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
/
compiler.cs
3324 lines (3232 loc) · 104 KB
/
compiler.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 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.Collections;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using IKVM.Runtime;
using IKVM.Attributes;
using IKVM.Internal;
using ILGenerator = CountingILGenerator;
using ExceptionTableEntry = ClassFile.Method.ExceptionTableEntry;
using LocalVariableTableEntry = ClassFile.Method.LocalVariableTableEntry;
using Instruction = ClassFile.Method.Instruction;
class Compiler
{
private static MethodInfo mapExceptionMethod;
private static MethodInfo mapExceptionFastMethod;
private static MethodWrapper fillInStackTraceMethod;
private static MethodInfo getTypeFromHandleMethod;
private static MethodInfo getClassFromTypeHandleMethod;
private static MethodInfo multiANewArrayMethod;
private static MethodInfo monitorEnterMethod;
private static MethodInfo monitorExitMethod;
private static MethodInfo objectToStringMethod;
private static MethodInfo keepAliveMethod;
private static MethodInfo f2iMethod;
private static MethodInfo d2iMethod;
private static MethodInfo f2lMethod;
private static MethodInfo d2lMethod;
private static MethodInfo arraycopy_fastMethod;
private static MethodInfo arraycopy_primitive_8Method;
private static MethodInfo arraycopy_primitive_4Method;
private static MethodInfo arraycopy_primitive_2Method;
private static MethodInfo arraycopy_primitive_1Method;
private static MethodInfo arraycopyMethod;
private static TypeWrapper java_lang_Object;
private static TypeWrapper java_lang_Class;
private static TypeWrapper java_lang_Throwable;
private static TypeWrapper java_lang_ThreadDeath;
private static TypeWrapper cli_System_Exception;
private TypeWrapper clazz;
private MethodWrapper mw;
private ClassFile classFile;
private ClassFile.Method m;
private ILGenerator ilGenerator;
private ClassLoaderWrapper classLoader;
private MethodAnalyzer ma;
private ExceptionTableEntry[] exceptions;
private ISymbolDocumentWriter symboldocument;
private System.IO.MemoryStream lineNumbers;
private bool nonleaf;
static Compiler()
{
getTypeFromHandleMethod = typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(RuntimeTypeHandle) }, null);
getClassFromTypeHandleMethod = typeof(ByteCodeHelper).GetMethod("GetClassFromTypeHandle");
multiANewArrayMethod = typeof(ByteCodeHelper).GetMethod("multianewarray");
monitorEnterMethod = typeof(System.Threading.Monitor).GetMethod("Enter", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(object) }, null);
monitorExitMethod = typeof(System.Threading.Monitor).GetMethod("Exit", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(object) }, null);
objectToStringMethod = typeof(object).GetMethod("ToString");
keepAliveMethod = typeof(GC).GetMethod("KeepAlive", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(object) }, null);
f2iMethod = typeof(ByteCodeHelper).GetMethod("f2i");
d2iMethod = typeof(ByteCodeHelper).GetMethod("d2i");
f2lMethod = typeof(ByteCodeHelper).GetMethod("f2l");
d2lMethod = typeof(ByteCodeHelper).GetMethod("d2l");
arraycopy_fastMethod = typeof(ByteCodeHelper).GetMethod("arraycopy_fast");
arraycopy_primitive_8Method = typeof(ByteCodeHelper).GetMethod("arraycopy_primitive_8");
arraycopy_primitive_4Method = typeof(ByteCodeHelper).GetMethod("arraycopy_primitive_4");
arraycopy_primitive_2Method = typeof(ByteCodeHelper).GetMethod("arraycopy_primitive_2");
arraycopy_primitive_1Method = typeof(ByteCodeHelper).GetMethod("arraycopy_primitive_1");
arraycopyMethod = typeof(ByteCodeHelper).GetMethod("arraycopy");
java_lang_Throwable = CoreClasses.java.lang.Throwable.Wrapper;
cli_System_Exception = ClassLoaderWrapper.LoadClassCritical("cli.System.Exception");
java_lang_Object = CoreClasses.java.lang.Object.Wrapper;
java_lang_Class = CoreClasses.java.lang.Class.Wrapper;
java_lang_ThreadDeath = ClassLoaderWrapper.LoadClassCritical("java.lang.ThreadDeath");
// HACK we need to special case core compilation, because the __<map> methods are HideFromJava
if(java_lang_Throwable.TypeAsBaseType is TypeBuilder)
{
MethodWrapper mw = java_lang_Throwable.GetMethodWrapper("__<map>", "(Ljava.lang.Throwable;Lcli.System.Type;)Ljava.lang.Throwable;", false);
mw.Link();
mapExceptionMethod = (MethodInfo)mw.GetMethod();
mw = java_lang_Throwable.GetMethodWrapper("__<map>", "(Ljava.lang.Throwable;)Ljava.lang.Throwable;", false);
mw.Link();
mapExceptionFastMethod = (MethodInfo)mw.GetMethod();
}
else
{
mapExceptionMethod = java_lang_Throwable.TypeAsBaseType.GetMethod("__<map>", new Type[] { typeof(Exception), typeof(Type) });
mapExceptionFastMethod = java_lang_Throwable.TypeAsBaseType.GetMethod("__<map>", new Type[] { typeof(Exception) });
}
fillInStackTraceMethod = java_lang_Throwable.GetMethodWrapper("fillInStackTrace", "()Ljava.lang.Throwable;", false);
fillInStackTraceMethod.Link();
}
private class ExceptionSorter : IComparer
{
public int Compare(object x, object y)
{
ExceptionTableEntry e1 = (ExceptionTableEntry)x;
ExceptionTableEntry e2 = (ExceptionTableEntry)y;
if(e1.start_pc < e2.start_pc)
{
return -1;
}
if(e1.start_pc == e2.start_pc)
{
if(e1.end_pc == e2.end_pc)
{
if(e1.ordinal > e2.ordinal)
{
return -1;
}
return 1;
}
if(e1.end_pc > e2.end_pc)
{
return -1;
}
}
return 1;
}
}
private Compiler(TypeWrapper clazz, MethodWrapper mw, ClassFile classFile, ClassFile.Method m, ILGenerator ilGenerator, ClassLoaderWrapper classLoader, ISymbolDocumentWriter symboldocument)
{
this.clazz = clazz;
this.mw = mw;
this.classFile = classFile;
this.m = m;
this.ilGenerator = ilGenerator;
this.classLoader = classLoader;
this.symboldocument = symboldocument;
if(m.LineNumberTableAttribute != null && !JVM.NoStackTraceInfo)
{
this.lineNumbers = new System.IO.MemoryStream(m.LineNumberTableAttribute.Length * 2);
}
Profiler.Enter("MethodAnalyzer");
try
{
ma = new MethodAnalyzer(clazz, mw, classFile, m, classLoader);
}
finally
{
Profiler.Leave("MethodAnalyzer");
}
TypeWrapper[] args = mw.GetParameters();
LocalVar[] locals = ma.GetAllLocalVars();
foreach(LocalVar v in locals)
{
if(v.isArg)
{
int arg = m.ArgMap[v.local];
TypeWrapper tw;
if(m.IsStatic)
{
tw = args[arg];
}
else if(arg == 0)
{
tw = clazz;
}
else
{
tw = args[arg - 1];
}
if(!tw.IsUnloadable &&
v.type != VerifierTypeWrapper.UninitializedThis &&
(v.type != tw || tw.TypeAsLocalOrStackType != tw.TypeAsSignatureType))
{
v.builder = ilGenerator.DeclareLocal(v.type.TypeAsLocalOrStackType);
if(JVM.Debug && v.name != null)
{
v.builder.SetLocalSymInfo(v.name);
}
v.isArg = false;
ilGenerator.Emit(OpCodes.Ldarg_S, (byte)arg);
tw.EmitConvSignatureTypeToStackType(ilGenerator);
ilGenerator.Emit(OpCodes.Stloc, v.builder);
}
}
}
// NOTE we're going to be messing with ExceptionTableEntrys that are owned by the Method, this is very bad practice,
// this code should probably be changed to use our own ETE class (which should also contain the ordinal, instead
// of the one in ClassFile.cs)
ArrayList ar = new ArrayList(m.ExceptionTable);
restart:
for(int i = 0; i < ar.Count; i++)
{
ExceptionTableEntry ei = (ExceptionTableEntry)ar[i];
for(int j = 0; j < ar.Count; j++)
{
ExceptionTableEntry ej = (ExceptionTableEntry)ar[j];
if(ei.start_pc <= ej.start_pc && ej.start_pc < ei.end_pc)
{
// 0006/test.j
if(ej.end_pc > ei.end_pc)
{
ExceptionTableEntry emi = new ExceptionTableEntry();
emi.start_pc = ej.start_pc;
emi.end_pc = ei.end_pc;
emi.catch_type = ei.catch_type;
emi.handler_pc = ei.handler_pc;
ExceptionTableEntry emj = new ExceptionTableEntry();
emj.start_pc = ej.start_pc;
emj.end_pc = ei.end_pc;
emj.catch_type = ej.catch_type;
emj.handler_pc = ej.handler_pc;
ei.end_pc = emi.start_pc;
ej.start_pc = emj.end_pc;
ar.Insert(j, emj);
ar.Insert(i + 1, emi);
goto restart;
}
// 0007/test.j
else if(j > i && ej.end_pc < ei.end_pc)
{
ExceptionTableEntry emi = new ExceptionTableEntry();
emi.start_pc = ej.start_pc;
emi.end_pc = ej.end_pc;
emi.catch_type = ei.catch_type;
emi.handler_pc = ei.handler_pc;
ExceptionTableEntry eei = new ExceptionTableEntry();
eei.start_pc = ej.end_pc;
eei.end_pc = ei.end_pc;
eei.catch_type = ei.catch_type;
eei.handler_pc = ei.handler_pc;
ei.end_pc = emi.start_pc;
ar.Insert(i + 1, eei);
ar.Insert(i + 1, emi);
goto restart;
}
}
}
}
// __jsr inside a try block (to a PC outside the try block) causes the try
// block to be broken into two blocks surrounding the __jsr
// This is actually pretty common. Take, for example, the following code:
// class hello
// {
// public static void main(String[] args)
// {
// try
// {
// for(;;)
// {
// if(args.length == 0) return;
// }
// }
// finally
// {
// System.out.println("Hello, world!");
// }
// }
// }
restart_jsr:
for(int i = 0; i < ar.Count; i++)
{
ExceptionTableEntry ei = (ExceptionTableEntry)ar[i];
for(int j = FindPcIndex(ei.start_pc), e = FindPcIndex(ei.end_pc); j < e; j++)
{
if(m.Instructions[j].NormalizedOpCode == NormalizedByteCode.__jsr)
{
int targetPC = m.Instructions[j].NormalizedArg1 + m.Instructions[j].PC;
if(targetPC < ei.start_pc || targetPC >= ei.end_pc)
{
ExceptionTableEntry en = new ExceptionTableEntry();
en.catch_type = ei.catch_type;
en.handler_pc = ei.handler_pc;
en.start_pc = (ushort)m.Instructions[j + 1].PC;
en.end_pc = ei.end_pc;
ei.end_pc = (ushort)m.Instructions[j].PC;
ar.Insert(i + 1, en);
goto restart_jsr;
}
}
}
}
// Split try blocks at branch targets (branches from outside the try block)
for(int i = 0; i < ar.Count; i++)
{
ExceptionTableEntry ei = (ExceptionTableEntry)ar[i];
int start = FindPcIndex(ei.start_pc);
int end = FindPcIndex(ei.end_pc);
for(int j = 0; j < m.Instructions.Length; j++)
{
if(j < start || j >= end)
{
switch(m.Instructions[j].NormalizedOpCode)
{
case NormalizedByteCode.__lookupswitch:
// start at -1 to have an opportunity to handle the default offset
for(int k = -1; k < m.Instructions[j].SwitchEntryCount; k++)
{
int targetPC = m.Instructions[j].PC + (k == -1 ? m.Instructions[j].DefaultOffset : m.Instructions[j].GetSwitchTargetOffset(k));
if(ei.start_pc < targetPC && targetPC < ei.end_pc)
{
ExceptionTableEntry en = new ExceptionTableEntry();
en.catch_type = ei.catch_type;
en.handler_pc = ei.handler_pc;
en.start_pc = (ushort)targetPC;
en.end_pc = ei.end_pc;
ei.end_pc = (ushort)targetPC;
ar.Insert(i + 1, en);
goto restart_jsr;
}
}
break;
case NormalizedByteCode.__ifeq:
case NormalizedByteCode.__ifne:
case NormalizedByteCode.__iflt:
case NormalizedByteCode.__ifge:
case NormalizedByteCode.__ifgt:
case NormalizedByteCode.__ifle:
case NormalizedByteCode.__if_icmpeq:
case NormalizedByteCode.__if_icmpne:
case NormalizedByteCode.__if_icmplt:
case NormalizedByteCode.__if_icmpge:
case NormalizedByteCode.__if_icmpgt:
case NormalizedByteCode.__if_icmple:
case NormalizedByteCode.__if_acmpeq:
case NormalizedByteCode.__if_acmpne:
case NormalizedByteCode.__ifnull:
case NormalizedByteCode.__ifnonnull:
case NormalizedByteCode.__goto:
case NormalizedByteCode.__jsr:
{
int targetPC = m.Instructions[j].PC + m.Instructions[j].Arg1;
if(ei.start_pc < targetPC && targetPC < ei.end_pc)
{
ExceptionTableEntry en = new ExceptionTableEntry();
en.catch_type = ei.catch_type;
en.handler_pc = ei.handler_pc;
en.start_pc = (ushort)targetPC;
en.end_pc = ei.end_pc;
ei.end_pc = (ushort)targetPC;
ar.Insert(i + 1, en);
goto restart_jsr;
}
break;
}
}
}
}
}
// exception handlers are also a kind of jump, so we need to split try blocks around handlers as well
for(int i = 0; i < ar.Count; i++)
{
ExceptionTableEntry ei = (ExceptionTableEntry)ar[i];
for(int j = 0; j < ar.Count; j++)
{
ExceptionTableEntry ej = (ExceptionTableEntry)ar[j];
if(ei.start_pc < ej.handler_pc && ej.handler_pc < ei.end_pc)
{
ExceptionTableEntry en = new ExceptionTableEntry();
en.catch_type = ei.catch_type;
en.handler_pc = ei.handler_pc;
en.start_pc = ej.handler_pc;
en.end_pc = ei.end_pc;
ei.end_pc = ej.handler_pc;
ar.Insert(i + 1, en);
goto restart_jsr;
}
}
}
// filter out zero length try blocks
for(int i = 0; i < ar.Count; i++)
{
ExceptionTableEntry ei = (ExceptionTableEntry)ar[i];
if(ei.start_pc == ei.end_pc)
{
ar.RemoveAt(i);
i--;
}
else
{
// exception blocks that only contain harmless instructions (i.e. instructions that will *never* throw an exception)
// are also filtered out (to improve the quality of the generated code)
// NOTE we don't remove exception handlers that could catch ThreadDeath, because that can be thrown
// asynchronously (and thus appear on any instruction). This is particularly important to ensure that
// we run finally blocks when a thread is killed.
if(ei.catch_type != 0)
{
TypeWrapper exceptionType = classFile.GetConstantPoolClassType(ei.catch_type);
if(!exceptionType.IsUnloadable && !java_lang_ThreadDeath.IsAssignableTo(exceptionType))
{
int start = FindPcIndex(ei.start_pc);
int end = FindPcIndex(ei.end_pc);
for(int j = start; j < end; j++)
{
if(ByteCodeMetaData.CanThrowException(m.Instructions[j].OpCode))
{
goto next;
}
}
ar.RemoveAt(i);
i--;
}
}
}
next:;
}
// Console.WriteLine("after processing:");
// foreach(ExceptionTableEntry e in ar)
// {
// Console.WriteLine("{0} to {1} handler {2}", e.start_pc, e.end_pc, e.handler_pc);
// }
exceptions = new ExceptionTableEntry[ar.Count];
ar.CopyTo(exceptions, 0);
for(int i = 0; i < exceptions.Length; i++)
{
exceptions[i].ordinal = i;
}
Array.Sort(exceptions, new ExceptionSorter());
// TODO remove these checks, if the above exception untangling is correct, this shouldn't ever
// be triggered
for(int i = 0; i < exceptions.Length; i++)
{
for(int j = i + 1; j < exceptions.Length; j++)
{
// check for partially overlapping try blocks (which is legal for the JVM, but not the CLR)
if(exceptions[i].start_pc < exceptions[j].start_pc &&
exceptions[j].start_pc < exceptions[i].end_pc &&
exceptions[i].end_pc < exceptions[j].end_pc)
{
throw new InvalidOperationException("Partially overlapping try blocks is broken");
}
// check that we didn't destroy the ordering, when sorting
if(exceptions[i].start_pc <= exceptions[j].start_pc &&
exceptions[i].end_pc >= exceptions[j].end_pc &&
exceptions[i].ordinal < exceptions[j].ordinal)
{
throw new InvalidOperationException("Non recursive try blocks is broken");
}
}
// make sure __jsr doesn't jump out of try block
for(int j = FindPcIndex(exceptions[i].start_pc), e = FindPcIndex(exceptions[i].end_pc); j < e; j++)
{
if(m.Instructions[j].NormalizedOpCode == NormalizedByteCode.__jsr)
{
int targetPC = m.Instructions[j].NormalizedArg1 + m.Instructions[j].PC;
if(targetPC < exceptions[i].start_pc || targetPC >= exceptions[i].end_pc)
{
throw new InvalidOperationException("Try block splitting around __jsr is broken");
}
}
}
}
}
private class EmitException : ApplicationException
{
private TypeWrapper type;
internal EmitException(string message, TypeWrapper type)
: base(message)
{
this.type = type;
}
internal void Emit(ILGenerator ilgen, ClassFile classFile, ClassFile.Method m)
{
Tracer.Error(Tracer.Compiler, "{0}: {1}\n\tat {2}.{3}{4}", type.Name, Message, classFile.Name, m.Name, m.Signature);
ilgen.Emit(OpCodes.Ldstr, Message);
MethodWrapper method = type.GetMethodWrapper("<init>", "(Ljava.lang.String;)V", false);
method.Link();
method.EmitNewobj(ilgen);
ilgen.Emit(OpCodes.Throw);
}
}
private sealed class NoClassDefFoundError : EmitException
{
internal NoClassDefFoundError(string message)
: base(message, ClassLoaderWrapper.LoadClassCritical("java.lang.NoClassDefFoundError"))
{
}
}
private sealed class IllegalAccessError : EmitException
{
internal IllegalAccessError(string message)
: base(message, ClassLoaderWrapper.LoadClassCritical("java.lang.IllegalAccessError"))
{
}
}
private sealed class InstantiationError : EmitException
{
internal InstantiationError(string message)
: base(message, ClassLoaderWrapper.LoadClassCritical("java.lang.InstantiationError"))
{
}
}
private sealed class IncompatibleClassChangeError : EmitException
{
internal IncompatibleClassChangeError(string message)
: base(message, ClassLoaderWrapper.LoadClassCritical("java.lang.IncompatibleClassChangeError"))
{
}
}
private sealed class NoSuchFieldError : EmitException
{
internal NoSuchFieldError(string message)
: base(message, ClassLoaderWrapper.LoadClassCritical("java.lang.NoSuchFieldError"))
{
}
}
private sealed class AbstractMethodError : EmitException
{
internal AbstractMethodError(string message)
: base(message, ClassLoaderWrapper.LoadClassCritical("java.lang.AbstractMethodError"))
{
}
}
private sealed class NoSuchMethodError : EmitException
{
internal NoSuchMethodError(string message)
: base(message, ClassLoaderWrapper.LoadClassCritical("java.lang.NoSuchMethodError"))
{
}
}
private sealed class LinkageError : EmitException
{
internal LinkageError(string message)
: base(message, ClassLoaderWrapper.LoadClassCritical("java.lang.LinkageError"))
{
}
}
private sealed class ReturnCookie
{
private Label stub;
private LocalBuilder local;
internal ReturnCookie(Label stub, LocalBuilder local)
{
this.stub = stub;
this.local = local;
}
internal void EmitRet(ILGenerator ilgen)
{
ilgen.MarkLabel(stub);
if(local != null)
{
ilgen.Emit(OpCodes.Ldloc, local);
}
ilgen.Emit(OpCodes.Ret);
}
}
private sealed class BranchCookie
{
// NOTE Stub gets used for both the push stub (inside the exception block) as well as the pop stub (outside the block)
internal Label Stub;
internal Label TargetLabel;
internal bool ContentOnStack;
internal readonly int TargetPC;
internal DupHelper dh;
internal BranchCookie(ILGenerator ilgen, int stackHeight, int targetPC)
{
this.Stub = ilgen.DefineLabel();
this.TargetPC = targetPC;
this.dh = new DupHelper(ilgen, stackHeight);
}
internal BranchCookie(Label label, int targetPC)
{
this.Stub = label;
this.TargetPC = targetPC;
}
}
private struct DupHelper
{
private enum StackType : byte
{
Null,
New,
UnitializedThis,
Other
}
private ILGenerator ilgen;
private StackType[] types;
private LocalBuilder[] locals;
internal DupHelper(ILGenerator ilgen, int count)
{
this.ilgen = ilgen;
types = new StackType[count];
locals = new LocalBuilder[count];
}
internal int Count
{
get
{
return types.Length;
}
}
internal void SetType(int i, TypeWrapper type)
{
if(type == VerifierTypeWrapper.Null)
{
types[i] = StackType.Null;
}
else if(VerifierTypeWrapper.IsNew(type))
{
// new objects aren't really there on the stack
types[i] = StackType.New;
}
else if(type == VerifierTypeWrapper.UninitializedThis)
{
// uninitialized references cannot be stored in a local, but we can reload them
types[i] = StackType.UnitializedThis;
}
else
{
types[i] = StackType.Other;
locals[i] = ilgen.DeclareLocal(type.TypeAsLocalOrStackType);
}
}
internal void Load(int i)
{
switch(types[i])
{
case StackType.Null:
ilgen.Emit(OpCodes.Ldnull);
break;
case StackType.New:
// new objects aren't really there on the stack
break;
case StackType.UnitializedThis:
ilgen.Emit(OpCodes.Ldarg_0);
break;
case StackType.Other:
ilgen.Emit(OpCodes.Ldloc, locals[i]);
break;
default:
throw new InvalidOperationException();
}
}
internal void Store(int i)
{
switch(types[i])
{
case StackType.Null:
case StackType.UnitializedThis:
ilgen.Emit(OpCodes.Pop);
break;
case StackType.New:
// new objects aren't really there on the stack
break;
case StackType.Other:
ilgen.Emit(OpCodes.Stloc, locals[i]);
break;
default:
throw new InvalidOperationException();
}
}
}
internal static void Compile(DynamicTypeWrapper clazz, MethodWrapper mw, ClassFile classFile, ClassFile.Method m, ILGenerator ilGenerator, ref string verifyError)
{
bool nonleaf = false;
Compile(clazz, mw, classFile, m, ilGenerator, ref verifyError, ref nonleaf);
}
internal static void Compile(DynamicTypeWrapper clazz, MethodWrapper mw, ClassFile classFile, ClassFile.Method m, ILGenerator ilGenerator, ref string verifyError, ref bool nonleaf)
{
ClassLoaderWrapper classLoader = clazz.GetClassLoader();
ISymbolDocumentWriter symboldocument = null;
if(JVM.Debug)
{
string sourcefile = classFile.SourceFileAttribute;
if(sourcefile != null)
{
if(JVM.SourcePath != null)
{
string package = clazz.Name;
int index = package.LastIndexOf('.');
package = index == -1 ? "" : package.Substring(0, index).Replace('.', '/');
sourcefile = new System.IO.FileInfo(JVM.SourcePath + "/" + package + "/" + sourcefile).FullName;
}
symboldocument = classLoader.ModuleBuilder.DefineDocument(sourcefile, SymLanguageType.Java, Guid.Empty, SymDocumentType.Text);
// the very first instruction in the method must have an associated line number, to be able
// to step into the method in Visual Studio .NET
ClassFile.Method.LineNumberTableEntry[] table = m.LineNumberTableAttribute;
if(table != null)
{
int firstPC = int.MaxValue;
int firstLine = -1;
for(int i = 0; i < table.Length; i++)
{
if(table[i].start_pc < firstPC && table[i].line_number != 0)
{
firstLine = table[i].line_number;
firstPC = table[i].start_pc;
}
}
if(firstLine > 0)
{
ilGenerator.MarkSequencePoint(symboldocument, firstLine, 0, firstLine + 1, 0);
}
}
}
}
TypeWrapper[] args = mw.GetParameters();
for(int i = 0; i < args.Length; i++)
{
if(args[i].IsUnloadable)
{
Profiler.Count("EmitDynamicCast");
ilGenerator.Emit(OpCodes.Ldarg, (short)(i + (m.IsStatic ? 0 : 1)));
ilGenerator.Emit(OpCodes.Ldtoken, clazz.TypeAsTBD);
ilGenerator.Emit(OpCodes.Ldstr, args[i].Name);
ilGenerator.Emit(OpCodes.Call, typeof(ByteCodeHelper).GetMethod("DynamicCast"));
ilGenerator.Emit(OpCodes.Pop);
}
}
Compiler c;
try
{
Profiler.Enter("new Compiler");
try
{
c = new Compiler(clazz, mw, classFile, m, ilGenerator, classLoader, symboldocument);
}
finally
{
Profiler.Leave("new Compiler");
}
}
catch(VerifyError x)
{
Tracer.Error(Tracer.Verifier, x.ToString());
// because in Java the method is only verified if it is actually called,
// we generate code here to throw the VerificationError
EmitHelper.Throw(ilGenerator, "java.lang.VerifyError", x.Message);
if(verifyError == null)
{
verifyError = x.Message;
}
return;
}
Profiler.Enter("Compile");
try
{
if(m.IsSynchronized && m.IsStatic)
{
ilGenerator.Emit(OpCodes.Ldsfld, clazz.ClassObjectField);
Label label = ilGenerator.DefineLabel();
ilGenerator.Emit(OpCodes.Brtrue_S, label);
ilGenerator.Emit(OpCodes.Ldtoken, clazz.TypeAsTBD);
ilGenerator.Emit(OpCodes.Call, getClassFromTypeHandleMethod);
ilGenerator.Emit(OpCodes.Stsfld, clazz.ClassObjectField);
ilGenerator.MarkLabel(label);
ilGenerator.Emit(OpCodes.Ldsfld, clazz.ClassObjectField);
ilGenerator.Emit(OpCodes.Dup);
LocalBuilder monitor = ilGenerator.DeclareLocal(typeof(object));
ilGenerator.Emit(OpCodes.Stloc, monitor);
ilGenerator.Emit(OpCodes.Call, monitorEnterMethod);
ilGenerator.BeginExceptionBlock();
Block b = new Block(c, 0, int.MaxValue, -1, new ArrayList(), true);
c.Compile(b);
b.Leave();
ilGenerator.BeginFinallyBlock();
ilGenerator.Emit(OpCodes.Ldloc, monitor);
ilGenerator.Emit(OpCodes.Call, monitorExitMethod);
ilGenerator.EndExceptionBlock();
b.LeaveStubs(new Block(c, 0, int.MaxValue, -1, null, false));
}
else
{
Block b = new Block(c, 0, int.MaxValue, -1, null, false);
c.Compile(b);
b.Leave();
}
if(c.lineNumbers != null)
{
AttributeHelper.SetLineNumberTable(mw.GetMethod(), c.lineNumbers.ToArray());
}
// HACK because of the bogus Leave instruction that Reflection.Emit generates, this location
// sometimes appears reachable (it isn't), so we emit a bogus branch to keep the verifier happy.
ilGenerator.Emit(OpCodes.Br, - (ilGenerator.GetILOffset() + 5));
//ilGenerator.Emit(OpCodes.Br_S, (sbyte)-2);
ilGenerator.Finish();
nonleaf = c.nonleaf;
}
finally
{
Profiler.Leave("Compile");
}
}
private class Block
{
private Compiler compiler;
private ILGenerator ilgen;
private int begin;
private int end;
private int exceptionIndex;
private ArrayList exits;
private bool nested;
private object[] labels;
internal Block(Compiler compiler, int beginPC, int endPC, int exceptionIndex, ArrayList exits, bool nested)
{
this.compiler = compiler;
this.ilgen = compiler.ilGenerator;
this.begin = beginPC;
this.end = endPC;
this.exceptionIndex = exceptionIndex;
this.exits = exits;
this.nested = nested;
labels = new object[compiler.m.Instructions.Length];
}
internal int End
{
get
{
return end;
}
}
internal int ExceptionIndex
{
get
{
return exceptionIndex;
}
}
internal void SetBackwardBranchLabel(int instructionIndex, BranchCookie bc)
{
// NOTE we're overwriting the label that is already there
labels[instructionIndex] = bc.Stub;
if(exits == null)
{
exits = new ArrayList();
}
exits.Add(bc);
}
internal Label GetLabel(int targetPC)
{
int targetIndex = compiler.FindPcIndex(targetPC);
if(IsInRange(targetPC))
{
object l = labels[targetIndex];
if(l == null)
{
l = ilgen.DefineLabel();
labels[targetIndex] = l;
}
return (Label)l;
}
else
{
object l = labels[targetIndex];
if(l == null)
{
// if we're branching out of the current exception block, we need to indirect this thru a stub
// that saves the stack and uses leave to leave the exception block (to another stub that recovers
// the stack)
int stackHeight = compiler.ma.GetStackHeight(targetIndex);
BranchCookie bc = new BranchCookie(ilgen, stackHeight, targetPC);
bc.ContentOnStack = true;
for(int i = 0; i < stackHeight; i++)
{
bc.dh.SetType(i, compiler.ma.GetRawStackTypeWrapper(targetIndex, i));
}
exits.Add(bc);
l = bc;
labels[targetIndex] = l;
}
return ((BranchCookie)l).Stub;
}
}
internal bool HasLabel(int instructionIndex)
{
return labels[instructionIndex] != null;
}
internal void MarkLabel(int instructionIndex)
{
object label = labels[instructionIndex];
if(label == null)
{
Label l = ilgen.DefineLabel();
ilgen.MarkLabel(l);
labels[instructionIndex] = l;
}
else
{
ilgen.MarkLabel((Label)label);
}
}
internal bool IsInRange(int pc)
{
return begin <= pc && pc < end;
}
internal void Leave()
{
if(exits != null)
{
for(int i = 0; i < exits.Count; i++)
{
object exit = exits[i];
BranchCookie bc = exit as BranchCookie;
if(bc != null && bc.ContentOnStack)
{
bc.ContentOnStack = false;
int stack = bc.dh.Count;
// HACK this is unreachable code, but we make sure that
// forward pass verification always yields a valid stack
// (this is required for unreachable leave stubs that are
// generated for unreachable code that follows an
// embedded exception emitted by the compiler for invalid
// code (e.g. NoSuchFieldError))
for(int n = stack - 1; n >= 0; n--)
{
bc.dh.Load(n);
}
ilgen.MarkLabel(bc.Stub);
for(int n = 0; n < stack; n++)
{
bc.dh.Store(n);
}
if(bc.TargetPC == -1)
{
ilgen.Emit(OpCodes.Br, bc.TargetLabel);
}
else
{
bc.Stub = ilgen.DefineLabel();
ilgen.Emit(OpCodes.Leave, bc.Stub);
}
}
}
}
}
internal void LeaveStubs(Block newBlock)
{
if(exits != null)
{
for(int i = 0; i < exits.Count; i++)
{
object exit = exits[i];
ReturnCookie rc = exit as ReturnCookie;
if(rc != null)
{
if(newBlock.IsNested)