BuildManager.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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-2008 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.IO;
  39. using System.Reflection;
  40. using System.Text;
  41. using System.Threading;
  42. using System.Web;
  43. using System.Web.Caching;
  44. using System.Web.Configuration;
  45. using System.Web.Hosting;
  46. using System.Web.Util;
  47. namespace System.Web.Compilation {
  48. public sealed class BuildManager {
  49. class BuildItem
  50. {
  51. public BuildProvider buildProvider;
  52. public AssemblyBuilder assemblyBuilder;
  53. public Type codeDomProviderType;
  54. public bool codeGenerated;
  55. public Assembly compiledAssembly;
  56. public CompilerParameters CompilerOptions {
  57. get {
  58. if (buildProvider == null)
  59. throw new HttpException ("No build provider.");
  60. return buildProvider.CodeCompilerType.CompilerParameters;
  61. }
  62. }
  63. public string VirtualPath {
  64. get {
  65. if (buildProvider == null)
  66. throw new HttpException ("No build provider.");
  67. return buildProvider.VirtualPath;
  68. }
  69. }
  70. public CodeCompileUnit CodeUnit {
  71. get {
  72. if (buildProvider == null)
  73. throw new HttpException ("No build provider.");
  74. return buildProvider.CodeUnit;
  75. }
  76. }
  77. public BuildItem (BuildProvider provider)
  78. {
  79. this.buildProvider = provider;
  80. if (provider != null)
  81. codeDomProviderType = GetCodeDomProviderType (provider);
  82. }
  83. public void SetCompiledAssembly (AssemblyBuilder assemblyBuilder, Assembly compiledAssembly)
  84. {
  85. if (this.compiledAssembly != null || this.assemblyBuilder == null || this.assemblyBuilder != assemblyBuilder)
  86. return;
  87. this.compiledAssembly = compiledAssembly;
  88. }
  89. public CodeDomProvider CreateCodeDomProvider ()
  90. {
  91. if (codeDomProviderType == null)
  92. throw new HttpException ("Unable to create compilation provider, no provider type given.");
  93. CodeDomProvider ret;
  94. try {
  95. ret = Activator.CreateInstance (codeDomProviderType) as CodeDomProvider;
  96. } catch (Exception ex) {
  97. throw new HttpException ("Failed to create compilation provider.", ex);
  98. }
  99. if (ret == null)
  100. throw new HttpException ("Unable to instantiate code DOM provider '" + codeDomProviderType + "'.");
  101. return ret;
  102. }
  103. public void GenerateCode ()
  104. {
  105. if (buildProvider == null)
  106. throw new HttpException ("Cannot generate code - missing build provider.");
  107. buildProvider.GenerateCode ();
  108. codeGenerated = true;
  109. }
  110. public void StoreCodeUnit ()
  111. {
  112. if (buildProvider == null)
  113. throw new HttpException ("Cannot generate code - missing build provider.");
  114. if (assemblyBuilder == null)
  115. throw new HttpException ("Cannot generate code - missing assembly builder.");
  116. buildProvider.GenerateCode (assemblyBuilder);
  117. }
  118. public override string ToString ()
  119. {
  120. string ret = "BuildItem [";
  121. string virtualPath = VirtualPath;
  122. if (!String.IsNullOrEmpty (virtualPath))
  123. ret += virtualPath;
  124. ret += "]";
  125. return ret;
  126. }
  127. }
  128. class BuildCacheItem
  129. {
  130. public string compiledCustomString;
  131. public Assembly assembly;
  132. public Type type;
  133. public string virtualPath;
  134. public BuildCacheItem (Assembly assembly, BuildProvider bp, CompilerResults results)
  135. {
  136. this.assembly = assembly;
  137. this.compiledCustomString = bp.GetCustomString (results);
  138. this.type = bp.GetGeneratedType (results);
  139. this.virtualPath = bp.VirtualPath;
  140. }
  141. public override string ToString ()
  142. {
  143. StringBuilder sb = new StringBuilder ("BuildCacheItem [");
  144. bool first = true;
  145. if (!String.IsNullOrEmpty (compiledCustomString)) {
  146. sb.Append ("compiledCustomString: " + compiledCustomString);
  147. first = false;
  148. }
  149. if (assembly != null) {
  150. sb.Append ((first ? "" : "; ") + "assembly: " + assembly.ToString ());
  151. first = false;
  152. }
  153. if (type != null) {
  154. sb.Append ((first ? "" : "; ") + "type: " + type.ToString ());
  155. first = false;
  156. }
  157. if (!String.IsNullOrEmpty (virtualPath)) {
  158. sb.Append ((first ? "" : "; ") + "virtualPath: " + virtualPath);
  159. first = false;
  160. }
  161. sb.Append ("]");
  162. return sb.ToString ();
  163. }
  164. }
  165. enum BuildKind {
  166. Unknown,
  167. Pages,
  168. NonPages,
  169. Application,
  170. Theme,
  171. Fake
  172. };
  173. internal const string FAKE_VIRTUAL_PATH_PREFIX = "/@@MonoFakeVirtualPath@@";
  174. const string BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX = "Build_Manager";
  175. static int BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX_LENGTH = BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX.Length;
  176. static object buildCacheLock = new object ();
  177. static Stack <BuildKind> recursiveBuilds = new Stack <BuildKind> ();
  178. //
  179. // Disabled - see comment at the end of BuildAssembly below
  180. //
  181. // static object buildCountLock = new object ();
  182. // static int buildCount = 0;
  183. static List<Assembly> AppCode_Assemblies = new List<Assembly>();
  184. static List<Assembly> TopLevel_Assemblies = new List<Assembly>();
  185. static bool haveResources;
  186. // The build cache which maps a virtual path to a build item with all the necessary
  187. // bits.
  188. static Dictionary <string, BuildCacheItem> buildCache;
  189. // Maps the virtual path of a non-page build to the assembly that contains the
  190. // compiled type.
  191. static Dictionary <string, Assembly> nonPagesCache;
  192. static List <Assembly> referencedAssemblies = new List <Assembly> ();
  193. static Dictionary <string, object> compilationTickets;
  194. static Assembly globalAsaxAssembly;
  195. static Dictionary <string, BuildKind> knownFileTypes = new Dictionary <string, BuildKind> (StringComparer.OrdinalIgnoreCase) {
  196. {".aspx", BuildKind.Pages},
  197. {".asax", BuildKind.Application},
  198. {".ashx", BuildKind.NonPages},
  199. {".asmx", BuildKind.NonPages},
  200. {".ascx", BuildKind.NonPages},
  201. {".master", BuildKind.NonPages}
  202. };
  203. static Dictionary <string, bool> virtualPathsToIgnore;
  204. static bool haveVirtualPathsToIgnore;
  205. static BuildManager ()
  206. {
  207. IEqualityComparer <string> comparer;
  208. if (HttpRuntime.CaseInsensitive)
  209. comparer = StringComparer.CurrentCultureIgnoreCase;
  210. else
  211. comparer = StringComparer.CurrentCulture;
  212. buildCache = new Dictionary <string, BuildCacheItem> (comparer);
  213. nonPagesCache = new Dictionary <string, Assembly> (comparer);
  214. compilationTickets = new Dictionary <string, object> (comparer);
  215. }
  216. internal static void ThrowNoProviderException (string extension)
  217. {
  218. string msg = "No registered provider for extension '{0}'.";
  219. throw new HttpException (String.Format (msg, extension));
  220. }
  221. public static object CreateInstanceFromVirtualPath (string virtualPath, Type requiredBaseType)
  222. {
  223. // virtualPath + Exists done in GetCompiledType()
  224. if (requiredBaseType == null)
  225. throw new NullReferenceException (); // This is what MS does, but from somewhere else.
  226. // Get the Type.
  227. Type type = GetCompiledType (virtualPath);
  228. if (type == null)
  229. //throw new HttpException ("Instance creation failed for virtual
  230. //path '" + virtualPath + "'.");
  231. return null;
  232. if (!requiredBaseType.IsAssignableFrom (type)) {
  233. string msg = String.Format ("Type '{0}' does not inherit from '{1}'.",
  234. type.FullName, requiredBaseType.FullName);
  235. throw new HttpException (500, msg);
  236. }
  237. return Activator.CreateInstance (type, null);
  238. }
  239. public static ICollection GetReferencedAssemblies ()
  240. {
  241. List <Assembly> al = new List <Assembly> ();
  242. CompilationSection compConfig = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
  243. if (compConfig == null)
  244. return al;
  245. bool addAssembliesInBin = false;
  246. foreach (AssemblyInfo info in compConfig.Assemblies) {
  247. if (info.Assembly == "*")
  248. addAssembliesInBin = true;
  249. else
  250. LoadAssembly (info, al);
  251. }
  252. foreach (Assembly topLevelAssembly in TopLevel_Assemblies)
  253. al.Add (topLevelAssembly);
  254. foreach (string assLocation in WebConfigurationManager.ExtraAssemblies)
  255. LoadAssembly (assLocation, al);
  256. if (addAssembliesInBin)
  257. foreach (string s in HttpApplication.BinDirectoryAssemblies)
  258. LoadAssembly (s, al);
  259. lock (buildCacheLock) {
  260. foreach (Assembly asm in referencedAssemblies) {
  261. if (!al.Contains (asm))
  262. al.Add (asm);
  263. }
  264. if (globalAsaxAssembly != null)
  265. al.Add (globalAsaxAssembly);
  266. }
  267. return al;
  268. }
  269. static void LoadAssembly (string path, List <Assembly> al)
  270. {
  271. AddAssembly (Assembly.LoadFrom (path), al);
  272. }
  273. static void LoadAssembly (AssemblyInfo info, List <Assembly> al)
  274. {
  275. AddAssembly (Assembly.Load (info.Assembly), al);
  276. }
  277. static void AddAssembly (Assembly asm, List <Assembly> al)
  278. {
  279. if (al.Contains (asm))
  280. return;
  281. al.Add (asm);
  282. }
  283. [MonoTODO ("Not implemented, always returns null")]
  284. public static BuildDependencySet GetCachedBuildDependencySet (HttpContext context, string virtualPath)
  285. {
  286. return null; // null is ok here until we store the dependency set in the Cache.
  287. }
  288. internal static BuildProvider GetBuildProviderForPath (VirtualPath virtualPath, bool throwOnMissing)
  289. {
  290. return GetBuildProviderForPath (virtualPath, null, throwOnMissing);
  291. }
  292. internal static BuildProvider GetBuildProviderForPath (VirtualPath virtualPath, CompilationSection section, bool throwOnMissing)
  293. {
  294. string extension = virtualPath.Extension;
  295. CompilationSection c = section;
  296. if (c == null)
  297. c = WebConfigurationManager.GetSection ("system.web/compilation", virtualPath.Original) as CompilationSection;
  298. if (c == null)
  299. if (throwOnMissing)
  300. ThrowNoProviderException (extension);
  301. else
  302. return null;
  303. BuildProviderCollection coll = c.BuildProviders;
  304. if (coll == null || coll.Count == 0)
  305. ThrowNoProviderException (extension);
  306. BuildProvider provider = coll.GetProviderForExtension (extension);
  307. if (provider == null)
  308. if (throwOnMissing)
  309. ThrowNoProviderException (extension);
  310. else
  311. return null;
  312. provider.SetVirtualPath (virtualPath);
  313. return provider;
  314. }
  315. static VirtualPath GetAbsoluteVirtualPath (string virtualPath)
  316. {
  317. string vp;
  318. if (!VirtualPathUtility.IsRooted (virtualPath)) {
  319. HttpContext ctx = HttpContext.Current;
  320. HttpRequest req = ctx != null ? ctx.Request : null;
  321. if (req != null)
  322. vp = VirtualPathUtility.GetDirectory (req.FilePath) + virtualPath;
  323. else
  324. throw new HttpException ("No context, cannot map paths.");
  325. } else
  326. vp = virtualPath;
  327. return new VirtualPath (vp);
  328. }
  329. static BuildCacheItem GetCachedItem (VirtualPath virtualPath)
  330. {
  331. BuildCacheItem ret;
  332. lock (buildCacheLock) {
  333. if (buildCache.TryGetValue (virtualPath.Absolute, out ret))
  334. return ret;
  335. }
  336. return null;
  337. }
  338. public static Assembly GetCompiledAssembly (string virtualPath)
  339. {
  340. VirtualPath vp = GetAbsoluteVirtualPath (virtualPath);
  341. BuildCacheItem ret = GetCachedItem (vp);
  342. if (ret != null)
  343. return ret.assembly;
  344. BuildAssembly (vp);
  345. ret = GetCachedItem (vp);
  346. if (ret != null)
  347. return ret.assembly;
  348. return null;
  349. }
  350. public static Type GetCompiledType (string virtualPath)
  351. {
  352. VirtualPath vp = GetAbsoluteVirtualPath (virtualPath);
  353. BuildCacheItem ret = GetCachedItem (vp);
  354. if (ret != null)
  355. return ret.type;
  356. BuildAssembly (vp);
  357. ret = GetCachedItem (vp);
  358. if (ret != null)
  359. return ret.type;
  360. return null;
  361. }
  362. public static string GetCompiledCustomString (string virtualPath)
  363. {
  364. VirtualPath vp = GetAbsoluteVirtualPath (virtualPath);
  365. BuildCacheItem ret = GetCachedItem (vp);
  366. if (ret != null)
  367. return ret.compiledCustomString;
  368. BuildAssembly (vp);
  369. ret = GetCachedItem (vp);
  370. if (ret != null)
  371. return ret.compiledCustomString;
  372. return null;
  373. }
  374. static List <VirtualFile> GetFilesForBuild (VirtualPath virtualPath, out BuildKind kind)
  375. {
  376. string extension = virtualPath.Extension;
  377. var ret = new List <VirtualFile> ();
  378. if (virtualPath.StartsWith (FAKE_VIRTUAL_PATH_PREFIX)) {
  379. kind = BuildKind.Fake;
  380. return ret;
  381. }
  382. if (!knownFileTypes.TryGetValue (extension, out kind)) {
  383. if (StrUtils.StartsWith (virtualPath.AppRelative, "~/App_Themes/"))
  384. kind = BuildKind.Theme;
  385. else
  386. kind = BuildKind.Unknown;
  387. }
  388. if (kind == BuildKind.Theme || kind == BuildKind.Application)
  389. return ret;
  390. bool doBatch = BatchMode;
  391. lock (buildCacheLock) {
  392. if (recursiveBuilds.Count > 0 && recursiveBuilds.Peek () == kind)
  393. doBatch = false;
  394. recursiveBuilds.Push (kind);
  395. }
  396. string vpAbsolute = virtualPath.Absolute;
  397. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  398. VirtualDirectory dir = vpp.GetDirectory (vpAbsolute);
  399. if (doBatch && HostingEnvironment.HaveCustomVPP && dir != null && dir is DefaultVirtualDirectory)
  400. doBatch = false;
  401. if (doBatch) {
  402. if (dir == null)
  403. throw new HttpException (404, "Virtual directory '" + virtualPath.Directory + "' does not exist.");
  404. BuildKind fileKind;
  405. foreach (VirtualFile file in dir.Files) {
  406. if (!knownFileTypes.TryGetValue (VirtualPathUtility.GetExtension (file.Name), out fileKind))
  407. continue;
  408. if (kind == fileKind)
  409. ret.Add (file);
  410. }
  411. } else {
  412. VirtualFile vf = vpp.GetFile (vpAbsolute);
  413. if (vf == null)
  414. throw new HttpException (404, "Virtual file '" + virtualPath + "' does not exist.");
  415. ret.Add (vf);
  416. }
  417. return ret;
  418. }
  419. static Type GetCodeDomProviderType (BuildProvider provider)
  420. {
  421. CompilerType codeCompilerType;
  422. Type codeDomProviderType = null;
  423. codeCompilerType = provider.CodeCompilerType;
  424. if (codeCompilerType != null)
  425. codeDomProviderType = codeCompilerType.CodeDomProviderType;
  426. if (codeDomProviderType == null)
  427. throw new HttpException (String.Concat ("Provider '", provider, " 'fails to specify the compiler type."));
  428. return codeDomProviderType;
  429. }
  430. static List <BuildItem> LoadBuildProviders (VirtualPath virtualPath, string virtualDir, Dictionary <string, bool> vpCache,
  431. out BuildKind kind, out string assemblyBaseName)
  432. {
  433. HttpContext ctx = HttpContext.Current;
  434. HttpRequest req = ctx != null ? ctx.Request : null;
  435. if (req == null)
  436. throw new HttpException ("No context available, cannot build.");
  437. string vpAbsolute = virtualPath.Absolute;
  438. CompilationSection section = WebConfigurationManager.GetSection ("system.web/compilation", vpAbsolute) as CompilationSection;
  439. List <VirtualFile> files;
  440. try {
  441. files = GetFilesForBuild (virtualPath, out kind);
  442. } catch (Exception ex) {
  443. throw new HttpException ("Error loading build providers for path '" + virtualDir + "'.", ex);
  444. }
  445. List <BuildItem> ret = new List <BuildItem> ();
  446. BuildProvider provider = null;
  447. switch (kind) {
  448. case BuildKind.Theme:
  449. assemblyBaseName = "App_Theme_";
  450. provider = new ThemeDirectoryBuildProvider ();
  451. provider.SetVirtualPath (virtualPath);
  452. break;
  453. case BuildKind.Application:
  454. assemblyBaseName = "App_global.asax.";
  455. provider = new ApplicationFileBuildProvider ();
  456. provider.SetVirtualPath (virtualPath);
  457. break;
  458. case BuildKind.Fake:
  459. provider = GetBuildProviderForPath (virtualPath, section, false);
  460. assemblyBaseName = null;
  461. break;
  462. default:
  463. assemblyBaseName = null;
  464. break;
  465. }
  466. if (provider != null) {
  467. ret.Add (new BuildItem (provider));
  468. return ret;
  469. }
  470. string fileVirtualPath;
  471. string fileName;
  472. lock (buildCacheLock) {
  473. foreach (VirtualFile f in files) {
  474. fileVirtualPath = f.VirtualPath;
  475. if (IgnoreVirtualPath (fileVirtualPath))
  476. continue;
  477. if (buildCache.ContainsKey (fileVirtualPath) || vpCache.ContainsKey (fileVirtualPath))
  478. continue;
  479. vpCache.Add (fileVirtualPath, true);
  480. provider = GetBuildProviderForPath (new VirtualPath (fileVirtualPath), section, false);
  481. if (provider == null)
  482. continue;
  483. ret.Add (new BuildItem (provider));
  484. }
  485. }
  486. return ret;
  487. }
  488. static bool IgnoreVirtualPath (string virtualPath)
  489. {
  490. if (!haveVirtualPathsToIgnore)
  491. return false;
  492. if (virtualPathsToIgnore.ContainsKey (virtualPath))
  493. return true;
  494. return false;
  495. }
  496. static void AddPathToIgnore (string vp)
  497. {
  498. if (virtualPathsToIgnore == null)
  499. virtualPathsToIgnore = new Dictionary <string, bool> ();
  500. VirtualPath path = GetAbsoluteVirtualPath (vp);
  501. string vpAbsolute = path.Absolute;
  502. if (virtualPathsToIgnore.ContainsKey (vpAbsolute))
  503. return;
  504. virtualPathsToIgnore.Add (vpAbsolute, true);
  505. haveVirtualPathsToIgnore = true;
  506. }
  507. static char[] virtualPathsToIgnoreSplitChars = {','};
  508. static void LoadVirtualPathsToIgnore ()
  509. {
  510. if (virtualPathsToIgnore != null)
  511. return;
  512. NameValueCollection appSettings = WebConfigurationManager.AppSettings;
  513. if (appSettings == null)
  514. return;
  515. string pathsFromConfig = appSettings ["MonoAspnetBatchCompileIgnorePaths"];
  516. string pathsFromFile = appSettings ["MonoAspnetBatchCompileIgnoreFromFile"];
  517. if (!String.IsNullOrEmpty (pathsFromConfig)) {
  518. string[] paths = pathsFromConfig.Split (virtualPathsToIgnoreSplitChars);
  519. string path;
  520. foreach (string p in paths) {
  521. path = p.Trim ();
  522. if (path.Length == 0)
  523. continue;
  524. AddPathToIgnore (path);
  525. }
  526. }
  527. if (!String.IsNullOrEmpty (pathsFromFile)) {
  528. string realpath;
  529. HttpContext ctx = HttpContext.Current;
  530. HttpRequest req = ctx != null ? ctx.Request : null;
  531. if (req == null)
  532. throw new HttpException ("Missing context, cannot continue.");
  533. realpath = req.MapPath (pathsFromFile);
  534. if (!File.Exists (realpath))
  535. return;
  536. string[] paths = File.ReadAllLines (realpath);
  537. if (paths == null || paths.Length == 0)
  538. return;
  539. string path;
  540. foreach (string p in paths) {
  541. path = p.Trim ();
  542. if (path.Length == 0)
  543. continue;
  544. AddPathToIgnore (path);
  545. }
  546. }
  547. }
  548. static AssemblyBuilder CreateAssemblyBuilder (string assemblyBaseName, VirtualPath virtualPath, BuildItem buildItem)
  549. {
  550. buildItem.assemblyBuilder = new AssemblyBuilder (virtualPath, buildItem.CreateCodeDomProvider (), assemblyBaseName);
  551. buildItem.assemblyBuilder.CompilerOptions = buildItem.CompilerOptions;
  552. return buildItem.assemblyBuilder;
  553. }
  554. static Dictionary <string, CompileUnitPartialType> GetUnitPartialTypes (CodeCompileUnit unit)
  555. {
  556. Dictionary <string, CompileUnitPartialType> ret = null;
  557. CompileUnitPartialType pt;
  558. foreach (CodeNamespace ns in unit.Namespaces) {
  559. foreach (CodeTypeDeclaration type in ns.Types) {
  560. if (type.IsPartial) {
  561. pt = new CompileUnitPartialType (unit, ns, type);
  562. if (ret == null)
  563. ret = new Dictionary <string, CompileUnitPartialType> ();
  564. ret.Add (pt.TypeName, pt);
  565. }
  566. }
  567. }
  568. return ret;
  569. }
  570. static bool TypeHasConflictingMember (CodeTypeDeclaration type, CodeMemberMethod member)
  571. {
  572. if (type == null || member == null)
  573. return false;
  574. CodeMemberMethod method;
  575. string methodName = member.Name;
  576. int count;
  577. foreach (CodeTypeMember m in type.Members) {
  578. if (m.Name != methodName)
  579. continue;
  580. method = m as CodeMemberMethod;
  581. if (method == null)
  582. continue;
  583. if ((count = method.Parameters.Count) != member.Parameters.Count)
  584. continue;
  585. CodeParameterDeclarationExpressionCollection methodA = method.Parameters;
  586. CodeParameterDeclarationExpressionCollection methodB = member.Parameters;
  587. for (int i = 0; i < count; i++)
  588. if (methodA [i].Type != methodB [i].Type)
  589. continue;
  590. return true;
  591. }
  592. return false;
  593. }
  594. static bool TypeHasConflictingMember (CodeTypeDeclaration type, CodeMemberField member)
  595. {
  596. if (type == null || member == null)
  597. return false;
  598. CodeMemberField field = FindMemberByName (type, member.Name) as CodeMemberField;
  599. if (field == null)
  600. return false;
  601. if (field.Type == member.Type)
  602. return false; // This will get "flattened" by AssemblyBuilder
  603. return true;
  604. }
  605. static bool TypeHasConflictingMember (CodeTypeDeclaration type, CodeTypeMember member)
  606. {
  607. if (type == null || member == null)
  608. return false;
  609. return (FindMemberByName (type, member.Name) != null);
  610. }
  611. static CodeTypeMember FindMemberByName (CodeTypeDeclaration type, string name)
  612. {
  613. foreach (CodeTypeMember m in type.Members) {
  614. if (m == null || m.Name != name)
  615. continue;
  616. return m;
  617. }
  618. return null;
  619. }
  620. static bool PartialTypesConflict (CodeTypeDeclaration typeA, CodeTypeDeclaration typeB)
  621. {
  622. bool conflict;
  623. Type type;
  624. foreach (CodeTypeMember member in typeB.Members) {
  625. conflict = false;
  626. type = member.GetType ();
  627. if (type == typeof (CodeMemberMethod))
  628. conflict = TypeHasConflictingMember (typeA, (CodeMemberMethod) member);
  629. else if (type == typeof (CodeMemberField))
  630. conflict = TypeHasConflictingMember (typeA, (CodeMemberField) member);
  631. else
  632. conflict = TypeHasConflictingMember (typeA, member);
  633. if (conflict)
  634. return true;
  635. }
  636. return false;
  637. }
  638. static bool CanAcceptCode (AssemblyBuilder assemblyBuilder, BuildItem buildItem)
  639. {
  640. CodeCompileUnit newUnit = buildItem.CodeUnit;
  641. if (newUnit == null)
  642. return true;
  643. Dictionary <string, CompileUnitPartialType> unitPartialTypes = GetUnitPartialTypes (newUnit);
  644. if (unitPartialTypes == null)
  645. return true;
  646. if (assemblyBuilder.Units.Count > CompilationConfig.MaxBatchSize)
  647. return false;
  648. CompileUnitPartialType pt;
  649. foreach (List <CompileUnitPartialType> partialTypes in assemblyBuilder.PartialTypes.Values)
  650. foreach (CompileUnitPartialType cupt in partialTypes)
  651. if (unitPartialTypes.TryGetValue (cupt.TypeName, out pt) && PartialTypesConflict (cupt.PartialType, pt.PartialType))
  652. return false;
  653. return true;
  654. }
  655. static void AssignToAssemblyBuilder (string assemblyBaseName, VirtualPath virtualPath, BuildItem buildItem,
  656. Dictionary <Type, List <AssemblyBuilder>> assemblyBuilders)
  657. {
  658. if (!buildItem.codeGenerated)
  659. buildItem.GenerateCode ();
  660. List <AssemblyBuilder> builders;
  661. if (!assemblyBuilders.TryGetValue (buildItem.codeDomProviderType, out builders)) {
  662. builders = new List <AssemblyBuilder> ();
  663. assemblyBuilders.Add (buildItem.codeDomProviderType, builders);
  664. }
  665. // Put it in the first assembly builder that doesn't have conflicting
  666. // partial types
  667. foreach (AssemblyBuilder assemblyBuilder in builders) {
  668. if (CanAcceptCode (assemblyBuilder, buildItem)) {
  669. buildItem.assemblyBuilder = assemblyBuilder;
  670. buildItem.StoreCodeUnit ();
  671. return;
  672. }
  673. }
  674. // None of the existing builders can accept this unit, get it a new builder
  675. builders.Add (CreateAssemblyBuilder (assemblyBaseName, virtualPath, buildItem));
  676. buildItem.StoreCodeUnit ();
  677. }
  678. static void AssertVirtualPathExists (VirtualPath virtualPath)
  679. {
  680. string realpath;
  681. bool dothrow = false;
  682. if (virtualPath.StartsWith (FAKE_VIRTUAL_PATH_PREFIX)) {
  683. realpath = virtualPath.Original.Substring (FAKE_VIRTUAL_PATH_PREFIX.Length);
  684. if (!File.Exists (realpath) && !Directory.Exists (realpath))
  685. dothrow = true;
  686. } else {
  687. VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
  688. string vpPath = virtualPath.Original;
  689. if (!vpp.FileExists (vpPath) && !vpp.DirectoryExists (vpPath))
  690. dothrow = true;
  691. }
  692. if (dothrow)
  693. throw new HttpException (404, "The file '" + virtualPath + "' does not exist.");
  694. }
  695. static void BuildAssembly (VirtualPath virtualPath)
  696. {
  697. AssertVirtualPathExists (virtualPath);
  698. LoadVirtualPathsToIgnore ();
  699. object ticket;
  700. bool acquired;
  701. string virtualDir = virtualPath.Directory;
  702. BuildKind buildKind = BuildKind.Unknown;
  703. bool kindPushed = false;
  704. string vpAbsolute = virtualPath.Absolute;
  705. acquired = AcquireCompilationTicket (virtualDir, out ticket);
  706. try {
  707. Monitor.Enter (ticket);
  708. lock (buildCacheLock) {
  709. if (buildCache.ContainsKey (vpAbsolute))
  710. return;
  711. }
  712. string assemblyBaseName;
  713. Dictionary <string, bool> vpCache = new Dictionary <string, bool> ();
  714. List <BuildItem> buildItems = LoadBuildProviders (virtualPath, virtualDir, vpCache, out buildKind, out assemblyBaseName);
  715. kindPushed = true;
  716. if (buildItems.Count == 0)
  717. return;
  718. Dictionary <Type, List <AssemblyBuilder>> assemblyBuilders = new Dictionary <Type, List <AssemblyBuilder>> ();
  719. bool checkForRecursion = buildKind == BuildKind.NonPages;
  720. foreach (BuildItem buildItem in buildItems) {
  721. if (checkForRecursion) {
  722. // Expensive but, alas, necessary - the builder in
  723. // our list might've been put into a different
  724. // assembly in a recursive call.
  725. lock (buildCacheLock) {
  726. if (buildCache.ContainsKey (buildItem.VirtualPath))
  727. continue;
  728. }
  729. }
  730. if (buildItem.assemblyBuilder == null)
  731. AssignToAssemblyBuilder (assemblyBaseName, virtualPath, buildItem, assemblyBuilders);
  732. }
  733. CompilerResults results;
  734. Assembly compiledAssembly;
  735. string vp;
  736. BuildProvider bp;
  737. foreach (List <AssemblyBuilder> abuilders in assemblyBuilders.Values) {
  738. foreach (AssemblyBuilder abuilder in abuilders) {
  739. abuilder.AddAssemblyReference (GetReferencedAssemblies () as List <Assembly>);
  740. try {
  741. results = abuilder.BuildAssembly (virtualPath);
  742. } catch (CompilationException ex) {
  743. throw new HttpException ("Compilation failed for virtual path '" + virtualPath.Original + "'.", ex);
  744. }
  745. // No results is not an error - it is possible that the assembly builder contained only .asmx and
  746. // .ashx files which had no body, just the directive. In such case, no code unit or code file is added
  747. // to the assembly builder and, in effect, no assembly is produced but there are STILL types that need
  748. // to be added to the cache.
  749. compiledAssembly = results != null ? results.CompiledAssembly : null;
  750. lock (buildCacheLock) {
  751. switch (buildKind) {
  752. case BuildKind.NonPages:
  753. if (compiledAssembly != null && !referencedAssemblies.Contains (compiledAssembly))
  754. referencedAssemblies.Add (compiledAssembly);
  755. break;
  756. case BuildKind.Application:
  757. globalAsaxAssembly = compiledAssembly;
  758. break;
  759. }
  760. foreach (BuildItem buildItem in buildItems) {
  761. if (buildItem.assemblyBuilder != abuilder)
  762. continue;
  763. vp = buildItem.VirtualPath;
  764. bp = buildItem.buildProvider;
  765. buildItem.SetCompiledAssembly (abuilder, compiledAssembly);
  766. if (!buildCache.ContainsKey (vp)) {
  767. AddToCache (vp, bp);
  768. buildCache.Add (vp, new BuildCacheItem (compiledAssembly, bp, results));
  769. }
  770. if (compiledAssembly != null && !nonPagesCache.ContainsKey (vp))
  771. nonPagesCache.Add (vp, compiledAssembly);
  772. }
  773. }
  774. }
  775. }
  776. // WARNING: enabling this code breaks the test suite - it stays
  777. // disabled until I figure out what to do about it.
  778. // See http://support.microsoft.com/kb/319947
  779. // lock (buildCountLock) {
  780. // buildCount++;
  781. // if (buildCount > CompilationConfig.NumRecompilesBeforeAppRestart)
  782. // HttpRuntime.UnloadAppDomain ();
  783. // }
  784. } finally {
  785. if (kindPushed && buildKind == BuildKind.Pages || buildKind == BuildKind.NonPages) {
  786. lock (buildCacheLock) {
  787. recursiveBuilds.Pop ();
  788. }
  789. }
  790. Monitor.Exit (ticket);
  791. if (acquired)
  792. ReleaseCompilationTicket (virtualDir);
  793. }
  794. }
  795. internal static void AddToCache (string virtualPath, BuildProvider bp)
  796. {
  797. HttpContext ctx = HttpContext.Current;
  798. HttpRequest req = ctx != null ? ctx.Request : null;
  799. if (req == null)
  800. throw new HttpException ("No current context.");
  801. CacheItemRemovedCallback cb = new CacheItemRemovedCallback (OnVirtualPathChanged);
  802. CacheDependency dep;
  803. ICollection col = bp.VirtualPathDependencies;
  804. int count;
  805. if (col != null && (count = col.Count) > 0) {
  806. string[] files = new string [count];
  807. int fileCount = 0;
  808. string file;
  809. foreach (object o in col) {
  810. file = o as string;
  811. if (String.IsNullOrEmpty (file))
  812. continue;
  813. files [fileCount++] = req.MapPath (file);
  814. }
  815. dep = new CacheDependency (files);
  816. } else
  817. dep = null;
  818. HttpRuntime.InternalCache.Add (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX + virtualPath,
  819. true,
  820. dep,
  821. Cache.NoAbsoluteExpiration,
  822. Cache.NoSlidingExpiration,
  823. CacheItemPriority.High,
  824. cb);
  825. }
  826. static int RemoveVirtualPathFromCaches (VirtualPath virtualPath)
  827. {
  828. lock (buildCacheLock) {
  829. // This is expensive, but we must do it - we must not leave
  830. // the assembly in which the invalidated type lived. At the same
  831. // time, we must remove the virtual paths which were in that
  832. // assembly from the other caches, so that they get recompiled.
  833. BuildCacheItem item = GetCachedItem (virtualPath);
  834. if (item == null)
  835. return 0;
  836. string vpAbsolute = virtualPath.Absolute;
  837. if (buildCache.ContainsKey (vpAbsolute))
  838. buildCache.Remove (vpAbsolute);
  839. Assembly asm;
  840. if (nonPagesCache.TryGetValue (vpAbsolute, out asm)) {
  841. nonPagesCache.Remove (vpAbsolute);
  842. if (referencedAssemblies.Contains (asm))
  843. referencedAssemblies.Remove (asm);
  844. List <string> keysToRemove = new List <string> ();
  845. foreach (KeyValuePair <string, Assembly> kvp in nonPagesCache)
  846. if (kvp.Value == asm)
  847. keysToRemove.Add (kvp.Key);
  848. foreach (string key in keysToRemove) {
  849. nonPagesCache.Remove (key);
  850. if (buildCache.ContainsKey (key))
  851. buildCache.Remove (key);
  852. }
  853. }
  854. return 1;
  855. }
  856. }
  857. static void OnVirtualPathChanged (string key, object value, CacheItemRemovedReason removedReason)
  858. {
  859. string virtualPath;
  860. if (StrUtils.StartsWith (key, BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX))
  861. virtualPath = key.Substring (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX_LENGTH);
  862. else
  863. return;
  864. RemoveVirtualPathFromCaches (new VirtualPath (virtualPath));
  865. }
  866. static bool AcquireCompilationTicket (string key, out object ticket)
  867. {
  868. lock (((ICollection)compilationTickets).SyncRoot) {
  869. if (!compilationTickets.TryGetValue (key, out ticket)) {
  870. ticket = new Mutex ();
  871. compilationTickets.Add (key, ticket);
  872. return true;
  873. }
  874. }
  875. return false;
  876. }
  877. static void ReleaseCompilationTicket (string key)
  878. {
  879. lock (((ICollection)compilationTickets).SyncRoot) {
  880. if (compilationTickets.ContainsKey (key))
  881. compilationTickets.Remove (key);
  882. }
  883. }
  884. // The 2 GetType() overloads work on the global.asax, App_GlobalResources, App_WebReferences or App_Browsers
  885. public static Type GetType (string typeName, bool throwOnError)
  886. {
  887. return GetType (typeName, throwOnError, false);
  888. }
  889. public static Type GetType (string typeName, bool throwOnError, bool ignoreCase)
  890. {
  891. Type ret = null;
  892. try {
  893. foreach (Assembly asm in TopLevel_Assemblies) {
  894. ret = asm.GetType (typeName, throwOnError, ignoreCase);
  895. if (ret != null)
  896. break;
  897. }
  898. } catch (Exception ex) {
  899. throw new HttpException ("Failed to find the specified type.", ex);
  900. }
  901. return ret;
  902. }
  903. internal static ICollection GetVirtualPathDependencies (string virtualPath, BuildProvider bprovider)
  904. {
  905. BuildProvider provider = bprovider;
  906. if (provider == null)
  907. provider = GetBuildProviderForPath (new VirtualPath (virtualPath), false);
  908. if (provider == null)
  909. return null;
  910. return provider.VirtualPathDependencies;
  911. }
  912. public static ICollection GetVirtualPathDependencies (string virtualPath)
  913. {
  914. return GetVirtualPathDependencies (virtualPath, null);
  915. }
  916. // Assemblies built from the App_Code directory
  917. public static IList CodeAssemblies {
  918. get { return AppCode_Assemblies; }
  919. }
  920. internal static IList TopLevelAssemblies {
  921. get { return TopLevel_Assemblies; }
  922. }
  923. internal static bool HaveResources {
  924. get { return haveResources; }
  925. set { haveResources = value; }
  926. }
  927. internal static bool BatchMode {
  928. get { return CompilationConfig.Batch; }
  929. }
  930. internal static CompilationSection CompilationConfig {
  931. get { return WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection; }
  932. }
  933. }
  934. }
  935. #endif