-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
GenerateResource.cs
4153 lines (3701 loc) · 178 KB
/
GenerateResource.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.
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
#if FEATURE_RESXREADER_LIVEDESERIALIZATION
using System.ComponentModel.Design;
#endif
#if FEATURE_SYSTEM_CONFIGURATION
using System.Configuration;
#endif
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Resources;
using System.Resources.Extensions;
using System.Reflection;
using System.Runtime.InteropServices;
#if FEATURE_APPDOMAIN
using System.Runtime.Remoting;
using System.Runtime.Serialization.Formatters.Binary;
#endif
using System.Runtime.Serialization;
#if !FEATURE_ASSEMBLYLOADCONTEXT
using System.Runtime.Versioning;
using System.Security;
#endif
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Build.Eventing;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Shared.FileSystem;
using Microsoft.Build.Tasks.ResourceHandling;
using Microsoft.Build.Utilities;
#if FEATURE_RESXREADER_LIVEDESERIALIZATION
using Microsoft.Win32;
#endif
#nullable disable
namespace Microsoft.Build.Tasks
{
/// <summary>
/// This class defines the "GenerateResource" MSBuild task, which enables using resource APIs
/// to transform resource files.
/// </summary>
[RequiredRuntime("v2.0")]
public sealed partial class GenerateResource : TaskExtension, IIncrementalTask
{
#region Fields
// This cache helps us track the linked resource files listed inside of a resx resource file
private ResGenDependencies _cache;
// This is where we store the list of input files/sources
private ITaskItem[] _sources = null;
// Indicates whether the resource reader should use the source file's
// directory to resolve relative file paths.
private bool _useSourcePath = false;
// This is needed for the actual items from the project
private ITaskItem[] _references = null;
// Any additional inputs to dependency checking.
private ITaskItem[] _additionalInputs = null;
// This is the path/name of the dependency cache file
private ITaskItem _stateFile = null;
// This list is all of the resource file(s) generated by the task
private ITaskItem[] _outputResources = null;
// List of those output resources that were not actually created, due to an error
private ArrayList _unsuccessfullyCreatedOutFiles = new ArrayList();
// Storage for names of *all files* written to disk.
private ArrayList _filesWritten = new ArrayList();
// StronglyTypedLanguage
private string _stronglyTypedLanguage = null;
// StronglyTypedNamespace
private string _stronglyTypedNamespace = null;
// StronglyTypedManifestPrefix
private string _stronglyTypedManifestPrefix = null;
// StronglyTypedClassName
private string _stronglyTypedClassName = null;
// StronglyTypedFileName
private string _stronglyTypedFileName = null;
// Whether the STR class should have public members; default is false
private bool _publicClass = false;
// Did the CodeDOM succeed when creating any Strongly Typed Resource class?
private bool _stronglyTypedResourceSuccessfullyCreated = false;
// When true, a separate AppDomain is always created.
private bool _neverLockTypeAssemblies = false;
// Newest uncorrelated input,
// or null if not yet determined
private string _newestUncorrelatedInput;
// Write time of newest uncorrelated input
// DateTime.MinValue indicates "missing" iff _newestUncorrelatedInput != null
private DateTime _newestUncorrelatedInputWriteTime;
// The targets may pass in the path to the SDKToolsPath. If so this should be used to generate the commandline
// for logging purposes. Also, when ExecuteAsTool is true, it determines where the system goes looking for resgen.exe
private string _sdkToolsPath;
// True if the resource generation should be sent out-of-proc to resgen.exe; false otherwise. Defaults to true
// because we want to execute out-of-proc when ToolsVersion is < 4.0, and the earlier targets files don't know
// about this property.
private bool _executeAsTool = true;
// Path to resgen.exe
private string _resgenPath;
#if FEATURE_APPDOMAIN
// table of already seen types by their typename
// note the use of the ordinal comparer that matches the case sensitive Type.GetType usage
private Dictionary<string, Type> _typeTable = new Dictionary<string, Type>(StringComparer.Ordinal);
/// <summary>
/// Table of aliases for types defined in resx / resw files
/// Ordinal comparer matches ResXResourceReader's use of a HashTable.
/// </summary>
private Dictionary<string, string> _aliases = new Dictionary<string, string>(StringComparer.Ordinal);
#endif // FEATURE_APPDOMAIN
#if FEATURE_RESGEN
// Our calculation is not quite correct. Using a number substantially less than 32768 in order to
// be sure we don't exceed it.
private static int s_maximumCommandLength = 28000;
#endif // FEATURE_RESGEN
// Contains the list of paths from which inputs will not be taken into account during up-to-date check.
private ITaskItem[] _excludedInputPaths;
#if FEATURE_APPDOMAIN
/// <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<ITaskItem> _remotedTaskItems;
#endif
/// <summary>
/// Satellite input assemblies.
/// </summary>
private List<ITaskItem> _satelliteInputs;
#endregion // fields
#region Properties
/// <summary>
/// The names of the items to be converted. The extension must be one of the
/// following: .txt, .resx or .resources.
/// </summary>
[Required]
[Output]
public ITaskItem[] Sources
{
set { _sources = value; }
get { return _sources; }
}
/// <summary>
/// Indicates whether the resource reader should use the source file's directory to
/// resolve relative file paths.
/// </summary>
public bool UseSourcePath
{
set { _useSourcePath = value; }
get { return _useSourcePath; }
}
/// <summary>
/// Resolves types in ResX files (XML resources) for Strongly Typed Resources
/// </summary>
public ITaskItem[] References
{
set { _references = value; }
get { return _references; }
}
/// <summary>
/// Indicates whether resources should be passed through in their current serialization
/// format. .NET Core-targeted assemblies should use this; it's the only way to support
/// non-string resources with MSBuild running on .NET Core.
/// </summary>
public bool UsePreserializedResources { get; set; } = false;
/// <summary>
/// Additional inputs to the dependency checking done by this task. For example,
/// the project and targets files typically should be inputs, so that if they are updated,
/// all resources are regenerated.
/// </summary>
public ITaskItem[] AdditionalInputs
{
set { _additionalInputs = value; }
get { return _additionalInputs; }
}
/// <summary>
/// This is the path/name of the file containing the dependency cache
/// </summary>
public ITaskItem StateFile
{
set { _stateFile = value; }
get { return _stateFile; }
}
/// <summary>
/// The name(s) of the resource file to create. If the user does not specify this
/// attribute, the task will append a .resources extension to each input filename
/// argument and write the file to the directory that contains the input file.
/// Includes any output files that were already up to date, but not any output files
/// that failed to be written due to an error.
/// </summary>
[Output]
public ITaskItem[] OutputResources
{
set { _outputResources = value; }
get { return _outputResources; }
}
/// <summary>
/// Storage for names of *all files* written to disk. This is part of the implementation
/// for Clean, and contains the OutputResources items and the StateFile item.
/// Includes any output files that were already up to date, but not any output files
/// that failed to be written due to an error.
/// </summary>
[Output]
public ITaskItem[] FilesWritten
{
get
{
return (ITaskItem[])_filesWritten.ToArray(typeof(ITaskItem));
}
}
/// <summary>
/// Gets or sets the language to use when generating the class source for the strongly typed resource.
/// This parameter must match exactly one of the languages used by the CodeDomProvider.
/// </summary>
public string StronglyTypedLanguage
{
set
{
// Since this string is passed directly into the framework, we don't want to
// try to validate it -- that might prevent future expansion of supported languages.
_stronglyTypedLanguage = value;
}
get
{
return _stronglyTypedLanguage;
}
}
// Indicates whether any BinaryFormatter use should lead to a warning.
public bool WarnOnBinaryFormatterUse
{
get; set;
}
/// <summary>
/// Specifies the namespace to use for the generated class source for the
/// strongly typed resource. If left blank, no namespace is used.
/// </summary>
public string StronglyTypedNamespace
{
set { _stronglyTypedNamespace = value; }
get { return _stronglyTypedNamespace; }
}
/// <summary>
/// Specifies the resource namespace or manifest prefix to use in the generated
/// class source for the strongly typed resource.
/// </summary>
public string StronglyTypedManifestPrefix
{
set { _stronglyTypedManifestPrefix = value; }
get { return _stronglyTypedManifestPrefix; }
}
/// <summary>
/// Specifies the class name for the strongly typed resource class. If left blank, the base
/// name of the resource file is used.
/// </summary>
[Output]
public string StronglyTypedClassName
{
set { _stronglyTypedClassName = value; }
get { return _stronglyTypedClassName; }
}
/// <summary>
/// Specifies the filename for the source file. If left blank, the name of the class is
/// used as the base filename, with the extension dependent on the language.
/// </summary>
[Output]
public string StronglyTypedFileName
{
set { _stronglyTypedFileName = value; }
get { return _stronglyTypedFileName; }
}
/// <summary>
/// Specifies whether the strongly typed class should be created public (with public methods)
/// instead of the default internal. Analogous to resgen.exe's /publicClass switch.
/// </summary>
public bool PublicClass
{
set { _publicClass = value; }
get { return _publicClass; }
}
/// <summary>
/// Whether this rule is generating .resources files or extracting .ResW files from assemblies.
/// Requires some additional input filtering.
/// </summary>
public bool ExtractResWFiles
{
get;
set;
}
/// <summary>
/// (default = false)
/// When true, a new AppDomain is always created to evaluate the .resx files.
/// When false, a new AppDomain is created only when it looks like a user's
/// assembly is referenced by the .resx.
/// </summary>
public bool NeverLockTypeAssemblies
{
set { _neverLockTypeAssemblies = value; }
get { return _neverLockTypeAssemblies; }
}
/// <summary>
/// Even though the generate resource task will do the processing in process, a logging message is still generated. This logging message
/// will include the path to the windows SDK. Since the targets now will pass in the Windows SDK path we should use this for logging.
/// </summary>
public string SdkToolsPath
{
get { return _sdkToolsPath; }
set { _sdkToolsPath = value; }
}
/// <summary>
/// Property to allow multitargeting of ResolveComReferences: If true, tlbimp.exe and
/// aximp.exe from the appropriate target framework will be run out-of-proc to generate
/// the necessary wrapper assemblies.
/// </summary>
public bool ExecuteAsTool
{
set { _executeAsTool = value; }
get { return _executeAsTool; }
}
/// <summary>
/// Array of equals-separated pairs of environment
/// variables that should be passed to the spawned resgen.exe,
/// in addition to (or selectively overriding) the regular environment block.
/// These aren't currently used when resgen is run in-process.
/// </summary>
public string[] EnvironmentVariables
{
get;
set;
}
/// <summary>
/// That set of paths from which tracked inputs will be ignored during
/// Up to date checking
/// </summary>
public ITaskItem[] ExcludedInputPaths
{
get { return _excludedInputPaths; }
set { _excludedInputPaths = value; }
}
/// <summary>
/// Property used to set whether tracked incremental build will be used. If true,
/// incremental build is turned on; otherwise, a rebuild will be forced.
/// </summary>
public bool MinimalRebuildFromTracking
{
get
{
// not using tracking anymore
return false;
}
set
{
// do nothing
}
}
/// <summary>
/// True if we should be tracking file access patterns - necessary for incremental
/// build support.
/// </summary>
public bool TrackFileAccess
{
get
{
// not using tracking anymore
return false;
}
set
{
// do nothing
}
}
/// <summary>
/// Names of the read tracking logs.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLog", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")]
public ITaskItem[] TLogReadFiles
{
get
{
return Array.Empty<ITaskItem>();
}
}
/// <summary>
/// Names of the write tracking logs.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TLog", Justification = "Has now shipped as public API; plus it's unclear whether 'Tlog' or 'TLog' is the preferred casing")]
public ITaskItem[] TLogWriteFiles
{
get
{
return Array.Empty<ITaskItem>();
}
}
/// <summary>
/// Intermediate directory into which the tracking logs from running this task will be placed.
/// </summary>
public string TrackerLogDirectory
{
get
{
return String.Empty;
}
set
{
// do nothing
}
}
/// <summary>
/// Microsoft.Build.Utilities.ExecutableType of ResGen.exe. Used to determine whether or not
/// Tracker.exe needs to be used to spawn ResGen.exe. If empty, uses a heuristic to determine
/// a default architecture.
/// </summary>
public string ToolArchitecture
{
get
{
return String.Empty;
}
set
{
// do nothing
}
}
/// <summary>
/// Path to the appropriate .NET Framework location that contains FileTracker.dll. If set, the user
/// takes responsibility for making sure that the bitness of the FileTracker.dll that they pass matches
/// the bitness of the ResGen.exe that they intend to use. If not set, the task decides the appropriate
/// location based on the current .NET Framework version.
/// </summary>
/// <comments>
/// Should only need to be used in partial or full checked in toolset scenarios.
/// </comments>
public string TrackerFrameworkPath
{
get
{
return String.Empty;
}
set
{
// do nothing
}
}
/// <summary>
/// Path to the appropriate Windows SDK location that contains Tracker.exe. If set, the user takes
/// responsibility for making sure that the bitness of the Tracker.exe that they pass matches the
/// bitness of the ResGen.exe that they intend to use. If not set, the task decides the appropriate
/// location based on the current Windows SDK.
/// </summary>
/// <comments>
/// Should only need to be used in partial or full checked in toolset scenarios.
/// </comments>
public string TrackerSdkPath
{
get
{
return String.Empty;
}
set
{
// do nothing
}
}
/// <summary>
/// Where to extract ResW files. (Could be the intermediate directory.)
/// </summary>
public string OutputDirectory
{
get;
set;
}
#endregion // properties
/// <summary>
/// Simple public constructor.
/// </summary>
public GenerateResource()
{
// do nothing
}
public bool FailIfNotIncremental { get; set; }
/// <summary>
/// Logs a Resgen.exe command line that indicates what parameters were
/// passed to this task. Since this task is replacing Resgen, and we used
/// to log the Resgen.exe command line, we need to continue logging an
/// equivalent command line.
/// </summary>
/// <param name="inputFiles"></param>
/// <param name="outputFiles"></param>
private void LogResgenCommandLine(List<ITaskItem> inputFiles, List<ITaskItem> outputFiles)
{
CommandLineBuilderExtension commandLineBuilder = new CommandLineBuilderExtension();
// start the command line with the path to Resgen.exe
commandLineBuilder.AppendFileNameIfNotNull(Path.Combine(_resgenPath, "resgen.exe"));
GenerateResGenCommandLineWithoutResources(commandLineBuilder);
if (StronglyTypedLanguage == null)
{
// append the resources to compile
for (int i = 0; i < inputFiles.Count; ++i)
{
if (!ExtractResWFiles)
{
commandLineBuilder.AppendFileNamesIfNotNull(
new string[] { inputFiles[i].ItemSpec, outputFiles[i].ItemSpec },
",");
}
else
{
commandLineBuilder.AppendFileNameIfNotNull(inputFiles[i].ItemSpec);
}
}
}
else
{
// append the resource to compile
commandLineBuilder.AppendFileNamesIfNotNull(inputFiles.ToArray(), " ");
commandLineBuilder.AppendFileNamesIfNotNull(outputFiles.ToArray(), " ");
// append the strongly-typed resource details
commandLineBuilder.AppendSwitchIfNotNull(
"/str:",
new string[] { StronglyTypedLanguage, StronglyTypedNamespace, StronglyTypedClassName, StronglyTypedFileName },
",");
}
Log.LogCommandLine(MessageImportance.Low, commandLineBuilder.ToString());
}
/// <summary>
/// Generate the parts of the resgen command line that are don't involve resgen.exe itself or the
/// resources to be generated.
/// </summary>
/// <comments>
/// Expects resGenCommand to be non-null -- otherwise, it doesn't get passed back to the caller, so it's
/// useless anyway.
/// </comments>
/// <param name="resGenCommand"></param>
private void GenerateResGenCommandLineWithoutResources(CommandLineBuilderExtension resGenCommand)
{
// Throw an internal error, since this method should only ever get called by other aspects of this task, not
// anything that the user touches.
ErrorUtilities.VerifyThrowInternalNull(resGenCommand, nameof(resGenCommand));
// append the /useSourcePath flag if requested.
if (UseSourcePath)
{
resGenCommand.AppendSwitch("/useSourcePath");
}
// append the /publicClass flag if requested
if (PublicClass)
{
resGenCommand.AppendSwitch("/publicClass");
}
// append the references, if any
if (References != null)
{
foreach (ITaskItem reference in References)
{
resGenCommand.AppendSwitchIfNotNull("/r:", reference);
}
}
// append /compile switch if not creating strongly typed class
if (String.IsNullOrEmpty(StronglyTypedLanguage))
{
resGenCommand.AppendSwitch("/compile");
}
}
/// <summary>
/// This is the main entry point for the GenerateResource task.
/// </summary>
/// <returns>true, if task executes successfully</returns>
public override bool Execute()
{
bool outOfProcExecutionSucceeded = true;
MSBuildEventSource.Log.GenerateResourceOverallStart();
{
// If we're extracting ResW files from assemblies (instead of building resources),
// our Sources can contain PDB's, pictures, and other non-DLL's. Prune that list.
// .NET Framework assemblies are not included. However, other Microsoft ones
// such as MSTestFramework may be included (resolved from GetSDKReferenceFiles).
if (ExtractResWFiles && Sources != null)
{
_satelliteInputs = new List<ITaskItem>();
List<ITaskItem> newSources = new List<ITaskItem>();
foreach (ITaskItem item in Sources)
{
if (item.ItemSpec.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
if (item.ItemSpec.EndsWith(".resources.dll", StringComparison.OrdinalIgnoreCase))
{
_satelliteInputs.Add(item);
}
else
{
newSources.Add(item);
}
}
}
Sources = newSources.ToArray();
}
// If there are no sources to process, just return (with success) and report the condition.
if ((Sources == null) || (Sources.Length == 0))
{
Log.LogMessageFromResources(MessageImportance.Low, "GenerateResource.NoSources");
// Indicate we generated nothing
OutputResources = null;
return true;
}
if (!ValidateParameters())
{
// Indicate we generated nothing
OutputResources = null;
return false;
}
// In the case that OutputResources wasn't set, build up the outputs by transforming the Sources
// However if we are extracting ResW files, we cannot easily tell which files we'll produce up front,
// without loading each assembly.
if (!ExtractResWFiles && !CreateOutputResourcesNames())
{
// Indicate we generated nothing
OutputResources = null;
return false;
}
List<ITaskItem> inputsToProcess;
List<ITaskItem> outputsToProcess;
List<ITaskItem> cachedOutputFiles; // For incremental builds, this is the set of already-existing, up to date files.
GetResourcesToProcess(out inputsToProcess, out outputsToProcess, out cachedOutputFiles);
if (inputsToProcess.Count == 0 && !Log.HasLoggedErrors)
{
if (cachedOutputFiles.Count > 0)
{
OutputResources = cachedOutputFiles.ToArray();
}
Log.LogMessageFromResources("GenerateResource.NothingOutOfDate");
}
else if (FailIfNotIncremental)
{
Log.LogErrorFromResources("GenerateResource.OutOfDate");
}
else
{
if (!ComputePathToResGen())
{
// unable to compute the path to resgen.exe and that is necessary to
// continue forward, so return now.
return false;
}
// Check for the mark of the web on all possibly-exploitable files
// to be processed.
bool dangerousResourceFound = false;
foreach (ITaskItem source in _sources)
{
if (IsDangerous(source.ItemSpec))
{
Log.LogErrorWithCodeFromResources("GenerateResource.MOTW", source.ItemSpec);
dangerousResourceFound = true;
}
}
if (dangerousResourceFound)
{
// Do no further processing
return false;
}
if (ExecuteAsTool)
{
outOfProcExecutionSucceeded = GenerateResourcesUsingResGen(inputsToProcess, outputsToProcess);
}
else // Execute in-proc (or in a separate appdomain if necessary)
{
// Log equivalent command line as this is a convenient way to log all the references, etc
// even though we're not actually running resgen.exe
LogResgenCommandLine(inputsToProcess, outputsToProcess);
#if FEATURE_APPDOMAIN
// Figure out whether a separate AppDomain is required because an assembly would be locked.
bool needSeparateAppDomain = NeedSeparateAppDomain();
AppDomain appDomain = null;
#endif
ProcessResourceFiles process = null;
try
{
#if FEATURE_APPDOMAIN
if (needSeparateAppDomain)
{
// 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<ITaskItem>();
appDomain = AppDomain.CreateDomain(
"generateResourceAppDomain",
null,
AppDomain.CurrentDomain.SetupInformation);
object obj = appDomain.CreateInstanceFromAndUnwrap(
typeof(ProcessResourceFiles).Module.FullyQualifiedName,
typeof(ProcessResourceFiles).FullName);
Type processType = obj.GetType();
ErrorUtilities.VerifyThrow(processType == typeof(ProcessResourceFiles), "Somehow got a wrong and possibly incompatible type for ProcessResourceFiles.");
process = (ProcessResourceFiles)obj;
RecordItemsForDisconnectIfNecessary(_references);
RecordItemsForDisconnectIfNecessary(inputsToProcess);
RecordItemsForDisconnectIfNecessary(outputsToProcess);
}
else
#endif
{
process = new ProcessResourceFiles();
}
process.Run(Log,
_references,
inputsToProcess,
_satelliteInputs,
outputsToProcess,
UseSourcePath,
UsePreserializedResources,
StronglyTypedLanguage,
_stronglyTypedNamespace,
_stronglyTypedManifestPrefix,
StronglyTypedFileName,
StronglyTypedClassName,
PublicClass,
ExtractResWFiles,
OutputDirectory,
WarnOnBinaryFormatterUse);
this.StronglyTypedClassName = process.StronglyTypedClassName; // in case a default was chosen
this.StronglyTypedFileName = process.StronglyTypedFilename; // in case a default was chosen
_stronglyTypedResourceSuccessfullyCreated = process.StronglyTypedResourceSuccessfullyCreated;
if (process.UnsuccessfullyCreatedOutFiles != null)
{
foreach (string item in process.UnsuccessfullyCreatedOutFiles)
{
_unsuccessfullyCreatedOutFiles.Add(item);
}
}
if (ExtractResWFiles)
{
ITaskItem[] outputResources = process.ExtractedResWFiles.ToArray();
#if FEATURE_APPDOMAIN
if (needSeparateAppDomain)
{
// Ensure we can unload the other AppDomain, yet still use the
// ITaskItems we got back. Clone them.
outputResources = CloneValuesInThisAppDomain(outputResources);
}
#endif
if (cachedOutputFiles.Count > 0)
{
OutputResources = new ITaskItem[outputResources.Length + cachedOutputFiles.Count];
outputResources.CopyTo(OutputResources, 0);
cachedOutputFiles.CopyTo(OutputResources, outputResources.Length);
}
else
{
OutputResources = outputResources;
}
// Get portable library cache info (and if needed, marshal it to this AD).
List<ResGenDependencies.PortableLibraryFile> portableLibraryCacheInfo = process.PortableLibraryCacheInfo;
for (int i = 0; i < portableLibraryCacheInfo.Count; i++)
{
_cache.UpdatePortableLibrary(portableLibraryCacheInfo[i]);
}
}
process = null;
}
finally
{
#if FEATURE_APPDOMAIN
if (needSeparateAppDomain && appDomain != null)
{
Log.MarkAsInactive();
AppDomain.Unload(appDomain);
process = null;
appDomain = null;
// 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 (ITaskItem item in _remotedTaskItems)
{
if (item is MarshalByRefObject marshalByRefObject)
{
// Tell remoting to forget connections to the taskitem
RemotingServices.Disconnect(marshalByRefObject);
}
}
}
_remotedTaskItems = null;
}
#endif
}
}
}
// And now we serialize the cache to save our resgen linked file resolution for later use.
WriteStateFile();
RemoveUnsuccessfullyCreatedResourcesFromOutputResources();
RecordFilesWritten();
}
MSBuildEventSource.Log.GenerateResourceOverallStop();
return !Log.HasLoggedErrors && outOfProcExecutionSucceeded;
}
#if FEATURE_RESXREADER_LIVEDESERIALIZATION
private static readonly bool AllowMOTW = !NativeMethodsShared.IsWindows || (Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\SDK", "AllowProcessOfUntrustedResourceFiles", null) is string allowUntrustedFiles && allowUntrustedFiles.Equals("true", StringComparison.OrdinalIgnoreCase));
private const string CLSID_InternetSecurityManager = "7b8a2d94-0ac9-11d1-896c-00c04fb6bfc4";
private const uint ZoneInternet = 3;
private static IInternetSecurityManager internetSecurityManager = null;
#endif
// Resources can have arbitrarily serialized objects in them which can execute arbitrary code
// so check to see if we should trust them before analyzing them
private bool IsDangerous(String filename)
{
#if !FEATURE_RESXREADER_LIVEDESERIALIZATION
return false;
}
#else
// If they are opted out, there's no work to do
if (AllowMOTW)
{
return false;
}
// First check the zone, if they are not an untrusted zone, they aren't dangerous
if (internetSecurityManager == null)
{
Type iismType = Type.GetTypeFromCLSID(new Guid(CLSID_InternetSecurityManager));
internetSecurityManager = (IInternetSecurityManager)Activator.CreateInstance(iismType);
}
int zone;
internetSecurityManager.MapUrlToZone(Path.GetFullPath(filename), out zone, 0);
if (zone < ZoneInternet)
{
return false;
}
// By default all file types that get here are considered dangerous
bool dangerous = true;
string extension = Path.GetExtension(filename);
if (String.Equals(extension, ".resx", StringComparison.OrdinalIgnoreCase) ||
String.Equals(extension, ".resw", StringComparison.OrdinalIgnoreCase))
{
// XML files are only dangerous if there are unrecognized objects in them
dangerous = false;
FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
XmlTextReader reader = new XmlTextReader(stream);
reader.DtdProcessing = DtdProcessing.Ignore;
reader.XmlResolver = null;
try
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
string s = reader.LocalName;
// We only want to parse data nodes,
// the mimetype attribute gives the serializer
// that's requested.
if (reader.LocalName.Equals("data"))
{
if (reader["mimetype"] != null)
{
dangerous = true;
}
}
else if (reader.LocalName.Equals("metadata"))
{
if (reader["mimetype"] != null)
{
dangerous = true;
}
}
}
}
}
catch
{
// If we hit an error while parsing assume there's a dangerous type in this file.
dangerous = true;
}
stream.Close();
}