This repository has been archived by the owner on Feb 8, 2018. It is now read-only.
forked from gluck/ikvm
-
Notifications
You must be signed in to change notification settings - Fork 5
/
DynamicClassLoader.cs
405 lines (380 loc) · 12.4 KB
/
DynamicClassLoader.cs
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
/*
Copyright (C) 2002, 2003, 2004, 2005, 2006, 2008 Jeroen Frijters
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jeroen Frijters
jeroen@frijters.net
*/
#if !COMPACT_FRAMEWORK
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
#if IKVM_REF_EMIT
using IKVM.Reflection.Emit;
#else
using System.Reflection.Emit;
#endif
namespace IKVM.Internal
{
[Flags]
enum CodeGenOptions
{
None = 0,
Debug = 1,
NoStackTraceInfo = 2,
StrictFinalFieldSemantics = 4,
NoJNI = 8,
RemoveAsserts = 16,
}
sealed class DynamicClassLoader : TypeWrapperFactory
{
// note that MangleNestedTypeName() assumes that there are less than 16 special characters
private static readonly char[] specialCharacters = { '\\', '+', ',', '[', ']', '*', '&', '\u0000' };
private static readonly string specialCharactersString = new String(specialCharacters);
#if !STATIC_COMPILER
private static List<AssemblyBuilder> saveDebugAssemblies;
#endif // !STATIC_COMPILER
private readonly Dictionary<string, TypeWrapper> dynamicTypes = new Dictionary<string, TypeWrapper>();
private ModuleBuilder moduleBuilder;
#if STATIC_COMPILER
private TypeBuilder proxyHelperContainer;
private List<TypeBuilder> proxyHelpers;
#endif // STATIC_COMPILER
private Dictionary<string, TypeBuilder> unloadables;
private TypeBuilder unloadableContainer;
static DynamicClassLoader()
{
#if !STATIC_COMPILER
// TODO AppDomain.TypeResolve requires ControlAppDomain permission, but if we don't have that,
// we should handle that by disabling dynamic class loading
AppDomain.CurrentDomain.TypeResolve += new ResolveEventHandler(OnTypeResolve);
#endif // !STATIC_COMPILER
}
internal DynamicClassLoader(ModuleBuilder moduleBuilder)
{
this.moduleBuilder = moduleBuilder;
// Ref.Emit doesn't like the "<Module>" name for types
// (since it already defines a pseudo-type named <Module> for global methods and fields)
dynamicTypes.Add("<Module>", null);
}
#if !STATIC_COMPILER
internal static DynamicClassLoader Instance = new DynamicClassLoader(CreateModuleBuilder());
private static Assembly OnTypeResolve(object sender, ResolveEventArgs args)
{
TypeWrapper type;
lock(Instance.dynamicTypes)
{
Instance.dynamicTypes.TryGetValue(args.Name, out type);
}
if(type == null)
{
return null;
}
try
{
type.Finish();
}
catch(RetargetableJavaException x)
{
throw x.ToJava();
}
// NOTE We used to remove the type from the hashtable here, but that creates a race condition if
// another thread also fires the OnTypeResolve event while we're baking the type.
// I really would like to remove the type from the hashtable, but at the moment I don't see
// any way of doing that that wouldn't cause this race condition.
// UPDATE since we now also use the dynamicTypes hashtable to keep track of type names that
// have been used already, we cannot remove the keys.
return type.TypeAsTBD.Assembly;
}
#endif // !STATIC_COMPILER
internal static string EscapeName(string name)
{
// TODO the escaping of special characters is not required on .NET 2.0
// (but it doesn't really hurt that much either, the only overhead is the
// extra InnerClassAttribute to record the real name of the class)
// Note that even though .NET 2.0 automatically escapes the special characters,
// the name that gets passed in ResolveEventArgs.Name of the TypeResolve event
// contains the unescaped type name.
if(name.IndexOfAny(specialCharacters) >= 0)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach(char c in name)
{
if(specialCharactersString.IndexOf(c) >= 0)
{
if(c == 0)
{
// we can't escape the NUL character, so we replace it with a space.
sb.Append(' ');
continue;
}
sb.Append('\\');
}
sb.Append(c);
}
name = sb.ToString();
}
return name;
}
internal override bool ReserveName(string name)
{
lock(dynamicTypes)
{
if(dynamicTypes.ContainsKey(name))
{
return false;
}
dynamicTypes.Add(name, null);
return true;
}
}
private string AllocMangledName(string mangledTypeName)
{
lock(dynamicTypes)
{
mangledTypeName = EscapeName(mangledTypeName);
// FXBUG the CLR (both 1.1 and 2.0) doesn't like type names that end with a single period,
// it loses the trailing period in the name that gets passed in the TypeResolve event.
if(dynamicTypes.ContainsKey(mangledTypeName) || mangledTypeName.EndsWith("."))
{
#if STATIC_COMPILER
Tracer.Warning(Tracer.Compiler, "Class name clash: {0}", mangledTypeName);
#endif
// Java class names cannot contain slashes (since they are converted into periods),
// so we take advantage of that fact to create a unique name.
string baseName = mangledTypeName;
int instanceId = 0;
do
{
mangledTypeName = baseName + "/" + (++instanceId);
} while(dynamicTypes.ContainsKey(mangledTypeName));
}
dynamicTypes.Add(mangledTypeName, null);
}
return mangledTypeName;
}
internal sealed override TypeWrapper DefineClassImpl(Dictionary<string, TypeWrapper> types, ClassFile f, ClassLoaderWrapper classLoader, object protectionDomain)
{
DynamicTypeWrapper type;
#if STATIC_COMPILER
type = new AotTypeWrapper(f, (CompilerClassLoader)classLoader);
#else
type = new DynamicTypeWrapper(f, classLoader);
#endif
// this step can throw a retargettable exception, if the class is incorrect
bool hasclinit;
type.CreateStep1(out hasclinit);
// now we can allocate the mangledTypeName, because the next step cannot fail
string mangledTypeName = AllocMangledName(f.Name);
// This step actually creates the TypeBuilder. It is not allowed to throw any exceptions,
// if an exception does occur, it is due to a programming error in the IKVM or CLR runtime
// and will cause a CriticalFailure and exit the process.
type.CreateStep2NoFail(hasclinit, mangledTypeName);
lock(types)
{
// in very extreme conditions another thread may have beaten us to it
// and loaded (not defined) a class with the same name, in that case
// we'll leak the the Reflection.Emit defined type. Also see the comment
// in ClassLoaderWrapper.RegisterInitiatingLoader().
TypeWrapper race;
types.TryGetValue(f.Name, out race);
if(race == null)
{
lock(dynamicTypes)
{
Debug.Assert(dynamicTypes.ContainsKey(mangledTypeName) && dynamicTypes[mangledTypeName] == null);
dynamicTypes[mangledTypeName] = type;
}
types[f.Name] = type;
#if !STATIC_COMPILER && !FIRST_PASS
java.lang.Class clazz = java.lang.Class.newClass();
#if __MonoCS__
TypeWrapper.SetTypeWrapperHack(ref clazz.typeWrapper, type);
#else
clazz.typeWrapper = type;
#endif
clazz.pd = (java.security.ProtectionDomain)protectionDomain;
type.SetClassObject(clazz);
#endif
}
else
{
throw new LinkageError("duplicate class definition: " + f.Name);
}
}
return type;
}
#if STATIC_COMPILER
internal void DefineProxyHelper(Type type)
{
if(proxyHelperContainer == null)
{
proxyHelperContainer = moduleBuilder.DefineType("__<Proxy>", TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract);
AttributeHelper.HideFromJava(proxyHelperContainer);
AttributeHelper.SetEditorBrowsableNever(proxyHelperContainer);
proxyHelpers = new List<TypeBuilder>();
}
proxyHelpers.Add(proxyHelperContainer.DefineNestedType(MangleNestedTypeName(type.FullName), TypeAttributes.NestedPublic | TypeAttributes.Interface | TypeAttributes.Abstract, null, new Type[] { type }));
}
#endif
internal static string GetProxyHelperName(Type type)
{
return "__<Proxy>+" + MangleNestedTypeName(type.FullName);
}
private static string MangleNestedTypeName(string name)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (char c in name)
{
int index = specialCharactersString.IndexOf(c);
if(c == '.')
{
sb.Append("_");
}
else if(c == '_')
{
sb.Append("^-");
}
else if(index == -1)
{
sb.Append(c);
if(c == '^')
{
sb.Append(c);
}
}
else
{
sb.Append('^').AppendFormat("{0:X1}", index);
}
}
return sb.ToString();
}
internal override Type DefineUnloadable(string name)
{
lock(this)
{
if(unloadables == null)
{
unloadables = new Dictionary<string, TypeBuilder>();
}
TypeBuilder type;
if(unloadables.TryGetValue(name, out type))
{
return type;
}
if(unloadableContainer == null)
{
unloadableContainer = moduleBuilder.DefineType("__<Unloadable>", TypeAttributes.Interface | TypeAttributes.Abstract);
AttributeHelper.HideFromJava(unloadableContainer);
}
type = unloadableContainer.DefineNestedType(MangleNestedTypeName(name), TypeAttributes.NestedPrivate | TypeAttributes.Interface | TypeAttributes.Abstract);
unloadables.Add(name, type);
return type;
}
}
internal void FinishAll()
{
Dictionary<TypeWrapper, TypeWrapper> done = new Dictionary<TypeWrapper, TypeWrapper>();
bool more = true;
while(more)
{
more = false;
List<TypeWrapper> l = new List<TypeWrapper>(dynamicTypes.Values);
foreach(TypeWrapper tw in l)
{
if(tw != null && !done.ContainsKey(tw))
{
more = true;
done.Add(tw, tw);
Tracer.Info(Tracer.Runtime, "Finishing {0}", tw.TypeAsTBD.FullName);
tw.Finish();
}
}
}
if(unloadableContainer != null)
{
unloadableContainer.CreateType();
foreach(TypeBuilder tb in unloadables.Values)
{
tb.CreateType();
}
}
#if STATIC_COMPILER
if(proxyHelperContainer != null)
{
proxyHelperContainer.CreateType();
foreach(TypeBuilder tb in proxyHelpers)
{
tb.CreateType();
}
}
#endif // STATIC_COMPILER
}
#if !STATIC_COMPILER
internal void SaveDebugImage()
{
JVM.FinishingForDebugSave = true;
FinishAll();
AssemblyBuilder asm = ((AssemblyBuilder)moduleBuilder.Assembly);
asm.Save("ikvmdump.dll");
if(saveDebugAssemblies != null)
{
foreach(AssemblyBuilder ab in saveDebugAssemblies)
{
ab.Save(ab.GetName().Name + ".dll");
}
}
}
internal static void RegisterForSaveDebug(AssemblyBuilder ab)
{
if(saveDebugAssemblies == null)
{
saveDebugAssemblies = new List<AssemblyBuilder>();
}
saveDebugAssemblies.Add(ab);
}
#endif
internal sealed override ModuleBuilder ModuleBuilder
{
get
{
return moduleBuilder;
}
}
#if !STATIC_COMPILER
private static ModuleBuilder CreateModuleBuilder()
{
AssemblyName name = new AssemblyName();
if(JVM.IsSaveDebugImage)
{
name.Name = "ikvmdump";
}
else
{
name.Name = "ikvm_dynamic_assembly__" + (uint)Environment.TickCount;
}
DateTime now = DateTime.Now;
name.Version = new Version(now.Year, (now.Month * 100) + now.Day, (now.Hour * 100) + now.Minute, (now.Second * 1000) + now.Millisecond);
AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, JVM.IsSaveDebugImage ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run, null, null, null, null, null, true);
bool debug = System.Diagnostics.Debugger.IsAttached;
CustomAttributeBuilder debugAttr = new CustomAttributeBuilder(typeof(DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new object[] { true, debug });
assemblyBuilder.SetCustomAttribute(debugAttr);
return JVM.IsSaveDebugImage ? assemblyBuilder.DefineDynamicModule("ikvmdump.dll", "ikvmdump.dll", debug) : assemblyBuilder.DefineDynamicModule(name.Name, debug);
}
#endif // !STATIC_COMPILER
}
}
#endif //COMPACT_FRAMEWORK