-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
Sgen.cs
704 lines (631 loc) · 26.3 KB
/
Sgen.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
// 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.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Xml.Serialization;
namespace Microsoft.XmlSerializer.Generator
{
internal sealed class Sgen
{
public static int Main(string[] args)
{
Sgen sgen = new Sgen();
return sgen.Run(args);
}
private static string s_references = string.Empty;
private static readonly Dictionary<string, string> s_referencedic = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private int Run(string[] args)
{
string assembly = null;
var types = new List<string>();
string defaultNamespace = null;
string codePath = null;
var errs = new List<string>();
bool force = false;
bool proxyOnly = false;
bool disableRun = true;
bool noLogo = false;
bool parsableErrors = false;
bool silent = false;
bool verbose = false;
AppDomain.CurrentDomain.AssemblyResolve += SgenAssemblyResolver;
try
{
args = ParseResponseFile(args);
for (int i = 0; i < args.Length; i++)
{
string arg = args[i];
if (ArgumentMatch(arg, "help") || ShortNameArgumentMatch(arg, "h"))
{
WriteHeader();
WriteHelp();
return 0;
}
else if (ArgumentMatch(arg, "force"))
{
force = true;
}
else if (ArgumentMatch(arg, "proxytypes"))
{
proxyOnly = true;
}
else if (ArgumentMatch(arg, "out") || ShortNameArgumentMatch(arg, "o"))
{
i++;
if (i >= args.Length || codePath != null)
{
errs.Add(SR.Format(SR.ErrInvalidArgument, arg));
}
else
{
codePath = args[i];
}
}
else if (ArgumentMatch(arg, "type"))
{
i++;
if (i >= args.Length)
{
errs.Add(SR.Format(SR.ErrInvalidArgument, arg));
}
else
{
string[] typelist = args[i].Split(';');
foreach (var type in typelist)
{
types.Add(type);
}
}
}
else if (ArgumentMatch(arg, "assembly") || ShortNameArgumentMatch(arg, "a"))
{
i++;
if (i >= args.Length || assembly != null)
{
errs.Add(SR.Format(SR.ErrInvalidArgument, arg));
}
else
{
assembly = args[i];
}
}
else if (ArgumentMatch(arg, "default-namespace"))
{
i++;
if (i >= args.Length || defaultNamespace != null)
{
errs.Add(SR.Format(SR.ErrInvalidArgument, arg));
}
else
{
defaultNamespace = args[i];
}
}
else if (ArgumentMatch(arg, "quiet"))
{
disableRun = false;
}
else if (ArgumentMatch(arg, "nologo"))
{
noLogo = true;
}
else if (ArgumentMatch(arg, "silent"))
{
silent = true;
}
else if (ArgumentMatch(arg, "parsableerrors"))
{
parsableErrors = true;
}
else if (ArgumentMatch(arg, "verbose"))
{
verbose = true;
}
else if (ArgumentMatch(arg, "reference"))
{
i++;
if (i >= args.Length)
{
errs.Add(SR.Format(SR.ErrInvalidArgument, arg));
}
else
{
//if there are multiple --reference switches, the last one will overwrite previous ones.
s_references = args[i];
}
}
else
{
if (arg.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase) || arg.EndsWith(".exe", StringComparison.InvariantCultureIgnoreCase))
{
if (assembly != null)
{
errs.Add(SR.Format(SR.ErrInvalidArgument, arg));
}
assembly = arg;
}
else
{
errs.Add(SR.Format(SR.ErrInvalidArgument, arg));
}
}
}
if (!noLogo)
{
WriteHeader();
}
if (errs.Count > 0)
{
foreach (string err in errs)
{
Console.Error.WriteLine(FormatMessage(parsableErrors, true, SR.Format(SR.Warning, err)));
}
}
if (args.Length == 0 || assembly == null)
{
if (assembly == null)
{
Console.Error.WriteLine(FormatMessage(parsableErrors, false, SR.Format(SR.ErrMissingRequiredArgument, SR.Format(SR.ErrAssembly, "assembly"))));
}
WriteHelp();
return 0;
}
if (disableRun)
{
Console.WriteLine("This tool is not intended to be used directly.");
Console.WriteLine("Please refer to https://go.microsoft.com/fwlink/?linkid=858594 on how to use it.");
return 0;
}
if (!string.IsNullOrEmpty(s_references))
{
ParseReferences();
}
GenerateFile(types, defaultNamespace, assembly, proxyOnly, silent, verbose, force, codePath, parsableErrors);
}
catch (Exception e)
{
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
{
throw;
}
WriteError(e, parsableErrors);
return 1;
}
return 0;
}
private static void GenerateFile(List<string> typeNames, string defaultNamespace, string assemblyName, bool proxyOnly, bool silent, bool verbose, bool force, string outputDirectory, bool parsableerrors)
{
Assembly assembly = LoadAssembly(assemblyName);
Type[] types;
if (typeNames == null || typeNames.Count == 0)
{
try
{
types = assembly.GetTypes();
}
catch (ReflectionTypeLoadException typeException)
{
List<Type> loadedTypes = new List<Type>();
foreach (Type type in typeException.Types)
{
if (type != null)
{
loadedTypes.Add(type);
}
}
types = loadedTypes.ToArray();
}
}
else
{
types = new Type[typeNames.Count];
int typeIndex = 0;
foreach (string typeName in typeNames)
{
Type type = assembly.GetType(typeName);
if (type == null)
{
Console.Error.WriteLine(FormatMessage(parsableerrors, false, SR.Format(SR.ErrorDetails, SR.Format(SR.ErrLoadType, typeName, assemblyName))));
}
types[typeIndex++] = type;
}
}
var mappings = new List<XmlMapping>();
var importedTypes = new List<Type>();
var importer = new XmlReflectionImporter(defaultNamespace);
for (int i = 0; i < types.Length; i++)
{
Type type = types[i];
try
{
if (type != null)
{
if (verbose)
{
Console.WriteLine(SR.Format(SR.ImportInfo, type.Name, i + 1, types.Length));
}
bool isObsolete = false;
object[] obsoleteAttributes = type.GetCustomAttributes(typeof(ObsoleteAttribute), false);
foreach (object attribute in obsoleteAttributes)
{
if (((ObsoleteAttribute)attribute).IsError)
{
isObsolete = true;
break;
}
}
if (isObsolete)
{
continue;
}
}
}
//Ignore the FileNotFoundException when call GetCustomAttributes e.g. if the type uses the attributes defined in a different assembly
catch (FileNotFoundException e)
{
if (verbose)
{
Console.Out.WriteLine(FormatMessage(parsableerrors, true, SR.Format(SR.InfoIgnoreType, type.FullName)));
WriteWarning(e, parsableerrors);
}
continue;
}
if (!proxyOnly)
{
ImportType(type, defaultNamespace, mappings, importedTypes, verbose, importer, parsableerrors);
}
}
if (importedTypes.Count > 0)
{
var serializableTypes = importedTypes.ToArray();
var allMappings = mappings.ToArray();
bool gac = assembly.GlobalAssemblyCache;
outputDirectory ??= (gac ? Environment.CurrentDirectory : Path.GetDirectoryName(assembly.Location));
if (!Directory.Exists(outputDirectory))
{
//We need double quote the path to escpate the space in the path.
//However when a path ending with backslash, if followed by double quote, it becomes an escapte sequence
//e.g. "obj\Debug\netcoreapp2.0\", it will be converted as obj\Debug\netcoreapp2.0", which is not valid and not exist
//We need remove the ending quote for this situation
if (!outputDirectory.EndsWith("\"", StringComparison.Ordinal) || !Directory.Exists(outputDirectory = outputDirectory.Remove(outputDirectory.Length - 1)))
{
throw new ArgumentException(SR.Format(SR.ErrDirectoryNotExists, outputDirectory));
}
}
string serializerName = GetXmlSerializerAssemblyName(serializableTypes[0], defaultNamespace);
string codePath = Path.Combine(outputDirectory, serializerName + ".cs");
if (!force)
{
if (File.Exists(codePath))
throw new InvalidOperationException(SR.Format(SR.ErrSerializerExists, codePath, nameof(force)));
}
if (Directory.Exists(codePath))
{
throw new InvalidOperationException(SR.Format(SR.ErrDirectoryExists, codePath));
}
bool success = false;
bool toDeleteFile = true;
try
{
if (File.Exists(codePath))
{
File.Delete(codePath);
}
using (FileStream fs = File.Create(codePath))
{
MethodInfo method;
if (defaultNamespace == null)
{
method = typeof(System.Xml.Serialization.XmlSerializer).GetMethod("GenerateSerializer", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
}
else
{
Type tempAssemblyType = typeof(System.Xml.Serialization.XmlSerializer).Assembly.GetType("System.Xml.Serialization.TempAssembly");
method = tempAssemblyType.GetMethod("GenerateSerializerToStream", BindingFlags.Static | BindingFlags.NonPublic);
}
if (method == null)
{
Console.Error.WriteLine(FormatMessage(parsableerrors: false, warning: false, message: SR.GenerateSerializerNotFound));
}
else
{
if (defaultNamespace == null)
{
success = (bool)method.Invoke(null, new object[] { serializableTypes, allMappings, fs });
}
else
{
success = (bool)method.Invoke(null, new object[] { allMappings, serializableTypes, defaultNamespace, assembly, new Hashtable(), fs });
}
}
}
}
catch (UnauthorizedAccessException)
{
toDeleteFile = false;
throw new UnauthorizedAccessException(SR.Format(SR.DirectoryAccessDenied, outputDirectory));
}
finally
{
if (!success && toDeleteFile && File.Exists(codePath))
{
File.Delete(codePath);
}
}
if (success)
{
if (!silent)
{
Console.Out.WriteLine(SR.Format(SR.InfoFileName, codePath));
Console.Out.WriteLine(SR.Format(SR.InfoGeneratedFile, assembly.Location, codePath));
}
}
else
{
Console.Out.WriteLine(FormatMessage(parsableerrors, false, SR.Format(SR.ErrGenerationFailed, assembly.Location)));
}
}
else
{
Console.Out.WriteLine(FormatMessage(parsableerrors, true, SR.Format(SR.InfoNoSerializableTypes, assembly.Location)));
}
}
private static bool ArgumentMatch(string arg, string formal)
{
// Full name format, eg: --assembly
if (arg.Length < 3 || arg[0] != '-' || arg[1] != '-')
{
return false;
}
arg = arg.Substring(2);
return arg.Equals(formal, StringComparison.InvariantCultureIgnoreCase);
}
private static bool ShortNameArgumentMatch(string arg, string shortName)
{
// Short name format, eg: -a
if (arg.Length < 2 || arg[0] != '-')
{
return false;
}
arg = arg.Substring(1);
return arg.Equals(shortName, StringComparison.InvariantCultureIgnoreCase);
}
private static void ImportType(Type type, string defaultNamespace, List<XmlMapping> mappings, List<Type> importedTypes, bool verbose, XmlReflectionImporter importer, bool parsableerrors)
{
XmlTypeMapping xmlTypeMapping;
var localImporter = new XmlReflectionImporter(defaultNamespace);
try
{
xmlTypeMapping = localImporter.ImportTypeMapping(type, defaultNamespace);
}
catch (Exception e)
{
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException)
{
throw;
}
if (verbose)
{
Console.Out.WriteLine(FormatMessage(parsableerrors, true, SR.Format(SR.InfoIgnoreType, type.FullName)));
WriteWarning(e, parsableerrors);
}
return;
}
if (xmlTypeMapping != null)
{
xmlTypeMapping = importer.ImportTypeMapping(type, defaultNamespace);
mappings.Add(xmlTypeMapping);
importedTypes.Add(type);
}
}
private static Assembly LoadAssembly(string assemblyName)
{
Assembly assembly;
string path = Path.IsPathRooted(assemblyName) ? assemblyName : Path.GetFullPath(assemblyName);
assembly = Assembly.LoadFile(path);
if (assembly == null)
{
throw new InvalidOperationException(SR.Format(SR.ErrLoadAssembly, assemblyName));
}
return assembly;
}
private static void WriteHeader()
{
// do not localize Copyright header
Console.WriteLine($".NET Xml Serialization Generation Utility, Version {ThisAssembly.InformationalVersion}]");
}
private void WriteHelp()
{
Console.Out.WriteLine(SR.HelpDescription);
Console.Out.WriteLine(SR.Format(SR.HelpUsage, this.GetType().Assembly.GetName().Name.Substring("dotnet-".Length)));
Console.Out.WriteLine(SR.HelpDevOptions);
Console.Out.WriteLine(SR.Format(SR.HelpAssembly, "-a", "--assembly"));
Console.Out.WriteLine(SR.Format(SR.HelpType, "--type"));
Console.Out.WriteLine(SR.Format(SR.HelpProxy, "--proxytypes"));
Console.Out.WriteLine(SR.Format(SR.HelpForce, "--force"));
Console.Out.WriteLine(SR.Format(SR.HelpOut, "-o", "--out"));
Console.Out.WriteLine(SR.HelpMiscOptions);
Console.Out.WriteLine(SR.Format(SR.HelpHelp, "-h", "--help"));
}
private static string FormatMessage(bool parsableerrors, bool warning, string message)
{
return FormatMessage(parsableerrors, warning, "SGEN1", message);
}
private static string FormatMessage(bool parsableerrors, bool warning, string code, string message)
{
if (!parsableerrors)
{
return message;
}
return "SGEN: " + (warning ? "warning " : "error ") + code + ": " + message;
}
private static void WriteError(Exception e, bool parsableerrors)
{
Console.Error.WriteLine(FormatMessage(parsableerrors, false, e.Message));
if (e.InnerException != null)
{
WriteError(e.InnerException, parsableerrors);
}
}
private static void WriteWarning(Exception e, bool parsableerrors)
{
Console.Out.WriteLine(FormatMessage(parsableerrors, true, e.Message));
if (e.InnerException != null)
{
WriteWarning(e.InnerException, parsableerrors);
}
}
private static string GetXmlSerializerAssemblyName(Type type)
{
return GetXmlSerializerAssemblyName(type, null);
}
private static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace)
{
if (type is null)
{
throw new ArgumentNullException(nameof(type));
}
return GetTempAssemblyName(type.Assembly.GetName(), defaultNamespace);
}
private static string GetTempAssemblyName(AssemblyName parent, string ns)
{
return parent.Name + ".XmlSerializers" + (string.IsNullOrEmpty(ns) ? "" : $".{GetPersistentHashCode(ns)}");
}
private static uint GetPersistentHashCode(string value)
{
byte[] valueBytes = Encoding.UTF8.GetBytes(value);
byte[] hash = SHA512.Create().ComputeHash(valueBytes);
return ReadUInt32BigEndian(hash);
}
private static uint ReadUInt32BigEndian(byte[] value)
{
return (uint)(value[0] << 24 | value[1] << 16 | value[2] << 8 | value[3]);
}
private static void ParseReferences()
{
var referencelist = new List<string>();
if (s_references.Length > 0)
{
foreach (var entry in s_references.Split(';'))
{
string trimentry = entry.Trim();
if (string.IsNullOrEmpty(trimentry))
continue;
referencelist.Add(trimentry);
}
}
foreach (var reference in referencelist)
{
if (reference.EndsWith(".dll") || reference.EndsWith(".exe"))
{
if (File.Exists(reference))
{
string filename = Path.GetFileNameWithoutExtension(reference);
if (!string.IsNullOrEmpty(filename))
{
s_referencedic.Add(filename, reference);
}
}
}
}
}
private static Assembly SgenAssemblyResolver(object source, ResolveEventArgs e)
{
try
{
if (string.IsNullOrEmpty(e.Name) || e.Name.Split(',').Length == 0)
{
return null;
}
string assemblyname = e.Name.Split(',')[0];
if (string.IsNullOrEmpty(assemblyname))
{
return null;
}
if (s_referencedic.TryGetValue(assemblyname, out string reference))
{
// For System.ServiceModel.Primitives, we need to load its runtime assembly rather than reference assembly
if (assemblyname.Equals("System.ServiceModel.Primitives"))
{
// Replace "ref" with "lib" in the assembly's path, the path looks like:
// dir\.nuget\packages\system.servicemodel.primitives\4.5.3\ref\netstandard2.0\System.ServiceModel.Primitives.dll;
string pattern = @"\\ref\\netstandard\d*\.?\d*\.?\d*\\System.ServiceModel.Primitives.dll";
Match match = null;
try
{
match = Regex.Match(reference, pattern);
}
catch { }
if (match != null && match.Success)
{
int index = match.Index + 1;
StringBuilder sb = new StringBuilder(reference);
sb.Remove(index, "ref".Length);
sb.Insert(index, "lib");
reference = sb.ToString();
}
}
if (!string.IsNullOrEmpty(reference))
{
if (File.Exists(reference))
{
return Assembly.LoadFrom(reference);
}
}
}
}
catch (Exception exp)
{
if (exp is ThreadAbortException || exp is StackOverflowException || exp is OutOfMemoryException)
{
throw;
}
WriteWarning(exp, true);
}
return null;
}
private static string[] ParseResponseFile(string[] args)
{
var parsedArgs = new List<string>();
foreach (string arg in args)
{
if (!arg.EndsWith(".rsp"))
{
parsedArgs.Add(arg);
}
else
{
try
{
foreach (string line in File.ReadAllLines(arg))
{
int i = line.Trim().IndexOf(' ');
if (i < 0)
{
parsedArgs.Add(line);
}
else
{
parsedArgs.Add(line.Substring(0, i));
parsedArgs.Add(line.Substring(i + 1));
}
}
}
//If for any reasons the rsp file is not generated, this argument will be ignored and serializer will be generated with default settings
catch (FileNotFoundException)
{ }
}
}
return parsedArgs.ToArray();
}
}
}