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
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
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
{
protected readonly TestCaseCompilationMetadataProvider _metadataProvider;
protected readonly TestCaseSandbox _sandbox;
protected readonly ILCompiler _ilCompiler;
public TestCaseCompiler (TestCaseSandbox sandbox, TestCaseCompilationMetadataProvider metadataProvider)
: this (sandbox, metadataProvider, new ILCompiler ())
{
}
public TestCaseCompiler (TestCaseSandbox sandbox, TestCaseCompilationMetadataProvider 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 () ?? Array.Empty<string> ();
Prepare (outputDirectory);
var removeFromLinkerInputAssemblies = new List<NPath> ();
var compiledReferences = CompileBeforeTestCaseAssemblies (outputDirectory, originalCommonReferences, originalDefines, removeFromLinkerInputAssemblies).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, removeFromLinkerInputAssemblies);
foreach (var assemblyToRemove in removeFromLinkerInputAssemblies)
assemblyToRemove.DeleteIfExists ();
}
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 ?? Array.Empty<string> ()).ToArray ();
var allReferences = references.Concat (setupCompileInfo.References?.Select (p => MakeSupportingAssemblyReferencePathAbsolute (outputDirectory, p)) ?? Array.Empty<NPath> ()).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, IList<NPath> removeFromLinkerInputAssemblies)
{
foreach (var setupCompileInfo in _metadataProvider.GetSetupCompileAssembliesBefore ()) {
NPath outputFolder;
if (setupCompileInfo.OutputSubFolder == null) {
outputFolder = outputDirectory;
} else {
outputFolder = outputDirectory.Combine (setupCompileInfo.OutputSubFolder);
Directory.CreateDirectory (outputFolder.ToString ());
}
var options = CreateOptionsForSupportingAssembly (
setupCompileInfo,
outputFolder,
CollectSetupBeforeSourcesFiles (setupCompileInfo),
references,
defines,
CollectSetupBeforeResourcesFiles (setupCompileInfo));
var output = CompileAssembly (options);
if (setupCompileInfo.RemoveFromLinkerInput)
removeFromLinkerInputAssemblies.Add (output);
if (setupCompileInfo.AddAsReference)
yield return output;
}
}
private void CompileAfterTestCaseAssemblies (NPath outputDirectory, NPath[] references, string[] defines, IList<NPath> removeFromLinkerInputAssemblies)
{
foreach (var setupCompileInfo in _metadataProvider.GetSetupCompileAssembliesAfter ()) {
var options = CreateOptionsForSupportingAssembly (
setupCompileInfo,
outputDirectory,
CollectSetupAfterSourcesFiles (setupCompileInfo),
references,
defines,
CollectSetupAfterResourcesFiles (setupCompileInfo));
var output = CompileAssembly (options);
if (setupCompileInfo.RemoveFromLinkerInput)
removeFromLinkerInputAssemblies.Add (output);
}
}
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 ();
#if NETCOREAPP
if (referenceFileName.StartsWith ("System.", StringComparison.Ordinal) ||
referenceFileName.StartsWith ("Mono.", StringComparison.Ordinal) ||
referenceFileName.StartsWith ("Microsoft.", StringComparison.Ordinal) ||
referenceFileName == "netstandard.dll") {
var frameworkDir = Path.GetFullPath (Path.GetDirectoryName (typeof (object).Assembly.Location));
var filePath = Path.Combine (frameworkDir, referenceFileName);
if (File.Exists (filePath))
return filePath.ToNPath ();
}
#endif
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 CompileCSharpAssemblyWithCsc (options);
#endif
}
#if NETCOREAPP
protected virtual NPath CompileCSharpAssemblyWithRoslyn (CompilerOptions options)
{
var languageVersion = LanguageVersion.Preview;
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 CompileCSharpAssemblyWithCsc (CompilerOptions options)
{
#if NETCOREAPP
return CompileCSharpAssemblyWithRoslyn (options);
#else
return CompileCSharpAssemblyWithExternalCompiler (LocateCscExecutable (), options, "/shared ");
#endif
}
protected virtual NPath CompileCSharpAssemblyWithMcs (CompilerOptions options)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
CompileCSharpAssemblyWithExternalCompiler (LocateMcsExecutable (), options, string.Empty);
return CompileCSharpAssemblyWithDefaultCompiler (options);
}
protected static NPath CompileCSharpAssemblyWithExternalCompiler (string executable, CompilerOptions options, string compilerSpecificArguments)
{
var capturedOutput = new List<string> ();
var process = new Process ();
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = OptionsToCompilerCommandLineArguments (options, compilerSpecificArguments);
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 LocateMcsExecutable ()
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
Assert.Ignore ("We don't have a universal way of locating mcs on Windows");
return "mcs";
}
protected static string OptionsToCompilerCommandLineArguments (CompilerOptions options, string compilerSpecificArguments)
{
var builder = new StringBuilder ();
if (!string.IsNullOrEmpty (compilerSpecificArguments))
builder.Append (compilerSpecificArguments);
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);
}
}
}
|