2
0

BuildManager.cs 36 KB

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