[System]: Fix TLS Provider registration and use BTLS instead of Legacy. (#4793)
[mono.git] / mcs / class / System / Microsoft.CSharp / CSharpCodeGenerator.cs
1 //
2 // CSharpCodeGenerator:
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 using System;
33 using System.CodeDom;
34 using System.CodeDom.Compiler;
35 using System.ComponentModel;
36 using System.IO;
37 using System.Text;
38 using System.Reflection;
39 using System.Diagnostics;
40 using System.Text.RegularExpressions;
41 using System.Threading;
42 using System.Collections.Generic;
43 using System.Globalization;
44
45 namespace Microsoft.CSharp
46 {
47         partial class CSharpCodeGenerator
48         {
49                 private CompilerResults FromFileBatch (CompilerParameters options, string[] fileNames)
50                 {
51                         if (options == null)
52                                 throw new ArgumentNullException (nameof(options));
53
54                         if (fileNames == null)
55                                 throw new ArgumentNullException (nameof(fileNames));
56
57                         CompilerResults results=new CompilerResults(options.TempFiles);
58                         Process mcs=new Process();
59
60                         // FIXME: these lines had better be platform independent.
61                         if (Path.DirectorySeparatorChar == '\\') {
62                                 mcs.StartInfo.FileName = MonoToolsLocator.Mono;
63                                 mcs.StartInfo.Arguments = "\"" + MonoToolsLocator.McsCSharpCompiler + "\" ";
64                         } else {
65                                 mcs.StartInfo.FileName = MonoToolsLocator.McsCSharpCompiler;
66                         }
67
68                         mcs.StartInfo.Arguments += BuildArgs (options, fileNames, _provOptions);
69
70                         var mcsOutMutex = new Mutex ();
71 /*                     
72                         string monoPath = Environment.GetEnvironmentVariable ("MONO_PATH");
73                         if (monoPath != null)
74                                 monoPath = String.Empty;
75
76                         string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
77                         if (privateBinPath != null && privateBinPath.Length > 0)
78                                 monoPath = String.Format ("{0}:{1}", privateBinPath, monoPath);
79
80                         if (monoPath.Length > 0) {
81                                 StringDictionary dict = mcs.StartInfo.EnvironmentVariables;
82                                 if (dict.ContainsKey ("MONO_PATH"))
83                                         dict ["MONO_PATH"] = monoPath;
84                                 else
85                                         dict.Add ("MONO_PATH", monoPath);
86                         }
87 */
88                         /*
89                          * reset MONO_GC_PARAMS - we are invoking compiler possibly with another GC that
90                          * may not handle some of the options causing compilation failure
91                          */
92                         mcs.StartInfo.EnvironmentVariables ["MONO_GC_PARAMS"] = String.Empty;
93
94                         mcs.StartInfo.CreateNoWindow=true;
95                         mcs.StartInfo.UseShellExecute=false;
96                         mcs.StartInfo.RedirectStandardOutput=true;
97                         mcs.StartInfo.RedirectStandardError=true;
98                         mcs.ErrorDataReceived += new DataReceivedEventHandler ((sender, args) => {
99                                 if (args.Data != null) {
100                                         mcsOutMutex.WaitOne ();
101                                         results.Output.Add (args.Data);
102                                         mcsOutMutex.ReleaseMutex ();
103                                 }
104                         });
105
106                         // Use same text decoder as mcs and not user set values in Console
107                         mcs.StartInfo.StandardOutputEncoding =
108                         mcs.StartInfo.StandardErrorEncoding = Encoding.UTF8;
109                         
110                         try {
111                                 mcs.Start();
112                         } catch (Exception e) {
113                                 Win32Exception exc = e as Win32Exception;
114                                 if (exc != null) {
115                                         throw new SystemException (String.Format ("Error running {0}: {1}", mcs.StartInfo.FileName,
116                                                                         Win32Exception.GetErrorMessage (exc.NativeErrorCode)));
117                                 }
118                                 throw;
119                         }
120
121                         try {
122                                 mcs.BeginOutputReadLine ();
123                                 mcs.BeginErrorReadLine ();
124                                 mcs.WaitForExit();
125                                 
126                                 results.NativeCompilerReturnValue = mcs.ExitCode;
127                         } finally {
128                                 mcs.CancelErrorRead ();
129                                 mcs.CancelOutputRead ();
130                                 mcs.Close();
131                         }
132
133                         bool loadIt=true;
134                         foreach (string error_line in results.Output) {
135                                 CompilerError error = CreateErrorFromString (error_line);
136                                 if (error != null) {
137                                         results.Errors.Add (error);
138                                         if (!error.IsWarning)
139                                                 loadIt = false;
140                                 }
141                         }
142                         
143                         if (results.Output.Count > 0) {
144                                 results.Output.Insert (0, mcs.StartInfo.FileName + " " + mcs.StartInfo.Arguments + Environment.NewLine);
145                         }
146
147                         if (loadIt) {
148                                 if (!File.Exists (options.OutputAssembly)) {
149                                         StringBuilder sb = new StringBuilder ();
150                                         foreach (string s in results.Output)
151                                                 sb.Append (s + Environment.NewLine);
152                                         
153                                         throw new Exception ("Compiler failed to produce the assembly. Output: '" + sb.ToString () + "'");
154                                 }
155                                 
156                                 if (options.GenerateInMemory) {
157                                         using (FileStream fs = File.OpenRead(options.OutputAssembly)) {
158                                                 byte[] buffer = new byte[fs.Length];
159                                                 fs.Read(buffer, 0, buffer.Length);
160                                                 results.CompiledAssembly = Assembly.Load(buffer, null);
161                                                 fs.Close();
162                                         }
163                                 } else {
164                                         // Avoid setting CompiledAssembly right now since the output might be a netmodule
165                                         results.PathToAssembly = options.OutputAssembly;
166                                 }
167                         } else {
168                                 results.CompiledAssembly = null;
169                         }
170                         
171                         return results;
172                 }
173
174                 private static string BuildArgs (CompilerParameters options, string[] fileNames, IDictionary<string, string> providerOptions)
175                 {
176                         StringBuilder args=new StringBuilder();
177                         if (options.GenerateExecutable)
178                                 args.Append("/target:exe ");
179                         else
180                                 args.Append("/target:library ");
181
182                         string privateBinPath = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath;
183                         if (privateBinPath != null && privateBinPath.Length > 0)
184                                 args.AppendFormat ("/lib:\"{0}\" ", privateBinPath);
185                         
186                         if (options.Win32Resource != null)
187                                 args.AppendFormat("/win32res:\"{0}\" ",
188                                         options.Win32Resource);
189
190                         if (options.IncludeDebugInformation)
191                                 args.Append("/debug+ /optimize- ");
192                         else
193                                 args.Append("/debug- /optimize+ ");
194
195                         if (options.TreatWarningsAsErrors)
196                                 args.Append("/warnaserror ");
197
198                         if (options.WarningLevel >= 0)
199                                 args.AppendFormat ("/warn:{0} ", options.WarningLevel);
200
201                         if (options.OutputAssembly == null || options.OutputAssembly.Length == 0) {
202                                 string extension = (options.GenerateExecutable ? "exe" : "dll");
203                                 options.OutputAssembly = GetTempFileNameWithExtension (options.TempFiles, extension,
204                                         !options.GenerateInMemory);
205                         }
206                         args.AppendFormat("/out:\"{0}\" ",options.OutputAssembly);
207
208                         foreach (string import in options.ReferencedAssemblies) {
209                                 if (import == null || import.Length == 0)
210                                         continue;
211
212                                 args.AppendFormat("/r:\"{0}\" ",import);
213                         }
214
215                         if (options.CompilerOptions != null) {
216                                 args.Append (options.CompilerOptions);
217                                 args.Append (" ");
218                         }
219
220                         foreach (string embeddedResource in options.EmbeddedResources) {
221                                 args.AppendFormat("/resource:\"{0}\" ", embeddedResource);
222                         }
223
224                         foreach (string linkedResource in options.LinkedResources) {
225                                 args.AppendFormat("/linkresource:\"{0}\" ", linkedResource);
226                         }
227                         
228                         if (providerOptions != null && providerOptions.Count > 0) {
229                                 string langver;
230
231                                 if (!providerOptions.TryGetValue ("CompilerVersion", out langver))
232                                         langver = "3.5";
233
234                                 if (langver.Length >= 1 && langver [0] == 'v')
235                                         langver = langver.Substring (1);
236
237                                 switch (langver) {
238                                         case "2.0":
239                                                 args.Append ("/langversion:ISO-2 ");
240                                                 break;
241
242                                         case "3.5":
243                                                 // current default, omit the switch
244                                                 break;
245                                 }
246                         }
247
248                         args.Append ("/noconfig ");
249
250                         args.Append (" -- ");
251                         foreach (string source in fileNames)
252                                 args.AppendFormat("\"{0}\" ",source);
253                         return args.ToString();
254                 }
255
256                 // Keep in sync with mcs/class/Microsoft.Build.Utilities/Microsoft.Build.Utilities/ToolTask.cs
257                 const string ErrorRegexPattern = @"
258                         ^
259                         (\s*(?<file>[^\(]+)                         # filename (optional)
260                          (\((?<line>\d*)(,(?<column>\d*[\+]*))?\))? # line+column (optional)
261                          :\s+)?
262                         (?<level>\w+)                               # error|warning
263                         \s+
264                         (?<number>[^:]*\d)                          # CS1234
265                         :
266                         \s*
267                         (?<message>.*)$";
268
269                 static readonly Regex RelatedSymbolsRegex = new Regex(
270                         @"
271             \(Location\ of\ the\ symbol\ related\ to\ previous\ (warning|error)\)
272                         ",
273                         RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
274
275                 private static CompilerError CreateErrorFromString(string error_string)
276                 {
277                         if (error_string.StartsWith ("BETA"))
278                                 return null;
279
280                         if (error_string == null || error_string == "")
281                                 return null;
282
283                         CompilerError error=new CompilerError();
284                         Regex reg = new Regex (ErrorRegexPattern, RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnorePatternWhitespace);
285                         Match match=reg.Match(error_string);
286                         if (!match.Success) {
287                                 match = RelatedSymbolsRegex.Match (error_string);
288                                 if (!match.Success) {
289                                         // We had some sort of runtime crash
290                                         error.ErrorText = error_string;
291                                         error.IsWarning = false;
292                                         error.ErrorNumber = "";
293                                         return error;
294                                 } else {
295                                         // This line is a continuation of previous warning of error
296                                         return null;
297                                 }
298                         }
299                         if (String.Empty != match.Result("${file}"))
300                                 error.FileName=match.Result("${file}");
301                         if (String.Empty != match.Result("${line}"))
302                                 error.Line=Int32.Parse(match.Result("${line}"));
303                         if (String.Empty != match.Result("${column}"))
304                                 error.Column=Int32.Parse(match.Result("${column}").Trim('+'));
305
306                         string level = match.Result ("${level}");
307                         if (level == "warning")
308                                 error.IsWarning = true;
309                         else if (level != "error")
310                                 return null; // error CS8028 will confuse the regex.
311
312                         error.ErrorNumber=match.Result("${number}");
313                         error.ErrorText=match.Result("${message}");
314                         return error;
315                 }
316
317                 private static string GetTempFileNameWithExtension (TempFileCollection temp_files, string extension, bool keepFile)
318                 {
319                         return temp_files.AddExtension (extension, keepFile);
320                 }
321         }
322 }