-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathTaskExecutionHost.cs
1660 lines (1470 loc) · 68 KB
/
TaskExecutionHost.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.Globalization;
using System.Reflection;
#if FEATURE_APPDOMAIN
using System.Runtime.Remoting;
#endif
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Build.BackEnd.Logging;
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 Microsoft.Build.Utilities;
using TaskItem = Microsoft.Build.Execution.ProjectItemInstance.TaskItem;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.Build.BackEnd
{
/// <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 : ITaskExecutionHost, 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 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>
/// 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);
/// <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;
}
}
/// <summary>
/// Constructor, for unit testing only.
/// </summary>
internal TaskExecutionHost()
{
// do nothing
}
/// <summary>
/// Finalizer
/// </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>
ProjectInstance ITaskExecutionHost.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;
}
#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>
void ITaskExecutionHost.InitializeForTask(IBuildEngine2 buildEngine, TargetLoggingContext loggingContext, ProjectInstance projectInstance, string taskName, ElementLocation taskLocation, ITaskHost taskHost, bool continueOnError,
#if FEATURE_APPDOMAIN
AppDomainSetup appDomainSetup,
#endif
bool isOutOfProc, CancellationToken cancellationToken)
{
_buildEngine = buildEngine;
_projectInstance = projectInstance;
_targetLoggingContext = loggingContext;
_taskName = taskName;
_taskLocation = taskLocation;
_cancellationTokenRegistration = cancellationToken.Register(Cancel);
_taskHost = taskHost;
_taskExecutionIdle.Set();
#if FEATURE_APPDOMAIN
AppDomainSetup = appDomainSetup;
#endif
IsOutOfProc = isOutOfProc;
}
/// <summary>
/// Ask the task host to find its task in the registry and get it ready for initializing the batch
/// </summary>
/// <returns>True if the task is found in the task registry false if otherwise.</returns>
TaskRequirements? ITaskExecutionHost.FindTask(IDictionary<string, string> taskIdentityParameters)
{
if (_taskFactoryWrapper == null)
{
_taskFactoryWrapper = FindTaskInRegistry(taskIdentityParameters);
}
if (_taskFactoryWrapper == null)
{
return null;
}
TaskRequirements requirements = TaskRequirements.None;
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;
}
/// <summary>
/// Initialize to run a specific batch of the current task.
/// </summary>
bool ITaskExecutionHost.InitializeForBatch(TaskLoggingContext loggingContext, ItemBucket batchBucket, IDictionary<string, string> taskIdentityParameters)
{
ErrorUtilities.VerifyThrowArgumentNull(loggingContext, nameof(loggingContext));
ErrorUtilities.VerifyThrowArgumentNull(batchBucket, nameof(batchBucket));
_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.
if (_resolver == null)
{
_resolver = new TaskEngineAssemblyResolver();
_resolver.Initialize(_taskFactoryWrapper.TaskFactoryLoadedType.Assembly.AssemblyFile);
_resolver.InstallHandler();
}
#endif
// We instantiate a new task object for each batch
TaskInstance = InstantiateTask(taskIdentityParameters);
if (TaskInstance == null)
{
return false;
}
TaskInstance.BuildEngine = _buildEngine;
TaskInstance.HostObject = _taskHost;
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>
bool ITaskExecutionHost.SetTaskParameters(IDictionary<string, (string, ElementLocation)> parameters)
{
ErrorUtilities.VerifyThrowArgumentNull(parameters, nameof(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);
IDictionary<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) // Catching Exception, but rethrowing unless it's a well-known exception.
{
if (ExceptionHandling.NotExpectedReflectionException(e))
{
throw;
}
// 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 (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>
bool ITaskExecutionHost.GatherTaskOutputs(string parameterName, ElementLocation parameterLocation, bool outputTargetIsItem, string outputTargetName)
{
ErrorUtilities.VerifyThrow(_taskFactoryWrapper != null, "Need a taskFactoryWrapper to retrieve outputs from.");
bool gatheredGeneratedOutputsSuccessfully = true;
try
{
TaskPropertyInfo parameter = _taskFactoryWrapper.GetProperty(parameterName);
// 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
);
// grab the outputs from the task's designated output parameter (which is a .NET property)
Type type = parameter.PropertyType;
EnsureParameterInitialized(parameter, _batchBucket.Lookup);
if (TaskParameterTypeVerifier.IsAssignableToITask(type))
{
ITaskItem[] outputs = GetItemOutputs(parameter);
GatherTaskItemOutputs(outputTargetIsItem, outputTargetName, outputs, parameterLocation, parameter);
}
else if (TaskParameterTypeVerifier.IsValueTypeOutputParameter(type))
{
string[] outputs = GetValueOutputs(parameter);
GatherArrayStringAndValueOutputs(outputTargetIsItem, outputTargetName, outputs, parameterLocation, parameter);
}
else
{
ProjectErrorUtilities.VerifyThrowInvalidProject
(
false,
parameterLocation,
"UnsupportedTaskParameterTypeError",
parameter.PropertyType.FullName,
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.VerifyThrowInvalidProject
(
false,
parameterLocation,
"FailedToRetrieveTaskOutputs",
_taskName,
parameterName,
e.InnerException?.Message
);
}
catch (Exception e)
{
// Catching Exception, but rethrowing unless it's a well-known exception.
if (ExceptionHandling.NotExpectedReflectionException(e))
{
throw;
}
ProjectErrorUtilities.VerifyThrowInvalidProject
(
false,
parameterLocation,
"FailedToRetrieveTaskOutputs",
_taskName,
parameterName,
e.Message
);
}
return gatheredGeneratedOutputsSuccessfully;
}
/// <summary>
/// Cleans up after running a batch.
/// </summary>
void ITaskExecutionHost.CleanupForBatch()
{
try
{
if (_taskFactoryWrapper != null && TaskInstance != null)
{
_taskFactoryWrapper.TaskFactory.CleanupTask(TaskInstance);
}
}
finally
{
TaskInstance = null;
}
}
/// <summary>
/// Cleans up after running the task.
/// </summary>
void ITaskExecutionHost.CleanupForTask()
{
#if FEATURE_APPDOMAIN
if (_resolver != null)
{
_resolver.RemoveHandler();
_resolver = null;
}
#endif
_taskFactoryWrapper = 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();
ErrorUtilities.VerifyThrow(TaskInstance == null, "Task Instance should be null");
}
/// <summary>
/// Executes the task.
/// </summary>
bool ITaskExecutionHost.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
{
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)
{
if (ExceptionHandling.IsCriticalException(e))
{
throw;
}
try
{
_taskLoggingContext.LogFatalTaskError(e, new BuildEventFileInfo(_taskLocation), ((ProjectTaskInstance)_taskLoggingContext.Task).Name);
}
catch (InternalErrorException)
{
// 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.
if (_taskLoggingContext.IsValid)
{
throw;
}
}
}
}
// 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 FEATURE_HANDLE_SAFEWAITHANDLE
if (!_taskExecutionIdle.SafeWaitHandle.IsClosed)
#else
if (!_taskExecutionIdle.GetSafeWaitHandle().IsClosed)
#endif
{
// 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>
/// 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)
{
if (parameterType == typeof(bool))
{
// Convert the string to the appropriate datatype, and set the task's parameter.
return InternalSetTaskParameter(parameter, ConversionUtilities.ConvertStringToBool(expandedParameterValue));
}
else if (parameterType == typeof(string))
{
return InternalSetTaskParameter(parameter, expandedParameterValue);
}
else
{
return InternalSetTaskParameter(parameter, Convert.ChangeType(expandedParameterValue, parameterType, CultureInfo.InvariantCulture));
}
}
/// <summary>
/// Called on the local side.
/// </summary>
private bool SetParameterArray(TaskPropertyInfo parameter, Type parameterType, IList<TaskItem> taskItems, ElementLocation parameterLocation)
{
TaskItem currentItem = null;
try
{
// Loop through all the TaskItems in our arraylist, and convert them.
ArrayList finalTaskInputs = new ArrayList(taskItems.Count);
if (parameterType != typeof(ITaskItem[]))
{
foreach (TaskItem item in taskItems)
{
currentItem = item;
if (parameterType == typeof(string[]))
{
finalTaskInputs.Add(item.ItemSpec);
}
else if (parameterType == typeof(bool[]))
{
finalTaskInputs.Add(ConversionUtilities.ConvertStringToBool(item.ItemSpec));
}
else
{
finalTaskInputs.Add(Convert.ChangeType(item.ItemSpec, parameterType.GetElementType(), CultureInfo.InvariantCulture));
}
}
}
else
{
foreach (TaskItem item in taskItems)
{
// if we've been asked to remote these items then
// remember them so we can disconnect them from remoting later
RecordItemForDisconnectIfNecessary(item);
finalTaskInputs.Add(item);
}
}
return InternalSetTaskParameter(parameter, finalTaskInputs.ToArray(parameterType.GetElementType()));
}
catch (Exception ex)
{
if (ex is InvalidCastException || // invalid type
ex is ArgumentException || // can't convert to bool
ex is FormatException || // bad string representation of a type
ex is OverflowException) // overflow when converting string representation of a numerical type
{
ProjectErrorUtilities.ThrowInvalidProject
(
parameterLocation,
"InvalidTaskParameterValueError",
currentItem.ItemSpec,
parameter.Name,
parameterType.FullName,
_taskName
);
}
throw;
}
}
/// <summary>
/// Remember this TaskItem so that we can disconnect it when this Task has finished executing
/// Only if we're passing TaskItems to another AppDomain is this necessary. This call
/// Will make that determination for you.
/// </summary>
private void RecordItemForDisconnectIfNecessary(TaskItem item)
{
// remember that we need to disconnect this item
_remotedTaskItems?.Add(item);
}
/// <summary>
/// Gets the outputs (as an array of ITaskItem) from the specified output parameter.
/// </summary>
private ITaskItem[] GetItemOutputs(TaskPropertyInfo parameter)
{
object outputs = _taskFactoryWrapper.GetPropertyValue(TaskInstance, parameter);
if (!(outputs is ITaskItem[] taskItemOutputs))
{
taskItemOutputs = new[] { (ITaskItem)outputs };
}
return taskItemOutputs;
}
/// <summary>
/// Gets the outputs (as an array of string values) from the specified output parameter.
/// </summary>
private string[] GetValueOutputs(TaskPropertyInfo parameter)
{
object outputs = _taskFactoryWrapper.GetPropertyValue(TaskInstance, parameter);
Array convertibleOutputs = parameter.PropertyType.IsArray ? (Array)outputs : new[] { outputs };
if (convertibleOutputs == null)
{
return null;
}
var stringOutputs = new string[convertibleOutputs.Length];
for (int i = 0; i < convertibleOutputs.Length; i++)
{
object output = convertibleOutputs.GetValue(i);
if (output != null)
{
stringOutputs[i] = (string)Convert.ChangeType(output, typeof(string), CultureInfo.InvariantCulture);
}
}
return stringOutputs;
}
#endregion
/// <summary>
/// Given the task name, this method tries to find the task. It uses the following search order:
/// 1) checks the tasks declared by the project, searching by exact name and task identity parameters
/// 2) checks the global task declarations (in *.TASKS in MSbuild bin dir), searching by exact name and task identity parameters
/// 3) checks the tasks declared by the project, searching by fuzzy match (missing namespace, etc.) and task identity parameters
/// 4) checks the global task declarations (in *.TASKS in MSbuild bin dir), searching by fuzzy match (missing namespace, etc.) and task identity parameters
/// 5) 1-4 again in order without the task identity parameters, to gather additional information for the user (if the task identity
/// parameters don't match, it is an error, but at least we can return them a more useful error in this case than just "could not
/// find task")
///
/// The search ordering is meant to reduce the number of assemblies we scan, because loading assemblies can be expensive.
/// The tasks and assemblies declared by the project are scanned first, on the assumption that if the project declared
/// them, they are likely used.
///
/// If the set of task identity parameters are defined, only tasks that match that identity are chosen.
/// </summary>
/// <returns>The Type of the task, or null if it was not found.</returns>
private TaskFactoryWrapper FindTaskInRegistry(IDictionary<string, string> taskIdentityParameters)
{
if (!_intrinsicTasks.TryGetValue(_taskName, out TaskFactoryWrapper returnClass))
{
returnClass = _projectInstance.TaskRegistry.GetRegisteredTask(_taskName, null, taskIdentityParameters, true /* exact match */, _targetLoggingContext, _taskLocation);
if (returnClass == null)
{
returnClass = _projectInstance.TaskRegistry.GetRegisteredTask(_taskName, null, taskIdentityParameters, false /* fuzzy match */, _targetLoggingContext, _taskLocation);
if (returnClass == null)
{
returnClass = _projectInstance.TaskRegistry.GetRegisteredTask(_taskName, null, null, true /* exact match */, _targetLoggingContext, _taskLocation);
if (returnClass == null)
{
returnClass = _projectInstance.TaskRegistry.GetRegisteredTask(_taskName, null, null, false /* fuzzy match */, _targetLoggingContext, _taskLocation);
if (returnClass == null)
{
_targetLoggingContext.LogError
(
new BuildEventFileInfo(_taskLocation),
"MissingTaskError",
_taskName,
_projectInstance.TaskRegistry.Toolset.ToolsPath
);
return null;
}
}
string usingTaskRuntime = null;
string usingTaskArchitecture = null;
if (returnClass.FactoryIdentityParameters != null)
{
returnClass.FactoryIdentityParameters.TryGetValue(XMakeAttributes.runtime, out usingTaskRuntime);
returnClass.FactoryIdentityParameters.TryGetValue(XMakeAttributes.architecture, out usingTaskArchitecture);
}
taskIdentityParameters.TryGetValue(XMakeAttributes.runtime, out string taskRuntime);
taskIdentityParameters.TryGetValue(XMakeAttributes.architecture, out string taskArchitecture);
_targetLoggingContext.LogError
(
new BuildEventFileInfo(_taskLocation),
"TaskExistsButHasMismatchedIdentityError",
_taskName,
usingTaskRuntime ?? XMakeAttributes.MSBuildRuntimeValues.any,
usingTaskArchitecture ?? XMakeAttributes.MSBuildArchitectureValues.any,
taskRuntime ?? XMakeAttributes.MSBuildRuntimeValues.any,
taskArchitecture ?? XMakeAttributes.MSBuildArchitectureValues.any
);
// if we've logged this error, even though we've found something, we want to act like we didn't.
return null;
}
}
// Map to an intrinsic task, if necessary.
if (String.Equals(returnClass.TaskFactory.TaskType.FullName, "Microsoft.Build.Tasks.MSBuild", StringComparison.OrdinalIgnoreCase))
{
returnClass = new TaskFactoryWrapper(new IntrinsicTaskFactory(typeof(MSBuild)), new LoadedType(typeof(MSBuild), AssemblyLoadInfo.Create(typeof(TaskExecutionHost).GetTypeInfo().Assembly.FullName, null)), _taskName, null);
_intrinsicTasks[_taskName] = returnClass;
}
else if (String.Equals(returnClass.TaskFactory.TaskType.FullName, "Microsoft.Build.Tasks.CallTarget", StringComparison.OrdinalIgnoreCase))
{
returnClass = new TaskFactoryWrapper(new IntrinsicTaskFactory(typeof(CallTarget)), new LoadedType(typeof(CallTarget), AssemblyLoadInfo.Create(typeof(TaskExecutionHost).GetTypeInfo().Assembly.FullName, null)), _taskName, null);
_intrinsicTasks[_taskName] = returnClass;
}
}
return returnClass;
}
/// <summary>
/// Instantiates the task.
/// </summary>
private ITask InstantiateTask(IDictionary<string, string> taskIdentityParameters)
{
ITask task = null;
try
{
if (_taskFactoryWrapper.TaskFactory is AssemblyTaskFactory assemblyTaskFactory)
{
task = assemblyTaskFactory.CreateTaskInstance(_taskLocation, _taskLoggingContext, _buildComponentHost, taskIdentityParameters,
#if FEATURE_APPDOMAIN
AppDomainSetup,
#endif
IsOutOfProc);
}
else
{
TaskFactoryLoggingHost loggingHost = new TaskFactoryLoggingHost(_buildEngine.IsRunningMultipleNodes, _taskLocation, _taskLoggingContext);
ITaskFactory2 taskFactory2 = _taskFactoryWrapper.TaskFactory as ITaskFactory2;
try
{
if (taskFactory2 == null)
{
task = _taskFactoryWrapper.TaskFactory.CreateTask(loggingHost);
}
else
{
task = taskFactory2.CreateTask(loggingHost, taskIdentityParameters);
}
}
finally
{
#if FEATURE_APPDOMAIN
loggingHost.MarkAsInactive();
#endif
}
}
}
catch (InvalidCastException e)
{
_taskLoggingContext.LogError
(
new BuildEventFileInfo(_taskLocation),
"TaskInstantiationFailureErrorInvalidCast",
_taskName,
_taskFactoryWrapper.TaskFactory.FactoryName,
e.Message
);
}
catch (TargetInvocationException e)
{
// Exception thrown by the called code itself
// Log the stack, so the task vendor can fix their code
_taskLoggingContext.LogError
(
new BuildEventFileInfo(_taskLocation),
"TaskInstantiationFailureError",
_taskName,
_taskFactoryWrapper.TaskFactory.FactoryName,
Environment.NewLine + e.InnerException