Welcome to mirror list, hosted at ThFree Co, Russian Federation.

TestCaseCompiler.cs « TestCasesRunner « Mono.Linker.Tests « test - github.com/mono/linker.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 14ac2e85d5b396c885d61472e1f1dfb4f14648bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Mono.Linker.Tests.Extensions;
using NUnit.Framework;
#if NETCOREAPP
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.CSharp;
#endif

namespace Mono.Linker.Tests.TestCasesRunner {
	public class TestCaseCompiler {
		static string _cachedWindowsCscPath = null;
		protected readonly TestCaseMetadaProvider _metadataProvider;
		protected readonly TestCaseSandbox _sandbox;
		protected readonly ILCompiler _ilCompiler;

		public TestCaseCompiler (TestCaseSandbox sandbox, TestCaseMetadaProvider metadataProvider)
			: this(sandbox, metadataProvider, new ILCompiler ())
		{
		}

		public TestCaseCompiler (TestCaseSandbox sandbox, TestCaseMetadaProvider metadataProvider, ILCompiler ilCompiler)
		{
			_ilCompiler = ilCompiler;
			_sandbox = sandbox;
			_metadataProvider = metadataProvider;
		}

		public NPath CompileTestIn (NPath outputDirectory, string outputName, IEnumerable<string> sourceFiles, string[] commonReferences, string[] mainAssemblyReferences, IEnumerable<string> defines, NPath[] resources, string[] additionalArguments)
		{
			var originalCommonReferences = commonReferences.Select (r => r.ToNPath ()).ToArray ();
			var originalDefines = defines?.ToArray () ?? new string [0];

			Prepare (outputDirectory);

			var compiledReferences = CompileBeforeTestCaseAssemblies (outputDirectory, originalCommonReferences, originalDefines).ToArray ();
			var allTestCaseReferences = originalCommonReferences
				.Concat (compiledReferences)
				.Concat (mainAssemblyReferences.Select (r => r.ToNPath ()))
				.ToArray ();

			var options = CreateOptionsForTestCase (
				outputDirectory.Combine (outputName),
				sourceFiles.Select (s => s.ToNPath ()).ToArray (),
				allTestCaseReferences,
				originalDefines,
				resources,
				additionalArguments);
			var testAssembly = CompileAssembly (options);
				

			// The compile after step is used by tests to mess around with the input to the linker.  Generally speaking, it doesn't seem like we would ever want to mess with the
			// expectations assemblies because this would undermine our ability to inspect them for expected results during ResultChecking.  The UnityLinker UnresolvedHandling tests depend on this
			// behavior of skipping the after test compile
			if (outputDirectory != _sandbox.ExpectationsDirectory)
				CompileAfterTestCaseAssemblies (outputDirectory, originalCommonReferences, originalDefines);

			return testAssembly;
		}

		protected virtual void Prepare (NPath outputDirectory)
		{
		}

		protected virtual CompilerOptions CreateOptionsForTestCase (NPath outputPath, NPath[] sourceFiles, NPath[] references, string[] defines, NPath[] resources, string[] additionalArguments)
		{
			return new CompilerOptions
			{
				OutputPath = outputPath,
				SourceFiles = sourceFiles,
				References = references,
				Defines = defines.Concat (_metadataProvider.GetDefines ()).ToArray (),
				Resources = resources,
				AdditionalArguments = additionalArguments,
				CompilerToUse = _metadataProvider.GetCSharpCompilerToUse ()
			};
		}

		protected virtual CompilerOptions CreateOptionsForSupportingAssembly (SetupCompileInfo setupCompileInfo, NPath outputDirectory, NPath[] sourceFiles, NPath[] references, string[] defines, NPath[] resources)
		{
			var allDefines = defines.Concat (setupCompileInfo.Defines ?? new string [0]).ToArray ();
			var allReferences = references.Concat (setupCompileInfo.References?.Select (p => MakeSupportingAssemblyReferencePathAbsolute (outputDirectory, p)) ?? new NPath [0]).ToArray ();
			string[] additionalArguments = string.IsNullOrEmpty (setupCompileInfo.AdditionalArguments) ? null : new[] { setupCompileInfo.AdditionalArguments };
			return new CompilerOptions
			{
				OutputPath = outputDirectory.Combine (setupCompileInfo.OutputName),
				SourceFiles = sourceFiles,
				References = allReferences,
				Defines = allDefines,
				Resources = resources,
				AdditionalArguments = additionalArguments,
				CompilerToUse = setupCompileInfo.CompilerToUse?.ToLower ()
			};
		}

		private IEnumerable<NPath> CompileBeforeTestCaseAssemblies (NPath outputDirectory, NPath[] references, string[] defines)
		{
			foreach (var setupCompileInfo in _metadataProvider.GetSetupCompileAssembliesBefore ())
			{
				var options = CreateOptionsForSupportingAssembly (
					setupCompileInfo,
					outputDirectory,
					CollectSetupBeforeSourcesFiles (setupCompileInfo),
					references,
					defines,
					CollectSetupBeforeResourcesFiles (setupCompileInfo));
				var output = CompileAssembly (options);
				if (setupCompileInfo.AddAsReference)
					yield return output;
			}
		}

		private void CompileAfterTestCaseAssemblies (NPath outputDirectory, NPath[] references, string[] defines)
		{
			foreach (var setupCompileInfo in _metadataProvider.GetSetupCompileAssembliesAfter ())
			{
				var options = CreateOptionsForSupportingAssembly (
					setupCompileInfo,
					outputDirectory,
					CollectSetupAfterSourcesFiles (setupCompileInfo),
					references,
					defines,
					CollectSetupAfterResourcesFiles (setupCompileInfo));
				CompileAssembly (options);
			}
		}

		private NPath[] CollectSetupBeforeSourcesFiles (SetupCompileInfo info)
		{
			return CollectSourceFilesFrom (_sandbox.BeforeReferenceSourceDirectoryFor (info.OutputName));
		}

		private NPath[] CollectSetupAfterSourcesFiles (SetupCompileInfo info)
		{
			return CollectSourceFilesFrom (_sandbox.AfterReferenceSourceDirectoryFor (info.OutputName));
		}
		
		private NPath[] CollectSetupBeforeResourcesFiles (SetupCompileInfo info)
		{
			return _sandbox.BeforeReferenceResourceDirectoryFor (info.OutputName).Files ().ToArray ();
		}

		private NPath[] CollectSetupAfterResourcesFiles (SetupCompileInfo info)
		{
			return  _sandbox.AfterReferenceResourceDirectoryFor (info.OutputName).Files ().ToArray ();
		}

		private static NPath[] CollectSourceFilesFrom (NPath directory)
		{
			var sourceFiles = directory.Files ("*.cs").ToArray ();
			if (sourceFiles.Length > 0)
				return sourceFiles;

			sourceFiles = directory.Files ("*.il").ToArray ();
			if (sourceFiles.Length > 0)
				return sourceFiles;

			throw new FileNotFoundException ($"Didn't find any sources files in {directory}");
		}

		protected static NPath MakeSupportingAssemblyReferencePathAbsolute (NPath outputDirectory, string referenceFileName)
		{
			// Not a good idea to use a full path in a test, but maybe someone is trying to quickly test something locally
			if (Path.IsPathRooted (referenceFileName))
				return referenceFileName.ToNPath ();

			var possiblePath = outputDirectory.Combine (referenceFileName);
			if (possiblePath.FileExists ())
				return possiblePath;

			return referenceFileName.ToNPath();
		}

		protected NPath CompileAssembly (CompilerOptions options)
		{
			if (options.SourceFiles.Any (path => path.ExtensionWithDot == ".cs"))
				return CompileCSharpAssembly (options);

			if (options.SourceFiles.Any (path => path.ExtensionWithDot == ".il"))
				return CompileIlAssembly (options);

			throw new NotSupportedException ($"Unable to compile sources files with extension `{options.SourceFiles.First ().ExtensionWithDot}`");
		}

		protected virtual NPath CompileCSharpAssemblyWithDefaultCompiler (CompilerOptions options)
		{
#if NETCOREAPP
			return CompileCSharpAssemblyWithRoslyn (options);
#else
			return CompileCSharpAssemblyWithCodeDom (options);
#endif
		}

#if NETCOREAPP
		protected virtual NPath CompileCSharpAssemblyWithRoslyn (CompilerOptions options)
		{
			var languageVersion = LanguageVersion.Default;
			var compilationOptions = new CSharpCompilationOptions (
				outputKind: options.OutputPath.FileName.EndsWith (".exe") ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary,
				assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default
			);
			// Default debug info format for the current platform.
			DebugInformationFormat debugType = RuntimeInformation.IsOSPlatform (OSPlatform.Windows) ? DebugInformationFormat.Pdb : DebugInformationFormat.PortablePdb;
			bool emitPdb = false;
			if (options.AdditionalArguments != null) {
				foreach (var option in options.AdditionalArguments) {
					switch (option) {
						case "/unsafe":
							compilationOptions = compilationOptions.WithAllowUnsafe(true);
							break;
						case "/optimize+":
							compilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
							break;
						case "/debug:full":
						case "/debug:pdbonly":
							// Use platform's default debug info. This behavior is the same as csc.
							emitPdb = true;
							break;
						case "/debug:portable":
							emitPdb = true;
							debugType = DebugInformationFormat.PortablePdb;
							break;
						case "/debug:embedded":
							emitPdb = true;
							debugType = DebugInformationFormat.Embedded;
							break;
						case "/langversion:7.3":
							languageVersion = LanguageVersion.CSharp7_3;
							break;
							
					}
				}
			}
			var parseOptions = new CSharpParseOptions (preprocessorSymbols: options.Defines, languageVersion: languageVersion);
			var emitOptions = new EmitOptions (debugInformationFormat: debugType);
			var pdbPath = (!emitPdb || debugType == DebugInformationFormat.Embedded) ? null : options.OutputPath.ChangeExtension (".pdb").ToString ();

			var syntaxTrees = options.SourceFiles.Select (p =>
				CSharpSyntaxTree.ParseText (
					text: p.ReadAllText (),
					options: parseOptions
				)
			);

			var compilation = CSharpCompilation.Create (
				assemblyName: options.OutputPath.FileNameWithoutExtension,
				syntaxTrees: syntaxTrees,
				references: options.References.Select (r => MetadataReference.CreateFromFile (r)),
				options: compilationOptions
			);

			var manifestResources = options.Resources.Select (r => {
				var fullPath = r.ToString ();
				return new ResourceDescription (
					resourceName: Path.GetFileName (fullPath),
					dataProvider: () => new FileStream (fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite),
					isPublic: true
				);
			});

			EmitResult result;
			using (var outputStream = File.Create (options.OutputPath.ToString ()))
			using (var pdbStream = (pdbPath == null ? null : File.Create (pdbPath))) {
				result = compilation.Emit(
					peStream: outputStream,
					pdbStream: pdbStream,
					manifestResources: manifestResources,
					options: emitOptions
				);
			}

			var errors = new StringBuilder ();
			if (result.Success)
				return options.OutputPath;

			foreach (var diagnostic in result.Diagnostics)
				errors.AppendLine (diagnostic.ToString ());
			throw new Exception ("Roslyn compilation errors: " + errors);
		}
#endif

		protected virtual NPath CompileCSharpAssemblyWithCodeDom (CompilerOptions options)
		{
			var compilerOptions = CreateCodeDomCompilerOptions (options);
			var provider = CodeDomProvider.CreateProvider ("C#");
			var result = provider.CompileAssemblyFromFile (compilerOptions, options.SourceFiles.Select (p => p.ToString ()).ToArray ());
			if (!result.Errors.HasErrors)
				return compilerOptions.OutputAssembly.ToNPath ();

			var errors = new StringBuilder ();
			foreach (var error in result.Errors)
				errors.AppendLine (error.ToString ());
			throw new Exception ("Compilation errors: " + errors);
		}

		protected virtual NPath CompileCSharpAssemblyWithCsc (CompilerOptions options)
		{
#if NETCOREAPP
			return CompileCSharpAssemblyWithRoslyn (options);
#else
			return CompileCSharpAssemblyWithExternalCompiler (LocateCscExecutable (), options);
#endif
		}

		protected virtual NPath CompileCSharpAssemblyWithMcs(CompilerOptions options)
		{
			if (Environment.OSVersion.Platform == PlatformID.Win32NT)
				CompileCSharpAssemblyWithExternalCompiler (LocateMcsExecutable (), options);

			return CompileCSharpAssemblyWithDefaultCompiler (options);
		}

		protected NPath CompileCSharpAssemblyWithExternalCompiler (string executable, CompilerOptions options)
		{
			var capturedOutput = new List<string> ();
			var process = new Process ();
			process.StartInfo.FileName = executable;
			process.StartInfo.Arguments = OptionsToCompilerCommandLineArguments (options);
			process.StartInfo.UseShellExecute = false;
			process.StartInfo.CreateNoWindow = true;
			process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
			process.StartInfo.RedirectStandardOutput = true;
			process.OutputDataReceived += (sender, args) => capturedOutput.Add (args.Data);
			process.Start ();
			process.BeginOutputReadLine ();
			process.WaitForExit ();

			if (process.ExitCode != 0)
				Assert.Fail ($"Failed to compile assembly with csc: {options.OutputPath}\n{capturedOutput.Aggregate ((buff, s) => buff + Environment.NewLine + s)}");

			return options.OutputPath;
		}

		static string LocateCscExecutable ()
		{
			if (Environment.OSVersion.Platform != PlatformID.Win32NT)
				return "csc";

			if (_cachedWindowsCscPath != null)
				return _cachedWindowsCscPath;

			var capturedOutput = new List<string> ();
			var process = new Process ();

			var vswherePath = Environment.ExpandEnvironmentVariables ("%ProgramFiles(x86)%\\Microsoft Visual Studio\\Installer\\vswhere.exe");
			if (!File.Exists (vswherePath))
				Assert.Fail ($"Unable to locate csc.exe on windows because vshwere.exe was not found at {vswherePath}");

			process.StartInfo.FileName = vswherePath;
			process.StartInfo.Arguments = "-latest -products * -requires Microsoft.Component.MSBuild -property installationPath";
			process.StartInfo.UseShellExecute = false;
			process.StartInfo.CreateNoWindow = true;
			process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
			process.StartInfo.RedirectStandardOutput = true;
			process.OutputDataReceived += (sender, args) => capturedOutput.Add (args.Data);
			process.Start ();
			process.BeginOutputReadLine ();
			process.WaitForExit ();

			if (process.ExitCode != 0)
				Assert.Fail ($"vswhere.exe failed with :\n{capturedOutput.Aggregate ((buff, s) => buff + Environment.NewLine + s)}");

			if (capturedOutput.Count == 0 || string.IsNullOrEmpty (capturedOutput [0]))
				Assert.Fail ("vswhere.exe was unable to locate an install directory");

			var installPath = capturedOutput [0].Trim ().ToNPath ();

			if (!installPath.Exists ())
				Assert.Fail ($"No install found at {installPath}");

			// Do a search for the roslyn directory for a little bit of furture proofing since it normally lives under
			// a versioned msbuild directory
			foreach (var roslynDirectory in installPath.Directories ("Roslyn", true)) {
				var possibleCscPath = roslynDirectory.Combine ("csc.exe");
				if (possibleCscPath.Exists ()) {
					_cachedWindowsCscPath = possibleCscPath.ToString ();
					return _cachedWindowsCscPath;
				}
			}

			Assert.Fail ("Unable to locate a roslyn csc.exe");
			return null;
		}

		static string LocateMcsExecutable ()
		{
			if (Environment.OSVersion.Platform == PlatformID.Win32NT)
				Assert.Ignore ("We don't have a universal way of locating mcs on Windows");

			return "mcs";
		}

		protected string OptionsToCompilerCommandLineArguments (CompilerOptions options)
		{
			var builder = new StringBuilder ();
			builder.Append ($"/out:{options.OutputPath}");
			var target = options.OutputPath.ExtensionWithDot == ".exe" ? "exe" : "library";
			builder.Append ($" /target:{target}");
			if (options.Defines != null && options.Defines.Length > 0)
				builder.Append (options.Defines.Aggregate (string.Empty, (buff, arg) => $"{buff} /define:{arg}"));

			builder.Append (options.References.Aggregate (string.Empty, (buff, arg) => $"{buff} /r:{arg}"));

			if (options.Resources != null && options.Resources.Length > 0)
				builder.Append (options.Resources.Aggregate (string.Empty, (buff, arg) => $"{buff} /res:{arg}"));

			if (options.AdditionalArguments != null && options.AdditionalArguments.Length > 0)
				builder.Append (options.AdditionalArguments.Aggregate (string.Empty, (buff, arg) => $"{buff} {arg}"));

			builder.Append (options.SourceFiles.Aggregate (string.Empty, (buff, arg) => $"{buff} {arg}"));

			return builder.ToString ();
		}

		protected NPath CompileCSharpAssembly (CompilerOptions options)
		{
			if (string.IsNullOrEmpty (options.CompilerToUse))
				return CompileCSharpAssemblyWithDefaultCompiler (options);

			if (options.CompilerToUse == "csc")
				return CompileCSharpAssemblyWithCsc (options);

			if (options.CompilerToUse == "mcs")
				return CompileCSharpAssemblyWithMcs (options);

			throw new ArgumentException ($"Invalid compiler value `{options.CompilerToUse}`");
		}

		protected NPath CompileIlAssembly (CompilerOptions options)
		{
			return _ilCompiler.Compile (options);
		}

		private CompilerParameters CreateCodeDomCompilerOptions (CompilerOptions options)
		{
			var compilerParameters = new CompilerParameters
			{
				OutputAssembly = options.OutputPath.ToString (),
				GenerateExecutable = options.OutputPath.FileName.EndsWith (".exe")
			};

			compilerParameters.CompilerOptions = options.Defines?.Aggregate (string.Empty, (buff, arg) => $"{buff} /define:{arg}");

			compilerParameters.ReferencedAssemblies.AddRange (options.References.Select (r => r.ToString ()).ToArray ());

			if (options.Resources != null)
				compilerParameters.EmbeddedResources.AddRange (options.Resources.Select (r => r.ToString ()).ToArray ());

			if (options.AdditionalArguments != null) {
				var combinedValues = options.AdditionalArguments.Aggregate (string.Empty, (buff, arg) => $"{buff} {arg}");
				compilerParameters.CompilerOptions = $"{compilerParameters.CompilerOptions} {combinedValues}";
			}

			return compilerParameters;
		}
	}
}