BuildManager.cs 35 KB

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