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
/
CompilerClassLoader.cs
2836 lines (2677 loc) · 90.2 KB
/
CompilerClassLoader.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
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 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
*/
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.IO;
using System.Collections;
using System.Xml;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Text;
using System.Threading;
using IKVM.Attributes;
using IKVM.Runtime;
using ILGenerator = IKVM.Internal.CountingILGenerator;
using Label = IKVM.Internal.CountingLabel;
using System.Security.Permissions;
using System.Security;
namespace IKVM.Internal
{
class CompilerClassLoader : ClassLoaderWrapper
{
private Hashtable classes;
private Hashtable remapped = new Hashtable();
private string assemblyName;
private string assemblyFile;
private string assemblyDir;
private string keyfilename;
private string keycontainer;
private string version;
private bool targetIsModule;
private AssemblyBuilder assemblyBuilder;
private IKVM.Internal.MapXml.Attribute[] assemblyAttributes;
private CompilerOptions options;
private AssemblyClassLoader[] referencedAssemblies;
private Hashtable nameMappings = new Hashtable();
private Hashtable packages = new Hashtable();
private Hashtable ghosts;
private TypeWrapper[] mappedExceptions;
private bool[] mappedExceptionsAllSubClasses;
private Hashtable mapxml;
private Hashtable baseClasses;
internal CompilerClassLoader(AssemblyClassLoader[] referencedAssemblies, CompilerOptions options, string path, string keyfilename, string keycontainer, string version, bool targetIsModule, string assemblyName, Hashtable classes)
: base(options.codegenoptions, null)
{
this.referencedAssemblies = referencedAssemblies;
this.options = options;
this.classes = classes;
this.assemblyName = assemblyName;
FileInfo assemblyPath = new FileInfo(path);
this.assemblyFile = assemblyPath.Name;
this.assemblyDir = assemblyPath.DirectoryName;
this.targetIsModule = targetIsModule;
this.version = version;
this.keyfilename = keyfilename;
this.keycontainer = keycontainer;
Tracer.Info(Tracer.Compiler, "Instantiate CompilerClassLoader for {0}", assemblyName);
}
internal void AddNameMapping(string javaName, string typeName)
{
nameMappings.Add(javaName, typeName);
}
internal void AddReference(AssemblyClassLoader acl)
{
AssemblyClassLoader[] temp = new AssemblyClassLoader[referencedAssemblies.Length + 1];
Array.Copy(referencedAssemblies, 0, temp, 0, referencedAssemblies.Length);
temp[temp.Length - 1] = acl;
referencedAssemblies = temp;
}
internal override string SourcePath
{
get
{
return options.sourcepath;
}
}
internal ModuleBuilder CreateModuleBuilder()
{
AssemblyName name = new AssemblyName();
name.Name = assemblyName;
if(keyfilename != null)
{
using(FileStream stream = File.OpenRead(keyfilename))
{
name.KeyPair = new StrongNameKeyPair(stream);
}
}
if(keycontainer != null)
{
name.KeyPair = new StrongNameKeyPair(keycontainer);
}
name.Version = new Version(version);
#if WHIDBEY
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.ReflectionOnly, assemblyDir);
#else
assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Save, assemblyDir);
#endif
ModuleBuilder moduleBuilder;
moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName, assemblyFile, this.EmitDebugInfo);
if(this.EmitStackTraceInfo)
{
AttributeHelper.SetSourceFile(moduleBuilder, null);
}
if(this.EmitDebugInfo || this.EmitStackTraceInfo)
{
CustomAttributeBuilder debugAttr = new CustomAttributeBuilder(typeof(DebuggableAttribute).GetConstructor(new Type[] { typeof(bool), typeof(bool) }), new object[] { true, this.EmitDebugInfo });
assemblyBuilder.SetCustomAttribute(debugAttr);
}
return moduleBuilder;
}
protected override TypeWrapper LoadClassImpl(string name, bool throwClassNotFoundException)
{
foreach(AssemblyClassLoader acl in referencedAssemblies)
{
TypeWrapper tw = acl.DoLoad(name);
if(tw != null)
{
return tw;
}
}
return GetTypeWrapperCompilerHook(name);
}
private TypeWrapper GetTypeWrapperCompilerHook(string name)
{
TypeWrapper type = null;
if(type == null)
{
type = (TypeWrapper)remapped[name];
if(type != null)
{
return type;
}
byte[] classdef = (byte[])classes[name];
if(classdef != null)
{
classes.Remove(name);
ClassFile f;
try
{
ClassFileParseOptions cfp = ClassFileParseOptions.LocalVariableTable;
if(this.EmitStackTraceInfo)
{
cfp |= ClassFileParseOptions.LineNumberTable;
}
f = new ClassFile(classdef, 0, classdef.Length, name, cfp);
}
catch(ClassFormatError x)
{
StaticCompiler.IssueMessage(Message.ClassFormatError, name, x.Message);
return null;
}
if(options.removeUnusedFields)
{
f.RemoveUnusedFields();
}
if(f.IsPublic && options.privatePackages != null)
{
foreach(string p in options.privatePackages)
{
if(f.Name.StartsWith(p))
{
f.SetInternal();
break;
}
}
}
if(!f.IsInterface
&& !f.IsAbstract
&& !f.IsPublic
&& !f.IsFinal
&& !baseClasses.ContainsKey(f.Name)
&& !options.targetIsModule)
{
f.SetEffectivelyFinal();
}
try
{
type = DefineClass(f, null);
}
catch (ClassFormatError x)
{
StaticCompiler.IssueMessage(Message.ClassFormatError, name, x.Message);
return null;
}
catch (IllegalAccessError x)
{
StaticCompiler.IssueMessage(Message.IllegalAccessError, name, x.Message);
return null;
}
catch (VerifyError x)
{
StaticCompiler.IssueMessage(Message.VerificationError, name, x.Message);
return null;
}
catch (NoClassDefFoundError x)
{
StaticCompiler.IssueMessage(Message.NoClassDefFoundError, name, x.Message);
return null;
}
catch (RetargetableJavaException x)
{
StaticCompiler.IssueMessage(Message.GenericUnableToCompileError, name, x.GetType().Name, x.Message);
return null;
}
}
}
return type;
}
internal override Type GetType(string name)
{
foreach(AssemblyClassLoader loader in referencedAssemblies)
{
Type type = loader.GetType(name);
if(type != null)
{
return type;
}
}
return null;
}
internal void SetMain(MethodInfo m, PEFileKinds target, Hashtable props, bool noglobbing, Type apartmentAttributeType)
{
Type[] args = Type.EmptyTypes;
if(noglobbing)
{
args = new Type[] { typeof(string[]) };
}
MethodBuilder mainStub = this.GetTypeWrapperFactory().ModuleBuilder.DefineGlobalMethod("main", MethodAttributes.Public | MethodAttributes.Static, typeof(int), args);
if(apartmentAttributeType != null)
{
mainStub.SetCustomAttribute(new CustomAttributeBuilder(apartmentAttributeType.GetConstructor(Type.EmptyTypes), new object[0]));
}
ILGenerator ilgen = mainStub.GetILGenerator();
LocalBuilder rc = ilgen.DeclareLocal(typeof(int));
TypeWrapper startupType = LoadClassByDottedName("ikvm.runtime.Startup");
if(props.Count > 0)
{
ilgen.Emit(OpCodes.Newobj, typeof(Hashtable).GetConstructor(Type.EmptyTypes));
foreach(DictionaryEntry de in props)
{
ilgen.Emit(OpCodes.Dup);
ilgen.Emit(OpCodes.Ldstr, (string)de.Key);
ilgen.Emit(OpCodes.Ldstr, (string)de.Value);
ilgen.Emit(OpCodes.Callvirt, typeof(Hashtable).GetMethod("Add"));
}
startupType.GetMethodWrapper("setProperties", "(Lcli.System.Collections.Hashtable;)V", false).EmitCall(ilgen);
}
ilgen.BeginExceptionBlock();
startupType.GetMethodWrapper("enterMainThread", "()V", false).EmitCall(ilgen);
if(noglobbing)
{
ilgen.Emit(OpCodes.Ldarg_0);
}
else
{
startupType.GetMethodWrapper("glob", "()[Ljava.lang.String;", false).EmitCall(ilgen);
}
ilgen.Emit(OpCodes.Call, m);
ilgen.BeginCatchBlock(typeof(Exception));
LoadClassByDottedName("ikvm.runtime.Util").GetMethodWrapper("mapException", "(Ljava.lang.Throwable;)Ljava.lang.Throwable;", false).EmitCall(ilgen);
LocalBuilder exceptionLocal = ilgen.DeclareLocal(typeof(Exception));
ilgen.Emit(OpCodes.Stloc, exceptionLocal);
TypeWrapper threadTypeWrapper = ClassLoaderWrapper.LoadClassCritical("java.lang.Thread");
LocalBuilder threadLocal = ilgen.DeclareLocal(threadTypeWrapper.TypeAsLocalOrStackType);
threadTypeWrapper.GetMethodWrapper("currentThread", "()Ljava.lang.Thread;", false).EmitCall(ilgen);
ilgen.Emit(OpCodes.Stloc, threadLocal);
ilgen.Emit(OpCodes.Ldloc, threadLocal);
threadTypeWrapper.GetMethodWrapper("getThreadGroup", "()Ljava.lang.ThreadGroup;", false).EmitCallvirt(ilgen);
ilgen.Emit(OpCodes.Ldloc, threadLocal);
ilgen.Emit(OpCodes.Ldloc, exceptionLocal);
ClassLoaderWrapper.LoadClassCritical("java.lang.ThreadGroup").GetMethodWrapper("uncaughtException", "(Ljava.lang.Thread;Ljava.lang.Throwable;)V", false).EmitCallvirt(ilgen);
ilgen.Emit(OpCodes.Ldc_I4_1);
ilgen.Emit(OpCodes.Stloc, rc);
ilgen.BeginFinallyBlock();
startupType.GetMethodWrapper("exitMainThread", "()V", false).EmitCall(ilgen);
ilgen.EndExceptionBlock();
ilgen.Emit(OpCodes.Ldloc, rc);
ilgen.Emit(OpCodes.Ret);
assemblyBuilder.SetEntryPoint(mainStub, target);
}
internal void Save()
{
Tracer.Info(Tracer.Compiler, "CompilerClassLoader.Save...");
((DynamicClassLoader)this.GetTypeWrapperFactory()).FinishAll();
ModuleBuilder mb = GetTypeWrapperFactory().ModuleBuilder;
// HACK force all referenced assemblies to end up as references in the assembly
// (even if they are otherwise unused), to make sure that the assembly class loader
// delegates to them at runtime.
for(int i = 0;i < referencedAssemblies.Length; i++)
{
Type[] types = referencedAssemblies[i].Assembly.GetExportedTypes();
if(types.Length > 0)
{
mb.GetTypeToken(types[0]);
}
}
mb.CreateGlobalFunctions();
// add a class.map resource, if needed.
if(nameMappings.Count > 0)
{
string[] list = new string[nameMappings.Count * 2];
int i = 0;
foreach(DictionaryEntry de in nameMappings)
{
list[i++] = (string)de.Key;
list[i++] = (string)de.Value;
}
CustomAttributeBuilder cab = new CustomAttributeBuilder(JVM.LoadType(typeof(JavaModuleAttribute)).GetConstructor(new Type[] { typeof(string[]) }), new object[] { list });
mb.SetCustomAttribute(cab);
}
else
{
CustomAttributeBuilder cab = new CustomAttributeBuilder(JVM.LoadType(typeof(JavaModuleAttribute)).GetConstructor(Type.EmptyTypes), new object[0]);
mb.SetCustomAttribute(cab);
}
// add a package list
if(true)
{
string[] list = new string[packages.Count];
packages.Keys.CopyTo(list, 0);
mb.SetCustomAttribute(new CustomAttributeBuilder(JVM.LoadType(typeof(PackageListAttribute)).GetConstructor(new Type[] { typeof(string[]) }), new object[] { list }));
}
if(targetIsModule)
{
Tracer.Info(Tracer.Compiler, "CompilerClassLoader saving temp.$$$ in {0}", assemblyDir);
string manifestAssembly = "temp.$$$";
assemblyBuilder.Save(manifestAssembly);
File.Delete(assemblyDir + manifestAssembly);
}
else
{
Tracer.Info(Tracer.Compiler, "CompilerClassLoader saving {0} in {1}", assemblyFile, assemblyDir);
assemblyBuilder.Save(assemblyFile);
}
}
internal void AddResources(Hashtable resources, bool compressedResources)
{
Tracer.Info(Tracer.Compiler, "CompilerClassLoader adding resources...");
ModuleBuilder moduleBuilder = this.GetTypeWrapperFactory().ModuleBuilder;
foreach(DictionaryEntry d in resources)
{
byte[] buf = (byte[])d.Value;
if(true)
{
string name = JVM.MangleResourceName((string)d.Key);
#if WHIDBEY
MemoryStream mem = new MemoryStream();
if(compressedResources)
{
mem.WriteByte(1);
System.IO.Compression.DeflateStream def = new System.IO.Compression.DeflateStream(mem, System.IO.Compression.CompressionMode.Compress, true);
def.Write(buf, 0, buf.Length);
def.Close();
}
else
{
mem.WriteByte(0);
mem.Write(buf, 0, buf.Length);
}
mem.Position = 0;
moduleBuilder.DefineManifestResource(name, mem, ResourceAttributes.Public);
#else
if(compressedResources)
{
MemoryStream mem = new MemoryStream();
LZOutputStream lz = new LZOutputStream(mem);
lz.Write(buf, 0, buf.Length);
lz.Flush();
buf = mem.ToArray();
}
IResourceWriter writer = moduleBuilder.DefineResource(name, "");
writer.AddResource(compressedResources ? "lz" : "ikvm", buf);
#endif
}
}
}
private static MethodAttributes MapMethodAccessModifiers(IKVM.Internal.MapXml.MapModifiers mod)
{
const IKVM.Internal.MapXml.MapModifiers access = IKVM.Internal.MapXml.MapModifiers.Public | IKVM.Internal.MapXml.MapModifiers.Protected | IKVM.Internal.MapXml.MapModifiers.Private;
switch(mod & access)
{
case IKVM.Internal.MapXml.MapModifiers.Public:
return MethodAttributes.Public;
case IKVM.Internal.MapXml.MapModifiers.Protected:
return MethodAttributes.FamORAssem;
case IKVM.Internal.MapXml.MapModifiers.Private:
return MethodAttributes.Private;
default:
return MethodAttributes.Assembly;
}
}
private static FieldAttributes MapFieldAccessModifiers(IKVM.Internal.MapXml.MapModifiers mod)
{
const IKVM.Internal.MapXml.MapModifiers access = IKVM.Internal.MapXml.MapModifiers.Public | IKVM.Internal.MapXml.MapModifiers.Protected | IKVM.Internal.MapXml.MapModifiers.Private;
switch(mod & access)
{
case IKVM.Internal.MapXml.MapModifiers.Public:
return FieldAttributes.Public;
case IKVM.Internal.MapXml.MapModifiers.Protected:
return FieldAttributes.FamORAssem;
case IKVM.Internal.MapXml.MapModifiers.Private:
return FieldAttributes.Private;
default:
return FieldAttributes.Assembly;
}
}
private class RemapperTypeWrapper : TypeWrapper
{
private CompilerClassLoader classLoader;
private TypeBuilder typeBuilder;
private TypeBuilder helperTypeBuilder;
private Type shadowType;
private IKVM.Internal.MapXml.Class classDef;
private TypeWrapper[] interfaceWrappers;
internal override ClassLoaderWrapper GetClassLoader()
{
return classLoader;
}
internal override bool IsRemapped
{
get
{
return true;
}
}
private static TypeWrapper GetBaseWrapper(IKVM.Internal.MapXml.Class c)
{
if((c.Modifiers & IKVM.Internal.MapXml.MapModifiers.Interface) != 0)
{
return null;
}
if(c.Name == "java.lang.Object")
{
return null;
}
return CoreClasses.java.lang.Object.Wrapper;
}
internal RemapperTypeWrapper(CompilerClassLoader classLoader, IKVM.Internal.MapXml.Class c, IKVM.Internal.MapXml.Root map)
: base((Modifiers)c.Modifiers, c.Name, GetBaseWrapper(c))
{
this.classLoader = classLoader;
classDef = c;
bool baseIsSealed = false;
shadowType = Type.GetType(c.Shadows, true);
classLoader.SetRemappedType(shadowType, this);
Type baseType = shadowType;
Type baseInterface = null;
if(baseType.IsInterface)
{
baseInterface = baseType;
}
TypeAttributes attrs = TypeAttributes.Public;
if((c.Modifiers & IKVM.Internal.MapXml.MapModifiers.Interface) == 0)
{
attrs |= TypeAttributes.Class;
if(baseType.IsSealed)
{
baseIsSealed = true;
// FXBUG .NET framework bug
// ideally we would make the type sealed and abstract,
// but Reflection.Emit incorrectly prohibits that
// (the ECMA spec explicitly mentions this is valid)
// attrs |= TypeAttributes.Abstract | TypeAttributes.Sealed;
attrs |= TypeAttributes.Abstract;
}
}
else
{
attrs |= TypeAttributes.Interface | TypeAttributes.Abstract;
baseType = null;
}
if((c.Modifiers & IKVM.Internal.MapXml.MapModifiers.Abstract) != 0)
{
attrs |= TypeAttributes.Abstract;
}
string name = c.Name.Replace('/', '.');
typeBuilder = classLoader.GetTypeWrapperFactory().ModuleBuilder.DefineType(name, attrs, baseIsSealed ? typeof(object) : baseType);
if(c.Attributes != null)
{
foreach(IKVM.Internal.MapXml.Attribute custattr in c.Attributes)
{
AttributeHelper.SetCustomAttribute(typeBuilder, custattr);
}
}
if(baseInterface != null)
{
typeBuilder.AddInterfaceImplementation(baseInterface);
}
if(classLoader.EmitStackTraceInfo)
{
AttributeHelper.SetSourceFile(typeBuilder, IKVM.Internal.MapXml.Root.filename);
}
if(baseIsSealed)
{
AttributeHelper.SetModifiers(typeBuilder, (Modifiers)c.Modifiers, false);
}
if(c.scope == IKVM.Internal.MapXml.Scope.Public)
{
// FXBUG we would like to emit an attribute with a Type argument here, but that doesn't work because
// of a bug in SetCustomAttribute that causes type arguments to be serialized incorrectly (if the type
// is in the same assembly). Normally we use AttributeHelper.FreezeDry to get around this, but that doesn't
// work in this case (no attribute is emitted at all). So we work around by emitting a string instead
AttributeHelper.SetRemappedClass(classLoader.assemblyBuilder, name, shadowType);
AttributeHelper.SetRemappedType(typeBuilder, shadowType);
}
// HACK because of the above FXBUG that prevents us from making the type both abstract and sealed,
// we need to emit a private constructor (otherwise reflection will automatically generate a public
// default constructor, another lame feature)
if(baseIsSealed)
{
ConstructorBuilder cb = typeBuilder.DefineConstructor(MethodAttributes.Private, CallingConventions.Standard, Type.EmptyTypes);
ILGenerator ilgen = cb.GetILGenerator();
// lazyman's way to create a type-safe bogus constructor
ilgen.Emit(OpCodes.Ldnull);
ilgen.Emit(OpCodes.Throw);
}
ArrayList methods = new ArrayList();
if(c.Constructors != null)
{
foreach(IKVM.Internal.MapXml.Constructor m in c.Constructors)
{
methods.Add(new RemappedConstructorWrapper(this, m));
}
}
if(c.Methods != null)
{
foreach(IKVM.Internal.MapXml.Method m in c.Methods)
{
methods.Add(new RemappedMethodWrapper(this, m, map, false));
}
}
// add methods from our super classes (e.g. Throwable should have Object's methods)
if(!this.IsFinal && !this.IsInterface && this.BaseTypeWrapper != null)
{
foreach(MethodWrapper mw in BaseTypeWrapper.GetMethods())
{
RemappedMethodWrapper rmw = mw as RemappedMethodWrapper;
if(rmw != null && (rmw.IsPublic || rmw.IsProtected))
{
if(!FindMethod(methods, rmw.Name, rmw.Signature))
{
methods.Add(new RemappedMethodWrapper(this, rmw.XmlMethod, map, true));
}
}
}
}
SetMethods((MethodWrapper[])methods.ToArray(typeof(MethodWrapper)));
}
private static bool FindMethod(ArrayList methods, string name, string sig)
{
foreach(MethodWrapper mw in methods)
{
if(mw.Name == name && mw.Signature == sig)
{
return true;
}
}
return false;
}
abstract class RemappedMethodBaseWrapper : MethodWrapper
{
internal RemappedMethodBaseWrapper(RemapperTypeWrapper typeWrapper, string name, string sig, Modifiers modifiers)
: base(typeWrapper, name, sig, null, null, null, modifiers, MemberFlags.None)
{
}
internal abstract MethodBase DoLink();
internal abstract void Finish();
internal static void AddDeclaredExceptions(MethodBase mb, IKVM.Internal.MapXml.Throws[] throws)
{
if(throws != null)
{
string[] exceptions = new string[throws.Length];
for(int i = 0; i < exceptions.Length; i++)
{
exceptions[i] = throws[i].Class;
}
AttributeHelper.SetThrowsAttribute(mb, exceptions);
}
}
}
sealed class RemappedConstructorWrapper : RemappedMethodBaseWrapper
{
private IKVM.Internal.MapXml.Constructor m;
private MethodBuilder mbHelper;
internal RemappedConstructorWrapper(RemapperTypeWrapper typeWrapper, IKVM.Internal.MapXml.Constructor m)
: base(typeWrapper, "<init>", m.Sig, (Modifiers)m.Modifiers)
{
this.m = m;
}
internal override void EmitCall(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Call, (ConstructorInfo)GetMethod());
}
internal override void EmitNewobj(ILGenerator ilgen, MethodAnalyzer ma, int opcodeIndex)
{
if(mbHelper != null)
{
ilgen.Emit(OpCodes.Call, mbHelper);
}
else
{
ilgen.Emit(OpCodes.Newobj, (ConstructorInfo)GetMethod());
}
}
internal override MethodBase DoLink()
{
MethodAttributes attr = MapMethodAccessModifiers(m.Modifiers);
RemapperTypeWrapper typeWrapper = (RemapperTypeWrapper)DeclaringType;
Type[] paramTypes = typeWrapper.GetClassLoader().ArgTypeListFromSig(m.Sig);
ConstructorBuilder cbCore = null;
if(typeWrapper.shadowType.IsSealed)
{
mbHelper = typeWrapper.typeBuilder.DefineMethod("newhelper", attr | MethodAttributes.Static, CallingConventions.Standard, typeWrapper.shadowType, paramTypes);
if(m.Attributes != null)
{
foreach(IKVM.Internal.MapXml.Attribute custattr in m.Attributes)
{
AttributeHelper.SetCustomAttribute(mbHelper, custattr);
}
}
SetParameters(mbHelper, m.Params);
AttributeHelper.SetModifiers(mbHelper, (Modifiers)m.Modifiers, false);
AttributeHelper.SetNameSig(mbHelper, "<init>", m.Sig);
AddDeclaredExceptions(mbHelper, m.throws);
}
else
{
cbCore = typeWrapper.typeBuilder.DefineConstructor(attr, CallingConventions.Standard, paramTypes);
if(m.Attributes != null)
{
foreach(IKVM.Internal.MapXml.Attribute custattr in m.Attributes)
{
AttributeHelper.SetCustomAttribute(cbCore, custattr);
}
}
SetParameters(cbCore, m.Params);
AddDeclaredExceptions(cbCore, m.throws);
}
return cbCore;
}
internal override void Finish()
{
// TODO we should insert method tracing (if enabled)
Type[] paramTypes = this.GetParametersForDefineMethod();
ConstructorBuilder cbCore = GetMethod() as ConstructorBuilder;
if(cbCore != null)
{
ILGenerator ilgen = cbCore.GetILGenerator();
// TODO we need to support ghost (and other funky?) parameter types
if(m.body != null)
{
// TODO do we need return type conversion here?
m.body.Emit(ilgen);
}
else
{
ilgen.Emit(OpCodes.Ldarg_0);
for(int i = 0; i < paramTypes.Length; i++)
{
ilgen.Emit(OpCodes.Ldarg, (short)(i + 1));
}
if(m.redirect != null)
{
throw new NotImplementedException();
}
else
{
ConstructorInfo baseCon = DeclaringType.TypeAsTBD.GetConstructor(paramTypes);
if(baseCon == null)
{
// TODO better error handling
throw new InvalidOperationException("base class constructor not found: " + DeclaringType.Name + ".<init>" + m.Sig);
}
ilgen.Emit(OpCodes.Call, baseCon);
}
ilgen.Emit(OpCodes.Ret);
}
if(this.DeclaringType.GetClassLoader().EmitStackTraceInfo)
{
ilgen.EmitLineNumberTable(cbCore);
}
}
if(mbHelper != null)
{
ILGenerator ilgen = mbHelper.GetILGenerator();
if(m.redirect != null)
{
m.redirect.Emit(ilgen);
}
else if(m.alternateBody != null)
{
m.alternateBody.Emit(ilgen);
}
else if(m.body != null)
{
// <body> doesn't make sense for helper constructors (which are actually factory methods)
throw new InvalidOperationException();
}
else
{
ConstructorInfo baseCon = DeclaringType.TypeAsTBD.GetConstructor(paramTypes);
if(baseCon == null)
{
// TODO better error handling
throw new InvalidOperationException("constructor not found: " + DeclaringType.Name + ".<init>" + m.Sig);
}
for(int i = 0; i < paramTypes.Length; i++)
{
ilgen.Emit(OpCodes.Ldarg, (short)i);
}
ilgen.Emit(OpCodes.Newobj, baseCon);
ilgen.Emit(OpCodes.Ret);
}
if(this.DeclaringType.GetClassLoader().EmitStackTraceInfo)
{
ilgen.EmitLineNumberTable(mbHelper);
}
}
}
}
sealed class RemappedMethodWrapper : RemappedMethodBaseWrapper
{
private IKVM.Internal.MapXml.Method m;
private IKVM.Internal.MapXml.Root map;
private MethodBuilder mbHelper;
private ArrayList overriders = new ArrayList();
private bool inherited;
internal RemappedMethodWrapper(RemapperTypeWrapper typeWrapper, IKVM.Internal.MapXml.Method m, IKVM.Internal.MapXml.Root map, bool inherited)
: base(typeWrapper, m.Name, m.Sig, (Modifiers)m.Modifiers)
{
this.m = m;
this.map = map;
this.inherited = inherited;
}
internal IKVM.Internal.MapXml.Method XmlMethod
{
get
{
return m;
}
}
internal override void EmitCall(ILGenerator ilgen)
{
ilgen.Emit(OpCodes.Call, (MethodInfo)GetMethod());
}
internal override void EmitCallvirt(ILGenerator ilgen)
{
if(mbHelper != null)
{
ilgen.Emit(OpCodes.Call, mbHelper);
}
else
{
ilgen.Emit(OpCodes.Callvirt, (MethodInfo)GetMethod());
}
}
internal override MethodBase DoLink()
{
RemapperTypeWrapper typeWrapper = (RemapperTypeWrapper)DeclaringType;
if(typeWrapper.IsInterface)
{
if(m.@override == null)
{
throw new InvalidOperationException(typeWrapper.Name + "." + m.Name + m.Sig);
}
MethodInfo interfaceMethod = typeWrapper.shadowType.GetMethod(m.@override.Name, typeWrapper.GetClassLoader().ArgTypeListFromSig(m.Sig));
if(interfaceMethod == null)
{
throw new InvalidOperationException(typeWrapper.Name + "." + m.Name + m.Sig);
}
if(m.throws != null)
{
// TODO we need a place to stick the declared exceptions
throw new NotImplementedException();
}
// if any of the remapped types has a body for this interface method, we need a helper method
// to special invocation through this interface for that type
ArrayList specialCases = null;
foreach(IKVM.Internal.MapXml.Class c in map.assembly.Classes)
{
if(c.Methods != null)
{
foreach(IKVM.Internal.MapXml.Method mm in c.Methods)
{
if(mm.Name == m.Name && mm.Sig == m.Sig && mm.body != null)
{
if(specialCases == null)
{
specialCases = new ArrayList();
}
specialCases.Add(c);
break;
}
}
}
}
AttributeHelper.SetRemappedInterfaceMethod(typeWrapper.typeBuilder, m.Name, m.@override.Name);
MethodBuilder helper = null;
if(specialCases != null)
{
ILGenerator ilgen;
Type[] temp = typeWrapper.GetClassLoader().ArgTypeListFromSig(m.Sig);
Type[] argTypes = new Type[temp.Length + 1];
temp.CopyTo(argTypes, 1);
argTypes[0] = typeWrapper.shadowType;
if(typeWrapper.helperTypeBuilder == null)
{
// FXBUG we use a nested helper class, because Reflection.Emit won't allow us to add a static method to the interface
typeWrapper.helperTypeBuilder = typeWrapper.typeBuilder.DefineNestedType("__Helper", TypeAttributes.NestedPublic | TypeAttributes.Class | TypeAttributes.Sealed);
ilgen = typeWrapper.helperTypeBuilder.DefineConstructor(MethodAttributes.Private, CallingConventions.Standard, Type.EmptyTypes).GetILGenerator();
ilgen.Emit(OpCodes.Ldnull);
ilgen.Emit(OpCodes.Throw);
AttributeHelper.HideFromJava(typeWrapper.helperTypeBuilder);
}
helper = typeWrapper.helperTypeBuilder.DefineMethod(m.Name, MethodAttributes.HideBySig | MethodAttributes.Public | MethodAttributes.Static, typeWrapper.GetClassLoader().RetTypeWrapperFromSig(m.Sig).TypeAsSignatureType, argTypes);
if(m.Attributes != null)
{
foreach(IKVM.Internal.MapXml.Attribute custattr in m.Attributes)
{
AttributeHelper.SetCustomAttribute(helper, custattr);
}
}
SetParameters(helper, m.Params);
ilgen = helper.GetILGenerator();
foreach(IKVM.Internal.MapXml.Class c in specialCases)
{
TypeWrapper tw = typeWrapper.GetClassLoader().LoadClassByDottedName(c.Name);
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Isinst, tw.TypeAsTBD);
ilgen.Emit(OpCodes.Dup);
Label label = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Brfalse_S, label);
for(int i = 1; i < argTypes.Length; i++)
{
ilgen.Emit(OpCodes.Ldarg, (short)i);
}
MethodWrapper mw = tw.GetMethodWrapper(m.Name, m.Sig, false);
mw.Link();
mw.EmitCallvirt(ilgen);
ilgen.Emit(OpCodes.Ret);
ilgen.MarkLabel(label);
ilgen.Emit(OpCodes.Pop);
}
for(int i = 0; i < argTypes.Length; i++)
{
ilgen.Emit(OpCodes.Ldarg, (short)i);
}
ilgen.Emit(OpCodes.Callvirt, interfaceMethod);
ilgen.Emit(OpCodes.Ret);
}
mbHelper = helper;
return interfaceMethod;
}
else
{
MethodBuilder mbCore = null;
Type[] paramTypes = typeWrapper.GetClassLoader().ArgTypeListFromSig(m.Sig);
Type retType = typeWrapper.GetClassLoader().RetTypeWrapperFromSig(m.Sig).TypeAsSignatureType;
if(typeWrapper.shadowType.IsSealed && (m.Modifiers & IKVM.Internal.MapXml.MapModifiers.Static) == 0)
{
// skip instance methods in sealed types, but we do need to add them to the overriders
if(typeWrapper.BaseTypeWrapper != null && (m.Modifiers & IKVM.Internal.MapXml.MapModifiers.Private) == 0)
{
RemappedMethodWrapper baseMethod = typeWrapper.BaseTypeWrapper.GetMethodWrapper(m.Name, m.Sig, true) as RemappedMethodWrapper;
if(baseMethod != null &&
!baseMethod.IsFinal &&
!baseMethod.IsPrivate &&
(baseMethod.m.@override != null ||
baseMethod.m.redirect != null ||
baseMethod.m.body != null ||
baseMethod.m.alternateBody != null))
{
baseMethod.overriders.Add(typeWrapper);
}
}
}
else
{
MethodInfo overrideMethod = null;
MethodAttributes attr = MapMethodAccessModifiers(m.Modifiers) | MethodAttributes.HideBySig;
if((m.Modifiers & IKVM.Internal.MapXml.MapModifiers.Static) != 0)
{
attr |= MethodAttributes.Static;
}
else if((m.Modifiers & IKVM.Internal.MapXml.MapModifiers.Private) == 0 && (m.Modifiers & IKVM.Internal.MapXml.MapModifiers.Final) == 0)
{
attr |= MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.CheckAccessOnOverride;
if(typeWrapper.BaseTypeWrapper != null)
{
RemappedMethodWrapper baseMethod = typeWrapper.BaseTypeWrapper.GetMethodWrapper(m.Name, m.Sig, true) as RemappedMethodWrapper;
if(baseMethod != null)
{
baseMethod.overriders.Add(typeWrapper);
if(baseMethod.m.@override != null)
{
overrideMethod = typeWrapper.BaseTypeWrapper.TypeAsTBD.GetMethod(baseMethod.m.@override.Name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, paramTypes, null);
if(overrideMethod == null)
{
throw new InvalidOperationException();
}
}
}
}
}
mbCore = typeWrapper.typeBuilder.DefineMethod(m.Name, attr, CallingConventions.Standard, retType, paramTypes);
if(m.Attributes != null)
{
foreach(IKVM.Internal.MapXml.Attribute custattr in m.Attributes)
{
AttributeHelper.SetCustomAttribute(mbCore, custattr);
}
}
SetParameters(mbCore, m.Params);
if(overrideMethod != null && !inherited)
{
typeWrapper.typeBuilder.DefineMethodOverride(mbCore, overrideMethod);
}
if(inherited)
{
AttributeHelper.HideFromReflection(mbCore);