CachingCompiler.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. //
  2. // System.Web.Compilation.CachingCompiler
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002 Ximian, Inc (http://www.ximian.com)
  8. // (c) Copyright Novell, Inc. (http://www.novell.com)
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.CodeDom.Compiler;
  32. using System.Collections;
  33. using System.Collections.Specialized;
  34. using System.IO;
  35. using System.Reflection;
  36. using System.Threading;
  37. using System.Web.UI;
  38. using System.Web.Caching;
  39. using System.Web.Configuration;
  40. namespace System.Web.Compilation
  41. {
  42. class CachingCompiler
  43. {
  44. static string dynamicBase = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
  45. static Hashtable compilationTickets = new Hashtable ();
  46. const string cachePrefix = "@@Assembly";
  47. const string cacheTypePrefix = "@@@Type";
  48. static Hashtable assemblyCache = new Hashtable ();
  49. public static void InsertTypeFileDep (Type type, string filename)
  50. {
  51. CacheDependency dep = new CacheDependency (filename);
  52. HttpRuntime.InternalCache.Insert (cacheTypePrefix + filename, type, dep);
  53. }
  54. public static void InsertType (Type type, string filename)
  55. {
  56. string [] cacheKeys = new string [] { cachePrefix + filename };
  57. CacheDependency dep = new CacheDependency (null, cacheKeys);
  58. HttpRuntime.InternalCache.Insert (cacheTypePrefix + filename, type, dep);
  59. }
  60. public static Type GetTypeFromCache (string filename)
  61. {
  62. return (Type) HttpRuntime.InternalCache [cacheTypePrefix + filename];
  63. }
  64. public static CompilerResults Compile (BaseCompiler compiler)
  65. {
  66. Cache cache = HttpRuntime.InternalCache;
  67. string key = cachePrefix + compiler.Parser.InputFile;
  68. CompilerResults results = (CompilerResults) cache [key];
  69. #if NET_2_0
  70. if (!compiler.IsRebuildingPartial)
  71. #endif
  72. if (results != null)
  73. return results;
  74. object ticket;
  75. bool acquired = AcquireCompilationTicket (key, out ticket);
  76. try {
  77. Monitor.Enter (ticket);
  78. results = (CompilerResults) cache [key];
  79. #if NET_2_0
  80. if (!compiler.IsRebuildingPartial)
  81. #endif
  82. if (results != null)
  83. return results;
  84. ICodeCompiler comp = compiler.Compiler;
  85. GetExtraAssemblies (compiler.CompilerParameters);
  86. results = comp.CompileAssemblyFromDom (compiler.CompilerParameters, compiler.Unit);
  87. string [] deps = (string []) compiler.Parser.Dependencies.ToArray (typeof (string));
  88. cache.Insert (key, results, new CacheDependency (deps));
  89. } finally {
  90. Monitor.Exit (ticket);
  91. if (acquired)
  92. ReleaseCompilationTicket (key);
  93. }
  94. return results;
  95. }
  96. public static CompilerResults Compile (WebServiceCompiler compiler)
  97. {
  98. string key = cachePrefix + compiler.Parser.PhysicalPath;
  99. Cache cache = HttpRuntime.InternalCache;
  100. CompilerResults results = (CompilerResults) cache [key];
  101. if (results != null)
  102. return results;
  103. object ticket;
  104. bool acquired = AcquireCompilationTicket (key, out ticket);
  105. try {
  106. Monitor.Enter (ticket);
  107. results = (CompilerResults) cache [key];
  108. if (results != null)
  109. return results;
  110. SimpleWebHandlerParser parser = compiler.Parser;
  111. CompilerParameters options = compiler.CompilerOptions;
  112. options.IncludeDebugInformation = parser.Debug;
  113. GetExtraAssemblies (options);
  114. results = compiler.Compiler.CompileAssemblyFromFile (options, compiler.InputFile);
  115. string [] deps = (string []) parser.Dependencies.ToArray (typeof (string));
  116. cache.Insert (key, results, new CacheDependency (deps));
  117. } finally {
  118. Monitor.Exit (ticket);
  119. if (acquired)
  120. ReleaseCompilationTicket (key);
  121. }
  122. return results;
  123. }
  124. internal static CompilerParameters GetOptions (ICollection assemblies)
  125. {
  126. CompilerParameters options = new CompilerParameters ();
  127. if (assemblies != null) {
  128. StringCollection coll = options.ReferencedAssemblies;
  129. foreach (string str in assemblies)
  130. coll.Add (str);
  131. }
  132. GetExtraAssemblies (options);
  133. return options;
  134. }
  135. public static CompilerResults Compile (string language, string key, string file,
  136. ArrayList assemblies)
  137. {
  138. Cache cache = HttpRuntime.InternalCache;
  139. CompilerResults results = (CompilerResults) cache [cachePrefix + key];
  140. if (results != null)
  141. return results;
  142. if (!Directory.Exists (dynamicBase))
  143. Directory.CreateDirectory (dynamicBase);
  144. object ticket;
  145. bool acquired = AcquireCompilationTicket (cachePrefix + key, out ticket);
  146. try {
  147. Monitor.Enter (ticket);
  148. results = (CompilerResults) cache [cachePrefix + key];
  149. if (results != null)
  150. return results;
  151. #if NET_2_0
  152. CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
  153. Compiler c = config.Compilers[language];
  154. Type t = Type.GetType (c.Type, true);
  155. CodeDomProvider provider = Activator.CreateInstance (t) as CodeDomProvider;
  156. #else
  157. CompilationConfiguration config;
  158. config = CompilationConfiguration.GetInstance (HttpContext.Current);
  159. CodeDomProvider provider = config.GetProvider (language);
  160. #endif
  161. if (provider == null)
  162. throw new HttpException ("Configuration error. Language not supported: " +
  163. language, 500);
  164. ICodeCompiler compiler = provider.CreateCompiler ();
  165. CompilerParameters options = GetOptions (assemblies);
  166. TempFileCollection tempcoll = new TempFileCollection (config.TempDirectory, true);
  167. string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
  168. options.OutputAssembly = Path.Combine (dynamicBase, dllfilename);
  169. results = compiler.CompileAssemblyFromFile (options, file);
  170. ArrayList realdeps = new ArrayList (assemblies.Count + 1);
  171. realdeps.Add (file);
  172. for (int i = assemblies.Count - 1; i >= 0; i--) {
  173. string current = (string) assemblies [i];
  174. if (Path.IsPathRooted (current))
  175. realdeps.Add (current);
  176. }
  177. string [] deps = (string []) realdeps.ToArray (typeof (string));
  178. cache.Insert (cachePrefix + key, results, new CacheDependency (deps));
  179. } finally {
  180. Monitor.Exit (ticket);
  181. if (acquired)
  182. ReleaseCompilationTicket (cachePrefix + key);
  183. }
  184. return results;
  185. }
  186. public static Type CompileAndGetType (string typename, string language, string key,
  187. string file, ArrayList assemblies)
  188. {
  189. CompilerResults result = CachingCompiler.Compile (language, key, file, assemblies);
  190. if (result.NativeCompilerReturnValue != 0) {
  191. StreamReader reader = new StreamReader (file);
  192. throw new CompilationException (file, result.Errors, reader.ReadToEnd ());
  193. }
  194. Assembly assembly = result.CompiledAssembly;
  195. if (assembly == null) {
  196. StreamReader reader = new StreamReader (file);
  197. throw new CompilationException (file, result.Errors, reader.ReadToEnd ());
  198. }
  199. Type type = assembly.GetType (typename, true);
  200. InsertType (type, file);
  201. return type;
  202. }
  203. static void GetExtraAssemblies (CompilerParameters options)
  204. {
  205. StringCollection refAsm = options.ReferencedAssemblies;
  206. string asmName, asmLocation;
  207. #if NET_2_0
  208. ArrayList al = WebConfigurationManager.ExtraAssemblies;
  209. if (al != null && al.Count > 0) {
  210. foreach (object o in al) {
  211. asmName = o as string;
  212. if (asmName != null && !refAsm.Contains (asmName))
  213. refAsm.Add (asmName);
  214. }
  215. }
  216. Assembly asm;
  217. IList list = BuildManager.CodeAssemblies;
  218. if (list != null && list.Count > 0) {
  219. foreach (object o in list) {
  220. asm = o as Assembly;
  221. if (asm == null)
  222. continue;
  223. asmName = asm.Location;
  224. if (asmName != null && !refAsm.Contains (asmName))
  225. refAsm.Add (asmName);
  226. }
  227. }
  228. list = BuildManager.TopLevelAssemblies;
  229. if (list != null && list.Count > 0) {
  230. foreach (object o in list) {
  231. asm = o as Assembly;
  232. if (o == null)
  233. continue;
  234. asmName = asm.Location;
  235. if (!refAsm.Contains (asmName))
  236. refAsm.Add (asmName);
  237. }
  238. }
  239. CompilationSection cfg = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
  240. AssemblyCollection asmcoll = cfg != null ? cfg.Assemblies : null;
  241. if (asmcoll == null)
  242. return;
  243. foreach (AssemblyInfo ai in asmcoll) {
  244. asmLocation = GetAssemblyLocationFromName (ai.Assembly);
  245. if (asmLocation == null || refAsm.Contains (asmLocation))
  246. continue;
  247. refAsm.Add (asmLocation);
  248. }
  249. #else
  250. CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
  251. ArrayList asmcoll = cfg != null ? cfg.Assemblies : null;
  252. if (asmcoll == null)
  253. return;
  254. foreach (string asm in asmcoll) {
  255. asmLocation = GetAssemblyLocationFromName (asm);
  256. if (asmLocation == null || refAsm.Contains (asmLocation))
  257. continue;
  258. refAsm.Add (asmLocation);
  259. }
  260. #endif
  261. }
  262. static string GetAssemblyLocationFromName (string name)
  263. {
  264. Assembly asm = assemblyCache [name] as Assembly;
  265. if (asm != null)
  266. return asm.Location;
  267. try {
  268. asm = Assembly.Load (name);
  269. } catch {
  270. }
  271. if (asm == null)
  272. return null;
  273. assemblyCache [name] = asm;
  274. return asm.Location;
  275. }
  276. static bool AcquireCompilationTicket (string key, out object ticket)
  277. {
  278. lock (compilationTickets.SyncRoot) {
  279. ticket = compilationTickets [key];
  280. if (ticket == null) {
  281. ticket = new object ();
  282. compilationTickets [key] = ticket;
  283. return true;
  284. }
  285. }
  286. return false;
  287. }
  288. static void ReleaseCompilationTicket (string key)
  289. {
  290. lock (compilationTickets.SyncRoot) {
  291. compilationTickets.Remove (key);
  292. }
  293. }
  294. }
  295. }