Repository navigation
Expand file tree
/
Copy pathScriptBuilder.cs
More file actions
171 lines (148 loc) · 7.18 KB
/
Copy pathScriptBuilder.cs
File metadata and controls
171 lines (148 loc) · 7.18 KB
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
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// Represents a runtime execution context for scripts.
/// </summary>
internal sealed class ScriptBuilder
{
/// <summary>
/// Unique prefix for generated assemblies.
/// </summary>
/// <remarks>
/// The full names of uncollectible assemblies generated by this context must be unique,
/// so that we can resolve references among them. Note that CLR can load two different assemblies of the very same
/// identity into the same load context.
///
/// We are using a certain naming scheme for the generated assemblies (a fixed name prefix followed by a number).
/// If we allowed the compiled code to add references that match this exact pattern it might happen that
/// the user supplied reference identity conflicts with the identity we use for our generated assemblies and
/// the AppDomain assembly resolve event won't be able to correctly identify the target assembly.
///
/// To avoid this problem we use a prefix for assemblies we generate that is unlikely to conflict with user specified references.
/// We also check that no user provided references are allowed to be used in the compiled code and report an error ("reserved assembly name").
/// </remarks>
private static readonly string s_globalAssemblyNamePrefix;
private static int s_engineIdDispenser;
private int _submissionIdDispenser = -1;
private readonly string _assemblyNamePrefix;
private readonly InteractiveAssemblyLoader _assemblyLoader;
static ScriptBuilder()
{
s_globalAssemblyNamePrefix = "\u211B*" + Guid.NewGuid().ToString();
}
public ScriptBuilder(InteractiveAssemblyLoader assemblyLoader)
{
Debug.Assert(assemblyLoader != null);
_assemblyNamePrefix = s_globalAssemblyNamePrefix + "#" + Interlocked.Increment(ref s_engineIdDispenser).ToString();
_assemblyLoader = assemblyLoader;
}
public int GenerateSubmissionId(out string assemblyName, out string typeName)
{
int id = Interlocked.Increment(ref _submissionIdDispenser);
string idAsString = id.ToString();
assemblyName = _assemblyNamePrefix + "-" + idAsString;
typeName = "Submission#" + idAsString;
return id;
}
/// <exception cref="CompilationErrorException">Compilation has errors.</exception>
internal Func<object[], Task<T>> CreateExecutor<T>(ScriptCompiler compiler, Compilation compilation, CancellationToken cancellationToken)
{
var diagnostics = DiagnosticBag.GetInstance();
try
{
// get compilation diagnostics first.
diagnostics.AddRange(compilation.GetParseDiagnostics());
ThrowIfAnyCompilationErrors(diagnostics, compiler.DiagnosticFormatter);
diagnostics.Clear();
var executor = Build<T>(compilation, diagnostics, cancellationToken);
// emit can fail due to compilation errors or because there is nothing to emit:
ThrowIfAnyCompilationErrors(diagnostics, compiler.DiagnosticFormatter);
if (executor == null)
{
executor = (s) => Task.FromResult(default(T));
}
return executor;
}
finally
{
diagnostics.Free();
}
}
private static void ThrowIfAnyCompilationErrors(DiagnosticBag diagnostics, DiagnosticFormatter formatter)
{
if (diagnostics.IsEmptyWithoutResolution)
{
return;
}
var filtered = diagnostics.AsEnumerable().Where(d => d.Severity == DiagnosticSeverity.Error).AsImmutable();
if (filtered.IsEmpty)
{
return;
}
throw new CompilationErrorException(
formatter.Format(filtered[0], CultureInfo.CurrentCulture),
filtered);
}
/// <summary>
/// Builds a delegate that will execute just this scripts code.
/// </summary>
private Func<object[], Task<T>> Build<T>(
Compilation compilation,
DiagnosticBag diagnostics,
CancellationToken cancellationToken)
{
var entryPoint = compilation.GetEntryPoint(cancellationToken);
using (var peStream = new MemoryStream())
{
var emitResult = compilation.Emit(
peStream: peStream,
pdbStream: null,
xmlDocumentationStream: null,
win32Resources: null,
manifestResources: null,
options: EmitOptions.Default,
cancellationToken: cancellationToken);
diagnostics.AddRange(emitResult.Diagnostics);
if (!emitResult.Success)
{
return null;
}
// let the loader know where to find assemblies:
foreach (var referencedAssembly in compilation.GetBoundReferenceManager().GetReferencedAssemblies())
{
var path = (referencedAssembly.Key as PortableExecutableReference)?.FilePath;
if (path != null)
{
// TODO: Should the #r resolver return contract metadata and runtime assembly path -
// Contract assembly used in the compiler, RT assembly path here.
_assemblyLoader.RegisterDependency(referencedAssembly.Value.Identity, path);
}
}
peStream.Position = 0;
var assembly = _assemblyLoader.LoadAssemblyFromStream(peStream, pdbStream: null);
var runtimeEntryPoint = GetEntryPointRuntimeMethod(entryPoint, assembly, cancellationToken);
return runtimeEntryPoint.CreateDelegate<Func<object[], Task<T>>>();
}
}
internal static MethodInfo GetEntryPointRuntimeMethod(IMethodSymbol entryPoint, Assembly assembly, CancellationToken cancellationToken)
{
string entryPointTypeName = MetadataHelpers.BuildQualifiedName(entryPoint.ContainingNamespace.MetadataName, entryPoint.ContainingType.MetadataName);
string entryPointMethodName = entryPoint.MetadataName;
var entryPointType = assembly.GetType(entryPointTypeName, throwOnError: true, ignoreCase: false).GetTypeInfo();
return entryPointType.GetDeclaredMethod(entryPointMethodName);
}
}
}