forked from dotnet/msbuild
/
ProjectCollection.cs
2560 lines (2257 loc) · 102 KB
/
ProjectCollection.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Xml;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Collections;
using Microsoft.Build.Construction;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.ObjectModelRemoting;
using Microsoft.Build.Shared;
using Microsoft.Build.Internal;
using Microsoft.Build.Utilities;
using ForwardingLoggerRecord = Microsoft.Build.Logging.ForwardingLoggerRecord;
using ILoggingService = Microsoft.Build.BackEnd.Logging.ILoggingService;
using InternalLoggerException = Microsoft.Build.Exceptions.InternalLoggerException;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using LoggerMode = Microsoft.Build.BackEnd.Logging.LoggerMode;
using ObjectModel = System.Collections.ObjectModel;
namespace Microsoft.Build.Evaluation
{
using Utilities = Internal.Utilities;
/// <summary>
/// Flags for controlling the toolset initialization.
/// </summary>
[Flags]
public enum ToolsetDefinitionLocations
{
/// <summary>
/// Do not read toolset information from any external location.
/// </summary>
None = 0,
/// <summary>
/// Read toolset information from the exe configuration file.
/// </summary>
ConfigurationFile = 1,
/// <summary>
/// Read toolset information from the registry (HKLM\Software\Microsoft\MSBuild\ToolsVersions).
/// </summary>
Registry = 2,
/// <summary>
/// Read toolset information from the current exe path
/// </summary>
Local = 4,
/// <summary>
/// Use the default location or locations.
/// </summary>
Default = None
#if FEATURE_SYSTEM_CONFIGURATION
| ConfigurationFile
#endif
#if FEATURE_REGISTRY_TOOLSETS
| Registry
#endif
#if !FEATURE_SYSTEM_CONFIGURATION && !FEATURE_REGISTRY_TOOLSETS
| Local
#endif
}
/// <summary>
/// This class encapsulates a set of related projects, their toolsets, a default set of global properties,
/// and the loggers that should be used to build them.
/// A global version of this class acts as the default ProjectCollection.
/// Multiple ProjectCollections can exist within an appdomain. However, these must not build concurrently.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "This is a collection of projects API review has approved this")]
public class ProjectCollection : IToolsetProvider, IBuildComponent, IDisposable
{
// ProjectCollection is highly reentrant - project creation, toolset and logger changes, and so on
// all need lock protection, but there are a lot of read cases as well, and calls to create Projects
// call back to the ProjectCollection under locks. Use a RW lock, but default to always using
// upgradable read locks to avoid adding reentrancy bugs.
private class DisposableReaderWriterLockSlim
{
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
public bool IsWriteLockHeld => _lock.IsWriteLockHeld;
public IDisposable EnterUpgradeableReadLock()
{
_lock.EnterUpgradeableReadLock();
return new DelegateDisposable(() => _lock.ExitUpgradeableReadLock());
}
public IDisposable EnterWriteLock()
{
_lock.EnterWriteLock();
return new DelegateDisposable(() => _lock.ExitWriteLock());
}
}
private class DelegateDisposable : IDisposable
{
private readonly Action _disposeAction;
public DelegateDisposable(Action disposeAction)
{
_disposeAction = disposeAction;
}
public void Dispose()
{
_disposeAction();
}
}
/// <summary>
/// The object to synchronize with when accessing certain fields.
/// </summary>
private readonly DisposableReaderWriterLockSlim _locker = new DisposableReaderWriterLockSlim();
/// <summary>
/// The global singleton project collection used as a default for otherwise
/// unassociated projects.
/// </summary>
private static ProjectCollection s_globalProjectCollection;
/// <summary>
/// Gets the file version of the file in which the Engine assembly lies.
/// </summary>
/// <remarks>
/// This is the Windows file version (specifically the value of the ProductVersion
/// resource), not necessarily the assembly version.
/// If you want the assembly version, use Constants.AssemblyVersion.
/// </remarks>
private static Version s_engineVersion;
/// <summary>
/// The display version of the file in which the Engine assembly lies.
/// </summary>
private static string s_assemblyDisplayVersion;
/// <summary>
/// The projects loaded into this collection.
/// </summary>
private readonly LoadedProjectCollection _loadedProjects;
/// <summary>
/// External projects support
/// </summary>
private ExternalProjectsProvider _link;
/// <summary>
/// Single logging service used for all builds of projects in this project collection
/// </summary>
private ILoggingService _loggingService;
/// <summary>
/// Any object exposing host services.
/// May be null.
/// </summary>
private HostServices _hostServices;
/// <summary>
/// A mapping of tools versions to Toolsets, which contain the public Toolsets.
/// This is the collection we use internally.
/// </summary>
private Dictionary<string, Toolset> _toolsets;
/// <summary>
/// The default global properties.
/// </summary>
private readonly PropertyDictionary<ProjectPropertyInstance> _globalProperties;
/// <summary>
/// The properties representing the environment.
/// </summary>
private PropertyDictionary<ProjectPropertyInstance> _environmentProperties;
/// <summary>
/// The default tools version obtained by examining all of the toolsets.
/// </summary>
private string _defaultToolsVersion;
/// <summary>
/// A counter incremented every time the toolsets change which would necessitate a re-evaluation of
/// associated projects.
/// </summary>
private int _toolsetsVersion;
/// <summary>
/// This is the default value used by newly created projects for whether or not the building
/// of projects is enabled. This is for security purposes in case a host wants to closely
/// control which projects it allows to run targets/tasks.
/// </summary>
private bool _isBuildEnabled = true;
/// <summary>
/// We may only wish to log critical events, record that fact so we can apply it to build requests
/// </summary>
private bool _onlyLogCriticalEvents;
/// <summary>
/// Whether reevaluation is temporarily disabled on projects in this collection.
/// This is useful when the host expects to make a number of reads and writes
/// to projects, and wants to temporarily sacrifice correctness for performance.
/// </summary>
private bool _skipEvaluation;
/// <summary>
/// Whether <see cref="Project.MarkDirty()">MarkDirty()</see> is temporarily disabled on
/// projects in this collection.
/// This allows, for example, global properties to be set without projects getting
/// marked dirty for reevaluation as a consequence.
/// </summary>
private bool _disableMarkDirty;
/// <summary>
/// The maximum number of nodes which can be started during the build
/// </summary>
private int _maxNodeCount;
/// <summary>
/// Instantiates a project collection with no global properties or loggers that reads toolset
/// information from the configuration file and registry.
/// </summary>
public ProjectCollection()
: this(null)
{
}
/// <summary>
/// Instantiates a project collection using toolsets from the specified locations,
/// and no global properties or loggers.
/// May throw InvalidToolsetDefinitionException.
/// </summary>
/// <param name="toolsetLocations">The locations from which to load toolsets.</param>
public ProjectCollection(ToolsetDefinitionLocations toolsetLocations)
: this(null, null, toolsetLocations)
{
}
/// <summary>
/// Instantiates a project collection with specified global properties, no loggers,
/// and that reads toolset information from the configuration file and registry.
/// May throw InvalidToolsetDefinitionException.
/// </summary>
/// <param name="globalProperties">The default global properties to use. May be null.</param>
public ProjectCollection(IDictionary<string, string> globalProperties)
: this(globalProperties, null, ToolsetDefinitionLocations.Default)
{
}
/// <summary>
/// Instantiates a project collection with specified global properties and loggers and using the
/// specified toolset locations.
/// May throw InvalidToolsetDefinitionException.
/// </summary>
/// <param name="globalProperties">The default global properties to use. May be null.</param>
/// <param name="loggers">The loggers to register. May be null.</param>
/// <param name="toolsetDefinitionLocations">The locations from which to load toolsets.</param>
public ProjectCollection(IDictionary<string, string> globalProperties, IEnumerable<ILogger> loggers, ToolsetDefinitionLocations toolsetDefinitionLocations)
: this(globalProperties, loggers, null, toolsetDefinitionLocations, 1 /* node count */, false /* do not only log critical events */)
{
}
/// <summary>
/// Instantiates a project collection with specified global properties and loggers and using the
/// specified toolset locations, node count, and setting of onlyLogCriticalEvents.
/// Global properties and loggers may be null.
/// Throws InvalidProjectFileException if any of the global properties are reserved.
/// May throw InvalidToolsetDefinitionException.
/// </summary>
/// <param name="globalProperties">The default global properties to use. May be null.</param>
/// <param name="loggers">The loggers to register. May be null and specified to any build instead.</param>
/// <param name="remoteLoggers">Any remote loggers to register. May be null and specified to any build instead.</param>
/// <param name="toolsetDefinitionLocations">The locations from which to load toolsets.</param>
/// <param name="maxNodeCount">The maximum number of nodes to use for building.</param>
/// <param name="onlyLogCriticalEvents">If set to true, only critical events will be logged.</param>
public ProjectCollection(IDictionary<string, string> globalProperties, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers, ToolsetDefinitionLocations toolsetDefinitionLocations, int maxNodeCount, bool onlyLogCriticalEvents)
: this(globalProperties, loggers, null, toolsetDefinitionLocations, maxNodeCount, onlyLogCriticalEvents, loadProjectsReadOnly: false)
{
}
/// <summary>
/// Instantiates a project collection with specified global properties and loggers and using the
/// specified toolset locations, node count, and setting of onlyLogCriticalEvents.
/// Global properties and loggers may be null.
/// Throws InvalidProjectFileException if any of the global properties are reserved.
/// May throw InvalidToolsetDefinitionException.
/// </summary>
/// <param name="globalProperties">The default global properties to use. May be null.</param>
/// <param name="loggers">The loggers to register. May be null and specified to any build instead.</param>
/// <param name="remoteLoggers">Any remote loggers to register. May be null and specified to any build instead.</param>
/// <param name="toolsetDefinitionLocations">The locations from which to load toolsets.</param>
/// <param name="maxNodeCount">The maximum number of nodes to use for building.</param>
/// <param name="onlyLogCriticalEvents">If set to true, only critical events will be logged.</param>
/// <param name="loadProjectsReadOnly">If set to true, load all projects as read-only.</param>
public ProjectCollection(IDictionary<string, string> globalProperties, IEnumerable<ILogger> loggers, IEnumerable<ForwardingLoggerRecord> remoteLoggers, ToolsetDefinitionLocations toolsetDefinitionLocations, int maxNodeCount, bool onlyLogCriticalEvents, bool loadProjectsReadOnly)
{
_loadedProjects = new LoadedProjectCollection();
ToolsetLocations = toolsetDefinitionLocations;
MaxNodeCount = maxNodeCount;
if (Traits.Instance.UseSimpleProjectRootElementCacheConcurrency)
{
ProjectRootElementCache = new SimpleProjectRootElementCache();
}
else
{
ProjectRootElementCache = new ProjectRootElementCache(autoReloadFromDisk: false, loadProjectsReadOnly);
}
OnlyLogCriticalEvents = onlyLogCriticalEvents;
try
{
CreateLoggingService(maxNodeCount, onlyLogCriticalEvents);
RegisterLoggers(loggers);
RegisterForwardingLoggers(remoteLoggers);
if (globalProperties != null)
{
_globalProperties = new PropertyDictionary<ProjectPropertyInstance>(globalProperties.Count);
foreach (KeyValuePair<string, string> pair in globalProperties)
{
try
{
_globalProperties.Set(ProjectPropertyInstance.Create(pair.Key, pair.Value));
}
catch (ArgumentException ex)
{
// Reserved or invalid property name
try
{
ProjectErrorUtilities.ThrowInvalidProject(ElementLocation.Create("MSBUILD"), "InvalidProperty", ex.Message);
}
catch (InvalidProjectFileException ex2)
{
BuildEventContext buildEventContext = new BuildEventContext(0 /* node ID */, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId);
LoggingService.LogInvalidProjectFileError(buildEventContext, ex2);
throw;
}
}
}
}
else
{
_globalProperties = new PropertyDictionary<ProjectPropertyInstance>();
}
InitializeToolsetCollection();
}
catch (Exception)
{
ShutDownLoggingService();
throw;
}
ProjectRootElementCache.ProjectRootElementAddedHandler += ProjectRootElementCache_ProjectRootElementAddedHandler;
ProjectRootElementCache.ProjectRootElementDirtied += ProjectRootElementCache_ProjectRootElementDirtiedHandler;
ProjectRootElementCache.ProjectDirtied += ProjectRootElementCache_ProjectDirtiedHandler;
}
/// <summary>
/// Handler to receive which project got added to the project collection.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "This has been API reviewed")]
public delegate void ProjectAddedEventHandler(object sender, ProjectAddedToProjectCollectionEventArgs e);
/// <summary>
/// Event that is fired when a project is added to the ProjectRootElementCache of this project collection.
/// </summary>
public event ProjectAddedEventHandler ProjectAdded;
/// <summary>
/// Raised when state is changed on this instance.
/// </summary>
/// <remarks>
/// This event is NOT raised for changes in individual projects.
/// </remarks>
public event EventHandler<ProjectCollectionChangedEventArgs> ProjectCollectionChanged;
/// <summary>
/// Raised when a <see cref="ProjectRootElement"/> contained by this instance is changed.
/// </summary>
/// <remarks>
/// This event is NOT raised for changes to global properties, or any other change that doesn't actually dirty the XML.
/// </remarks>
public event EventHandler<ProjectXmlChangedEventArgs> ProjectXmlChanged;
/// <summary>
/// Raised when a <see cref="Project"/> contained by this instance is directly changed.
/// </summary>
/// <remarks>
/// This event is NOT raised for direct project XML changes via the construction model.
/// </remarks>
public event EventHandler<ProjectChangedEventArgs> ProjectChanged;
/// <summary>
/// Retrieves the global project collection object.
/// This is a singleton project collection with no global properties or loggers that reads toolset
/// information from the configuration file and registry.
/// May throw InvalidToolsetDefinitionException.
/// Thread safe.
/// </summary>
public static ProjectCollection GlobalProjectCollection
{
get
{
if (s_globalProjectCollection == null)
{
// Take care to ensure that there is never more than one value observed
// from this property even in the case of race conditions while lazily initializing.
var local = new ProjectCollection();
Interlocked.CompareExchange(ref s_globalProjectCollection, local, null);
}
return s_globalProjectCollection;
}
}
/// <summary>
/// Gets the file version of the file in which the Engine assembly lies.
/// </summary>
/// <remarks>
/// This is the Windows file version (specifically the value of the FileVersion
/// resource), not necessarily the assembly version.
/// If you want the assembly version, use Constants.AssemblyVersion.
/// This is not the <see cref="ToolsetsVersion">ToolsetCollectionVersion</see>.
/// </remarks>
public static Version Version
{
get
{
if (s_engineVersion == null)
{
// Get the file version from the currently executing assembly.
// Use .CodeBase instead of .Location, because .Location doesn't
// work when Microsoft.Build.dll has been shadow-copied, for example
// in scenarios where NUnit is loading Microsoft.Build.
var versionInfo = FileVersionInfo.GetVersionInfo(FileUtilities.ExecutingAssemblyPath);
s_engineVersion = new Version(versionInfo.FileMajorPart, versionInfo.FileMinorPart, versionInfo.FileBuildPart, versionInfo.FilePrivatePart);
}
return s_engineVersion;
}
}
/// <summary>
/// Gets a version of the Engine suitable for display to a user.
/// </summary>
/// <remarks>
/// This is in the form of a SemVer v2 version, Major.Minor.Patch-prerelease+metadata.
/// </remarks>
public static string DisplayVersion
{
get
{
if (s_assemblyDisplayVersion == null)
{
var fullInformationalVersion = typeof(Constants).GetTypeInfo().Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
// use a truncated version with only 9 digits of SHA
var plusIndex = fullInformationalVersion.IndexOf('+');
s_assemblyDisplayVersion = plusIndex < 0
? fullInformationalVersion
: fullInformationalVersion.Substring(startIndex: 0, length: plusIndex + 10);
}
return s_assemblyDisplayVersion;
}
}
/// <summary>
/// The default tools version of this project collection. Projects use this tools version if they
/// aren't otherwise told what tools version to use.
/// This value is gotten from the .exe.config file, or else in the registry,
/// or if neither specify a default tools version then it is hard-coded to the tools version "2.0".
/// Setter throws InvalidOperationException if a toolset with the provided tools version has not been defined.
/// Always defined.
/// </summary>
public string DefaultToolsVersion
{
get
{
using (_locker.EnterUpgradeableReadLock())
{
ErrorUtilities.VerifyThrow(_defaultToolsVersion != null, "Should have a default");
return _defaultToolsVersion;
}
}
set
{
ErrorUtilities.VerifyThrowArgumentLength(value, nameof(DefaultToolsVersion));
bool sendEvent = false;
using (_locker.EnterWriteLock())
{
if (!_toolsets.ContainsKey(value))
{
string toolsVersionList = Utilities.CreateToolsVersionListString(Toolsets);
ErrorUtilities.ThrowInvalidOperation("UnrecognizedToolsVersion", value, toolsVersionList);
}
if (_defaultToolsVersion != value)
{
_defaultToolsVersion = value;
sendEvent = true;
}
}
if (sendEvent)
{
OnProjectCollectionChanged(new ProjectCollectionChangedEventArgs(ProjectCollectionChangedState.DefaultToolsVersion));
}
}
}
/// <summary>
/// Returns default global properties for all projects in this collection.
/// Read-only dead dictionary.
/// </summary>
/// <remarks>
/// This is the publicly exposed getter, that translates into a read-only dead IDictionary<string, string>.
///
/// To be consistent with Project, setting and removing global properties is done with
/// <see cref="SetGlobalProperty">SetGlobalProperty</see> and <see cref="RemoveGlobalProperty">RemoveGlobalProperty</see>.
/// </remarks>
public IDictionary<string, string> GlobalProperties
{
get
{
Dictionary<string, string> dictionary;
using (_locker.EnterUpgradeableReadLock())
{
if (_globalProperties.Count == 0)
{
return ReadOnlyEmptyDictionary<string, string>.Instance;
}
dictionary = new Dictionary<string, string>(_globalProperties.Count, MSBuildNameIgnoreCaseComparer.Default);
foreach (ProjectPropertyInstance property in _globalProperties)
{
dictionary[property.Name] = ((IProperty)property).EvaluatedValueEscaped;
}
}
return new ObjectModel.ReadOnlyDictionary<string, string>(dictionary);
}
}
/// <summary>
/// All the projects currently loaded into this collection.
/// Each has a unique combination of path, global properties, and tools version.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods", Justification = "This is a reasonable choice. API review approved")]
public ICollection<Project> LoadedProjects => GetLoadedProjects(true, null);
/// <summary>
/// Number of projects currently loaded into this collection.
/// </summary>
public int Count
{
get
{
using (_locker.EnterUpgradeableReadLock())
{
return _loadedProjects.Count;
}
}
}
/// <summary>
/// Loggers that all contained projects will use for their builds.
/// Loggers are added with the <see cref="RegisterLogger"/>.
/// Returns an empty collection if there are no loggers.
/// </summary>
// UNDONE: Currently loggers cannot be removed.
public ICollection<ILogger> Loggers
{
[DebuggerStepThrough]
get
{
using (_locker.EnterUpgradeableReadLock())
{
return _loggingService.Loggers == null
? (ICollection<ILogger>) ReadOnlyEmptyCollection<ILogger>.Instance
: new List<ILogger>(_loggingService.Loggers);
}
}
}
/// <summary>
/// Returns the toolsets this ProjectCollection knows about.
/// </summary>
/// <comments>
/// ValueCollection is already read-only
/// </comments>
public ICollection<Toolset> Toolsets
{
get
{
using (_locker.EnterUpgradeableReadLock())
{
return new List<Toolset>(_toolsets.Values);
}
}
}
/// <summary>
/// Returns the locations used to find the toolsets.
/// </summary>
public ToolsetDefinitionLocations ToolsetLocations { get; }
/// <summary>
/// This is the default value used by newly created projects for whether or not the building
/// of projects is enabled. This is for security purposes in case a host wants to closely
/// control which projects it allows to run targets/tasks.
/// </summary>
public bool IsBuildEnabled
{
[DebuggerStepThrough]
get
{
using (_locker.EnterUpgradeableReadLock())
{
return _isBuildEnabled;
}
}
[DebuggerStepThrough]
set
{
bool sendEvent = false;
using (_locker.EnterWriteLock())
{
if (_isBuildEnabled != value)
{
_isBuildEnabled = value;
sendEvent = true;
}
}
if (sendEvent)
{
OnProjectCollectionChanged(new ProjectCollectionChangedEventArgs(ProjectCollectionChangedState.IsBuildEnabled));
}
}
}
/// <summary>
/// When true, only log critical events such as warnings and errors. Has to be in here for API compat
/// </summary>
public bool OnlyLogCriticalEvents
{
get
{
using (_locker.EnterUpgradeableReadLock())
{
return _onlyLogCriticalEvents;
}
}
set
{
bool sendEvent = false;
using (_locker.EnterWriteLock())
{
if (_onlyLogCriticalEvents != value)
{
_onlyLogCriticalEvents = value;
sendEvent = true;
}
}
if (sendEvent)
{
OnProjectCollectionChanged(
new ProjectCollectionChangedEventArgs(ProjectCollectionChangedState.OnlyLogCriticalEvents));
}
}
}
/// <summary>
/// Object exposing host services to tasks during builds of projects
/// contained by this project collection.
/// By default, <see cref="HostServices">HostServices</see> is used.
/// May be set to null, but the getter will create a new instance in that case.
/// </summary>
public HostServices HostServices
{
get
{
// Avoid write lock if possible, this getter is called a lot during Project construction.
using (_locker.EnterUpgradeableReadLock())
{
if (_hostServices != null)
{
return _hostServices;
}
using (_locker.EnterWriteLock())
{
return _hostServices ?? (_hostServices = new HostServices());
}
}
}
set
{
bool sendEvent = false;
using (_locker.EnterWriteLock())
{
if (_hostServices != value)
{
_hostServices = value;
sendEvent = true;
}
}
if (sendEvent)
{
OnProjectCollectionChanged(
new ProjectCollectionChangedEventArgs(ProjectCollectionChangedState.HostServices));
}
}
}
/// <summary>
/// Whether reevaluation is temporarily disabled on projects in this collection.
/// This is useful when the host expects to make a number of reads and writes
/// to projects, and wants to temporarily sacrifice correctness for performance.
/// </summary>
public bool SkipEvaluation
{
get
{
using (_locker.EnterUpgradeableReadLock())
{
return _skipEvaluation;
}
}
set
{
bool sendEvent = false;
using (_locker.EnterWriteLock())
{
if (_skipEvaluation != value)
{
_skipEvaluation = value;
sendEvent = true;
}
}
if (sendEvent)
{
OnProjectCollectionChanged(
new ProjectCollectionChangedEventArgs(ProjectCollectionChangedState.SkipEvaluation));
}
}
}
/// <summary>
/// Whether <see cref="Project.MarkDirty()">MarkDirty()</see> is temporarily disabled on
/// projects in this collection.
/// This allows, for example, global properties to be set without projects getting
/// marked dirty for reevaluation as a consequence.
/// </summary>
public bool DisableMarkDirty
{
get
{
using (_locker.EnterUpgradeableReadLock())
{
return _disableMarkDirty;
}
}
set
{
bool sendEvent = false;
using (_locker.EnterWriteLock())
{
if (_disableMarkDirty != value)
{
_disableMarkDirty = value;
sendEvent = true;
}
}
if (sendEvent)
{
OnProjectCollectionChanged(
new ProjectCollectionChangedEventArgs(ProjectCollectionChangedState.DisableMarkDirty));
}
}
}
/// <summary>
/// Global collection id.
/// Can be used for external providers to optimize the cross-site link exchange
/// </summary>
internal Guid CollectionId { get; } = Guid.NewGuid();
/// <summary>
/// External project support.
/// Establish a remote project link for this collection.
/// </summary>
internal ExternalProjectsProvider Link
{
get => _link;
set => Interlocked.Exchange(ref _link, value)?.Disconnected(this);
}
/// <summary>
/// Logging service that should be used for project load and for builds
/// </summary>
internal ILoggingService LoggingService
{
[DebuggerStepThrough]
get
{
using (_locker.EnterUpgradeableReadLock())
{
return _loggingService;
}
}
}
/// <summary>
/// Gets default global properties for all projects in this collection.
/// Dead copy.
/// </summary>
internal PropertyDictionary<ProjectPropertyInstance> GlobalPropertiesCollection
{
[DebuggerStepThrough]
get
{
var clone = new PropertyDictionary<ProjectPropertyInstance>();
using (_locker.EnterUpgradeableReadLock())
{
foreach (ProjectPropertyInstance property in _globalProperties)
{
clone.Set(property.DeepClone());
}
return clone;
}
}
}
/// <summary>
/// Returns the property dictionary containing the properties representing the environment.
/// </summary>
internal PropertyDictionary<ProjectPropertyInstance> EnvironmentProperties
{
get
{
using (_locker.EnterUpgradeableReadLock())
{
// Retrieves the environment properties.
// This is only done once, when the project collection is created. Any subsequent
// environment changes will be ignored. Child nodes will be passed this set
// of properties in their build parameters.
if (_environmentProperties == null)
{
using (_locker.EnterWriteLock())
{
if (_environmentProperties == null)
{
_environmentProperties = Utilities.GetEnvironmentProperties();
}
}
}
return new PropertyDictionary<ProjectPropertyInstance>(_environmentProperties);
}
}
}
/// <summary>
/// Returns the internal version for this object's state.
/// Updated when toolsets change, indicating all contained projects are potentially invalid.
/// </summary>
internal int ToolsetsVersion
{
[DebuggerStepThrough]
get
{
using (_locker.EnterUpgradeableReadLock())
{
return _toolsetsVersion;
}
}
}
/// <summary>
/// The maximum number of nodes which can be started during the build
/// </summary>
internal int MaxNodeCount
{
get
{
using (_locker.EnterUpgradeableReadLock())
{
return _maxNodeCount;
}
}
set
{
using (_locker.EnterWriteLock())
{
_maxNodeCount = value;
}
}
}
/// <summary>
/// The cache of project root elements associated with this project collection.
/// Each is associated with a specific project collection for two reasons:
/// - To help protect one project collection from any XML edits through another one:
/// until a reload from disk - when it's ready to accept changes - it won't see the edits;
/// - So that the owner of this project collection can force the XML to be loaded again
/// from disk, by doing <see cref="UnloadAllProjects"/>.
/// </summary>
internal ProjectRootElementCacheBase ProjectRootElementCache { get; }
/// <summary>
/// Escape a string using MSBuild escaping format. For example, "%3b" for ";".
/// Only characters that are especially significant to MSBuild parsing are escaped.
/// Callers can use this method to make a string safe to be parsed to other methods
/// that would otherwise expand it; or to make a string safe to be written to a project file.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string", Justification = "Public API that has shipped")]
public static string Escape(string unescapedString)
{
return EscapingUtilities.Escape(unescapedString);
}
/// <summary>
/// Unescape a string using MSBuild escaping format. For example, "%3b" for ";".
/// All escaped characters are unescaped.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string", Justification = "Public API that has shipped")]
public static string Unescape(string escapedString)
{
return EscapingUtilities.UnescapeAll(escapedString);
}
/// <summary>
/// Returns true if there is a toolset defined for the specified
/// tools version, otherwise false.
/// </summary>
public bool ContainsToolset(string toolsVersion) => GetToolset(toolsVersion) != null;
/// <summary>
/// Add a new toolset.
/// Replaces any existing toolset with the same tools version.
/// </summary>
public void AddToolset(Toolset toolset)
{
ErrorUtilities.VerifyThrowArgumentNull(toolset, nameof(toolset));
using (_locker.EnterWriteLock())
{
_toolsets[toolset.ToolsVersion] = toolset;
_toolsetsVersion++;
}
OnProjectCollectionChanged(new ProjectCollectionChangedEventArgs(ProjectCollectionChangedState.Toolsets));
}
/// <summary>
/// Remove a toolset.
/// Returns true if it was present, otherwise false.
/// </summary>
public bool RemoveToolset(string toolsVersion)
{
ErrorUtilities.VerifyThrowArgumentLength(toolsVersion, nameof(toolsVersion));
bool changed;
using (_locker.EnterWriteLock())
{
changed = RemoveToolsetInternal(toolsVersion);
}
if (changed)
{
OnProjectCollectionChanged(new ProjectCollectionChangedEventArgs(ProjectCollectionChangedState.Toolsets));