2007-09-07 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / class / System.Web / System.Web.Compilation / CachingCompiler.cs
1 //
2 // System.Web.Compilation.CachingCompiler
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2002 Ximian, Inc (http://www.ximian.com)
8 // (c) Copyright Novell, Inc. (http://www.novell.com)
9 //
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.Compiler;
33 using System.Collections;
34 using System.Collections.Specialized;
35 using System.IO;
36 using System.Reflection;
37 using System.Threading;
38 using System.Web.UI;
39 using System.Web.Caching;
40 using System.Web.Configuration;
41
42 namespace System.Web.Compilation
43 {
44         class CachingCompiler
45         {
46                 static string dynamicBase = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
47                 static Hashtable compilationTickets = new Hashtable ();
48                 const string cachePrefix = "@@Assembly";
49                 const string cacheTypePrefix = "@@@Type";
50                 static Hashtable assemblyCache = new Hashtable ();
51                 
52                 public static void InsertTypeFileDep (Type type, string filename)
53                 {
54                         CacheDependency dep = new CacheDependency (filename);
55                         HttpRuntime.InternalCache.Insert (cacheTypePrefix + filename, type, dep);
56                 }
57
58                 public static void InsertType (Type type, string filename)
59                 {
60                         string [] cacheKeys = new string [] { cachePrefix + filename };
61                         CacheDependency dep = new CacheDependency (null, cacheKeys);
62                         HttpRuntime.InternalCache.Insert (cacheTypePrefix + filename, type, dep);
63                 }
64
65                 public static Type GetTypeFromCache (string filename)
66                 {
67                         return (Type) HttpRuntime.InternalCache [cacheTypePrefix + filename];
68                 }
69
70                 public static CompilerResults Compile (BaseCompiler compiler)
71                 {
72                         Cache cache = HttpRuntime.InternalCache;
73                         string key = cachePrefix + compiler.Parser.InputFile;
74                         CompilerResults results = (CompilerResults) cache [key];
75
76 #if NET_2_0
77                         if (!compiler.IsRebuildingPartial)
78 #endif
79                         if (results != null)
80                                 return results;
81
82                         object ticket;
83                         bool acquired = AcquireCompilationTicket (key, out ticket);
84
85                         try {
86                                 Monitor.Enter (ticket);
87                                 results = (CompilerResults) cache [key];
88 #if NET_2_0
89                                 if (!compiler.IsRebuildingPartial)
90 #endif
91                                 if (results != null)
92                                         return results;
93
94                                 ICodeCompiler comp = compiler.Compiler;
95                                 GetExtraAssemblies (compiler.CompilerParameters);
96                                 results = comp.CompileAssemblyFromDom (compiler.CompilerParameters, compiler.Unit);
97                                 string [] deps = (string []) compiler.Parser.Dependencies.ToArray (typeof (string));
98                                 cache.Insert (key, results, new CacheDependency (deps));
99                         } finally {
100                                 Monitor.Exit (ticket);
101                                 if (acquired)
102                                         ReleaseCompilationTicket (key);
103                         }
104
105                         return results;
106                 }
107
108                 public static CompilerResults Compile (WebServiceCompiler compiler)
109                 {
110                         string key = cachePrefix + compiler.Parser.PhysicalPath;
111                         Cache cache = HttpRuntime.InternalCache;
112                         CompilerResults results = (CompilerResults) cache [key];
113                         if (results != null)
114                                 return results;
115
116                         object ticket;
117                         bool acquired = AcquireCompilationTicket (key, out ticket);
118
119                         try {
120                                 Monitor.Enter (ticket);
121                                 results = (CompilerResults) cache [key];
122                                 if (results != null)
123                                         return results;
124
125                                 SimpleWebHandlerParser parser = compiler.Parser;
126                                 CompilerParameters options = compiler.CompilerOptions;
127                                 options.IncludeDebugInformation = parser.Debug;
128                                 GetExtraAssemblies (options);
129                                 results = compiler.Compiler.CompileAssemblyFromFile (options, compiler.InputFile);
130                                 string [] deps = (string []) parser.Dependencies.ToArray (typeof (string));
131                                 cache.Insert (key, results, new CacheDependency (deps));
132                         } finally {
133                                 Monitor.Exit (ticket);
134                                 if (acquired)
135                                         ReleaseCompilationTicket (key);
136                         }
137
138                         return results;
139                 }
140
141                 internal static CompilerParameters GetOptions (ICollection assemblies)
142                 {
143                         CompilerParameters options = new CompilerParameters ();
144                         if (assemblies != null) {
145                                 StringCollection coll = options.ReferencedAssemblies;
146                                 foreach (string str in assemblies)
147                                         coll.Add (str);
148                         }
149                         GetExtraAssemblies (options);
150                         return options;
151                 }
152
153                 public static CompilerResults Compile (string language, string key, string file,
154                                                         ArrayList assemblies)
155                 {
156                         Cache cache = HttpRuntime.InternalCache;
157                         CompilerResults results = (CompilerResults) cache [cachePrefix + key];
158                         if (results != null)
159                                 return results;
160
161                         if (!Directory.Exists (dynamicBase))
162                                 Directory.CreateDirectory (dynamicBase);
163
164                         object ticket;
165                         bool acquired = AcquireCompilationTicket (cachePrefix + key, out ticket);
166
167                         try {
168                                 Monitor.Enter (ticket);
169                                 results = (CompilerResults) cache [cachePrefix + key];
170                                 if (results != null)
171                                         return results;
172  
173 #if NET_2_0
174                                 CompilationSection config = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
175                                 Compiler c = config.Compilers[language];
176                                 Type t = Type.GetType (c.Type, true);
177                                 CodeDomProvider provider = Activator.CreateInstance (t) as CodeDomProvider;
178 #else
179                                 CompilationConfiguration config;
180                                 config = CompilationConfiguration.GetInstance (HttpContext.Current);
181                                 CodeDomProvider provider = config.GetProvider (language);
182 #endif
183                                 if (provider == null)
184                                         throw new HttpException ("Configuration error. Language not supported: " +
185                                                                   language, 500);
186                                 ICodeCompiler compiler = provider.CreateCompiler ();
187                                 CompilerParameters options = GetOptions (assemblies);
188                                 TempFileCollection tempcoll = new TempFileCollection (config.TempDirectory, true);
189                                 string dllfilename = Path.GetFileName (tempcoll.AddExtension ("dll", true));
190                                 options.OutputAssembly = Path.Combine (dynamicBase, dllfilename);
191                                 results = compiler.CompileAssemblyFromFile (options, file);
192                                 ArrayList realdeps = new ArrayList (assemblies.Count + 1);
193                                 realdeps.Add (file);
194                                 for (int i = assemblies.Count - 1; i >= 0; i--) {
195                                         string current = (string) assemblies [i];
196                                         if (Path.IsPathRooted (current))
197                                                 realdeps.Add (current);
198                                 }
199
200                                 string [] deps = (string []) realdeps.ToArray (typeof (string));
201                                 cache.Insert (cachePrefix + key, results, new CacheDependency (deps));
202                         } finally {
203                                 Monitor.Exit (ticket);
204                                 if (acquired)
205                                         ReleaseCompilationTicket (cachePrefix + key);
206                         }
207
208                         return results;
209                 }
210
211                 public static Type CompileAndGetType (string typename, string language, string key,
212                                                 string file, ArrayList assemblies)
213                 {
214                         CompilerResults result = CachingCompiler.Compile (language, key, file, assemblies);
215                         if (result.NativeCompilerReturnValue != 0) {
216                                 StreamReader reader = new StreamReader (file);
217                                 throw new CompilationException (file, result.Errors, reader.ReadToEnd ());
218                         }
219
220                         Assembly assembly = result.CompiledAssembly;
221                         if (assembly == null) {
222                                 StreamReader reader = new StreamReader (file);
223                                 throw new CompilationException (file, result.Errors, reader.ReadToEnd ());
224                         }
225                 
226                         Type type = assembly.GetType (typename, true);
227                         InsertType (type, file);
228                         return type;
229                 }
230
231                 static void GetExtraAssemblies (CompilerParameters options)
232                 {
233                         StringCollection refAsm = options.ReferencedAssemblies;
234                         string asmName, asmLocation;
235                         
236 #if NET_2_0
237                         ArrayList al = WebConfigurationManager.ExtraAssemblies;
238                         
239                         if (al != null && al.Count > 0) {
240                                 foreach (object o in al) {
241                                         asmName = o as string;
242                                         if (asmName != null && !refAsm.Contains (asmName))
243                                                 refAsm.Add (asmName);
244                                 }
245                         }
246
247                         Assembly asm;
248                         IList list = BuildManager.CodeAssemblies;
249                         if (list != null && list.Count > 0) {
250                                 foreach (object o in list) {
251                                         asm = o as Assembly;
252                                         if (asm == null)
253                                                 continue;
254                                         asmName = asm.Location;
255                                         if (asmName != null && !refAsm.Contains (asmName))
256                                                 refAsm.Add (asmName);
257                                 }
258                         }
259                         
260                         list = BuildManager.TopLevelAssemblies;
261                         if (list != null && list.Count > 0) {
262                                 foreach (object o in list) {
263                                         asm = o as Assembly;
264                                         if (o == null)
265                                                 continue;
266                                         asmName = asm.Location;
267                                         if (!refAsm.Contains (asmName))
268                                                 refAsm.Add (asmName);
269                                 }
270                         }
271
272                         CompilationSection cfg = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
273                         AssemblyCollection asmcoll = cfg != null ? cfg.Assemblies : null;
274
275                         if (asmcoll == null)
276                                 return;
277
278                         foreach (AssemblyInfo ai in asmcoll) {
279                                 asmLocation = GetAssemblyLocationFromName (ai.Assembly);
280                                 
281                                 if (asmLocation == null || refAsm.Contains (asmLocation))
282                                         continue;
283                                 refAsm.Add (asmLocation);
284                         }
285 #else
286                         CompilationConfiguration cfg = CompilationConfiguration.GetInstance (HttpContext.Current);
287                         ArrayList asmcoll = cfg != null ? cfg.Assemblies : null;
288
289                         if (asmcoll == null)
290                                 return;
291
292                         foreach (string asm in asmcoll) {
293                                 asmLocation = GetAssemblyLocationFromName (asm);
294                                 
295                                 if (asmLocation == null || refAsm.Contains (asmLocation))
296                                         continue;
297                                 refAsm.Add (asmLocation);
298                         }
299 #endif
300                 }
301
302                 static string GetAssemblyLocationFromName (string name)
303                 {
304                         Assembly asm = assemblyCache [name] as Assembly;
305                         if (asm != null)
306                                 return asm.Location;
307
308                         try {
309                                 asm = Assembly.Load (name);
310                         } catch {
311                         }
312
313                         if (asm == null)
314                                 return null;
315
316                         assemblyCache [name] = asm;
317                         return asm.Location;
318                 }
319                 
320                 static bool AcquireCompilationTicket (string key, out object ticket)
321                 {
322                         lock (compilationTickets.SyncRoot) {
323                                 ticket = compilationTickets [key];
324                                 if (ticket == null) {
325                                         ticket = new object ();
326                                         compilationTickets [key] = ticket;
327                                         return true;
328                                 }
329                         }
330                         return false;
331                 }
332
333                 static void ReleaseCompilationTicket (string key)
334                 {
335                         lock (compilationTickets.SyncRoot) {
336                                 compilationTickets.Remove (key);
337                         }
338                 }
339         }
340 }
341