-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathTaskExecutionHost.cs
More file actions
2266 lines (2017 loc) · 104 KB
/
Copy pathTaskExecutionHost.cs
File metadata and controls
2266 lines (2017 loc) · 104 KB
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 System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
#if NET
using System.Runtime.CompilerServices;
#endif
#if FEATURE_APPDOMAIN
using System.Runtime.Remoting;
#endif
using System.Text;
using System.Threading;
using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.Collections;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
using Task = System.Threading.Tasks.Task;
#nullable disable
namespace Microsoft.Build.BackEnd
{
/// <summary>
/// Flags returned by TaskExecutionHost.FindTask().
/// </summary>
[Flags]
internal enum TaskRequirements
{
/// <summary>
/// The task was not found.
/// </summary>
None = 0,
/// <summary>
/// The task must be executed on an STA thread.
/// </summary>
RequireSTAThread = 0x01,
/// <summary>
/// The task must be executed in a separate AppDomain.
/// </summary>
RequireSeparateAppDomain = 0x02
}
/// <summary>
/// The TaskExecutionHost is responsible for instantiating tasks, setting their parameters and gathering outputs using
/// reflection, and executing the task in the appropriate context.The TaskExecutionHost does not deal with any part of the task declaration or
/// XML.
/// </summary>
internal class TaskExecutionHost : IDisposable
{
/// <summary>
/// Time interval in miliseconds to wait between receiving a cancelation signal and emitting the first warning that a non-cancelable task has not finished
/// </summary>
private const int CancelFirstWarningWaitInterval = 5000;
/// <summary>
/// Time interval in miliseconds between subsequent warnings that a non-cancelable task has not finished
/// </summary>
private const int CancelWarningWaitInterval = 15000;
#if FEATURE_APPDOMAIN
/// <summary>
/// Resolver to assist in resolving types when a new appdomain is created
/// </summary>
private TaskEngineAssemblyResolver _resolver;
#endif
/// <summary>
/// The interface used to call back into the build engine.
/// </summary>
private IBuildEngine2 _buildEngine;
/// <summary>
/// The project instance in whose context we are executing
/// </summary>
private ProjectInstance _projectInstance;
// Items required for all batches of a task
/// <summary>
/// The logging context for the target.
/// </summary>
private TargetLoggingContext _targetLoggingContext;
/// <summary>
/// The logging context for the task.
/// </summary>
private TaskLoggingContext _taskLoggingContext;
/// <summary>
/// The registration which handles the callback when task cancellation is invoked.
/// </summary>
private CancellationTokenRegistration _cancellationTokenRegistration;
/// <summary>
/// The name of the task to execute.
/// </summary>
private string _taskName;
/// <summary>
/// The project file path that runs the task.
/// </summary>
private string _projectFile;
/// <summary>
/// The XML location of the task element.
/// </summary>
private ElementLocation _taskLocation;
/// <summary>
/// The arbitrary task host object.
/// </summary>
private ITaskHost _taskHost;
// Items required for a particular batch of a task
/// <summary>
/// The bucket used to evaluate items and properties.
/// </summary>
private ItemBucket _batchBucket;
/// <summary>
/// The task type retrieved from the assembly.
/// </summary>
private TaskFactoryWrapper _taskFactoryWrapper;
/// <summary>
/// When the task was resolved from <see cref="TaskClassRegistry"/> (a host-registered task), the
/// factory that constructs it with no assembly loading or reflection. Non-null only for registered
/// tasks, which run even when reflective task execution is disabled (trimmed/AOT host).
/// </summary>
private RegisteredTaskFactory _registeredTaskFactory;
/// <summary>
/// Set to true if the execution has been cancelled.
/// </summary>
private bool _cancelled;
/// <summary>
/// Event which is signalled when a task is not executing. Used for cancellation.
/// </summary>
private readonly ManualResetEvent _taskExecutionIdle = new ManualResetEvent(true);
/// <summary>
/// The task items that we remoted across the appdomain boundary
/// we use this list to disconnect the task items once we're done.
/// </summary>
private List<TaskItem> _remotedTaskItems;
/// <summary>
/// We need access to the build component host so that we can get at the
/// task host node provider when running a task wrapped by TaskHostTask
/// </summary>
private readonly IBuildComponentHost _buildComponentHost;
/// <summary>
/// The set of intrinsic tasks mapped for this process.
/// </summary>
private readonly Dictionary<string, TaskFactoryWrapper> _intrinsicTasks = new Dictionary<string, TaskFactoryWrapper>(StringComparer.OrdinalIgnoreCase);
private readonly PropertyTrackingSetting _propertyTrackingSettings;
/// <summary>
/// The task environment to be used by IMultiThreadableTask instances.
/// </summary>
internal TaskEnvironment TaskEnvironment { get; set; }
/// <summary>
/// Constructor
/// </summary>
internal TaskExecutionHost(IBuildComponentHost host)
{
_buildComponentHost = host;
if (host?.BuildParameters != null)
{
LogTaskInputs = host.BuildParameters.LogTaskInputs;
}
// If this is false, check the environment variable to see if it's there:
if (!LogTaskInputs)
{
LogTaskInputs = Traits.Instance.EscapeHatches.LogTaskInputs;
}
_propertyTrackingSettings = (PropertyTrackingSetting)Traits.Instance.LogPropertyTracking;
}
/// <summary>
/// Initializes a new instance of the <see cref="TaskExecutionHost"/> class
/// for unit testing only.
/// </summary>
internal TaskExecutionHost()
{
// do nothing
}
/// <summary>
/// Finalizes an instance of the <see cref="TaskExecutionHost"/> class.
/// </summary>
~TaskExecutionHost()
{
Debug.Fail("Unexpected finalization. Dispose should already have been called.");
Dispose(false);
}
/// <summary>
/// Flag to determine whether or not to log task inputs.
/// </summary>
public bool LogTaskInputs { get; }
/// <summary>
/// The associated project.
/// </summary>
public ProjectInstance ProjectInstance => _projectInstance;
/// <summary>
/// Gets the task instance
/// </summary>
internal ITask TaskInstance { get; private set; }
/// <summary>
/// FOR UNIT TESTING ONLY
/// </summary>
internal TaskFactoryWrapper _UNITTESTONLY_TaskFactoryWrapper
{
get => _taskFactoryWrapper;
set => _taskFactoryWrapper = value;
}
private HostServices _hostServices;
#if FEATURE_APPDOMAIN
/// <summary>
/// App domain configuration.
/// </summary>
internal AppDomainSetup AppDomainSetup { get; set; }
#endif
/// <summary>
/// Whether or not this is out-of-proc.
/// </summary>
internal bool IsOutOfProc { get; set; }
/// <summary>
/// Implementation of IDisposable
/// </summary>
public virtual void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#region ITaskExecutionHost Members
/// <summary>
/// Initialize to run a specific task.
/// </summary>
public void InitializeForTask(
IBuildEngine2 buildEngine,
TargetLoggingContext loggingContext,
ProjectInstance projectInstance,
string taskName,
ElementLocation taskLocation,
ITaskHost taskHost,
bool continueOnError,
string projectFile,
#if FEATURE_APPDOMAIN
AppDomainSetup appDomainSetup,
#endif
HostServices hostServices,
bool isOutOfProc,
CancellationToken cancellationToken,
TaskEnvironment taskEnvironment)
{
_buildEngine = buildEngine;
_projectInstance = projectInstance;
_targetLoggingContext = loggingContext;
_taskName = taskName;
_projectFile = projectFile;
_taskLocation = taskLocation;
_cancellationTokenRegistration = cancellationToken.Register(Cancel);
_taskHost = taskHost;
_taskExecutionIdle.Set();
#if FEATURE_APPDOMAIN
AppDomainSetup = appDomainSetup;
#endif
_hostServices = hostServices;
IsOutOfProc = isOutOfProc;
TaskEnvironment = taskEnvironment;
}
/// <summary>
/// Ask the task host to find its task in the registry and get it ready for initializing the batch
/// </summary>
/// <returns>The task requirements and task factory wrapper if the task is found, (null, null) otherwise.</returns>
public (TaskRequirements? requirements, TaskFactoryWrapper taskFactoryWrapper) FindTask(in TaskHostParameters taskIdentityParameters)
{
if (_taskFactoryWrapper is null)
{
// A fresh task resolution: clear any registered-task factory left over from a previous task on
// this reused host, so an unregistered (e.g. intrinsic) task is not mistaken for the prior
// registered one when constructing its instance.
_registeredTaskFactory = null;
// A host-registered task (TaskClassRegistry) resolves with no assembly loading or by-name
// type resolution, so it runs even when reflective task execution is disabled - the path a
// trimmed/AOT host takes. Consult the registry first.
if (TryCreateRegisteredTaskFactory(out TaskFactoryWrapper registeredTaskFactoryWrapper))
{
_taskFactoryWrapper = registeredTaskFactoryWrapper;
}
else if (!FeatureSwitches.EnableReflectiveTaskExecution)
{
// The intrinsic MSBuild and CallTarget tasks are engine-internal types resolved without
// reflecting over a runtime-discovered assembly, so they stay available when reflective task
// execution is disabled (the trimmed/AOT path) - virtually every real build uses them.
if (TryCreateIntrinsicTaskFactory(out TaskFactoryWrapper intrinsicTaskFactoryWrapper))
{
_taskFactoryWrapper = intrinsicTaskFactoryWrapper;
}
else
{
// Loading a task factory/type reflects over an assembly discovered at run time, which a
// trimmed/AOT host cannot do. Fail observably with a reported build error (rather than
// crashing in reflection) so the host can fall back to a JIT MSBuild. This is the leaf gate
// that frees the whole build-execution chain above from carrying [RequiresUnreferencedCode],
// and it lets the trimmer remove the reflective task-loading path from the image.
ProjectErrorUtilities.ThrowInvalidProject(_taskLocation, "ReflectiveTaskExecutionNotSupported", _taskName);
return (null, null);
}
}
else
{
_taskFactoryWrapper = FindTaskInRegistry(taskIdentityParameters);
}
}
if (_taskFactoryWrapper is null)
{
return (null, null);
}
TaskRequirements requirements = TaskRequirements.None;
// HasSTAThreadAttribute / HasLoadInSeparateAppDomainAttribute come from custom attributes
// ([RunInSTA] / [LoadInSeparateAppDomain]) on the task type. A registered task's LoadedType is
// rooted for trimming with PublicParameterlessConstructor | PublicProperties only, so under Native
// AOT those attributes are not preserved and read as false - a registered task declaring them would
// not get STA / separate-AppDomain treatment. That is acceptable for the in-process registered-task
// path (separate AppDomains do not exist on .NET Core regardless); the reflective JIT path, which
// loads the full type, observes the attributes exactly as before.
if (_taskFactoryWrapper.TaskFactoryLoadedType.HasSTAThreadAttribute)
{
requirements |= TaskRequirements.RequireSTAThread;
}
if (_taskFactoryWrapper.TaskFactoryLoadedType.HasLoadInSeparateAppDomainAttribute)
{
requirements |= TaskRequirements.RequireSeparateAppDomain;
// we're going to be remoting across the appdomain boundary, so
// create the list that we'll use to disconnect the taskitems once we're done
_remotedTaskItems = new List<TaskItem>();
}
return (requirements, _taskFactoryWrapper);
}
/// <summary>
/// Attempts to resolve the current task from the host task registry (<see cref="TaskClassRegistry"/>).
/// A registered task is constructed with no assembly loading or by-name type resolution, so it can run
/// even in a trimmed/AOT host where reflective task execution is disabled.
/// </summary>
/// <param name="taskFactoryWrapper">The wrapper for the registered task, or <see langword="null"/> if the task is not registered.</param>
/// <returns><see langword="true"/> if the task was found in the registry.</returns>
private bool TryCreateRegisteredTaskFactory(out TaskFactoryWrapper taskFactoryWrapper)
{
if (TaskClassRegistry.TryGetRegistration(_taskName, out TaskClassRegistration registration))
{
LoadedType loadedType = registration.GetLoadedType();
_registeredTaskFactory = new RegisteredTaskFactory(registration, loadedType);
taskFactoryWrapper = new TaskFactoryWrapper(_registeredTaskFactory, loadedType, _taskName, TaskHostParameters.Empty);
return true;
}
taskFactoryWrapper = null;
return false;
}
/// <summary>
/// Attempts to resolve the current task as an intrinsic engine task (<c>MSBuild</c> or <c>CallTarget</c>).
/// These map to engine-internal types via <see cref="IntrinsicTaskFactory"/> with no reflection over a
/// runtime-discovered assembly, so they remain usable when reflective task execution is disabled (the
/// trimmed/Native AOT path). The reflective path resolves them by type in <see cref="FindTaskInRegistry"/>.
/// </summary>
/// <param name="taskFactoryWrapper">The wrapper for the intrinsic task, or <see langword="null"/> if the task is not intrinsic.</param>
/// <returns><see langword="true"/> if the task is an intrinsic engine task.</returns>
private bool TryCreateIntrinsicTaskFactory(out TaskFactoryWrapper taskFactoryWrapper)
{
if (string.Equals(_taskName, "MSBuild", StringComparison.OrdinalIgnoreCase))
{
taskFactoryWrapper = CreateIntrinsicTaskFactoryWrapper(typeof(MSBuild));
return true;
}
if (string.Equals(_taskName, "CallTarget", StringComparison.OrdinalIgnoreCase))
{
taskFactoryWrapper = CreateIntrinsicTaskFactoryWrapper(typeof(CallTarget));
return true;
}
taskFactoryWrapper = null;
return false;
}
/// <summary>
/// Builds a <see cref="TaskFactoryWrapper"/> for an intrinsic engine task (<c>MSBuild</c> or
/// <c>CallTarget</c>) by direct type reference - no assembly probing or by-name resolution. Shared by
/// the reflective resolution path (<see cref="FindTaskInRegistry"/>) and the reflection-free path
/// (<see cref="TryCreateIntrinsicTaskFactory"/>) so the two constructions cannot drift.
/// </summary>
private TaskFactoryWrapper CreateIntrinsicTaskFactoryWrapper(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicProperties)] Type intrinsicTaskType)
{
Assembly taskExecutionHostAssembly = typeof(TaskExecutionHost).Assembly;
return new TaskFactoryWrapper(
new IntrinsicTaskFactory(intrinsicTaskType),
new LoadedType(intrinsicTaskType, AssemblyLoadInfo.Create(taskExecutionHostAssembly.FullName, null), taskExecutionHostAssembly, typeof(ITaskItem)),
_taskName,
TaskHostParameters.Empty);
}
/// <summary>
/// Initialize to run a specific batch of the current task.
/// </summary>
public bool InitializeForBatch(TaskLoggingContext loggingContext, ItemBucket batchBucket, in TaskHostParameters taskIdentityParameters, int scheduledNodeId)
{
ArgumentNullException.ThrowIfNull(loggingContext);
_taskLoggingContext = loggingContext;
_batchBucket = batchBucket;
if (_taskFactoryWrapper == null)
{
return false;
}
#if FEATURE_APPDOMAIN
// If the task assembly is loaded into a separate AppDomain using LoadFrom, then we have a problem
// to solve - when the task class Type is marshalled back into our AppDomain, it's not just transferred
// here. Instead, NDP will try to Load (not LoadFrom!) the task assembly into our AppDomain, and since
// we originally used LoadFrom, it will fail miserably not knowing where to find it.
// We need to temporarily subscribe to the AppDomain.AssemblyResolve event to fix it.
// A registered task's assembly is already loaded (the host referenced it statically), so it
// needs no assembly-resolve handler.
if (_registeredTaskFactory is null && _resolver == null)
{
_resolver = new TaskEngineAssemblyResolver();
_resolver.Initialize(_taskFactoryWrapper.TaskFactoryLoadedType.Assembly.AssemblyFile);
_resolver.InstallHandler();
}
#endif
// We instantiate a new task object for each batch.
if (_registeredTaskFactory is not null)
{
// Reflection-free construction via the host-supplied factory. This deliberately avoids the
// [RequiresUnreferencedCode] ITaskFactory.CreateTask interface member, so the registered-task
// path carries no trim warning and runs under Native AOT.
TaskInstance = _registeredTaskFactory.CreateRegisteredTask(TaskEnvironment);
}
else if (!FeatureSwitches.EnableReflectiveTaskExecution && _taskFactoryWrapper.TaskFactory is IntrinsicTaskFactory intrinsicTaskFactory)
{
// Reflective-OFF (trimmed/AOT) path only: construct the intrinsic MSBuild/CallTarget task by
// direct `new` (no reflection), because the reflective InstantiateTask below is gated off and
// dead-stripped under trimming. Under the JIT default (switch on) intrinsic tasks deliberately
// fall through to InstantiateTask exactly as before, so they keep their TaskFactoryEngineContext
// lifecycle and ProjectTelemetry accounting - this branch must not alter the JIT path.
TaskInstance = intrinsicTaskFactory.CreateIntrinsicTask();
}
else if (!FeatureSwitches.EnableReflectiveTaskExecution)
{
// See FindTask: instantiating an unregistered task reflects over a runtime-discovered type, so
// a trimmed/AOT host fails observably here. Normally unreachable - FindTask already failed -
// but it keeps the reflective InstantiateTask below behind the feature guard.
ProjectErrorUtilities.ThrowInvalidProject(_taskLocation, "ReflectiveTaskExecutionNotSupported", _taskName);
return false;
}
else
{
TaskInstance = InstantiateTask(scheduledNodeId, taskIdentityParameters);
}
if (TaskInstance == null)
{
return false;
}
// The task-assembly location-mismatch diagnostic reads Assembly.Location, which is empty (and
// meaningless) in a single-file/Native AOT host - and a registered task is already the loaded
// type. On .NET, guard the read on dynamic-code support so ILC dead-strips it (and its IL3000)
// under Native AOT while the JIT keeps the diagnostic; .NET Framework (no AOT) always runs it.
// A TaskHostTask is only an in-proc proxy - the task assembly it stands for is loaded in the task
// host process, so the proxy's own location (always Microsoft.Build.dll) says nothing about where
// the task came from and comparing it would report a mismatch for every out-of-proc task.
#if NET
if (RuntimeFeature.IsDynamicCodeSupported && TaskInstance is not TaskHostTask)
#else
if (TaskInstance is not TaskHostTask)
#endif
{
// When MSBuild loads a task assembly, it uses Assembly.LoadFrom() with a specific path, but
// .NET then loads based on the assembly identity with that path only as a hint. This can
// result in the assembly being loaded from a different location than expected (for example
// from the GAC, or because something already loaded the same identity from another path),
// which can cause confusing task behavior. This validation logs a message when the loaded
// assembly location does not match the path we resolved the task from.
string realTaskAssemblyLocation = TaskInstance.GetType().Assembly.Location;
if (!string.IsNullOrWhiteSpace(realTaskAssemblyLocation) && realTaskAssemblyLocation != _taskFactoryWrapper.TaskFactoryLoadedType.Path)
{
_taskLoggingContext.LogComment(MessageImportance.Normal, "TaskAssemblyLocationMismatch", realTaskAssemblyLocation, _taskFactoryWrapper.TaskFactoryLoadedType.Path);
}
}
TaskInstance.BuildEngine = _buildEngine;
TaskInstance.HostObject = _taskHost;
if (TaskInstance is IMultiThreadableTask multiThreadableTask)
{
multiThreadableTask.TaskEnvironment = TaskEnvironment;
}
return true;
}
/// <summary>
/// Sets all of the specified parameters on the task.
/// </summary>
/// <param name="parameters">The name/value pairs for the parameters.</param>
/// <returns>True if the parameters were set correctly, false otherwise.</returns>
public bool SetTaskParameters(IDictionary<string, (string, ElementLocation)> parameters)
{
if (_registeredTaskFactory is null && _taskFactoryWrapper.TaskFactory is not IntrinsicTaskFactory && !FeatureSwitches.EnableReflectiveTaskExecution)
{
// Binding task parameters reflects over the task type. A registered task's type is trim-rooted
// (so binding stays trim-safe) and is exempt, as is an intrinsic MSBuild/CallTarget task (an
// engine-internal type); for any other task in a trimmed/AOT host this fails observably. See
// FindTask: normally unreachable (FindTask fails first).
ProjectErrorUtilities.ThrowInvalidProject(_taskLocation, "ReflectiveTaskExecutionNotSupported", _taskName);
return false;
}
ArgumentNullException.ThrowIfNull(parameters);
bool taskInitialized = true;
// Get the properties that exist on this task. We need to gather all of the ones that are marked
// "required" so that we can keep track of whether or not they all get set.
var setParameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
IReadOnlyDictionary<string, string> requiredParameters = GetNamesOfPropertiesWithRequiredAttribute();
// look through all the attributes of the task element
foreach (KeyValuePair<string, (string, ElementLocation)> parameter in parameters)
{
bool taskParameterSet = false; // Did we actually call the setter on this task parameter?
bool success;
try
{
success = SetTaskParameter(parameter.Key, parameter.Value.Item1, parameter.Value.Item2, requiredParameters.ContainsKey(parameter.Key), out taskParameterSet);
}
catch (Exception e) when (!ExceptionHandling.NotExpectedReflectionException(e))
{
// Reflection related exception
_taskLoggingContext.LogError(new BuildEventFileInfo(_taskLocation), "TaskParametersError", _taskName, e.Message);
success = false;
}
if (!success)
{
// stop processing any more attributes
taskInitialized = false;
break;
}
else if (taskParameterSet)
{
// Keep track that we've set a value for this property. Note that this will
// keep track of non-required properties as well, but that's okay. We just
// to check at the end that there are no values in the requiredParameters
// table that aren't also in the setParameters table.
setParameters[parameter.Key] = String.Empty;
}
}
if (TaskInstance is IIncrementalTask incrementalTask)
{
incrementalTask.FailIfNotIncremental = _buildComponentHost.BuildParameters.Question;
}
if (taskInitialized)
{
// See if any required properties were not set
foreach (KeyValuePair<string, string> requiredParameter in requiredParameters)
{
ProjectErrorUtilities.VerifyThrowInvalidProject(
setParameters.ContainsKey(requiredParameter.Key),
_taskLocation,
"RequiredPropertyNotSetError",
_taskName,
requiredParameter.Key);
}
}
return taskInitialized;
}
/// <summary>
/// Retrieve the outputs from the task.
/// </summary>
/// <returns>True of the outputs were gathered successfully, false otherwise.</returns>
public bool GatherTaskOutputs(string parameterName, ElementLocation parameterLocation, bool outputTargetIsItem, string outputTargetName)
{
Assumed.NotNull(_taskFactoryWrapper, "Need a taskFactoryWrapper to retrieve outputs from.");
bool gatheredGeneratedOutputsSuccessfully = true;
try
{
TaskPropertyInfo parameter = _taskFactoryWrapper.GetProperty(parameterName);
foreach (TaskPropertyInfo prop in _taskFactoryWrapper.TaskFactoryLoadedType.Properties)
{
if (prop.Name.Equals(parameterName, StringComparison.OrdinalIgnoreCase))
{
parameter = prop;
break;
}
}
// flag an error if we find a parameter that has no .NET property equivalent
ProjectErrorUtilities.VerifyThrowInvalidProject(
parameter != null,
parameterLocation,
"UnexpectedTaskOutputAttribute",
parameterName,
_taskName);
// output parameters must have their corresponding .NET properties marked with the Output attribute
ProjectErrorUtilities.VerifyThrowInvalidProject(
_taskFactoryWrapper.GetNamesOfPropertiesWithOutputAttribute.ContainsKey(parameterName),
parameterLocation,
"UnmarkedOutputTaskParameter",
parameter.Name,
_taskName);
EnsureParameterInitialized(parameter, _batchBucket.Lookup);
if (parameter.IsAssignableToITask
|| (parameter is ReflectableTaskPropertyInfo { IsTypeUnresolved: true }
&& TaskInstance is TaskHostTask taskHostTask
&& taskHostTask.IsTaskItemOutput(parameter.Name)))
{
ITaskItem[] outputs = GetItemOutputs(parameter);
GatherTaskItemOutputs(outputTargetIsItem, outputTargetName, outputs, parameterLocation, parameter);
}
else if (parameter.IsValueTypeOutputParameter)
{
string[] outputs = GetValueOutputs(parameter);
GatherArrayStringAndValueOutputs(outputTargetIsItem, outputTargetName, outputs, parameterLocation, parameter);
}
else
{
ProjectErrorUtilities.ThrowInvalidProject(
parameterLocation,
"UnsupportedTaskParameterTypeError",
GetTaskParameterTypeName(parameter),
parameter.Name,
_taskName);
}
}
catch (InvalidOperationException e)
{
// handle invalid TaskItems in task outputs
_targetLoggingContext.LogError(
new BuildEventFileInfo(parameterLocation),
"InvalidTaskItemsInTaskOutputs",
_taskName,
parameterName,
e.Message);
gatheredGeneratedOutputsSuccessfully = false;
}
catch (TargetInvocationException e)
{
// handle any exception thrown by the task's getter
// Exception thrown by the called code itself
// Log the stack, so the task vendor can fix their code
// Log the task line number, whatever the value of ContinueOnError;
// because this will be a hard error anyway.
_targetLoggingContext.LogFatalTaskError(
e.InnerException,
new BuildEventFileInfo(parameterLocation),
_taskName);
// We do not recover from a task exception while getting outputs,
// so do not merely set gatheredGeneratedOutputsSuccessfully = false; here
ProjectErrorUtilities.ThrowInvalidProject(
parameterLocation,
"FailedToRetrieveTaskOutputs",
_taskName,
parameterName,
e.InnerException?.Message);
}
catch (Exception e) when (!ExceptionHandling.NotExpectedReflectionException(e))
{
ProjectErrorUtilities.ThrowInvalidProject(
parameterLocation,
"FailedToRetrieveTaskOutputs",
_taskName,
parameterName,
e.Message);
}
return gatheredGeneratedOutputsSuccessfully;
}
/// <summary>
/// Cleans up after running a batch.
/// </summary>
public void CleanupForBatch()
{
try
{
if (_taskFactoryWrapper != null && TaskInstance != null)
{
_taskFactoryWrapper.TaskFactory.CleanupTask(TaskInstance);
}
}
finally
{
TaskInstance = null;
}
}
/// <summary>
/// Cleans up after running the task.
/// </summary>
public void CleanupForTask()
{
#if FEATURE_APPDOMAIN
if (_resolver != null)
{
_resolver.RemoveHandler();
_resolver = null;
}
#endif
_taskFactoryWrapper = null;
// Clear the registered-task factory too, so it cannot leak into the next task that reuses this host.
_registeredTaskFactory = null;
// We must null this out because it could be a COM object (or any other ref-counted object) which needs to
// be released.
_taskHost = null;
CleanupCancellationToken();
Assumed.Null(TaskInstance, "Task Instance should be null");
}
/// <summary>
/// Executes the task.
/// </summary>
public bool Execute()
{
// If cancel is called before we get here, we simply don't execute and return failure. If cancel is called after this check
// the task needs to be able to handle the possibility that Cancel has been called before the task has done anything meaningful,
// and Execute may not even have been called yet.
_taskExecutionIdle.Reset();
if (_cancelled)
{
_taskExecutionIdle.Set();
return false;
}
bool taskReturnValue;
try
{
Debug.Assert(TaskInstance is not IMultiThreadableTask multiThreadableTask || multiThreadableTask.TaskEnvironment != null, "task environment missing for multi-threadable task");
taskReturnValue = TaskInstance.Execute();
}
finally
{
_taskExecutionIdle.Set();
}
return taskReturnValue;
}
#endregion
/// <summary>
/// Implementation of IDisposable
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_taskExecutionIdle.Dispose();
CleanupCancellationToken();
}
#if FEATURE_APPDOMAIN
// if we've been asked to remote these items then
// we need to disconnect them from .NET Remoting now we're all done with them
if (_remotedTaskItems != null)
{
foreach (TaskItem item in _remotedTaskItems)
{
// Tell remoting to forget connections to the taskitem
RemotingServices.Disconnect(item);
}
}
_remotedTaskItems = null;
#endif
}
/// <summary>
/// Disposes of the cancellation token registration.
/// </summary>
private void CleanupCancellationToken()
{
_cancellationTokenRegistration.Dispose();
}
/// <summary>
/// Cancels the currently-running task.
/// Kick off a task to wait for the currently-running task and log the wait message.
/// </summary>
private void Cancel()
{
// This will prevent the current and any future tasks from running on this TaskExecutionHost, because we don't reset the cancelled flag.
_cancelled = true;
ITask currentInstance = TaskInstance;
ICancelableTask cancellableTask = null;
if (currentInstance != null)
{
cancellableTask = currentInstance as ICancelableTask;
}
if (cancellableTask != null)
{
try
{
cancellableTask.Cancel();
}
catch (Exception e) when (!ExceptionHandling.IsCriticalException(e))
{
try
{
_taskLoggingContext.LogFatalTaskError(e, new BuildEventFileInfo(_taskLocation), ((ProjectTaskInstance)_taskLoggingContext.Task).Name);
}
// If this fails it could be due to the task logging context no longer being valid due to a race condition where the task completes while we
// are in this method. In that case we simply ignore the exception and carry on since we can't log anything anyhow.
catch (InternalErrorException) when (!_taskLoggingContext.IsValid)
{
}
}
}
// Let the task finish now. If cancellation worked, hopefully it finishes sooner than it would have otherwise.
// If the task builder crashed, this could have already been disposed
if (!_taskExecutionIdle.SafeWaitHandle.IsClosed)
{
// Kick off a task to log the message so that we don't block the calling thread.
Task.Run(async delegate
{
await _taskExecutionIdle.ToTask(CancelFirstWarningWaitInterval);
if (!_taskExecutionIdle.WaitOne(0))
{
DisplayCancelWaitMessage();
await _taskExecutionIdle.ToTask(CancelWarningWaitInterval);
while (!_taskExecutionIdle.WaitOne(0))
{
DisplayCancelWaitMessage();
await _taskExecutionIdle.ToTask(CancelWarningWaitInterval);
}
}
});
}
}
#region Local Methods
/// <summary>
/// Cache of compiled constructor delegates that wrap an <see cref="ITaskItem"/> into a
/// <see cref="TaskItem{T}"/>, keyed by the generic argument T. Building the closed generic type and
/// resolving the constructor via reflection on every parameter binding is expensive, so the delegate
/// is compiled once per T and reused.
/// </summary>
private static readonly ConcurrentDictionary<Type, Func<ITaskItem, ITaskItem>> s_taskItemOfTFactories = new();
/// <summary>
/// Wraps the given <paramref name="item"/> into a <c>TaskItem<T></c> where T is
/// <paramref name="genericArgument"/>, using a cached compiled constructor delegate.
/// </summary>
private static ITaskItem CreateTaskItemOfT(Type genericArgument, ITaskItem item)
{
Func<ITaskItem, ITaskItem> factory = s_taskItemOfTFactories.GetOrAdd(genericArgument, static t =>
{
#if NET
if (!RuntimeFeature.IsDynamicCodeSupported)
{
// Wrapping an ITaskItem into a closed-generic TaskItem<T> requires Type.MakeGenericType
// plus an expression-tree Compile(), both of which need runtime code generation. Fail
// observably under trimming / Native AOT rather than silently mis-binding the typed task
// parameter. (See documentation/aot/follow-up-work.md - the typed TaskItem<T> parameter
// feature still needs a proper AOT-safe binding strategy.)
throw new NotSupportedException(
"Task parameters typed as TaskItem<T> or ITaskItem<T> require runtime code generation " +
"(Type.MakeGenericType and expression compilation) and are not supported when MSBuild " +
"runs trimmed or with Native AOT.");
}
#endif
ConstructorInfo constructor = typeof(TaskItem<>).MakeGenericType(t).GetConstructor([typeof(ITaskItem)]);
ParameterExpression itemParameter = Expression.Parameter(typeof(ITaskItem), "item");
return Expression.Lambda<Func<ITaskItem, ITaskItem>>(
Expression.Convert(Expression.New(constructor, itemParameter), typeof(ITaskItem)),
itemParameter).Compile();
});
return factory(item);
}
/// <summary>
/// Called on the local side.
/// </summary>
private bool SetTaskItemParameter(TaskPropertyInfo parameter, ITaskItem item)
{
return InternalSetTaskParameter(parameter, item);
}
/// <summary>
/// Called on the local side.
/// </summary>
private bool SetValueParameter(TaskPropertyInfo parameter, Type parameterType, string expandedParameterValue)
{
return InternalSetTaskParameter(parameter, ConvertStringToParameterValue(expandedParameterValue, parameterType));
}
/// <summary>
/// Converts a single string value to an instance of <paramref name="targetType"/>, applying the same
/// conversions for both scalar parameters and the elements of array parameters.
/// </summary>
private object ConvertStringToParameterValue(string value, Type targetType)
{
// Path-like types are resolved through TaskEnvironment so the path is rooted consistently
// with the rest of the build before being handed to the task.
if (targetType == typeof(AbsolutePath))
{
return TaskEnvironment.GetAbsolutePath(value);
}
if (targetType == typeof(FileInfo))
{
return new FileInfo(TaskEnvironment.GetAbsolutePath(value).Value);
}
if (targetType == typeof(DirectoryInfo))
{
return new DirectoryInfo(TaskEnvironment.GetAbsolutePath(value).Value);
}
return ValueTypeParser.Parse(value, targetType);
}
/// <summary>