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 | getOldNewOptionsExtra(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(OPT_vctoolsdir)) |
686 | VCToolsDir = A->getValue(); |
687 | if (auto *A = Args.getLastArg(OPT_vctoolsversion)) |
688 | VCToolsVersion = A->getValue(); |
689 | if (auto *A = Args.getLastArg(OPT_winsysroot)) |
690 | WinSysRoot = A->getValue(); |
691 | if (!findVCToolChainViaCommandLine(VFS&: *VFS, VCToolsDir, VCToolsVersion, |
692 | WinSysRoot, Path&: vcToolChainPath, VSLayout&: vsLayout) && |
693 | (Args.hasArg(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(OPT_diasdkdir, OPT_winsysroot)) { |
705 | diaPath = A->getValue(); |
706 | if (A->getOption().getID() == OPT_winsysroot) |
707 | path::append(path&: diaPath, a: "DIA SDK"); |
708 | } |
709 | useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) || |
710 | !Process::GetEnv(name: "LIB") || |
711 | Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot); |
712 | if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv(name: "LIB") || |
713 | Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) { |
714 | std::optional<StringRef> WinSdkDir, WinSdkVersion; |
715 | if (auto *A = Args.getLastArg(OPT_winsdkdir)) |
716 | WinSdkDir = A->getValue(); |
717 | if (auto *A = Args.getLastArg(OPT_winsdkversion)) |
718 | WinSdkVersion = A->getValue(); |
719 | |
720 | if (useUniversalCRT(VSLayout: vsLayout, VCToolChainPath: vcToolChainPath, TargetArch: getArch(), VFS&: *VFS)) { |
721 | std::string UniversalCRTSdkPath; |
722 | std::string UCRTVersion; |
723 | if (getUniversalCRTSdkDir(VFS&: *VFS, WinSdkDir, WinSdkVersion, WinSysRoot, |
724 | Path&: UniversalCRTSdkPath, UCRTVersion)) { |
725 | universalCRTLibPath = UniversalCRTSdkPath; |
726 | path::append(path&: universalCRTLibPath, a: "Lib", b: UCRTVersion, c: "ucrt"); |
727 | } |
728 | } |
729 | |
730 | std::string sdkPath; |
731 | std::string windowsSDKIncludeVersion; |
732 | std::string windowsSDKLibVersion; |
733 | if (getWindowsSDKDir(VFS&: *VFS, WinSdkDir, WinSdkVersion, WinSysRoot, Path&: sdkPath, |
734 | Major&: sdkMajor, WindowsSDKIncludeVersion&: windowsSDKIncludeVersion, |
735 | WindowsSDKLibVersion&: windowsSDKLibVersion)) { |
736 | windowsSdkLibPath = sdkPath; |
737 | path::append(path&: windowsSdkLibPath, a: "Lib"); |
738 | if (sdkMajor >= 8) |
739 | path::append(path&: windowsSdkLibPath, a: windowsSDKLibVersion, b: "um"); |
740 | } |
741 | } |
742 | } |
743 | |
744 | void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) { |
745 | std::string lldBinary = sys::fs::getMainExecutable(argv0: argv0.c_str(), MainExecAddr: nullptr); |
746 | SmallString<128> binDir(lldBinary); |
747 | sys::path::remove_filename(path&: binDir); // remove lld-link.exe |
748 | StringRef rootDir = sys::path::parent_path(path: binDir); // remove 'bin' |
749 | |
750 | SmallString<128> libDir(rootDir); |
751 | sys::path::append(path&: libDir, a: "lib"); |
752 | |
753 | // Add the resource dir library path |
754 | SmallString<128> runtimeLibDir(rootDir); |
755 | sys::path::append(path&: runtimeLibDir, a: "lib", b: "clang", |
756 | c: std::to_string(LLVM_VERSION_MAJOR), d: "lib"); |
757 | // Resource dir + osname, which is hardcoded to windows since we are in the |
758 | // COFF driver. |
759 | SmallString<128> runtimeLibDirWithOS(runtimeLibDir); |
760 | sys::path::append(path&: runtimeLibDirWithOS, a: "windows"); |
761 | |
762 | searchPaths.push_back(x: saver().save(S: runtimeLibDirWithOS.str())); |
763 | searchPaths.push_back(x: saver().save(S: runtimeLibDir.str())); |
764 | searchPaths.push_back(x: saver().save(S: libDir.str())); |
765 | } |
766 | |
767 | void LinkerDriver::addWinSysRootLibSearchPaths() { |
768 | if (!diaPath.empty()) { |
769 | // The DIA SDK always uses the legacy vc arch, even in new MSVC versions. |
770 | path::append(path&: diaPath, a: "lib", b: archToLegacyVCArch(Arch: getArch())); |
771 | searchPaths.push_back(x: saver().save(S: diaPath.str())); |
772 | } |
773 | if (useWinSysRootLibPath) { |
774 | searchPaths.push_back(x: saver().save(S: getSubDirectoryPath( |
775 | Type: SubDirectoryType::Lib, VSLayout: vsLayout, VCToolChainPath: vcToolChainPath, TargetArch: getArch()))); |
776 | searchPaths.push_back(x: saver().save( |
777 | S: getSubDirectoryPath(Type: SubDirectoryType::Lib, VSLayout: vsLayout, VCToolChainPath: vcToolChainPath, |
778 | TargetArch: getArch(), SubdirParent: "atlmfc"))); |
779 | } |
780 | if (!universalCRTLibPath.empty()) { |
781 | StringRef ArchName = archToWindowsSDKArch(Arch: getArch()); |
782 | if (!ArchName.empty()) { |
783 | path::append(path&: universalCRTLibPath, a: ArchName); |
784 | searchPaths.push_back(x: saver().save(S: universalCRTLibPath.str())); |
785 | } |
786 | } |
787 | if (!windowsSdkLibPath.empty()) { |
788 | std::string path; |
789 | if (appendArchToWindowsSDKLibPath(SDKMajor: sdkMajor, LibPath: windowsSdkLibPath, Arch: getArch(), |
790 | path)) |
791 | searchPaths.push_back(x: saver().save(S: path)); |
792 | } |
793 | |
794 | // Libraries specified by `/nodefaultlib:` may not be found in incomplete |
795 | // search paths before lld infers a machine type from input files. |
796 | std::set<std::string> noDefaultLibs; |
797 | for (const std::string &path : ctx.config.noDefaultLibs) |
798 | noDefaultLibs.insert(x: findLib(filename: path).lower()); |
799 | ctx.config.noDefaultLibs = noDefaultLibs; |
800 | } |
801 | |
802 | // Parses LIB environment which contains a list of search paths. |
803 | void LinkerDriver::addLibSearchPaths() { |
804 | std::optional<std::string> envOpt = Process::GetEnv(name: "LIB"); |
805 | if (!envOpt) |
806 | return; |
807 | StringRef env = saver().save(S: *envOpt); |
808 | while (!env.empty()) { |
809 | StringRef path; |
810 | std::tie(args&: path, args&: env) = env.split(Separator: ';'); |
811 | searchPaths.push_back(x: path); |
812 | } |
813 | } |
814 | |
815 | uint64_t LinkerDriver::getDefaultImageBase() { |
816 | if (ctx.config.is64()) |
817 | return ctx.config.dll ? 0x180000000 : 0x140000000; |
818 | return ctx.config.dll ? 0x10000000 : 0x400000; |
819 | } |
820 | |
821 | static std::string rewritePath(StringRef s) { |
822 | if (fs::exists(Path: s)) |
823 | return relativeToRoot(path: s); |
824 | return std::string(s); |
825 | } |
826 | |
827 | // Reconstructs command line arguments so that so that you can re-run |
828 | // the same command with the same inputs. This is for --reproduce. |
829 | static std::string createResponseFile(const opt::InputArgList &args, |
830 | ArrayRef<StringRef> searchPaths) { |
831 | SmallString<0> data; |
832 | raw_svector_ostream os(data); |
833 | |
834 | for (auto *arg : args) { |
835 | switch (arg->getOption().getID()) { |
836 | case OPT_linkrepro: |
837 | case OPT_reproduce: |
838 | case OPT_libpath: |
839 | case OPT_winsysroot: |
840 | break; |
841 | case OPT_INPUT: |
842 | os << quote(s: rewritePath(s: arg->getValue())) << "\n"; |
843 | break; |
844 | case OPT_wholearchive_file: |
845 | os << arg->getSpelling() << quote(s: rewritePath(s: arg->getValue())) << "\n"; |
846 | break; |
847 | case OPT_call_graph_ordering_file: |
848 | case OPT_deffile: |
849 | case OPT_manifestinput: |
850 | case OPT_natvis: |
851 | os << arg->getSpelling() << quote(s: rewritePath(s: arg->getValue())) << '\n'; |
852 | break; |
853 | case OPT_order: { |
854 | StringRef orderFile = arg->getValue(); |
855 | orderFile.consume_front(Prefix: "@"); |
856 | os << arg->getSpelling() << '@' << quote(s: rewritePath(s: orderFile)) << '\n'; |
857 | break; |
858 | } |
859 | case OPT_pdbstream: { |
860 | const std::pair<StringRef, StringRef> nameFile = |
861 | StringRef(arg->getValue()).split(Separator: "="); |
862 | os << arg->getSpelling() << nameFile.first << '=' |
863 | << quote(s: rewritePath(s: nameFile.second)) << '\n'; |
864 | break; |
865 | } |
866 | case OPT_implib: |
867 | case OPT_manifestfile: |
868 | case OPT_pdb: |
869 | case OPT_pdbstripped: |
870 | case OPT_out: |
871 | os << arg->getSpelling() << sys::path::filename(path: arg->getValue()) << "\n"; |
872 | break; |
873 | default: |
874 | os << toString(arg: *arg) << "\n"; |
875 | } |
876 | } |
877 | |
878 | for (StringRef path : searchPaths) { |
879 | std::string relPath = relativeToRoot(path); |
880 | os << "/libpath:"<< quote(s: relPath) << "\n"; |
881 | } |
882 | |
883 | return std::string(data); |
884 | } |
885 | |
886 | static unsigned parseDebugTypes(COFFLinkerContext &ctx, |
887 | const opt::InputArgList &args) { |
888 | unsigned debugTypes = static_cast<unsigned>(DebugType::None); |
889 | |
890 | if (auto *a = args.getLastArg(OPT_debugtype)) { |
891 | SmallVector<StringRef, 3> types; |
892 | StringRef(a->getValue()) |
893 | .split(A&: types, Separator: ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); |
894 | |
895 | for (StringRef type : types) { |
896 | unsigned v = StringSwitch<unsigned>(type.lower()) |
897 | .Case(S: "cv", Value: static_cast<unsigned>(DebugType::CV)) |
898 | .Case(S: "pdata", Value: static_cast<unsigned>(DebugType::PData)) |
899 | .Case(S: "fixup", Value: static_cast<unsigned>(DebugType::Fixup)) |
900 | .Default(Value: 0); |
901 | if (v == 0) { |
902 | Warn(ctx) << "/debugtype: unknown option '"<< type << "'"; |
903 | continue; |
904 | } |
905 | debugTypes |= v; |
906 | } |
907 | return debugTypes; |
908 | } |
909 | |
910 | // Default debug types |
911 | debugTypes = static_cast<unsigned>(DebugType::CV); |
912 | if (args.hasArg(OPT_driver)) |
913 | debugTypes |= static_cast<unsigned>(DebugType::PData); |
914 | if (args.hasArg(OPT_profile)) |
915 | debugTypes |= static_cast<unsigned>(DebugType::Fixup); |
916 | |
917 | return debugTypes; |
918 | } |
919 | |
920 | std::string LinkerDriver::getMapFile(const opt::InputArgList &args, |
921 | opt::OptSpecifier os, |
922 | opt::OptSpecifier osFile) { |
923 | auto *arg = args.getLastArg(Ids: os, Ids: osFile); |
924 | if (!arg) |
925 | return ""; |
926 | if (arg->getOption().getID() == osFile.getID()) |
927 | return arg->getValue(); |
928 | |
929 | assert(arg->getOption().getID() == os.getID()); |
930 | StringRef outFile = ctx.config.outputFile; |
931 | return (outFile.substr(Start: 0, N: outFile.rfind(C: '.')) + ".map").str(); |
932 | } |
933 | |
934 | std::string LinkerDriver::getImplibPath() { |
935 | if (!ctx.config.implib.empty()) |
936 | return std::string(ctx.config.implib); |
937 | SmallString<128> out = StringRef(ctx.config.outputFile); |
938 | sys::path::replace_extension(path&: out, extension: ".lib"); |
939 | return std::string(out); |
940 | } |
941 | |
942 | // The import name is calculated as follows: |
943 | // |
944 | // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY |
945 | // -----+----------------+---------------------+------------------ |
946 | // LINK | {value} | {value}.{.dll/.exe} | {output name} |
947 | // LIB | {value} | {value}.dll | {output name}.dll |
948 | // |
949 | std::string LinkerDriver::getImportName(bool asLib) { |
950 | SmallString<128> out; |
951 | |
952 | if (ctx.config.importName.empty()) { |
953 | out.assign(RHS: sys::path::filename(path: ctx.config.outputFile)); |
954 | if (asLib) |
955 | sys::path::replace_extension(path&: out, extension: ".dll"); |
956 | } else { |
957 | out.assign(RHS: ctx.config.importName); |
958 | if (!sys::path::has_extension(path: out)) |
959 | sys::path::replace_extension(path&: out, |
960 | extension: (ctx.config.dll || asLib) ? ".dll": ".exe"); |
961 | } |
962 | |
963 | return std::string(out); |
964 | } |
965 | |
966 | void LinkerDriver::createImportLibrary(bool asLib) { |
967 | llvm::TimeTraceScope timeScope("Create import library"); |
968 | std::vector<COFFShortExport> exports, nativeExports; |
969 | |
970 | auto getExports = [](SymbolTable &symtab, |
971 | std::vector<COFFShortExport> &exports) { |
972 | for (Export &e1 : symtab.exports) { |
973 | COFFShortExport e2; |
974 | e2.Name = std::string(e1.name); |
975 | e2.SymbolName = std::string(e1.symbolName); |
976 | e2.ExtName = std::string(e1.extName); |
977 | e2.ExportAs = std::string(e1.exportAs); |
978 | e2.ImportName = std::string(e1.importName); |
979 | e2.Ordinal = e1.ordinal; |
980 | e2.Noname = e1.noname; |
981 | e2.Data = e1.data; |
982 | e2.Private = e1.isPrivate; |
983 | e2.Constant = e1.constant; |
984 | exports.push_back(x: e2); |
985 | } |
986 | }; |
987 | |
988 | getExports(ctx.symtab, exports); |
989 | if (ctx.config.machine == ARM64X) |
990 | getExports(*ctx.hybridSymtab, nativeExports); |
991 | |
992 | std::string libName = getImportName(asLib); |
993 | std::string path = getImplibPath(); |
994 | |
995 | if (!ctx.config.incremental) { |
996 | checkError(e: writeImportLibrary(ImportName: libName, Path: path, Exports: exports, Machine: ctx.config.machine, |
997 | MinGW: ctx.config.mingw, NativeExports: nativeExports)); |
998 | return; |
999 | } |
1000 | |
1001 | // If the import library already exists, replace it only if the contents |
1002 | // have changed. |
1003 | ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( |
1004 | Filename: path, /*IsText=*/false, /*RequiresNullTerminator=*/false); |
1005 | if (!oldBuf) { |
1006 | checkError(e: writeImportLibrary(ImportName: libName, Path: path, Exports: exports, Machine: ctx.config.machine, |
1007 | MinGW: ctx.config.mingw, NativeExports: nativeExports)); |
1008 | return; |
1009 | } |
1010 | |
1011 | SmallString<128> tmpName; |
1012 | if (std::error_code ec = |
1013 | sys::fs::createUniqueFile(Model: path + ".tmp-%%%%%%%%.lib", ResultPath&: tmpName)) |
1014 | Fatal(ctx) << "cannot create temporary file for import library "<< path |
1015 | << ": "<< ec.message(); |
1016 | |
1017 | if (Error e = |
1018 | writeImportLibrary(ImportName: libName, Path: tmpName, Exports: exports, Machine: ctx.config.machine, |
1019 | MinGW: ctx.config.mingw, NativeExports: nativeExports)) { |
1020 | checkError(e: std::move(e)); |
1021 | return; |
1022 | } |
1023 | |
1024 | std::unique_ptr<MemoryBuffer> newBuf = check(e: MemoryBuffer::getFile( |
1025 | Filename: tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false)); |
1026 | if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { |
1027 | oldBuf->reset(); |
1028 | checkError(e: errorCodeToError(EC: sys::fs::rename(from: tmpName, to: path))); |
1029 | } else { |
1030 | sys::fs::remove(path: tmpName); |
1031 | } |
1032 | } |
1033 | |
1034 | void LinkerDriver::enqueueTask(std::function<void()> task) { |
1035 | taskQueue.push_back(x: std::move(task)); |
1036 | } |
1037 | |
1038 | bool LinkerDriver::run() { |
1039 | llvm::TimeTraceScope timeScope("Read input files"); |
1040 | ScopedTimer t(ctx.inputFileTimer); |
1041 | |
1042 | bool didWork = !taskQueue.empty(); |
1043 | while (!taskQueue.empty()) { |
1044 | taskQueue.front()(); |
1045 | taskQueue.pop_front(); |
1046 | } |
1047 | return didWork; |
1048 | } |
1049 | |
1050 | // Parse an /order file. If an option is given, the linker places |
1051 | // COMDAT sections in the same order as their names appear in the |
1052 | // given file. |
1053 | void LinkerDriver::parseOrderFile(StringRef arg) { |
1054 | // For some reason, the MSVC linker requires a filename to be |
1055 | // preceded by "@". |
1056 | if (!arg.starts_with(Prefix: "@")) { |
1057 | Err(ctx) << "malformed /order option: '@' missing"; |
1058 | return; |
1059 | } |
1060 | |
1061 | // Get a list of all comdat sections for error checking. |
1062 | DenseSet<StringRef> set; |
1063 | for (Chunk *c : ctx.driver.getChunks()) |
1064 | if (auto *sec = dyn_cast<SectionChunk>(Val: c)) |
1065 | if (sec->sym) |
1066 | set.insert(V: sec->sym->getName()); |
1067 | |
1068 | // Open a file. |
1069 | StringRef path = arg.substr(Start: 1); |
1070 | std::unique_ptr<MemoryBuffer> mb = |
1071 | CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, |
1072 | /*RequiresNullTerminator=*/false, |
1073 | /*IsVolatile=*/true), |
1074 | "could not open "+ path); |
1075 | |
1076 | // Parse a file. An order file contains one symbol per line. |
1077 | // All symbols that were not present in a given order file are |
1078 | // considered to have the lowest priority 0 and are placed at |
1079 | // end of an output section. |
1080 | for (StringRef arg : args::getLines(mb: mb->getMemBufferRef())) { |
1081 | std::string s(arg); |
1082 | if (ctx.config.machine == I386 && !isDecorated(sym: s)) |
1083 | s = "_"+ s; |
1084 | |
1085 | if (set.count(V: s) == 0) { |
1086 | if (ctx.config.warnMissingOrderSymbol) |
1087 | Warn(ctx) << "/order:"<< arg << ": missing symbol: "<< s |
1088 | << " [LNK4037]"; |
1089 | } else |
1090 | ctx.config.order[s] = INT_MIN + ctx.config.order.size(); |
1091 | } |
1092 | |
1093 | // Include in /reproduce: output if applicable. |
1094 | ctx.driver.takeBuffer(mb: std::move(mb)); |
1095 | } |
1096 | |
1097 | void LinkerDriver::parseCallGraphFile(StringRef path) { |
1098 | std::unique_ptr<MemoryBuffer> mb = |
1099 | CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, |
1100 | /*RequiresNullTerminator=*/false, |
1101 | /*IsVolatile=*/true), |
1102 | "could not open "+ path); |
1103 | |
1104 | // Build a map from symbol name to section. |
1105 | DenseMap<StringRef, Symbol *> map; |
1106 | for (ObjFile *file : ctx.objFileInstances) |
1107 | for (Symbol *sym : file->getSymbols()) |
1108 | if (sym) |
1109 | map[sym->getName()] = sym; |
1110 | |
1111 | auto findSection = [&](StringRef name) -> SectionChunk * { |
1112 | Symbol *sym = map.lookup(Val: name); |
1113 | if (!sym) { |
1114 | if (ctx.config.warnMissingOrderSymbol) |
1115 | Warn(ctx) << path << ": no such symbol: "<< name; |
1116 | return nullptr; |
1117 | } |
1118 | |
1119 | if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(Val: sym)) |
1120 | return dyn_cast_or_null<SectionChunk>(Val: dr->getChunk()); |
1121 | return nullptr; |
1122 | }; |
1123 | |
1124 | for (StringRef line : args::getLines(mb: *mb)) { |
1125 | SmallVector<StringRef, 3> fields; |
1126 | line.split(A&: fields, Separator: ' '); |
1127 | uint64_t count; |
1128 | |
1129 | if (fields.size() != 3 || !to_integer(S: fields[2], Num&: count)) { |
1130 | Err(ctx) << path << ": parse error"; |
1131 | return; |
1132 | } |
1133 | |
1134 | if (SectionChunk *from = findSection(fields[0])) |
1135 | if (SectionChunk *to = findSection(fields[1])) |
1136 | ctx.config.callGraphProfile[{from, to}] += count; |
1137 | } |
1138 | |
1139 | // Include in /reproduce: output if applicable. |
1140 | ctx.driver.takeBuffer(mb: std::move(mb)); |
1141 | } |
1142 | |
1143 | static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) { |
1144 | for (ObjFile *obj : ctx.objFileInstances) { |
1145 | if (obj->callgraphSec) { |
1146 | ArrayRef<uint8_t> contents; |
1147 | cantFail( |
1148 | Err: obj->getCOFFObj()->getSectionContents(Sec: obj->callgraphSec, Res&: contents)); |
1149 | BinaryStreamReader reader(contents, llvm::endianness::little); |
1150 | while (!reader.empty()) { |
1151 | uint32_t fromIndex, toIndex; |
1152 | uint64_t count; |
1153 | if (Error err = reader.readInteger(Dest&: fromIndex)) |
1154 | Fatal(ctx) << toString(file: obj) << ": Expected 32-bit integer"; |
1155 | if (Error err = reader.readInteger(Dest&: toIndex)) |
1156 | Fatal(ctx) << toString(file: obj) << ": Expected 32-bit integer"; |
1157 | if (Error err = reader.readInteger(Dest&: count)) |
1158 | Fatal(ctx) << toString(file: obj) << ": Expected 64-bit integer"; |
1159 | auto *fromSym = dyn_cast_or_null<Defined>(Val: obj->getSymbol(symbolIndex: fromIndex)); |
1160 | auto *toSym = dyn_cast_or_null<Defined>(Val: obj->getSymbol(symbolIndex: toIndex)); |
1161 | if (!fromSym || !toSym) |
1162 | continue; |
1163 | auto *from = dyn_cast_or_null<SectionChunk>(Val: fromSym->getChunk()); |
1164 | auto *to = dyn_cast_or_null<SectionChunk>(Val: toSym->getChunk()); |
1165 | if (from && to) |
1166 | ctx.config.callGraphProfile[{from, to}] += count; |
1167 | } |
1168 | } |
1169 | } |
1170 | } |
1171 | |
1172 | static void markAddrsig(Symbol *s) { |
1173 | if (auto *d = dyn_cast_or_null<Defined>(Val: s)) |
1174 | if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(Val: d->getChunk())) |
1175 | c->keepUnique = true; |
1176 | } |
1177 | |
1178 | static void findKeepUniqueSections(COFFLinkerContext &ctx) { |
1179 | llvm::TimeTraceScope timeScope("Find keep unique sections"); |
1180 | |
1181 | // Exported symbols could be address-significant in other executables or DSOs, |
1182 | // so we conservatively mark them as address-significant. |
1183 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { |
1184 | for (Export &r : symtab.exports) |
1185 | markAddrsig(s: r.sym); |
1186 | }); |
1187 | |
1188 | // Visit the address-significance table in each object file and mark each |
1189 | // referenced symbol as address-significant. |
1190 | for (ObjFile *obj : ctx.objFileInstances) { |
1191 | ArrayRef<Symbol *> syms = obj->getSymbols(); |
1192 | if (obj->addrsigSec) { |
1193 | ArrayRef<uint8_t> contents; |
1194 | cantFail( |
1195 | Err: obj->getCOFFObj()->getSectionContents(Sec: obj->addrsigSec, Res&: contents)); |
1196 | const uint8_t *cur = contents.begin(); |
1197 | while (cur != contents.end()) { |
1198 | unsigned size; |
1199 | const char *err = nullptr; |
1200 | uint64_t symIndex = decodeULEB128(p: cur, n: &size, end: contents.end(), error: &err); |
1201 | if (err) |
1202 | Fatal(ctx) << toString(file: obj) |
1203 | << ": could not decode addrsig section: "<< err; |
1204 | if (symIndex >= syms.size()) |
1205 | Fatal(ctx) << toString(file: obj) |
1206 | << ": invalid symbol index in addrsig section"; |
1207 | markAddrsig(s: syms[symIndex]); |
1208 | cur += size; |
1209 | } |
1210 | } else { |
1211 | // If an object file does not have an address-significance table, |
1212 | // conservatively mark all of its symbols as address-significant. |
1213 | for (Symbol *s : syms) |
1214 | markAddrsig(s); |
1215 | } |
1216 | } |
1217 | } |
1218 | |
1219 | // link.exe replaces each %foo% in altPath with the contents of environment |
1220 | // variable foo, and adds the two magic env vars _PDB (expands to the basename |
1221 | // of pdb's output path) and _EXT (expands to the extension of the output |
1222 | // binary). |
1223 | // lld only supports %_PDB% and %_EXT% and warns on references to all other env |
1224 | // vars. |
1225 | void LinkerDriver::parsePDBAltPath() { |
1226 | SmallString<128> buf; |
1227 | StringRef pdbBasename = |
1228 | sys::path::filename(path: ctx.config.pdbPath, style: sys::path::Style::windows); |
1229 | StringRef binaryExtension = |
1230 | sys::path::extension(path: ctx.config.outputFile, style: sys::path::Style::windows); |
1231 | if (!binaryExtension.empty()) |
1232 | binaryExtension = binaryExtension.substr(Start: 1); // %_EXT% does not include '.'. |
1233 | |
1234 | // Invariant: |
1235 | // +--------- cursor ('a...' might be the empty string). |
1236 | // | +----- firstMark |
1237 | // | | +- secondMark |
1238 | // v v v |
1239 | // a...%...%... |
1240 | size_t cursor = 0; |
1241 | while (cursor < ctx.config.pdbAltPath.size()) { |
1242 | size_t firstMark, secondMark; |
1243 | if ((firstMark = ctx.config.pdbAltPath.find(C: '%', From: cursor)) == |
1244 | StringRef::npos || |
1245 | (secondMark = ctx.config.pdbAltPath.find(C: '%', From: firstMark + 1)) == |
1246 | StringRef::npos) { |
1247 | // Didn't find another full fragment, treat rest of string as literal. |
1248 | buf.append(RHS: ctx.config.pdbAltPath.substr(Start: cursor)); |
1249 | break; |
1250 | } |
1251 | |
1252 | // Found a full fragment. Append text in front of first %, and interpret |
1253 | // text between first and second % as variable name. |
1254 | buf.append(RHS: ctx.config.pdbAltPath.substr(Start: cursor, N: firstMark - cursor)); |
1255 | StringRef var = |
1256 | ctx.config.pdbAltPath.substr(Start: firstMark, N: secondMark - firstMark + 1); |
1257 | if (var.equals_insensitive(RHS: "%_pdb%")) |
1258 | buf.append(RHS: pdbBasename); |
1259 | else if (var.equals_insensitive(RHS: "%_ext%")) |
1260 | buf.append(RHS: binaryExtension); |
1261 | else { |
1262 | Warn(ctx) << "only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " |
1263 | << var << " as literal"; |
1264 | buf.append(RHS: var); |
1265 | } |
1266 | |
1267 | cursor = secondMark + 1; |
1268 | } |
1269 | |
1270 | ctx.config.pdbAltPath = buf; |
1271 | } |
1272 | |
1273 | /// Convert resource files and potentially merge input resource object |
1274 | /// trees into one resource tree. |
1275 | /// Call after ObjFile::Instances is complete. |
1276 | void LinkerDriver::convertResources() { |
1277 | llvm::TimeTraceScope timeScope("Convert resources"); |
1278 | std::vector<ObjFile *> resourceObjFiles; |
1279 | |
1280 | for (ObjFile *f : ctx.objFileInstances) { |
1281 | if (f->isResourceObjFile()) |
1282 | resourceObjFiles.push_back(x: f); |
1283 | } |
1284 | |
1285 | if (!ctx.config.mingw && |
1286 | (resourceObjFiles.size() > 1 || |
1287 | (resourceObjFiles.size() == 1 && !resources.empty()))) { |
1288 | Err(ctx) << (!resources.empty() |
1289 | ? "internal .obj file created from .res files" |
1290 | : toString(file: resourceObjFiles[1])) |
1291 | << ": more than one resource obj file not allowed, already got " |
1292 | << resourceObjFiles.front(); |
1293 | return; |
1294 | } |
1295 | |
1296 | if (resources.empty() && resourceObjFiles.size() <= 1) { |
1297 | // No resources to convert, and max one resource object file in |
1298 | // the input. Keep that preconverted resource section as is. |
1299 | for (ObjFile *f : resourceObjFiles) |
1300 | f->includeResourceChunks(); |
1301 | return; |
1302 | } |
1303 | ObjFile *f = |
1304 | ObjFile::create(ctx, mb: convertResToCOFF(mbs: resources, objs: resourceObjFiles)); |
1305 | addFile(file: f); |
1306 | f->includeResourceChunks(); |
1307 | } |
1308 | |
1309 | void LinkerDriver::maybeCreateECExportThunk(StringRef name, Symbol *&sym) { |
1310 | Defined *def; |
1311 | if (!sym) |
1312 | return; |
1313 | if (auto undef = dyn_cast<Undefined>(Val: sym)) |
1314 | def = undef->getDefinedWeakAlias(); |
1315 | else |
1316 | def = dyn_cast<Defined>(Val: sym); |
1317 | if (!def) |
1318 | return; |
1319 | |
1320 | if (def->getChunk()->getArm64ECRangeType() != chpe_range_type::Arm64EC) |
1321 | return; |
1322 | StringRef expName; |
1323 | if (auto mangledName = getArm64ECMangledFunctionName(Name: name)) |
1324 | expName = saver().save(S: "EXP+"+ *mangledName); |
1325 | else |
1326 | expName = saver().save(S: "EXP+"+ name); |
1327 | sym = ctx.symtab.addGCRoot(sym: expName); |
1328 | if (auto undef = dyn_cast<Undefined>(Val: sym)) { |
1329 | if (!undef->getWeakAlias()) { |
1330 | auto thunk = make<ECExportThunkChunk>(args&: def); |
1331 | replaceSymbol<DefinedSynthetic>(s: undef, arg: undef->getName(), arg&: thunk); |
1332 | } |
1333 | } |
1334 | } |
1335 | |
1336 | void LinkerDriver::createECExportThunks() { |
1337 | // Check if EXP+ symbols have corresponding $hp_target symbols and use them |
1338 | // to create export thunks when available. |
1339 | for (Symbol *s : ctx.symtab.expSymbols) { |
1340 | if (!s->isUsedInRegularObj) |
1341 | continue; |
1342 | assert(s->getName().starts_with("EXP+")); |
1343 | std::string targetName = |
1344 | (s->getName().substr(Start: strlen(s: "EXP+")) + "$hp_target").str(); |
1345 | Symbol *sym = ctx.symtab.find(name: targetName); |
1346 | if (!sym) |
1347 | continue; |
1348 | Defined *targetSym; |
1349 | if (auto undef = dyn_cast<Undefined>(Val: sym)) |
1350 | targetSym = undef->getDefinedWeakAlias(); |
1351 | else |
1352 | targetSym = dyn_cast<Defined>(Val: sym); |
1353 | if (!targetSym) |
1354 | continue; |
1355 | |
1356 | auto *undef = dyn_cast<Undefined>(Val: s); |
1357 | if (undef && !undef->getWeakAlias()) { |
1358 | auto thunk = make<ECExportThunkChunk>(args&: targetSym); |
1359 | replaceSymbol<DefinedSynthetic>(s: undef, arg: undef->getName(), arg&: thunk); |
1360 | } |
1361 | if (!targetSym->isGCRoot) { |
1362 | targetSym->isGCRoot = true; |
1363 | ctx.config.gcroot.push_back(x: targetSym); |
1364 | } |
1365 | } |
1366 | |
1367 | if (ctx.symtab.entry) |
1368 | maybeCreateECExportThunk(name: ctx.symtab.entry->getName(), sym&: ctx.symtab.entry); |
1369 | for (Export &e : ctx.symtab.exports) { |
1370 | if (!e.data) |
1371 | maybeCreateECExportThunk(name: e.extName.empty() ? e.name : e.extName, sym&: e.sym); |
1372 | } |
1373 | } |
1374 | |
1375 | void LinkerDriver::pullArm64ECIcallHelper() { |
1376 | if (!ctx.config.arm64ECIcallHelper) |
1377 | ctx.config.arm64ECIcallHelper = |
1378 | ctx.symtab.addGCRoot(sym: "__icall_helper_arm64ec"); |
1379 | } |
1380 | |
1381 | // In MinGW, if no symbols are chosen to be exported, then all symbols are |
1382 | // automatically exported by default. This behavior can be forced by the |
1383 | // -export-all-symbols option, so that it happens even when exports are |
1384 | // explicitly specified. The automatic behavior can be disabled using the |
1385 | // -exclude-all-symbols option, so that lld-link behaves like link.exe rather |
1386 | // than MinGW in the case that nothing is explicitly exported. |
1387 | void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { |
1388 | if (!args.hasArg(OPT_export_all_symbols)) { |
1389 | if (!ctx.config.dll) |
1390 | return; |
1391 | |
1392 | if (ctx.symtab.hadExplicitExports || |
1393 | (ctx.config.machine == ARM64X && ctx.hybridSymtab->hadExplicitExports)) |
1394 | return; |
1395 | if (args.hasArg(OPT_exclude_all_symbols)) |
1396 | return; |
1397 | } |
1398 | |
1399 | ctx.forEachActiveSymtab(f: [&](SymbolTable &symtab) { |
1400 | AutoExporter exporter(symtab, excludedSymbols); |
1401 | |
1402 | for (auto *arg : args.filtered(OPT_wholearchive_file)) |
1403 | if (std::optional<StringRef> path = findFile(arg->getValue())) |
1404 | exporter.addWholeArchive(*path); |
1405 | |
1406 | for (auto *arg : args.filtered(OPT_exclude_symbols)) { |
1407 | SmallVector<StringRef, 2> vec; |
1408 | StringRef(arg->getValue()).split(vec, ','); |
1409 | for (StringRef sym : vec) |
1410 | exporter.addExcludedSymbol(symtab.mangle(sym)); |
1411 | } |
1412 | |
1413 | symtab.forEachSymbol(callback: [&](Symbol *s) { |
1414 | auto *def = dyn_cast<Defined>(Val: s); |
1415 | if (!exporter.shouldExport(sym: def)) |
1416 | return; |
1417 | |
1418 | if (!def->isGCRoot) { |
1419 | def->isGCRoot = true; |
1420 | ctx.config.gcroot.push_back(x: def); |
1421 | } |
1422 | |
1423 | Export e; |
1424 | e.name = def->getName(); |
1425 | e.sym = def; |
1426 | if (Chunk *c = def->getChunk()) |
1427 | if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) |
1428 | e.data = true; |
1429 | s->isUsedInRegularObj = true; |
1430 | symtab.exports.push_back(x: e); |
1431 | }); |
1432 | }); |
1433 | } |
1434 | |
1435 | // lld has a feature to create a tar file containing all input files as well as |
1436 | // all command line options, so that other people can run lld again with exactly |
1437 | // the same inputs. This feature is accessible via /linkrepro and /reproduce. |
1438 | // |
1439 | // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory |
1440 | // name while /reproduce takes a full path. We have /linkrepro for compatibility |
1441 | // with Microsoft link.exe. |
1442 | std::optional<std::string> getReproduceFile(const opt::InputArgList &args) { |
1443 | if (auto *arg = args.getLastArg(OPT_reproduce)) |
1444 | return std::string(arg->getValue()); |
1445 | |
1446 | if (auto *arg = args.getLastArg(OPT_linkrepro)) { |
1447 | SmallString<64> path = StringRef(arg->getValue()); |
1448 | sys::path::append(path, a: "repro.tar"); |
1449 | return std::string(path); |
1450 | } |
1451 | |
1452 | // This is intentionally not guarded by OPT_lldignoreenv since writing |
1453 | // a repro tar file doesn't affect the main output. |
1454 | if (auto *path = getenv(name: "LLD_REPRODUCE")) |
1455 | return std::string(path); |
1456 | |
1457 | return std::nullopt; |
1458 | } |
1459 | |
1460 | static std::unique_ptr<llvm::vfs::FileSystem> |
1461 | getVFS(COFFLinkerContext &ctx, const opt::InputArgList &args) { |
1462 | using namespace llvm::vfs; |
1463 | |
1464 | const opt::Arg *arg = args.getLastArg(OPT_vfsoverlay); |
1465 | if (!arg) |
1466 | return nullptr; |
1467 | |
1468 | auto bufOrErr = llvm::MemoryBuffer::getFile(Filename: arg->getValue()); |
1469 | if (!bufOrErr) { |
1470 | checkError(e: errorCodeToError(EC: bufOrErr.getError())); |
1471 | return nullptr; |
1472 | } |
1473 | |
1474 | if (auto ret = vfs::getVFSFromYAML(Buffer: std::move(*bufOrErr), |
1475 | /*DiagHandler*/ nullptr, YAMLFilePath: arg->getValue())) |
1476 | return ret; |
1477 | |
1478 | Err(ctx) << "Invalid vfs overlay"; |
1479 | return nullptr; |
1480 | } |
1481 | |
1482 | constexpr const char *lldsaveTempsValues[] = { |
1483 | "resolution", "preopt", "promote", "internalize", "import", |
1484 | "opt", "precodegen", "prelink", "combinedindex"}; |
1485 | |
1486 | void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { |
1487 | ScopedTimer rootTimer(ctx.rootTimer); |
1488 | Configuration *config = &ctx.config; |
1489 | |
1490 | // Needed for LTO. |
1491 | InitializeAllTargetInfos(); |
1492 | InitializeAllTargets(); |
1493 | InitializeAllTargetMCs(); |
1494 | InitializeAllAsmParsers(); |
1495 | InitializeAllAsmPrinters(); |
1496 | |
1497 | // If the first command line argument is "/lib", link.exe acts like lib.exe. |
1498 | // We call our own implementation of lib.exe that understands bitcode files. |
1499 | if (argsArr.size() > 1 && |
1500 | (StringRef(argsArr[1]).equals_insensitive(RHS: "/lib") || |
1501 | StringRef(argsArr[1]).equals_insensitive(RHS: "-lib"))) { |
1502 | if (llvm::libDriverMain(ARgs: argsArr.slice(N: 1)) != 0) |
1503 | Fatal(ctx) << "lib failed"; |
1504 | return; |
1505 | } |
1506 | |
1507 | // Parse command line options. |
1508 | ArgParser parser(ctx); |
1509 | opt::InputArgList args = parser.parse(args: argsArr); |
1510 | |
1511 | // Initialize time trace profiler. |
1512 | config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq); |
1513 | config->timeTraceGranularity = |
1514 | args::getInteger(args, OPT_time_trace_granularity_eq, 500); |
1515 | |
1516 | if (config->timeTraceEnabled) |
1517 | timeTraceProfilerInitialize(TimeTraceGranularity: config->timeTraceGranularity, ProcName: argsArr[0]); |
1518 | |
1519 | llvm::TimeTraceScope timeScope("COFF link"); |
1520 | |
1521 | // Parse and evaluate -mllvm options. |
1522 | std::vector<const char *> v; |
1523 | v.push_back(x: "lld-link (LLVM option parsing)"); |
1524 | for (const auto *arg : args.filtered(OPT_mllvm)) { |
1525 | v.push_back(arg->getValue()); |
1526 | config->mllvmOpts.emplace_back(arg->getValue()); |
1527 | } |
1528 | { |
1529 | llvm::TimeTraceScope timeScope2("Parse cl::opt"); |
1530 | cl::ResetAllOptionOccurrences(); |
1531 | cl::ParseCommandLineOptions(argc: v.size(), argv: v.data()); |
1532 | } |
1533 | |
1534 | // Handle /errorlimit early, because error() depends on it. |
1535 | if (auto *arg = args.getLastArg(OPT_errorlimit)) { |
1536 | int n = 20; |
1537 | StringRef s = arg->getValue(); |
1538 | if (s.getAsInteger(Radix: 10, Result&: n)) |
1539 | Err(ctx) << arg->getSpelling() << " number expected, but got "<< s; |
1540 | ctx.e.errorLimit = n; |
1541 | } |
1542 | |
1543 | config->vfs = getVFS(ctx, args); |
1544 | |
1545 | // Handle /help |
1546 | if (args.hasArg(OPT_help)) { |
1547 | printHelp(argv0: argsArr[0]); |
1548 | return; |
1549 | } |
1550 | |
1551 | // /threads: takes a positive integer and provides the default value for |
1552 | // /opt:lldltojobs=. |
1553 | if (auto *arg = args.getLastArg(OPT_threads)) { |
1554 | StringRef v(arg->getValue()); |
1555 | unsigned threads = 0; |
1556 | if (!llvm::to_integer(S: v, Num&: threads, Base: 0) || threads == 0) |
1557 | Err(ctx) << arg->getSpelling() |
1558 | << ": expected a positive integer, but got '"<< arg->getValue() |
1559 | << "'"; |
1560 | parallel::strategy = hardware_concurrency(ThreadCount: threads); |
1561 | config->thinLTOJobs = v.str(); |
1562 | } |
1563 | |
1564 | if (args.hasArg(OPT_show_timing)) |
1565 | config->showTiming = true; |
1566 | |
1567 | config->showSummary = args.hasArg(OPT_summary); |
1568 | config->printSearchPaths = args.hasArg(OPT_print_search_paths); |
1569 | |
1570 | // Handle --version, which is an lld extension. This option is a bit odd |
1571 | // because it doesn't start with "/", but we deliberately chose "--" to |
1572 | // avoid conflict with /version and for compatibility with clang-cl. |
1573 | if (args.hasArg(OPT_dash_dash_version)) { |
1574 | Msg(ctx) << getLLDVersion(); |
1575 | return; |
1576 | } |
1577 | |
1578 | // Handle /lldmingw early, since it can potentially affect how other |
1579 | // options are handled. |
1580 | config->mingw = args.hasArg(OPT_lldmingw); |
1581 | if (config->mingw) |
1582 | ctx.e.errorLimitExceededMsg = "too many errors emitted, stopping now" |
1583 | " (use --error-limit=0 to see all errors)"; |
1584 | |
1585 | // Handle /linkrepro and /reproduce. |
1586 | { |
1587 | llvm::TimeTraceScope timeScope2("Reproducer"); |
1588 | if (std::optional<std::string> path = getReproduceFile(args)) { |
1589 | Expected<std::unique_ptr<TarWriter>> errOrWriter = |
1590 | TarWriter::create(OutputPath: *path, BaseDir: sys::path::stem(path: *path)); |
1591 | |
1592 | if (errOrWriter) { |
1593 | tar = std::move(*errOrWriter); |
1594 | } else { |
1595 | Err(ctx) << "/linkrepro: failed to open "<< *path << ": " |
1596 | << toString(E: errOrWriter.takeError()); |
1597 | } |
1598 | } |
1599 | } |
1600 | |
1601 | if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { |
1602 | if (args.hasArg(OPT_deffile)) |
1603 | config->noEntry = true; |
1604 | else |
1605 | Fatal(ctx) << "no input files"; |
1606 | } |
1607 | |
1608 | // Construct search path list. |
1609 | { |
1610 | llvm::TimeTraceScope timeScope2("Search paths"); |
1611 | searchPaths.emplace_back(args: ""); |
1612 | for (auto *arg : args.filtered(OPT_libpath)) |
1613 | searchPaths.push_back(arg->getValue()); |
1614 | if (!config->mingw) { |
1615 | // Prefer the Clang provided builtins over the ones bundled with MSVC. |
1616 | // In MinGW mode, the compiler driver passes the necessary libpath |
1617 | // options explicitly. |
1618 | addClangLibSearchPaths(argv0: argsArr[0]); |
1619 | // Don't automatically deduce the lib path from the environment or MSVC |
1620 | // installations when operating in mingw mode. (This also makes LLD ignore |
1621 | // winsysroot and vctoolsdir arguments.) |
1622 | detectWinSysRoot(Args: args); |
1623 | if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot)) |
1624 | addLibSearchPaths(); |
1625 | } else { |
1626 | if (args.hasArg(OPT_vctoolsdir, OPT_winsysroot)) |
1627 | Warn(ctx) << "ignoring /vctoolsdir or /winsysroot flags in MinGW mode"; |
1628 | } |
1629 | } |
1630 | |
1631 | // Handle /ignore |
1632 | for (auto *arg : args.filtered(OPT_ignore)) { |
1633 | SmallVector<StringRef, 8> vec; |
1634 | StringRef(arg->getValue()).split(vec, ','); |
1635 | for (StringRef s : vec) { |
1636 | if (s == "4037") |
1637 | config->warnMissingOrderSymbol = false; |
1638 | else if (s == "4099") |
1639 | config->warnDebugInfoUnusable = false; |
1640 | else if (s == "4217") |
1641 | config->warnLocallyDefinedImported = false; |
1642 | else if (s == "longsections") |
1643 | config->warnLongSectionNames = false; |
1644 | // Other warning numbers are ignored. |
1645 | } |
1646 | } |
1647 | |
1648 | // Handle /out |
1649 | if (auto *arg = args.getLastArg(OPT_out)) |
1650 | config->outputFile = arg->getValue(); |
1651 | |
1652 | // Handle /verbose |
1653 | if (args.hasArg(OPT_verbose)) |
1654 | config->verbose = true; |
1655 | ctx.e.verbose = config->verbose; |
1656 | |
1657 | // Handle /force or /force:unresolved |
1658 | if (args.hasArg(OPT_force, OPT_force_unresolved)) |
1659 | config->forceUnresolved = true; |
1660 | |
1661 | // Handle /force or /force:multiple |
1662 | if (args.hasArg(OPT_force, OPT_force_multiple)) |
1663 | config->forceMultiple = true; |
1664 | |
1665 | // Handle /force or /force:multipleres |
1666 | if (args.hasArg(OPT_force, OPT_force_multipleres)) |
1667 | config->forceMultipleRes = true; |
1668 | |
1669 | // Don't warn about long section names, such as .debug_info, for mingw (or |
1670 | // when -debug:dwarf is requested, handled below). |
1671 | if (config->mingw) |
1672 | config->warnLongSectionNames = false; |
1673 | |
1674 | bool doGC = true; |
1675 | |
1676 | // Handle /debug |
1677 | bool shouldCreatePDB = false; |
1678 | for (auto *arg : args.filtered(OPT_debug, OPT_debug_opt)) { |
1679 | std::string str; |
1680 | if (arg->getOption().getID() == OPT_debug) |
1681 | str = "full"; |
1682 | else |
1683 | str = StringRef(arg->getValue()).lower(); |
1684 | SmallVector<StringRef, 1> vec; |
1685 | StringRef(str).split(vec, ','); |
1686 | for (StringRef s : vec) { |
1687 | if (s == "fastlink") { |
1688 | Warn(ctx) << "/debug:fastlink unsupported; using /debug:full"; |
1689 | s = "full"; |
1690 | } |
1691 | if (s == "none") { |
1692 | config->debug = false; |
1693 | config->incremental = false; |
1694 | config->includeDwarfChunks = false; |
1695 | config->debugGHashes = false; |
1696 | config->writeSymtab = false; |
1697 | shouldCreatePDB = false; |
1698 | doGC = true; |
1699 | } else if (s == "full"|| s == "ghash"|| s == "noghash") { |
1700 | config->debug = true; |
1701 | config->incremental = true; |
1702 | config->includeDwarfChunks = true; |
1703 | if (s == "full"|| s == "ghash") |
1704 | config->debugGHashes = true; |
1705 | shouldCreatePDB = true; |
1706 | doGC = false; |
1707 | } else if (s == "dwarf") { |
1708 | config->debug = true; |
1709 | config->incremental = true; |
1710 | config->includeDwarfChunks = true; |
1711 | config->writeSymtab = true; |
1712 | config->warnLongSectionNames = false; |
1713 | doGC = false; |
1714 | } else if (s == "nodwarf") { |
1715 | config->includeDwarfChunks = false; |
1716 | } else if (s == "symtab") { |
1717 | config->writeSymtab = true; |
1718 | doGC = false; |
1719 | } else if (s == "nosymtab") { |
1720 | config->writeSymtab = false; |
1721 | } else { |
1722 | Err(ctx) << "/debug: unknown option: "<< s; |
1723 | } |
1724 | } |
1725 | } |
1726 | |
1727 | // Handle /demangle |
1728 | config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no, true); |
1729 | |
1730 | // Handle /debugtype |
1731 | config->debugTypes = parseDebugTypes(ctx, args); |
1732 | |
1733 | // Handle /driver[:uponly|:wdm]. |
1734 | config->driverUponly = args.hasArg(OPT_driver_uponly) || |
1735 | args.hasArg(OPT_driver_uponly_wdm) || |
1736 | args.hasArg(OPT_driver_wdm_uponly); |
1737 | config->driverWdm = args.hasArg(OPT_driver_wdm) || |
1738 | args.hasArg(OPT_driver_uponly_wdm) || |
1739 | args.hasArg(OPT_driver_wdm_uponly); |
1740 | config->driver = |
1741 | config->driverUponly || config->driverWdm || args.hasArg(OPT_driver); |
1742 | |
1743 | // Handle /pdb |
1744 | if (shouldCreatePDB) { |
1745 | if (auto *arg = args.getLastArg(OPT_pdb)) |
1746 | config->pdbPath = arg->getValue(); |
1747 | if (auto *arg = args.getLastArg(OPT_pdbaltpath)) |
1748 | config->pdbAltPath = arg->getValue(); |
1749 | if (auto *arg = args.getLastArg(OPT_pdbpagesize)) |
1750 | parsePDBPageSize(arg->getValue()); |
1751 | if (args.hasArg(OPT_natvis)) |
1752 | config->natvisFiles = args.getAllArgValues(OPT_natvis); |
1753 | if (args.hasArg(OPT_pdbstream)) { |
1754 | for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) { |
1755 | const std::pair<StringRef, StringRef> nameFile = value.split("="); |
1756 | const StringRef name = nameFile.first; |
1757 | const std::string file = nameFile.second.str(); |
1758 | config->namedStreams[name] = file; |
1759 | } |
1760 | } |
1761 | |
1762 | if (auto *arg = args.getLastArg(OPT_pdb_source_path)) |
1763 | config->pdbSourcePath = arg->getValue(); |
1764 | } |
1765 | |
1766 | // Handle /pdbstripped |
1767 | if (args.hasArg(OPT_pdbstripped)) |
1768 | Warn(ctx) << "ignoring /pdbstripped flag, it is not yet supported"; |
1769 | |
1770 | // Handle /noentry |
1771 | if (args.hasArg(OPT_noentry)) { |
1772 | if (args.hasArg(OPT_dll)) |
1773 | config->noEntry = true; |
1774 | else |
1775 | Err(ctx) << "/noentry must be specified with /dll"; |
1776 | } |
1777 | |
1778 | // Handle /dll |
1779 | if (args.hasArg(OPT_dll)) { |
1780 | config->dll = true; |
1781 | config->manifestID = 2; |
1782 | } |
1783 | |
1784 | // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase |
1785 | // because we need to explicitly check whether that option or its inverse was |
1786 | // present in the argument list in order to handle /fixed. |
1787 | auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); |
1788 | if (dynamicBaseArg && |
1789 | dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) |
1790 | config->dynamicBase = false; |
1791 | |
1792 | // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the |
1793 | // default setting for any other project type.", but link.exe defaults to |
1794 | // /FIXED:NO for exe outputs as well. Match behavior, not docs. |
1795 | bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); |
1796 | if (fixed) { |
1797 | if (dynamicBaseArg && |
1798 | dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { |
1799 | Err(ctx) << "/fixed must not be specified with /dynamicbase"; |
1800 | } else { |
1801 | config->relocatable = false; |
1802 | config->dynamicBase = false; |
1803 | } |
1804 | } |
1805 | |
1806 | // Handle /appcontainer |
1807 | config->appContainer = |
1808 | args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); |
1809 | |
1810 | // Handle /machine |
1811 | { |
1812 | llvm::TimeTraceScope timeScope2("Machine arg"); |
1813 | if (auto *arg = args.getLastArg(OPT_machine)) { |
1814 | MachineTypes machine = getMachineType(arg->getValue()); |
1815 | if (machine == IMAGE_FILE_MACHINE_UNKNOWN) |
1816 | Fatal(ctx) << "unknown /machine argument: "<< arg->getValue(); |
1817 | setMachine(machine); |
1818 | } |
1819 | } |
1820 | |
1821 | // Handle /nodefaultlib:<filename> |
1822 | { |
1823 | llvm::TimeTraceScope timeScope2("Nodefaultlib"); |
1824 | for (auto *arg : args.filtered(OPT_nodefaultlib)) |
1825 | config->noDefaultLibs.insert(findLib(arg->getValue()).lower()); |
1826 | } |
1827 | |
1828 | // Handle /nodefaultlib |
1829 | if (args.hasArg(OPT_nodefaultlib_all)) |
1830 | config->noDefaultLibAll = true; |
1831 | |
1832 | // Handle /base |
1833 | if (auto *arg = args.getLastArg(OPT_base)) |
1834 | parseNumbers(arg: arg->getValue(), addr: &config->imageBase); |
1835 | |
1836 | // Handle /filealign |
1837 | if (auto *arg = args.getLastArg(OPT_filealign)) { |
1838 | parseNumbers(arg: arg->getValue(), addr: &config->fileAlign); |
1839 | if (!isPowerOf2_64(Value: config->fileAlign)) |
1840 | Err(ctx) << "/filealign: not a power of two: "<< config->fileAlign; |
1841 | } |
1842 | |
1843 | // Handle /stack |
1844 | if (auto *arg = args.getLastArg(OPT_stack)) |
1845 | parseNumbers(arg: arg->getValue(), addr: &config->stackReserve, size: &config->stackCommit); |
1846 | |
1847 | // Handle /guard:cf |
1848 | if (auto *arg = args.getLastArg(OPT_guard)) |
1849 | parseGuard(arg: arg->getValue()); |
1850 | |
1851 | // Handle /heap |
1852 | if (auto *arg = args.getLastArg(OPT_heap)) |
1853 | parseNumbers(arg: arg->getValue(), addr: &config->heapReserve, size: &config->heapCommit); |
1854 | |
1855 | // Handle /version |
1856 | if (auto *arg = args.getLastArg(OPT_version)) |
1857 | parseVersion(arg: arg->getValue(), major: &config->majorImageVersion, |
1858 | minor: &config->minorImageVersion); |
1859 | |
1860 | // Handle /subsystem |
1861 | if (auto *arg = args.getLastArg(OPT_subsystem)) |
1862 | parseSubsystem(arg: arg->getValue(), sys: &config->subsystem, |
1863 | major: &config->majorSubsystemVersion, |
1864 | minor: &config->minorSubsystemVersion); |
1865 | |
1866 | // Handle /osversion |
1867 | if (auto *arg = args.getLastArg(OPT_osversion)) { |
1868 | parseVersion(arg: arg->getValue(), major: &config->majorOSVersion, |
1869 | minor: &config->minorOSVersion); |
1870 | } else { |
1871 | config->majorOSVersion = config->majorSubsystemVersion; |
1872 | config->minorOSVersion = config->minorSubsystemVersion; |
1873 | } |
1874 | |
1875 | // Handle /timestamp |
1876 | if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { |
1877 | if (arg->getOption().getID() == OPT_repro) { |
1878 | config->timestamp = 0; |
1879 | config->repro = true; |
1880 | } else { |
1881 | config->repro = false; |
1882 | StringRef value(arg->getValue()); |
1883 | if (value.getAsInteger(Radix: 0, Result&: config->timestamp)) |
1884 | Fatal(ctx) << "invalid timestamp: "<< value |
1885 | << ". Expected 32-bit integer"; |
1886 | } |
1887 | } else { |
1888 | config->repro = false; |
1889 | if (std::optional<std::string> epoch = |
1890 | Process::GetEnv(name: "SOURCE_DATE_EPOCH")) { |
1891 | StringRef value(*epoch); |
1892 | if (value.getAsInteger(Radix: 0, Result&: config->timestamp)) |
1893 | Fatal(ctx) << "invalid SOURCE_DATE_EPOCH timestamp: "<< value |
1894 | << ". Expected 32-bit integer"; |
1895 | } else { |
1896 | config->timestamp = time(timer: nullptr); |
1897 | } |
1898 | } |
1899 | |
1900 | // Handle /alternatename |
1901 | for (auto *arg : args.filtered(OPT_alternatename)) |
1902 | ctx.symtab.parseAlternateName(arg->getValue()); |
1903 | |
1904 | // Handle /include |
1905 | for (auto *arg : args.filtered(OPT_incl)) |
1906 | ctx.symtab.addGCRoot(arg->getValue()); |
1907 | |
1908 | // Handle /implib |
1909 | if (auto *arg = args.getLastArg(OPT_implib)) |
1910 | config->implib = arg->getValue(); |
1911 | |
1912 | config->noimplib = args.hasArg(OPT_noimplib); |
1913 | |
1914 | if (args.hasArg(OPT_profile)) |
1915 | doGC = true; |
1916 | // Handle /opt. |
1917 | std::optional<ICFLevel> icfLevel; |
1918 | if (args.hasArg(OPT_profile)) |
1919 | icfLevel = ICFLevel::None; |
1920 | unsigned tailMerge = 1; |
1921 | bool ltoDebugPM = false; |
1922 | for (auto *arg : args.filtered(OPT_opt)) { |
1923 | std::string str = StringRef(arg->getValue()).lower(); |
1924 | SmallVector<StringRef, 1> vec; |
1925 | StringRef(str).split(vec, ','); |
1926 | for (StringRef s : vec) { |
1927 | if (s == "ref") { |
1928 | doGC = true; |
1929 | } else if (s == "noref") { |
1930 | doGC = false; |
1931 | } else if (s == "icf"|| s.starts_with( "icf=")) { |
1932 | icfLevel = ICFLevel::All; |
1933 | } else if (s == "safeicf") { |
1934 | icfLevel = ICFLevel::Safe; |
1935 | } else if (s == "noicf") { |
1936 | icfLevel = ICFLevel::None; |
1937 | } else if (s == "lldtailmerge") { |
1938 | tailMerge = 2; |
1939 | } else if (s == "nolldtailmerge") { |
1940 | tailMerge = 0; |
1941 | } else if (s == "ltodebugpassmanager") { |
1942 | ltoDebugPM = true; |
1943 | } else if (s == "noltodebugpassmanager") { |
1944 | ltoDebugPM = false; |
1945 | } else if (s.consume_front("lldlto=")) { |
1946 | if (s.getAsInteger(10, config->ltoo) || config->ltoo > 3) |
1947 | Err(ctx) << "/opt:lldlto: invalid optimization level: "<< s; |
1948 | } else if (s.consume_front("lldltocgo=")) { |
1949 | config->ltoCgo.emplace(); |
1950 | if (s.getAsInteger(10, *config->ltoCgo) || *config->ltoCgo > 3) |
1951 | Err(ctx) << "/opt:lldltocgo: invalid codegen optimization level: " |
1952 | << s; |
1953 | } else if (s.consume_front("lldltojobs=")) { |
1954 | if (!get_threadpool_strategy(s)) |
1955 | Err(ctx) << "/opt:lldltojobs: invalid job count: "<< s; |
1956 | config->thinLTOJobs = s.str(); |
1957 | } else if (s.consume_front("lldltopartitions=")) { |
1958 | if (s.getAsInteger(10, config->ltoPartitions) || |
1959 | config->ltoPartitions == 0) |
1960 | Err(ctx) << "/opt:lldltopartitions: invalid partition count: "<< s; |
1961 | } else if (s != "lbr"&& s != "nolbr") |
1962 | Err(ctx) << "/opt: unknown option: "<< s; |
1963 | } |
1964 | } |
1965 | |
1966 | if (!icfLevel) |
1967 | icfLevel = doGC ? ICFLevel::All : ICFLevel::None; |
1968 | config->doGC = doGC; |
1969 | config->doICF = *icfLevel; |
1970 | config->tailMerge = |
1971 | (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2; |
1972 | config->ltoDebugPassManager = ltoDebugPM; |
1973 | |
1974 | // Handle /lldsavetemps |
1975 | if (args.hasArg(OPT_lldsavetemps)) { |
1976 | config->saveTempsArgs.insert_range(R: lldsaveTempsValues); |
1977 | } else { |
1978 | for (auto *arg : args.filtered(OPT_lldsavetemps_colon)) { |
1979 | StringRef s = arg->getValue(); |
1980 | if (llvm::is_contained(lldsaveTempsValues, s)) |
1981 | config->saveTempsArgs.insert(s); |
1982 | else |
1983 | Err(ctx) << "unknown /lldsavetemps value: "<< s; |
1984 | } |
1985 | } |
1986 | |
1987 | // Handle /lldemit |
1988 | if (auto *arg = args.getLastArg(OPT_lldemit)) { |
1989 | StringRef s = arg->getValue(); |
1990 | if (s == "obj") |
1991 | config->emit = EmitKind::Obj; |
1992 | else if (s == "llvm") |
1993 | config->emit = EmitKind::LLVM; |
1994 | else if (s == "asm") |
1995 | config->emit = EmitKind::ASM; |
1996 | else |
1997 | Err(ctx) << "/lldemit: unknown option: "<< s; |
1998 | } |
1999 | |
2000 | // Handle /kill-at |
2001 | if (args.hasArg(OPT_kill_at)) |
2002 | config->killAt = true; |
2003 | |
2004 | // Handle /lldltocache |
2005 | if (auto *arg = args.getLastArg(OPT_lldltocache)) |
2006 | config->ltoCache = arg->getValue(); |
2007 | |
2008 | // Handle /lldsavecachepolicy |
2009 | if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) |
2010 | config->ltoCachePolicy = CHECK( |
2011 | parseCachePruningPolicy(arg->getValue()), |
2012 | Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); |
2013 | |
2014 | // Handle /failifmismatch |
2015 | for (auto *arg : args.filtered(OPT_failifmismatch)) |
2016 | checkFailIfMismatch(arg->getValue(), nullptr); |
2017 | |
2018 | // Handle /merge |
2019 | for (auto *arg : args.filtered(OPT_merge)) |
2020 | parseMerge(arg->getValue()); |
2021 | |
2022 | // Add default section merging rules after user rules. User rules take |
2023 | // precedence, but we will emit a warning if there is a conflict. |
2024 | parseMerge(".idata=.rdata"); |
2025 | parseMerge(".didat=.rdata"); |
2026 | parseMerge(".edata=.rdata"); |
2027 | parseMerge(".xdata=.rdata"); |
2028 | parseMerge(".00cfg=.rdata"); |
2029 | parseMerge(".bss=.data"); |
2030 | |
2031 | if (isArm64EC(Machine: config->machine)) |
2032 | parseMerge(".wowthk=.text"); |
2033 | |
2034 | if (config->mingw) { |
2035 | parseMerge(".ctors=.rdata"); |
2036 | parseMerge(".dtors=.rdata"); |
2037 | parseMerge(".CRT=.rdata"); |
2038 | parseMerge(".data_cygwin_nocopy=.data"); |
2039 | } |
2040 | |
2041 | // Handle /section |
2042 | for (auto *arg : args.filtered(OPT_section)) |
2043 | parseSection(arg->getValue()); |
2044 | |
2045 | // Handle /align |
2046 | if (auto *arg = args.getLastArg(OPT_align)) { |
2047 | parseNumbers(arg: arg->getValue(), addr: &config->align); |
2048 | if (!isPowerOf2_64(Value: config->align)) |
2049 | Err(ctx) << "/align: not a power of two: "<< StringRef(arg->getValue()); |
2050 | if (!args.hasArg(OPT_driver)) |
2051 | Warn(ctx) << "/align specified without /driver; image may not run"; |
2052 | } |
2053 | |
2054 | // Handle /aligncomm |
2055 | for (auto *arg : args.filtered(OPT_aligncomm)) |
2056 | ctx.symtab.parseAligncomm(arg->getValue()); |
2057 | |
2058 | // Handle /manifestdependency. |
2059 | for (auto *arg : args.filtered(OPT_manifestdependency)) |
2060 | config->manifestDependencies.insert(arg->getValue()); |
2061 | |
2062 | // Handle /manifest and /manifest: |
2063 | if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { |
2064 | if (arg->getOption().getID() == OPT_manifest) |
2065 | config->manifest = Configuration::SideBySide; |
2066 | else |
2067 | parseManifest(arg: arg->getValue()); |
2068 | } |
2069 | |
2070 | // Handle /manifestuac |
2071 | if (auto *arg = args.getLastArg(OPT_manifestuac)) |
2072 | parseManifestUAC(arg: arg->getValue()); |
2073 | |
2074 | // Handle /manifestfile |
2075 | if (auto *arg = args.getLastArg(OPT_manifestfile)) |
2076 | config->manifestFile = arg->getValue(); |
2077 | |
2078 | // Handle /manifestinput |
2079 | for (auto *arg : args.filtered(OPT_manifestinput)) |
2080 | config->manifestInput.push_back(arg->getValue()); |
2081 | |
2082 | if (!config->manifestInput.empty() && |
2083 | config->manifest != Configuration::Embed) { |
2084 | Fatal(ctx) << "/manifestinput: requires /manifest:embed"; |
2085 | } |
2086 | |
2087 | // Handle /dwodir |
2088 | config->dwoDir = args.getLastArgValue(OPT_dwodir); |
2089 | |
2090 | config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); |
2091 | config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || |
2092 | args.hasArg(OPT_thinlto_index_only_arg); |
2093 | config->thinLTOIndexOnlyArg = |
2094 | args.getLastArgValue(OPT_thinlto_index_only_arg); |
2095 | std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew, |
2096 | config->thinLTOPrefixReplaceNativeObject) = |
2097 | getOldNewOptionsExtra(ctx, args, OPT_thinlto_prefix_replace); |
2098 | config->thinLTOObjectSuffixReplace = |
2099 | getOldNewOptions(ctx, args, OPT_thinlto_object_suffix_replace); |
2100 | config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); |
2101 | config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); |
2102 | config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); |
2103 | config->ltoSampleProfileName = args.getLastArgValue(OPT_lto_sample_profile); |
2104 | // Handle miscellaneous boolean flags. |
2105 | config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, |
2106 | OPT_lto_pgo_warn_mismatch_no, true); |
2107 | config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); |
2108 | config->allowIsolation = |
2109 | args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); |
2110 | config->incremental = |
2111 | args.hasFlag(OPT_incremental, OPT_incremental_no, |
2112 | !config->doGC && config->doICF == ICFLevel::None && |
2113 | !args.hasArg(OPT_order) && !args.hasArg(OPT_profile)); |
2114 | config->integrityCheck = |
2115 | args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); |
2116 | config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false); |
2117 | config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); |
2118 | for (auto *arg : args.filtered(OPT_swaprun)) |
2119 | parseSwaprun(arg->getValue()); |
2120 | config->terminalServerAware = |
2121 | !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); |
2122 | config->autoImport = |
2123 | args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw); |
2124 | config->pseudoRelocs = args.hasFlag( |
2125 | OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw); |
2126 | config->callGraphProfileSort = args.hasFlag( |
2127 | OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true); |
2128 | config->stdcallFixup = |
2129 | args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw); |
2130 | config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup); |
2131 | config->allowDuplicateWeak = |
2132 | args.hasFlag(OPT_lld_allow_duplicate_weak, |
2133 | OPT_lld_allow_duplicate_weak_no, config->mingw); |
2134 | |
2135 | if (args.hasFlag(OPT_inferasanlibs, OPT_inferasanlibs_no, false)) |
2136 | Warn(ctx) << "ignoring '/inferasanlibs', this flag is not supported"; |
2137 | |
2138 | if (config->incremental && args.hasArg(OPT_profile)) { |
2139 | Warn(ctx) << "ignoring '/incremental' due to '/profile' specification"; |
2140 | config->incremental = false; |
2141 | } |
2142 | |
2143 | if (config->incremental && args.hasArg(OPT_order)) { |
2144 | Warn(ctx) << "ignoring '/incremental' due to '/order' specification"; |
2145 | config->incremental = false; |
2146 | } |
2147 | |
2148 | if (config->incremental && config->doGC) { |
2149 | Warn(ctx) << "ignoring '/incremental' because REF is enabled; use " |
2150 | "'/opt:noref' to " |
2151 | "disable"; |
2152 | config->incremental = false; |
2153 | } |
2154 | |
2155 | if (config->incremental && config->doICF != ICFLevel::None) { |
2156 | Warn(ctx) << "ignoring '/incremental' because ICF is enabled; use " |
2157 | "'/opt:noicf' to " |
2158 | "disable"; |
2159 | config->incremental = false; |
2160 | } |
2161 | |
2162 | if (errCount(ctx)) |
2163 | return; |
2164 | |
2165 | std::set<sys::fs::UniqueID> wholeArchives; |
2166 | for (auto *arg : args.filtered(OPT_wholearchive_file)) |
2167 | if (std::optional<StringRef> path = findFile(arg->getValue())) |
2168 | if (std::optional<sys::fs::UniqueID> id = getUniqueID(*path)) |
2169 | wholeArchives.insert(*id); |
2170 | |
2171 | // A predicate returning true if a given path is an argument for |
2172 | // /wholearchive:, or /wholearchive is enabled globally. |
2173 | // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" |
2174 | // needs to be handled as "/wholearchive:foo.obj foo.obj". |
2175 | auto isWholeArchive = [&](StringRef path) -> bool { |
2176 | if (args.hasArg(OPT_wholearchive_flag)) |
2177 | return true; |
2178 | if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) |
2179 | return wholeArchives.count(x: *id); |
2180 | return false; |
2181 | }; |
2182 | |
2183 | // Create a list of input files. These can be given as OPT_INPUT options |
2184 | // and OPT_wholearchive_file options, and we also need to track OPT_start_lib |
2185 | // and OPT_end_lib. |
2186 | { |
2187 | llvm::TimeTraceScope timeScope2("Parse & queue inputs"); |
2188 | bool inLib = false; |
2189 | for (auto *arg : args) { |
2190 | switch (arg->getOption().getID()) { |
2191 | case OPT_end_lib: |
2192 | if (!inLib) |
2193 | Err(ctx) << "stray "<< arg->getSpelling(); |
2194 | inLib = false; |
2195 | break; |
2196 | case OPT_start_lib: |
2197 | if (inLib) |
2198 | Err(ctx) << "nested "<< arg->getSpelling(); |
2199 | inLib = true; |
2200 | break; |
2201 | case OPT_wholearchive_file: |
2202 | if (std::optional<StringRef> path = findFileIfNew(filename: arg->getValue())) |
2203 | enqueuePath(path: *path, wholeArchive: true, lazy: inLib); |
2204 | break; |
2205 | case OPT_INPUT: |
2206 | if (std::optional<StringRef> path = findFileIfNew(filename: arg->getValue())) |
2207 | enqueuePath(path: *path, wholeArchive: isWholeArchive(*path), lazy: inLib); |
2208 | break; |
2209 | default: |
2210 | // Ignore other options. |
2211 | break; |
2212 | } |
2213 | } |
2214 | } |
2215 | |
2216 | // Read all input files given via the command line. |
2217 | run(); |
2218 | if (errorCount()) |
2219 | return; |
2220 | |
2221 | // We should have inferred a machine type by now from the input files, but if |
2222 | // not we assume x64. |
2223 | if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { |
2224 | Warn(ctx) << "/machine is not specified. x64 is assumed"; |
2225 | setMachine(AMD64); |
2226 | } |
2227 | config->wordsize = config->is64() ? 8 : 4; |
2228 | |
2229 | if (config->printSearchPaths) { |
2230 | SmallString<256> buffer; |
2231 | raw_svector_ostream stream(buffer); |
2232 | stream << "Library search paths:\n"; |
2233 | |
2234 | for (StringRef path : searchPaths) { |
2235 | if (path == "") |
2236 | path = "(cwd)"; |
2237 | stream << " "<< path << "\n"; |
2238 | } |
2239 | |
2240 | Msg(ctx) << buffer; |
2241 | } |
2242 | |
2243 | // Process files specified as /defaultlib. These must be processed after |
2244 | // addWinSysRootLibSearchPaths(), which is why they are in a separate loop. |
2245 | for (auto *arg : args.filtered(OPT_defaultlib)) |
2246 | if (std::optional<StringRef> path = findLibIfNew(arg->getValue())) |
2247 | enqueuePath(*path, false, false); |
2248 | run(); |
2249 | if (errorCount()) |
2250 | return; |
2251 | |
2252 | // Handle /RELEASE |
2253 | if (args.hasArg(OPT_release)) |
2254 | config->writeCheckSum = true; |
2255 | |
2256 | // Handle /safeseh, x86 only, on by default, except for mingw. |
2257 | if (config->machine == I386) { |
2258 | config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw); |
2259 | config->noSEH = args.hasArg(OPT_noseh); |
2260 | } |
2261 | |
2262 | // Handle /stub |
2263 | if (auto *arg = args.getLastArg(OPT_stub)) |
2264 | parseDosStub(path: arg->getValue()); |
2265 | |
2266 | // Handle /functionpadmin |
2267 | for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) |
2268 | parseFunctionPadMin(arg); |
2269 | |
2270 | // Handle /dependentloadflag |
2271 | for (auto *arg : |
2272 | args.filtered(OPT_dependentloadflag, OPT_dependentloadflag_opt)) |
2273 | parseDependentLoadFlags(arg); |
2274 | |
2275 | if (tar) { |
2276 | llvm::TimeTraceScope timeScope("Reproducer: response file"); |
2277 | tar->append( |
2278 | Path: "response.txt", |
2279 | Data: createResponseFile(args, searchPaths: ArrayRef<StringRef>(searchPaths).slice(N: 1))); |
2280 | } |
2281 | |
2282 | // Handle /largeaddressaware |
2283 | config->largeAddressAware = args.hasFlag( |
2284 | OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); |
2285 | |
2286 | // Handle /highentropyva |
2287 | config->highEntropyVA = |
2288 | config->is64() && |
2289 | args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); |
2290 | |
2291 | if (!config->dynamicBase && |
2292 | (config->machine == ARMNT || isAnyArm64(Machine: config->machine))) |
2293 | Err(ctx) << "/dynamicbase:no is not compatible with " |
2294 | << machineToStr(MT: config->machine); |
2295 | |
2296 | // Handle /export |
2297 | { |
2298 | llvm::TimeTraceScope timeScope("Parse /export"); |
2299 | for (auto *arg : args.filtered(OPT_export)) { |
2300 | Export e = parseExport(arg->getValue()); |
2301 | if (config->machine == I386) { |
2302 | if (!isDecorated(e.name)) |
2303 | e.name = saver().save("_"+ e.name); |
2304 | if (!e.extName.empty() && !isDecorated(e.extName)) |
2305 | e.extName = saver().save("_"+ e.extName); |
2306 | } |
2307 | ctx.symtab.exports.push_back(e); |
2308 | } |
2309 | } |
2310 | |
2311 | // Handle /def |
2312 | if (auto *arg = args.getLastArg(OPT_deffile)) { |
2313 | // parseModuleDefs mutates Config object. |
2314 | ctx.symtab.parseModuleDefs(path: arg->getValue()); |
2315 | if (ctx.config.machine == ARM64X) { |
2316 | // MSVC ignores the /defArm64Native argument on non-ARM64X targets. |
2317 | // It is also ignored if the /def option is not specified. |
2318 | if (auto *arg = args.getLastArg(OPT_defarm64native)) |
2319 | ctx.hybridSymtab->parseModuleDefs(path: arg->getValue()); |
2320 | } |
2321 | } |
2322 | |
2323 | // Handle generation of import library from a def file. |
2324 | if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { |
2325 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { symtab.fixupExports(); }); |
2326 | if (!config->noimplib) |
2327 | createImportLibrary(/*asLib=*/true); |
2328 | return; |
2329 | } |
2330 | |
2331 | // Windows specific -- if no /subsystem is given, we need to infer |
2332 | // that from entry point name. Must happen before /entry handling, |
2333 | // and after the early return when just writing an import library. |
2334 | if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { |
2335 | llvm::TimeTraceScope timeScope("Infer subsystem"); |
2336 | config->subsystem = ctx.symtab.inferSubsystem(); |
2337 | if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) |
2338 | Fatal(ctx) << "subsystem must be defined"; |
2339 | } |
2340 | |
2341 | // Handle /entry and /dll |
2342 | ctx.forEachActiveSymtab(f: [&](SymbolTable &symtab) { |
2343 | llvm::TimeTraceScope timeScope("Entry point"); |
2344 | if (auto *arg = args.getLastArg(OPT_entry)) { |
2345 | if (!arg->getValue()[0]) |
2346 | Fatal(ctx) << "missing entry point symbol name"; |
2347 | symtab.entry = symtab.addGCRoot(sym: symtab.mangle(sym: arg->getValue()), aliasEC: true); |
2348 | } else if (!symtab.entry && !config->noEntry) { |
2349 | if (args.hasArg(OPT_dll)) { |
2350 | StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" |
2351 | : "_DllMainCRTStartup"; |
2352 | symtab.entry = symtab.addGCRoot(sym: s, aliasEC: true); |
2353 | } else if (config->driverWdm) { |
2354 | // /driver:wdm implies /entry:_NtProcessStartup |
2355 | symtab.entry = |
2356 | symtab.addGCRoot(sym: symtab.mangle(sym: "_NtProcessStartup"), aliasEC: true); |
2357 | } else { |
2358 | // Windows specific -- If entry point name is not given, we need to |
2359 | // infer that from user-defined entry name. |
2360 | StringRef s = symtab.findDefaultEntry(); |
2361 | if (s.empty()) |
2362 | Fatal(ctx) << "entry point must be defined"; |
2363 | symtab.entry = symtab.addGCRoot(sym: s, aliasEC: true); |
2364 | Log(ctx) << "Entry name inferred: "<< s; |
2365 | } |
2366 | } |
2367 | }); |
2368 | |
2369 | // Handle /delayload |
2370 | { |
2371 | llvm::TimeTraceScope timeScope("Delay load"); |
2372 | for (auto *arg : args.filtered(OPT_delayload)) { |
2373 | config->delayLoads.insert(StringRef(arg->getValue()).lower()); |
2374 | ctx.forEachActiveSymtab([&](SymbolTable &symtab) { |
2375 | if (symtab.machine == I386) { |
2376 | symtab.delayLoadHelper = symtab.addGCRoot("___delayLoadHelper2@8"); |
2377 | } else { |
2378 | symtab.delayLoadHelper = symtab.addGCRoot("__delayLoadHelper2", true); |
2379 | } |
2380 | }); |
2381 | } |
2382 | } |
2383 | |
2384 | // Set default image name if neither /out or /def set it. |
2385 | if (config->outputFile.empty()) { |
2386 | config->outputFile = getOutputPath( |
2387 | (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue(), |
2388 | config->dll, config->driver); |
2389 | } |
2390 | |
2391 | // Fail early if an output file is not writable. |
2392 | if (auto e = tryCreateFile(path: config->outputFile)) { |
2393 | Err(ctx) << "cannot open output file "<< config->outputFile << ": " |
2394 | << e.message(); |
2395 | return; |
2396 | } |
2397 | |
2398 | config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file); |
2399 | config->mapFile = getMapFile(args, OPT_map, OPT_map_file); |
2400 | |
2401 | if (config->mapFile != ""&& args.hasArg(OPT_map_info)) { |
2402 | for (auto *arg : args.filtered(OPT_map_info)) { |
2403 | std::string s = StringRef(arg->getValue()).lower(); |
2404 | if (s == "exports") |
2405 | config->mapInfo = true; |
2406 | else |
2407 | Err(ctx) << "unknown option: /mapinfo:"<< s; |
2408 | } |
2409 | } |
2410 | |
2411 | if (config->lldmapFile != ""&& config->lldmapFile == config->mapFile) { |
2412 | Warn(ctx) << "/lldmap and /map have the same output file '" |
2413 | << config->mapFile << "'.\n>>> ignoring /lldmap"; |
2414 | config->lldmapFile.clear(); |
2415 | } |
2416 | |
2417 | // If should create PDB, use the hash of PDB content for build id. Otherwise, |
2418 | // generate using the hash of executable content. |
2419 | if (args.hasFlag(OPT_build_id, OPT_build_id_no, false)) |
2420 | config->buildIDHash = BuildIDHash::Binary; |
2421 | |
2422 | if (shouldCreatePDB) { |
2423 | // Put the PDB next to the image if no /pdb flag was passed. |
2424 | if (config->pdbPath.empty()) { |
2425 | config->pdbPath = config->outputFile; |
2426 | sys::path::replace_extension(path&: config->pdbPath, extension: ".pdb"); |
2427 | } |
2428 | |
2429 | // The embedded PDB path should be the absolute path to the PDB if no |
2430 | // /pdbaltpath flag was passed. |
2431 | if (config->pdbAltPath.empty()) { |
2432 | config->pdbAltPath = config->pdbPath; |
2433 | |
2434 | // It's important to make the path absolute and remove dots. This path |
2435 | // will eventually be written into the PE header, and certain Microsoft |
2436 | // tools won't work correctly if these assumptions are not held. |
2437 | sys::fs::make_absolute(path&: config->pdbAltPath); |
2438 | sys::path::remove_dots(path&: config->pdbAltPath); |
2439 | } else { |
2440 | // Don't do this earlier, so that ctx.OutputFile is ready. |
2441 | parsePDBAltPath(); |
2442 | } |
2443 | config->buildIDHash = BuildIDHash::PDB; |
2444 | } |
2445 | |
2446 | // Set default image base if /base is not given. |
2447 | if (config->imageBase == uint64_t(-1)) |
2448 | config->imageBase = getDefaultImageBase(); |
2449 | |
2450 | ctx.forEachSymtab(f: [&](SymbolTable &symtab) { |
2451 | symtab.addSynthetic(n: symtab.mangle(sym: "__ImageBase"), c: nullptr); |
2452 | if (symtab.machine == I386) { |
2453 | symtab.addAbsolute(n: "___safe_se_handler_table", va: 0); |
2454 | symtab.addAbsolute(n: "___safe_se_handler_count", va: 0); |
2455 | } |
2456 | |
2457 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_fids_count"), va: 0); |
2458 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_fids_table"), va: 0); |
2459 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_flags"), va: 0); |
2460 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_iat_count"), va: 0); |
2461 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_iat_table"), va: 0); |
2462 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_longjmp_count"), va: 0); |
2463 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_longjmp_table"), va: 0); |
2464 | // Needed for MSVC 2017 15.5 CRT. |
2465 | symtab.addAbsolute(n: symtab.mangle(sym: "__enclave_config"), va: 0); |
2466 | // Needed for MSVC 2019 16.8 CRT. |
2467 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_eh_cont_count"), va: 0); |
2468 | symtab.addAbsolute(n: symtab.mangle(sym: "__guard_eh_cont_table"), va: 0); |
2469 | |
2470 | if (symtab.isEC()) { |
2471 | symtab.addAbsolute(n: "__arm64x_extra_rfe_table", va: 0); |
2472 | symtab.addAbsolute(n: "__arm64x_extra_rfe_table_size", va: 0); |
2473 | symtab.addAbsolute(n: "__arm64x_redirection_metadata", va: 0); |
2474 | symtab.addAbsolute(n: "__arm64x_redirection_metadata_count", va: 0); |
2475 | symtab.addAbsolute(n: "__hybrid_auxiliary_delayload_iat_copy", va: 0); |
2476 | symtab.addAbsolute(n: "__hybrid_auxiliary_delayload_iat", va: 0); |
2477 | symtab.addAbsolute(n: "__hybrid_auxiliary_iat", va: 0); |
2478 | symtab.addAbsolute(n: "__hybrid_auxiliary_iat_copy", va: 0); |
2479 | symtab.addAbsolute(n: "__hybrid_code_map", va: 0); |
2480 | symtab.addAbsolute(n: "__hybrid_code_map_count", va: 0); |
2481 | symtab.addAbsolute(n: "__hybrid_image_info_bitfield", va: 0); |
2482 | symtab.addAbsolute(n: "__x64_code_ranges_to_entry_points", va: 0); |
2483 | symtab.addAbsolute(n: "__x64_code_ranges_to_entry_points_count", va: 0); |
2484 | symtab.addSynthetic(n: "__guard_check_icall_a64n_fptr", c: nullptr); |
2485 | symtab.addSynthetic(n: "__arm64x_native_entrypoint", c: nullptr); |
2486 | } |
2487 | |
2488 | if (config->pseudoRelocs) { |
2489 | symtab.addAbsolute(n: symtab.mangle(sym: "__RUNTIME_PSEUDO_RELOC_LIST__"), va: 0); |
2490 | symtab.addAbsolute(n: symtab.mangle(sym: "__RUNTIME_PSEUDO_RELOC_LIST_END__"), va: 0); |
2491 | } |
2492 | if (config->mingw) { |
2493 | symtab.addAbsolute(n: symtab.mangle(sym: "__CTOR_LIST__"), va: 0); |
2494 | symtab.addAbsolute(n: symtab.mangle(sym: "__DTOR_LIST__"), va: 0); |
2495 | symtab.addAbsolute(n: "__data_start__", va: 0); |
2496 | symtab.addAbsolute(n: "__data_end__", va: 0); |
2497 | symtab.addAbsolute(n: "__bss_start__", va: 0); |
2498 | symtab.addAbsolute(n: "__bss_end__", va: 0); |
2499 | } |
2500 | if (config->debug || config->buildIDHash != BuildIDHash::None) |
2501 | if (symtab.findUnderscore(name: "__buildid")) |
2502 | symtab.addUndefined(name: symtab.mangle(sym: "__buildid")); |
2503 | }); |
2504 | |
2505 | // This code may add new undefined symbols to the link, which may enqueue more |
2506 | // symbol resolution tasks, so we need to continue executing tasks until we |
2507 | // converge. |
2508 | { |
2509 | llvm::TimeTraceScope timeScope("Add unresolved symbols"); |
2510 | do { |
2511 | ctx.forEachSymtab(f: [&](SymbolTable &symtab) { |
2512 | // Windows specific -- if entry point is not found, |
2513 | // search for its mangled names. |
2514 | if (symtab.entry) |
2515 | symtab.mangleMaybe(s: symtab.entry); |
2516 | |
2517 | // Windows specific -- Make sure we resolve all dllexported symbols. |
2518 | for (Export &e : symtab.exports) { |
2519 | if (!e.forwardTo.empty()) |
2520 | continue; |
2521 | e.sym = symtab.addGCRoot(sym: e.name, aliasEC: !e.data); |
2522 | if (e.source != ExportSource::Directives) |
2523 | e.symbolName = symtab.mangleMaybe(s: e.sym); |
2524 | } |
2525 | |
2526 | // Add weak aliases. Weak aliases is a mechanism to give remaining |
2527 | // undefined symbols final chance to be resolved successfully. |
2528 | for (auto pair : symtab.alternateNames) { |
2529 | StringRef from = pair.first; |
2530 | StringRef to = pair.second; |
2531 | Symbol *sym = symtab.find(name: from); |
2532 | if (!sym) |
2533 | continue; |
2534 | if (auto *u = dyn_cast<Undefined>(Val: sym)) { |
2535 | if (u->weakAlias) { |
2536 | // On ARM64EC, anti-dependency aliases are treated as undefined |
2537 | // symbols unless a demangled symbol aliases a defined one, which |
2538 | // is part of the implementation. |
2539 | if (!symtab.isEC() || !u->isAntiDep) |
2540 | continue; |
2541 | if (!isa<Undefined>(Val: u->weakAlias) && |
2542 | !isArm64ECMangledFunctionName(Name: u->getName())) |
2543 | continue; |
2544 | } |
2545 | u->setWeakAlias(sym: symtab.addUndefined(name: to)); |
2546 | } |
2547 | } |
2548 | }); |
2549 | |
2550 | ctx.forEachActiveSymtab(f: [&](SymbolTable &symtab) { |
2551 | // If any inputs are bitcode files, the LTO code generator may create |
2552 | // references to library functions that are not explicit in the bitcode |
2553 | // file's symbol table. If any of those library functions are defined in |
2554 | // a bitcode file in an archive member, we need to arrange to use LTO to |
2555 | // compile those archive members by adding them to the link beforehand. |
2556 | if (!symtab.bitcodeFileInstances.empty()) { |
2557 | llvm::Triple TT( |
2558 | symtab.bitcodeFileInstances.front()->obj->getTargetTriple()); |
2559 | for (auto *s : lto::LTO::getRuntimeLibcallSymbols(TT)) |
2560 | symtab.addLibcall(name: s); |
2561 | } |
2562 | |
2563 | // Windows specific -- if __load_config_used can be resolved, resolve |
2564 | // it. |
2565 | if (symtab.findUnderscore(name: "_load_config_used")) |
2566 | symtab.addGCRoot(sym: symtab.mangle(sym: "_load_config_used")); |
2567 | |
2568 | if (args.hasArg(OPT_include_optional)) { |
2569 | // Handle /includeoptional |
2570 | for (auto *arg : args.filtered(OPT_include_optional)) |
2571 | if (isa_and_nonnull<LazyArchive>(symtab.find(arg->getValue()))) |
2572 | symtab.addGCRoot(arg->getValue()); |
2573 | } |
2574 | }); |
2575 | } while (run()); |
2576 | } |
2577 | |
2578 | // Handle /includeglob |
2579 | for (StringRef pat : args::getStrings(args, OPT_incl_glob)) |
2580 | ctx.forEachActiveSymtab( |
2581 | [&](SymbolTable &symtab) { symtab.addUndefinedGlob(pat); }); |
2582 | |
2583 | // Create wrapped symbols for -wrap option. |
2584 | ctx.forEachSymtab(f: [&](SymbolTable &symtab) { |
2585 | addWrappedSymbols(symtab, args); |
2586 | // Load more object files that might be needed for wrapped symbols. |
2587 | if (!symtab.wrapped.empty()) |
2588 | while (run()) |
2589 | ; |
2590 | }); |
2591 | |
2592 | if (config->autoImport || config->stdcallFixup) { |
2593 | // MinGW specific. |
2594 | // Load any further object files that might be needed for doing automatic |
2595 | // imports, and do stdcall fixups. |
2596 | // |
2597 | // For cases with no automatically imported symbols, this iterates once |
2598 | // over the symbol table and doesn't do anything. |
2599 | // |
2600 | // For the normal case with a few automatically imported symbols, this |
2601 | // should only need to be run once, since each new object file imported |
2602 | // is an import library and wouldn't add any new undefined references, |
2603 | // but there's nothing stopping the __imp_ symbols from coming from a |
2604 | // normal object file as well (although that won't be used for the |
2605 | // actual autoimport later on). If this pass adds new undefined references, |
2606 | // we won't iterate further to resolve them. |
2607 | // |
2608 | // If stdcall fixups only are needed for loading import entries from |
2609 | // a DLL without import library, this also just needs running once. |
2610 | // If it ends up pulling in more object files from static libraries, |
2611 | // (and maybe doing more stdcall fixups along the way), this would need |
2612 | // to loop these two calls. |
2613 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { symtab.loadMinGWSymbols(); }); |
2614 | run(); |
2615 | } |
2616 | |
2617 | // At this point, we should not have any symbols that cannot be resolved. |
2618 | // If we are going to do codegen for link-time optimization, check for |
2619 | // unresolvable symbols first, so we don't spend time generating code that |
2620 | // will fail to link anyway. |
2621 | if (!config->forceUnresolved) |
2622 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { |
2623 | if (!symtab.bitcodeFileInstances.empty()) |
2624 | symtab.reportUnresolvable(); |
2625 | }); |
2626 | if (errorCount()) |
2627 | return; |
2628 | |
2629 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { |
2630 | symtab.hadExplicitExports = !symtab.exports.empty(); |
2631 | }); |
2632 | if (config->mingw) { |
2633 | // In MinGW, all symbols are automatically exported if no symbols |
2634 | // are chosen to be exported. |
2635 | maybeExportMinGWSymbols(args); |
2636 | } |
2637 | |
2638 | // Do LTO by compiling bitcode input files to a set of native COFF files then |
2639 | // link those files (unless -thinlto-index-only was given, in which case we |
2640 | // resolve symbols and write indices, but don't generate native code or link). |
2641 | ltoCompilationDone = true; |
2642 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { symtab.compileBitcodeFiles(); }); |
2643 | |
2644 | if (Defined *d = |
2645 | dyn_cast_or_null<Defined>(Val: ctx.symtab.findUnderscore(name: "_tls_used"))) |
2646 | config->gcroot.push_back(x: d); |
2647 | |
2648 | // If -thinlto-index-only is given, we should create only "index |
2649 | // files" and not object files. Index file creation is already done |
2650 | // in addCombinedLTOObject, so we are done if that's the case. |
2651 | // Likewise, don't emit object files for other /lldemit options. |
2652 | if (config->emit != EmitKind::Obj || config->thinLTOIndexOnly) |
2653 | return; |
2654 | |
2655 | // If we generated native object files from bitcode files, this resolves |
2656 | // references to the symbols we use from them. |
2657 | run(); |
2658 | |
2659 | // Apply symbol renames for -wrap. |
2660 | ctx.forEachSymtab(f: [](SymbolTable &symtab) { |
2661 | if (!symtab.wrapped.empty()) |
2662 | wrapSymbols(symtab); |
2663 | }); |
2664 | |
2665 | if (isArm64EC(Machine: config->machine)) |
2666 | createECExportThunks(); |
2667 | |
2668 | // Resolve remaining undefined symbols and warn about imported locals. |
2669 | ctx.forEachSymtab( |
2670 | f: [&](SymbolTable &symtab) { symtab.resolveRemainingUndefines(); }); |
2671 | |
2672 | if (errorCount()) |
2673 | return; |
2674 | |
2675 | if (config->mingw) { |
2676 | // Make sure the crtend.o object is the last object file. This object |
2677 | // file can contain terminating section chunks that need to be placed |
2678 | // last. GNU ld processes files and static libraries explicitly in the |
2679 | // order provided on the command line, while lld will pull in needed |
2680 | // files from static libraries only after the last object file on the |
2681 | // command line. |
2682 | for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end(); |
2683 | i != e; i++) { |
2684 | ObjFile *file = *i; |
2685 | if (isCrtend(s: file->getName())) { |
2686 | ctx.objFileInstances.erase(position: i); |
2687 | ctx.objFileInstances.push_back(x: file); |
2688 | break; |
2689 | } |
2690 | } |
2691 | } |
2692 | |
2693 | // Windows specific -- when we are creating a .dll file, we also |
2694 | // need to create a .lib file. In MinGW mode, we only do that when the |
2695 | // -implib option is given explicitly, for compatibility with GNU ld. |
2696 | if (config->dll || !ctx.symtab.exports.empty() || |
2697 | (ctx.config.machine == ARM64X && !ctx.hybridSymtab->exports.empty())) { |
2698 | llvm::TimeTraceScope timeScope("Create .lib exports"); |
2699 | ctx.forEachActiveSymtab(f: [](SymbolTable &symtab) { symtab.fixupExports(); }); |
2700 | if (!config->noimplib && (!config->mingw || !config->implib.empty())) |
2701 | createImportLibrary(/*asLib=*/false); |
2702 | ctx.forEachActiveSymtab( |
2703 | f: [](SymbolTable &symtab) { symtab.assignExportOrdinals(); }); |
2704 | } |
2705 | |
2706 | // Handle /output-def (MinGW specific). |
2707 | if (auto *arg = args.getLastArg(OPT_output_def)) |
2708 | writeDefFile(ctx, arg->getValue(), ctx.symtab.exports); |
2709 | |
2710 | // Set extra alignment for .comm symbols |
2711 | ctx.forEachSymtab(f: [&](SymbolTable &symtab) { |
2712 | for (auto pair : symtab.alignComm) { |
2713 | StringRef name = pair.first; |
2714 | uint32_t alignment = pair.second; |
2715 | |
2716 | Symbol *sym = symtab.find(name); |
2717 | if (!sym) { |
2718 | Warn(ctx) << "/aligncomm symbol "<< name << " not found"; |
2719 | continue; |
2720 | } |
2721 | |
2722 | // If the symbol isn't common, it must have been replaced with a regular |
2723 | // symbol, which will carry its own alignment. |
2724 | auto *dc = dyn_cast<DefinedCommon>(Val: sym); |
2725 | if (!dc) |
2726 | continue; |
2727 | |
2728 | CommonChunk *c = dc->getChunk(); |
2729 | c->setAlignment(std::max(a: c->getAlignment(), b: alignment)); |
2730 | } |
2731 | }); |
2732 | |
2733 | // Windows specific -- Create an embedded or side-by-side manifest. |
2734 | // /manifestdependency: enables /manifest unless an explicit /manifest:no is |
2735 | // also passed. |
2736 | if (config->manifest == Configuration::Embed) |
2737 | addBuffer(mb: createManifestRes(), wholeArchive: false, lazy: false); |
2738 | else if (config->manifest == Configuration::SideBySide || |
2739 | (config->manifest == Configuration::Default && |
2740 | !config->manifestDependencies.empty())) |
2741 | createSideBySideManifest(); |
2742 | |
2743 | // Handle /order. We want to do this at this moment because we |
2744 | // need a complete list of comdat sections to warn on nonexistent |
2745 | // functions. |
2746 | if (auto *arg = args.getLastArg(OPT_order)) { |
2747 | if (args.hasArg(OPT_call_graph_ordering_file)) |
2748 | Err(ctx) << "/order and /call-graph-order-file may not be used together"; |
2749 | parseOrderFile(arg: arg->getValue()); |
2750 | config->callGraphProfileSort = false; |
2751 | } |
2752 | |
2753 | // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). |
2754 | if (config->callGraphProfileSort) { |
2755 | llvm::TimeTraceScope timeScope("Call graph"); |
2756 | if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) |
2757 | parseCallGraphFile(path: arg->getValue()); |
2758 | else |
2759 | readCallGraphsFromObjectFiles(ctx); |
2760 | } |
2761 | |
2762 | // Handle /print-symbol-order. |
2763 | if (auto *arg = args.getLastArg(OPT_print_symbol_order)) |
2764 | config->printSymbolOrder = arg->getValue(); |
2765 | |
2766 | if (ctx.symtab.isEC()) |
2767 | ctx.symtab.initializeECThunks(); |
2768 | ctx.forEachActiveSymtab( |
2769 | f: [](SymbolTable &symtab) { symtab.initializeLoadConfig(); }); |
2770 | |
2771 | // Identify unreferenced COMDAT sections. |
2772 | if (config->doGC) { |
2773 | if (config->mingw) { |
2774 | // markLive doesn't traverse .eh_frame, but the personality function is |
2775 | // only reached that way. The proper solution would be to parse and |
2776 | // traverse the .eh_frame section, like the ELF linker does. |
2777 | // For now, just manually try to retain the known possible personality |
2778 | // functions. This doesn't bring in more object files, but only marks |
2779 | // functions that already have been included to be retained. |
2780 | ctx.forEachSymtab(f: [&](SymbolTable &symtab) { |
2781 | for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0", |
2782 | "rust_eh_personality"}) { |
2783 | Defined *d = dyn_cast_or_null<Defined>(Val: symtab.findUnderscore(name: n)); |
2784 | if (d && !d->isGCRoot) { |
2785 | d->isGCRoot = true; |
2786 | config->gcroot.push_back(x: d); |
2787 | } |
2788 | } |
2789 | }); |
2790 | } |
2791 | |
2792 | markLive(ctx); |
2793 | } |
2794 | |
2795 | // Needs to happen after the last call to addFile(). |
2796 | convertResources(); |
2797 | |
2798 | // Identify identical COMDAT sections to merge them. |
2799 | if (config->doICF != ICFLevel::None) { |
2800 | findKeepUniqueSections(ctx); |
2801 | doICF(ctx); |
2802 | } |
2803 | |
2804 | // Write the result. |
2805 | writeResult(ctx); |
2806 | |
2807 | // Stop early so we can print the results. |
2808 | rootTimer.stop(); |
2809 | if (config->showTiming) |
2810 | ctx.rootTimer.print(); |
2811 | |
2812 | if (config->timeTraceEnabled) { |
2813 | // Manually stop the topmost "COFF link" scope, since we're shutting down. |
2814 | timeTraceProfilerEnd(); |
2815 | |
2816 | checkError(timeTraceProfilerWrite( |
2817 | args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile)); |
2818 | timeTraceProfilerCleanup(); |
2819 | } |
2820 | } |
2821 | |
2822 | } // namespace lld::coff |
2823 |
Definitions
- COFFSyncStream
- Log
- Msg
- Warn
- Err
- Fatal
- errCount
- link
- getOldNewOptions
- getOldNewOptionsExtra
- getOutputPath
- isCrtend
- createFutureForFile
- getArch
- getChunks
- compatibleMachineType
- addFile
- takeBuffer
- addBuffer
- enqueuePath
- addArchiveBuffer
- enqueueArchiveMember
- isDecorated
- parseDirectives
- findFile
- getUniqueID
- findFileIfNew
- findLibMinGW
- findLib
- findLibIfNew
- setMachine
- detectWinSysRoot
- addClangLibSearchPaths
- addWinSysRootLibSearchPaths
- addLibSearchPaths
- getDefaultImageBase
- rewritePath
- createResponseFile
- parseDebugTypes
- getMapFile
- getImplibPath
- getImportName
- createImportLibrary
- enqueueTask
- run
- parseOrderFile
- parseCallGraphFile
- readCallGraphsFromObjectFiles
- markAddrsig
- findKeepUniqueSections
- parsePDBAltPath
- convertResources
- maybeCreateECExportThunk
- createECExportThunks
- pullArm64ECIcallHelper
- maybeExportMinGWSymbols
- getReproduceFile
- getVFS
- lldsaveTempsValues
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more