-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexec.js
2164 lines (1991 loc) · 68.7 KB
/
exec.js
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
//
// exec.js
//
// Kopiluwak. Copyright (c) 2020 Ben Zotto
//
function KLStackFrame(method) {
this.method = method;
this.pc = 0;
this.localVariables = [];
this.operandStack = [];
this.pendingException = null;
this.completionHandlers = [];
}
// const KLTHREAD_STATE_STOPPED = 0;
const KLTHREAD_STATE_RUNNING = 1;
const KLTHREAD_STATE_ENDED = 2;
const KLTHREAD_STATE_WAITING = 3;
const KLTHREAD_END_REASON_NORMAL = 0;
const KLTHREAD_END_REASON_EXCEPTION = 1;
const KLTHREAD_END_REASON_VM_ERROR = 2;
// each new KLThreadContext bumps this value
let KLNextThreadId = 1;
function KLIoRequest(fd, len) {
this.fd = fd;
this.buffer = [];
this.len = len;
this.completedLen = 0;
}
function KLThreadContext(bootstrapMethod, bootstrapArgs) {
this.stack = [];
this.threadId = KLNextThreadId++;
this.javaThreadObj = null;
this.pendingIo = null;
this.returnValue = null;
this.state = KLTHREAD_STATE_RUNNING;
this.endReason;
this.pushFrame = function(frame) {
this.stack.unshift(frame);
}
this.popFrame = function(isAbrupt) {
let isNormal = !(isAbrupt);
let outgoingFrame = this.stack.shift();
if (AccessFlagIsSet(outgoingFrame.method.access, ACC_SYNCHRONIZED)) {
// XXX: release method monitor.
}
if (isNormal) {
for (let i = 0; i < outgoingFrame.completionHandlers.length; i++) {
outgoingFrame.completionHandlers[i](outgoingFrame);
}
}
// console.log("--> Exiting " + outgoingFrame.method.class.name + "." + outgoingFrame.method.name);
return outgoingFrame;
}
// Exception class name is required; message (JS string) and cause (Throwable jobject) are optional.
this.throwException = function(exceptionClassName, message, cause) {
// // XXX Debug dump
// let bt = DebugBacktrace(this);
// console.log("Exception " + exceptionClassName + ": " + (message?message:"?") + "\n" + bt);
// ////
let npeClass = ResolveClass(exceptionClassName);
let e = npeClass.createInstance();
this.stack[0].pendingException = e; // Not initialized yet but will be when we unwind back to it!
let initFrame = CreateObjInitFrameForObjectAndDescriptor(e, "(Ljava.lang.String;Ljava.lang.Throwable;)V");
initFrame.localVariables[0] = e;
initFrame.localVariables[1] = message ? JavaLangStringObjForJSString(message) : new JNull();
initFrame.localVariables[2] = cause ? cause : new JNull();
initFrame.completionHandlers.push(function() {
e.state = JOBJ_STATE_INITIALIZED;
});
this.pushFrame(initFrame);
}
this.currentFQMethodName = function() {
let frame = this.stack[0];
if (!frame) {
return null;
}
return frame.method.class.name + "." + frame.method.name;
}
this.currentJavaLangThreadObject = function() {
if (!this.javaThreadObj) {
let klclass = ResolveClass("java.lang.Thread");
this.javaThreadObj = klclass.createInstance();
this.javaThreadObj.fieldValsByClass["java.lang.Thread"]["name"] = JavaLangStringObjForJSString("Thread-main");
this.javaThreadObj.fieldValsByClass["java.lang.Thread"]["priority"] = new JInt(1);
this.javaThreadObj.state = JOBJ_STATE_INITIALIZED;
klclass = ResolveClass("java.lang.ThreadGroup");
let threadGroup = klclass.createInstance();
threadGroup.fieldValsByClass["java.lang.ThreadGroup"]["name"] = JavaLangStringObjForJSString("system");
threadGroup.fieldValsByClass["java.lang.ThreadGroup"]["maxPriority"] = new JInt(10);
threadGroup.state = JOBJ_STATE_INITIALIZED;
this.javaThreadObj.fieldValsByClass["java.lang.Thread"]["group"] = threadGroup;
}
return this.javaThreadObj;
}
this.waitForIoRequest = function(ioRequest) {
this.pendingIoRequest = ioRequest;
this.state = KLTHREAD_STATE_WAITING;
}
this.completeIoRequest = function(ioRequest) {
if (!this.state == KLTHREAD_STATE_WAITING ||
this.pendingIoRequest != ioRequest) {
debugger;
}
this.state = KLTHREAD_STATE_RUNNING;
}
this.endThreadWithReason = function(reason) {
this.state = KLTHREAD_STATE_ENDED;
this.endReason = reason;
}
// Returns an array of objects with keys className, methodName, fileName, lineNumber
this.currentBacktrace = function() {
let stacktrace = [];
for (let i = 0; i < this.stack.length; i++) {
let frame = this.stack[i];
// Is there a line number table?
let lineNumbers = frame.method.lineNumbers;
let lineNumber = null;
if (lineNumbers) {
for (let j = 0; j < lineNumbers.length; j++) {
let lineEntry = lineNumbers[j];
if (lineEntry.start_pc > frame.pc) {
break;
}
lineNumber = lineEntry.line_number;
}
}
// Is there a source file name?
let sourceFileName = frame.method.class.sourceFileName();
let frameEntry = { "className": frame.method.class.name, "methodName": frame.method.name };
if (sourceFileName) {
frameEntry["fileName"] = sourceFileName;
}
if (lineNumber) {
frameEntry["lineNumber"] = lineNumber;
}
stacktrace.push(frameEntry);
}
return stacktrace;
}
this.exec = function(maxInstructions) {
if (this.state != KLTHREAD_STATE_RUNNING) {
debugger;
return;
}
this.state = KLTHREAD_STATE_RUNNING;
if (maxInstructions == undefined) { maxInstructions = 0; }
let instructionsExecuted = 0;
while (this.stack.length > 0 && (maxInstructions == 0 || instructionsExecuted < maxInstructions)) {
let frame = this.stack[0];
// If there's a pending exception in this frame, look for a handler for it at our current
// pc and either go there first, or continue down the stack.
if (frame.pendingException) {
let exception = frame.pendingException;
frame.pendingException = null;
let handlerPC = HandlerPcForException(frame.method.class, frame.pc, exception, frame.method.exceptions);
if (handlerPC >= 0) {
// We can handle this one. Blow away the stack and jump to the handler.
frame.pc = handlerPC;
frame.operandStack = [exception];
} else if (this.stack.length > 1) {
// Nope. Kaboom.
this.popFrame(true);
this.stack[0].pendingException = exception;
continue;
} else {
// Nowhere left to throw...
let jmessage = exception.fieldValsByClass["java.lang.Throwable"]["detailMessage"];
let message = (jmessage && !jmessage.isa.isNull()) ? JSStringFromJavaLangStringObj(jmessage) : "(unknown)";
KLLogInfo("JVM: Java thread terminated due to unhandled exception " + exception.class.name + ":\n\t" + message);
this.endThreadWithReason(KLTHREAD_END_REASON_EXCEPTION);
return;
}
}
// Are we at the top of a method? If so, a couple special cases are handled now:
// 1. If this method is part of a class which has not yet been initialized.
// 2. If this method is native and either has a bound implementation that is not bytecode or has no implementation.
if (frame.pc == 0) {
// If we are starting to execute a method contained in a class which is not yet initialized, then
// stop and initialize the class if appropriate. We check this first, because we'll need to do this
// whether or not the method itself has a native implementation.
let clinitFrame = CreateClassInitFrameIfNeeded(frame.method.class);
if (clinitFrame) {
frame.method.class.state = KLCLASS_STATE_INITIALIZING;
this.pushFrame(clinitFrame);
continue;
}
// console.log("Entering -> " + this.currentFQMethodName());
if (ShouldBreakOnMethodStart(this)) { debugger; }
if (AccessFlagIsSet(frame.method.access, ACC_SYNCHRONIZED)) {
// XXX: acquire method monitor.
}
// If this is a native method, either execute it or if not present, pretend it executed and returned
// some default value.
if ((frame.method.access & ACC_NATIVE) != 0 || frame.method.code == null) { // XXX the code==null condition just helps us with mock objects
// Check if this is a native method we don't support. If so, log it and return a default value.
if (frame.method.impl) {
// Marshal the thread context and arguments for the native implementation.
// First argument to an internal implementation is always the KLThreadContext, followed by the
// normal Java-land args for the method.
let implArgs = [this];
for (let i = 0; i < frame.localVariables.length; i++) {
implArgs.push(frame.localVariables[i]);
if (frame.localVariables[i].isa.isCategory2ComputationalType()) {
i++; // Drop the redundant long/double args from the native calls arg list.
}
}
let result = frame.method.impl.apply(null, implArgs);
// If this function changed the thread's state to waiting, by making an IO request, then return immediately
// leaving the state intact. The I/O's completion will re-enter this native method which should know what to
// do with the updated situation.
if (this.state == KLTHREAD_STATE_WAITING) {
return;
}
// Skip the epilog logic if the native impl either pushed another frame onto the stack (called another
// method) or threw an exception. In the former case, we will unwind back to this frame eventually and
// re-invoke the same method in full so the impl must be smart enough to know when to return.
if (this.stack[0] == frame && !frame.pendingException) {
// Pop this frame and result the result *unless* the native impl threw an exception.
this.popFrame();
if (!frame.method.descriptor.returnsVoid()) {
if (!result || !TypeIsAssignableToType(result.isa, frame.method.descriptor.returnType())) {
debugger;
}
this.stack[0].operandStack.push(result);
}
}
} else {
KLLogWarn("Eliding native method " + frame.method.class.name + "." + frame.method.name + " (desc: " + frame.method.descriptor.descriptorString() + ")");
let nativeFrame = this.popFrame();
if (!nativeFrame.method.descriptor.returnsVoid()) {
let returnType = nativeFrame.method.descriptor.returnType();
let defaultVal = DefaultValueForType(returnType);
this.stack[0].operandStack.push(defaultVal);
}
}
continue;
}
}
if (!frame.method.code) { debugger; }
// Verify that the pc is valid.
if (frame.pc < 0 || frame.pc >= frame.method.length) {
KLLogError("JVM: Error: pc " + pc + " invalid for method " + this.currentFQMethodName());
this.endThreadWithReason(KLTHREAD_END_REASON_VM_ERROR);
return;
}
// Fetch and execute the next instruction.
let opcode = frame.method.code[frame.pc];
// let str = Number(opcode).toString(16);
// str = str.length == 1 ? "0x0" + str : "0x" + str;
// console.log("opcode " + str);
if (ShouldBreakOnInstruction(this)) { debugger; }
let handler = this.instructionHandlers[opcode];
if (!handler) {
let str = Number(opcode).toString(16);
str = str.length == 1 ? "0x0" + str : "0x" + str;
alert("Unimplemented opcode " + str);
debugger;
}
handler(frame, opcode, this);
instructionsExecuted++;
}
if (this.stack.length == 0) {
this.endThreadWithReason(KLTHREAD_END_REASON_NORMAL);
}
}
//
// Construction
//
if (bootstrapMethod) {
let baseFrame = new KLStackFrame(bootstrapMethod);
if (bootstrapArgs) {
baseFrame.localVariables = bootstrapArgs.slice();
}
this.stack.push(baseFrame);
}
//
// INSTRUCTION HANDLING
//
//
// Exec helper snippets for instruction handling.
//
function IncrementPC(frame, count) {
frame.pc = frame.pc + count;
}
function U8FromInstruction(frame, offset) {
if (offset == undefined) offset = 1;
let code = frame.method.code;
let byte = code[frame.pc + offset];
return byte;
}
function S8FromInstruction(frame, offset) {
if (offset == undefined) offset = 1;
let code = frame.method.code;
let byte = code[frame.pc + offset];
if (byte > 127) { byte -= 256; }
return byte;
}
function U16FromInstruction(frame) {
let code = frame.method.code;
let high = code[frame.pc + 1];
let low = code[frame.pc + 2];
return ((high << 8) | low) >>> 0;
}
function S16FromInstruction(frame) {
let code = frame.method.code;
let high = code[frame.pc + 1];
let low = code[frame.pc + 2];
let sign = high & (1 << 7);
let x = (((high & 0xFF) << 8) | (low & 0xFF));
let s16 = sign ? (0xFFFF0000 | x) : x;
return s16;
}
function S32FromInstruction(frame, offset) {
let code = frame.method.code;
let one = code[frame.pc + offset];
let two = code[frame.pc + offset + 1];
let three = code[frame.pc + offset + 2];
let four = code[frame.pc + offset + 3];
let uval = ((one << 24 ) | (two << 16 ) | (three << 8 ) | four) >>> 0;
let sval;
if (uval > 2147483647) {
// Surely there's some better way of converting an unsigned value into its
// signed 32-bit equivalent...??
sval = uval - 0xFFFFFFFF - 1;
} else {
sval = uval;
}
return sval;
}
//
// Map of opcode values to handler functions. Each handler function takes a thread context,
// in which the active frame has a pc pointing to the beginning of the relevant instruction
// within the method's code stream. Handlers do not return a value. They are expected to
//
this.instructionHandlers = [];
this.instructionHandlers[INSTR_aconst_null] = function(frame) {
frame.operandStack.push(new JNull());
IncrementPC(frame, 1);
};
const instr_ldc = function(frame, opcode, thread) {
let instlen = ((opcode == INSTR_ldc) ? 2 : 3);
let index;
if (opcode == INSTR_ldc) {
index = U8FromInstruction(frame);
} else {
index = U16FromInstruction(frame);
}
let constref = frame.method.class.constantPool[index];
let val;
if (constref.tag == CONSTANT_Class) {
let className = frame.method.class.classNameFromUtf8Constant(constref.name_index);
let klclass = ResolveClass(className);
let jobj = JavaLangClassObjForClass(klclass);
let initFrame;
if (jobj.state != JOBJ_STATE_INITIALIZED && (initFrame = CreateObjInitFrameIfNeeded(jobj))) {
jobj.state = JOBJ_STATE_INITIALIZING;
initFrame.completionHandlers.push(function() {
jobj.state = JOBJ_STATE_INITIALIZED;
});
thread.pushFrame(initFrame);
return;
} else {
val = jobj;
}
} else {
val = frame.method.class.constantValueFromConstantPool(index);
}
if (val == undefined) {
debugger;
}
frame.operandStack.push(val);
IncrementPC(frame, instlen);
};
this.instructionHandlers[INSTR_ldc] = instr_ldc;
this.instructionHandlers[INSTR_ldc_w] = instr_ldc;
this.instructionHandlers[INSTR_ldc2_w] = function(frame, opcode, thread) {
index = U16FromInstruction(frame);
let val = frame.method.class.constantValueFromConstantPool(index);
if (val == undefined) {
debugger;
}
frame.operandStack.push(val);
IncrementPC(frame, 3);
}
this.instructionHandlers[INSTR_getstatic] = function(frame, opcode, thread) {
let index = U16FromInstruction(frame);
let fieldRef = frame.method.class.fieldReferenceFromIndex(index);
let field = ResolveFieldReference(fieldRef);
if (!field) {
thread.throwException("java.lang.IncompatibleClassChangeError", "Cannot resolve static field " + fieldRef.fieldName + " for class " + fieldRef.className);
return;
}
if (field.class.state != KLCLASS_STATE_INITIALIZED && (clinitFrame = CreateClassInitFrameIfNeeded(field.class))) {
field.class.state = KLCLASS_STATE_INITIALIZING;
thread.pushFrame(clinitFrame);
} else {
let fieldValue = field.class.fieldVals[fieldRef.fieldName];
if (!fieldValue) {
debugger;
}
frame.operandStack.push(fieldValue);
IncrementPC(frame, 3);
}
}
this.instructionHandlers[INSTR_putstatic] = function(frame, opcode, thread) {
let index = U16FromInstruction(frame);
let fieldRef = frame.method.class.fieldReferenceFromIndex(index);
let field = ResolveFieldReference(fieldRef);
if (!field) {
thread.throwException("java.lang.IncompatibleClassChangeError", "Cannot resolve static field " + fieldRef.fieldName + " for class " + fieldRef.className);
return;
}
// Is the class in which the field lives intialized yet?
if (field.class.state != KLCLASS_STATE_INITIALIZED && (clinitFrame = CreateClassInitFrameIfNeeded(field.class))) {
field.class.state = KLCLASS_STATE_INITIALIZING;
thread.pushFrame(clinitFrame);
} else {
let fieldValue = frame.operandStack.pop();
if (!fieldValue) {
debugger;
}
field.class.fieldVals[fieldRef.fieldName] = fieldValue;
IncrementPC(frame, 3);
}
}
this.instructionHandlers[INSTR_getfield] = function(frame) {
let index = U16FromInstruction(frame);
let fieldRef = frame.method.class.fieldReferenceFromIndex(index);
let field = ResolveFieldReference(fieldRef);
let objectref = frame.operandStack.pop();
if (!objectref.isa.isReferenceType()) {
debugger;
}
let value = objectref.fieldValsByClass[field.class.name][field.name];
if (!value || !TypeIsAssignableToType(value.isa, field.field.type)) {
// This is an extra check while VM is under development. This break indicates a bug in the VM logic,
// not a type-unsafe class file.
debugger;
}
frame.operandStack.push(value);
IncrementPC(frame, 3);
}
this.instructionHandlers[INSTR_putfield] = function(frame, opcode, thread) {
let index = U16FromInstruction(frame);
let fieldRef = frame.method.class.fieldReferenceFromIndex(index);
let field = ResolveFieldReference(fieldRef);
if ((field.access & ACC_STATIC) != 0) {
thread.throwException("java.lang.IncompatibleClassChangeError");
return;
}
if ((field.access & ACC_FINAL) != 0) {
if (fieldRef.className != frame.method.class.name ||
method.name != "<init>") {
thread.throwException("java.lang.IllegalAccessError");
}
}
let value = frame.operandStack.pop();
let objectref = frame.operandStack.pop();
if (!objectref.isa.isReferenceType()) {
debugger;
}
if (objectref.isa.isNull()) {
thread.throwException("java.lang.NullPointerException");
return;
}
if (!TypeIsAssignableToType(value.isa, field.field.type)) {
debugger;
}
objectref.fieldValsByClass[field.class.name][field.name] = value;
IncrementPC(frame, 3);
}
const instr_iconst_n = function(frame, opcode) {
let i = opcode - INSTR_iconst_0;
frame.operandStack.push(new JInt(i));
IncrementPC(frame, 1);
}
this.instructionHandlers[INSTR_iconst_m1] = instr_iconst_n;
this.instructionHandlers[INSTR_iconst_0] = instr_iconst_n;
this.instructionHandlers[INSTR_iconst_1] = instr_iconst_n;
this.instructionHandlers[INSTR_iconst_2] = instr_iconst_n;
this.instructionHandlers[INSTR_iconst_3] = instr_iconst_n;
this.instructionHandlers[INSTR_iconst_4] = instr_iconst_n;
this.instructionHandlers[INSTR_iconst_5] = instr_iconst_n;
const instr_lconst_l = function(frame, opcode) {
let val;
if (opcode == INSTR_lconst_0) {
val = KLInt64Zero;
} else {
val = new KLInt64([0, 0, 0, 0, 0, 0, 0, 1]); // == 1
}
frame.operandStack.push(new JLong(val));
IncrementPC(frame, 1);
}
this.instructionHandlers[INSTR_lconst_0] = instr_lconst_l;
this.instructionHandlers[INSTR_lconst_1] = instr_lconst_l;
const instr_fconst_f = function(frame, opcode) {
let f = opcode - INSTR_fconst_0;
frame.operandStack.push(new JFloat(f * 1.0));
IncrementPC(frame, 1);
}
this.instructionHandlers[INSTR_fconst_0] = instr_fconst_f;
this.instructionHandlers[INSTR_fconst_1] = instr_fconst_f;
this.instructionHandlers[INSTR_fconst_2] = instr_fconst_f;
const instr_dconst_d = function(frame, opcode) {
let d = opcode - INSTR_dconst_0;
frame.operandStack.push(new JDouble(d * 1.0));
IncrementPC(frame, 1);
}
this.instructionHandlers[INSTR_dconst_0] = instr_dconst_d;
this.instructionHandlers[INSTR_dconst_1] = instr_dconst_d;
this.instructionHandlers[INSTR_anewarray] = function(frame, opcode, thread) {
let index = U16FromInstruction(frame);
let constref = frame.method.class.constantPool[index];
let className = frame.method.class.classNameFromUtf8Constant(constref.name_index);
let arrayComponentClass = ResolveClass(className);
let count = frame.operandStack.pop();
if (!count.isa.isInt()) {
debugger;
}
let intCount = count.val;
if (intCount < 0) {
thread.throwException("NegativeArraySizeException");
return;
}
let arrayClass = CreateArrayClassWithAttributes(arrayComponentClass, 1);
let newarray = new JArray(arrayClass, intCount);
frame.operandStack.push(newarray);
IncrementPC(frame, 3);
}
this.instructionHandlers[INSTR_newarray] = function(frame, opcode, thread) {
let count = frame.operandStack.pop();
if (!count.isa.isInt()) {
debugger;
}
let intCount = count.val;
if (intCount < 0) {
thread.throwException("NegativeArraySizeException");
return;
}
let atype = U8FromInstruction(frame);
if (atype < 4 || atype > 11) {
debugger;
}
let jtype = JTypeFromJVMArrayType(atype);
let arrayClass = CreateArrayClassFromName("[" + jtype.descriptorString());
let arrayref = new JArray(arrayClass, intCount);
frame.operandStack.push(arrayref);
IncrementPC(frame, 2);
}
this.instructionHandlers[INSTR_new] = function(frame) {
let index = U16FromInstruction(frame);
let constref = frame.method.class.constantPool[index];
let className = frame.method.class.classNameFromUtf8Constant(constref.name_index);
let klclass = ResolveClass(className);
let jObj = klclass.createInstance();
frame.operandStack.push(jObj);
IncrementPC(frame, 3);
}
this.instructionHandlers[INSTR_dup] = function(frame) {
let value = frame.operandStack.pop();
if (!value.isa.isCategory1ComputationalType()) {
debugger;
}
frame.operandStack.push(value);
frame.operandStack.push(value);
IncrementPC(frame, 1);
}
this.instructionHandlers[INSTR_dup_x1] = function(frame) {
let value1 = frame.operandStack.pop();
let value2 = frame.operandStack.pop();
if (!value1.isa.isCategory1ComputationalType() || !value2.isa.isCategory1ComputationalType()) {
debugger;
}
frame.operandStack.push(value1);
frame.operandStack.push(value2);
frame.operandStack.push(value1);
IncrementPC(frame, 1);
}
this.instructionHandlers[INSTR_dup2] = function(frame) {
let value1 = frame.operandStack.pop();
if (value1.isa.isCategory2ComputationalType()) {
frame.operandStack.push(value1);
frame.operandStack.push(value1);
} else {
let value2 = frame.operandStack.pop();
if (!value2.isa.isCategory1ComputationalType()) {
debugger;
}
frame.operandStack.push(value2);
frame.operandStack.push(value1);
frame.operandStack.push(value2);
frame.operandStack.push(value1);
}
IncrementPC(frame, 1);
}
function PrepareArgumentsByRemovingFromStackForMethod(stack, method) {
let args = [];
let narg = method.descriptor.argumentCount();
// Walk backwards
for (let i = (narg-1); i >= 0; i--) {
let argType = method.descriptor.argumentTypeAtIndex(i);
if (stack.length < 1) {
return null;
}
let value = stack.pop();
if (!TypeIsAssignableToType(value.isa, argType)) {
debugger;
return null;
}
args.unshift(value);
// Longs and double get added twice,
if (argType.isCategory2ComputationalType()) {
args.unshift(value);
}
}
return args;
}
this.instructionHandlers[INSTR_invokestatic] = function(frame, opcode, thread) {
let index = U16FromInstruction(frame);
let methodRef = frame.method.class.methodReferenceFromIndex(index);
let method = ResolveMethodReference(methodRef, null); // what's the right class param here?
if (!AccessFlagIsSet(method.access, ACC_STATIC)) {
thread.throwException("java.lang.IncompatibleClassChangeError", "Expected method " + FullyQualifiedMethodName(method) + " to be static.");
return;
}
if (AccessFlagIsSet(method.access, ACC_NATIVE) && !method.impl) {
thread.throwException("java.lang.UnsatisfiedLinkError", "Static native method " + FullyQualifiedMethodName(method) + " not implemented.");
return;
}
args = PrepareArgumentsByRemovingFromStackForMethod(frame.operandStack, method);
if (args == null) {
debugger;
}
let childFrame = new KLStackFrame(method);
childFrame.localVariables = args;
IncrementPC(frame, 3);
thread.pushFrame(childFrame);
}
this.instructionHandlers[INSTR_invokevirtual] = function(frame, opcode, thread) {
let index = U16FromInstruction(frame);
let methodRef = frame.method.class.methodReferenceFromIndex(index);
let resolvedMethod = ResolveMethodReference(methodRef);
if (IsMethodSignaturePolymorphic(resolvedMethod)) {
// XXX We don't know how to do this yet.
debugger;
}
// Pull args off the stack based on the resolve method's descriptor, even if we end up selecting a
// different thing to actually invoke. We need to use *something* to determine the number of args to pull
// of the stack before we can get to the objectref, which we need to find the chosen method.
let args = PrepareArgumentsByRemovingFromStackForMethod(frame.operandStack, resolvedMethod);
if (args == null) { debugger; }
let objectref = frame.operandStack.pop();
if (objectref.isa.isNull()) {
thread.throwException("java.lang.NullPointerException", "Can't call method " + methodRef.className + "." + methodRef.methodName + " on null object.");
return;
}
args.unshift(objectref);
let classC = objectref.class;
let method = classC.vtableEntry(resolvedMethod.name, resolvedMethod.descriptor);
if (!method) {
let soleMaximallySpecifiedMethod = FindSoleMaximallySpecifiedSuperinterfaceMethod(resolvedMethod.name, resolvedMethod.descriptor);
if (!AccessFlagIsSet(soleMaximallySpecifiedMethod, ACC_ABSTRACT)) {
method = soleMaximallySpecifiedMethod;
}
}
if (AccessFlagIsSet(method.access, ACC_ABSTRACT)) {
thread.throwException("java.lang.AbstractMethodError", "Selected method is abstract and cannot be invoked");
return;
}
if (AccessFlagIsSet(method.access, ACC_NATIVE) && !method.impl) {
thread.throwException("java.lang.UnsatisfiedLinkError", "Native method " + FullyQualifiedMethodName(method) + " not implemented.");
return;
}
let childFrame = new KLStackFrame(method);
childFrame.localVariables = args;
IncrementPC(frame, 3);
thread.pushFrame(childFrame);
}
this.instructionHandlers[INSTR_invokespecial] = function(frame, opcode, thread) {
let index = U16FromInstruction(frame);
let methodRef = frame.method.class.methodReferenceFromIndex(index);
let resolvedMethod = ResolveMethodReference(methodRef);
// if (AccessFlagIsSet(method.access, ACC_PROTECTED) ...
let classC;
if (resolvedMethod.name != "<init>" &&
!resolvedMethod.class.isInterface() &&
IsClassASubclassOf(frame.method.class.name, resolvedMethod.class.name) &&
AccessFlagIsSet(frame.method.class.accessFlags, ACC_SUPER)) {
classC = frame.method.class.superclass;
} else {
classC = resolvedMethod.class;
}
let method = classC.vtableEntry(resolvedMethod.name, resolvedMethod.descriptor);
if (!method) {
let objectClass = ResolveClass("java.lang.Object");
let objectMethod = objectClass.vtableEntry(resolvedMethod.name, resolvedMethod.descriptor);
if (classC.isInterface() && objectMethod && AccessFlagIsSet(objectMethod.access, ACC_PUBLIC)) {
method = objectMethod;
}
}
if (!method) {
let soleMaximallySpecifiedMethod = FindSoleMaximallySpecifiedSuperinterfaceMethod(resolvedMethod.name, resolvedMethod.descriptor);
if (!AccessFlagIsSet(soleMaximallySpecifiedMethod, ACC_ABSTRACT)) {
method = soleMaximallySpecifiedMethod;
}
}
if (AccessFlagIsSet(method.access, ACC_ABSTRACT)) {
thread.throwException("java.lang.AbstractMethodError", "Selected method is abstract and cannot be invoked");
return;
}
if (AccessFlagIsSet(method.access, ACC_NATIVE) && !method.impl) {
thread.throwException("java.lang.UnsatisfiedLinkError", "Native method " + FullyQualifiedMethodName(method) + " not implemented.");
return;
}
let args = PrepareArgumentsByRemovingFromStackForMethod(frame.operandStack, method);
if (args == null) { debugger; }
let objectref = frame.operandStack.pop();
if (objectref.isa.isNull()) {
thread.throwException("java.lang.NullPointerException", "Can't call method " + methodRef.className + "." + methodRef.methodName + " on null object.");
return;
}
args.unshift(objectref);
let childFrame = new KLStackFrame(method);
childFrame.localVariables = args;
IncrementPC(frame, 3);
thread.pushFrame(childFrame);
}
this.instructionHandlers[INSTR_invokeinterface] = function(frame, opcode, thread) {
let index = U16FromInstruction(frame);
let count = U8FromInstruction(frame, 3);
let methodRef = frame.method.class.methodReferenceFromIndex(index);
if (!methodRef.isInterface) {
debugger;
}
let resolvedMethod = ResolveMethodReference(methodRef);
if (!resolvedMethod) {
thread.throwException("java.lang.AbstractMethodError");
return;
}
if (resolvedMethod.name == "<init>" || resolvedMethod.name == "<clinit>") {
debugger;
}
if (count == 0) {
debugger;
}
let args = PrepareArgumentsByRemovingFromStackForMethod(frame.operandStack, resolvedMethod);
if (args == null) {
debugger; // static type safety error or internal stack management error.
}
let objectref = frame.operandStack.pop();
if (objectref.isa.isNull()) {
thread.throwException("java.lang.NullPointerException");
return;
}
if (!objectref.isa.isReferenceType()) {
debugger;
}
let classC = objectref.class;
let method = classC.vtableEntry(resolvedMethod.name, resolvedMethod.descriptor);
if (!method) {
method = FindSoleMaximallySpecifiedSuperinterfaceMethod(resolvedMethod.name, resolvedMethod.descriptor);
}
if (!classC.implementsInterface(methodRef.className)) {
thread.throwException("java.lang.IncompatibleClassChangeError");
return;
}
if (!AccessFlagIsSet(method.access, ACC_PUBLIC)) {
thread.throwException("java.lang.IllegalAccessError");
return;
}
if (AccessFlagIsSet(method.access, ACC_ABSTRACT)) {
thread.throwException("java.lang.AbstractMethodError");
return;
}
if (AccessFlagIsSet(method.access, ACC_NATIVE) && !method.impl) {
thread.throwException("java.lang.UnsatisfiedLinkError", "Interface native method " + FullyQualifiedMethodName(method) + " not implemented.");
return;
}
args.unshift(objectref);
let childFrame = new KLStackFrame(method);
childFrame.localVariables = args;
IncrementPC(frame, 5);
thread.pushFrame(childFrame);
}
const instr_aload_n = function(frame, opcode) {
let n = opcode - INSTR_aload_0;
let objectref = frame.localVariables[n];
if (!objectref.isa.isReferenceType()) {
debugger;
}
frame.operandStack.push(objectref);
IncrementPC(frame, 1);
}
this.instructionHandlers[INSTR_aload_0] = instr_aload_n;
this.instructionHandlers[INSTR_aload_1] = instr_aload_n;
this.instructionHandlers[INSTR_aload_2] = instr_aload_n;
this.instructionHandlers[INSTR_aload_3] = instr_aload_n;
this.instructionHandlers[INSTR_return] = function(frame, opcode, thread) {
if (!frame.method.descriptor.returnsVoid()) {
debugger;
}
thread.popFrame();
}
this.instructionHandlers[INSTR_ireturn] = function(frame, opcode, thread) {
let returnType = frame.method.descriptor.returnType();
if (!returnType.isBoolean() && !returnType.isByte() && !returnType.isShort() && !returnType.isChar() && !returnType.isInt()) {
debugger;
}
let value = frame.operandStack.pop();
if (!value || !TypeIsAssignableToType(value.isa, returnType)) {
debugger;
}
thread.popFrame();
if (thread.stack.length > 0) {
thread.stack[0].operandStack.push(value);
} else {
thread.returnValue = value;
}
}
this.instructionHandlers[INSTR_areturn] = function(frame, opcode, thread) {
let objectref = frame.operandStack.pop();
if (!objectref || !objectref.isa.isReferenceType() || !TypeIsAssignableToType(objectref.isa, frame.method.descriptor.returnType())) {
debugger;
}
thread.popFrame();
if (thread.stack.length > 0) {
thread.stack[0].operandStack.push(objectref);
} else {
thread.returnValue = objectref;
}
}
this.instructionHandlers[INSTR_freturn] = function(frame, opcode, thread) {
let value = frame.operandStack.pop();
if (!value || !value.isa.isFloat() || !frame.method.descriptor.returnType() || !frame.method.descriptor.returnType().isFloat()) {
debugger;
}
thread.popFrame();
if (thread.stack.length > 0) {
thread.stack[0].operandStack.push(value);
} else {
thread.returnValue = value;
}
}
this.instructionHandlers[INSTR_dreturn] = function(frame, opcode, thread) {
let value = frame.operandStack.pop();
if (!value || !value.isa.isDouble() || !frame.method.descriptor.returnType() || !frame.method.descriptor.returnType().isDouble()) {
debugger;
}
thread.popFrame();
if (thread.stack.length > 0) {
thread.stack[0].operandStack.push(value);
} else {
thread.returnValue = value;
}
}
this.instructionHandlers[INSTR_lreturn] = function(frame, opcode, thread) {
let value = frame.operandStack.pop();
if (!value || !value.isa.isLong() || !frame.method.descriptor.returnType() || !frame.method.descriptor.returnType().isLong()) {
debugger;
}
thread.popFrame();
if (thread.stack.length > 0) {
thread.stack[0].operandStack.push(value);
} else {
thread.returnValue = value;
}
}
const instr_iload_n = function(frame, opcode) {
let n = opcode - INSTR_iload_0;
let value = frame.localVariables[n];
if (!value.isa.isInt()) {
debugger;
}
frame.operandStack.push(value);
IncrementPC(frame, 1);
}
this.instructionHandlers[INSTR_iload_0] = instr_iload_n;
this.instructionHandlers[INSTR_iload_1] = instr_iload_n;
this.instructionHandlers[INSTR_iload_2] = instr_iload_n;
this.instructionHandlers[INSTR_iload_3] = instr_iload_n;
const instr_lload_n = function(frame, opcode) {
let n = opcode - INSTR_lload_0;
let value = frame.localVariables[n];
if (!value.isa.isLong()) {
debugger;
}
frame.operandStack.push(value);
IncrementPC(frame, 1);
}
this.instructionHandlers[INSTR_lload_0] = instr_lload_n;
this.instructionHandlers[INSTR_lload_1] = instr_lload_n;
this.instructionHandlers[INSTR_lload_2] = instr_lload_n;
this.instructionHandlers[INSTR_lload_3] = instr_lload_n;
const instr_fload_n = function(frame, opcode) {
let n = opcode - INSTR_fload_0;
let value = frame.localVariables[n];
if (!value.isa.isFloat()) {
debugger;
}