-
Notifications
You must be signed in to change notification settings - Fork 12.6k
/
Copy pathDriver.cpp
2804 lines (2486 loc) · 97.4 KB
/
Driver.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- Driver.cpp ---------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Driver.h"
#include "COFFLinkerContext.h"
#include "Config.h"
#include "DebugTypes.h"
#include "ICF.h"
#include "InputFiles.h"
#include "MarkLive.h"
#include "MinGW.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "Writer.h"
#include "lld/Common/Args.h"
#include "lld/Common/CommonLinkerContext.h"
#include "lld/Common/Driver.h"
#include "lld/Common/Filesystem.h"
#include "lld/Common/Timer.h"
#include "lld/Common/Version.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/BinaryFormat/Magic.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/LTO/LTO.h"
#include "llvm/Object/ArchiveWriter.h"
#include "llvm/Object/COFFImportFile.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/BinaryStreamReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/Parallel.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/TarWriter.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/TimeProfiler.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/TargetParser/Triple.h"
#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
#include <algorithm>
#include <future>
#include <memory>
#include <optional>
#include <tuple>
using namespace lld;
using namespace lld::coff;
using namespace llvm;
using namespace llvm::object;
using namespace llvm::COFF;
using namespace llvm::sys;
COFFSyncStream::COFFSyncStream(COFFLinkerContext &ctx, DiagLevel level)
: SyncStream(ctx.e, level), ctx(ctx) {}
COFFSyncStream coff::Log(COFFLinkerContext &ctx) {
return {ctx, DiagLevel::Log};
}
COFFSyncStream coff::Msg(COFFLinkerContext &ctx) {
return {ctx, DiagLevel::Msg};
}
COFFSyncStream coff::Warn(COFFLinkerContext &ctx) {
return {ctx, DiagLevel::Warn};
}
COFFSyncStream coff::Err(COFFLinkerContext &ctx) {
return {ctx, DiagLevel::Err};
}
COFFSyncStream coff::Fatal(COFFLinkerContext &ctx) {
return {ctx, DiagLevel::Fatal};
}
uint64_t coff::errCount(COFFLinkerContext &ctx) { return ctx.e.errorCount; }
namespace lld::coff {
bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS,
llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
// This driver-specific context will be freed later by unsafeLldMain().
auto *ctx = new COFFLinkerContext;
ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
ctx->e.logName = args::getFilenameWithoutExe(args[0]);
ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now"
" (use /errorlimit:0 to see all errors)";
ctx->driver.linkerMain(args);
return errCount(*ctx) == 0;
}
// Parse options of the form "old;new".
static std::pair<StringRef, StringRef>
getOldNewOptions(COFFLinkerContext &ctx, opt::InputArgList &args, unsigned id) {
auto *arg = args.getLastArg(id);
if (!arg)
return {"", ""};
StringRef s = arg->getValue();
std::pair<StringRef, StringRef> ret = s.split(';');
if (ret.second.empty())
Err(ctx) << arg->getSpelling() << " expects 'old;new' format, but got "
<< s;
return ret;
}
// Parse options of the form "old;new[;extra]".
static std::tuple<StringRef, StringRef, StringRef>
getOldNewOptionsExtra(COFFLinkerContext &ctx, opt::InputArgList &args,
unsigned id) {
auto [oldDir, second] = getOldNewOptions(ctx, args, id);
auto [newDir, extraDir] = second.split(';');
return {oldDir, newDir, extraDir};
}
// Drop directory components and replace extension with
// ".exe", ".dll" or ".sys".
static std::string getOutputPath(StringRef path, bool isDll, bool isDriver) {
StringRef ext = ".exe";
if (isDll)
ext = ".dll";
else if (isDriver)
ext = ".sys";
return (sys::path::stem(path) + ext).str();
}
// Returns true if S matches /crtend.?\.o$/.
static bool isCrtend(StringRef s) {
if (!s.consume_back(".o"))
return false;
if (s.ends_with("crtend"))
return true;
return !s.empty() && s.drop_back().ends_with("crtend");
}
// ErrorOr is not default constructible, so it cannot be used as the type
// parameter of a future.
// FIXME: We could open the file in createFutureForFile and avoid needing to
// return an error here, but for the moment that would cost us a file descriptor
// (a limited resource on Windows) for the duration that the future is pending.
using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
// Create a std::future that opens and maps a file using the best strategy for
// the host platform.
static std::future<MBErrPair> createFutureForFile(std::string path) {
#if _WIN64
// On Windows, file I/O is relatively slow so it is best to do this
// asynchronously. But 32-bit has issues with potentially launching tons
// of threads
auto strategy = std::launch::async;
#else
auto strategy = std::launch::deferred;
#endif
return std::async(strategy, [=]() {
auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
/*RequiresNullTerminator=*/false);
if (!mbOrErr)
return MBErrPair{nullptr, mbOrErr.getError()};
return MBErrPair{std::move(*mbOrErr), std::error_code()};
});
}
llvm::Triple::ArchType LinkerDriver::getArch() {
return getMachineArchType(ctx.config.machine);
}
std::vector<Chunk *> LinkerDriver::getChunks() const {
std::vector<Chunk *> res;
for (ObjFile *file : ctx.objFileInstances) {
ArrayRef<Chunk *> v = file->getChunks();
res.insert(res.end(), v.begin(), v.end());
}
return res;
}
static bool compatibleMachineType(COFFLinkerContext &ctx, MachineTypes mt) {
if (mt == IMAGE_FILE_MACHINE_UNKNOWN)
return true;
switch (ctx.config.machine) {
case ARM64:
return mt == ARM64 || mt == ARM64X;
case ARM64EC:
return isArm64EC(mt) || mt == AMD64;
case ARM64X:
return isAnyArm64(mt) || mt == AMD64;
case IMAGE_FILE_MACHINE_UNKNOWN:
return true;
default:
return ctx.config.machine == mt;
}
}
void LinkerDriver::addFile(InputFile *file) {
Log(ctx) << "Reading " << toString(file);
if (file->lazy) {
if (auto *f = dyn_cast<BitcodeFile>(file))
f->parseLazy();
else
cast<ObjFile>(file)->parseLazy();
} else {
file->parse();
if (auto *f = dyn_cast<ObjFile>(file)) {
ctx.objFileInstances.push_back(f);
} else if (auto *f = dyn_cast<BitcodeFile>(file)) {
if (ltoCompilationDone) {
Err(ctx) << "LTO object file " << toString(file)
<< " linked in after "
"doing LTO compilation.";
}
f->symtab.bitcodeFileInstances.push_back(f);
} else if (auto *f = dyn_cast<ImportFile>(file)) {
ctx.importFileInstances.push_back(f);
}
}
MachineTypes mt = file->getMachineType();
// The ARM64EC target must be explicitly specified and cannot be inferred.
if (mt == ARM64EC &&
(ctx.config.machine == IMAGE_FILE_MACHINE_UNKNOWN ||
(ctx.config.machineInferred &&
(ctx.config.machine == ARM64 || ctx.config.machine == AMD64)))) {
Err(ctx) << toString(file)
<< ": machine type arm64ec is ambiguous and cannot be "
"inferred, use /machine:arm64ec or /machine:arm64x";
return;
}
if (!compatibleMachineType(ctx, mt)) {
Err(ctx) << toString(file) << ": machine type " << machineToStr(mt)
<< " conflicts with " << machineToStr(ctx.config.machine);
return;
}
if (ctx.config.machine == IMAGE_FILE_MACHINE_UNKNOWN &&
mt != IMAGE_FILE_MACHINE_UNKNOWN) {
ctx.config.machineInferred = true;
setMachine(mt);
}
parseDirectives(file);
}
MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
MemoryBufferRef mbref = *mb;
make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
if (ctx.driver.tar)
ctx.driver.tar->append(relativeToRoot(mbref.getBufferIdentifier()),
mbref.getBuffer());
return mbref;
}
void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
bool wholeArchive, bool lazy) {
StringRef filename = mb->getBufferIdentifier();
MemoryBufferRef mbref = takeBuffer(std::move(mb));
// File type is detected by contents, not by file extension.
switch (identify_magic(mbref.getBuffer())) {
case file_magic::windows_resource:
resources.push_back(mbref);
break;
case file_magic::archive:
if (wholeArchive) {
std::unique_ptr<Archive> file =
CHECK(Archive::create(mbref), filename + ": failed to parse archive");
Archive *archive = file.get();
make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
int memberIndex = 0;
for (MemoryBufferRef m : getArchiveMembers(ctx, archive))
addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
return;
}
addFile(make<ArchiveFile>(ctx, mbref));
break;
case file_magic::bitcode:
addFile(BitcodeFile::create(ctx, mbref, "", 0, lazy));
break;
case file_magic::coff_object:
case file_magic::coff_import_library:
addFile(ObjFile::create(ctx, mbref, lazy));
break;
case file_magic::pdb:
addFile(make<PDBInputFile>(ctx, mbref));
break;
case file_magic::coff_cl_gl_object:
Err(ctx) << filename
<< ": is not a native COFF file. Recompile without /GL";
break;
case file_magic::pecoff_executable:
if (ctx.config.mingw) {
addFile(make<DLLFile>(ctx.symtab, mbref));
break;
}
if (filename.ends_with_insensitive(".dll")) {
Err(ctx) << filename
<< ": bad file type. Did you specify a DLL instead of an "
"import library?";
break;
}
[[fallthrough]];
default:
Err(ctx) << mbref.getBufferIdentifier() << ": unknown file type";
break;
}
}
void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
auto future = std::make_shared<std::future<MBErrPair>>(
createFutureForFile(std::string(path)));
std::string pathStr = std::string(path);
enqueueTask([=]() {
llvm::TimeTraceScope timeScope("File: ", path);
auto [mb, ec] = future->get();
if (ec) {
// Retry reading the file (synchronously) now that we may have added
// winsysroot search paths from SymbolTable::addFile().
// Retrying synchronously is important for keeping the order of inputs
// consistent.
// This makes it so that if the user passes something in the winsysroot
// before something we can find with an architecture, we won't find the
// winsysroot file.
if (std::optional<StringRef> retryPath = findFileIfNew(pathStr)) {
auto retryMb = MemoryBuffer::getFile(*retryPath, /*IsText=*/false,
/*RequiresNullTerminator=*/false);
ec = retryMb.getError();
if (!ec)
mb = std::move(*retryMb);
} else {
// We've already handled this file.
return;
}
}
if (ec) {
std::string msg = "could not open '" + pathStr + "': " + ec.message();
// Check if the filename is a typo for an option flag. OptTable thinks
// that all args that are not known options and that start with / are
// filenames, but e.g. `/nodefaultlibs` is more likely a typo for
// the option `/nodefaultlib` than a reference to a file in the root
// directory.
std::string nearest;
if (ctx.optTable.findNearest(pathStr, nearest) > 1)
Err(ctx) << msg;
else
Err(ctx) << msg << "; did you mean '" << nearest << "'";
} else
ctx.driver.addBuffer(std::move(mb), wholeArchive, lazy);
});
}
void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
StringRef parentName,
uint64_t offsetInArchive) {
file_magic magic = identify_magic(mb.getBuffer());
if (magic == file_magic::coff_import_library) {
InputFile *imp = make<ImportFile>(ctx, mb);
imp->parentName = parentName;
addFile(imp);
return;
}
InputFile *obj;
if (magic == file_magic::coff_object) {
obj = ObjFile::create(ctx, mb);
} else if (magic == file_magic::bitcode) {
obj = BitcodeFile::create(ctx, mb, parentName, offsetInArchive,
/*lazy=*/false);
} else if (magic == file_magic::coff_cl_gl_object) {
Err(ctx) << mb.getBufferIdentifier()
<< ": is not a native COFF file. Recompile without /GL?";
return;
} else {
Err(ctx) << "unknown file type: " << mb.getBufferIdentifier();
return;
}
obj->parentName = parentName;
addFile(obj);
Log(ctx) << "Loaded " << obj << " for " << symName;
}
void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
const Archive::Symbol &sym,
StringRef parentName) {
auto reportBufferError = [=](Error &&e, StringRef childName) {
Fatal(ctx) << "could not get the buffer for the member defining symbol "
<< &sym << ": " << parentName << "(" << childName
<< "): " << std::move(e);
};
if (!c.getParent()->isThin()) {
uint64_t offsetInArchive = c.getChildOffset();
Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
if (!mbOrErr)
reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
MemoryBufferRef mb = mbOrErr.get();
enqueueTask([=]() {
llvm::TimeTraceScope timeScope("Archive: ", mb.getBufferIdentifier());
ctx.driver.addArchiveBuffer(mb, toCOFFString(ctx, sym), parentName,
offsetInArchive);
});
return;
}
std::string childName =
CHECK(c.getFullName(),
"could not get the filename for the member defining symbol " +
toCOFFString(ctx, sym));
auto future =
std::make_shared<std::future<MBErrPair>>(createFutureForFile(childName));
enqueueTask([=]() {
auto mbOrErr = future->get();
if (mbOrErr.second)
reportBufferError(errorCodeToError(mbOrErr.second), childName);
llvm::TimeTraceScope timeScope("Archive: ",
mbOrErr.first->getBufferIdentifier());
// Pass empty string as archive name so that the original filename is
// used as the buffer identifier.
ctx.driver.addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
toCOFFString(ctx, sym), "",
/*OffsetInArchive=*/0);
});
}
bool LinkerDriver::isDecorated(StringRef sym) {
return sym.starts_with("@") || sym.contains("@@") || sym.starts_with("?") ||
(!ctx.config.mingw && sym.contains('@'));
}
// Parses .drectve section contents and returns a list of files
// specified by /defaultlib.
void LinkerDriver::parseDirectives(InputFile *file) {
StringRef s = file->getDirectives();
if (s.empty())
return;
Log(ctx) << "Directives: " << file << ": " << s;
ArgParser parser(ctx);
// .drectve is always tokenized using Windows shell rules.
// /EXPORT: option can appear too many times, processing in fastpath.
ParsedDirectives directives = parser.parseDirectives(s);
for (StringRef e : directives.exports) {
// If a common header file contains dllexported function
// declarations, many object files may end up with having the
// same /EXPORT options. In order to save cost of parsing them,
// we dedup them first.
if (!file->symtab.directivesExports.insert(e).second)
continue;
Export exp = parseExport(e);
if (ctx.config.machine == I386 && ctx.config.mingw) {
if (!isDecorated(exp.name))
exp.name = saver().save("_" + exp.name);
if (!exp.extName.empty() && !isDecorated(exp.extName))
exp.extName = saver().save("_" + exp.extName);
}
exp.source = ExportSource::Directives;
file->symtab.exports.push_back(exp);
}
// Handle /include: in bulk.
for (StringRef inc : directives.includes)
file->symtab.addGCRoot(inc);
// Handle /exclude-symbols: in bulk.
for (StringRef e : directives.excludes) {
SmallVector<StringRef, 2> vec;
e.split(vec, ',');
for (StringRef sym : vec)
excludedSymbols.insert(file->symtab.mangle(sym));
}
// https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160
for (auto *arg : directives.args) {
switch (arg->getOption().getID()) {
case OPT_aligncomm:
parseAligncomm(arg->getValue());
break;
case OPT_alternatename:
parseAlternateName(arg->getValue());
break;
case OPT_defaultlib:
if (std::optional<StringRef> path = findLibIfNew(arg->getValue()))
enqueuePath(*path, false, false);
break;
case OPT_entry:
if (!arg->getValue()[0])
Fatal(ctx) << "missing entry point symbol name";
ctx.forEachSymtab([&](SymbolTable &symtab) {
symtab.entry = symtab.addGCRoot(symtab.mangle(arg->getValue()), true);
});
break;
case OPT_failifmismatch:
checkFailIfMismatch(arg->getValue(), file);
break;
case OPT_incl:
file->symtab.addGCRoot(arg->getValue());
break;
case OPT_manifestdependency:
ctx.config.manifestDependencies.insert(arg->getValue());
break;
case OPT_merge:
parseMerge(arg->getValue());
break;
case OPT_nodefaultlib:
ctx.config.noDefaultLibs.insert(findLib(arg->getValue()).lower());
break;
case OPT_release:
ctx.config.writeCheckSum = true;
break;
case OPT_section:
parseSection(arg->getValue());
break;
case OPT_stack:
parseNumbers(arg->getValue(), &ctx.config.stackReserve,
&ctx.config.stackCommit);
break;
case OPT_subsystem: {
bool gotVersion = false;
parseSubsystem(arg->getValue(), &ctx.config.subsystem,
&ctx.config.majorSubsystemVersion,
&ctx.config.minorSubsystemVersion, &gotVersion);
if (gotVersion) {
ctx.config.majorOSVersion = ctx.config.majorSubsystemVersion;
ctx.config.minorOSVersion = ctx.config.minorSubsystemVersion;
}
break;
}
// Only add flags here that link.exe accepts in
// `#pragma comment(linker, "/flag")`-generated sections.
case OPT_editandcontinue:
case OPT_guardsym:
case OPT_throwingnew:
case OPT_inferasanlibs:
case OPT_inferasanlibs_no:
break;
default:
Err(ctx) << arg->getSpelling() << " is not allowed in .drectve ("
<< toString(file) << ")";
}
}
}
// Find file from search paths. You can omit ".obj", this function takes
// care of that. Note that the returned path is not guaranteed to exist.
StringRef LinkerDriver::findFile(StringRef filename) {
auto getFilename = [this](StringRef filename) -> StringRef {
if (ctx.config.vfs)
if (auto statOrErr = ctx.config.vfs->status(filename))
return saver().save(statOrErr->getName());
return filename;
};
if (sys::path::is_absolute(filename))
return getFilename(filename);
bool hasExt = filename.contains('.');
for (StringRef dir : searchPaths) {
SmallString<128> path = dir;
sys::path::append(path, filename);
path = SmallString<128>{getFilename(path.str())};
if (sys::fs::exists(path.str()))
return saver().save(path.str());
if (!hasExt) {
path.append(".obj");
path = SmallString<128>{getFilename(path.str())};
if (sys::fs::exists(path.str()))
return saver().save(path.str());
}
}
return filename;
}
static std::optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
sys::fs::UniqueID ret;
if (sys::fs::getUniqueID(path, ret))
return std::nullopt;
return ret;
}
// Resolves a file path. This never returns the same path
// (in that case, it returns std::nullopt).
std::optional<StringRef> LinkerDriver::findFileIfNew(StringRef filename) {
StringRef path = findFile(filename);
if (std::optional<sys::fs::UniqueID> id = getUniqueID(path)) {
bool seen = !visitedFiles.insert(*id).second;
if (seen)
return std::nullopt;
}
if (path.ends_with_insensitive(".lib"))
visitedLibs.insert(std::string(sys::path::filename(path).lower()));
return path;
}
// MinGW specific. If an embedded directive specified to link to
// foo.lib, but it isn't found, try libfoo.a instead.
StringRef LinkerDriver::findLibMinGW(StringRef filename) {
if (filename.contains('/') || filename.contains('\\'))
return filename;
SmallString<128> s = filename;
sys::path::replace_extension(s, ".a");
StringRef libName = saver().save("lib" + s.str());
return findFile(libName);
}
// Find library file from search path.
StringRef LinkerDriver::findLib(StringRef filename) {
// Add ".lib" to Filename if that has no file extension.
bool hasExt = filename.contains('.');
if (!hasExt)
filename = saver().save(filename + ".lib");
StringRef ret = findFile(filename);
// For MinGW, if the find above didn't turn up anything, try
// looking for a MinGW formatted library name.
if (ctx.config.mingw && ret == filename)
return findLibMinGW(filename);
return ret;
}
// Resolves a library path. /nodefaultlib options are taken into
// consideration. This never returns the same path (in that case,
// it returns std::nullopt).
std::optional<StringRef> LinkerDriver::findLibIfNew(StringRef filename) {
if (ctx.config.noDefaultLibAll)
return std::nullopt;
if (!visitedLibs.insert(filename.lower()).second)
return std::nullopt;
StringRef path = findLib(filename);
if (ctx.config.noDefaultLibs.count(path.lower()))
return std::nullopt;
if (std::optional<sys::fs::UniqueID> id = getUniqueID(path))
if (!visitedFiles.insert(*id).second)
return std::nullopt;
return path;
}
void LinkerDriver::setMachine(MachineTypes machine) {
assert(ctx.config.machine == IMAGE_FILE_MACHINE_UNKNOWN);
assert(machine != IMAGE_FILE_MACHINE_UNKNOWN);
ctx.config.machine = machine;
if (machine != ARM64X) {
ctx.symtab.machine = machine;
if (machine == ARM64EC)
ctx.symtabEC = &ctx.symtab;
} else {
ctx.symtab.machine = ARM64;
ctx.hybridSymtab.emplace(ctx, ARM64EC);
ctx.symtabEC = &*ctx.hybridSymtab;
}
addWinSysRootLibSearchPaths();
}
void LinkerDriver::detectWinSysRoot(const opt::InputArgList &Args) {
IntrusiveRefCntPtr<vfs::FileSystem> VFS = vfs::getRealFileSystem();
// Check the command line first, that's the user explicitly telling us what to
// use. Check the environment next, in case we're being invoked from a VS
// command prompt. Failing that, just try to find the newest Visual Studio
// version we can and use its default VC toolchain.
std::optional<StringRef> VCToolsDir, VCToolsVersion, WinSysRoot;
if (auto *A = Args.getLastArg(OPT_vctoolsdir))
VCToolsDir = A->getValue();
if (auto *A = Args.getLastArg(OPT_vctoolsversion))
VCToolsVersion = A->getValue();
if (auto *A = Args.getLastArg(OPT_winsysroot))
WinSysRoot = A->getValue();
if (!findVCToolChainViaCommandLine(*VFS, VCToolsDir, VCToolsVersion,
WinSysRoot, vcToolChainPath, vsLayout) &&
(Args.hasArg(OPT_lldignoreenv) ||
!findVCToolChainViaEnvironment(*VFS, vcToolChainPath, vsLayout)) &&
!findVCToolChainViaSetupConfig(*VFS, {}, vcToolChainPath, vsLayout) &&
!findVCToolChainViaRegistry(vcToolChainPath, vsLayout))
return;
// If the VC environment hasn't been configured (perhaps because the user did
// not run vcvarsall), try to build a consistent link environment. If the
// environment variable is set however, assume the user knows what they're
// doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env
// vars.
if (const auto *A = Args.getLastArg(OPT_diasdkdir, OPT_winsysroot)) {
diaPath = A->getValue();
if (A->getOption().getID() == OPT_winsysroot)
path::append(diaPath, "DIA SDK");
}
useWinSysRootLibPath = Args.hasArg(OPT_lldignoreenv) ||
!Process::GetEnv("LIB") ||
Args.getLastArg(OPT_vctoolsdir, OPT_winsysroot);
if (Args.hasArg(OPT_lldignoreenv) || !Process::GetEnv("LIB") ||
Args.getLastArg(OPT_winsdkdir, OPT_winsysroot)) {
std::optional<StringRef> WinSdkDir, WinSdkVersion;
if (auto *A = Args.getLastArg(OPT_winsdkdir))
WinSdkDir = A->getValue();
if (auto *A = Args.getLastArg(OPT_winsdkversion))
WinSdkVersion = A->getValue();
if (useUniversalCRT(vsLayout, vcToolChainPath, getArch(), *VFS)) {
std::string UniversalCRTSdkPath;
std::string UCRTVersion;
if (getUniversalCRTSdkDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot,
UniversalCRTSdkPath, UCRTVersion)) {
universalCRTLibPath = UniversalCRTSdkPath;
path::append(universalCRTLibPath, "Lib", UCRTVersion, "ucrt");
}
}
std::string sdkPath;
std::string windowsSDKIncludeVersion;
std::string windowsSDKLibVersion;
if (getWindowsSDKDir(*VFS, WinSdkDir, WinSdkVersion, WinSysRoot, sdkPath,
sdkMajor, windowsSDKIncludeVersion,
windowsSDKLibVersion)) {
windowsSdkLibPath = sdkPath;
path::append(windowsSdkLibPath, "Lib");
if (sdkMajor >= 8)
path::append(windowsSdkLibPath, windowsSDKLibVersion, "um");
}
}
}
void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) {
std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
SmallString<128> binDir(lldBinary);
sys::path::remove_filename(binDir); // remove lld-link.exe
StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
SmallString<128> libDir(rootDir);
sys::path::append(libDir, "lib");
// Add the resource dir library path
SmallString<128> runtimeLibDir(rootDir);
sys::path::append(runtimeLibDir, "lib", "clang",
std::to_string(LLVM_VERSION_MAJOR), "lib");
// Resource dir + osname, which is hardcoded to windows since we are in the
// COFF driver.
SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
sys::path::append(runtimeLibDirWithOS, "windows");
searchPaths.push_back(saver().save(runtimeLibDirWithOS.str()));
searchPaths.push_back(saver().save(runtimeLibDir.str()));
searchPaths.push_back(saver().save(libDir.str()));
}
void LinkerDriver::addWinSysRootLibSearchPaths() {
if (!diaPath.empty()) {
// The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
path::append(diaPath, "lib", archToLegacyVCArch(getArch()));
searchPaths.push_back(saver().save(diaPath.str()));
}
if (useWinSysRootLibPath) {
searchPaths.push_back(saver().save(getSubDirectoryPath(
SubDirectoryType::Lib, vsLayout, vcToolChainPath, getArch())));
searchPaths.push_back(saver().save(
getSubDirectoryPath(SubDirectoryType::Lib, vsLayout, vcToolChainPath,
getArch(), "atlmfc")));
}
if (!universalCRTLibPath.empty()) {
StringRef ArchName = archToWindowsSDKArch(getArch());
if (!ArchName.empty()) {
path::append(universalCRTLibPath, ArchName);
searchPaths.push_back(saver().save(universalCRTLibPath.str()));
}
}
if (!windowsSdkLibPath.empty()) {
std::string path;
if (appendArchToWindowsSDKLibPath(sdkMajor, windowsSdkLibPath, getArch(),
path))
searchPaths.push_back(saver().save(path));
}
}
// Parses LIB environment which contains a list of search paths.
void LinkerDriver::addLibSearchPaths() {
std::optional<std::string> envOpt = Process::GetEnv("LIB");
if (!envOpt)
return;
StringRef env = saver().save(*envOpt);
while (!env.empty()) {
StringRef path;
std::tie(path, env) = env.split(';');
searchPaths.push_back(path);
}
}
uint64_t LinkerDriver::getDefaultImageBase() {
if (ctx.config.is64())
return ctx.config.dll ? 0x180000000 : 0x140000000;
return ctx.config.dll ? 0x10000000 : 0x400000;
}
static std::string rewritePath(StringRef s) {
if (fs::exists(s))
return relativeToRoot(s);
return std::string(s);
}
// Reconstructs command line arguments so that so that you can re-run
// the same command with the same inputs. This is for --reproduce.
static std::string createResponseFile(const opt::InputArgList &args,
ArrayRef<StringRef> searchPaths) {
SmallString<0> data;
raw_svector_ostream os(data);
for (auto *arg : args) {
switch (arg->getOption().getID()) {
case OPT_linkrepro:
case OPT_reproduce:
case OPT_libpath:
case OPT_winsysroot:
break;
case OPT_INPUT:
os << quote(rewritePath(arg->getValue())) << "\n";
break;
case OPT_wholearchive_file:
os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << "\n";
break;
case OPT_call_graph_ordering_file:
case OPT_deffile:
case OPT_manifestinput:
case OPT_natvis:
os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n';
break;
case OPT_order: {
StringRef orderFile = arg->getValue();
orderFile.consume_front("@");
os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n';
break;
}
case OPT_pdbstream: {
const std::pair<StringRef, StringRef> nameFile =
StringRef(arg->getValue()).split("=");
os << arg->getSpelling() << nameFile.first << '='
<< quote(rewritePath(nameFile.second)) << '\n';
break;
}
case OPT_implib:
case OPT_manifestfile:
case OPT_pdb:
case OPT_pdbstripped:
case OPT_out:
os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
break;
default:
os << toString(*arg) << "\n";
}
}
for (StringRef path : searchPaths) {
std::string relPath = relativeToRoot(path);
os << "/libpath:" << quote(relPath) << "\n";
}
return std::string(data);
}
static unsigned parseDebugTypes(COFFLinkerContext &ctx,
const opt::InputArgList &args) {
unsigned debugTypes = static_cast<unsigned>(DebugType::None);
if (auto *a = args.getLastArg(OPT_debugtype)) {
SmallVector<StringRef, 3> types;
StringRef(a->getValue())
.split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
for (StringRef type : types) {
unsigned v = StringSwitch<unsigned>(type.lower())
.Case("cv", static_cast<unsigned>(DebugType::CV))
.Case("pdata", static_cast<unsigned>(DebugType::PData))
.Case("fixup", static_cast<unsigned>(DebugType::Fixup))
.Default(0);
if (v == 0) {
Warn(ctx) << "/debugtype: unknown option '" << type << "'";
continue;
}
debugTypes |= v;
}
return debugTypes;
}
// Default debug types
debugTypes = static_cast<unsigned>(DebugType::CV);
if (args.hasArg(OPT_driver))
debugTypes |= static_cast<unsigned>(DebugType::PData);
if (args.hasArg(OPT_profile))
debugTypes |= static_cast<unsigned>(DebugType::Fixup);
return debugTypes;
}
std::string LinkerDriver::getMapFile(const opt::InputArgList &args,
opt::OptSpecifier os,
opt::OptSpecifier osFile) {
auto *arg = args.getLastArg(os, osFile);
if (!arg)
return "";
if (arg->getOption().getID() == osFile.getID())
return arg->getValue();
assert(arg->getOption().getID() == os.getID());
StringRef outFile = ctx.config.outputFile;
return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
}
std::string LinkerDriver::getImplibPath() {
if (!ctx.config.implib.empty())
return std::string(ctx.config.implib);
SmallString<128> out = StringRef(ctx.config.outputFile);
sys::path::replace_extension(out, ".lib");
return std::string(out);
}
// The import name is calculated as follows:
//
// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
// -----+----------------+---------------------+------------------
// LINK | {value} | {value}.{.dll/.exe} | {output name}
// LIB | {value} | {value}.dll | {output name}.dll
//
std::string LinkerDriver::getImportName(bool asLib) {
SmallString<128> out;
if (ctx.config.importName.empty()) {
out.assign(sys::path::filename(ctx.config.outputFile));
if (asLib)
sys::path::replace_extension(out, ".dll");
} else {
out.assign(ctx.config.importName);
if (!sys::path::has_extension(out))
sys::path::replace_extension(out,
(ctx.config.dll || asLib) ? ".dll" : ".exe");
}
return std::string(out);
}
void LinkerDriver::createImportLibrary(bool asLib) {
llvm::TimeTraceScope timeScope("Create import library");
std::vector<COFFShortExport> exports, nativeExports;
auto getExports = [](SymbolTable &symtab,
std::vector<COFFShortExport> &exports) {
for (Export &e1 : symtab.exports) {
COFFShortExport e2;
e2.Name = std::string(e1.name);
e2.SymbolName = std::string(e1.symbolName);
e2.ExtName = std::string(e1.extName);
e2.ExportAs = std::string(e1.exportAs);
e2.ImportName = std::string(e1.importName);
e2.Ordinal = e1.ordinal;
e2.Noname = e1.noname;
e2.Data = e1.data;
e2.Private = e1.isPrivate;
e2.Constant = e1.constant;
exports.push_back(e2);
}
};
if (ctx.hybridSymtab) {
getExports(ctx.symtab, nativeExports);
getExports(*ctx.hybridSymtab, exports);
} else {
getExports(ctx.symtab, exports);
}
std::string libName = getImportName(asLib);
std::string path = getImplibPath();
if (!ctx.config.incremental) {
checkError(writeImportLibrary(libName, path, exports, ctx.config.machine,
ctx.config.mingw, nativeExports));
return;
}
// If the import library already exists, replace it only if the contents
// have changed.
ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
if (!oldBuf) {
checkError(writeImportLibrary(libName, path, exports, ctx.config.machine,
ctx.config.mingw, nativeExports));
return;