-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathSGen.cs
More file actions
464 lines (382 loc) · 16.1 KB
/
SGen.cs
File metadata and controls
464 lines (382 loc) · 16.1 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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if !RUNTIME_TYPE_NETCORE
using System;
using System.IO;
using System.Diagnostics;
#endif
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
#if !RUNTIME_TYPE_NETCORE
using Microsoft.Build.Shared.FileSystem;
using Microsoft.Build.Utilities;
#endif
#nullable disable
namespace Microsoft.Build.Tasks
{
/// <summary>
/// An interface containing public SGen task properties to make sure that all versions of the task have the same public surface.
/// </summary>
internal interface ISGenTaskContract
{
#region Properties
// Input files
[Required]
string BuildAssemblyName { get; set; }
[Required]
string BuildAssemblyPath { get; set; }
[Required]
bool ShouldGenerateSerializer { get; set; }
[Required]
bool UseProxyTypes { get; set; }
bool UseKeep { get; set; }
string[] References { get; set; }
string KeyContainer { get; set; }
string KeyFile { get; set; }
bool DelaySign { get; set; }
[Output]
ITaskItem[] SerializationAssembly { get; set; }
string SerializationAssemblyName { get; }
string SdkToolsPath { get; set; }
/// <summary>
/// Gets or Sets the Compiler Platform used by SGen to generate the output assembly.
/// </summary>
string Platform { get; set; }
/// <summary>
/// Gets or Sets a list of specific Types to generate serialization code for, SGen will generate serialization code only for those types.
/// </summary>
string[] Types { get; set; }
#endregion
}
#if RUNTIME_TYPE_NETCORE
[MSBuildMultiThreadableTask]
public class SGen : ToolTaskExtension, ISGenTaskContract
{
#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both
#region Properties
[Required]
public string BuildAssemblyName { get; set; }
[Required]
public string BuildAssemblyPath { get; set; }
[Required]
public bool ShouldGenerateSerializer { get; set; }
[Required]
public bool UseProxyTypes { get; set; }
public bool UseKeep { get; set; }
public string[] References { get; set; }
public string KeyContainer { get; set; }
public string KeyFile { get; set; }
public bool DelaySign { get; set; }
[Output]
public ITaskItem[] SerializationAssembly { get; set; }
public string SerializationAssemblyName { get; }
public string SdkToolsPath { get; set; }
public string Platform { get; set; }
public string[] Types { get; set; }
#endregion
#region Tool Members
protected override string ToolName
{
get
{
ErrorUtilities.ThrowInternalErrorUnreachable();
return null;
}
}
protected override string GenerateFullPathToTool()
{
ErrorUtilities.ThrowInternalErrorUnreachable();
return null;
}
public override bool Execute()
{
Log.LogErrorWithCodeFromResources("SGen.TaskNotSupported", nameof(SGen));
return false;
}
#endregion
#pragma warning restore format
}
#else
/// <summary>
/// Genererates a serialization assembly containing XML serializers for the input assembly.
/// </summary>
[MSBuildMultiThreadableTask]
public class SGen : ToolTaskExtension, ISGenTaskContract
{
private string _buildAssemblyPath;
#pragma warning disable format // region formatting is different in net7.0 and net472, and cannot be fixed for both
#region Properties
// Input files
[Required]
public string BuildAssemblyName
{
set
{
ErrorUtilities.VerifyThrowArgumentNull(value, nameof(BuildAssemblyName));
Bag[nameof(BuildAssemblyName)] = value;
}
get => (string)Bag[nameof(BuildAssemblyName)];
}
[Required]
public string BuildAssemblyPath
{
set
{
ErrorUtilities.VerifyThrowArgumentNull(value, nameof(BuildAssemblyPath));
_buildAssemblyPath = value;
}
get
{
string thisPath;
try
{
Path.GetFullPath(_buildAssemblyPath);
thisPath = !string.IsNullOrEmpty(_buildAssemblyPath)
? TaskEnvironment.GetAbsolutePath(_buildAssemblyPath).GetCanonicalForm()
: _buildAssemblyPath;
}
catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
{
// If it is an Expected Exception log the error
Log.LogErrorWithCodeFromResources("SGen.InvalidPath", "BuildAssemblyPath", e.Message);
throw;
}
return thisPath;
}
}
[Required]
public bool ShouldGenerateSerializer
{
set => Bag[nameof(ShouldGenerateSerializer)] = value;
get => GetBoolParameterWithDefault(nameof(ShouldGenerateSerializer), false);
}
[Required]
public bool UseProxyTypes
{
set => Bag[nameof(UseProxyTypes)] = value;
get => GetBoolParameterWithDefault(nameof(UseProxyTypes), false);
}
public bool UseKeep
{
set => Bag[nameof(UseKeep)] = value;
get => GetBoolParameterWithDefault(nameof(UseKeep), false);
}
public string[] References
{
set => Bag[nameof(References)] = value;
get => (string[])Bag[nameof(References)];
}
public string KeyContainer
{
set => Bag[nameof(KeyContainer)] = value;
get => (string)Bag[nameof(KeyContainer)];
}
public string KeyFile
{
set => Bag[nameof(KeyFile)] = value;
get => (string)Bag[nameof(KeyFile)];
}
public bool DelaySign
{
set => Bag[nameof(DelaySign)] = value;
get => GetBoolParameterWithDefault(nameof(DelaySign), false);
}
[Output]
public ITaskItem[] SerializationAssembly
{
set => Bag[nameof(SerializationAssembly)] = value;
get => (ITaskItem[])Bag[nameof(SerializationAssembly)];
}
public string SerializationAssemblyName
{
get
{
Debug.Assert(BuildAssemblyName.Length > 0, "Build assembly name is blank");
string prunedAssemblyName;
try
{
prunedAssemblyName = Path.GetFileNameWithoutExtension(BuildAssemblyName);
}
catch (ArgumentException e)
{
Log.LogErrorWithCodeFromResources("SGen.InvalidPath", "BuildAssemblyName", e.Message);
throw;
}
prunedAssemblyName += ".XmlSerializers.dll";
return prunedAssemblyName;
}
}
private AbsolutePath SerializationAssemblyPath => new AbsolutePath(Path.Combine(BuildAssemblyPath, SerializationAssemblyName));
private AbsolutePath AssemblyFullPathv => new AbsolutePath(Path.Combine(BuildAssemblyPath, BuildAssemblyName));
public string SdkToolsPath
{
set => Bag[nameof(SdkToolsPath)] = value;
get => (string)Bag[nameof(SdkToolsPath)];
}
/// <summary>
/// Gets or Sets the Compiler Platform used by SGen to generate the output assembly.
/// </summary>
public string Platform
{
set => Bag[nameof(Platform)] = value;
get => (string)Bag[nameof(Platform)];
}
/// <summary>
/// Gets or Sets a list of specific Types to generate serialization code for, SGen will generate serialization code only for those types.
/// </summary>
public string[] Types
{
set => Bag[nameof(Types)] = value;
get => (string[])Bag[nameof(Types)];
}
#endregion
#region Tool Members
/// <summary>
/// The name of the tool to execute.
/// </summary>
protected override string ToolName => "sgen.exe";
/// <summary>
/// The full path of the tool to execute.
/// </summary>
protected override string GenerateFullPathToTool()
{
string pathToTool = null;
// If COMPLUS_InstallRoot\COMPLUS_Version are set (the dogfood world), we want to find it there, instead of
// the SDK, which may or may not be installed. The following will look there.
if (!String.IsNullOrEmpty(TaskEnvironment.GetEnvironmentVariable("COMPLUS_InstallRoot")) || !String.IsNullOrEmpty(TaskEnvironment.GetEnvironmentVariable("COMPLUS_Version")))
{
pathToTool = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolExe, TargetDotNetFrameworkVersion.Latest);
}
if (String.IsNullOrEmpty(pathToTool) || !FileSystems.Default.FileExists(TaskEnvironment.GetAbsolutePath(pathToTool)))
{
pathToTool = SdkToolsPathUtility.GeneratePathToTool(
f => !string.IsNullOrEmpty(f)
? SdkToolsPathUtility.FileInfoExists(TaskEnvironment.GetAbsolutePath(f))
: SdkToolsPathUtility.FileInfoExists(f),
ProcessorArchitecture.CurrentProcessArchitecture, SdkToolsPath, ToolExe, Log, true);
}
return string.IsNullOrEmpty(pathToTool) ? pathToTool : TaskEnvironment.GetAbsolutePath(pathToTool).Value;
}
/// <summary>
/// Validate parameters, log errors and warnings and return true if Execute should proceed.
/// </summary>
protected override bool ValidateParameters()
{
// Ensure the references exist before passing them to SGen.exe
if (References != null)
{
foreach (string reference in References)
{
if (string.IsNullOrEmpty(reference) || !FileSystems.Default.FileExists(TaskEnvironment.GetAbsolutePath(reference)))
{
Log.LogErrorWithCodeFromResources("SGen.ResourceNotFound", reference);
return false;
}
}
}
return true;
}
/// <summary>
/// Returns true if task execution is not necessary. Executed after ValidateParameters
/// </summary>
/// <returns></returns>
protected override bool SkipTaskExecution()
{
return SerializationAssembly == null && !ShouldGenerateSerializer;
}
/// <summary>
/// Returns a string with those switches and other information that can't go into a response file and
/// must go directly onto the command line.
/// Called after ValidateParameters and SkipTaskExecution
/// </summary>
protected override string GenerateCommandLineCommands()
{
var commandLineBuilder = new CommandLineBuilderExtension();
bool serializationAssemblyPathExists = false;
try
{
if (SerializationAssembly == null)
{
Debug.Assert(ShouldGenerateSerializer, "GenerateCommandLineCommands() should not be called if ShouldGenerateSerializer is true and SerializationAssembly is null.");
SerializationAssembly = [new TaskItem(SerializationAssemblyPath.OriginalValue)];
}
// Add the assembly switch
commandLineBuilder.AppendSwitchIfNotNull("/assembly:", AssemblyFullPath.Value);
commandLineBuilder.AppendWhenTrue("/proxytypes", Bag, "UseProxyTypes");
// add the keep switch
commandLineBuilder.AppendWhenTrue("/keep", Bag, "UseKeep");
// Append the references, if any.
if (References != null)
{
if (References.Length > 0)
{
// Use a single comma-delimited argument rather than multiple /reference:file
// arguments to save 11 characters per reference (" /reference:" versus ","),
// which can help squeak under the command-line length limit in the
// many-references case.
commandLineBuilder.AppendSwitchIfNotNull("/reference:", string.Join(",", References));
}
}
// Append the Types to the command line, if any.
if (Types != null)
{
foreach (string type in Types)
{
commandLineBuilder.AppendSwitchIfNotNull("/type:", type);
}
}
// The arguments to the "/compiler" switch are themselves switches to be passed to
// the compiler when generating the serialization assembly.
// Add the compiler command switches for strong naming on the serialization assembly
if (KeyFile != null)
{
commandLineBuilder.AppendNestedSwitch("/compiler:", "/keyfile:", KeyFile);
}
else if (KeyContainer != null)
{
commandLineBuilder.AppendNestedSwitch("/compiler:", "/keycontainer:", KeyContainer);
}
commandLineBuilder.AppendPlusOrMinusSwitch("/compiler:/delaysign", Bag, "DelaySign");
// Add the Platform switch to the compiler.
if (Platform != null)
{
commandLineBuilder.AppendNestedSwitch("/compiler:", "/platform:", Platform);
}
serializationAssemblyPathExists = FileSystems.Default.FileExists(SerializationAssemblyPath);
}
catch (Exception e) when (ExceptionHandling.IsIoRelatedException(e))
{
// Ignore the expected exceptions because they have already been logged
}
// Delete the assembly if it already exists.
if (serializationAssemblyPathExists)
{
try
{
File.Delete(SerializationAssemblyPath);
}
// Of all of the exceptions that can be thrown on a File.Delete, the only ones we need to
// be immediately concerned with are the UnauthorizedAccessException and the IOException
// (file is in use exception). We need to make sure that the assembly is gone before we
// try to produce a new one because it is possible that after some changes were made to the
// base assembly, there will, in fact, not be a serialization assembly produced. We cannot
// leave the earlier produced assembly around to be propagated by later processes.
catch (UnauthorizedAccessException e)
{
Log.LogErrorWithCodeFromResources("SGen.CouldNotDeleteSerializer", SerializationAssemblyPath.OriginalValue, e.Message);
}
catch (IOException e)
{
Log.LogErrorWithCodeFromResources("SGen.CouldNotDeleteSerializer", SerializationAssemblyPath.OriginalValue, e.Message);
}
// The DirectoryNotFoundException is safely ignorable since that means that there is no
// existing serialization assembly. This would be extremely unlikely anyway because we
// found the serializer just a couple of milliseconds ago.
}
return commandLineBuilder.ToString();
}
#endregion
#pragma warning restore format
}
#endif
}