Merge pull request #1504 from madrang/SafeHandle.SetInvalidRelease
[mono.git] / mcs / class / System / Microsoft.CSharp / CSharpCodeCompiler.cs
1 //
2 // Mono.CSharp CSharpCodeCompiler Class implementation
3 //
4 // Authors:
5 //      Sean Kasun (seank@users.sf.net)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // Copyright (c) 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
32 namespace Mono.CSharp
33 {
34         using System;
35         using System.CodeDom;
36         using System.CodeDom.Compiler;
37         using System.ComponentModel;
38         using System.IO;
39         using System.Text;
40         using System.Reflection;
41         using System.Collections;
42         using System.Collections.Specialized;
43         using System.Diagnostics;
44         using System.Text.RegularExpressions;
45         using System.Threading;
46         using System.Collections.Generic;
47         using System.Globalization;
48         
49         internal class CSharpCodeCompiler : CSharpCodeGenerator, ICodeCompiler
50         {
51                 static string windowsMcsPath;
52                 static string windowsMonoPath;
53
54                 Mutex mcsOutMutex;
55                 StringCollection mcsOutput;
56                 
57                 static CSharpCodeCompiler ()
58                 {
59                         if (Path.DirectorySeparatorChar == '\\') {
60                                 PropertyInfo gac = typeof (Environment).GetProperty ("GacPath", BindingFlags.Static|BindingFlags.NonPublic);
61                                 MethodInfo get_gac = gac.GetGetMethod (true);
62                                 string p = Path.GetDirectoryName (
63                                         (string) get_gac.Invoke (null, null));
64                                 windowsMonoPath = Path.Combine (
65                                         Path.GetDirectoryName (
66                                                 Path.GetDirectoryName (p)),
67                                         "bin\\mono.bat");
68                                 if (!File.Exists (windowsMonoPath))
69                                         windowsMonoPath = Path.Combine (
70                                                 Path.GetDirectoryName (
71                                                         Path.GetDirectoryName (p)),
72                                                 "bin\\mono.exe");
73                                 if (!File.Exists (windowsMonoPath))
74                                         windowsMonoPath = Path.Combine (
75                                                 Path.GetDirectoryName (
76                                                         Path.GetDirectoryName (
77                                                                 Path.GetDirectoryName (p))),
78                                                 "mono\\mono\\mini\\mono.exe");
79                                 if (!File.Exists (windowsMonoPath))
80                                         throw new FileNotFoundException ("Windows mono path not found: " + windowsMonoPath);
81
82                                 windowsMcsPath = Path.Combine (p, "4.5\\mcs.exe");
83                                 if (!File.Exists (windowsMcsPath))
84                                         windowsMcsPath = Path.Combine(Path.GetDirectoryName (p), "lib\\build\\mcs.exe");
85                                 
86                                 if (!File.Exists (windowsMcsPath))
87                                         throw new FileNotFoundException ("Windows mcs path not found: " + windowsMcsPath);
88                         }
89                 }
90
91                 //
92                 // Constructors
93                 //
94                 public CSharpCodeCompiler()
95                 {
96                 }
97
98                 public CSharpCodeCompiler (IDictionary <string, string> providerOptions) :
99                         base (providerOptions)
100                 {
101                 }
102                 
103                 //
104                 // Methods
105                 //
106                 public CompilerResults CompileAssemblyFromDom (CompilerParameters options, CodeCompileUnit e)
107                 {
108                         return CompileAssemblyFromDomBatch (options, new CodeCompileUnit[] { e });
109                 }
110
111                 public CompilerResults CompileAssemblyFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
112                 {
113                         if (options == null) {
114                                 throw new ArgumentNullException ("options");
115                         }
116
117                         try {
118                                 return CompileFromDomBatch (options, ea);
119                         } finally {
120                                 options.TempFiles.Delete ();
121                         }
122                 }
123
124                 public CompilerResults CompileAssemblyFromFile (CompilerParameters options, string fileName)
125                 {
126                         return CompileAssemblyFromFileBatch (options, new string[] { fileName });
127                 }
128
129                 public CompilerResults CompileAssemblyFromFileBatch (CompilerParameters options, string[] fileNames)
130                 {
131                         if (options == null) {
132                                 throw new ArgumentNullException ("options");
133                         }
134
135                         try {
136                                 return CompileFromFileBatch (options, fileNames);
137                         } finally {
138                                 options.TempFiles.Delete ();
139                         }
140                 }
141
142                 public CompilerResults CompileAssemblyFromSource (CompilerParameters options, string source)
143                 {
144                         return CompileAssemblyFromSourceBatch (options, new string[] { source });
145                 }
146
147                 public CompilerResults CompileAssemblyFromSourceBatch (CompilerParameters options, string[] sources)
148                 {
149                         if (options == null) {
150                                 throw new ArgumentNullException ("options");
151                         }
152
153                         try {
154                                 return CompileFromSourceBatch (options, sources);
155                         } finally {
156                                 options.TempFiles.Delete ();
157                         }
158                 }
159
160                 private CompilerResults CompileFromFileBatch (CompilerParameters options, string[] fileNames)
161                 {
162                         if (null == options)
163                                 throw new ArgumentNullException("options");
164                         if (null == fileNames)
165                                 throw new ArgumentNullException("fileNames");
166
167                         CompilerResults results=new CompilerResults(options.TempFiles);
168                         Process mcs=new Process();
169
170                         // FIXME: these lines had better be platform independent.
171                         if (Path.DirectorySeparatorChar == '\\') {
172                                 mcs.StartInfo.FileName = windowsMonoPath;
173                                 mcs.StartInfo.Arguments = "\"" + windowsMcsPath + "\" " +
174                                         BuildArgs (options, fileNames, ProviderOptions);
175                         } else {
176                                 mcs.StartInfo.FileName="mcs";
177                                 mcs.StartInfo.Arguments=BuildArgs(options, fileNames, ProviderOptions);
178                         }
179
180                         mcsOutput = new StringCollection ();
181                         mcsOutMutex = new Mutex ();
182 /*                     
183                         string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
184                         if (monoPath != null)
185                                 monoPath = String.Empty;
186
187                         string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
188                         if (privateBinPath != null && privateBinPath.Length > 0)
189                                 monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
190
191                         if (monoPath.Length > 0) {
192                                 StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
193                                 if (dict.ContainsKey ("MONO_PATH"))
194                                         dict ["MONO_PATH"] = monoPath;
195                                 else
196                                         dict.Add ("MONO_PATH", monoPath);
197                         }
198 */
199                         /*
200                          * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that
201                          * may not handle some of the options causing compilation failure
202                          */
203                         mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty;
204
205                         mcs.StartInfo.CreateNoWindow=true;
206                         mcs.StartInfo.UseShellExecute=false;
207                         mcs.StartInfo.RedirectStandardOutput=true;
208                         mcs.StartInfo.RedirectStandardError=true;
209                         mcs.ErrorDataReceived += new DataReceivedEventHandler (McsStderrDataReceived);
210                         
211                         try {
212                                 mcs.Start();
213                         } catch (Exception e) {
214                                 Win32Exception exc = e as Win32Exception;
215                                 if (exc != null) {
216                                         throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName,
217                                                                         Win32Exception.W32ErrorMessage (exc.NativeErrorCode)));
218                                 }
219                                 throw;
220                         }
221
222                         try {
223                                 mcs.BeginOutputReadLine ();
224                                 mcs.BeginErrorReadLine ();
225                                 mcs.WaitForExit();
226                                 
227                                 results.NativeCompilerReturnValue = mcs.ExitCode;
228                         } finally {
229                                 mcs.CancelErrorRead ();
230                                 mcs.CancelOutputRead ();
231                                 mcs.Close();
232                         }
233
234                         StringCollection sc = mcsOutput;
235                        
236                         bool loadIt=true;
237                         foreach (string error_line in mcsOutput) {
238                                 CompilerError error = CreateErrorFromString (error_line);
239                                 if (error != null) {
240                                         results.Errors.Add (error);
241                                         if (!error.IsWarning)
242                                                 loadIt = false;
243                                 }
244                         }
245                         
246                         if (sc.Count > 0) {
247                                 sc.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
248                                 results.Output = sc;
249                         }
250
251                         if (loadIt) {
252                                 if (!File.Exists (options.OutputAssembly)) {
253                                         StringBuilder sb = new StringBuilder ();
254                                         foreach (string s in sc)
255                                                 sb.Append (s + Environment.NewLine);
256                                         
257                                         throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
258                                 }
259                                 
260                                 if (options.GenerateInMemory) {
261                                         using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
262                                                 byte[] buffer = new byte[fs.Length];
263                                                 fs.Read(buffer, 0, buffer.Length);
264                                                 results.CompiledAssembly = Assembly.Load(buffer, null);
265                                                 fs.Close();
266                                         }
267                                 } else {
268                                         // Avoid setting CompiledAssembly right now since the output might be a netmodule
269                                         results.PathToAssembly = options.OutputAssembly;
270                                 }
271                         } else {
272                                 results.CompiledAssembly = null;
273                         }
274                         
275                         return results;
276                 }
277
278                 void McsStderrDataReceived (object sender, DataReceivedEventArgs args)
279                 {
280                         if (args.Data != null) {
281                                 mcsOutMutex.WaitOne ();
282                                 mcsOutput.Add (args.Data);
283                                 mcsOutMutex.ReleaseMutex ();
284                         }
285                 }               
286
287                 private static string BuildArgs(CompilerParameters options,string[] fileNames, IDictionary <string, string> providerOptions)
288                 {
289                         StringBuilder args=new StringBuilder();
290                         if (options.GenerateExecutable)
291                                 args.Append("/target:exe ");
292                         else
293                                 args.Append("/target:library ");
294
295                         string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
296                         if (privateBinPath != null && privateBinPath.Length > 0)
297                                 args.AppendFormat ("/lib:\"{0}\" ", privateBinPath);
298                         
299                         if (options.Win32Resource != null)
300                                 args.AppendFormat("/win32res:\"{0}\" ",
301                                         options.Win32Resource);
302
303                         if (options.IncludeDebugInformation)
304                                 args.Append("/debug+ /optimize- ");
305                         else
306                                 args.Append("/debug- /optimize+ ");
307
308                         if (options.TreatWarningsAsErrors)
309                                 args.Append("/warnaserror ");
310
311                         if (options.WarningLevel >= 0)
312                                 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
313
314                         if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
315                                 string extension = (options.GenerateExecutable ? "exe" : "dll");
316                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
317                                         !options.GenerateInMemory);
318                         }
319                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
320
321                         foreach (string import in options.ReferencedAssemblies) {
322                                 if (import == null || import.Length == 0)
323                                         continue;
324
325                                 args.AppendFormat("/r:\"{0}\" ",import);
326                         }
327
328                         if (options.CompilerOptions != null) {
329                                 args.Append (options.CompilerOptions);
330                                 args.Append (" ");
331                         }
332
333                         foreach (string embeddedResource in options.EmbeddedResources) {
334                                 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
335                         }
336
337                         foreach (string linkedResource in options.LinkedResources) {
338                                 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
339                         }
340                         
341                         if (providerOptions != null && providerOptions.Count > 0) {
342                                 string langver;
343
344                                 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
345                                         langver = "3.5";
346
347                                 if (langver.Length >= 1 && langver [0] == 'v')
348                                         langver = langver.Substring (1);
349
350                                 switch (langver) {
351                                         case "2.0":
352                                                 args.Append ("/langversion:ISO-2 ");
353                                                 break;
354
355                                         case "3.5":
356                                                 // current default, omit the switch
357                                                 break;
358                                 }
359                         }
360
361                         args.Append("/sdk:4.5");
362
363                         args.Append (" -- ");
364                         foreach (string source in fileNames)
365                                 args.AppendFormat("\"{0}\" ",source);
366                         return args.ToString();
367                 }
368
369                 // Keep in sync with mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
370                 const string ErrorRegexPattern = @"
371                         ^
372                         (\s*(?<file>[^\(]+)                         # filename (optional)
373                          (\((?<line>\d*)(,(?<column>\d*[\+]*))?\))? # line+column (optional)
374                          :\s+)?
375                         (?<level>\w+)                               # error|warning
376                         \s+
377                         (?<number>[^:]*\d)                          # CS1234
378                         :
379                         \s*
380                         (?<message>.*)$";
381
382                 private static CompilerError CreateErrorFromString(string error_string)
383                 {
384                         if (error_string.StartsWith ("BETA"))
385                                 return null;
386
387                         if (error_string == null || error_string == "")
388                                 return null;
389
390                         CompilerError error=new CompilerError();
391                         Regex reg = new Regex (ErrorRegexPattern, RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
392                         Match match=reg.Match(error_string);
393                         if (!match.Success) {
394                                 // We had some sort of runtime crash
395                                 error.ErrorText = error_string;
396                                 error.IsWarning = false;
397                                 error.ErrorNumber = "";
398                                 return error;
399                         }
400                         if (String.Empty != match.Result("${file}"))
401                                 error.FileName=match.Result("${file}");
402                         if (String.Empty != match.Result("${line}"))
403                                 error.Line=Int32.Parse(match.Result("${line}"));
404                         if (String.Empty != match.Result("${column}"))
405                                 error.Column=Int32.Parse(match.Result("${column}").Trim('+'));
406
407                         string level = match.Result ("${level}");
408                         if (level == "warning")
409                                 error.IsWarning = true;
410                         else if (level != "error")
411                                 return null; // error CS8028 will confuse the regex.
412
413                         error.ErrorNumber=match.Result("${number}");
414                         error.ErrorText=match.Result("${message}");
415                         return error;
416                 }
417
418                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
419                 {
420                         return temp_files.AddExtension (extension, keepFile);
421                 }
422
423                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension)
424                 {
425                         return temp_files.AddExtension (extension);
426                 }
427
428                 private CompilerResults CompileFromDomBatch (CompilerParameters options, CodeCompileUnit[] ea)
429                 {
430                         if (options == null) {
431                                 throw new ArgumentNullException ("options");
432                         }
433
434                         if (ea == null) {
435                                 throw new ArgumentNullException ("ea");
436                         }
437
438                         string[] fileNames = new string[ea.Length];
439                         StringCollection assemblies = options.ReferencedAssemblies;
440
441                         for (int i = 0; i < ea.Length; i++) {
442                                 CodeCompileUnit compileUnit = ea[i];
443                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
444                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
445                                 StreamWriter s = new StreamWriter (f, Encoding.UTF8);
446                                 if (compileUnit.ReferencedAssemblies != null) {
447                                         foreach (string str in compileUnit.ReferencedAssemblies) {
448                                                 if (!assemblies.Contains (str))
449                                                         assemblies.Add (str);
450                                         }
451                                 }
452
453                                 ((ICodeGenerator) this).GenerateCodeFromCompileUnit (compileUnit, s, new CodeGeneratorOptions ());
454                                 s.Close ();
455                                 f.Close ();
456                         }
457                         return CompileAssemblyFromFileBatch (options, fileNames);
458                 }
459
460                 private CompilerResults CompileFromSourceBatch (CompilerParameters options, string[] sources)
461                 {
462                         if (options == null) {
463                                 throw new ArgumentNullException ("options");
464                         }
465
466                         if (sources == null) {
467                                 throw new ArgumentNullException ("sources");
468                         }
469
470                         string[] fileNames = new string[sources.Length];
471
472                         for (int i = 0; i < sources.Length; i++) {
473                                 fileNames[i] = GetTempFileNameWithExtension (options.TempFiles, i + ".cs");
474                                 FileStream f = new FileStream (fileNames[i], FileMode.OpenOrCreate);
475                                 using (StreamWriter s = new StreamWriter (f, Encoding.UTF8)) {
476                                         s.Write (sources[i]);
477                                         s.Close ();
478                                 }
479                                 f.Close ();
480                         }
481                         return CompileFromFileBatch (options, fileNames);
482                 }
483         }
484 }