Repository navigation
Expand file tree
/
Copy pathScriptBuilder.cs
More file actions
124 lines (107 loc) · 5.48 KB
/
Copy pathScriptBuilder.cs
File metadata and controls
124 lines (107 loc) · 5.48 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
// 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.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Scripting
{
/// <summary>
/// Represents a runtime execution context for C# scripts.
/// </summary>
internal 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()
{
_assemblyNamePrefix = s_globalAssemblyNamePrefix + "#" + Interlocked.Increment(ref s_engineIdDispenser).ToString();
_assemblyLoader = new InteractiveAssemblyLoader();
}
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;
}
/// <summary>
/// Builds a delegate that will execute just this scripts code.
/// </summary>
public Func<object[], Task<T>> Build<T>(
Script script,
DiagnosticBag diagnostics,
CancellationToken cancellationToken)
{
var compilation = script.GetCompilation();
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.Load(peStream, pdbStream: null);
// TODO: GetEntryPoint currently doesn't work for scripts/submissions.
// See https://github.com/dotnet/roslyn/issues/3719.
// var entryPoint = compilation.GetEntryPoint(cancellationToken);
var entryPointMethod = GetEntryPointRuntimeMethod(emitResult.EntryPointOpt, assembly, cancellationToken);
return entryPointMethod.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);
}
}
}