BuildManager.cs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. //
  2. // System.Web.Compilation.BuildManager
  3. //
  4. // Authors:
  5. // Chris Toshok ([email protected])
  6. // Gonzalo Paniagua Javier ([email protected])
  7. // Marek Habersack ([email protected])
  8. //
  9. // (C) 2006-2009 Novell, Inc (http://www.novell.com)
  10. //
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. #if NET_2_0
  32. using System;
  33. using System.CodeDom;
  34. using System.CodeDom.Compiler;
  35. using System.Collections;
  36. using System.Collections.Generic;
  37. using System.Collections.Specialized;
  38. using System.ComponentModel;
  39. using System.IO;
  40. using System.Reflection;
  41. using System.Text;
  42. using System.Threading;
  43. using System.Xml;
  44. using System.Web;
  45. using System.Web.Caching;
  46. using System.Web.Configuration;
  47. using System.Web.Hosting;
  48. using System.Web.Util;
  49. namespace System.Web.Compilation {
  50. public sealed class BuildManager
  51. {
  52. internal const string FAKE_VIRTUAL_PATH_PREFIX = "/@@MonoFakeVirtualPath@@";
  53. const string BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX = "@@Build_Manager@@";
  54. static int BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX_LENGTH = BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX.Length;
  55. static readonly object bigCompilationLock = new object ();
  56. static readonly char[] virtualPathsToIgnoreSplitChars = {','};
  57. static EventHandlerList events = new EventHandlerList ();
  58. static object buildManagerRemoveEntryEvent = new object ();
  59. static bool hosted;
  60. static IEqualityComparer <string> comparer;
  61. static StringComparison stringComparer;
  62. static Dictionary <string, bool> virtualPathsToIgnore;
  63. static bool haveVirtualPathsToIgnore;
  64. static List <Assembly> AppCode_Assemblies = new List<Assembly>();
  65. static List <Assembly> TopLevel_Assemblies = new List<Assembly>();
  66. static Dictionary <Type, CodeDomProvider> codeDomProviders;
  67. static Dictionary <string, BuildManagerCacheItem> buildCache;
  68. static List <Assembly> referencedAssemblies;
  69. static int buildCount;
  70. static bool is_precompiled;
  71. static Dictionary<string, PreCompilationData> precompiled;
  72. // This is here _only_ for the purpose of unit tests!
  73. internal static bool suppressDebugModeMessages;
  74. #if SYSTEMCORE_DEP
  75. static ReaderWriterLockSlim buildCacheLock;
  76. #else
  77. static ReaderWriterLock buildCacheLock;
  78. #endif
  79. static ulong recursionDepth;
  80. internal static event BuildManagerRemoveEntryEventHandler RemoveEntry {
  81. add { events.AddHandler (buildManagerRemoveEntryEvent, value); }
  82. remove { events.RemoveHandler (buildManagerRemoveEntryEvent, value); }
  83. }
  84. internal static bool BatchMode {
  85. get {
  86. if (!hosted)
  87. return false; // Fix for bug #380985
  88. CompilationSection cs = CompilationConfig;
  89. if (cs == null)
  90. return true;
  91. return cs.Batch;
  92. }
  93. }
  94. // Assemblies built from the App_Code directory
  95. public static IList CodeAssemblies {
  96. get { return AppCode_Assemblies; }
  97. }
  98. internal static CompilationSection CompilationConfig {
  99. get { return WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection; }
  100. }
  101. internal static bool HaveResources {
  102. get; set;
  103. }
  104. internal static IList TopLevelAssemblies {
  105. get { return TopLevel_Assemblies; }
  106. }
  107. static BuildManager ()
  108. {
  109. if (HttpRuntime.CaseInsensitive) {
  110. comparer = StringComparer.CurrentCultureIgnoreCase;
  111. stringComparer = StringComparison.CurrentCultureIgnoreCase;
  112. } else {
  113. comparer = StringComparer.CurrentCulture;
  114. stringComparer = StringComparison.CurrentCulture;
  115. }
  116. hosted = (AppDomain.CurrentDomain.GetData (ApplicationHost.MonoHostedDataKey) as string) == "yes";
  117. buildCache = new Dictionary <string, BuildManagerCacheItem> (comparer);
  118. #if SYSTEMCORE_DEP
  119. buildCacheLock = new ReaderWriterLockSlim ();
  120. #else
  121. buildCacheLock = new ReaderWriterLock ();
  122. #endif
  123. referencedAssemblies = new List <Assembly> ();
  124. recursionDepth = 0;
  125. string appPath = HttpRuntime.AppDomainAppPath;
  126. is_precompiled = String.IsNullOrEmpty (appPath) ? false : File.Exists (Path.Combine (appPath, "PrecompiledApp.config"));
  127. if (is_precompiled) {
  128. LoadPrecompilationInfo ();
  129. }
  130. LoadVirtualPathsToIgnore ();
  131. }
  132. static void LoadPrecompilationInfo ()
  133. {
  134. string [] compiled = Directory.GetFiles (HttpRuntime.BinDirectory, "*.compiled");
  135. foreach (string str in compiled) {
  136. LoadCompiled (str);
  137. }
  138. }
  139. static void LoadCompiled (string filename)
  140. {
  141. using (XmlTextReader reader = new XmlTextReader (filename)) {
  142. reader.MoveToContent ();
  143. if (reader.Name == "preserve" && reader.HasAttributes) {
  144. reader.MoveToNextAttribute ();
  145. string val = reader.Value;
  146. // 2 -> ashx
  147. // 3 -> ascx, aspx
  148. // 6 -> app_code - nothing to do here
  149. // 8 -> global.asax
  150. // 9 -> App_GlobalResources - nothing to do?
  151. if (reader.Name == "resultType" && (val == "2" || val == "3" || val == "8"))
  152. LoadPageData (reader);
  153. }
  154. }
  155. }
  156. class PreCompilationData {
  157. public string VirtualPath;
  158. public string AssemblyFileName;
  159. public string TypeName;
  160. public Type Type;
  161. }
  162. static void LoadPageData (XmlTextReader reader)
  163. {
  164. PreCompilationData pc_data = new PreCompilationData ();
  165. while (reader.MoveToNextAttribute ()) {
  166. string name = reader.Name;
  167. if (name == "virtualPath")
  168. pc_data.VirtualPath = reader.Value;
  169. else if (name == "assembly")
  170. pc_data.AssemblyFileName = reader.Value;
  171. else if (name == "type")
  172. pc_data.TypeName = reader.Value;
  173. }
  174. if (precompiled == null)
  175. precompiled = new Dictionary<string, PreCompilationData> (comparer);
  176. precompiled.Add (pc_data.VirtualPath, pc_data);
  177. }
  178. static void AddAssembly (Assembly asm, List <Assembly> al)
  179. {
  180. if (al.Contains (asm))
  181. return;
  182. al.Add (asm);
  183. }
  184. static void AddPathToIgnore (string vp)
  185. {
  186. if (virtualPathsToIgnore == null)
  187. virtualPathsToIgnore = new Dictionary <string, bool> (comparer);
  188. VirtualPath path = GetAbsoluteVirtualPath (vp);
  189. string vpAbsolute = path.Absolute;
  190. if (!virtualPathsToIgnore.ContainsKey (vpAbsolute)) {
  191. virtualPathsToIgnore.Add (vpAbsolute, true);
  192. haveVirtualPathsToIgnore = true;
  193. }
  194. string vpRelative = path.AppRelative;
  195. if (!virtualPathsToIgnore.ContainsKey (vpRelative)) {
  196. virtualPathsToIgnore.Add (vpRelative, true);
  197. haveVirtualPathsToIgnore = true;
  198. }
  199. if (!virtualPathsToIgnore.ContainsKey (vp)) {
  200. virtualPathsToIgnore.Add (vp, true);
  201. haveVirtualPathsToIgnore = true;
  202. }
  203. }
  204. internal static void AddToReferencedAssemblies (Assembly asm)
  205. {
  206. // should not be used
  207. }
  208. static void AssertVirtualPathExists (VirtualPath virtualPath)
  209. {
  210. string realpath;
  211. bool dothrow = false;
  212. if (virtualPath.IsFake) {
  213. realpath = virtualPath.PhysicalPath;
  214. if (!File.Exists (realpath) && !Directory.Exists (realpath))
  215. dothrow = true;
  216. } else {
  217. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  218. string vpAbsolute = virtualPath.Absolute;
  219. if (!vpp.FileExists (vpAbsolute) && !vpp.DirectoryExists (vpAbsolute))
  220. dothrow = true;
  221. }
  222. if (dothrow)
  223. throw new HttpException (404, "The file '" + virtualPath + "' does not exist.");
  224. }
  225. static void Build (VirtualPath vp)
  226. {
  227. AssertVirtualPathExists (vp);
  228. CompilationSection cs = CompilationConfig;
  229. lock (bigCompilationLock) {
  230. if (HasCachedItemNoLock (vp.Absolute))
  231. return;
  232. if (recursionDepth == 0)
  233. referencedAssemblies.Clear ();
  234. recursionDepth++;
  235. try {
  236. BuildInner (vp, cs != null ? cs.Debug : false);
  237. if (recursionDepth <= 1)
  238. buildCount++;
  239. // See http://support.microsoft.com/kb/319947
  240. if (buildCount > cs.NumRecompilesBeforeAppRestart)
  241. HttpRuntime.UnloadAppDomain ();
  242. } finally {
  243. recursionDepth--;
  244. }
  245. }
  246. }
  247. // This method assumes it is being called with the big compilation lock held
  248. static void BuildInner (VirtualPath vp, bool debug)
  249. {
  250. var builder = new BuildManagerDirectoryBuilder (vp);
  251. bool recursive = recursionDepth > 1;
  252. List <BuildProviderGroup> builderGroups = builder.Build (IsSingleBuild (vp, recursive));
  253. if (builderGroups == null)
  254. return;
  255. string vpabsolute = vp.Absolute;
  256. int buildHash = (vpabsolute.GetHashCode () | (int)DateTime.Now.Ticks) + (int)recursionDepth;
  257. string assemblyBaseName;
  258. AssemblyBuilder abuilder;
  259. CompilerType ct;
  260. int attempts;
  261. bool singleBuild, needMainVpBuild;
  262. CompilationException compilationError;
  263. // Each group becomes a separate assembly.
  264. foreach (BuildProviderGroup group in builderGroups) {
  265. needMainVpBuild = false;
  266. compilationError = null;
  267. assemblyBaseName = null;
  268. if (group.Count == 1) {
  269. if (recursive || !group.Master)
  270. assemblyBaseName = String.Format ("{0}_{1}.{2:x}.", group.NamePrefix, VirtualPathUtility.GetFileName (group [0].VirtualPath), buildHash);
  271. singleBuild = true;
  272. } else
  273. singleBuild = false;
  274. if (assemblyBaseName == null)
  275. assemblyBaseName = group.NamePrefix + "_";
  276. ct = group.CompilerType;
  277. attempts = 3;
  278. while (attempts > 0) {
  279. abuilder = new AssemblyBuilder (vp, CreateDomProvider (ct), assemblyBaseName);
  280. abuilder.CompilerOptions = ct.CompilerParameters;
  281. abuilder.AddAssemblyReference (GetReferencedAssemblies () as List <Assembly>);
  282. try {
  283. GenerateAssembly (abuilder, group, vp, debug);
  284. attempts = 0;
  285. } catch (CompilationException ex) {
  286. attempts--;
  287. if (singleBuild)
  288. throw new HttpException ("Single file build failed.", ex);
  289. if (attempts == 0) {
  290. needMainVpBuild = true;
  291. compilationError = ex;
  292. break;
  293. }
  294. CompilerResults results = ex.Results;
  295. if (results == null)
  296. throw new HttpException ("No results returned from failed compilation.", ex);
  297. else
  298. RemoveFailedAssemblies (vpabsolute, ex, abuilder, group, results, debug);
  299. }
  300. }
  301. if (needMainVpBuild) {
  302. // One last attempt - try to build just the requested path
  303. // if it's not built yet or just return without throwing the
  304. // exception if it has already been built.
  305. if (HasCachedItemNoLock (vpabsolute)) {
  306. if (debug)
  307. DescribeCompilationError ("Path '{0}' built successfully, but a compilation exception has been thrown for other files:",
  308. compilationError, vpabsolute);
  309. return;
  310. };
  311. // This will trigger a recursive build of the requested vp,
  312. // which means only the vp alone will be built (or not);
  313. Build (vp);
  314. if (HasCachedItemNoLock (vpabsolute)) {
  315. if (debug)
  316. DescribeCompilationError ("Path '{0}' built successfully, but a compilation exception has been thrown for other files:",
  317. compilationError, vpabsolute);
  318. return;
  319. }
  320. // In theory this code is unreachable. If the recursive
  321. // build of the main vp failed, then it should have thrown
  322. // the build exception.
  323. throw new HttpException ("Requested virtual path build failed.", compilationError);
  324. }
  325. }
  326. }
  327. static CodeDomProvider CreateDomProvider (CompilerType ct)
  328. {
  329. if (codeDomProviders == null)
  330. codeDomProviders = new Dictionary <Type, CodeDomProvider> ();
  331. Type type = ct.CodeDomProviderType;
  332. if (type == null) {
  333. CompilationSection cs = CompilationConfig;
  334. CompilerType tmp = GetDefaultCompilerTypeForLanguage (cs.DefaultLanguage, cs);
  335. if (tmp != null)
  336. type = tmp.CodeDomProviderType;
  337. }
  338. if (type == null)
  339. return null;
  340. CodeDomProvider ret;
  341. if (codeDomProviders.TryGetValue (type, out ret))
  342. return ret;
  343. ret = Activator.CreateInstance (type) as CodeDomProvider;
  344. if (ret == null)
  345. return null;
  346. codeDomProviders.Add (type, ret);
  347. return ret;
  348. }
  349. public static object CreateInstanceFromVirtualPath (string virtualPath, Type requiredBaseType)
  350. {
  351. if (requiredBaseType == null)
  352. throw new NullReferenceException (); // This is what MS does, but
  353. // from somewhere else.
  354. Type type = GetCompiledType (virtualPath);
  355. if (type == null)
  356. return null;
  357. if (!requiredBaseType.IsAssignableFrom (type))
  358. throw new HttpException (500,
  359. String.Format ("Type '{0}' does not inherit from '{1}'.", type.FullName, requiredBaseType.FullName));
  360. return Activator.CreateInstance (type, null);
  361. }
  362. static void DescribeCompilationError (string format, CompilationException ex, params object[] parms)
  363. {
  364. StringBuilder sb = new StringBuilder ();
  365. string newline = Environment.NewLine;
  366. if (parms != null)
  367. sb.AppendFormat (format + newline, parms);
  368. else
  369. sb.Append (format + newline);
  370. CompilerResults results = ex != null ? ex.Results : null;
  371. if (results == null)
  372. sb.Append ("No compiler error information present." + newline);
  373. else {
  374. sb.Append ("Compiler errors:" + newline);
  375. foreach (CompilerError error in results.Errors)
  376. sb.Append (" " + error.ToString () + newline);
  377. }
  378. if (ex != null) {
  379. sb.Append (newline + "Exception thrown:" + newline);
  380. sb.Append (ex.ToString ());
  381. }
  382. ShowDebugModeMessage (sb.ToString ());
  383. }
  384. static BuildProvider FindBuildProviderForPhysicalPath (string path, BuildProviderGroup group, HttpRequest req)
  385. {
  386. if (req == null || String.IsNullOrEmpty (path))
  387. return null;
  388. foreach (BuildProvider bp in group) {
  389. if (String.Compare (path, req.MapPath (bp.VirtualPath), stringComparer) == 0)
  390. return bp;
  391. }
  392. return null;
  393. }
  394. static void GenerateAssembly (AssemblyBuilder abuilder, BuildProviderGroup group, VirtualPath vp, bool debug)
  395. {
  396. IDictionary <string, bool> deps;
  397. BuildManagerCacheItem bmci;
  398. string bvp, vpabsolute = vp.Absolute;
  399. StringBuilder sb;
  400. string newline;
  401. int failedCount = 0;
  402. if (debug) {
  403. newline = Environment.NewLine;
  404. sb = new StringBuilder ("Code generation for certain virtual paths in a batch failed. Those files have been removed from the batch." + newline);
  405. sb.Append ("Since you're running in debug mode, here's some more information about the error:" + newline);
  406. } else {
  407. newline = null;
  408. sb = null;
  409. }
  410. List <BuildProvider> failedBuildProviders = null;
  411. foreach (BuildProvider bp in group) {
  412. bvp = bp.VirtualPath;
  413. if (HasCachedItemNoLock (bvp))
  414. continue;
  415. try {
  416. bp.GenerateCode (abuilder);
  417. } catch (Exception ex) {
  418. if (String.Compare (bvp, vpabsolute, stringComparer) == 0)
  419. throw;
  420. if (failedBuildProviders == null)
  421. failedBuildProviders = new List <BuildProvider> ();
  422. failedBuildProviders.Add (bp);
  423. failedCount++;
  424. if (sb != null) {
  425. if (failedCount > 1)
  426. sb.Append (newline);
  427. sb.AppendFormat ("Failed file virtual path: {0}; Exception: {1}{2}{1}", bp.VirtualPath, newline, ex);
  428. }
  429. continue;
  430. }
  431. deps = bp.ExtractDependencies ();
  432. if (deps != null) {
  433. foreach (var dep in deps) {
  434. bmci = GetCachedItemNoLock (dep.Key);
  435. if (bmci == null || bmci.BuiltAssembly == null)
  436. continue;
  437. abuilder.AddAssemblyReference (bmci.BuiltAssembly);
  438. }
  439. }
  440. }
  441. if (sb != null && failedCount > 0)
  442. ShowDebugModeMessage (sb.ToString ());
  443. if (failedBuildProviders != null) {
  444. foreach (BuildProvider bp in failedBuildProviders)
  445. group.Remove (bp);
  446. }
  447. foreach (Assembly asm in referencedAssemblies) {
  448. if (asm == null)
  449. continue;
  450. abuilder.AddAssemblyReference (asm);
  451. }
  452. CompilerResults results = abuilder.BuildAssembly (vp);
  453. // No results is not an error - it is possible that the assembly builder contained only .asmx and
  454. // .ashx files which had no body, just the directive. In such case, no code unit or code file is added
  455. // to the assembly builder and, in effect, no assembly is produced but there are STILL types that need
  456. // to be added to the cache.
  457. Assembly compiledAssembly = results != null ? results.CompiledAssembly : null;
  458. bool locked = false;
  459. try {
  460. #if SYSTEMCORE_DEP
  461. buildCacheLock.EnterWriteLock ();
  462. #else
  463. buildCacheLock.AcquireWriterLock (-1);
  464. #endif
  465. locked = true;
  466. if (compiledAssembly != null)
  467. referencedAssemblies.Add (compiledAssembly);
  468. foreach (BuildProvider bp in group) {
  469. if (HasCachedItemNoLock (bp.VirtualPath))
  470. continue;
  471. StoreInCache (bp, compiledAssembly, results);
  472. }
  473. } finally {
  474. if (locked) {
  475. #if SYSTEMCORE_DEP
  476. buildCacheLock.ExitWriteLock ();
  477. #else
  478. buildCacheLock.ReleaseWriterLock ();
  479. #endif
  480. }
  481. }
  482. }
  483. static VirtualPath GetAbsoluteVirtualPath (string virtualPath)
  484. {
  485. string vp;
  486. if (!VirtualPathUtility.IsRooted (virtualPath)) {
  487. HttpContext ctx = HttpContext.Current;
  488. HttpRequest req = ctx != null ? ctx.Request : null;
  489. if (req != null)
  490. vp = VirtualPathUtility.Combine (VirtualPathUtility.GetDirectory (req.FilePath), virtualPath);
  491. else
  492. throw new HttpException ("No context, cannot map paths.");
  493. } else
  494. vp = virtualPath;
  495. return new VirtualPath (vp);
  496. }
  497. [MonoTODO ("Not implemented, always returns null")]
  498. public static BuildDependencySet GetCachedBuildDependencySet (HttpContext context, string virtualPath)
  499. {
  500. return null; // null is ok here until we store the dependency set in the Cache.
  501. }
  502. static BuildManagerCacheItem GetCachedItem (string vp)
  503. {
  504. bool locked = false;
  505. try {
  506. #if SYSTEMCORE_DEP
  507. buildCacheLock.EnterReadLock ();
  508. #else
  509. buildCacheLock.AcquireReaderLock (-1);
  510. #endif
  511. locked = true;
  512. return GetCachedItemNoLock (vp);
  513. } finally {
  514. if (locked) {
  515. #if SYSTEMCORE_DEP
  516. buildCacheLock.ExitReadLock ();
  517. #else
  518. buildCacheLock.ReleaseReaderLock ();
  519. #endif
  520. }
  521. }
  522. }
  523. static BuildManagerCacheItem GetCachedItemNoLock (string vp)
  524. {
  525. BuildManagerCacheItem ret;
  526. if (buildCache.TryGetValue (vp, out ret))
  527. return ret;
  528. return null;
  529. }
  530. internal static Type GetCodeDomProviderType (BuildProvider provider)
  531. {
  532. CompilerType codeCompilerType;
  533. Type codeDomProviderType = null;
  534. codeCompilerType = provider.CodeCompilerType;
  535. if (codeCompilerType != null)
  536. codeDomProviderType = codeCompilerType.CodeDomProviderType;
  537. if (codeDomProviderType == null)
  538. throw new HttpException (String.Concat ("Provider '", provider, " 'fails to specify the compiler type."));
  539. return codeDomProviderType;
  540. }
  541. static Type GetPrecompiledType (string virtualPath)
  542. {
  543. PreCompilationData pc_data;
  544. if (precompiled != null && precompiled.TryGetValue (virtualPath, out pc_data)) {
  545. if (pc_data.Type == null) {
  546. pc_data.Type = Type.GetType (pc_data.TypeName + ", " + pc_data.AssemblyFileName, true);
  547. }
  548. return pc_data.Type;
  549. }
  550. //Console.WriteLine ("VPath not precompiled: {0}", virtualPath);
  551. return null;
  552. }
  553. internal static Type GetPrecompiledApplicationType ()
  554. {
  555. if (!is_precompiled)
  556. return null;
  557. Type apptype = GetPrecompiledType (HttpRuntime.AppDomainAppVirtualPath + "/Global.asax");
  558. if (apptype == null)
  559. apptype = GetPrecompiledType (HttpRuntime.AppDomainAppVirtualPath + "/global.asax");
  560. return apptype;
  561. }
  562. public static Assembly GetCompiledAssembly (string virtualPath)
  563. {
  564. VirtualPath vp = GetAbsoluteVirtualPath (virtualPath);
  565. string vpabsolute = vp.Absolute;
  566. if (is_precompiled) {
  567. Type type = GetPrecompiledType (vpabsolute);
  568. if (type != null)
  569. return type.Assembly;
  570. }
  571. BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
  572. if (bmci != null)
  573. return bmci.BuiltAssembly;
  574. Build (vp);
  575. bmci = GetCachedItem (vpabsolute);
  576. if (bmci != null)
  577. return bmci.BuiltAssembly;
  578. return null;
  579. }
  580. public static Type GetCompiledType (string virtualPath)
  581. {
  582. VirtualPath vp = GetAbsoluteVirtualPath (virtualPath);
  583. string vpabsolute = vp.Absolute;
  584. if (is_precompiled) {
  585. Type type = GetPrecompiledType (vpabsolute);
  586. if (type != null)
  587. return type;
  588. }
  589. BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
  590. if (bmci != null) {
  591. ReferenceAssemblyInCompilation (bmci);
  592. return bmci.Type;
  593. }
  594. Build (vp);
  595. bmci = GetCachedItem (vpabsolute);
  596. if (bmci != null) {
  597. ReferenceAssemblyInCompilation (bmci);
  598. return bmci.Type;
  599. }
  600. return null;
  601. }
  602. public static string GetCompiledCustomString (string virtualPath)
  603. {
  604. VirtualPath vp = GetAbsoluteVirtualPath (virtualPath);
  605. string vpabsolute = vp.Absolute;
  606. BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
  607. if (bmci != null)
  608. return bmci.CompiledCustomString;
  609. Build (vp);
  610. bmci = GetCachedItem (vpabsolute);
  611. if (bmci != null)
  612. return bmci.CompiledCustomString;
  613. return null;
  614. }
  615. internal static CompilerType GetDefaultCompilerTypeForLanguage (string language, CompilationSection configSection)
  616. {
  617. return GetDefaultCompilerTypeForLanguage (language, configSection, true);
  618. }
  619. internal static CompilerType GetDefaultCompilerTypeForLanguage (string language, CompilationSection configSection, bool throwOnMissing)
  620. {
  621. // MS throws when accesing a Hashtable, we do here.
  622. if (language == null || language.Length == 0)
  623. throw new ArgumentNullException ("language");
  624. CompilationSection config;
  625. if (configSection == null)
  626. config = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection;
  627. else
  628. config = configSection;
  629. Compiler compiler = config.Compilers.Get (language);
  630. CompilerParameters p;
  631. Type type;
  632. if (compiler != null) {
  633. type = HttpApplication.LoadType (compiler.Type, true);
  634. p = new CompilerParameters ();
  635. p.CompilerOptions = compiler.CompilerOptions;
  636. p.WarningLevel = compiler.WarningLevel;
  637. SetCommonParameters (config, p, type, language);
  638. return new CompilerType (type, p);
  639. }
  640. if (CodeDomProvider.IsDefinedLanguage (language)) {
  641. CompilerInfo info = CodeDomProvider.GetCompilerInfo (language);
  642. p = info.CreateDefaultCompilerParameters ();
  643. type = info.CodeDomProviderType;
  644. SetCommonParameters (config, p, type, language);
  645. return new CompilerType (type, p);
  646. }
  647. if (throwOnMissing)
  648. throw new HttpException (String.Concat ("No compiler for language '", language, "'."));
  649. return null;
  650. }
  651. public static ICollection GetReferencedAssemblies ()
  652. {
  653. List <Assembly> al = new List <Assembly> ();
  654. CompilationSection compConfig = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection;
  655. if (compConfig == null)
  656. return al;
  657. bool addAssembliesInBin = false;
  658. foreach (AssemblyInfo info in compConfig.Assemblies) {
  659. if (info.Assembly == "*")
  660. addAssembliesInBin = is_precompiled ? false : true;
  661. else
  662. LoadAssembly (info, al);
  663. }
  664. foreach (Assembly topLevelAssembly in TopLevelAssemblies)
  665. al.Add (topLevelAssembly);
  666. foreach (string assLocation in WebConfigurationManager.ExtraAssemblies)
  667. LoadAssembly (assLocation, al);
  668. if (is_precompiled) {
  669. // Add well-known assemblies which need to be referenced by everyone
  670. string binDir = HttpApplication.BinDirectory;
  671. string asmPath;
  672. foreach (String s in new string[] {"App_Code.dll", "App_GlobalResources.dll", "App_global.asax.dll"}) {
  673. asmPath = Path.Combine (binDir, s);
  674. if (File.Exists (asmPath))
  675. LoadAssembly (asmPath, al);
  676. }
  677. } else if (addAssembliesInBin) {
  678. foreach (string s in HttpApplication.BinDirectoryAssemblies) {
  679. try {
  680. LoadAssembly (s, al);
  681. } catch (BadImageFormatException) {
  682. // ignore silently
  683. }
  684. }
  685. }
  686. return al;
  687. }
  688. // The 2 GetType() overloads work on the global.asax, App_GlobalResources, App_WebReferences or App_Browsers
  689. public static Type GetType (string typeName, bool throwOnError)
  690. {
  691. return GetType (typeName, throwOnError, false);
  692. }
  693. public static Type GetType (string typeName, bool throwOnError, bool ignoreCase)
  694. {
  695. Type ret = null;
  696. try {
  697. foreach (Assembly asm in TopLevel_Assemblies) {
  698. ret = asm.GetType (typeName, throwOnError, ignoreCase);
  699. if (ret != null)
  700. break;
  701. }
  702. } catch (Exception ex) {
  703. throw new HttpException ("Failed to find the specified type.", ex);
  704. }
  705. return ret;
  706. }
  707. public static IDictionary <string, bool> GetVirtualPathDependencies (string virtualPath)
  708. {
  709. return GetVirtualPathDependencies (virtualPath, null);
  710. }
  711. internal static IDictionary <string, bool> GetVirtualPathDependencies (string virtualPath, BuildProvider bprovider)
  712. {
  713. BuildProvider provider = bprovider;
  714. if (provider == null) {
  715. CompilationSection cs = CompilationConfig;
  716. if (cs == null)
  717. return null;
  718. provider = BuildManagerDirectoryBuilder.GetBuildProvider (virtualPath, cs.BuildProviders);
  719. }
  720. if (provider == null)
  721. return null;
  722. return provider.ExtractDependencies ();
  723. }
  724. internal static bool HasCachedItemNoLock (string vp)
  725. {
  726. return buildCache.ContainsKey (vp);
  727. }
  728. internal static bool IgnoreVirtualPath (string virtualPath)
  729. {
  730. if (!haveVirtualPathsToIgnore)
  731. return false;
  732. if (virtualPathsToIgnore.ContainsKey (virtualPath))
  733. return true;
  734. return false;
  735. }
  736. static bool IsSingleBuild (VirtualPath vp, bool recursive)
  737. {
  738. if (String.Compare (vp.AppRelative, "~/global.asax", StringComparison.OrdinalIgnoreCase) == 0)
  739. return true;
  740. if (!BatchMode)
  741. return true;
  742. return recursive;
  743. }
  744. static void LoadAssembly (string path, List <Assembly> al)
  745. {
  746. AddAssembly (Assembly.LoadFrom (path), al);
  747. }
  748. static void LoadAssembly (AssemblyInfo info, List <Assembly> al)
  749. {
  750. AddAssembly (Assembly.Load (info.Assembly), al);
  751. }
  752. static void LoadVirtualPathsToIgnore ()
  753. {
  754. NameValueCollection appSettings = WebConfigurationManager.AppSettings;
  755. if (appSettings == null)
  756. return;
  757. string pathsFromConfig = appSettings ["MonoAspnetBatchCompileIgnorePaths"];
  758. string pathsFromFile = appSettings ["MonoAspnetBatchCompileIgnoreFromFile"];
  759. if (!String.IsNullOrEmpty (pathsFromConfig)) {
  760. string[] paths = pathsFromConfig.Split (virtualPathsToIgnoreSplitChars);
  761. string path;
  762. foreach (string p in paths) {
  763. path = p.Trim ();
  764. if (path.Length == 0)
  765. continue;
  766. AddPathToIgnore (path);
  767. }
  768. }
  769. if (!String.IsNullOrEmpty (pathsFromFile)) {
  770. string realpath;
  771. HttpContext ctx = HttpContext.Current;
  772. HttpRequest req = ctx != null ? ctx.Request : null;
  773. if (req == null)
  774. throw new HttpException ("Missing context, cannot continue.");
  775. realpath = req.MapPath (pathsFromFile);
  776. if (!File.Exists (realpath))
  777. return;
  778. string[] paths = File.ReadAllLines (realpath);
  779. if (paths == null || paths.Length == 0)
  780. return;
  781. string path;
  782. foreach (string p in paths) {
  783. path = p.Trim ();
  784. if (path.Length == 0)
  785. continue;
  786. AddPathToIgnore (path);
  787. }
  788. }
  789. }
  790. static void OnEntryRemoved (string vp)
  791. {
  792. BuildManagerRemoveEntryEventHandler eh = events [buildManagerRemoveEntryEvent] as BuildManagerRemoveEntryEventHandler;
  793. if (eh != null)
  794. eh (new BuildManagerRemoveEntryEventArgs (vp, HttpContext.Current));
  795. }
  796. static void OnVirtualPathChanged (string key, object value, CacheItemRemovedReason removedReason)
  797. {
  798. string virtualPath;
  799. if (StrUtils.StartsWith (key, BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX))
  800. virtualPath = key.Substring (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX_LENGTH);
  801. else
  802. return;
  803. bool locked = false;
  804. try {
  805. #if SYSTEMCORE_DEP
  806. buildCacheLock.EnterWriteLock ();
  807. #else
  808. buildCacheLock.AcquireWriterLock (-1);
  809. #endif
  810. locked = true;
  811. if (HasCachedItemNoLock (virtualPath)) {
  812. buildCache.Remove (virtualPath);
  813. OnEntryRemoved (virtualPath);
  814. }
  815. } finally {
  816. if (locked) {
  817. #if SYSTEMCORE_DEP
  818. buildCacheLock.ExitWriteLock ();
  819. #else
  820. buildCacheLock.ReleaseWriterLock ();
  821. #endif
  822. }
  823. }
  824. }
  825. static void ReferenceAssemblyInCompilation (BuildManagerCacheItem bmci)
  826. {
  827. if (recursionDepth == 0 || referencedAssemblies.Contains (bmci.BuiltAssembly))
  828. return;
  829. referencedAssemblies.Add (bmci.BuiltAssembly);
  830. }
  831. static void RemoveFailedAssemblies (string requestedVirtualPath, CompilationException ex, AssemblyBuilder abuilder,
  832. BuildProviderGroup group, CompilerResults results, bool debug)
  833. {
  834. StringBuilder sb;
  835. string newline;
  836. if (debug) {
  837. newline = Environment.NewLine;
  838. sb = new StringBuilder ("Compilation of certain files in a batch failed. Another attempt to compile the batch will be made." + newline);
  839. sb.Append ("Since you're running in debug mode, here's some more information about the error:" + newline);
  840. } else {
  841. newline = null;
  842. sb = null;
  843. }
  844. var failedBuildProviders = new List <BuildProvider> ();
  845. BuildProvider bp;
  846. HttpContext ctx = HttpContext.Current;
  847. HttpRequest req = ctx != null ? ctx.Request : null;
  848. bool rethrow = false;
  849. foreach (CompilerError error in results.Errors) {
  850. bp = abuilder.GetBuildProviderForPhysicalFilePath (error.FileName);
  851. if (bp == null) {
  852. bp = FindBuildProviderForPhysicalPath (error.FileName, group, req);
  853. if (bp == null)
  854. continue;
  855. }
  856. if (String.Compare (bp.VirtualPath, requestedVirtualPath, StringComparison.Ordinal) == 0)
  857. rethrow = true;
  858. if (!failedBuildProviders.Contains (bp)) {
  859. failedBuildProviders.Add (bp);
  860. if (sb != null)
  861. sb.AppendFormat ("\t{0}{1}", bp.VirtualPath, newline);
  862. }
  863. if (sb != null)
  864. sb.AppendFormat ("\t\t{0}{1}", error, newline);
  865. }
  866. foreach (BuildProvider fbp in failedBuildProviders)
  867. group.Remove (fbp);
  868. if (sb != null) {
  869. sb.AppendFormat ("{0}The following exception has been thrown for the file(s) listed above:{0}{1}",
  870. newline, ex.ToString ());
  871. ShowDebugModeMessage (sb.ToString ());
  872. sb = null;
  873. }
  874. if (rethrow)
  875. throw ex;
  876. }
  877. static void SetCommonParameters (CompilationSection config, CompilerParameters p, Type compilerType, string language)
  878. {
  879. p.IncludeDebugInformation = config.Debug;
  880. MonoSettingsSection mss = WebConfigurationManager.GetSection ("system.web/monoSettings") as MonoSettingsSection;
  881. if (mss == null || !mss.UseCompilersCompatibility)
  882. return;
  883. Compiler compiler = mss.CompilersCompatibility.Get (language);
  884. if (compiler == null)
  885. return;
  886. Type type = HttpApplication.LoadType (compiler.Type, false);
  887. if (type != compilerType)
  888. return;
  889. p.CompilerOptions = String.Concat (p.CompilerOptions, " ", compiler.CompilerOptions);
  890. }
  891. static void ShowDebugModeMessage (string msg)
  892. {
  893. if (suppressDebugModeMessages)
  894. return;
  895. Console.WriteLine ();
  896. Console.WriteLine ("******* DEBUG MODE MESSAGE *******");
  897. Console.WriteLine (msg);
  898. Console.WriteLine ("******* DEBUG MODE MESSAGE *******");
  899. Console.WriteLine ();
  900. }
  901. static void StoreInCache (BuildProvider bp, Assembly compiledAssembly, CompilerResults results)
  902. {
  903. buildCache.Add (bp.VirtualPath, new BuildManagerCacheItem (compiledAssembly, bp, results));
  904. HttpContext ctx = HttpContext.Current;
  905. HttpRequest req = ctx != null ? ctx.Request : null;
  906. CacheDependency dep;
  907. string virtualPath = bp.VirtualPath;
  908. if (req != null) {
  909. IDictionary <string, bool> deps = bp.ExtractDependencies ();
  910. var files = new List <string> ();
  911. string physicalPath;
  912. physicalPath = req.MapPath (virtualPath);
  913. if (File.Exists (physicalPath))
  914. files.Add (physicalPath);
  915. if (deps != null && deps.Count > 0) {
  916. foreach (var d in deps) {
  917. physicalPath = req.MapPath (d.Key);
  918. if (!File.Exists (physicalPath))
  919. continue;
  920. if (!files.Contains (physicalPath))
  921. files.Add (physicalPath);
  922. }
  923. }
  924. dep = new CacheDependency (files.ToArray ());
  925. } else
  926. dep = null;
  927. HttpRuntime.InternalCache.Add (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX + virtualPath,
  928. true,
  929. dep,
  930. Cache.NoAbsoluteExpiration,
  931. Cache.NoSlidingExpiration,
  932. CacheItemPriority.High,
  933. new CacheItemRemovedCallback (OnVirtualPathChanged));
  934. }
  935. }
  936. }
  937. #endif