/
ManagedCompiler.cs
1230 lines (1072 loc) · 49.8 KB
/
ManagedCompiler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.CommandLine;
using Microsoft.Build.Tasks;
namespace Microsoft.CodeAnalysis.BuildTasks
{
/// <summary>
/// This class defines all of the common stuff that is shared between the Vbc and Csc tasks.
/// This class is not instantiatable as a Task just by itself.
/// </summary>
public abstract class ManagedCompiler : ManagedToolTask
{
private enum CompilationKind
{
/// <summary>
/// Compilation occurred using the command line tool by normal processes, typically because
/// the customer opted out of the compiler server
/// </summary>
Tool,
/// <summary>
/// Compilation occurred using the command line tool because the server was unable to complete
/// the request
/// </summary>
ToolFallback,
/// <summary>
/// Compilation occurred in the compiler server process
/// </summary>
Server,
/// <summary>
/// Fatal error caused compilation to not even occur.
/// </summary>
FatalError,
}
private CancellationTokenSource? _sharedCompileCts;
internal readonly PropertyDictionary _store = new PropertyDictionary();
internal abstract RequestLanguage Language { get; }
public ManagedCompiler()
: base(ErrorString.ResourceManager)
{
// If there is a crash, the runtime error is output to stderr and
// we want MSBuild to print it out regardless of verbosity.
LogStandardErrorAsError = true;
}
#region Properties
// Please keep these alphabetized.
public string[]? AdditionalLibPaths
{
set { _store[nameof(AdditionalLibPaths)] = value; }
get { return (string[]?)_store[nameof(AdditionalLibPaths)]; }
}
public string[]? AddModules
{
set { _store[nameof(AddModules)] = value; }
get { return (string[]?)_store[nameof(AddModules)]; }
}
public ITaskItem[]? AdditionalFiles
{
set { _store[nameof(AdditionalFiles)] = value; }
get { return (ITaskItem[]?)_store[nameof(AdditionalFiles)]; }
}
public ITaskItem[]? EmbeddedFiles
{
set { _store[nameof(EmbeddedFiles)] = value; }
get { return (ITaskItem[]?)_store[nameof(EmbeddedFiles)]; }
}
public bool EmbedAllSources
{
set { _store[nameof(EmbedAllSources)] = value; }
get { return _store.GetOrDefault(nameof(EmbedAllSources), false); }
}
public ITaskItem[]? Analyzers
{
set { _store[nameof(Analyzers)] = value; }
get { return (ITaskItem[]?)_store[nameof(Analyzers)]; }
}
// We do not support BugReport because it always requires user interaction,
// which will cause a hang.
public string? ChecksumAlgorithm
{
set { _store[nameof(ChecksumAlgorithm)] = value; }
get { return (string?)_store[nameof(ChecksumAlgorithm)]; }
}
public string? CodeAnalysisRuleSet
{
set { _store[nameof(CodeAnalysisRuleSet)] = value; }
get { return (string?)_store[nameof(CodeAnalysisRuleSet)]; }
}
public int CodePage
{
set { _store[nameof(CodePage)] = value; }
get { return _store.GetOrDefault(nameof(CodePage), 0); }
}
[Output]
public ITaskItem[]? CommandLineArgs
{
set { _store[nameof(CommandLineArgs)] = value; }
get { return (ITaskItem[]?)_store[nameof(CommandLineArgs)]; }
}
public string? DebugType
{
set { _store[nameof(DebugType)] = value; }
get { return (string?)_store[nameof(DebugType)]; }
}
public string? SourceLink
{
set { _store[nameof(SourceLink)] = value; }
get { return (string?)_store[nameof(SourceLink)]; }
}
public string? DefineConstants
{
set { _store[nameof(DefineConstants)] = value; }
get { return (string?)_store[nameof(DefineConstants)]; }
}
public bool DelaySign
{
set { _store[nameof(DelaySign)] = value; }
get { return _store.GetOrDefault(nameof(DelaySign), false); }
}
public bool Deterministic
{
set { _store[nameof(Deterministic)] = value; }
get { return _store.GetOrDefault(nameof(Deterministic), false); }
}
public bool PublicSign
{
set { _store[nameof(PublicSign)] = value; }
get { return _store.GetOrDefault(nameof(PublicSign), false); }
}
public ITaskItem[]? AnalyzerConfigFiles
{
set { _store[nameof(AnalyzerConfigFiles)] = value; }
get { return (ITaskItem[]?)_store[nameof(AnalyzerConfigFiles)]; }
}
public bool EmitDebugInformation
{
set { _store[nameof(EmitDebugInformation)] = value; }
get { return _store.GetOrDefault(nameof(EmitDebugInformation), false); }
}
public string? ErrorLog
{
set { _store[nameof(ErrorLog)] = value; }
get { return (string?)_store[nameof(ErrorLog)]; }
}
public string? Features
{
set { _store[nameof(Features)] = value; }
get { return (string?)_store[nameof(Features)]; }
}
public int FileAlignment
{
set { _store[nameof(FileAlignment)] = value; }
get { return _store.GetOrDefault(nameof(FileAlignment), 0); }
}
public string? GeneratedFilesOutputPath
{
set { _store[nameof(GeneratedFilesOutputPath)] = value; }
get { return (string?)_store[nameof(GeneratedFilesOutputPath)]; }
}
public bool HighEntropyVA
{
set { _store[nameof(HighEntropyVA)] = value; }
get { return _store.GetOrDefault(nameof(HighEntropyVA), false); }
}
/// <summary>
/// Specifies the list of instrumentation kinds to be used during compilation.
/// </summary>
public string? Instrument
{
set { _store[nameof(Instrument)] = value; }
get { return (string?)_store[nameof(Instrument)]; }
}
public string? KeyContainer
{
set { _store[nameof(KeyContainer)] = value; }
get { return (string?)_store[nameof(KeyContainer)]; }
}
public string? KeyFile
{
set { _store[nameof(KeyFile)] = value; }
get { return (string?)_store[nameof(KeyFile)]; }
}
public ITaskItem[]? LinkResources
{
set { _store[nameof(LinkResources)] = value; }
get { return (ITaskItem[]?)_store[nameof(LinkResources)]; }
}
public string? MainEntryPoint
{
set { _store[nameof(MainEntryPoint)] = value; }
get { return (string?)_store[nameof(MainEntryPoint)]; }
}
public bool NoConfig
{
set { _store[nameof(NoConfig)] = value; }
get { return _store.GetOrDefault(nameof(NoConfig), false); }
}
public bool NoLogo
{
set { _store[nameof(NoLogo)] = value; }
get { return _store.GetOrDefault(nameof(NoLogo), false); }
}
public bool NoWin32Manifest
{
set { _store[nameof(NoWin32Manifest)] = value; }
get { return _store.GetOrDefault(nameof(NoWin32Manifest), false); }
}
public bool Optimize
{
set { _store[nameof(Optimize)] = value; }
get { return _store.GetOrDefault(nameof(Optimize), false); }
}
[Output]
public ITaskItem? OutputAssembly
{
set { _store[nameof(OutputAssembly)] = value; }
get { return (ITaskItem?)_store[nameof(OutputAssembly)]; }
}
[Output]
public ITaskItem? OutputRefAssembly
{
set { _store[nameof(OutputRefAssembly)] = value; }
get { return (ITaskItem?)_store[nameof(OutputRefAssembly)]; }
}
public string? Platform
{
set { _store[nameof(Platform)] = value; }
get { return (string?)_store[nameof(Platform)]; }
}
public ITaskItem[]? PotentialAnalyzerConfigFiles
{
set { _store[nameof(PotentialAnalyzerConfigFiles)] = value; }
get { return (ITaskItem[]?)_store[nameof(PotentialAnalyzerConfigFiles)]; }
}
public bool Prefer32Bit
{
set { _store[nameof(Prefer32Bit)] = value; }
get { return _store.GetOrDefault(nameof(Prefer32Bit), false); }
}
public string? ProjectName
{
set { _store[nameof(ProjectName)] = value; }
get { return (string?)_store[nameof(ProjectName)]; }
}
public bool ProvideCommandLineArgs
{
set { _store[nameof(ProvideCommandLineArgs)] = value; }
get { return _store.GetOrDefault(nameof(ProvideCommandLineArgs), false); }
}
public ITaskItem[]? References
{
set { _store[nameof(References)] = value; }
get { return (ITaskItem[]?)_store[nameof(References)]; }
}
public bool RefOnly
{
set { _store[nameof(RefOnly)] = value; }
get { return _store.GetOrDefault(nameof(RefOnly), false); }
}
public bool ReportAnalyzer
{
set { _store[nameof(ReportAnalyzer)] = value; }
get { return _store.GetOrDefault(nameof(ReportAnalyzer), false); }
}
public ITaskItem[]? Resources
{
set { _store[nameof(Resources)] = value; }
get { return (ITaskItem[]?)_store[nameof(Resources)]; }
}
public string? RuntimeMetadataVersion
{
set { _store[nameof(RuntimeMetadataVersion)] = value; }
get { return (string?)_store[nameof(RuntimeMetadataVersion)]; }
}
public ITaskItem[]? ResponseFiles
{
set { _store[nameof(ResponseFiles)] = value; }
get { return (ITaskItem[]?)_store[nameof(ResponseFiles)]; }
}
public string? SharedCompilationId
{
set { _store[nameof(SharedCompilationId)] = value; }
get { return (string?)_store[nameof(SharedCompilationId)]; }
}
public bool SkipAnalyzers
{
set { _store[nameof(SkipAnalyzers)] = value; }
get { return _store.GetOrDefault(nameof(SkipAnalyzers), false); }
}
public bool SkipCompilerExecution
{
set { _store[nameof(SkipCompilerExecution)] = value; }
get { return _store.GetOrDefault(nameof(SkipCompilerExecution), false); }
}
public ITaskItem[]? Sources
{
set
{
if (UsedCommandLineTool)
{
NormalizePaths(value);
}
_store[nameof(Sources)] = value;
}
get { return (ITaskItem[]?)_store[nameof(Sources)]; }
}
public string? SubsystemVersion
{
set { _store[nameof(SubsystemVersion)] = value; }
get { return (string?)_store[nameof(SubsystemVersion)]; }
}
public string? TargetFramework
{
set { _store[nameof(TargetFramework)] = value; }
get { return (string?)_store[nameof(TargetFramework)]; }
}
public string? TargetType
{
set
{
_store[nameof(TargetType)] = value != null
? CultureInfo.InvariantCulture.TextInfo.ToLower(value)
: null;
}
get { return (string?)_store[nameof(TargetType)]; }
}
public bool TreatWarningsAsErrors
{
set { _store[nameof(TreatWarningsAsErrors)] = value; }
get { return _store.GetOrDefault(nameof(TreatWarningsAsErrors), false); }
}
public bool Utf8Output
{
set { _store[nameof(Utf8Output)] = value; }
get { return _store.GetOrDefault(nameof(Utf8Output), false); }
}
public string? Win32Icon
{
set { _store[nameof(Win32Icon)] = value; }
get { return (string?)_store[nameof(Win32Icon)]; }
}
public string? Win32Manifest
{
set { _store[nameof(Win32Manifest)] = value; }
get { return (string?)_store[nameof(Win32Manifest)]; }
}
public string? Win32Resource
{
set { _store[nameof(Win32Resource)] = value; }
get { return (string?)_store[nameof(Win32Resource)]; }
}
public string? PathMap
{
set { _store[nameof(PathMap)] = value; }
get { return (string?)_store[nameof(PathMap)]; }
}
/// <summary>
/// If this property is true then the task will take every C# or VB
/// compilation which is queued by MSBuild and send it to the
/// VBCSCompiler server instance, starting a new instance if necessary.
/// If false, we will use the values from ToolPath/Exe.
/// </summary>
public bool UseSharedCompilation
{
set { _store[nameof(UseSharedCompilation)] = value; }
get { return _store.GetOrDefault(nameof(UseSharedCompilation), false); }
}
// Map explicit platform of "AnyCPU" or the default platform (null or ""), since it is commonly understood in the
// managed build process to be equivalent to "AnyCPU", to platform "AnyCPU32BitPreferred" if the Prefer32Bit
// property is set.
internal string? PlatformWith32BitPreference
{
get
{
string? platform = Platform;
if ((RoslynString.IsNullOrEmpty(platform) || platform.Equals("anycpu", StringComparison.OrdinalIgnoreCase)) && Prefer32Bit)
{
platform = "anycpu32bitpreferred";
}
return platform;
}
}
/// <summary>
/// Overridable property specifying the encoding of the captured task standard output stream
/// </summary>
protected override Encoding StandardOutputEncoding
{
get
{
return (Utf8Output) ? Encoding.UTF8 : base.StandardOutputEncoding;
}
}
public string? LangVersion
{
set { _store[nameof(LangVersion)] = value; }
get { return (string?)_store[nameof(LangVersion)]; }
}
public bool ReportIVTs
{
set { _store[nameof(ReportIVTs)] = value; }
get { return _store.GetOrDefault(nameof(ReportIVTs), false); }
}
#endregion
/// <summary>
/// Method for testing only
/// </summary>
public string GeneratePathToTool()
{
return GenerateFullPathToTool();
}
protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands)
{
using var logger = new CompilerServerLogger($"MSBuild {Process.GetCurrentProcess().Id}");
return ExecuteTool(pathToTool, responseFileCommands, commandLineCommands, logger);
}
internal int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands, ICompilerServerLogger logger)
{
if (ProvideCommandLineArgs)
{
CommandLineArgs = GenerateCommandLineArgsTaskItems(responseFileCommands);
}
if (SkipCompilerExecution)
{
return 0;
}
try
{
var requestId = getRequestId();
logger.Log($"Compilation request {requestId}, PathToTool={pathToTool}");
string workingDirectory = CurrentDirectoryToUse();
string? tempDirectory = BuildServerConnection.GetTempPath(workingDirectory);
if (!UseSharedCompilation ||
!IsManagedTool ||
!BuildServerConnection.IsCompilerServerSupported)
{
LogCompilationMessage(logger, requestId, CompilationKind.Tool, $"using command line tool by design '{pathToTool}'");
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
_sharedCompileCts = new CancellationTokenSource();
logger.Log($"CommandLine = '{commandLineCommands}'");
logger.Log($"BuildResponseFile = '{responseFileCommands}'");
var clientDirectory = Path.GetDirectoryName(PathToManagedTool);
if (clientDirectory is null || tempDirectory is null)
{
LogCompilationMessage(logger, requestId, CompilationKind.Tool, $"using command line tool because we could not find client or temp directory '{PathToManagedTool}'");
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
// Note: using ToolArguments here (the property) since
// commandLineCommands (the parameter) may have been mucked with
// (to support using the dotnet cli)
var buildRequest = BuildServerConnection.CreateBuildRequest(
requestId,
Language,
GenerateCommandLineArgsList(responseFileCommands),
workingDirectory: workingDirectory,
tempDirectory: tempDirectory,
keepAlive: null,
libDirectory: LibDirectoryToUse());
var pipeName = !string.IsNullOrEmpty(SharedCompilationId)
? SharedCompilationId
: BuildServerConnection.GetPipeName(clientDirectory);
var responseTask = BuildServerConnection.RunServerBuildRequestAsync(
buildRequest,
pipeName,
clientDirectory,
logger: logger,
cancellationToken: _sharedCompileCts.Token);
responseTask.Wait(_sharedCompileCts.Token);
ExitCode = HandleResponse(requestId, responseTask.Result, pathToTool, responseFileCommands, commandLineCommands, logger);
}
catch (OperationCanceledException)
{
ExitCode = 0;
}
catch (Exception e)
{
Log.LogErrorWithCodeFromResources("Compiler_UnexpectedException");
Log.LogErrorFromException(e);
ExitCode = -1;
}
finally
{
_sharedCompileCts?.Dispose();
_sharedCompileCts = null;
}
return ExitCode;
// Construct the friendly name for the compilation. This does not need to be unique. Instead
// it's used by developers to understand what compilation is running on the server.
string getRequestId()
{
if (!string.IsNullOrEmpty(ProjectName))
{
return string.IsNullOrEmpty(TargetFramework)
? ProjectName
: $"{ProjectName} ({TargetFramework})";
}
return $"Unnamed compilation {Guid.NewGuid()}";
}
}
/// <summary>
/// Cancel the in-process build task.
/// </summary>
public override void Cancel()
{
// This must be cancelled first. Otherwise we risk that MSBuild cancellation logic will take down
// our pipes and tasks in an order we're not expecting.
_sharedCompileCts?.Cancel();
base.Cancel();
}
/// <summary>
/// Get the current directory that the compiler should run in.
/// </summary>
private string CurrentDirectoryToUse()
{
// ToolTask has a method for this. But it may return null. Use the process directory
// if ToolTask didn't override. MSBuild uses the process directory.
string workingDirectory = GetWorkingDirectory();
if (string.IsNullOrEmpty(workingDirectory))
{
workingDirectory = Directory.GetCurrentDirectory();
}
return workingDirectory;
}
/// <summary>
/// Get the "LIB" environment variable, or NULL if none.
/// </summary>
private string? LibDirectoryToUse()
{
// First check the real environment.
string? libDirectory = Environment.GetEnvironmentVariable("LIB");
// Now go through additional environment variables.
string[] additionalVariables = EnvironmentVariables;
if (additionalVariables != null)
{
foreach (string var in EnvironmentVariables)
{
if (var.StartsWith("LIB=", StringComparison.OrdinalIgnoreCase))
{
libDirectory = var.Substring(4);
}
}
}
return libDirectory;
}
/// <summary>
/// The return code of the compilation. Strangely, this isn't overridable from ToolTask, so we need
/// to create our own.
/// </summary>
[Output]
public new int ExitCode { get; private set; }
/// <summary>
/// Handle a response from the server, reporting messages and returning
/// the appropriate exit code.
/// </summary>
private int HandleResponse(string requestId, BuildResponse? response, string pathToTool, string responseFileCommands, string commandLineCommands, ICompilerServerLogger logger)
{
#if BOOTSTRAP
if (!ValidateBootstrapResponse(response))
{
return 1;
}
#endif
if (response is null)
{
LogCompilationMessage(logger, requestId, CompilationKind.ToolFallback, "could not launch server");
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
switch (response.Type)
{
case BuildResponse.ResponseType.Completed:
var completedResponse = (CompletedBuildResponse)response;
LogCompilerOutput(completedResponse.Output, StandardOutputImportanceToUse);
LogCompilationMessage(logger, requestId, CompilationKind.Server, "server processed compilation");
return completedResponse.ReturnCode;
case BuildResponse.ResponseType.MismatchedVersion:
LogCompilationMessage(logger, requestId, CompilationKind.FatalError, "server reports different protocol version than build task");
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
case BuildResponse.ResponseType.IncorrectHash:
LogCompilationMessage(logger, requestId, CompilationKind.FatalError, "server reports different hash version than build task");
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
case BuildResponse.ResponseType.CannotConnect:
LogCompilationMessage(logger, requestId, CompilationKind.ToolFallback, $"cannot connect to the server");
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
case BuildResponse.ResponseType.Rejected:
var rejectedResponse = (RejectedBuildResponse)response;
LogCompilationMessage(logger, requestId, CompilationKind.ToolFallback, $"server rejected the request '{rejectedResponse.Reason}'");
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
case BuildResponse.ResponseType.AnalyzerInconsistency:
var analyzerResponse = (AnalyzerInconsistencyBuildResponse)response;
var combinedMessage = string.Join(", ", analyzerResponse.ErrorMessages.ToArray());
LogCompilationMessage(logger, requestId, CompilationKind.ToolFallback, $"server rejected the request due to analyzer / generator issues '{combinedMessage}'");
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
default:
LogCompilationMessage(logger, requestId, CompilationKind.ToolFallback, $"server gave an unrecognized response");
return base.ExecuteTool(pathToTool, responseFileCommands, commandLineCommands);
}
}
#if BOOTSTRAP
#pragma warning disable IDE0044
/// <summary>
/// Keeps track of the number of times the task failed to connect to the compiler
/// server. Even in valid builds this can be greater than zero (connect is
/// inherently a race condition). If this gets too high though in a bootstrap build
/// it's evidence of a bigger issue the team should be looking at.
/// </summary>
private static int s_connectFailedCount;
#pragma warning restore IDE0044
/// <summary>
/// In bootstrap builds this validates the response. When this returns false it
/// indicates the bootstrap build is incorrect and the compilation should fail.
/// </summary>
private bool ValidateBootstrapResponse(BuildResponse? response)
{
// This represents the maximum number of failed connection attempts on the server before we will declare
// that the overall build itself failed. Keeping this at zero is not realistic because even in a fully
// functioning server connection failures are expected. The server could be too busy to accept connections
// fast enough. Anything above this count though is considered worth investigating by the compiler team.
//
const int maxCannotConnectCount = 2;
var responseType = response?.Type ?? BuildResponse.ResponseType.CannotConnect;
switch (responseType)
{
case BuildResponse.ResponseType.AnalyzerInconsistency:
Log.LogError($"Analyzer inconsistency building");
return false;
case BuildResponse.ResponseType.MismatchedVersion:
case BuildResponse.ResponseType.IncorrectHash:
Log.LogError($"Critical error {responseType} when building");
return false;
case BuildResponse.ResponseType.Rejected:
Log.LogError($"Compiler request rejected: {((RejectedBuildResponse)response!).Reason}");
return false;
case BuildResponse.ResponseType.CannotConnect:
if (Interlocked.Increment(ref s_connectFailedCount) > maxCannotConnectCount)
{
Log.LogError("Too many errors connecting to the server");
return false;
}
return true;
case BuildResponse.ResponseType.Completed:
case BuildResponse.ResponseType.Shutdown:
// Expected messages
break;
default:
Log.LogError($"Unexpected response type {responseType}");
return false;
}
return true;
}
#endif
/// <summary>
/// Log the compiler output to MSBuild. Each language will override this to parse their output and log it
/// in the language specific manner. This often involves parsing the raw output and formatting it as
/// individual messages for MSBuild.
/// </summary>
/// <remarks>
/// Internal for testing only.
/// </remarks>
internal abstract void LogCompilerOutput(string output, MessageImportance messageImportance);
/// <summary>
/// Used to log a message that should go into both the compiler server log as well as the MSBuild logs
///
/// These are intended to be processed by automation in the binlog hence do not change the structure of
/// the messages here.
/// </summary>
private void LogCompilationMessage(ICompilerServerLogger logger, string requestId, CompilationKind kind, string diagnostic)
{
var category = kind switch
{
CompilationKind.Server => "server",
CompilationKind.Tool => "tool",
CompilationKind.ToolFallback => "server failed",
CompilationKind.FatalError => "fatal error",
_ => throw new Exception($"Unexpected value {kind}"),
};
var message = $"CompilerServer: {category} - {diagnostic} - {requestId}";
if (kind == CompilationKind.FatalError)
{
logger.LogError(message);
Log.LogError(message);
}
else
{
logger.Log(message);
Log.LogMessage(message);
}
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can't go into a response file and
/// must go directly onto the command line.
/// </summary>
protected override void AddCommandLineCommands(CommandLineBuilderExtension commandLine)
{
commandLine.AppendWhenTrue("/noconfig", _store, nameof(NoConfig));
}
/// <summary>
/// Fills the provided CommandLineBuilderExtension with those switches and other information that can go into a response file.
/// </summary>
protected override void AddResponseFileCommands(CommandLineBuilderExtension commandLine)
{
// If outputAssembly is not specified, then an "/out: <name>" option won't be added to
// overwrite the one resulting from the OutputAssembly member of the CompilerParameters class.
// In that case, we should set the outputAssembly member based on the first source file.
if (
(OutputAssembly == null) &&
(Sources != null) &&
(Sources.Length > 0) &&
(ResponseFiles == null) // The response file may already have a /out: switch in it, so don't try to be smart here.
)
{
try
{
OutputAssembly = new TaskItem(Path.GetFileNameWithoutExtension(Sources[0].ItemSpec));
}
catch (ArgumentException e)
{
throw new ArgumentException(e.Message, "Sources");
}
if (string.Compare(TargetType, "library", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".dll";
}
else if (string.Compare(TargetType, "module", StringComparison.OrdinalIgnoreCase) == 0)
{
OutputAssembly.ItemSpec += ".netmodule";
}
else
{
OutputAssembly.ItemSpec += ".exe";
}
}
commandLine.AppendSwitchIfNotNull("/addmodule:", AddModules, ",");
commandLine.AppendSwitchWithInteger("/codepage:", _store, nameof(CodePage));
ConfigureDebugProperties();
// The "DebugType" parameter should be processed after the "EmitDebugInformation" parameter
// because it's more specific. Order matters on the command-line, and the last one wins.
// /debug+ is just a shorthand for /debug:full. And /debug- is just a shorthand for /debug:none.
commandLine.AppendPlusOrMinusSwitch("/debug", _store, nameof(EmitDebugInformation));
commandLine.AppendSwitchIfNotNull("/debug:", DebugType);
commandLine.AppendPlusOrMinusSwitch("/delaysign", _store, nameof(DelaySign));
commandLine.AppendWhenTrue("/reportivts", _store, nameof(ReportIVTs));
commandLine.AppendSwitchWithInteger("/filealign:", _store, nameof(FileAlignment));
commandLine.AppendSwitchIfNotNull("/generatedfilesout:", GeneratedFilesOutputPath);
commandLine.AppendSwitchIfNotNull("/keycontainer:", KeyContainer);
commandLine.AppendSwitchIfNotNull("/keyfile:", KeyFile);
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/linkresource:", LinkResources, new string[] { "LogicalName", "Access" });
commandLine.AppendWhenTrue("/nologo", _store, nameof(NoLogo));
commandLine.AppendWhenTrue("/nowin32manifest", _store, nameof(NoWin32Manifest));
commandLine.AppendPlusOrMinusSwitch("/optimize", _store, nameof(Optimize));
commandLine.AppendSwitchIfNotNull("/pathmap:", PathMap);
commandLine.AppendSwitchIfNotNull("/out:", OutputAssembly);
commandLine.AppendSwitchIfNotNull("/refout:", OutputRefAssembly);
commandLine.AppendWhenTrue("/refonly", _store, nameof(RefOnly));
commandLine.AppendSwitchIfNotNull("/ruleset:", CodeAnalysisRuleSet);
commandLine.AppendSwitchIfNotNull("/errorlog:", ErrorLog);
commandLine.AppendSwitchIfNotNull("/subsystemversion:", SubsystemVersion);
commandLine.AppendWhenTrue("/reportanalyzer", _store, nameof(ReportAnalyzer));
// If the strings "LogicalName" or "Access" ever change, make sure to search/replace everywhere in vsproject.
commandLine.AppendSwitchIfNotNull("/resource:", Resources, new string[] { "LogicalName", "Access" });
commandLine.AppendSwitchIfNotNull("/target:", TargetType);
commandLine.AppendPlusOrMinusSwitch("/warnaserror", _store, nameof(TreatWarningsAsErrors));
commandLine.AppendWhenTrue("/utf8output", _store, nameof(Utf8Output));
commandLine.AppendSwitchIfNotNull("/win32icon:", Win32Icon);
commandLine.AppendSwitchIfNotNull("/win32manifest:", Win32Manifest);
AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(commandLine);
AddAnalyzersToCommandLine(commandLine, Analyzers);
AddAdditionalFilesToCommandLine(commandLine);
// Append the sources.
commandLine.AppendFileNamesIfNotNull(Sources, " ");
}
internal void AddResponseFileCommandsForSwitchesSinceInitialReleaseThatAreNeededByTheHost(CommandLineBuilderExtension commandLine)
{
commandLine.AppendPlusOrMinusSwitch("/deterministic", _store, nameof(Deterministic));
commandLine.AppendPlusOrMinusSwitch("/publicsign", _store, nameof(PublicSign));
commandLine.AppendSwitchIfNotNull("/runtimemetadataversion:", RuntimeMetadataVersion);
commandLine.AppendSwitchIfNotNull("/checksumalgorithm:", ChecksumAlgorithm);
commandLine.AppendSwitchWithSplitting("/instrument:", Instrument, ",", ';', ',');
commandLine.AppendSwitchIfNotNull("/sourcelink:", SourceLink);
commandLine.AppendSwitchIfNotNull("/langversion:", LangVersion);
commandLine.AppendPlusOrMinusSwitch("/skipanalyzers", _store, nameof(SkipAnalyzers));
AddFeatures(commandLine, Features);
AddEmbeddedFilesToCommandLine(commandLine);
AddAnalyzerConfigFilesToCommandLine(commandLine);
}
/// <summary>
/// Adds a "/features:" switch to the command line for each provided feature.
/// </summary>
internal static void AddFeatures(CommandLineBuilderExtension commandLine, string? features)
{
if (RoslynString.IsNullOrEmpty(features))
{
return;
}
foreach (var feature in CompilerOptionParseUtilities.ParseFeatureFromMSBuild(features))
{
commandLine.AppendSwitchIfNotNull("/features:", feature.Trim());
}
}
/// <summary>
/// Adds a "/analyzer:" switch to the command line for each provided analyzer.
/// </summary>
internal static void AddAnalyzersToCommandLine(CommandLineBuilderExtension commandLine, ITaskItem[]? analyzers)
{
// If there were no analyzers passed in, don't add any /analyzer: switches
// on the command-line.
if (analyzers == null)
{
return;
}
foreach (ITaskItem analyzer in analyzers)
{
commandLine.AppendSwitchIfNotNull("/analyzer:", analyzer.ItemSpec);
}
}
/// <summary>
/// Adds a "/additionalfile:" switch to the command line for each additional file.
/// </summary>
private void AddAdditionalFilesToCommandLine(CommandLineBuilderExtension commandLine)
{
if (AdditionalFiles != null)
{
foreach (ITaskItem additionalFile in AdditionalFiles)
{
commandLine.AppendSwitchIfNotNull("/additionalfile:", additionalFile.ItemSpec);
}
}
}
/// <summary>
/// Adds a "/embed:" switch to the command line for each pdb embedded file.
/// </summary>
private void AddEmbeddedFilesToCommandLine(CommandLineBuilderExtension commandLine)
{
if (EmbedAllSources)
{
commandLine.AppendSwitch("/embed");
}
if (EmbeddedFiles != null)
{
foreach (ITaskItem embeddedFile in EmbeddedFiles)
{
commandLine.AppendSwitchIfNotNull("/embed:", embeddedFile.ItemSpec);
}
}
}
/// <summary>
/// Adds a "/editorconfig:" switch to the command line for each .editorconfig file.
/// </summary>
private void AddAnalyzerConfigFilesToCommandLine(CommandLineBuilderExtension commandLine)