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 (!compiler.IsRebuildingPartial)
  70. if (results != null)
  71. return results;
  72. object ticket;
  73. bool acquired = AcquireCompilationTicket (key, out ticket);
  74. try {
  75. Monitor.Enter (ticket);
  76. results = (CompilerResults) cache [key];
  77. if (!compiler.IsRebuildingPartial)
  78. if (results != null)
  79. return results;
  80. CodeDomProvider comp = compiler.Provider;
  81. CompilerParameters options = compiler.CompilerParameters;
  82. GetExtraAssemblies (options);
  83. results = comp.CompileAssemblyFromDom (options, compiler.CompileUnit);
  84. ArrayList dependencies = compiler.Parser.Dependencies;
  85. if (dependencies != null && dependencies.Count > 0) {
  86. string [] deps = (string []) dependencies.ToArray (typeof (string));
  87. HttpContext ctx = HttpContext.Current;
  88. HttpRequest req = ctx != null ? ctx.Request : null;
  89. if (req == null)
  90. throw new HttpException ("No current context, cannot compile.");
  91. for (int i = 0; i < deps.Length; i++)
  92. deps [i] = req.MapPath (deps [i]);
  93. cache.Insert (key, results, new CacheDependency (deps));
  94. }
  95. } finally {
  96. Monitor.Exit (ticket);
  97. if (acquired)
  98. ReleaseCompilationTicket (key);
  99. }
  100. return results;
  101. }
  102. public static CompilerResults Compile (WebServiceCompiler compiler)
  103. {
  104. string key = cachePrefix + compiler.Parser.PhysicalPath;
  105. Cache cache = HttpRuntime.InternalCache;
  106. CompilerResults results = (CompilerResults) cache [key];
  107. if (results != null)
  108. return results;
  109. object ticket;
  110. bool acquired = AcquireCompilationTicket (key, out ticket);
  111. try {
  112. Monitor.Enter (ticket);
  113. results = (CompilerResults) cache [key];
  114. if (results != null)
  115. return results;
  116. CodeDomProvider comp = compiler.Provider;
  117. CompilerParameters options = compiler.CompilerParameters;
  118. GetExtraAssemblies (options);
  119. results = comp.CompileAssemblyFromFile (options, compiler.InputFile);
  120. string [] deps = (string []) compiler.Parser.Dependencies.ToArray (typeof (string));
  121. cache.Insert (key, results, new CacheDependency (deps));
  122. } finally {
  123. Monitor.Exit (ticket);
  124. if (acquired)
  125. ReleaseCompilationTicket (key);
  126. }
  127. return results;
  128. }
  129. internal static CompilerParameters GetOptions (ICollection assemblies)
  130. {
  131. CompilerParameters options = new CompilerParameters ();
  132. if (assemblies != null) {
  133. StringCollection coll = options.ReferencedAssemblies;
  134. foreach (string str in assemblies)
  135. coll.Add (str);
  136. }
  137. GetExtraAssemblies (options);
  138. return options;
  139. }
  140. public static CompilerResults Compile (string language, string key, string file, ArrayList assemblies)
  141. {
  142. return Compile (language, key, file, assemblies, false);
  143. }
  144. public static CompilerResults Compile (string language, string key, string file, ArrayList assemblies, bool debug)
  145. {
  146. Cache cache = HttpRuntime.InternalCache;
  147. CompilerResults results = (CompilerResults) cache [cachePrefix + key];
  148. if (results != null)
  149. return results;
  150. if (!Directory.Exists (dynamicBase))
  151. Directory.CreateDirectory (dynamicBase);
  152. object ticket;
  153. bool acquired = AcquireCompilationTicket (cachePrefix + key, out ticket);
  154. try {
  155. Monitor.Enter (ticket);
  156. results = (CompilerResults) cache [cachePrefix + key];
  157. if (results != null)
  158. return results;
  159. CodeDomProvider provider = null;
  160. int warningLevel;
  161. string compilerOptions;
  162. string tempdir;
  163. provider = BaseCompiler.CreateProvider (language, out compilerOptions, out warningLevel, out tempdir);
  164. if (provider == null)
  165. throw new HttpException ("Configuration error. Language not supported: " +
  166. language, 500);
  167. CodeDomProvider compiler = provider;
  168. CompilerParameters options = GetOptions (assemblies);
  169. options.IncludeDebugInformation = debug;
  170. options.WarningLevel = warningLevel;
  171. options.CompilerOptions = compilerOptions;
  172. TempFileCollection tempcoll = new TempFileCollection (tempdir, true);
  173. string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
  174. options.OutputAssembly = Path.Combine (dynamicBase, dllfilename);
  175. results = compiler.CompileAssemblyFromFile (options, file);
  176. ArrayList realdeps = new ArrayList (assemblies.Count + 1);
  177. realdeps.Add (file);
  178. for (int i = assemblies.Count - 1; i >= 0; i--) {
  179. string current = (string) assemblies [i];
  180. if (Path.IsPathRooted (current))
  181. realdeps.Add (current);
  182. }
  183. string [] deps = (string []) realdeps.ToArray (typeof (string));
  184. cache.Insert (cachePrefix + key, results, new CacheDependency (deps));
  185. } finally {
  186. Monitor.Exit (ticket);
  187. if (acquired)
  188. ReleaseCompilationTicket (cachePrefix + key);
  189. }
  190. return results;
  191. }
  192. public static Type CompileAndGetType (string typename, string language, string key,
  193. string file, ArrayList assemblies)
  194. {
  195. CompilerResults result = CachingCompiler.Compile (language, key, file, assemblies);
  196. if (result.NativeCompilerReturnValue != 0) {
  197. using (StreamReader reader = new StreamReader (file)) {
  198. throw new CompilationException (file, result.Errors, reader.ReadToEnd ());
  199. }
  200. }
  201. Assembly assembly = result.CompiledAssembly;
  202. if (assembly == null) {
  203. using (StreamReader reader = new StreamReader (file)) {
  204. throw new CompilationException (file, result.Errors, reader.ReadToEnd ());
  205. }
  206. }
  207. Type type = assembly.GetType (typename, true);
  208. InsertType (type, file);
  209. return type;
  210. }
  211. static void GetExtraAssemblies (CompilerParameters options)
  212. {
  213. StringCollection refAsm = options.ReferencedAssemblies;
  214. string asmLocation;
  215. string asmName;
  216. ArrayList al = WebConfigurationManager.ExtraAssemblies;
  217. if (al != null && al.Count > 0) {
  218. foreach (object o in al) {
  219. asmName = o as string;
  220. if (asmName != null && !refAsm.Contains (asmName))
  221. refAsm.Add (asmName);
  222. }
  223. }
  224. Assembly asm;
  225. IList list = BuildManager.CodeAssemblies;
  226. if (list != null && list.Count > 0) {
  227. foreach (object o in list) {
  228. asm = o as Assembly;
  229. if (asm == null)
  230. continue;
  231. asmName = asm.Location;
  232. if (asmName != null && !refAsm.Contains (asmName))
  233. refAsm.Add (asmName);
  234. }
  235. }
  236. list = BuildManager.TopLevelAssemblies;
  237. if (list != null && list.Count > 0) {
  238. foreach (object o in list) {
  239. asm = o as Assembly;
  240. if (o == null)
  241. continue;
  242. asmName = asm.Location;
  243. if (!refAsm.Contains (asmName))
  244. refAsm.Add (asmName);
  245. }
  246. }
  247. CompilationSection cfg = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection;
  248. AssemblyCollection asmcoll = cfg != null ? cfg.Assemblies : null;
  249. if (asmcoll == null)
  250. return;
  251. foreach (AssemblyInfo ai in asmcoll) {
  252. asmLocation = GetAssemblyLocationFromName (ai.Assembly);
  253. if (asmLocation == null || refAsm.Contains (asmLocation))
  254. continue;
  255. refAsm.Add (asmLocation);
  256. }
  257. }
  258. static string GetAssemblyLocationFromName (string name)
  259. {
  260. Assembly asm = assemblyCache [name] as Assembly;
  261. if (asm != null)
  262. return asm.Location;
  263. try {
  264. asm = Assembly.Load (name);
  265. } catch {
  266. }
  267. if (asm == null)
  268. return null;
  269. assemblyCache [name] = asm;
  270. return asm.Location;
  271. }
  272. static bool AcquireCompilationTicket (string key, out object ticket)
  273. {
  274. lock (compilationTickets.SyncRoot) {
  275. ticket = compilationTickets [key];
  276. if (ticket == null) {
  277. ticket = new object ();
  278. compilationTickets [key] = ticket;
  279. return true;
  280. }
  281. }
  282. return false;
  283. }
  284. static void ReleaseCompilationTicket (string key)
  285. {
  286. lock (compilationTickets.SyncRoot) {
  287. compilationTickets.Remove (key);
  288. }
  289. }
  290. }
  291. }