-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
BuildManager.cs
3429 lines (2684 loc) · 147 KB
/
BuildManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//------------------------------------------------------------------------------
// <copyright file="BuildManager.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/************************************************************************************************************/
namespace System.Web.Compilation {
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Profile;
using System.Web.UI;
using System.Web.Util;
using System.Xml;
/// <devdoc>
/// <para>
/// IProvider compilation related services
/// </para>
/// </devdoc>
public sealed class BuildManager {
/// Contants relating to generated assembly names
// All generated assemblies start with this prefix
internal const string AssemblyNamePrefix = "App_";
// Web assemblies are the assemblies generated from web files (aspx, ascx, ...)
internal const string WebAssemblyNamePrefix = AssemblyNamePrefix + "Web_";
internal const string AppThemeAssemblyNamePrefix = AssemblyNamePrefix + "Theme_";
internal const string GlobalThemeAssemblyNamePrefix = AssemblyNamePrefix + "GlobalTheme_";
internal const string AppBrowserCapAssemblyNamePrefix = AssemblyNamePrefix + "Browsers";
private const string CodeDirectoryAssemblyName = AssemblyNamePrefix + "Code";
internal const string SubCodeDirectoryAssemblyNamePrefix = AssemblyNamePrefix + "SubCode_";
private const string ResourcesDirectoryAssemblyName = AssemblyNamePrefix + "GlobalResources";
private const string LocalResourcesDirectoryAssemblyName = AssemblyNamePrefix + "LocalResources";
private const string WebRefDirectoryAssemblyName = AssemblyNamePrefix + "WebReferences";
internal const string GlobalAsaxAssemblyName = AssemblyNamePrefix + HttpApplicationFactory.applicationFileName;
private const string LicensesAssemblyName = AssemblyNamePrefix + "Licenses";
internal const string UpdatableInheritReplacementToken = "__ASPNET_INHERITS";
// Name of the temporary subdirectory under the codegen folder for buildproviders to generate embedded resource files.
private const string CodegenResourceDirectoryName = "ResX";
private static System.Security.Cryptography.RNGCryptoServiceProvider _rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
private static bool _theBuildManagerInitialized;
private static Exception _initializeException;
private static BuildManager _theBuildManager = new BuildManager(); // single instance of the class
private static long s_topLevelHash;
private readonly HashCodeCombiner _preAppStartHashCodeCombiner = new HashCodeCombiner();
internal static BuildManager TheBuildManager { get { return _theBuildManager; } }
// Precompilation related fields
private const string precompMarkerFileName = "PrecompiledApp.config";
private string _precompTargetPhysicalDir;
private PrecompilationFlags _precompilationFlags;
private bool _isPrecompiledApp;
private bool _isPrecompiledAppComputed;
private bool _isUpdatablePrecompiledApp;
private bool _precompilingApp; // we're in the process of precompiling an app
private string _strongNameKeyFile;
private string _strongNameKeyContainer;
private string _codegenResourceDir;
private bool _optimizeCompilations;
internal static bool OptimizeCompilations {
get { return _theBuildManager._optimizeCompilations; }
}
// filepath to the generated web.hash file, This file should only be re-created when
// the appdomain is restarted and the top-level generated assemblies need to be recompiled.
private string _webHashFilePath;
internal static String WebHashFilePath {
get { return _theBuildManager._webHashFilePath; }
}
private BuildResultCache[] _caches;
private StandardDiskBuildResultCache _codeGenCache;
private MemoryBuildResultCache _memoryCache;
private bool _topLevelFilesCompiledStarted;
private bool _topLevelFilesCompiledCompleted;
private Exception _topLevelFileCompilationException;
private BuildResultCompiledGlobalAsaxType _globalAsaxBuildResult;
private Type _profileType;
// Special top level directories that are treated differently from regular web directories
// during precompilation (e.g. App_Code)
private StringSet _excludedTopLevelDirectories;
// Directories that are not requestable
private StringSet _forbiddenTopLevelDirectories;
private StringSet _excludedCodeSubdirectories;
private List<VirtualPath> _excludedCompilationPaths;
private CompilationStage _compilationStage = CompilationStage.PreTopLevelFiles;
internal static CompilationStage CompilationStage { get { return _theBuildManager._compilationStage; } }
private VirtualPath _scriptVirtualDir;
private VirtualPath _globalAsaxVirtualPath;
internal static VirtualPath ScriptVirtualDir { get { return _theBuildManager._scriptVirtualDir; } }
internal static VirtualPath GlobalAsaxVirtualPath { get { return _theBuildManager._globalAsaxVirtualPath; } }
private BuildManager() { }
[PermissionSet(SecurityAction.Assert, Unrestricted = true)]
internal static bool InitializeBuildManager() {
// If we already tried and got an exception, just rethrow it
if (_initializeException != null) {
// We need to wrap it in a new exception, otherwise we lose the original stack.
throw new HttpException(_initializeException.Message, _initializeException);
}
if (!_theBuildManagerInitialized) {
// If Fusion was not yet initialized, skip the init.
// This can happen when there is a very early failure (e.g. see VSWhidbey 137366)
Debug.Trace("BuildManager", "InitializeBuildManager " + HttpRuntime.FusionInited);
if (!HttpRuntime.FusionInited)
return false;
// Likewise, if the trust level has not yet been determined, skip the init (VSWhidbey 422311)
if (HttpRuntime.TrustLevel == null)
return false;
_theBuildManagerInitialized = true;
try {
_theBuildManager.Initialize();
}
catch (Exception e) {
_theBuildManagerInitialized = false;
_initializeException = e;
throw;
}
}
return true;
}
private ClientBuildManagerCallback _cbmCallback;
internal static ClientBuildManagerCallback CBMCallback { get { return _theBuildManager._cbmCallback; } }
private static bool _parseErrorReported;
internal static void ReportParseError(ParserError parseError) {
// If there is a CBM callback, inform it of the error
if (BuildManager.CBMCallback != null) {
_parseErrorReported = true;
BuildManager.CBMCallback.ReportParseError(parseError);
}
}
private void ReportTopLevelCompilationException() {
Debug.Assert(_topLevelFileCompilationException != null);
// Try to report the cached error to the CBM callback
ReportErrorsFromException(_topLevelFileCompilationException);
// We need to wrap it in a new exception, otherwise we lose the original stack.
throw new HttpException(_topLevelFileCompilationException.Message,
_topLevelFileCompilationException);
}
// Given an exception, attempt to turn it into calls to the CBM callback
private void ReportErrorsFromException(Exception e) {
// If there is no CBM callback, nothing to do
if (BuildManager.CBMCallback == null)
return;
// Call the CBM callback as appropriate, based on the type of exception
if (e is HttpCompileException) {
CompilerResults results = ((HttpCompileException)e).Results;
foreach (CompilerError error in results.Errors) {
BuildManager.CBMCallback.ReportCompilerError(error);
}
}
else if (e is HttpParseException) {
foreach (ParserError parseError in ((HttpParseException)e).ParserErrors) {
ReportParseError(parseError);
}
}
}
// The assemblies produced from the code directories and global.asax, which
// every other compilation will linked with.
private List<Assembly> _topLevelReferencedAssemblies = new List<Assembly>() {
typeof(HttpRuntime).Assembly,
typeof(System.ComponentModel.Component).Assembly,
};
private List<Assembly> TopLevelReferencedAssemblies { get { return _topLevelReferencedAssemblies; } }
private Dictionary<String, AssemblyReferenceInfo> _topLevelAssembliesIndexTable;
private IDictionary<String, AssemblyReferenceInfo> TopLevelAssembliesIndexTable { get { return _topLevelAssembliesIndexTable; } }
private Dictionary<String, String> _generatedFileTable;
internal static Dictionary<String, String> GenerateFileTable {
get {
if (_theBuildManager._generatedFileTable == null) {
_theBuildManager._generatedFileTable = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase);
}
return _theBuildManager._generatedFileTable;
}
}
private ArrayList _codeAssemblies;
public static IList CodeAssemblies {
get {
_theBuildManager.EnsureTopLevelFilesCompiled();
return _theBuildManager._codeAssemblies;
}
}
private IDictionary _assemblyResolveMapping;
private Assembly _appResourcesAssembly;
internal static Assembly AppResourcesAssembly { get { return _theBuildManager._appResourcesAssembly; } }
// Indicates whether the parsers should coninue processing for more errors.
// This is used in both CBM precompile-web, precompile-page and aspnet_compiler tool.
private bool _throwOnFirstParseError = true;
internal static bool ThrowOnFirstParseError {
get { return _theBuildManager._throwOnFirstParseError; }
set { _theBuildManager._throwOnFirstParseError = value; }
}
// Marks whether we are in the middle of performing precompilation, which affects how
// we deal with error handling and batching
private bool _performingPrecompilation = false;
internal static bool PerformingPrecompilation {
get { return _theBuildManager._performingPrecompilation; }
set { _theBuildManager._performingPrecompilation = value; }
}
private bool _skipTopLevelCompilationExceptions;
internal static bool SkipTopLevelCompilationExceptions {
get { return _theBuildManager._skipTopLevelCompilationExceptions; }
set { _theBuildManager._skipTopLevelCompilationExceptions = value; }
}
private static HashSet<Assembly> s_dynamicallyAddedReferencedAssembly = new HashSet<Assembly>();
public static void AddReferencedAssembly(Assembly assembly) {
if (assembly == null) {
throw new ArgumentNullException("assembly");
}
ThrowIfPreAppStartNotRunning();
s_dynamicallyAddedReferencedAssembly.Add(assembly);
}
/*
* Return the list of assemblies that a compilation needs to reference for a given
* config minus the top-level assemblies indexed later than removeIndex
*/
internal static ICollection GetReferencedAssemblies(CompilationSection compConfig, int removeIndex) {
AssemblySet referencedAssemblies = new AssemblySet();
// Add all the config assemblies to the list
foreach (AssemblyInfo a in compConfig.Assemblies) {
Assembly[] assemblies = a.AssemblyInternal;
if (assemblies == null) {
lock (compConfig) {
assemblies = a.AssemblyInternal;
if (assemblies == null)
//
assemblies = a.AssemblyInternal = compConfig.LoadAssembly(a);
}
}
for (int i = 0; i < assemblies.Length; i++) {
if (assemblies[i] != null) {
referencedAssemblies.Add(assemblies[i]);
}
}
}
// Clone the top level referenced assemblies (code + global.asax + etc...), up to the removeIndex
for (int i = 0; i < removeIndex; i++) {
referencedAssemblies.Add(TheBuildManager.TopLevelReferencedAssemblies[i]);
}
//
foreach (Assembly assembly in s_dynamicallyAddedReferencedAssembly) {
referencedAssemblies.Add(assembly);
}
return referencedAssemblies;
}
internal static ICollection GetReferencedAssemblies(CompilationSection compConfig) {
// Start by cloning the top level referenced assemblies (code + global.asax + etc...)
AssemblySet referencedAssemblies = AssemblySet.Create(
TheBuildManager.TopLevelReferencedAssemblies);
// Add all the config assemblies to the list
foreach (AssemblyInfo a in compConfig.Assemblies) {
Assembly[] assemblies = a.AssemblyInternal;
if (assemblies == null) {
lock (compConfig) {
assemblies = a.AssemblyInternal;
if (assemblies == null)
//
assemblies = a.AssemblyInternal = compConfig.LoadAssembly(a);
}
}
for (int i = 0; i < assemblies.Length; i++) {
if (assemblies[i] != null) {
referencedAssemblies.Add(assemblies[i]);
}
}
}
//
foreach (Assembly assembly in s_dynamicallyAddedReferencedAssembly) {
referencedAssemblies.Add(assembly);
}
return referencedAssemblies;
}
/*
* Return the list of assemblies that all page compilations need to reference. This includes
* config assemblies (<assemblies> section), bin assemblies and assemblies built from the
* app App_Code and other top level folders.
*/
/// <devdoc>
/// Returns the assemblies referenced at the root application level of the current appF
/// </devdoc>
public static ICollection GetReferencedAssemblies() {
CompilationSection compConfig = MTConfigUtil.GetCompilationAppConfig();
_theBuildManager.EnsureTopLevelFilesCompiled();
return GetReferencedAssemblies(compConfig);
}
/// <summary>
/// Specifies a string representing a dependency that the BuildManager factors when determining if a clean build is required.
/// </summary>
/// <param name="dependency">String representation of a dependency.</param>
public static void AddCompilationDependency(string dependency) {
if (String.IsNullOrEmpty(dependency)) {
throw new ArgumentException(SR.GetString(SR.Parameter_can_not_be_empty), "dependency");
}
BuildManager.ThrowIfPreAppStartNotRunning();
_theBuildManager._preAppStartHashCodeCombiner.AddObject(dependency);
}
/*
* Perform initialization work that should only be done once (per app domain).
*/
private void Initialize() {
Debug.Assert(_caches == null);
// Register an AssemblyResolve event
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(this.ResolveAssembly);
_globalAsaxVirtualPath = HttpRuntime.AppDomainAppVirtualPathObject.SimpleCombine(
HttpApplicationFactory.applicationFileName);
_webHashFilePath = Path.Combine(HttpRuntime.CodegenDirInternal, "hash\\hash.web");
// Indicate whether we should ignore the top level compilation exceptions.
// In CBM case, we want to continue processing the page and return partial info even
// if the code files fail to compile.
_skipTopLevelCompilationExceptions = BuildManagerHost.InClientBuildManager;
// Deal with precompilation if we're in that mode
SetPrecompilationInfo(HostingEnvironment.HostingParameters);
MultiTargetingUtil.EnsureFrameworkNamesInitialized();
// The init code depends on whether we're precompiling or running an app
if (_precompTargetPhysicalDir != null) {
// If the app is already precompiled, fail
FailIfPrecompiledApp();
PrecompilationModeInitialize();
}
else {
// Check if this application has been precompiled by aspnet_compiler.exe
if (IsPrecompiledApp) {
PrecompiledAppRuntimeModeInitialize();
}
else {
RegularAppRuntimeModeInitialize();
}
}
_scriptVirtualDir = Util.GetScriptLocation();
// Top level directories that have a special semantic
_excludedTopLevelDirectories = new CaseInsensitiveStringSet();
_excludedTopLevelDirectories.Add(HttpRuntime.BinDirectoryName);
_excludedTopLevelDirectories.Add(HttpRuntime.CodeDirectoryName);
_excludedTopLevelDirectories.Add(HttpRuntime.ResourcesDirectoryName);
_excludedTopLevelDirectories.Add(HttpRuntime.LocalResourcesDirectoryName);
_excludedTopLevelDirectories.Add(HttpRuntime.WebRefDirectoryName);
_excludedTopLevelDirectories.Add(HttpRuntime.ThemesDirectoryName);
// Top level directories that are not requestable
// It's the same as _excludedTopLevelDirectories, except that we allow
// the bin directory to avoid a v1 breaking change (VSWhidbey 465018)
_forbiddenTopLevelDirectories = new CaseInsensitiveStringSet();
_forbiddenTopLevelDirectories.Add(HttpRuntime.CodeDirectoryName);
_forbiddenTopLevelDirectories.Add(HttpRuntime.ResourcesDirectoryName);
_forbiddenTopLevelDirectories.Add(HttpRuntime.LocalResourcesDirectoryName);
_forbiddenTopLevelDirectories.Add(HttpRuntime.WebRefDirectoryName);
_forbiddenTopLevelDirectories.Add(HttpRuntime.ThemesDirectoryName);
LoadLicensesAssemblyIfExists();
}
/*
* Init code used when we are running a non-precompiled app
*/
private void RegularAppRuntimeModeInitialize() {
//
// Initialize the caches
//
// Always try the memory cache first
_memoryCache = new MemoryBuildResultCache(HttpRuntime.CacheInternal);
// Use the standard disk cache for regular apps
_codeGenCache = new StandardDiskBuildResultCache(HttpRuntime.CodegenDirInternal);
_caches = new BuildResultCache[] { _memoryCache, _codeGenCache };
}
/*
* Init code used when we are running a precompiled app
*/
private void PrecompiledAppRuntimeModeInitialize() {
//
// Initialize the caches
//
// Always try the memory cache first
_memoryCache = new MemoryBuildResultCache(HttpRuntime.CacheInternal);
// Used the precomp cache for precompiled apps
BuildResultCache preCompCache = new PrecompiledSiteDiskBuildResultCache(
HttpRuntime.BinDirectoryInternal);
// Also create a regular disk cache so that we can compile and cache additional things.
// This is useful even in non-updatable precomp, to cache DefaultWsdlHelpGenerator.aspx.
_codeGenCache = new StandardDiskBuildResultCache(HttpRuntime.CodegenDirInternal);
_caches = new BuildResultCache[] { _memoryCache, preCompCache, _codeGenCache };
}
/*
* Init code used when we are precompiling an app
*/
private void PrecompilationModeInitialize() {
// We are precompiling an app
// Always try the memory cache first
_memoryCache = new MemoryBuildResultCache(HttpRuntime.CacheInternal);
// Create a regular disk cache, to take advantage of the fact that the app
// may already have been compiled (and to cause it to be if it wasn't)
_codeGenCache = new StandardDiskBuildResultCache(HttpRuntime.CodegenDirInternal);
// Create a special disk cache in the target's bin directory. Use a slightly different
// implementation for the updatable case.
string targetBinDir = Path.Combine(_precompTargetPhysicalDir, HttpRuntime.BinDirectoryName);
BuildResultCache preCompilationCache;
if (PrecompilingForUpdatableDeployment) {
preCompilationCache = new UpdatablePrecompilerDiskBuildResultCache(targetBinDir);
}
else {
preCompilationCache = new PrecompilerDiskBuildResultCache(targetBinDir);
}
_caches = new BuildResultCache[] { _memoryCache, preCompilationCache, _codeGenCache };
}
// Load the licenses assembly from the bin dir if it exists (DevDiv 42149)
private void LoadLicensesAssemblyIfExists() {
string licAssemblyPath = Path.Combine(HttpRuntime.BinDirectoryInternal, LicensesAssemblyName + ".dll");
if (File.Exists(licAssemblyPath)) {
Assembly.Load(LicensesAssemblyName);
}
}
// DevDiv #520869: Signal the PortableCompilationOutputSnapshotType to
// restore a snapshot of portable compilation output
private static void RestorePortableCompilationOutputSnapshot() {
if (BuildManagerHost.InClientBuildManager ||
!AppSettings.PortableCompilationOutput ||
String.IsNullOrEmpty(AppSettings.PortableCompilationOutputSnapshotType)) {
return;
}
// If a PortableCompilationOutputSnapshotsType has been configured but failed to be loaded, let it throw
Type t = Type.GetType(AppSettings.PortableCompilationOutputSnapshotType, true);
object[] args = new Object[] { AppSettings.PortableCompilationOutputSnapshotTypeOptions };
t.InvokeMember("RestoreSnapshot", BindingFlags.Static | BindingFlags.Public | BindingFlags.InvokeMethod, null, t, args, CultureInfo.InvariantCulture);
}
private long CheckTopLevelFilesUpToDate(long cachedHash) {
bool gotLock = false;
try {
// Grab the compilation mutex, since this method accesses the codegen files
CompilationLock.GetLock(ref gotLock);
return CheckTopLevelFilesUpToDateInternal(cachedHash);
}
finally {
// Always release the mutex if we had taken it
if (gotLock) {
CompilationLock.ReleaseLock();
}
}
}
/*
* Check if the top level files are up to date, and cleanup the codegendir
* if they are not.
*/
private long CheckTopLevelFilesUpToDateInternal(long cachedHash) {
Debug.Trace("BuildManager", "specialFilesCombinedHash=" + cachedHash);
var specialFilesHashCodeCombiner = new HashCodeCombiner();
// Delete all the non essential files left over in the codegen dir, unless
// specialFilesCombinedHash is 0, in which case we delete *everything* further down
if (cachedHash != 0) {
_codeGenCache.RemoveOldTempFiles();
}
// Use a HashCodeCombiner object to handle the time stamps of all the 'special'
// files and directories that all compilations depend on:
// - System.Web.dll (in case there is a newer version of ASP.NET)
// - ~\Bin directory
// - ~\Resource directory
// - ~\WebReferences directory
// - ~\Code directory
// - global.asax
// Add a check for the app's physical path, in case it changes (ASURT 12975)
specialFilesHashCodeCombiner.AddObject(HttpRuntime.AppDomainAppPathInternal);
// Process System.Web.dll
string aspBinaryFileName = typeof(HttpRuntime).Module.FullyQualifiedName;
if (!AppSettings.PortableCompilationOutput) {
specialFilesHashCodeCombiner.AddFile(aspBinaryFileName);
}
else {
specialFilesHashCodeCombiner.AddExistingFileVersion(aspBinaryFileName);
}
// Process machine.config
string machineConfigFileName = HttpConfigurationSystem.MachineConfigurationFilePath;
if (!AppSettings.PortableCompilationOutput) {
specialFilesHashCodeCombiner.AddFile(machineConfigFileName);
}
else {
specialFilesHashCodeCombiner.AddFileContentHash(machineConfigFileName);
}
// Process root web.config
string rootWebConfigFileName = HttpConfigurationSystem.RootWebConfigurationFilePath;
if (!AppSettings.PortableCompilationOutput) {
specialFilesHashCodeCombiner.AddFile(rootWebConfigFileName);
}
else {
specialFilesHashCodeCombiner.AddFileContentHash(rootWebConfigFileName);
}
RuntimeConfig appConfig = RuntimeConfig.GetAppConfig();
CompilationSection compConfig = appConfig.Compilation;
// Ignore the OptimizeCompilations flag in ClientBuildManager mode
if (!BuildManagerHost.InClientBuildManager) {
_optimizeCompilations = compConfig.OptimizeCompilations;
}
// In optimized compilation mode, we don't clean out all the compilations just because a top level
// file changes. Instead, we let already compiled pages run against the newer top level binaries.
// In can be incorrect in some cases (e.g. return type of method changes from int to short), which is
// why the optimization is optional
if (!OptimizeCompilations) {
// Add a dependency of the bin, resources, webresources and code directories
string binPhysicalDir = HttpRuntime.BinDirectoryInternal;
specialFilesHashCodeCombiner.AddDirectory(binPhysicalDir);
// Note that we call AddResourcesDirectory instead of AddDirectory, since we only want
// culture neutral files to be taken into account (VSWhidbey 359029)
specialFilesHashCodeCombiner.AddResourcesDirectory(HttpRuntime.ResourcesDirectoryVirtualPath.MapPathInternal());
specialFilesHashCodeCombiner.AddDirectory(HttpRuntime.WebRefDirectoryVirtualPath.MapPathInternal());
specialFilesHashCodeCombiner.AddDirectory(HttpRuntime.CodeDirectoryVirtualPath.MapPathInternal());
// Add a dependency on the global asax file.
specialFilesHashCodeCombiner.AddFile(GlobalAsaxVirtualPath.MapPathInternal());
}
// Add a dependency on the hash of the app level <compilation> section, since it
// affects all compilations, including the code directory. It it changes,
// we may as well, start all over.
specialFilesHashCodeCombiner.AddObject(compConfig.RecompilationHash);
ProfileSection profileSection = appConfig.Profile;
specialFilesHashCodeCombiner.AddObject(profileSection.RecompilationHash);
// Add a dependency on file encoding (DevDiv 4560)
specialFilesHashCodeCombiner.AddObject(appConfig.Globalization.FileEncoding);
// Also add a dependency on the <trust> config section
TrustSection casConfig = appConfig.Trust;
specialFilesHashCodeCombiner.AddObject(casConfig.Level);
specialFilesHashCodeCombiner.AddObject(casConfig.OriginUrl);
// Add a dependency on whether profile is enabled
specialFilesHashCodeCombiner.AddObject(ProfileManager.Enabled);
// Add a dependency to the force debug flag.
specialFilesHashCodeCombiner.AddObject(PrecompilingWithDebugInfo);
CheckCodeGenFiles(specialFilesHashCodeCombiner.CombinedHash, cachedHash);
return specialFilesHashCodeCombiner.CombinedHash;
}
private void AfterPreAppStartExecute(Tuple<long, long> currentHash, Tuple<long, long> cachedTopLevelFilesHash) {
bool gotLock = false;
try {
// Grab the compilation mutex, since this method accesses the codegen files
CompilationLock.GetLock(ref gotLock);
// After pre app start methods have executed, the second hash value should match the current value in the hash code combiner.
CheckCodeGenFiles(currentHash.Item2, cachedTopLevelFilesHash.Item2);
if (!cachedTopLevelFilesHash.Equals(currentHash)) {
// Hash has changed. Persist it to disk
_codeGenCache.SavePreservedSpecialFilesCombinedHash(currentHash);
}
// VSWhidbey 537929 : Setup a filechange monitor for the web.hash file. If this file is modified,
// we will need to shutdown the appdomain so we don't use the obsolete assemblies. The new appdomain
// will use the up-to-date assemblies.
HttpRuntime.FileChangesMonitor.StartMonitoringFile(_webHashFilePath,
new FileChangeEventHandler(this.OnWebHashFileChange));
Debug.Assert(File.Exists(_webHashFilePath), _webHashFilePath);
}
finally {
// Always release the mutex if we had taken it
if (gotLock) {
CompilationLock.ReleaseLock();
}
}
}
private void CheckCodeGenFiles(long currentHash, long cachedTopLevelFilesHash) {
// Store the top level hash
s_topLevelHash = currentHash;
if (PrecompilingForCleanBuild || currentHash != cachedTopLevelFilesHash) {
if (PrecompilingForCleanBuild) {
Debug.Trace("BuildManager", "Precompiling for clean build.");
}
else {
Debug.Trace("BuildManager", "EnsureFirstTimeInit: hash codes don't match. Old=" +
cachedTopLevelFilesHash + " New=" + currentHash);
}
_codeGenCache.RemoveAllCodegenFiles();
}
else {
Debug.Trace("BuildManager", "BuildManager: the special files are up to date");
}
}
private void OnWebHashFileChange(Object sender, FileChangeEvent e) {
// Shutdown the app domain
Debug.Trace("BuildManager", _webHashFilePath + " changed - shutting down the app domain");
Debug.Trace("AppDomainFactory", "Shutting down appdomain because " + _webHashFilePath + " file changed");
string message = FileChangesMonitor.GenerateErrorMessage(e.Action, _webHashFilePath);
if (message == null) {
message = "Change in " + _webHashFilePath;
}
HttpRuntime.ShutdownAppDomain(ApplicationShutdownReason.BuildManagerChange, message);
}
/*
* Check if an assembly name is reserved for a special purpose
*/
internal static bool IsReservedAssemblyName(string assemblyName) {
if (String.Compare(assemblyName, CodeDirectoryAssemblyName,
StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(assemblyName, ResourcesDirectoryAssemblyName,
StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(assemblyName, WebRefDirectoryAssemblyName,
StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(assemblyName, GlobalAsaxAssemblyName,
StringComparison.OrdinalIgnoreCase) == 0) {
return true;
}
return false;
}
internal static void ThrowIfPreAppStartNotRunning() {
if (PreStartInitStage != PreStartInitStage.DuringPreStartInit) {
throw new InvalidOperationException(SR.GetString(SR.Method_can_only_be_called_during_pre_start_init));
}
}
internal static PreStartInitStage PreStartInitStage { get; private set; }
internal static void ExecutePreAppStart() {
// Restore a snapshot of compilation output when the AppDomain just starts and
// before any web site code runs
BuildManager.RestorePortableCompilationOutputSnapshot();
string preStartInitListPath = Path.Combine(HttpRuntime.CodegenDirInternal, "preStartInitList.web");
Tuple<long, long> specialFilesCombinedHash = _theBuildManager._codeGenCache.GetPreservedSpecialFilesCombinedHash();
// Check top level files have changed
long topLevelFilesHash = _theBuildManager.CheckTopLevelFilesUpToDate(specialFilesCombinedHash.Item1);
bool hasUpdated = false;
ISet<string> preApplicationStartAssemblyNames = CallPreStartInitMethods(preStartInitListPath, out hasUpdated);
// Check if pre application start code hashes have changed since.
var currentHash = Tuple.Create(topLevelFilesHash, _theBuildManager._preAppStartHashCodeCombiner.CombinedHash);
_theBuildManager.AfterPreAppStartExecute(currentHash, specialFilesCombinedHash);
// Save the cache file only if needed
if (hasUpdated) {
SavePreStartInitAssembliesToFile(preStartInitListPath, preApplicationStartAssemblyNames);
}
}
// this method requires global lock as the part of the fix of DevDiv bug 501777
private static ISet<string> CallPreStartInitMethods(string preStartInitListPath, out bool isRefAssemblyLoaded) {
Debug.Assert(PreStartInitStage == Compilation.PreStartInitStage.BeforePreStartInit);
isRefAssemblyLoaded = false;
using (new ApplicationImpersonationContext()) {
ICollection<MethodInfo> methods = null;
ICollection<Assembly> cachedPreStartAssemblies = LoadCachedPreAppStartAssemblies(preStartInitListPath);
if (cachedPreStartAssemblies != null) {
methods = GetPreStartInitMethodsFromAssemblyCollection(cachedPreStartAssemblies, buildingFromCache: true);
}
if (methods == null) {
// In case of ctlr-f5 scenario, two processes (VS and IisExpress) will start compilation simultaneously.
// GetPreStartInitMethodsFromReferencedAssemblies() will load all referenced assemblies
// If shallow copy is enabled, one process may fail due race condition in copying assemblies (DevDiv bug 501777)
// to fix it, put GetPreStartInitMethodsFromReferencedAssemblies() under the global lock
bool gotLock = false;
try {
CompilationLock.GetLock(ref gotLock);
methods = GetPreStartInitMethodsFromReferencedAssemblies();
isRefAssemblyLoaded = true;
}
finally {
if (gotLock) {
CompilationLock.ReleaseLock();
}
}
}
InvokePreStartInitMethods(methods);
Debug.Assert(PreStartInitStage == Compilation.PreStartInitStage.AfterPreStartInit);
return new HashSet<string>(methods.Select(m => m.DeclaringType.Assembly.FullName), StringComparer.OrdinalIgnoreCase);
}
}
internal static ISet<string> GetPreStartInitAssembliesFromFile(string path) {
if (FileUtil.FileExists(path)) {
try {
return new HashSet<string>(File.ReadAllLines(path), StringComparer.OrdinalIgnoreCase);
}
catch {
// If there are issues delete the bad file. The list will be created from scratch.
try {
File.Delete(path);
}
catch { }
}
}
return null;
}
// this method requires global lock as the part of the fix of DevDiv bug 501777
internal static void SavePreStartInitAssembliesToFile(string path, ISet<string> assemblies) {
Debug.Assert(assemblies != null);
Debug.Assert(!String.IsNullOrEmpty(path));
Debug.Assert(!assemblies.Any(String.IsNullOrEmpty));
bool gotLock = false;
try {
//put write under the global lock to avoid race condition
CompilationLock.GetLock(ref gotLock);
File.WriteAllLines(path, assemblies);
}
catch {
try {
File.Delete(path);
}
catch { }
}
finally {
if (gotLock) {
CompilationLock.ReleaseLock();
}
}
}
/// <summary>
/// Load the cached list of assemblies containing pre app start methods. Since this is a cache we never throw from it.
/// </summary>
internal static ICollection<Assembly> LoadCachedPreAppStartAssemblies(string preStartInitListPath) {
try {
// Force the enumerable to be saved to a list so that any issues with loading assemblies get caught here.
ISet<string> assemblyList = GetPreStartInitAssembliesFromFile(preStartInitListPath);
if (assemblyList == null) {
return null;
}
return assemblyList.Select(Assembly.Load)
.Distinct()
.ToList();
}
catch {
return null;
}
}
private static void InvokePreStartInitMethods(ICollection<MethodInfo> methods) {
PreStartInitStage = Compilation.PreStartInitStage.DuringPreStartInit;
try {
InvokePreStartInitMethodsCore(methods, HostingEnvironment.SetCultures);
PreStartInitStage = Compilation.PreStartInitStage.AfterPreStartInit;
}
catch {
PreStartInitStage = Compilation.PreStartInitStage.BeforePreStartInit;
throw;
}
}
internal static void InvokePreStartInitMethodsCore(ICollection<MethodInfo> methods, Func<IDisposable> setHostingEnvironmentCultures) {
// Remove dupes
var methodsToExecute = methods.Distinct();
// We want to execute PreApplicationStartmethods in a deterministic order. We'll use a sorted sequence of fully qualified type names and method names.
methodsToExecute = methodsToExecute.OrderBy(m => m.DeclaringType.AssemblyQualifiedName, StringComparer.OrdinalIgnoreCase)
.ThenBy(m => m.Name, StringComparer.OrdinalIgnoreCase);
foreach (var method in methodsToExecute) {
try {
//
using (setHostingEnvironmentCultures()) {
method.Invoke(null, null);
}
}
catch (TargetInvocationException e) {
string message = (e.InnerException != null ? e.InnerException.Message : String.Empty);
throw new InvalidOperationException(
SR.GetString(SR.Pre_application_start_init_method_threw_exception,
method.Name,
method.DeclaringType.FullName,
message),
e.InnerException);
}
}
}
private static ICollection<MethodInfo> GetPreStartInitMethodsFromReferencedAssemblies() {
CompilationSection compConfig = MTConfigUtil.GetCompilationConfig(HttpRuntime.AppDomainAppVirtualPath);
var referencedAssemblies = BuildManager.GetReferencedAssemblies(compConfig).Cast<Assembly>();
return GetPreStartInitMethodsFromAssemblyCollection(referencedAssemblies, buildingFromCache: false);
}
/// <summary>
/// Resolves pre application start methods from the assemblies specified.
/// </summary>
/// <param name="assemblies">The list of assemblies to look for methods in.</param>
/// <param name="buildingFromCache">Flag that determines if we are rebuilding methods from cache.</param>
internal static ICollection<MethodInfo> GetPreStartInitMethodsFromAssemblyCollection(IEnumerable<Assembly> assemblies, bool buildingFromCache) {
List<MethodInfo> methods = new List<MethodInfo>();
foreach (Assembly assembly in assemblies) {
PreApplicationStartMethodAttribute[] attributes = null;
try {
attributes = (PreApplicationStartMethodAttribute[])assembly.GetCustomAttributes(typeof(PreApplicationStartMethodAttribute), inherit: true);
}
catch {
// GetCustomAttributes invokes the constructors of the attributes, so it is possible that they might throw unexpected exceptions.
// (Dev10 bug 831981)
}
if (attributes == null || !attributes.Any()) {
// When rebuilding methods from cache every assembly specified must have one or more PreApplicationStartMethod attributes.
// If one of them doesn't, the cache might be stale. We'll force it to retry it with the list of assemblies currently loaded into the AppDomain.
if (buildingFromCache) {
return null;
}
}
else {
foreach (PreApplicationStartMethodAttribute attribute in attributes) {
MethodInfo method = null;
// Ensure the Type on the attribute is in the same assembly as the attribute itself
if (attribute.Type != null && !String.IsNullOrEmpty(attribute.MethodName) && attribute.Type.Assembly == assembly) {
method = FindPreStartInitMethod(attribute.Type, attribute.MethodName);
}
if (method != null) {
methods.Add(method);
}
else {
throw new HttpException(SR.GetString(SR.Invalid_PreApplicationStartMethodAttribute_value,
assembly.FullName,
(attribute.Type != null ? attribute.Type.FullName : String.Empty),
attribute.MethodName));
}
}
}
}
return methods;
}
internal static MethodInfo FindPreStartInitMethod(Type type, string methodName) {
Debug.Assert(type != null);
Debug.Assert(!String.IsNullOrEmpty(methodName));
MethodInfo method = null;
if (type.IsPublic) {
// Verify that type is public to avoid allowing internal code execution. This implementation will not match
// nested public types.
method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase,
binder: null,
types: Type.EmptyTypes,
modifiers: null);
}
return method;
}
// excludedSubdirectories contains a list of subdirectory names that should not be
// recursively included in the compilation (they'll instead be compiled into their
// own assemblies).
private Assembly CompileCodeDirectory(VirtualPath virtualDir, CodeDirectoryType dirType,
string assemblyName, StringSet excludedSubdirectories) {
Debug.Trace("BuildManager", "CompileCodeDirectory(" + virtualDir.VirtualPathString + ")");
bool isDirectoryAllowed = true;
if (IsPrecompiledApp) {
// Most special dirs are not allowed in precompiled apps. App_LocalResources is
// an exception, as it is allowed in updatable precompiled apps.
if (IsUpdatablePrecompiledAppInternal && dirType == CodeDirectoryType.LocalResources)
isDirectoryAllowed = true;
else
isDirectoryAllowed = false;
}