mirror of
https://github.com/BepInEx/mono.git
synced 2026-11-17 01:41:17 -10:00
* Makefile (net_2_0_dirs): added System.Web - it now depends on
System.Core, so it needs to be recompiled one more time after
System.Core is done.
2009-01-22 Marek Habersack <[email protected]>
* System.Web.dll.sources: added
System.Web.Compilation/BuildManagerCacheItem.cs,
System.Web.Compilation/BuildManagerDirectoryBuilder.cs,
System.Web.Compilation/BuildProviderGroup.cs
* Makefile (SYSTEMCORE_DEP): added. Defines SYSTEMCORE_DEP on the
mcs command line when System.Core is present.
Added the DEVEL define, which defines DEVEL on the mcs command
line. This is used to conditionally compile development helper code in
System.Web.Util.FileUtils (and possibly other stuff later on)
2009-01-22 Marek Habersack <[email protected]>
* XsdBuildProvider.cs: added missing BuildProviderAppliesTo
attribute.
* BuildProvider.cs: added new internal virtual method,
ExtractDependencies() whose purpose is to extract virtual path
dependencies without compiling the code, if possible.
* TemplateBuildProvider.cs: implemented the new
ExtractDependencies () method which uses regular expressions to
extract file dependencies from the source without having to
compile the file.
* CompilationException.cs: added a new public property, Results,
which returns the compilation results.
* BuildProviderGroup.cs: added. A simple class descending from
List <BuildProvider> which is used to hold a compilation batch -
that is a collection of BuildProvider instances.
* BuildManagerDirectoryBuilder.cs: new class which takes care of
generating compilation batches for the requested virtual path. A
set of batches is generated from files found in the same virtual
directory as the requested virtual path and all of the
dependencies of those files. All files are grouped in batches
within which no file depends upon its siblings. An attempt is made
to sort the batches from the "least dependent" to the "most
dependent" batches - i.e. the batches which do not depend on other
batches go to the top.
Code generating the batches now correctly detects dependency loops
and throws an exception when one is encountered.
Batches are represented as instances of a new class -
BuildProviderGroup.
* BuildManagerCacheItem.cs: added. Contains all the compilation
result information needed by BuildManager. See below.
* BuildManager.cs: complete batch building rewrite:
- only one build lock is held instead of a set of compilation
tickets. Only one thread can compile anything at one given
time.
- retrieving types from the build cache now uses a slim rw lock,
so that readers aren't blocked while compilation is in
progress. Writer lock is acquired only when adding a newly
compiled type to the build cache and when removing it after its
dependencies made it invalid.
- assembly references for each compilation are now collected
dynamically as the source is being compiled, this removed a lot
of complexity in dealing with assembles containing conflicting
types. As a consequence right now there may exist several
loaded assemblies containing the same type, but only the latest
of them will be used in new compiles.
- the thread compiling code can recurse into the Build method
which causes the recursively referenced code to be compiled
into a separate, uniquely named, assembly. This deals with all
recursion loops and dependency problems.
- automatic app domain restart after a certain number of compiles
is enabled now.
- improved compilation error handling. If a compilation error
occurs, the code attempts to recompile the assembly up to 3
times, each time removing from the batch the files/virtual
paths which failed parsing/compilation. If the attempts failed,
another one is made to compile only the virtual path requested
by the calling code. Only should that fail a compilation
exception is thrown. All the compilation errors are written to
stdout if the application is in the debug mode.
- changed assembly naming. It now generates assembly names based
on whether the compilation is recursive and whether the batch
being compiled contains more than one code unit or
not.
- compilation results are now stored in the cache as instances of
the new BuildManagerCacheItem class, which contains all the
information required by BuildManager to return types,
assemblies, dependencies etc.
- GetReferencedAssemblies now correctly returns only the
assemblies defined in the .config files.
- GetVirtualPathDependencies does not need to compile code
anymore in order to extract virtual path dependencies. New code
in BuildProvider.ExtractDependencies () takes care of that.
- a BuildManagerDirectoryBuilder class instance is used to
generate compilation batches.
* AssemblyBuilder.cs: added support for keeping track of which
code unit was generated by which BuildProvider andr which
BuildProvider produced a given source file. Both changes serve the
purpose of dealing with compilation errors in BuildManager.
* ApplicationFileBuildProvider.cs: added missing
BuildProviderAppliesTo attribute
2009-01-22 Marek Habersack <[email protected]>
* FileUtils.cs: added two conditionally compiled methods (they
require DEVEL to be defined) which output lines to a log file.
2009-01-22 Marek Habersack <[email protected]>
* WebTest.cs: Run () sets the internal field
BuildManager.suppressDebugModeMessages to true.
2009-01-22 Marek Habersack <[email protected]>
* Web.mono.config: added numRecompilesBeforeAppRestart attribute
to the compilation element, set to 100000, to avoid appdomain
restarts during tests.
svn path=/trunk/mcs/; revision=124179
1000 lines
29 KiB
C#
1000 lines
29 KiB
C#
//
|
|
// System.Web.Compilation.BuildManager
|
|
//
|
|
// Authors:
|
|
// Chris Toshok ([email protected])
|
|
// Gonzalo Paniagua Javier ([email protected])
|
|
// Marek Habersack ([email protected])
|
|
//
|
|
// (C) 2006-2009 Novell, Inc (http://www.novell.com)
|
|
//
|
|
|
|
//
|
|
// Permission is hereby granted, free of charge, to any person obtaining
|
|
// a copy of this software and associated documentation files (the
|
|
// "Software"), to deal in the Software without restriction, including
|
|
// without limitation the rights to use, copy, modify, merge, publish,
|
|
// distribute, sublicense, and/or sell copies of the Software, and to
|
|
// permit persons to whom the Software is furnished to do so, subject to
|
|
// the following conditions:
|
|
//
|
|
// The above copyright notice and this permission notice shall be
|
|
// included in all copies or substantial portions of the Software.
|
|
//
|
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
|
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
|
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
|
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
//
|
|
|
|
#if NET_2_0
|
|
|
|
using System;
|
|
using System.CodeDom;
|
|
using System.CodeDom.Compiler;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Collections.Specialized;
|
|
using System.ComponentModel;
|
|
using System.IO;
|
|
using System.Reflection;
|
|
using System.Text;
|
|
using System.Threading;
|
|
using System.Web;
|
|
using System.Web.Caching;
|
|
using System.Web.Configuration;
|
|
using System.Web.Hosting;
|
|
using System.Web.Util;
|
|
|
|
namespace System.Web.Compilation {
|
|
public sealed class BuildManager
|
|
{
|
|
internal const string FAKE_VIRTUAL_PATH_PREFIX = "/@@MonoFakeVirtualPath@@";
|
|
const string BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX = "@@Build_Manager@@";
|
|
static int BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX_LENGTH = BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX.Length;
|
|
|
|
static readonly object bigCompilationLock = new object ();
|
|
static readonly char[] virtualPathsToIgnoreSplitChars = {','};
|
|
|
|
static EventHandlerList events = new EventHandlerList ();
|
|
static object buildManagerRemoveEntryEvent = new object ();
|
|
|
|
static bool hosted;
|
|
static IEqualityComparer <string> comparer;
|
|
static StringComparison stringComparer;
|
|
static Dictionary <string, bool> virtualPathsToIgnore;
|
|
static bool haveVirtualPathsToIgnore;
|
|
static List <Assembly> AppCode_Assemblies = new List<Assembly>();
|
|
static List <Assembly> TopLevel_Assemblies = new List<Assembly>();
|
|
static Dictionary <Type, CodeDomProvider> codeDomProviders;
|
|
static Dictionary <string, BuildManagerCacheItem> buildCache;
|
|
static List <Assembly> referencedAssemblies;
|
|
|
|
static int buildCount;
|
|
|
|
// These two are here _only_ for the purpose of unit tests!
|
|
internal static bool suppressDebugModeMessages;
|
|
internal static bool suppressAutoRestart;
|
|
|
|
#if SYSTEMCORE_DEP
|
|
static ReaderWriterLockSlim buildCacheLock;
|
|
//static ReaderWriterLock buildCacheLock;
|
|
#endif
|
|
static ulong recursionDepth;
|
|
|
|
internal static event BuildManagerRemoveEntryEventHandler RemoveEntry {
|
|
add { events.AddHandler (buildManagerRemoveEntryEvent, value); }
|
|
remove { events.RemoveHandler (buildManagerRemoveEntryEvent, value); }
|
|
}
|
|
|
|
internal static bool BatchMode {
|
|
get {
|
|
if (!hosted)
|
|
return false; // Fix for bug #380985
|
|
|
|
CompilationSection cs = CompilationConfig;
|
|
if (cs == null)
|
|
return true;
|
|
|
|
return cs.Batch;
|
|
}
|
|
}
|
|
|
|
// Assemblies built from the App_Code directory
|
|
public static IList CodeAssemblies {
|
|
get { return AppCode_Assemblies; }
|
|
}
|
|
|
|
internal static CompilationSection CompilationConfig {
|
|
get { return WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection; }
|
|
}
|
|
|
|
internal static bool HaveResources {
|
|
get; set;
|
|
}
|
|
|
|
internal static IList TopLevelAssemblies {
|
|
get { return TopLevel_Assemblies; }
|
|
}
|
|
|
|
static BuildManager ()
|
|
{
|
|
if (HttpRuntime.CaseInsensitive) {
|
|
comparer = StringComparer.CurrentCultureIgnoreCase;
|
|
stringComparer = StringComparison.CurrentCultureIgnoreCase;
|
|
} else {
|
|
comparer = StringComparer.CurrentCulture;
|
|
stringComparer = StringComparison.CurrentCulture;
|
|
}
|
|
|
|
hosted = (AppDomain.CurrentDomain.GetData (ApplicationHost.MonoHostedDataKey) as string) == "yes";
|
|
buildCache = new Dictionary <string, BuildManagerCacheItem> (comparer);
|
|
#if SYSTEMCORE_DEP
|
|
buildCacheLock = new ReaderWriterLockSlim ();
|
|
//buildCacheLock = new ReaderWriterLock ();
|
|
#endif
|
|
referencedAssemblies = new List <Assembly> ();
|
|
recursionDepth = 0;
|
|
LoadVirtualPathsToIgnore ();
|
|
}
|
|
|
|
static void AddAssembly (Assembly asm, List <Assembly> al)
|
|
{
|
|
if (al.Contains (asm))
|
|
return;
|
|
|
|
al.Add (asm);
|
|
}
|
|
|
|
static void AddPathToIgnore (string vp)
|
|
{
|
|
if (virtualPathsToIgnore == null)
|
|
virtualPathsToIgnore = new Dictionary <string, bool> (comparer);
|
|
|
|
VirtualPath path = GetAbsoluteVirtualPath (vp);
|
|
string vpAbsolute = path.Absolute;
|
|
if (!virtualPathsToIgnore.ContainsKey (vpAbsolute)) {
|
|
virtualPathsToIgnore.Add (vpAbsolute, true);
|
|
haveVirtualPathsToIgnore = true;
|
|
}
|
|
|
|
string vpRelative = path.AppRelative;
|
|
if (!virtualPathsToIgnore.ContainsKey (vpRelative)) {
|
|
virtualPathsToIgnore.Add (vpRelative, true);
|
|
haveVirtualPathsToIgnore = true;
|
|
}
|
|
|
|
if (!virtualPathsToIgnore.ContainsKey (vp)) {
|
|
virtualPathsToIgnore.Add (vp, true);
|
|
haveVirtualPathsToIgnore = true;
|
|
}
|
|
}
|
|
|
|
internal static void AddToReferencedAssemblies (Assembly asm)
|
|
{
|
|
// should not be used
|
|
}
|
|
|
|
static void AssertVirtualPathExists (VirtualPath virtualPath)
|
|
{
|
|
string realpath;
|
|
bool dothrow = false;
|
|
|
|
if (virtualPath.StartsWith (FAKE_VIRTUAL_PATH_PREFIX)) {
|
|
realpath = virtualPath.Original.Substring (FAKE_VIRTUAL_PATH_PREFIX.Length);
|
|
if (!File.Exists (realpath) && !Directory.Exists (realpath))
|
|
dothrow = true;
|
|
} else {
|
|
VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
|
|
string vpAbsolute = virtualPath.Absolute;
|
|
|
|
if (!vpp.FileExists (vpAbsolute) && !vpp.DirectoryExists (vpAbsolute))
|
|
dothrow = true;
|
|
}
|
|
|
|
if (dothrow)
|
|
throw new HttpException (404, "The file '" + virtualPath + "' does not exist.");
|
|
}
|
|
|
|
static void Build (VirtualPath vp)
|
|
{
|
|
AssertVirtualPathExists (vp);
|
|
|
|
CompilationSection cs = CompilationConfig;
|
|
lock (bigCompilationLock) {
|
|
if (HasCachedItemNoLock (vp.Absolute))
|
|
return;
|
|
|
|
if (recursionDepth == 0)
|
|
referencedAssemblies.Clear ();
|
|
|
|
recursionDepth++;
|
|
try {
|
|
BuildInner (vp, cs != null ? cs.Debug : false);
|
|
buildCount++;
|
|
|
|
// See http://support.microsoft.com/kb/319947
|
|
if (!suppressAutoRestart && buildCount > cs.NumRecompilesBeforeAppRestart)
|
|
HttpRuntime.UnloadAppDomain ();
|
|
} finally {
|
|
recursionDepth--;
|
|
}
|
|
}
|
|
}
|
|
|
|
// This method assumes it is being called with the big compilation lock held
|
|
static void BuildInner (VirtualPath vp, bool debug)
|
|
{
|
|
var builder = new BuildManagerDirectoryBuilder (vp);
|
|
bool recursive = recursionDepth > 1;
|
|
List <BuildProviderGroup> builderGroups = builder.Build (IsSingleBuild (vp, recursive));
|
|
if (builderGroups == null)
|
|
return;
|
|
|
|
string vpabsolute = vp.Absolute;
|
|
int buildHash = (vpabsolute.GetHashCode () | (int)DateTime.Now.Ticks) + (int)recursionDepth;
|
|
string assemblyBaseName;
|
|
AssemblyBuilder abuilder;
|
|
CompilerType ct;
|
|
int attempts;
|
|
bool singleBuild, needMainVpBuild;
|
|
CompilationException compilationError;
|
|
|
|
// Each group becomes a separate assembly.
|
|
foreach (BuildProviderGroup group in builderGroups) {
|
|
needMainVpBuild = false;
|
|
compilationError = null;
|
|
assemblyBaseName = null;
|
|
|
|
if (group.Count == 1) {
|
|
if (recursive || !group.Master)
|
|
assemblyBaseName = String.Format ("{0}_{1}.{2:x}.", group.NamePrefix, VirtualPathUtility.GetFileName (group [0].VirtualPath), buildHash);
|
|
singleBuild = true;
|
|
} else
|
|
singleBuild = false;
|
|
|
|
if (assemblyBaseName == null)
|
|
assemblyBaseName = group.NamePrefix + "_";
|
|
|
|
ct = group.CompilerType;
|
|
attempts = 3;
|
|
while (attempts > 0) {
|
|
abuilder = new AssemblyBuilder (vp, CreateDomProvider (ct), assemblyBaseName);
|
|
abuilder.CompilerOptions = ct.CompilerParameters;
|
|
abuilder.AddAssemblyReference (GetReferencedAssemblies () as List <Assembly>);
|
|
try {
|
|
GenerateAssembly (abuilder, group, vp, debug);
|
|
attempts = 0;
|
|
} catch (CompilationException ex) {
|
|
attempts--;
|
|
if (singleBuild)
|
|
throw;
|
|
|
|
if (attempts == 0) {
|
|
needMainVpBuild = true;
|
|
compilationError = ex;
|
|
break;
|
|
}
|
|
|
|
CompilerResults results = ex.Results;
|
|
if (results == null)
|
|
throw;
|
|
else
|
|
RemoveFailedAssemblies (ex, abuilder, group, results, debug);
|
|
}
|
|
}
|
|
|
|
if (needMainVpBuild) {
|
|
// One last attempt - try to build just the requested path
|
|
// if it's not built yet or just return without throwing the
|
|
// exception if it has already been built.
|
|
if (HasCachedItemNoLock (vpabsolute)) {
|
|
if (debug)
|
|
DescribeCompilationError ("Path '{0}' built successfully, but a compilation exception has been thrown for other files:",
|
|
compilationError, vpabsolute);
|
|
return;
|
|
};
|
|
|
|
// This will trigger a recursive build of the requested vp,
|
|
// which means only the vp alone will be built (or not);
|
|
Build (vp);
|
|
if (HasCachedItemNoLock (vpabsolute)) {
|
|
if (debug)
|
|
DescribeCompilationError ("Path '{0}' built successfully, but a compilation exception has been thrown for other files:",
|
|
compilationError, vpabsolute);
|
|
return;
|
|
}
|
|
|
|
// In theory this code is unreachable. If the recursive
|
|
// build of the main vp failed, then it should have thrown
|
|
// the build exception.
|
|
throw compilationError;
|
|
}
|
|
}
|
|
}
|
|
|
|
static CodeDomProvider CreateDomProvider (CompilerType ct)
|
|
{
|
|
if (codeDomProviders == null)
|
|
codeDomProviders = new Dictionary <Type, CodeDomProvider> ();
|
|
|
|
Type type = ct.CodeDomProviderType;
|
|
if (type == null) {
|
|
CompilationSection cs = CompilationConfig;
|
|
CompilerType tmp = GetDefaultCompilerTypeForLanguage (cs.DefaultLanguage, cs);
|
|
if (tmp != null)
|
|
type = tmp.CodeDomProviderType;
|
|
}
|
|
|
|
if (type == null)
|
|
return null;
|
|
|
|
CodeDomProvider ret;
|
|
if (codeDomProviders.TryGetValue (type, out ret))
|
|
return ret;
|
|
|
|
ret = Activator.CreateInstance (type) as CodeDomProvider;
|
|
if (ret == null)
|
|
return null;
|
|
|
|
codeDomProviders.Add (type, ret);
|
|
return ret;
|
|
}
|
|
|
|
public static object CreateInstanceFromVirtualPath (string virtualPath, Type requiredBaseType)
|
|
{
|
|
if (requiredBaseType == null)
|
|
throw new NullReferenceException (); // This is what MS does, but
|
|
// from somewhere else.
|
|
|
|
Type type = GetCompiledType (virtualPath);
|
|
if (type == null)
|
|
return null;
|
|
|
|
if (!requiredBaseType.IsAssignableFrom (type))
|
|
throw new HttpException (500,
|
|
String.Format ("Type '{0}' does not inherit from '{1}'.", type.FullName, requiredBaseType.FullName));
|
|
|
|
return Activator.CreateInstance (type, null);
|
|
}
|
|
|
|
static void DescribeCompilationError (string format, CompilationException ex, params object[] parms)
|
|
{
|
|
StringBuilder sb = new StringBuilder ();
|
|
string newline = Environment.NewLine;
|
|
|
|
if (parms != null)
|
|
sb.AppendFormat (format + newline, parms);
|
|
else
|
|
sb.Append (format + newline);
|
|
|
|
CompilerResults results = ex != null ? ex.Results : null;
|
|
if (results == null)
|
|
sb.Append ("No compiler error information present." + newline);
|
|
else {
|
|
sb.Append ("Compiler errors:" + newline);
|
|
foreach (CompilerError error in results.Errors)
|
|
sb.Append (" " + error.ToString () + newline);
|
|
}
|
|
|
|
if (ex != null) {
|
|
sb.Append (newline + "Exception thrown:" + newline);
|
|
sb.Append (ex.ToString ());
|
|
}
|
|
|
|
ShowDebugModeMessage (sb.ToString ());
|
|
}
|
|
|
|
static BuildProvider FindBuildProviderForPhysicalPath (string path, BuildProviderGroup group, HttpRequest req)
|
|
{
|
|
if (req == null || String.IsNullOrEmpty (path))
|
|
return null;
|
|
|
|
foreach (BuildProvider bp in group) {
|
|
if (String.Compare (path, req.MapPath (bp.VirtualPath), stringComparer) == 0)
|
|
return bp;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
static void GenerateAssembly (AssemblyBuilder abuilder, BuildProviderGroup group, VirtualPath vp, bool debug)
|
|
{
|
|
List <string> deps;
|
|
BuildManagerCacheItem bmci;
|
|
string bvp, vpabsolute = vp.Absolute;
|
|
StringBuilder sb;
|
|
string newline;
|
|
int failedCount = 0;
|
|
|
|
if (debug) {
|
|
newline = Environment.NewLine;
|
|
sb = new StringBuilder ("Code generation for certain virtual paths in a batch failed. Those files have been removed from the batch." + newline);
|
|
sb.Append ("Since you're running in debug mode, here's some more information about the error:" + newline);
|
|
} else {
|
|
newline = null;
|
|
sb = null;
|
|
}
|
|
|
|
List <BuildProvider> failedBuildProviders = null;
|
|
foreach (BuildProvider bp in group) {
|
|
bvp = bp.VirtualPath;
|
|
if (HasCachedItemNoLock (bvp))
|
|
continue;
|
|
|
|
try {
|
|
bp.GenerateCode (abuilder);
|
|
} catch (Exception ex) {
|
|
if (String.Compare (bvp, vpabsolute, stringComparer) == 0)
|
|
throw;
|
|
if (failedBuildProviders == null)
|
|
failedBuildProviders = new List <BuildProvider> ();
|
|
failedBuildProviders.Add (bp);
|
|
failedCount++;
|
|
if (sb != null) {
|
|
if (failedCount > 1)
|
|
sb.Append (newline);
|
|
|
|
sb.AppendFormat ("Failed file virtual path: {0}; Exception: {1}{2}{1}", bp.VirtualPath, newline, ex);
|
|
}
|
|
continue;
|
|
}
|
|
|
|
deps = bp.ExtractDependencies ();
|
|
if (deps != null) {
|
|
foreach (string dep in deps) {
|
|
bmci = GetCachedItemNoLock (dep);
|
|
if (bmci == null || bmci.BuiltAssembly == null)
|
|
continue;
|
|
abuilder.AddAssemblyReference (bmci.BuiltAssembly);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (sb != null && failedCount > 0)
|
|
ShowDebugModeMessage (sb.ToString ());
|
|
|
|
if (failedBuildProviders != null) {
|
|
foreach (BuildProvider bp in failedBuildProviders)
|
|
group.Remove (bp);
|
|
}
|
|
|
|
foreach (Assembly asm in referencedAssemblies) {
|
|
if (asm == null)
|
|
continue;
|
|
|
|
abuilder.AddAssemblyReference (asm);
|
|
}
|
|
|
|
CompilerResults results = abuilder.BuildAssembly (vp);
|
|
|
|
// No results is not an error - it is possible that the assembly builder contained only .asmx and
|
|
// .ashx files which had no body, just the directive. In such case, no code unit or code file is added
|
|
// to the assembly builder and, in effect, no assembly is produced but there are STILL types that need
|
|
// to be added to the cache.
|
|
Assembly compiledAssembly = results != null ? results.CompiledAssembly : null;
|
|
bool locked = false;
|
|
try {
|
|
#if SYSTEMCORE_DEP
|
|
buildCacheLock.EnterWriteLock ();
|
|
//buildCacheLock.AcquireWriterLock (0);
|
|
#endif
|
|
locked = true;
|
|
if (compiledAssembly != null)
|
|
referencedAssemblies.Add (compiledAssembly);
|
|
|
|
foreach (BuildProvider bp in group) {
|
|
if (HasCachedItemNoLock (bp.VirtualPath))
|
|
continue;
|
|
|
|
StoreInCache (bp, compiledAssembly, results);
|
|
}
|
|
} finally {
|
|
#if SYSTEMCORE_DEP
|
|
if (locked) {
|
|
buildCacheLock.ExitWriteLock ();
|
|
//buildCacheLock.ReleaseWriterLock ();
|
|
}
|
|
#endif
|
|
}
|
|
}
|
|
|
|
static VirtualPath GetAbsoluteVirtualPath (string virtualPath)
|
|
{
|
|
string vp;
|
|
|
|
if (!VirtualPathUtility.IsRooted (virtualPath)) {
|
|
HttpContext ctx = HttpContext.Current;
|
|
HttpRequest req = ctx != null ? ctx.Request : null;
|
|
|
|
if (req != null)
|
|
vp = VirtualPathUtility.Combine (VirtualPathUtility.GetDirectory (req.FilePath), virtualPath);
|
|
else
|
|
throw new HttpException ("No context, cannot map paths.");
|
|
} else
|
|
vp = virtualPath;
|
|
|
|
return new VirtualPath (vp);
|
|
}
|
|
|
|
[MonoTODO ("Not implemented, always returns null")]
|
|
public static BuildDependencySet GetCachedBuildDependencySet (HttpContext context, string virtualPath)
|
|
{
|
|
return null; // null is ok here until we store the dependency set in the Cache.
|
|
}
|
|
|
|
static BuildManagerCacheItem GetCachedItem (string vp)
|
|
{
|
|
bool locked = false;
|
|
|
|
try {
|
|
#if SYSTEMCORE_DEP
|
|
buildCacheLock.EnterReadLock ();
|
|
//buildCacheLock.AcquireReaderLock (0);
|
|
#endif
|
|
locked = true;
|
|
return GetCachedItemNoLock (vp);
|
|
} finally {
|
|
#if SYSTEMCORE_DEP
|
|
if (locked)
|
|
buildCacheLock.ExitReadLock ();
|
|
//buildCacheLock.ReleaseReaderLock ();
|
|
#endif
|
|
}
|
|
}
|
|
|
|
static BuildManagerCacheItem GetCachedItemNoLock (string vp)
|
|
{
|
|
BuildManagerCacheItem ret;
|
|
if (buildCache.TryGetValue (vp, out ret))
|
|
return ret;
|
|
|
|
return null;
|
|
}
|
|
|
|
internal static Type GetCodeDomProviderType (BuildProvider provider)
|
|
{
|
|
CompilerType codeCompilerType;
|
|
Type codeDomProviderType = null;
|
|
|
|
codeCompilerType = provider.CodeCompilerType;
|
|
if (codeCompilerType != null)
|
|
codeDomProviderType = codeCompilerType.CodeDomProviderType;
|
|
|
|
if (codeDomProviderType == null)
|
|
throw new HttpException (String.Concat ("Provider '", provider, " 'fails to specify the compiler type."));
|
|
|
|
return codeDomProviderType;
|
|
}
|
|
|
|
public static Assembly GetCompiledAssembly (string virtualPath)
|
|
{
|
|
VirtualPath vp = GetAbsoluteVirtualPath (virtualPath);
|
|
string vpabsolute = vp.Absolute;
|
|
BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
|
|
if (bmci != null)
|
|
return bmci.BuiltAssembly;
|
|
|
|
Build (vp);
|
|
bmci = GetCachedItem (vpabsolute);
|
|
if (bmci != null)
|
|
return bmci.BuiltAssembly;
|
|
|
|
return null;
|
|
}
|
|
|
|
public static Type GetCompiledType (string virtualPath)
|
|
{
|
|
VirtualPath vp = GetAbsoluteVirtualPath (virtualPath);
|
|
string vpabsolute = vp.Absolute;
|
|
BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
|
|
if (bmci != null) {
|
|
ReferenceAssemblyInCompilation (bmci);
|
|
return bmci.Type;
|
|
}
|
|
|
|
Build (vp);
|
|
bmci = GetCachedItem (vpabsolute);
|
|
if (bmci != null) {
|
|
ReferenceAssemblyInCompilation (bmci);
|
|
return bmci.Type;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public static string GetCompiledCustomString (string virtualPath)
|
|
{
|
|
VirtualPath vp = GetAbsoluteVirtualPath (virtualPath);
|
|
string vpabsolute = vp.Absolute;
|
|
BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
|
|
if (bmci != null)
|
|
return bmci.CompiledCustomString;
|
|
|
|
Build (vp);
|
|
bmci = GetCachedItem (vpabsolute);
|
|
if (bmci != null)
|
|
return bmci.CompiledCustomString;
|
|
|
|
return null;
|
|
}
|
|
|
|
internal static CompilerType GetDefaultCompilerTypeForLanguage (string language, CompilationSection configSection)
|
|
{
|
|
return GetDefaultCompilerTypeForLanguage (language, configSection, true);
|
|
}
|
|
|
|
internal static CompilerType GetDefaultCompilerTypeForLanguage (string language, CompilationSection configSection, bool throwOnMissing)
|
|
{
|
|
// MS throws when accesing a Hashtable, we do here.
|
|
if (language == null || language.Length == 0)
|
|
throw new ArgumentNullException ("language");
|
|
|
|
CompilationSection config;
|
|
if (configSection == null)
|
|
config = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
|
|
else
|
|
config = configSection;
|
|
|
|
Compiler compiler = config.Compilers.Get (language);
|
|
CompilerParameters p;
|
|
Type type;
|
|
|
|
if (compiler != null) {
|
|
type = HttpApplication.LoadType (compiler.Type, true);
|
|
p = new CompilerParameters ();
|
|
p.CompilerOptions = compiler.CompilerOptions;
|
|
p.WarningLevel = compiler.WarningLevel;
|
|
SetCommonParameters (config, p, type, language);
|
|
return new CompilerType (type, p);
|
|
}
|
|
|
|
if (CodeDomProvider.IsDefinedLanguage (language)) {
|
|
CompilerInfo info = CodeDomProvider.GetCompilerInfo (language);
|
|
p = info.CreateDefaultCompilerParameters ();
|
|
type = info.CodeDomProviderType;
|
|
SetCommonParameters (config, p, type, language);
|
|
return new CompilerType (type, p);
|
|
}
|
|
|
|
if (throwOnMissing)
|
|
throw new HttpException (String.Concat ("No compiler for language '", language, "'."));
|
|
|
|
return null;
|
|
}
|
|
|
|
public static ICollection GetReferencedAssemblies ()
|
|
{
|
|
List <Assembly> al = new List <Assembly> ();
|
|
|
|
CompilationSection compConfig = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
|
|
if (compConfig == null)
|
|
return al;
|
|
|
|
bool addAssembliesInBin = false;
|
|
foreach (AssemblyInfo info in compConfig.Assemblies) {
|
|
if (info.Assembly == "*")
|
|
addAssembliesInBin = true;
|
|
else
|
|
LoadAssembly (info, al);
|
|
}
|
|
|
|
foreach (Assembly topLevelAssembly in TopLevelAssemblies)
|
|
al.Add (topLevelAssembly);
|
|
|
|
foreach (string assLocation in WebConfigurationManager.ExtraAssemblies)
|
|
LoadAssembly (assLocation, al);
|
|
|
|
if (addAssembliesInBin)
|
|
foreach (string s in HttpApplication.BinDirectoryAssemblies) {
|
|
try {
|
|
LoadAssembly (s, al);
|
|
} catch (BadImageFormatException) {
|
|
// ignore silently
|
|
}
|
|
}
|
|
|
|
return al;
|
|
}
|
|
|
|
// The 2 GetType() overloads work on the global.asax, App_GlobalResources, App_WebReferences or App_Browsers
|
|
public static Type GetType (string typeName, bool throwOnError)
|
|
{
|
|
return GetType (typeName, throwOnError, false);
|
|
}
|
|
|
|
public static Type GetType (string typeName, bool throwOnError, bool ignoreCase)
|
|
{
|
|
Type ret = null;
|
|
try {
|
|
foreach (Assembly asm in TopLevel_Assemblies) {
|
|
ret = asm.GetType (typeName, throwOnError, ignoreCase);
|
|
if (ret != null)
|
|
break;
|
|
}
|
|
} catch (Exception ex) {
|
|
throw new HttpException ("Failed to find the specified type.", ex);
|
|
}
|
|
return ret;
|
|
}
|
|
|
|
public static ICollection GetVirtualPathDependencies (string virtualPath)
|
|
{
|
|
return GetVirtualPathDependencies (virtualPath, null);
|
|
}
|
|
|
|
internal static ICollection GetVirtualPathDependencies (string virtualPath, BuildProvider bprovider)
|
|
{
|
|
BuildProvider provider = bprovider;
|
|
if (provider == null) {
|
|
CompilationSection cs = CompilationConfig;
|
|
if (cs == null)
|
|
return null;
|
|
provider = BuildManagerDirectoryBuilder.GetBuildProvider (virtualPath, cs.BuildProviders);
|
|
}
|
|
|
|
if (provider == null)
|
|
return null;
|
|
|
|
return provider.ExtractDependencies ();
|
|
}
|
|
|
|
internal static bool HasCachedItemNoLock (string vp)
|
|
{
|
|
return buildCache.ContainsKey (vp);
|
|
}
|
|
|
|
internal static bool IgnoreVirtualPath (string virtualPath)
|
|
{
|
|
if (!haveVirtualPathsToIgnore)
|
|
return false;
|
|
|
|
if (virtualPathsToIgnore.ContainsKey (virtualPath))
|
|
return true;
|
|
|
|
return false;
|
|
}
|
|
|
|
static bool IsSingleBuild (VirtualPath vp, bool recursive)
|
|
{
|
|
if (String.Compare (vp.AppRelative, "~/global.asax", StringComparison.OrdinalIgnoreCase) == 0)
|
|
return true;
|
|
|
|
if (!BatchMode)
|
|
return true;
|
|
|
|
return recursive;
|
|
}
|
|
|
|
static void LoadAssembly (string path, List <Assembly> al)
|
|
{
|
|
AddAssembly (Assembly.LoadFrom (path), al);
|
|
}
|
|
|
|
static void LoadAssembly (AssemblyInfo info, List <Assembly> al)
|
|
{
|
|
AddAssembly (Assembly.Load (info.Assembly), al);
|
|
}
|
|
|
|
static void LoadVirtualPathsToIgnore ()
|
|
{
|
|
NameValueCollection appSettings = WebConfigurationManager.AppSettings;
|
|
if (appSettings == null)
|
|
return;
|
|
|
|
string pathsFromConfig = appSettings ["MonoAspnetBatchCompileIgnorePaths"];
|
|
string pathsFromFile = appSettings ["MonoAspnetBatchCompileIgnoreFromFile"];
|
|
|
|
if (!String.IsNullOrEmpty (pathsFromConfig)) {
|
|
string[] paths = pathsFromConfig.Split (virtualPathsToIgnoreSplitChars);
|
|
string path;
|
|
|
|
foreach (string p in paths) {
|
|
path = p.Trim ();
|
|
if (path.Length == 0)
|
|
continue;
|
|
|
|
AddPathToIgnore (path);
|
|
}
|
|
}
|
|
|
|
if (!String.IsNullOrEmpty (pathsFromFile)) {
|
|
string realpath;
|
|
HttpContext ctx = HttpContext.Current;
|
|
HttpRequest req = ctx != null ? ctx.Request : null;
|
|
|
|
if (req == null)
|
|
throw new HttpException ("Missing context, cannot continue.");
|
|
|
|
realpath = req.MapPath (pathsFromFile);
|
|
if (!File.Exists (realpath))
|
|
return;
|
|
|
|
string[] paths = File.ReadAllLines (realpath);
|
|
if (paths == null || paths.Length == 0)
|
|
return;
|
|
|
|
string path;
|
|
foreach (string p in paths) {
|
|
path = p.Trim ();
|
|
if (path.Length == 0)
|
|
continue;
|
|
|
|
AddPathToIgnore (path);
|
|
}
|
|
}
|
|
}
|
|
|
|
static void OnEntryRemoved (string vp)
|
|
{
|
|
BuildManagerRemoveEntryEventHandler eh = events [buildManagerRemoveEntryEvent] as BuildManagerRemoveEntryEventHandler;
|
|
|
|
if (eh != null)
|
|
eh (new BuildManagerRemoveEntryEventArgs (vp, HttpContext.Current));
|
|
}
|
|
|
|
static void OnVirtualPathChanged (string key, object value, CacheItemRemovedReason removedReason)
|
|
{
|
|
string virtualPath;
|
|
|
|
if (StrUtils.StartsWith (key, BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX))
|
|
virtualPath = key.Substring (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX_LENGTH);
|
|
else
|
|
return;
|
|
|
|
bool locked = false;
|
|
try {
|
|
#if SYSTEMCORE_DEP
|
|
buildCacheLock.EnterWriteLock ();
|
|
//buildCacheLock.AcquireWriterLock (0);
|
|
#endif
|
|
locked = true;
|
|
|
|
if (HasCachedItemNoLock (virtualPath)) {
|
|
buildCache.Remove (virtualPath);
|
|
OnEntryRemoved (virtualPath);
|
|
}
|
|
} finally {
|
|
#if SYSTEMCORE_DEP
|
|
if (locked) {
|
|
buildCacheLock.ExitWriteLock ();
|
|
//buildCacheLock.ReleaseWriterLock ();
|
|
}
|
|
#endif
|
|
}
|
|
}
|
|
|
|
static void ReferenceAssemblyInCompilation (BuildManagerCacheItem bmci)
|
|
{
|
|
if (recursionDepth == 0 || referencedAssemblies.Contains (bmci.BuiltAssembly))
|
|
return;
|
|
|
|
referencedAssemblies.Add (bmci.BuiltAssembly);
|
|
}
|
|
|
|
static void RemoveFailedAssemblies (CompilationException ex, AssemblyBuilder abuilder, BuildProviderGroup group,
|
|
CompilerResults results, bool debug)
|
|
{
|
|
StringBuilder sb;
|
|
string newline;
|
|
|
|
if (debug) {
|
|
newline = Environment.NewLine;
|
|
sb = new StringBuilder ("Compilation of certain files in a batch failed. Another attempt to compile the batch will be made." + newline);
|
|
sb.Append ("Since you're running in debug mode, here's some more information about the error:" + newline);
|
|
} else {
|
|
newline = null;
|
|
sb = null;
|
|
}
|
|
|
|
var failedBuildProviders = new List <BuildProvider> ();
|
|
BuildProvider bp;
|
|
HttpContext ctx = HttpContext.Current;
|
|
HttpRequest req = ctx != null ? ctx.Request : null;
|
|
|
|
foreach (CompilerError error in results.Errors) {
|
|
bp = abuilder.GetBuildProviderForPhysicalFilePath (error.FileName);
|
|
if (bp == null) {
|
|
bp = FindBuildProviderForPhysicalPath (error.FileName, group, req);
|
|
if (bp == null)
|
|
continue;
|
|
}
|
|
|
|
if (!failedBuildProviders.Contains (bp)) {
|
|
failedBuildProviders.Add (bp);
|
|
if (sb != null)
|
|
sb.AppendFormat ("\t{0}{1}", bp.VirtualPath, newline);
|
|
}
|
|
|
|
if (sb != null)
|
|
sb.AppendFormat ("\t\t{0}{1}", error, newline);
|
|
}
|
|
|
|
foreach (BuildProvider fbp in failedBuildProviders)
|
|
group.Remove (fbp);
|
|
|
|
if (sb != null) {
|
|
sb.AppendFormat ("{0}The following exception has been thrown for the file(s) listed above:{0}{1}",
|
|
newline, ex.ToString ());
|
|
ShowDebugModeMessage (sb.ToString ());
|
|
sb = null;
|
|
}
|
|
}
|
|
|
|
static void SetCommonParameters (CompilationSection config, CompilerParameters p, Type compilerType, string language)
|
|
{
|
|
p.IncludeDebugInformation = config.Debug;
|
|
MonoSettingsSection mss = WebConfigurationManager.GetSection ("system.web/monoSettings") as MonoSettingsSection;
|
|
if (mss == null || !mss.UseCompilersCompatibility)
|
|
return;
|
|
|
|
Compiler compiler = mss.CompilersCompatibility.Get (language);
|
|
if (compiler == null)
|
|
return;
|
|
|
|
Type type = HttpApplication.LoadType (compiler.Type, false);
|
|
if (type != compilerType)
|
|
return;
|
|
|
|
p.CompilerOptions = String.Concat (p.CompilerOptions, " ", compiler.CompilerOptions);
|
|
}
|
|
|
|
static void ShowDebugModeMessage (string msg)
|
|
{
|
|
if (suppressDebugModeMessages)
|
|
return;
|
|
|
|
Console.WriteLine ();
|
|
Console.WriteLine ("******* DEBUG MODE MESSAGE *******");
|
|
Console.WriteLine (msg);
|
|
Console.WriteLine ("******* DEBUG MODE MESSAGE *******");
|
|
Console.WriteLine ();
|
|
}
|
|
|
|
static void StoreInCache (BuildProvider bp, Assembly compiledAssembly, CompilerResults results)
|
|
{
|
|
buildCache.Add (bp.VirtualPath, new BuildManagerCacheItem (compiledAssembly, bp, results));
|
|
|
|
HttpContext ctx = HttpContext.Current;
|
|
HttpRequest req = ctx != null ? ctx.Request : null;
|
|
CacheDependency dep;
|
|
string virtualPath = bp.VirtualPath;
|
|
|
|
if (req != null) {
|
|
List <string> deps = bp.ExtractDependencies ();
|
|
var files = new List <string> ();
|
|
string physicalPath;
|
|
|
|
physicalPath = req.MapPath (virtualPath);
|
|
if (File.Exists (physicalPath))
|
|
files.Add (physicalPath);
|
|
|
|
if (deps != null && deps.Count > 0) {
|
|
foreach (string d in bp.ExtractDependencies ()) {
|
|
physicalPath = req.MapPath (d);
|
|
if (!File.Exists (physicalPath))
|
|
continue;
|
|
if (!files.Contains (physicalPath))
|
|
files.Add (physicalPath);
|
|
}
|
|
}
|
|
|
|
dep = new CacheDependency (files.ToArray ());
|
|
} else
|
|
dep = null;
|
|
|
|
HttpRuntime.InternalCache.Add (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX + virtualPath,
|
|
true,
|
|
dep,
|
|
Cache.NoAbsoluteExpiration,
|
|
Cache.NoSlidingExpiration,
|
|
CacheItemPriority.High,
|
|
new CacheItemRemovedCallback (OnVirtualPathChanged));
|
|
}
|
|
}
|
|
}
|
|
#endif
|