-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathModuleInterfaceLoader.cpp
2814 lines (2510 loc) · 116 KB
/
ModuleInterfaceLoader.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
//===------ ModuleInterfaceLoader.cpp - Loads .swiftinterface files -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "textual-module-interface"
#include "swift/Frontend/ModuleInterfaceLoader.h"
#include "ModuleInterfaceBuilder.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/FileSystem.h"
#include "swift/AST/Module.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Platform.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Frontend/CachingUtils.h"
#include "swift/Frontend/CompileJobCacheResult.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/ModuleInterfaceSupport.h"
#include "swift/Parse/ParseVersion.h"
#include "swift/Serialization/SerializationOptions.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Serialization/Validation.h"
#include "swift/Strings.h"
#include "clang/Basic/Module.h"
#include "clang/Frontend/CompileJobCacheResult.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Twine.h"
#include "llvm/CAS/ActionCache.h"
#include "llvm/CAS/ObjectStore.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/VirtualOutputBackend.h"
#include "llvm/Support/YAMLParser.h"
#include "llvm/Support/YAMLTraits.h"
#include "llvm/Support/xxhash.h"
using namespace swift;
using FileDependency = SerializationOptions::FileDependency;
#pragma mark - Forwarding Modules
namespace {
/// Describes a "forwarding module", that is, a .swiftmodule that's actually
/// a YAML file inside, pointing to a the original .swiftmodule but describing
/// a different dependency resolution strategy.
struct ForwardingModule {
/// The path to the original .swiftmodule in the prebuilt cache.
std::string underlyingModulePath;
/// Describes a set of file-based dependencies with their size and
/// modification time stored. This is slightly different from
/// \c SerializationOptions::FileDependency, because this type needs to be
/// serializable to and from YAML.
struct Dependency {
std::string path;
uint64_t size;
uint64_t lastModificationTime;
bool isSDKRelative;
};
std::vector<Dependency> dependencies;
unsigned version = 1;
ForwardingModule() = default;
ForwardingModule(StringRef underlyingModulePath)
: underlyingModulePath(underlyingModulePath) {}
/// Loads the contents of the forwarding module whose contents lie in
/// the provided buffer, and returns a new \c ForwardingModule, or an error
/// if the YAML could not be parsed.
static llvm::ErrorOr<ForwardingModule> load(const llvm::MemoryBuffer &buf);
/// Adds a given dependency to the dependencies list.
void addDependency(StringRef path, bool isSDKRelative, uint64_t size,
uint64_t modTime) {
dependencies.push_back({path.str(), size, modTime, isSDKRelative});
}
};
} // end anonymous namespace
#pragma mark - YAML Serialization
namespace llvm {
namespace yaml {
template <>
struct MappingTraits<ForwardingModule::Dependency> {
static void mapping(IO &io, ForwardingModule::Dependency &dep) {
io.mapRequired("mtime", dep.lastModificationTime);
io.mapRequired("path", dep.path);
io.mapRequired("size", dep.size);
io.mapOptional("sdk_relative", dep.isSDKRelative, /*default*/false);
}
};
template <>
struct SequenceElementTraits<ForwardingModule::Dependency> {
static const bool flow = false;
};
template <>
struct MappingTraits<ForwardingModule> {
static void mapping(IO &io, ForwardingModule &module) {
io.mapRequired("path", module.underlyingModulePath);
io.mapRequired("dependencies", module.dependencies);
io.mapRequired("version", module.version);
}
};
}
} // end namespace llvm
llvm::ErrorOr<ForwardingModule>
ForwardingModule::load(const llvm::MemoryBuffer &buf) {
llvm::yaml::Input yamlIn(buf.getBuffer());
ForwardingModule fwd;
yamlIn >> fwd;
if (yamlIn.error())
return yamlIn.error();
// We only currently support Version 1 of the forwarding module format.
if (fwd.version != 1)
return std::make_error_code(std::errc::not_supported);
return std::move(fwd);
}
#pragma mark - Module Discovery
namespace {
/// The result of a search for a module either alongside an interface, in the
/// module cache, or in the prebuilt module cache.
class DiscoveredModule {
/// The kind of module we've found.
enum class Kind {
/// A module that's either alongside the swiftinterface or in the
/// module cache.
Normal,
/// A module that resides in the prebuilt cache, and has hash-based
/// dependencies.
Prebuilt,
/// A 'forwarded' module. This is a module in the prebuilt cache, but whose
/// dependencies live in a forwarding module.
/// \sa ForwardingModule.
Forwarded
};
/// The kind of module that's been discovered.
const Kind kind;
DiscoveredModule(StringRef path, Kind kind,
std::unique_ptr<llvm::MemoryBuffer> moduleBuffer)
: kind(kind), moduleBuffer(std::move(moduleBuffer)), path(path) {}
public:
/// The contents of the .swiftmodule, if we've read it while validating
/// dependencies.
std::unique_ptr<llvm::MemoryBuffer> moduleBuffer;
/// The path to the discovered serialized .swiftmodule on disk.
const std::string path;
/// Creates a \c Normal discovered module.
static DiscoveredModule normal(StringRef path,
std::unique_ptr<llvm::MemoryBuffer> moduleBuffer) {
return { path, Kind::Normal, std::move(moduleBuffer) };
}
/// Creates a \c Prebuilt discovered module.
static DiscoveredModule prebuilt(
StringRef path, std::unique_ptr<llvm::MemoryBuffer> moduleBuffer) {
return { path, Kind::Prebuilt, std::move(moduleBuffer) };
}
/// Creates a \c Forwarded discovered module, whose dependencies have been
/// externally validated by a \c ForwardingModule.
static DiscoveredModule forwarded(
StringRef path, std::unique_ptr<llvm::MemoryBuffer> moduleBuffer) {
return { path, Kind::Forwarded, std::move(moduleBuffer) };
}
bool isNormal() const { return kind == Kind::Normal; }
bool isPrebuilt() const { return kind == Kind::Prebuilt; }
bool isForwarded() const { return kind == Kind::Forwarded; }
};
} // end anonymous namespace
#pragma mark - Common utilities
namespace path = llvm::sys::path;
static bool serializedASTLooksValid(const llvm::MemoryBuffer &buf,
bool requiresOSSAModules,
StringRef requiredSDK) {
auto VI = serialization::validateSerializedAST(buf.getBuffer(),
requiresOSSAModules,
requiredSDK);
return VI.status == serialization::Status::Valid;
}
#pragma mark - Module Loading
namespace {
/// Keeps track of the various reasons the module interface loader needed to
/// fall back and rebuild a module from its interface.
struct ModuleRebuildInfo {
enum class ModuleKind {
Normal,
Cached,
Forwarding,
Prebuilt
};
enum class ReasonIgnored {
NotIgnored,
PublicFramework,
InterfacePreferred,
CompilerHostModule,
Blocklisted,
DistributedInterfaceByDefault,
};
// Keep aligned with diag::module_interface_ignored_reason.
enum class ReasonModuleInterfaceIgnored {
NotIgnored,
LocalModule,
Blocklisted,
Debugger,
};
struct CandidateModule {
std::string path;
std::optional<serialization::Status> serializationStatus;
ModuleKind kind;
ReasonIgnored reasonIgnored;
ReasonModuleInterfaceIgnored reasonModuleInterfaceIgnored;
SmallVector<std::string, 10> outOfDateDependencies;
SmallVector<std::string, 10> missingDependencies;
};
SmallVector<CandidateModule, 3> candidateModules;
CandidateModule &getOrInsertCandidateModule(StringRef path) {
for (auto &mod : candidateModules) {
if (mod.path == path) return mod;
}
candidateModules.push_back({path.str(),
std::nullopt,
ModuleKind::Normal,
ReasonIgnored::NotIgnored,
ReasonModuleInterfaceIgnored::NotIgnored,
{},
{}});
return candidateModules.back();
}
/// Sets the kind of a module that failed to load.
void setModuleKind(StringRef path, ModuleKind kind) {
getOrInsertCandidateModule(path).kind = kind;
}
/// Sets the serialization status of the module at \c path. If this is
/// anything other than \c Valid, a note will be added stating why the module
/// was invalid.
void setSerializationStatus(StringRef path, serialization::Status status) {
getOrInsertCandidateModule(path).serializationStatus = status;
}
/// Registers an out-of-date dependency at \c depPath for the module
/// at \c modulePath.
void addOutOfDateDependency(StringRef modulePath, StringRef depPath) {
getOrInsertCandidateModule(modulePath)
.outOfDateDependencies.push_back(depPath.str());
}
/// Registers a missing dependency at \c depPath for the module
/// at \c modulePath.
void addMissingDependency(StringRef modulePath, StringRef depPath) {
getOrInsertCandidateModule(modulePath)
.missingDependencies.push_back(depPath.str());
}
/// Sets the reason that the module at \c modulePath was ignored. If this is
/// anything besides \c NotIgnored a note will be added stating why the module
/// was ignored.
void addIgnoredModule(StringRef modulePath, ReasonIgnored reasonIgnored) {
getOrInsertCandidateModule(modulePath).reasonIgnored = reasonIgnored;
}
/// Record why no swiftinterfaces were preferred over the binary swiftmodule
/// at \c modulePath.
void addIgnoredModuleInterface(StringRef modulePath,
ReasonModuleInterfaceIgnored reasonIgnored) {
getOrInsertCandidateModule(modulePath).reasonModuleInterfaceIgnored =
reasonIgnored;
}
/// Determines if we saw the given module path and registered is as out of
/// date.
bool sawOutOfDateModule(StringRef modulePath) {
for (auto &mod : candidateModules)
if (mod.path == modulePath &&
mod.reasonIgnored == ReasonIgnored::NotIgnored)
return true;
return false;
}
const char *invalidModuleReason(serialization::Status status) {
using namespace serialization;
switch (status) {
case Status::FormatTooOld:
return "compiled with an older version of the compiler";
case Status::FormatTooNew:
return "compiled with a newer version of the compiler";
case Status::RevisionIncompatible:
return "compiled with a different version of the compiler";
case Status::ChannelIncompatible:
return "compiled for a different distribution channel";
case Status::NotInOSSA:
return "module was not built with OSSA";
case Status::MissingDependency:
return "missing dependency";
case Status::MissingUnderlyingModule:
return "missing underlying module";
case Status::CircularDependency:
return "circular dependency";
case Status::FailedToLoadBridgingHeader:
return "failed to load bridging header";
case Status::Malformed:
return "malformed";
case Status::MalformedDocumentation:
return "malformed documentation";
case Status::NameMismatch:
return "name mismatch";
case Status::TargetIncompatible:
return "compiled for a different target platform";
case Status::TargetTooNew:
return "target platform newer than current platform";
case Status::SDKMismatch:
return "SDK does not match";
case Status::Valid:
return nullptr;
}
llvm_unreachable("bad status");
}
/// Emits a diagnostic for all out-of-date compiled or forwarding modules
/// encountered while trying to load a module.
template<typename... DiagArgs>
void diagnose(ASTContext &ctx, DiagnosticEngine &diags,
StringRef prebuiltCacheDir, SourceLoc loc,
DiagArgs &&...diagArgs) {
diags.diagnose(loc, std::forward<DiagArgs>(diagArgs)...);
auto SDKVer = getSDKBuildVersion(ctx.SearchPathOpts.getSDKPath());
llvm::SmallString<64> buffer = prebuiltCacheDir;
llvm::sys::path::append(buffer, "SystemVersion.plist");
auto PBMVer = getSDKBuildVersionFromPlist(buffer.str());
if (!SDKVer.empty() && !PBMVer.empty()) {
// Remark the potential version difference.
diags.diagnose(loc, diag::sdk_version_pbm_version, SDKVer,
PBMVer);
}
// We may have found multiple failing modules, that failed for different
// reasons. Emit a note for each of them.
for (auto &mod : candidateModules) {
// If the compiled module was ignored, diagnose the reason.
if (mod.reasonIgnored != ReasonIgnored::NotIgnored) {
diags.diagnose(loc, diag::compiled_module_ignored_reason, mod.path,
(unsigned)mod.reasonIgnored);
} else {
diags.diagnose(loc, diag::out_of_date_module_here, (unsigned)mod.kind,
mod.path);
}
// Diagnose any out-of-date dependencies in this module.
for (auto &dep : mod.outOfDateDependencies) {
diags.diagnose(loc, diag::module_interface_dependency_out_of_date,
dep);
}
// Diagnose any missing dependencies in this module.
for (auto &dep : mod.missingDependencies) {
diags.diagnose(loc, diag::module_interface_dependency_missing, dep);
}
// If there was a compiled module that wasn't able to be read, diagnose
// the reason we couldn't read it.
if (auto status = mod.serializationStatus) {
if (auto reason = invalidModuleReason(*status)) {
diags.diagnose(loc, diag::compiled_module_invalid_reason,
mod.path, reason);
} else {
diags.diagnose(loc, diag::compiled_module_invalid, mod.path);
}
}
}
}
/// Emits a diagnostic for the reason why binary swiftmodules were preferred
/// over textual swiftinterfaces.
void diagnoseIgnoredModuleInterfaces(ASTContext &ctx, SourceLoc loc) {
for (auto &mod : candidateModules) {
auto interfaceIgnore = mod.reasonModuleInterfaceIgnored;
if (interfaceIgnore == ReasonModuleInterfaceIgnored::NotIgnored)
continue;
ctx.Diags.diagnose(loc, diag::module_interface_ignored_reason,
mod.path, (unsigned)interfaceIgnore);
}
}
};
/// Constructs the full path of the dependency \p dep by prepending the SDK
/// path if necessary.
StringRef getFullDependencyPath(const FileDependency &dep,
const ASTContext &ctx,
SmallVectorImpl<char> &scratch) {
if (!dep.isSDKRelative())
return dep.getPath();
path::native(ctx.SearchPathOpts.getSDKPath(), scratch);
llvm::sys::path::append(scratch, dep.getPath());
return StringRef(scratch.data(), scratch.size());
}
class UpToDateModuleCheker {
ASTContext &ctx;
llvm::vfs::FileSystem &fs;
RequireOSSAModules_t requiresOSSAModules;
public:
UpToDateModuleCheker(ASTContext &ctx,
RequireOSSAModules_t requiresOSSAModules)
: ctx(ctx),
fs(*ctx.SourceMgr.getFileSystem()),
requiresOSSAModules(requiresOSSAModules) {}
// Check if all the provided file dependencies are up-to-date compared to
// what's currently on disk.
bool dependenciesAreUpToDate(StringRef modulePath,
ModuleRebuildInfo &rebuildInfo,
ArrayRef<FileDependency> deps,
bool skipSystemDependencies) {
SmallString<128> SDKRelativeBuffer;
for (auto &in : deps) {
if (skipSystemDependencies && in.isSDKRelative() &&
in.isModificationTimeBased()) {
continue;
}
StringRef fullPath = getFullDependencyPath(in, ctx, SDKRelativeBuffer);
switch (checkDependency(modulePath, in, fullPath)) {
case DependencyStatus::UpToDate:
LLVM_DEBUG(llvm::dbgs() << "Dep " << fullPath << " is up to date\n");
break;
case DependencyStatus::OutOfDate:
LLVM_DEBUG(llvm::dbgs() << "Dep " << fullPath << " is out of date\n");
rebuildInfo.addOutOfDateDependency(modulePath, fullPath);
return false;
case DependencyStatus::Missing:
LLVM_DEBUG(llvm::dbgs() << "Dep " << fullPath << " is missing\n");
rebuildInfo.addMissingDependency(modulePath, fullPath);
return false;
}
}
return true;
}
// Check that the output .swiftmodule file is at least as new as all the
// dependencies it read when it was built last time.
bool serializedASTBufferIsUpToDate(
StringRef path, const llvm::MemoryBuffer &buf,
ModuleRebuildInfo &rebuildInfo,
SmallVectorImpl<FileDependency> &allDeps) {
// Clear the existing dependencies, because we're going to re-fill them
// in validateSerializedAST.
allDeps.clear();
LLVM_DEBUG(llvm::dbgs() << "Validating deps of " << path << "\n");
auto validationInfo = serialization::validateSerializedAST(
buf.getBuffer(), requiresOSSAModules,
ctx.LangOpts.SDKName, /*ExtendedValidationInfo=*/nullptr, &allDeps);
if (validationInfo.status != serialization::Status::Valid) {
rebuildInfo.setSerializationStatus(path, validationInfo.status);
return false;
}
bool skipCheckingSystemDependencies =
ctx.SearchPathOpts.DisableModulesValidateSystemDependencies;
return dependenciesAreUpToDate(path, rebuildInfo, allDeps,
skipCheckingSystemDependencies);
}
// Check that the output .swiftmodule file is at least as new as all the
// dependencies it read when it was built last time.
bool swiftModuleIsUpToDate(
StringRef modulePath, ModuleRebuildInfo &rebuildInfo,
SmallVectorImpl<FileDependency> &AllDeps,
std::unique_ptr<llvm::MemoryBuffer> &moduleBuffer) {
auto OutBuf = fs.getBufferForFile(modulePath);
if (!OutBuf)
return false;
moduleBuffer = std::move(*OutBuf);
return serializedASTBufferIsUpToDate(modulePath, *moduleBuffer, rebuildInfo, AllDeps);
}
enum class DependencyStatus {
UpToDate,
OutOfDate,
Missing
};
// Checks that a dependency read from the cached module is up to date compared
// to the interface file it represents.
DependencyStatus checkDependency(StringRef modulePath,
const FileDependency &dep,
StringRef fullPath) {
auto status = fs.status(fullPath);
if (!status)
return DependencyStatus::Missing;
// If the sizes differ, then we know the file has changed.
if (status->getSize() != dep.getSize())
return DependencyStatus::OutOfDate;
// Otherwise, if this dependency is verified by modification time, check
// it vs. the modification time of the file.
if (dep.isModificationTimeBased()) {
uint64_t mtime =
status->getLastModificationTime().time_since_epoch().count();
return mtime == dep.getModificationTime() ?
DependencyStatus::UpToDate :
DependencyStatus::OutOfDate;
}
// Slow path: if the dependency is verified by content hash, check it vs.
// the hash of the file.
auto buf = fs.getBufferForFile(fullPath, /*FileSize=*/-1,
/*RequiresNullTerminator=*/false);
if (!buf)
return DependencyStatus::Missing;
return xxHash64(buf.get()->getBuffer()) == dep.getContentHash() ?
DependencyStatus::UpToDate :
DependencyStatus::OutOfDate;
}
};
/// Handles the details of loading module interfaces as modules, and will
/// do the necessary lookup to determine if we should be loading from the
/// normal cache, the prebuilt cache, a module adjacent to the interface, or
/// a module that we'll build from a module interface.
class ModuleInterfaceLoaderImpl {
friend class swift::ModuleInterfaceLoader;
friend class swift::ModuleInterfaceCheckerImpl;
ASTContext &ctx;
llvm::vfs::FileSystem &fs;
DiagnosticEngine &diags;
ModuleRebuildInfo rebuildInfo;
UpToDateModuleCheker upToDateChecker;
const StringRef modulePath;
const std::string interfacePath;
const StringRef moduleName;
const StringRef prebuiltCacheDir;
const StringRef backupInterfaceDir;
const StringRef cacheDir;
const SourceLoc diagnosticLoc;
DependencyTracker *const dependencyTracker;
const ModuleLoadingMode loadMode;
ModuleInterfaceLoaderOptions Opts;
RequireOSSAModules_t requiresOSSAModules;
ModuleInterfaceLoaderImpl(
ASTContext &ctx, StringRef modulePath, StringRef interfacePath,
StringRef moduleName, StringRef cacheDir, StringRef prebuiltCacheDir,
StringRef backupInterfaceDir,
SourceLoc diagLoc, ModuleInterfaceLoaderOptions Opts,
RequireOSSAModules_t requiresOSSAModules,
DependencyTracker *dependencyTracker = nullptr,
ModuleLoadingMode loadMode = ModuleLoadingMode::PreferSerialized)
: ctx(ctx), fs(*ctx.SourceMgr.getFileSystem()), diags(ctx.Diags),
upToDateChecker(ctx, requiresOSSAModules),
modulePath(modulePath), interfacePath(interfacePath),
moduleName(moduleName),
prebuiltCacheDir(prebuiltCacheDir),
backupInterfaceDir(backupInterfaceDir),
cacheDir(cacheDir), diagnosticLoc(diagLoc),
dependencyTracker(dependencyTracker), loadMode(loadMode), Opts(Opts),
requiresOSSAModules(requiresOSSAModules) {}
std::string getBackupPublicModuleInterfacePath() {
return getBackupPublicModuleInterfacePath(ctx.SourceMgr, backupInterfaceDir,
moduleName, interfacePath);
}
static std::string getBackupPublicModuleInterfacePath(SourceManager &SM,
StringRef backupInterfaceDir,
StringRef moduleName,
StringRef interfacePath) {
if (backupInterfaceDir.empty())
return std::string();
auto &fs = *SM.getFileSystem();
auto fileName = llvm::sys::path::filename(interfacePath);
{
llvm::SmallString<256> path(backupInterfaceDir);
llvm::sys::path::append(path, llvm::Twine(moduleName) + ".swiftmodule");
llvm::sys::path::append(path, fileName);
if (fs.exists(path.str())) {
return path.str().str();
}
}
{
llvm::SmallString<256> path(backupInterfaceDir);
llvm::sys::path::append(path, fileName);
if (fs.exists(path.str())) {
return path.str().str();
}
}
return std::string();
}
// Check that a "forwarding" .swiftmodule file is at least as new as all the
// dependencies it read when it was built last time. Requires that the
// forwarding module has been loaded from disk.
bool forwardingModuleIsUpToDate(
StringRef path, const ForwardingModule &fwd,
SmallVectorImpl<FileDependency> &deps,
std::unique_ptr<llvm::MemoryBuffer> &moduleBuffer) {
// Clear the existing dependencies, because we're going to re-fill them
// from the forwarding module.
deps.clear();
LLVM_DEBUG(llvm::dbgs() << "Validating deps of " << path << "\n");
// First, make sure the underlying module path exists and is valid.
auto modBuf = fs.getBufferForFile(fwd.underlyingModulePath);
if (!modBuf)
return false;
auto looksValid = serializedASTLooksValid(*modBuf.get(),
requiresOSSAModules,
ctx.LangOpts.SDKName);
if (!looksValid)
return false;
// Next, check the dependencies in the forwarding file.
for (auto &dep : fwd.dependencies) {
deps.push_back(
FileDependency::modTimeBased(
dep.path, dep.isSDKRelative, dep.size, dep.lastModificationTime));
}
bool skipCheckingSystemDependencies =
ctx.SearchPathOpts.DisableModulesValidateSystemDependencies;
if (!upToDateChecker.dependenciesAreUpToDate(path, rebuildInfo, deps,
skipCheckingSystemDependencies))
return false;
moduleBuffer = std::move(*modBuf);
return true;
}
bool canInterfaceHavePrebuiltModule() {
StringRef sdkPath = ctx.SearchPathOpts.getSDKPath();
if (!sdkPath.empty() &&
hasPrefix(path::begin(interfacePath), path::end(interfacePath),
path::begin(sdkPath), path::end(sdkPath))) {
return !(StringRef(interfacePath).ends_with(".private.swiftinterface") ||
StringRef(interfacePath).ends_with(".package.swiftinterface"));
}
return false;
}
std::optional<StringRef>
computePrebuiltModulePath(llvm::SmallString<256> &scratch) {
namespace path = llvm::sys::path;
// Check if this is a public interface file from the SDK.
if (!canInterfaceHavePrebuiltModule())
return std::nullopt;
// Assemble the expected path: $PREBUILT_CACHE/Foo.swiftmodule or
// $PREBUILT_CACHE/Foo.swiftmodule/arch.swiftmodule. Note that there's no
// cache key here.
scratch = prebuiltCacheDir;
// FIXME: Would it be possible to only have architecture-specific names
// here? Then we could skip this check.
StringRef inParentDirName =
path::filename(path::parent_path(interfacePath));
if (path::extension(inParentDirName) == ".swiftmodule") {
assert(path::stem(inParentDirName) ==
ctx.getRealModuleName(ctx.getIdentifier(moduleName)).str());
path::append(scratch, inParentDirName);
}
path::append(scratch, path::filename(modulePath));
// If there isn't a file at this location, skip returning a path.
if (!fs.exists(scratch))
return std::nullopt;
return scratch.str();
}
/// Hack to deal with build systems (including the Swift standard library, at
/// the time of this comment) that aren't yet using target-specific names for
/// multi-target swiftmodules, in case the prebuilt cache is.
std::optional<StringRef>
computeFallbackPrebuiltModulePath(llvm::SmallString<256> &scratch) {
namespace path = llvm::sys::path;
StringRef sdkPath = ctx.SearchPathOpts.getSDKPath();
// Check if this is a public interface file from the SDK.
if (sdkPath.empty() ||
!hasPrefix(path::begin(interfacePath), path::end(interfacePath),
path::begin(sdkPath), path::end(sdkPath)) ||
StringRef(interfacePath).ends_with(".private.swiftinterface") ||
StringRef(interfacePath).ends_with(".package.swiftinterface"))
return std::nullopt;
// If the module isn't target-specific, there's no fallback path.
StringRef inParentDirName =
path::filename(path::parent_path(interfacePath));
if (path::extension(inParentDirName) != ".swiftmodule")
return std::nullopt;
// If the interface is already using the target-specific name, there's
// nothing else to try.
auto normalizedTarget = getTargetSpecificModuleTriple(ctx.LangOpts.Target);
if (path::stem(modulePath) == normalizedTarget.str())
return std::nullopt;
// Assemble the expected path:
// $PREBUILT_CACHE/Foo.swiftmodule/target.swiftmodule. Note that there's no
// cache key here.
scratch = prebuiltCacheDir;
path::append(scratch, inParentDirName);
path::append(scratch, normalizedTarget.str());
scratch += ".swiftmodule";
// If there isn't a file at this location, skip returning a path.
if (!fs.exists(scratch))
return std::nullopt;
return scratch.str();
}
bool isInResourceDir(StringRef path) {
StringRef resourceDir = ctx.SearchPathOpts.RuntimeResourcePath;
if (resourceDir.empty()) return false;
return pathStartsWith(resourceDir, path);
}
bool isInResourceHostDir(StringRef path) {
StringRef resourceDir = ctx.SearchPathOpts.RuntimeResourcePath;
if (resourceDir.empty()) return false;
SmallString<128> hostPath;
llvm::sys::path::append(hostPath,
resourceDir, "host");
return pathStartsWith(hostPath, path);
}
bool isInSDK(StringRef path) {
StringRef sdkPath = ctx.SearchPathOpts.getSDKPath();
if (sdkPath.empty()) return false;
return pathStartsWith(sdkPath, path);
}
bool isInSystemFrameworks(StringRef path, bool publicFramework) {
StringRef sdkPath = ctx.SearchPathOpts.getSDKPath();
if (sdkPath.empty()) return false;
SmallString<128> frameworksPath;
llvm::sys::path::append(frameworksPath,
sdkPath, "System", "Library",
publicFramework ? "Frameworks" : "PrivateFrameworks");
return pathStartsWith(frameworksPath, path);
}
std::pair<std::string, std::string> getCompiledModuleCandidates() {
using ReasonIgnored = ModuleRebuildInfo::ReasonIgnored;
using ReasonModuleInterfaceIgnored =
ModuleRebuildInfo::ReasonModuleInterfaceIgnored;
std::pair<std::string, std::string> result;
bool ignoreByDefault = ctx.blockListConfig.hasBlockListAction(
"Swift_UseSwiftinterfaceByDefault",
BlockListKeyKind::ModuleName,
BlockListAction::ShouldUseBinaryModule);
bool shouldLoadAdjacentModule;
if (ignoreByDefault) {
ReasonModuleInterfaceIgnored ignore =
ReasonModuleInterfaceIgnored::NotIgnored;
if (!isInSDK(modulePath) &&
!isInResourceHostDir(modulePath)) {
ignore = ReasonModuleInterfaceIgnored::LocalModule;
} else if (ctx.blockListConfig.hasBlockListAction(moduleName,
BlockListKeyKind::ModuleName,
BlockListAction::ShouldUseBinaryModule)) {
ignore = ReasonModuleInterfaceIgnored::Blocklisted;
} else if (ctx.LangOpts.DebuggerSupport) {
ignore = ReasonModuleInterfaceIgnored::Debugger;
}
shouldLoadAdjacentModule =
ignore != ReasonModuleInterfaceIgnored::NotIgnored;
if (shouldLoadAdjacentModule) {
// Prefer the swiftmodule.
rebuildInfo.addIgnoredModuleInterface(modulePath, ignore);
} else {
// Prefer the swiftinterface.
rebuildInfo.addIgnoredModule(modulePath,
ReasonIgnored::DistributedInterfaceByDefault);
}
} else {
// Should we attempt to load a swiftmodule adjacent to the swiftinterface?
shouldLoadAdjacentModule = !ctx.IgnoreAdjacentModules;
if (modulePath.contains(".sdk")) {
if (ctx.blockListConfig.hasBlockListAction(moduleName,
BlockListKeyKind::ModuleName,
BlockListAction::ShouldUseTextualModule)) {
shouldLoadAdjacentModule = false;
rebuildInfo.addIgnoredModule(modulePath, ReasonIgnored::Blocklisted);
}
}
// Don't use the adjacent swiftmodule for frameworks from the public
// Frameworks folder of the SDK.
if (isInSystemFrameworks(modulePath, /*publicFramework*/true)) {
shouldLoadAdjacentModule = false;
rebuildInfo.addIgnoredModule(modulePath,
ReasonIgnored::PublicFramework);
} else if (isInResourceHostDir(modulePath)) {
shouldLoadAdjacentModule = false;
rebuildInfo.addIgnoredModule(modulePath,
ReasonIgnored::CompilerHostModule);
}
}
switch (loadMode) {
case ModuleLoadingMode::OnlyInterface:
// Always skip both the caches and adjacent modules, and always build the
// module interface.
return {};
case ModuleLoadingMode::PreferInterface:
// If we're in the load mode that prefers .swiftinterfaces, specifically
// skip the module adjacent to the interface, but use the caches if
// they're present.
shouldLoadAdjacentModule = false;
rebuildInfo.addIgnoredModule(modulePath,
ReasonIgnored::InterfacePreferred);
break;
case ModuleLoadingMode::PreferSerialized:
// The rest of the function should be covered by this.
break;
case ModuleLoadingMode::OnlySerialized:
llvm_unreachable("module interface loader should not have been created");
}
// [NOTE: ModuleInterfaceLoader-defer-to-ImplicitSerializedModuleLoader]
// If there's a module adjacent to the .swiftinterface that we can
// _likely_ load (it validates OK and is up to date), bail early with
// errc::not_supported, so the next (serialized) loader in the chain will
// load it.
// Alternately, if there's a .swiftmodule present but we can't even
// read it (for whatever reason), we should let the other module loader
// diagnose it.
if (shouldLoadAdjacentModule) {
if (fs.exists(modulePath)) {
result.first = modulePath.str();
}
}
// If we have a prebuilt cache path, check that too if the interface comes
// from the SDK.
if (!prebuiltCacheDir.empty()) {
llvm::SmallString<256> scratch;
std::unique_ptr<llvm::MemoryBuffer> moduleBuffer;
std::optional<StringRef> path = computePrebuiltModulePath(scratch);
if (!path) {
// Hack: deal with prebuilds of modules that still use the target-based
// names.
path = computeFallbackPrebuiltModulePath(scratch);
}
if (path) {
if (fs.exists(*path)) {
result.second = path->str();
}
}
}
return result;
}
llvm::ErrorOr<DiscoveredModule>
discoverUpToDateCompiledModuleForInterface(SmallVectorImpl<FileDependency> &deps,
std::string &UsableModulePath) {
std::string adjacentMod, prebuiltMod;
std::tie(adjacentMod, prebuiltMod) = getCompiledModuleCandidates();
if (!adjacentMod.empty()) {
auto adjacentModuleBuffer = fs.getBufferForFile(adjacentMod);
if (adjacentModuleBuffer) {
if (upToDateChecker.serializedASTBufferIsUpToDate(adjacentMod, *adjacentModuleBuffer.get(),
rebuildInfo, deps)) {
LLVM_DEBUG(llvm::dbgs() << "Found up-to-date module at "
<< adjacentMod
<< "; deferring to serialized module loader\n");
UsableModulePath = adjacentMod;
return std::make_error_code(std::errc::not_supported);
} else if (isInResourceDir(adjacentMod) &&
loadMode == ModuleLoadingMode::PreferSerialized &&
!version::isCurrentCompilerTagged() &&
rebuildInfo.getOrInsertCandidateModule(adjacentMod).serializationStatus !=
serialization::Status::SDKMismatch) {
// Special-case here: If we're loading a .swiftmodule from the resource
// dir adjacent to the compiler, defer to the serialized loader instead
// of falling back. This is to support local development of Swift,
// where one might change the module format version but forget to
// recompile the standard library. If that happens, don't fall back
// and silently recompile the standard library, raise an error
// instead.
//
// This logic is disabled for tagged compilers, so distributed
// compilers should ignore this restriction and rebuild all modules
// from a swiftinterface when required.
//
// Still accept modules built with a different SDK, allowing the use
// of one toolchain against a different SDK.
LLVM_DEBUG(llvm::dbgs() << "Found out-of-date module in the "
"resource-dir at "
<< adjacentMod
<< "; deferring to serialized module loader "
"to diagnose\n");
return std::make_error_code(std::errc::not_supported);
} else {
LLVM_DEBUG(llvm::dbgs() << "Found out-of-date module at "
<< adjacentMod << "\n");
rebuildInfo.setModuleKind(adjacentMod,
ModuleRebuildInfo::ModuleKind::Normal);
}
} else {
LLVM_DEBUG(llvm::dbgs() << "Found unreadable module at "
<< adjacentMod
<< "; deferring to serialized module loader\n");
return std::make_error_code(std::errc::not_supported);
}
}
if(!prebuiltMod.empty()) {
std::unique_ptr<llvm::MemoryBuffer> moduleBuffer;
if (upToDateChecker.swiftModuleIsUpToDate(prebuiltMod, rebuildInfo,
deps, moduleBuffer)) {
LLVM_DEBUG(llvm::dbgs() << "Found up-to-date prebuilt module at "
<< prebuiltMod << "\n");
UsableModulePath = prebuiltMod;
return DiscoveredModule::prebuilt(prebuiltMod, std::move(moduleBuffer));
} else {
LLVM_DEBUG(llvm::dbgs() << "Found out-of-date prebuilt module at "
<< prebuiltMod << "\n");
rebuildInfo.setModuleKind(prebuiltMod,
ModuleRebuildInfo::ModuleKind::Prebuilt);
}
}
// We cannot find any proper compiled module to use.
return std::make_error_code(std::errc::no_such_file_or_directory);
}
/// Finds the most appropriate .swiftmodule, whose dependencies are up to
/// date, that we can load for the provided .swiftinterface file.
llvm::ErrorOr<DiscoveredModule> discoverUpToDateModuleForInterface(
StringRef cachedOutputPath,
SmallVectorImpl<FileDependency> &deps) {
// First, check the cached module path. Whatever's in this cache represents
// the most up-to-date knowledge we have about the module.