-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ProcessFrameworkReferences.cs
1200 lines (996 loc) · 57.3 KB
/
ProcessFrameworkReferences.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Configurer;
using Microsoft.DotNet.Workloads.Workload;
using Microsoft.NET.Sdk.WorkloadManifestReader;
using Newtonsoft.Json;
using NuGet.Frameworks;
using NuGet.Versioning;
namespace Microsoft.NET.Build.Tasks
{
/// <summary>
/// This class processes the FrameworkReference items. It adds PackageReferences for the
/// targeting packs which provide the reference assemblies, and creates RuntimeFramework
/// items, which are written to the runtimeconfig file
/// </summary>
public class ProcessFrameworkReferences : TaskBase
{
public string TargetFrameworkIdentifier { get; set; }
public string TargetFrameworkVersion { get; set; }
public string TargetPlatformIdentifier { get; set; }
public string TargetPlatformVersion { get; set; }
public string TargetingPackRoot { get; set; }
[Required]
public string RuntimeGraphPath { get; set; }
public bool SelfContained { get; set; }
public bool ReadyToRunEnabled { get; set; }
public bool ReadyToRunUseCrossgen2 { get; set; }
public bool PublishAot { get; set; }
public bool RequiresILLinkPack { get; set; }
public bool IsAotCompatible { get; set; }
public bool SilenceIsAotCompatibleUnsupportedWarning { get; set; }
public string MinNonEolTargetFrameworkForAot { get; set; }
public bool EnableAotAnalyzer { get; set; }
public string FirstTargetFrameworkVersionToSupportAotAnalyzer { get; set; }
public bool PublishTrimmed { get; set; }
public bool IsTrimmable { get; set; }
public string FirstTargetFrameworkVersionToSupportTrimAnalyzer { get; set; }
public bool SilenceIsTrimmableUnsupportedWarning { get; set; }
public string MinNonEolTargetFrameworkForTrimming { get; set; }
public bool EnableTrimAnalyzer { get; set; }
public bool EnableSingleFileAnalyzer { get; set; }
public string FirstTargetFrameworkVersionToSupportSingleFileAnalyzer { get; set; }
public bool SilenceEnableSingleFileAnalyzerUnsupportedWarning { get; set; }
public string MinNonEolTargetFrameworkForSingleFile { get; set; }
public bool AotUseKnownRuntimePackForTarget { get; set; }
public string RuntimeIdentifier { get; set; }
public string[] RuntimeIdentifiers { get; set; }
public string RuntimeFrameworkVersion { get; set; }
public bool TargetLatestRuntimePatch { get; set; }
public bool TargetLatestRuntimePatchIsDefault { get; set; }
public bool EnableTargetingPackDownload { get; set; }
public bool EnableRuntimePackDownload { get; set; }
public bool EnableWindowsTargeting { get; set; }
public bool DisableTransitiveFrameworkReferenceDownloads { get; set; }
public ITaskItem[] FrameworkReferences { get; set; } = Array.Empty<ITaskItem>();
public ITaskItem[] KnownFrameworkReferences { get; set; } = Array.Empty<ITaskItem>();
public ITaskItem[] KnownRuntimePacks { get; set; } = Array.Empty<ITaskItem>();
public ITaskItem[] KnownCrossgen2Packs { get; set; } = Array.Empty<ITaskItem>();
public ITaskItem[] KnownILCompilerPacks { get; set; } = Array.Empty<ITaskItem>();
public ITaskItem[] KnownILLinkPacks { get; set; } = Array.Empty<ITaskItem>();
public ITaskItem[] KnownWebAssemblySdkPacks { get; set; } = Array.Empty<ITaskItem>();
public ITaskItem[] KnownAspNetCorePacks { get; set; } = Array.Empty<ITaskItem>();
public bool UsingMicrosoftNETSdkWebAssembly { get; set; }
public bool UsingMicrosoftNETSdkRazor { get; set; }
[Required]
public string NETCoreSdkRuntimeIdentifier { get; set; }
public string NETCoreSdkPortableRuntimeIdentifier { get; set; }
[Required]
public string NetCoreRoot { get; set; }
[Required]
public string NETCoreSdkVersion { get; set; }
[Output]
public ITaskItem[] PackagesToDownload { get; set; }
[Output]
public ITaskItem[] RuntimeFrameworks { get; set; }
[Output]
public ITaskItem[] TargetingPacks { get; set; }
[Output]
public ITaskItem[] RuntimePacks { get; set; }
[Output]
public ITaskItem[] Crossgen2Packs { get; set; }
[Output]
public ITaskItem[] HostILCompilerPacks { get; set; }
[Output]
public ITaskItem[] TargetILCompilerPacks { get; set; }
[Output]
public ITaskItem[] ImplicitPackageReferences { get; set; }
// Runtime packs which aren't available for the specified RuntimeIdentifier
[Output]
public ITaskItem[] UnavailableRuntimePacks { get; set; }
[Output]
public string[] KnownRuntimeIdentifierPlatforms { get; set; }
private Version _normalizedTargetFrameworkVersion;
void AddPacksForFrameworkReferences(
List<ITaskItem> packagesToDownload,
List<ITaskItem> runtimeFrameworks,
List<ITaskItem> targetingPacks,
List<ITaskItem> runtimePacks,
List<ITaskItem> unavailableRuntimePacks,
out List<KnownRuntimePack> knownRuntimePacksForTargetFramework
)
{
var knownFrameworkReferencesForTargetFramework =
KnownFrameworkReferences
.Select(item => new KnownFrameworkReference(item))
.Where(kfr => KnownFrameworkReferenceAppliesToTargetFramework(kfr.TargetFramework))
.ToList();
// Get known runtime packs from known framework references.
// Only use items where the framework reference name matches the RuntimeFrameworkName.
// This will filter out known framework references for "profiles", ie WindowsForms and WPF
knownRuntimePacksForTargetFramework =
knownFrameworkReferencesForTargetFramework
.Where(kfr => kfr.Name.Equals(kfr.RuntimeFrameworkName, StringComparison.OrdinalIgnoreCase))
.Select(kfr => kfr.ToKnownRuntimePack())
.ToList();
// Add additional known runtime packs
knownRuntimePacksForTargetFramework.AddRange(
KnownRuntimePacks.Select(item => new KnownRuntimePack(item))
.Where(krp => KnownFrameworkReferenceAppliesToTargetFramework(krp.TargetFramework)));
var frameworkReferenceMap = FrameworkReferences.ToDictionary(fr => fr.ItemSpec, StringComparer.OrdinalIgnoreCase);
HashSet<string> unrecognizedRuntimeIdentifiers = new(StringComparer.OrdinalIgnoreCase);
bool windowsOnlyErrorLogged = false;
foreach (var knownFrameworkReference in knownFrameworkReferencesForTargetFramework)
{
frameworkReferenceMap.TryGetValue(knownFrameworkReference.Name, out ITaskItem frameworkReference);
// Handle Windows-only frameworks on non-Windows platforms
if (knownFrameworkReference.IsWindowsOnly &&
!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&
!EnableWindowsTargeting)
{
// It is an error to reference the framework from non-Windows
if (!windowsOnlyErrorLogged && frameworkReference != null)
{
Log.LogError(Strings.WindowsDesktopFrameworkRequiresWindows);
windowsOnlyErrorLogged = true;
}
// Ignore (and don't download) this known framework reference as it requires Windows
continue;
}
KnownRuntimePack? selectedRuntimePack = SelectRuntimePack(frameworkReference, knownFrameworkReference, knownRuntimePacksForTargetFramework);
// Add targeting pack and all known runtime packs to "preferred packages" list.
// These are packages that will win in conflict resolution for assets that have identical assembly and file versions
var preferredPackages = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase);
preferredPackages.Add(knownFrameworkReference.TargetingPackName);
if (selectedRuntimePack != null)
{
var knownFrameworkReferenceRuntimePackRuntimeIdentifiers = selectedRuntimePack?.RuntimePackRuntimeIdentifiers.Split(';');
foreach (var runtimeIdentifier in knownFrameworkReferenceRuntimePackRuntimeIdentifiers)
{
foreach (var runtimePackNamePattern in selectedRuntimePack?.RuntimePackNamePatterns.Split(';'))
{
string runtimePackName = runtimePackNamePattern.Replace("**RID**", runtimeIdentifier);
preferredPackages.Add(runtimePackName);
}
}
}
TaskItem targetingPack = new(knownFrameworkReference.Name);
targetingPack.SetMetadata(MetadataKeys.NuGetPackageId, knownFrameworkReference.TargetingPackName);
targetingPack.SetMetadata(MetadataKeys.PackageConflictPreferredPackages, string.Join(";", preferredPackages));
string targetingPackVersion = null;
if (frameworkReference != null)
{
// Allow targeting pack version to be overridden via metadata on FrameworkReference
targetingPackVersion = frameworkReference.GetMetadata("TargetingPackVersion");
}
if (string.IsNullOrEmpty(targetingPackVersion))
{
targetingPackVersion = knownFrameworkReference.TargetingPackVersion;
}
// Look up targeting pack version from workload manifests if necessary
targetingPackVersion = GetResolvedPackVersion(knownFrameworkReference.TargetingPackName, targetingPackVersion);
targetingPack.SetMetadata(MetadataKeys.NuGetPackageVersion, targetingPackVersion);
targetingPack.SetMetadata("TargetingPackFormat", knownFrameworkReference.TargetingPackFormat);
targetingPack.SetMetadata("TargetFramework", knownFrameworkReference.TargetFramework.GetShortFolderName());
targetingPack.SetMetadata(MetadataKeys.RuntimeFrameworkName, knownFrameworkReference.RuntimeFrameworkName);
if (selectedRuntimePack != null)
{
targetingPack.SetMetadata(MetadataKeys.RuntimePackRuntimeIdentifiers, selectedRuntimePack?.RuntimePackRuntimeIdentifiers);
}
if (!string.IsNullOrEmpty(knownFrameworkReference.Profile))
{
targetingPack.SetMetadata("Profile", knownFrameworkReference.Profile);
}
// Get the path of the targeting pack in the targeting pack root (e.g. dotnet/packs)
string targetingPackPath = GetPackPath(knownFrameworkReference.TargetingPackName, targetingPackVersion);
if (targetingPackPath != null)
{
// Use targeting pack from packs folder
targetingPack.SetMetadata(MetadataKeys.PackageDirectory, targetingPackPath);
targetingPack.SetMetadata(MetadataKeys.Path, targetingPackPath);
}
else
{
// If transitive framework reference downloads are disabled, then don't download targeting packs where there isn't
// a direct framework reference
if (EnableTargetingPackDownload &&
!(DisableTransitiveFrameworkReferenceDownloads && frameworkReference == null))
{
// Download targeting pack
TaskItem packageToDownload = new(knownFrameworkReference.TargetingPackName);
packageToDownload.SetMetadata(MetadataKeys.Version, targetingPackVersion);
packagesToDownload.Add(packageToDownload);
}
}
targetingPacks.Add(targetingPack);
var runtimeFrameworkVersion = GetRuntimeFrameworkVersion(
frameworkReference,
knownFrameworkReference,
selectedRuntimePack,
out string runtimePackVersion);
string isTrimmable = null;
if (frameworkReference != null)
{
// Allow IsTrimmable to be overridden via metadata on FrameworkReference
isTrimmable = frameworkReference.GetMetadata(MetadataKeys.IsTrimmable);
}
if (string.IsNullOrEmpty(isTrimmable))
{
isTrimmable = selectedRuntimePack?.IsTrimmable;
}
bool useRuntimePackAndDownloadIfNecessary;
KnownRuntimePack runtimePackForRuntimeIDProcessing;
if (knownFrameworkReference.Name.Equals(knownFrameworkReference.RuntimeFrameworkName, StringComparison.OrdinalIgnoreCase))
{
// Only add runtime packs where the framework reference name matches the RuntimeFrameworkName
// Framework references for "profiles" will use the runtime pack from the corresponding non-profile framework
runtimePackForRuntimeIDProcessing = selectedRuntimePack.Value;
useRuntimePackAndDownloadIfNecessary = true;
}
else if (!knownFrameworkReference.RuntimePackRuntimeIdentifiers.Equals(selectedRuntimePack?.RuntimePackRuntimeIdentifiers))
{
// If the profile has a different set of runtime identifiers than the runtime pack, use the profile.
runtimePackForRuntimeIDProcessing = knownFrameworkReference.ToKnownRuntimePack();
useRuntimePackAndDownloadIfNecessary = true;
}
else
{
// For the remaining profiles, don't include them in package download but add them to unavailable if necessary.
runtimePackForRuntimeIDProcessing = knownFrameworkReference.ToKnownRuntimePack();
useRuntimePackAndDownloadIfNecessary = false;
}
bool processedPrimaryRuntimeIdentifier = false;
var hasRuntimePackAlwaysCopyLocal =
selectedRuntimePack != null && selectedRuntimePack.Value.RuntimePackAlwaysCopyLocal;
var runtimeRequiredByDeployment
= (SelfContained || ReadyToRunEnabled) &&
!string.IsNullOrEmpty(RuntimeIdentifier) &&
selectedRuntimePack != null &&
!string.IsNullOrEmpty(selectedRuntimePack.Value.RuntimePackNamePatterns);
if (hasRuntimePackAlwaysCopyLocal || runtimeRequiredByDeployment)
{
// Find other KnownFrameworkReferences that map to the same runtime pack, if any
List<string> additionalFrameworkReferencesForRuntimePack = null;
foreach (var additionalKnownFrameworkReference in knownFrameworkReferencesForTargetFramework)
{
if (additionalKnownFrameworkReference.RuntimeFrameworkName.Equals(knownFrameworkReference.RuntimeFrameworkName, StringComparison.OrdinalIgnoreCase) &&
!additionalKnownFrameworkReference.RuntimeFrameworkName.Equals(additionalKnownFrameworkReference.Name, StringComparison.OrdinalIgnoreCase))
{
if (additionalFrameworkReferencesForRuntimePack == null)
{
additionalFrameworkReferencesForRuntimePack = new List<string>();
}
additionalFrameworkReferencesForRuntimePack.Add(additionalKnownFrameworkReference.Name);
}
}
ProcessRuntimeIdentifier(string.IsNullOrEmpty(RuntimeIdentifier) ? "any" : RuntimeIdentifier, runtimePackForRuntimeIDProcessing, runtimePackVersion, additionalFrameworkReferencesForRuntimePack,
unrecognizedRuntimeIdentifiers, unavailableRuntimePacks, runtimePacks, packagesToDownload, isTrimmable, useRuntimePackAndDownloadIfNecessary,
wasReferencedDirectly: frameworkReference != null);
processedPrimaryRuntimeIdentifier = true;
}
if (RuntimeIdentifiers != null)
{
foreach (var runtimeIdentifier in RuntimeIdentifiers)
{
if (processedPrimaryRuntimeIdentifier && runtimeIdentifier == RuntimeIdentifier)
{
// We've already processed this RID
continue;
}
// Pass in null for the runtimePacks list, as for these runtime identifiers we only want to
// download the runtime packs, but not use the assets from them
ProcessRuntimeIdentifier(runtimeIdentifier, runtimePackForRuntimeIDProcessing, runtimePackVersion, additionalFrameworkReferencesForRuntimePack: null,
unrecognizedRuntimeIdentifiers, unavailableRuntimePacks, runtimePacks: null, packagesToDownload, isTrimmable, useRuntimePackAndDownloadIfNecessary,
wasReferencedDirectly: frameworkReference != null);
}
}
if (!string.IsNullOrEmpty(knownFrameworkReference.RuntimeFrameworkName) && !knownFrameworkReference.RuntimePackAlwaysCopyLocal)
{
TaskItem runtimeFramework = new(knownFrameworkReference.RuntimeFrameworkName);
runtimeFramework.SetMetadata(MetadataKeys.Version, runtimeFrameworkVersion);
runtimeFramework.SetMetadata(MetadataKeys.FrameworkName, knownFrameworkReference.Name);
runtimeFramework.SetMetadata("Profile", knownFrameworkReference.Profile);
runtimeFrameworks.Add(runtimeFramework);
}
}
}
protected override void ExecuteCore()
{
List<ITaskItem> packagesToDownload = null;
List<ITaskItem> runtimeFrameworks = null;
List<ITaskItem> targetingPacks = null;
List<ITaskItem> runtimePacks = null;
List<ITaskItem> unavailableRuntimePacks = null;
List<KnownRuntimePack> knownRuntimePacksForTargetFramework = null;
// Perf optimization: If there are no FrameworkReference items, then don't do anything
// (This means that if you don't have any direct framework references, you won't get any transitive ones either
if (FrameworkReferences != null && FrameworkReferences.Length != 0)
{
_normalizedTargetFrameworkVersion = NormalizeVersion(new Version(TargetFrameworkVersion));
packagesToDownload = new List<ITaskItem>();
runtimeFrameworks = new List<ITaskItem>();
targetingPacks = new List<ITaskItem>();
runtimePacks = new List<ITaskItem>();
unavailableRuntimePacks = new List<ITaskItem>();
AddPacksForFrameworkReferences(
packagesToDownload,
runtimeFrameworks,
targetingPacks,
runtimePacks,
unavailableRuntimePacks,
out knownRuntimePacksForTargetFramework);
}
_normalizedTargetFrameworkVersion ??= NormalizeVersion(new Version(TargetFrameworkVersion));
packagesToDownload ??= new List<ITaskItem>();
List<ITaskItem> implicitPackageReferences = new();
if (ReadyToRunEnabled && ReadyToRunUseCrossgen2)
{
if (AddToolPack(ToolPackType.Crossgen2, _normalizedTargetFrameworkVersion, packagesToDownload, implicitPackageReferences) is not ToolPackSupport.Supported)
{
Log.LogError(Strings.ReadyToRunNoValidRuntimePackageError);
return;
}
}
if (PublishAot)
{
switch (AddToolPack(ToolPackType.ILCompiler, _normalizedTargetFrameworkVersion, packagesToDownload, implicitPackageReferences))
{
case ToolPackSupport.UnsupportedForTargetFramework:
Log.LogError(Strings.AotUnsupportedTargetFramework);
return;
case ToolPackSupport.UnsupportedForHostRuntimeIdentifier:
Log.LogError(Strings.AotUnsupportedHostRuntimeIdentifier, NETCoreSdkRuntimeIdentifier);
return;
case ToolPackSupport.UnsupportedForTargetRuntimeIdentifier:
Log.LogError(Strings.AotUnsupportedTargetRuntimeIdentifier, RuntimeIdentifier);
return;
case ToolPackSupport.Supported:
break;
}
}
if (RequiresILLinkPack)
{
if (AddToolPack(ToolPackType.ILLink, _normalizedTargetFrameworkVersion, packagesToDownload, implicitPackageReferences) is not ToolPackSupport.Supported)
{
// Keep the checked properties in sync with _RequiresILLinkPack in Microsoft.NET.Publish.targets.
if (PublishAot)
{
// If PublishAot is set, this should produce a specific error above already.
// Also produce one here just in case there are custom KnownILCompilerPack/KnownILLinkPack
// items that bypass the error above.
Log.LogError(Strings.AotUnsupportedTargetFramework);
}
else if (IsAotCompatible || EnableAotAnalyzer)
{
if (!SilenceIsAotCompatibleUnsupportedWarning)
Log.LogWarning(Strings.IsAotCompatibleUnsupported, MinNonEolTargetFrameworkForAot);
}
else if (PublishTrimmed)
{
Log.LogError(Strings.PublishTrimmedRequiresVersion30);
}
else if (IsTrimmable || EnableTrimAnalyzer)
{
if (!SilenceIsTrimmableUnsupportedWarning)
Log.LogWarning(Strings.IsTrimmableUnsupported, MinNonEolTargetFrameworkForTrimming);
}
else if (EnableSingleFileAnalyzer)
{
// There's no IsSingleFileCompatible setting. EnableSingleFileAnalyzer is the
// recommended way to ensure single-file compatibility for libraries.
if (!SilenceEnableSingleFileAnalyzerUnsupportedWarning)
Log.LogWarning(Strings.EnableSingleFileAnalyzerUnsupported, MinNonEolTargetFrameworkForSingleFile);
}
else
{
// _RequiresILLinkPack was set. This setting acts as an override for the
// user-visible properties, and should generally only be used by
// other SDKs that can't use the other properties for some reason.
Log.LogError(Strings.ILLinkNoValidRuntimePackageError);
}
}
}
if (UsingMicrosoftNETSdkWebAssembly)
{
// WebAssemblySdk is used for .NET >= 6, it's ok if no pack is added.
AddToolPack(ToolPackType.WebAssemblySdk, _normalizedTargetFrameworkVersion, packagesToDownload, implicitPackageReferences);
}
if (UsingMicrosoftNETSdkRazor && _normalizedTargetFrameworkVersion.Major >= 10)
{
if (AddToolPack(ToolPackType.AspNetCore, _normalizedTargetFrameworkVersion, packagesToDownload, implicitPackageReferences) is not ToolPackSupport.Supported)
{
Log.LogWarning(Strings.AspNetCorePackUnsupportedTargetFramework);
}
}
if (packagesToDownload.Any())
{
PackagesToDownload = packagesToDownload.Distinct(new PackageToDownloadComparer<ITaskItem>()).ToArray();
}
if (runtimeFrameworks?.Any() == true)
{
RuntimeFrameworks = runtimeFrameworks.ToArray();
}
if (targetingPacks?.Any() == true)
{
TargetingPacks = targetingPacks.ToArray();
}
if (runtimePacks?.Any() == true)
{
RuntimePacks = runtimePacks.ToArray();
}
if (unavailableRuntimePacks?.Any() == true)
{
UnavailableRuntimePacks = unavailableRuntimePacks.ToArray();
}
if (implicitPackageReferences.Any())
{
ImplicitPackageReferences = implicitPackageReferences.ToArray();
}
if (knownRuntimePacksForTargetFramework?.Any() == true)
{
// Determine the known runtime identifier platforms based on all available Microsoft.NETCore.App packs
HashSet<string> knownRuntimeIdentifierPlatforms = new(StringComparer.OrdinalIgnoreCase);
var netCoreAppPacks = knownRuntimePacksForTargetFramework!.Where(krp => krp.Name.Equals("Microsoft.NETCore.App", StringComparison.OrdinalIgnoreCase));
foreach (KnownRuntimePack netCoreAppPack in netCoreAppPacks)
{
foreach (var runtimeIdentifier in netCoreAppPack.RuntimePackRuntimeIdentifiers.Split(';'))
{
int separator = runtimeIdentifier.LastIndexOf('-');
string platform = separator < 0 ? runtimeIdentifier : runtimeIdentifier.Substring(0, separator);
knownRuntimeIdentifierPlatforms.Add(platform);
}
}
if (knownRuntimeIdentifierPlatforms.Count > 0)
{
KnownRuntimeIdentifierPlatforms = knownRuntimeIdentifierPlatforms.ToArray();
}
}
}
private bool KnownFrameworkReferenceAppliesToTargetFramework(NuGetFramework knownFrameworkReferenceTargetFramework)
{
if (!knownFrameworkReferenceTargetFramework.Framework.Equals(TargetFrameworkIdentifier, StringComparison.OrdinalIgnoreCase)
|| NormalizeVersion(knownFrameworkReferenceTargetFramework.Version) != _normalizedTargetFrameworkVersion)
{
return false;
}
if (!string.IsNullOrEmpty(knownFrameworkReferenceTargetFramework.Platform)
&& knownFrameworkReferenceTargetFramework.PlatformVersion != null)
{
if (!knownFrameworkReferenceTargetFramework.Platform.Equals(TargetPlatformIdentifier, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (!Version.TryParse(TargetPlatformVersion, out var targetPlatformVersionParsed))
{
return false;
}
if (NormalizeVersion(targetPlatformVersionParsed) != NormalizeVersion(knownFrameworkReferenceTargetFramework.PlatformVersion)
|| NormalizeVersion(knownFrameworkReferenceTargetFramework.Version) != _normalizedTargetFrameworkVersion)
{
return false;
}
}
return true;
}
private KnownRuntimePack? SelectRuntimePack(ITaskItem frameworkReference, KnownFrameworkReference knownFrameworkReference, List<KnownRuntimePack> knownRuntimePacks)
{
var requiredLabelsMetadata = frameworkReference?.GetMetadata(MetadataKeys.RuntimePackLabels) ?? "";
HashSet<string> requiredRuntimePackLabels = null;
if (frameworkReference != null)
{
requiredRuntimePackLabels = new HashSet<string>(requiredLabelsMetadata.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries), StringComparer.OrdinalIgnoreCase);
}
// The runtime pack name matches the RuntimeFrameworkName on the KnownFrameworkReference
var matchingRuntimePacks = knownRuntimePacks.Where(krp => krp.Name.Equals(knownFrameworkReference.RuntimeFrameworkName, StringComparison.OrdinalIgnoreCase))
.Where(krp =>
{
if (requiredRuntimePackLabels == null)
{
return krp.RuntimePackLabels.Length == 0;
}
else
{
return requiredRuntimePackLabels.SetEquals(krp.RuntimePackLabels);
}
})
.ToList();
if (matchingRuntimePacks.Count == 0)
{
return null;
}
else if (matchingRuntimePacks.Count == 1)
{
return matchingRuntimePacks[0];
}
else
{
string runtimePackDescriptionForErrorMessage = knownFrameworkReference.RuntimeFrameworkName +
(requiredLabelsMetadata == string.Empty ? string.Empty : ":" + requiredLabelsMetadata);
Log.LogError(Strings.ConflictingRuntimePackInformation, runtimePackDescriptionForErrorMessage,
string.Join(Environment.NewLine, matchingRuntimePacks.Select(rp => rp.RuntimePackNamePatterns)));
return knownFrameworkReference.ToKnownRuntimePack();
}
}
private void ProcessRuntimeIdentifier(
string runtimeIdentifier,
KnownRuntimePack selectedRuntimePack,
string runtimePackVersion,
List<string> additionalFrameworkReferencesForRuntimePack,
HashSet<string> unrecognizedRuntimeIdentifiers,
List<ITaskItem> unavailableRuntimePacks,
List<ITaskItem> runtimePacks,
List<ITaskItem> packagesToDownload,
string isTrimmable,
bool addRuntimePackAndDownloadIfNecessary,
bool wasReferencedDirectly)
{
var runtimeGraph = new RuntimeGraphCache(this).GetRuntimeGraph(RuntimeGraphPath);
var knownFrameworkReferenceRuntimePackRuntimeIdentifiers = selectedRuntimePack.RuntimePackRuntimeIdentifiers.Split(';');
var knownFrameworkReferenceRuntimePackExcludedRuntimeIdentifiers = selectedRuntimePack.RuntimePackExcludedRuntimeIdentifiers.Split(';');
string runtimePackRuntimeIdentifier = NuGetUtils.GetBestMatchingRidWithExclusion(
runtimeGraph,
runtimeIdentifier,
knownFrameworkReferenceRuntimePackExcludedRuntimeIdentifiers,
knownFrameworkReferenceRuntimePackRuntimeIdentifiers,
out bool wasInGraph);
if (runtimePackRuntimeIdentifier == null)
{
if (wasInGraph)
{
// Report this as an error later, if necessary. This is because we try to download
// all available runtime packs in case there is a transitive reference to a shared
// framework we don't directly reference. But we don't want to immediately error out
// here if a runtime pack that we might not need to reference isn't available for the
// targeted RID (e.g. Microsoft.WindowsDesktop.App for a linux RID).
var unavailableRuntimePack = new TaskItem(selectedRuntimePack.Name);
unavailableRuntimePack.SetMetadata(MetadataKeys.RuntimeIdentifier, runtimeIdentifier);
unavailableRuntimePacks.Add(unavailableRuntimePack);
}
else if (!unrecognizedRuntimeIdentifiers.Contains(runtimeIdentifier))
{
// NETSDK1083: The specified RuntimeIdentifier '{0}' is not recognized.
Log.LogError(Strings.RuntimeIdentifierNotRecognized, runtimeIdentifier);
unrecognizedRuntimeIdentifiers.Add(runtimeIdentifier);
}
}
else if (addRuntimePackAndDownloadIfNecessary)
{
foreach (var runtimePackNamePattern in selectedRuntimePack.RuntimePackNamePatterns.Split(';'))
{
string runtimePackName = runtimePackNamePattern.Replace("**RID**", runtimePackRuntimeIdentifier);
// Look up runtimePackVersion from workload manifests if necessary
string resolvedRuntimePackVersion = GetResolvedPackVersion(runtimePackName, runtimePackVersion);
string runtimePackPath = GetPackPath(runtimePackName, resolvedRuntimePackVersion);
if (runtimePacks != null)
{
TaskItem runtimePackItem = new(runtimePackName);
runtimePackItem.SetMetadata(MetadataKeys.NuGetPackageId, runtimePackName);
runtimePackItem.SetMetadata(MetadataKeys.NuGetPackageVersion, resolvedRuntimePackVersion);
runtimePackItem.SetMetadata(MetadataKeys.FrameworkName, selectedRuntimePack.Name);
runtimePackItem.SetMetadata(MetadataKeys.RuntimeIdentifier, runtimePackRuntimeIdentifier);
runtimePackItem.SetMetadata(MetadataKeys.IsTrimmable, isTrimmable);
if (selectedRuntimePack.RuntimePackAlwaysCopyLocal)
{
runtimePackItem.SetMetadata(MetadataKeys.RuntimePackAlwaysCopyLocal, "true");
}
if (additionalFrameworkReferencesForRuntimePack != null)
{
runtimePackItem.SetMetadata(MetadataKeys.AdditionalFrameworkReferences, string.Join(";", additionalFrameworkReferencesForRuntimePack));
}
if (runtimePackPath != null)
{
runtimePackItem.SetMetadata(MetadataKeys.PackageDirectory, runtimePackPath);
}
runtimePacks.Add(runtimePackItem);
}
if (EnableRuntimePackDownload &&
runtimePackPath == null &&
(wasReferencedDirectly || !DisableTransitiveFrameworkReferenceDownloads))
{
TaskItem packageToDownload = new(runtimePackName);
packageToDownload.SetMetadata(MetadataKeys.Version, resolvedRuntimePackVersion);
packagesToDownload.Add(packageToDownload);
}
}
}
}
// Enum values should match the name of the pack: Known<Foo>Pack
private enum ToolPackType
{
Crossgen2,
ILCompiler,
ILLink,
WebAssemblySdk,
AspNetCore,
}
enum ToolPackSupport
{
UnsupportedForTargetFramework,
UnsupportedForHostRuntimeIdentifier,
UnsupportedForTargetRuntimeIdentifier,
Supported
}
private ToolPackSupport AddToolPack(
ToolPackType toolPackType,
Version normalizedTargetFrameworkVersion,
List<ITaskItem> packagesToDownload,
List<ITaskItem> implicitPackageReferences)
{
var knownPacks = toolPackType switch
{
ToolPackType.Crossgen2 => KnownCrossgen2Packs,
ToolPackType.ILCompiler => KnownILCompilerPacks,
ToolPackType.ILLink => KnownILLinkPacks,
ToolPackType.WebAssemblySdk => KnownWebAssemblySdkPacks,
ToolPackType.AspNetCore => KnownAspNetCorePacks,
_ => throw new ArgumentException($"Unknown package type {toolPackType}", nameof(toolPackType))
};
var knownPack = knownPacks.Where(pack =>
{
var packTargetFramework = NuGetFramework.Parse(pack.GetMetadata("TargetFramework"));
return packTargetFramework.Framework.Equals(TargetFrameworkIdentifier, StringComparison.OrdinalIgnoreCase) &&
NormalizeVersion(packTargetFramework.Version) == normalizedTargetFrameworkVersion;
}).SingleOrDefault();
if (knownPack == null)
{
return ToolPackSupport.UnsupportedForTargetFramework;
}
var packName = toolPackType.ToString();
var packVersion = knownPack.GetMetadata(packName + "PackVersion");
if (!string.IsNullOrEmpty(RuntimeFrameworkVersion))
{
packVersion = RuntimeFrameworkVersion;
}
TaskItem? runtimePackToDownload = null;
// Crossgen and ILCompiler have RID-specific bits.
if (toolPackType is ToolPackType.Crossgen2 or ToolPackType.ILCompiler)
{
var packNamePattern = knownPack.GetMetadata(packName + "PackNamePattern");
var packSupportedRuntimeIdentifiers = knownPack.GetMetadata(packName + "RuntimeIdentifiers").Split(';');
// When publishing for the non-portable RID that matches NETCoreSdkRuntimeIdentifier, prefer NETCoreSdkRuntimeIdentifier for the host.
// Otherwise prefer the NETCoreSdkPortableRuntimeIdentifier.
// This makes non-portable SDKs behave the same as portable SDKs except for the specific case of targetting the non-portable RID.
// It also enables the non-portable ILCompiler to be packaged separately from the SDK and
// only required when publishing for the non-portable SDK RID.
string portableSdkRid = !string.IsNullOrEmpty(NETCoreSdkPortableRuntimeIdentifier) ? NETCoreSdkPortableRuntimeIdentifier : NETCoreSdkRuntimeIdentifier;
bool targetsNonPortableSdkRid = RuntimeIdentifier == NETCoreSdkRuntimeIdentifier && NETCoreSdkRuntimeIdentifier != portableSdkRid;
string hostRuntimeIdentifier = targetsNonPortableSdkRid ? NETCoreSdkRuntimeIdentifier : portableSdkRid;
// Get the best RID for the host machine, which will be used to validate that we can run crossgen for the target platform and architecture
var runtimeGraph = new RuntimeGraphCache(this).GetRuntimeGraph(RuntimeGraphPath);
hostRuntimeIdentifier = NuGetUtils.GetBestMatchingRid(runtimeGraph, hostRuntimeIdentifier, packSupportedRuntimeIdentifiers, out bool wasInGraph);
if (hostRuntimeIdentifier == null)
{
return ToolPackSupport.UnsupportedForHostRuntimeIdentifier;
}
var runtimePackName = packNamePattern.Replace("**RID**", hostRuntimeIdentifier);
var runtimePackItem = new TaskItem(runtimePackName);
runtimePackItem.SetMetadata(MetadataKeys.NuGetPackageId, runtimePackName);
runtimePackItem.SetMetadata(MetadataKeys.NuGetPackageVersion, packVersion);
string runtimePackPath = GetPackPath(runtimePackName, packVersion);
if (runtimePackPath != null)
{
runtimePackItem.SetMetadata(MetadataKeys.PackageDirectory, runtimePackPath);
}
else if (EnableRuntimePackDownload)
{
// We need to download the runtime pack
runtimePackToDownload = new TaskItem(runtimePackName);
runtimePackToDownload.SetMetadata(MetadataKeys.Version, packVersion);
}
switch (toolPackType)
{
case ToolPackType.Crossgen2:
Crossgen2Packs = new[] { runtimePackItem };
break;
case ToolPackType.ILCompiler:
// ILCompiler supports cross target compilation. If there is a cross-target request,
// we need to download that package as well unless we use KnownRuntimePack entries for the target.
// We expect RuntimeIdentifier to be defined during publish but can allow during build
if (RuntimeIdentifier != null && !AotUseKnownRuntimePackForTarget)
{
var targetRuntimeIdentifier = NuGetUtils.GetBestMatchingRid(runtimeGraph, RuntimeIdentifier, packSupportedRuntimeIdentifiers, out bool wasInGraph2);
if (targetRuntimeIdentifier == null)
{
return ToolPackSupport.UnsupportedForTargetRuntimeIdentifier;
}
if (!hostRuntimeIdentifier.Equals(targetRuntimeIdentifier))
{
var targetIlcPackName = packNamePattern.Replace("**RID**", targetRuntimeIdentifier);
var targetIlcPack = new TaskItem(targetIlcPackName);
targetIlcPack.SetMetadata(MetadataKeys.NuGetPackageId, targetIlcPackName);
targetIlcPack.SetMetadata(MetadataKeys.NuGetPackageVersion, packVersion);
TargetILCompilerPacks = new[] { targetIlcPack };
}
}
HostILCompilerPacks = new[] { runtimePackItem };
break;
}
}
if (runtimePackToDownload != null)
{
packagesToDownload.Add(runtimePackToDownload);
}
if (toolPackType is ToolPackType.ILLink)
{
// The ILLink tool pack is available for some TargetFrameworks where we nonetheless consider
// IsTrimmable/IsAotCompatible/EnableSingleFile to be unsupported, because the framework
// was not annotated with the attributes.
var firstTargetFrameworkVersionToSupportAotAnalyzer = NormalizeVersion(new Version(FirstTargetFrameworkVersionToSupportAotAnalyzer));
if ((IsAotCompatible || EnableAotAnalyzer) && normalizedTargetFrameworkVersion < firstTargetFrameworkVersionToSupportAotAnalyzer)
return ToolPackSupport.UnsupportedForTargetFramework;
var firstTargetFrameworkVersionToSupportSingleFileAnalyzer = NormalizeVersion(new Version(FirstTargetFrameworkVersionToSupportSingleFileAnalyzer));
if (EnableSingleFileAnalyzer && normalizedTargetFrameworkVersion < firstTargetFrameworkVersionToSupportSingleFileAnalyzer)
return ToolPackSupport.UnsupportedForTargetFramework;
var firstTargetFrameworkVersionToSupportTrimAnalyzer = NormalizeVersion(new Version(FirstTargetFrameworkVersionToSupportTrimAnalyzer));
if ((IsTrimmable || EnableTrimAnalyzer) && normalizedTargetFrameworkVersion < firstTargetFrameworkVersionToSupportTrimAnalyzer)
return ToolPackSupport.UnsupportedForTargetFramework;
}
// Packs with RID-agnostic build packages that contain MSBuild targets.
if (toolPackType is not ToolPackType.Crossgen2 && EnableRuntimePackDownload)
{
var buildPackageName = knownPack.ItemSpec;
var buildPackage = new TaskItem(buildPackageName);
buildPackage.SetMetadata(MetadataKeys.Version, packVersion);
implicitPackageReferences.Add(buildPackage);
}
// Before net8.0, ILLink analyzers shipped in a separate package.
// Add the analyzer package with version taken from KnownILLinkPack if the version is less than 8.0.0.
// The version comparison doesn't consider prerelease labels, so 8.0.0-foo will be considered equal to 8.0.0 and
// will not get the extra analyzer package reference.
if (toolPackType is ToolPackType.ILLink &&
new VersionComparer(VersionComparison.Version).Compare(NuGetVersion.Parse(packVersion), new NuGetVersion(8, 0, 0)) < 0 &&
EnableRuntimePackDownload)
{
var analyzerPackage = new TaskItem("Microsoft.NET.ILLink.Analyzers");
analyzerPackage.SetMetadata(MetadataKeys.Version, packVersion);
implicitPackageReferences.Add(analyzerPackage);
}
return ToolPackSupport.Supported;
}
private string GetRuntimeFrameworkVersion(
ITaskItem frameworkReference,
KnownFrameworkReference knownFrameworkReference,
KnownRuntimePack? knownRuntimePack,
out string runtimePackVersion)
{
// Precedence order for selecting runtime framework version
// - RuntimeFrameworkVersion metadata on FrameworkReference item
// - RuntimeFrameworkVersion MSBuild property
// - Then, use either the LatestRuntimeFrameworkVersion or the DefaultRuntimeFrameworkVersion of the KnownFrameworkReference, based on
// - The value (if set) of TargetLatestRuntimePatch metadata on the FrameworkReference
// - The TargetLatestRuntimePatch MSBuild property (which defaults to True if SelfContained is true, and False otherwise)
// - But, if TargetLatestRuntimePatch was defaulted and not overridden by user, then acquire latest runtime pack for future
// self-contained deployment (or for crossgen of framework-dependent deployment), while targeting the default version.
string requestedVersion = GetRequestedRuntimeFrameworkVersion(frameworkReference);
if (!string.IsNullOrEmpty(requestedVersion))
{
runtimePackVersion = requestedVersion;
return requestedVersion;
}
switch (GetRuntimePatchRequest(frameworkReference))
{
case RuntimePatchRequest.UseDefaultVersion:
runtimePackVersion = knownFrameworkReference.DefaultRuntimeFrameworkVersion;
return knownFrameworkReference.DefaultRuntimeFrameworkVersion;
case RuntimePatchRequest.UseLatestVersion:
if (knownRuntimePack != null)
{
runtimePackVersion = knownRuntimePack?.LatestRuntimeFrameworkVersion;
return knownRuntimePack?.LatestRuntimeFrameworkVersion;
}
else
{
runtimePackVersion = knownFrameworkReference.DefaultRuntimeFrameworkVersion;
return knownFrameworkReference.DefaultRuntimeFrameworkVersion;
}
case RuntimePatchRequest.UseDefaultVersionWithLatestRuntimePack:
if (knownRuntimePack != null)
{
runtimePackVersion = knownRuntimePack?.LatestRuntimeFrameworkVersion;
}
else
{
runtimePackVersion = knownFrameworkReference.DefaultRuntimeFrameworkVersion;
}
return knownFrameworkReference.DefaultRuntimeFrameworkVersion;
default:
// Unreachable
throw new InvalidOperationException();
}
}
private string GetPackPath(string packName, string packVersion)
{
IEnumerable<string> GetPackFolders()
{
var packRootEnvironmentVariable = Environment.GetEnvironmentVariable(EnvironmentVariableNames.WORKLOAD_PACK_ROOTS);
if (!string.IsNullOrEmpty(packRootEnvironmentVariable))
{
foreach (var packRoot in packRootEnvironmentVariable.Split(Path.PathSeparator))
{
yield return Path.Combine(packRoot, "packs");
}
}
if (!string.IsNullOrEmpty(NetCoreRoot) && !string.IsNullOrEmpty(NETCoreSdkVersion))
{
if (WorkloadFileBasedInstall.IsUserLocal(NetCoreRoot, NETCoreSdkVersion) &&
CliFolderPathCalculatorCore.GetDotnetUserProfileFolderPath() is { } userProfileDir)
{
yield return Path.Combine(userProfileDir, "packs");
}
}
if (!string.IsNullOrEmpty(TargetingPackRoot))
{
yield return TargetingPackRoot;
}
}
foreach (var packFolder in GetPackFolders())
{
string packPath = Path.Combine(packFolder, packName, packVersion);
if (Directory.Exists(packPath))
{
return packPath;
}
}