This repository has been archived by the owner on Aug 20, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 46
/
int.ts
2334 lines (2191 loc) · 90.5 KB
/
int.ts
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
module J2ME {
declare var config;
import assert = Debug.assert;
import Bytecodes = Bytecode.Bytecodes;
import isInvoke = Bytecode.isInvoke;
import toHEX = IntegerUtilities.toHEX;
function toName(o) {
if (o instanceof MethodInfo) {
return "MI: " + o.implKey;
}
function getArrayInfo(o) {
var s = [];
var x = [];
for (var i = 0; i < Math.min(o.length, 8); i++) {
s.push(o[i]);
x.push(String.fromCharCode(o[i]));
}
var suffix = (o.length > 8 ? "..." : "");
return fromUTF8(o.classInfo.utf8Name) +
", length: " + o.length +
", values: [" + s.join(", ") + suffix + "]" +
", chars: \"" + x.join("") + suffix + "\"";
}
function getObjectInfo(o) {
if (o.length !== undefined) {
return getArrayInfo(o);
}
return fromUTF8(o.classInfo.utf8Name) + (o._address ? " " + toHEX(o._address) : "");
}
if (o && !o.classInfo) {
return o;
}
if (o && o.classInfo === CLASSES.java_lang_Class) {
return "[" + getObjectInfo(o) + "] " + classIdToClassInfoMap[o.vmClass].getClassNameSlow();
}
if (o && o.classInfo === CLASSES.java_lang_String) {
return "[" + getObjectInfo(o) + "] \"" + fromStringAddr(o._address) + "\"";
}
return o ? ("[" + getObjectInfo(o) + "]") : "null";
}
/**
* The number of opcodes executed thus far.
*/
export var bytecodeCount = 0;
/**
* The number of times the interpreter method was called thus far.
*/
export var interpreterCount = 0;
export var onStackReplacementCount = 0;
function wordsToDouble(l: number, h: number): number {
aliasedI32[0] = l;
aliasedI32[1] = h;
return aliasedF64[0];
}
/**
* Calling Convention:
*
* Interpreter -> Interpreter:
* This follows the JVM bytecode calling convention. This interpreter is highly
* optimized for this calling convention.
*
* Compiled / Native -> Compiled / Native:
* 64-bit floats and single word values can be encoded using only one JS value. However, 64-bit longs cannot and
* require a (low, high) JS value pair. For example, the signature: "foo.(IDJi)J" is expressed as:
*
* function foo(i, d, lowBits, highBits, i) {
* return tempReturn0 = highBits, lowBits;
* }
*
* Returning longs is equally problamatic, the convention is to return the lowBits, and save the highBits in a
* global |tempReturn0| variable.
*/
/*
* Stack Frame Layout:
*
* LP ---> +--------------------------------+
* | Parameter 0 |
* +--------------------------------+
* | ... |
* +--------------------------------+
* | Parameter (P-1) |
* +--------------------------------+
* | Non-Parameter Local 0 |
* +--------------------------------+
* | ... |
* +--------------------------------+
* | Non-Parameter Local (L-1) |
* FP ---> +--------------------------------+
* | Caller Return Address | // The opPC of the caller's invoke bytecode.
* +--------------------------------+
* | Caller FP |
* +--------------------------------+
* | Callee Method Info | Marker |
* +--------------------------------+
* | Monitor |
* +--------------------------------+
* | Stack slot 0 |
* +--------------------------------+
* | ... |
* +--------------------------------+
* | Stack slot (S-1) |
* SP ---> +--------------------------------+
*/
export enum FrameType {
/**
* Normal interpreter frame.
*/
Interpreter = 0x00000000,
/**
* Marks the beginning of a sequence of interpreter frames. If we see this
* frame when returning we need to exit the interpreter loop.
*/
ExitInterpreter = 0x10000000,
/**
* Native frames are pending and need to be pushed on the stack.
*/
PushPendingFrames = 0x20000000,
/**
* Marks the beginning of frames that were not invoked by the previous frame.
*/
Interrupt = 0x30000000,
/**
* Marks the beginning of native/compiled code called from the interpreter.
*/
Native = 0x40000000
}
export const enum FrameLayout {
/**
* Stored in the lower 28 bits.
*/
CalleeMethodInfoOffset = 2,
CalleeMethodInfoMask = 0x0FFFFFFF,
/**
* Stored in the upper 4 bits.
*/
FrameTypeOffset = 2,
FrameTypeMask = 0xF0000000,
CallerFPOffset = 1,
CallerRAOffset = 0,
MonitorOffset = 3,
CallerSaveSize = 4
}
export class FrameView {
public fp: number;
public sp: number;
public pc: number;
public thread: Thread;
constructor() {
}
set(thread: Thread, fp: number, sp: number, pc: number) {
this.thread = thread;
this.fp = fp;
this.sp = sp;
this.pc = pc;
if (!release) {
assert(fp >= (thread.tp >> 2), "Frame pointer is not less than than the top of the stack.");
assert(fp < (thread.tp + Constants.MAX_STACK_SIZE >> 2), "Frame pointer is not greater than the stack size.");
var callee = methodIdToMethodInfoMap[i32[this.fp + FrameLayout.CalleeMethodInfoOffset] & FrameLayout.CalleeMethodInfoMask];
assert(
!callee ||
callee instanceof MethodInfo,
"Callee @" + ((this.fp + FrameLayout.CalleeMethodInfoOffset) & FrameLayout.CalleeMethodInfoMask) + " is not a MethodInfo, " + toName(callee)
);
}
}
setParameter(kind: Kind, i: number, v: any) {
i32[this.fp + this.parameterOffset + i] = v;
}
setStackSlot(kind: Kind, i: number, v: any) {
switch (kind) {
case Kind.Reference:
case Kind.Int:
case Kind.Byte:
case Kind.Char:
case Kind.Short:
case Kind.Boolean:
i32[this.fp + FrameLayout.CallerSaveSize + i] = v;
break;
default:
release || assert(false, "Cannot set stack slot of kind: " + getKindName(kind));
}
}
get methodInfo(): MethodInfo {
return methodIdToMethodInfoMap[i32[this.fp + FrameLayout.CalleeMethodInfoOffset] & FrameLayout.CalleeMethodInfoMask];
}
get type(): FrameType {
return i32[this.fp + FrameLayout.FrameTypeOffset] & FrameLayout.FrameTypeMask;
}
set methodInfo(methodInfo: MethodInfo) {
i32[this.fp + FrameLayout.CalleeMethodInfoOffset] = (i32[this.fp + FrameLayout.FrameTypeOffset] & FrameLayout.FrameTypeMask) | methodInfo.id;
}
get parameterOffset() {
return this.methodInfo ? -this.methodInfo.codeAttribute.max_locals : 0;
}
get stackOffset(): number {
return FrameLayout.CallerSaveSize;
}
traceStack(writer: IndentingWriter, details: boolean = false) {
var fp = this.fp;
var sp = this.sp;
var pc = this.pc;
while (true) {
if (this.fp < (this.thread.tp >> 2)) {
writer.writeLn("Bad frame pointer FP: " + this.fp + " TOP: " + (this.thread.tp >> 2));
break;
}
this.trace(writer, details);
if (this.fp === (this.thread.tp >> 2)) {
break;
}
this.set(this.thread, i32[this.fp + FrameLayout.CallerFPOffset],
this.fp + this.parameterOffset,
i32[this.fp + FrameLayout.CallerRAOffset]);
}
this.fp = fp;
this.sp = sp;
this.pc = pc;
}
trace(writer: IndentingWriter, details: boolean = true) {
function toNumber(v) {
if (v < 0) {
return String(v);
} else if (v === 0) {
return " 0";
} else {
return "+" + v;
}
}
function clampString(v, n) {
if (v.length > n) {
return v.substring(0, n - 3) + "...";
}
return v;
}
var op = -1;
if (this.methodInfo) {
op = this.methodInfo.codeAttribute.code[this.pc];
}
var type = i32[this.fp + FrameLayout.FrameTypeOffset] & FrameLayout.FrameTypeMask;
writer.writeLn("Frame: " + FrameType[type] + " " + (this.methodInfo ? this.methodInfo.implKey : "null") + ", FP: " + this.fp + "(" + (this.fp - (this.thread.tp >> 2)) + "), SP: " + this.sp + ", PC: " + this.pc + (op >= 0 ? ", OP: " + Bytecode.getBytecodesName(op) : ""));
if (details) {
for (var i = Math.max(0, this.fp + this.parameterOffset); i < this.sp; i++) {
var prefix = " ";
if (i >= this.fp + this.stackOffset) {
prefix = "S" + (i - (this.fp + this.stackOffset)) + ": ";
} else if (i === this.fp + FrameLayout.CalleeMethodInfoOffset) {
prefix = "MI: ";
} else if (i === this.fp + FrameLayout.CallerFPOffset) {
prefix = "CF: ";
} else if (i === this.fp + FrameLayout.CallerRAOffset) {
prefix = "RA: ";
} else if (i === this.fp + FrameLayout.MonitorOffset) {
prefix = "MO: ";
} else if (i >= this.fp + this.parameterOffset) {
prefix = "L" + (i - (this.fp + this.parameterOffset)) + ": ";
}
writer.writeLn(" " + prefix.padRight(' ', 5) + " " + toNumber(i - this.fp).padLeft(' ', 3) + " " + String(i).padLeft(' ', 4) + " " + toHEX(i << 2) + ": " +
String(i32[i]).padLeft(' ', 12) + " " +
toHEX(i32[i]) + " " +
((i32[i] >= 32 && i32[i] < 1024) ? String.fromCharCode(i32[i]) : "?") + " " +
clampString(String(f32[i]), 12).padLeft(' ', 12) + " " +
clampString(String(wordsToDouble(i32[i], i32[i + 1])), 12).padLeft(' ', 12) + " ");
// XXX ref[i] could be an address, so update toName to handle that.
//toName(ref[i]));
}
}
}
}
export var interpreterCounter = new Metrics.Counter(true);
export class Thread {
/**
* Thread base pointer.
*/
tp: number;
/**
* Stack base pointer.
*/
bp: number
/**
* Current frame pointer.
*/
fp: number
/**
* Current stack pointer.
*/
sp: number
/**
* Current program counter.
*/
pc: number
nativeFrameCount: number;
/**
* Context associated with this thread.
*/
ctx: Context;
view: FrameView;
/**
* Stack of native frames seen during unwinding. These appear in reverse order. If a marker frame
* is seen during unwinding, a null value is also pushed on this stack to mark native frame ranges.
*/
unwoundNativeFrames: any [];
/**
* Stack of native frames to push on the stack.
*/
pendingNativeFrames: any [];
constructor(ctx: Context) {
this.tp = gcMalloc(Constants.MAX_STACK_SIZE);
this.bp = this.tp >> 2;
this.fp = this.bp;
this.sp = this.fp;
this.pc = -1;
this.view = new FrameView();
this.ctx = ctx;
this.unwoundNativeFrames = [];
this.pendingNativeFrames = [];
this.nativeFrameCount = 0;
release || threadWriter && threadWriter.writeLn("creatingThread: tp: " + toHEX(this.tp) + " " + toHEX(this.tp + Constants.MAX_STACK_SIZE));
}
set(fp: number, sp: number, pc: number) {
this.fp = fp;
this.sp = sp;
this.pc = pc;
}
hashFrame(): number {
var fp = this.fp << 2;
var sp = this.sp << 2;
return HashUtilities.hashBytesTo32BitsAdler(u8, fp, sp);
}
get frame(): FrameView {
this.view.set(this, this.fp, this.sp, this.pc);
return this.view;
}
pushMarkerFrame(frameType: FrameType) {
if (frameType === FrameType.Native) {
this.nativeFrameCount++;
}
this.pushFrame(null, 0, 0, null, frameType);
}
pushFrame(methodInfo: MethodInfo, sp: number = 0, pc: number = 0, monitorAddr: number = Constants.NULL, frameType: FrameType = FrameType.Interpreter) {
var fp = this.fp;
if (methodInfo) {
this.fp = this.sp + methodInfo.codeAttribute.max_locals;
} else {
this.fp = this.sp;
}
release || assert(fp < (this.tp + Constants.MAX_STACK_SIZE >> 2), "Frame pointer is not greater than the stack size.");
i32[this.fp + FrameLayout.CallerRAOffset] = this.pc; // Caller RA
i32[this.fp + FrameLayout.CallerFPOffset] = fp; // Caller FP
i32[this.fp + FrameLayout.CalleeMethodInfoOffset] = frameType | (methodInfo === null ? Constants.NULL : methodInfo.id); // Callee
i32[this.fp + FrameLayout.MonitorOffset] = monitorAddr; // Monitor
this.sp = this.fp + FrameLayout.CallerSaveSize + sp;
this.pc = pc;
}
popMarkerFrame(frameType: FrameType): MethodInfo {
if (frameType === FrameType.Native) {
this.nativeFrameCount--;
}
return this.popFrame(null, frameType);
}
popFrame(methodInfo: MethodInfo, frameType: FrameType = FrameType.Interpreter): MethodInfo {
var mi = methodIdToMethodInfoMap[i32[this.fp + FrameLayout.CalleeMethodInfoOffset] & FrameLayout.CalleeMethodInfoMask];
var type = i32[this.fp + FrameLayout.FrameTypeOffset] & FrameLayout.FrameTypeMask;
release || assert(mi === methodInfo && type === frameType, "mi === methodInfo && type === frameType");
this.pc = i32[this.fp + FrameLayout.CallerRAOffset];
var maxLocals = mi ? mi.codeAttribute.max_locals : 0;
this.sp = this.fp - maxLocals;
this.fp = i32[this.fp + FrameLayout.CallerFPOffset];
release || assert(this.fp >= (this.tp >> 2), "Valid frame pointer after pop.");
return methodIdToMethodInfoMap[i32[this.fp + FrameLayout.CalleeMethodInfoOffset] & FrameLayout.CalleeMethodInfoMask];
}
run() {
release || traceWriter && traceWriter.writeLn("Thread.run " + $.ctx.id);
return interpret(this);
}
exceptionUnwind(e: java.lang.Exception) {
release || traceWriter && traceWriter.writeLn("exceptionUnwind: " + toName(e));
var pc = -1;
var classInfo;
while (true) {
var frameType = i32[this.fp + FrameLayout.FrameTypeOffset] & FrameLayout.FrameTypeMask;
switch (frameType) {
case FrameType.Interpreter:
var mi = methodIdToMethodInfoMap[i32[this.fp + FrameLayout.CalleeMethodInfoOffset] & FrameLayout.CalleeMethodInfoMask];
release || traceWriter && traceWriter.writeLn("Looking for handler in: " + mi.implKey);
for (var i = 0; i < mi.exception_table_length; i++) {
var exceptionEntryView = mi.getExceptionEntryViewByIndex(i);
release || traceWriter && traceWriter.writeLn("Checking catch range: " + exceptionEntryView.start_pc + " - " + exceptionEntryView.end_pc);
if (this.pc >= exceptionEntryView.start_pc && this.pc < exceptionEntryView.end_pc) {
if (exceptionEntryView.catch_type === 0) {
pc = exceptionEntryView.handler_pc;
break;
} else {
classInfo = mi.classInfo.constantPool.resolveClass(exceptionEntryView.catch_type);
release || traceWriter && traceWriter.writeLn("Checking catch type: " + classInfo);
if (isAssignableTo(e.classInfo, classInfo)) {
pc = exceptionEntryView.handler_pc;
break;
}
}
}
}
if (pc >= 0) {
this.pc = pc;
this.sp = this.fp + FrameLayout.CallerSaveSize;
release || assert(e instanceof Object && "_address" in e, "exception is object with address");
i32[this.sp++] = e._address;
return;
}
if (mi.isSynchronized) {
this.ctx.monitorExit(getMonitor(i32[this.fp + FrameLayout.MonitorOffset]));
}
this.popFrame(mi);
release || traceWriter && traceWriter.outdent();
release || traceWriter && traceWriter.writeLn("<< I Unwind");
break;
case FrameType.ExitInterpreter:
this.popMarkerFrame(FrameType.ExitInterpreter);
throw e;
case FrameType.PushPendingFrames:
this.frame.thread.pushPendingNativeFrames();
break;
case FrameType.Interrupt:
this.popMarkerFrame(FrameType.Interrupt);
break;
case FrameType.Native:
this.popMarkerFrame(FrameType.Native);
break;
default:
Debug.assertUnreachable("Unhandled frame type: " + frameType);
break;
}
}
}
classInitAndUnwindCheck(fp: number, sp: number, pc: number, classInfo: ClassInfo) {
this.set(fp, sp, pc);
classInitCheck(classInfo);
}
throwException(fp: number, sp: number, pc: number, type: ExceptionType, a?) {
this.set(fp, sp, pc);
switch (type) {
case ExceptionType.ArrayIndexOutOfBoundsException:
throwArrayIndexOutOfBoundsException(a);
break;
case ExceptionType.ArithmeticException:
throwArithmeticException();
break;
case ExceptionType.NegativeArraySizeException:
throwNegativeArraySizeException();
break;
case ExceptionType.NullPointerException:
throwNullPointerException();
break;
}
}
tracePendingFrames(writer: IndentingWriter) {
for (var i = 0; i < this.pendingNativeFrames.length; i++) {
var pendingFrame = this.pendingNativeFrames[i];
writer.writeLn(pendingFrame ? methodIdToMethodInfoMap[i32[pendingFrame + BailoutFrameLayout.MethodIdOffset >> 2]].implKey : "-marker-");
}
}
pushPendingNativeFrames() {
traceWriter && traceWriter.writeLn("Pushing pending native frames.");
if (traceWriter) {
traceWriter.enter("Pending native frames before:");
this.tracePendingFrames(traceWriter);
traceWriter.leave("");
traceWriter.enter("Stack before:");
this.frame.traceStack(traceWriter);
traceWriter.leave("");
}
while (true) {
// We should have a |PushPendingFrames| marker frame on the stack at this point.
this.popMarkerFrame(FrameType.PushPendingFrames);
var pendingNativeFrameAddress = null;
var frames = [];
while (pendingNativeFrameAddress = this.pendingNativeFrames.pop()) {
frames.push(pendingNativeFrameAddress);
}
while (pendingNativeFrameAddress = frames.pop()) {
var methodInfo = methodIdToMethodInfoMap[i32[pendingNativeFrameAddress + BailoutFrameLayout.MethodIdOffset >> 2]];
var stackCount = i32[pendingNativeFrameAddress + BailoutFrameLayout.StackCountOffset >> 2];
var localCount = i32[pendingNativeFrameAddress + BailoutFrameLayout.LocalCountOffset >> 2];
var pc = i32[pendingNativeFrameAddress + BailoutFrameLayout.PCOffset >> 2];
var lockObjectAddress = i32[pendingNativeFrameAddress + BailoutFrameLayout.LockOffset >> 2];
traceWriter && traceWriter.writeLn("Pushing frame: " + methodInfo.implKey);
this.pushFrame(methodInfo, stackCount, pc, lockObjectAddress);
var frame = this.frame;
for (var j = 0; j < localCount; j++) {
var value = i32[(pendingNativeFrameAddress + BailoutFrameLayout.HeaderSize >> 2) + j];
frame.setParameter(Kind.Int, j, value);
}
for (var j = 0; j < stackCount; j++) {
var value = i32[(pendingNativeFrameAddress + BailoutFrameLayout.HeaderSize >> 2) + j + localCount];
frame.setStackSlot(Kind.Int, j, value);
}
ASM._gcFree(pendingNativeFrameAddress);
}
var frameType = i32[this.fp + FrameLayout.FrameTypeOffset] & FrameLayout.FrameTypeMask;
if (frameType === FrameType.PushPendingFrames) {
continue;
}
break;
}
if (traceWriter) {
traceWriter.enter("Pending native frames after:");
this.tracePendingFrames(traceWriter);
traceWriter.leave("");
traceWriter.enter("Stack after:");
this.frame.traceStack(traceWriter);
traceWriter.leave("");
}
}
/**
* Called when unwinding begins.
*/
beginUnwind() {
// The |unwoundNativeFrames| stack should be empty at this point.
release || assert(this.unwoundNativeFrames.length === 0, "0 unwound native frames");
}
/*
* Called when unwinding ends.
*
* x: Interpreter Frame
* x': Compiler Frame
* -: Skip Frame
* +: Push Pending Frames
* /: null
*
*
* Suppose you have the following logical call stack: a, b, c, d', e', -, f, g, h', i', -, j, k. The physical call
* stack doesn't have any of the native frames on it: a, b, c, -, f, g, -, j, k, so when we resume we need to
* make sure that native frames are accounted for. During unwinding, we save the state of native frames in the
* |unwoundNativeFrames| array. In order to keep track of how native frames interleave with interpreter frames we
* insert null markers in the |unwoundNativeFrames| array. So in this example, the array will be: /, i', h', /,
* e', d'. When we resume in the interpreter, our call stack is: a, b, c, +, f, g, +, j, k. During unwinding, the
* skip marker frames have been converted to push pending frames. These indicate to the interpreter that some native
* frames should be pushed on the stack. When we return from j, we need to push h and i. Similarly, when we return
* from f, we need to push d and e. After unwiding is complete, all elements in |unwoundNativeFrames| are poped and
* pushed into the |pendingNativeFrames| which keeps track of the native frames that need to be pushed once a
* push pending prame marker is observed. In this case |pendingNativeFrames| is: d', e', /, h', i', /. When we return
* from j and see the first push pending frames marker, we look for the last set of frames in the |pendingNativeFrames|
* list and push those on the stack.
*
*
* Before every unwind, the |unwoundNativeFrames| list must be empty. However, the |pendingNativeFrames| list may
* have unprocessed frames in it. This can happen if after resuming and returning from j, we call some native code
* that unwinds. Luckily, all new native frames must be further down on the stack than the current frames in the
* |pendingNativeFrames| list, so we can just push them at the end.
*
* TODO: Do a better job explaining all this.
*/
endUnwind() {
var unwound = this.unwoundNativeFrames;
var pending = this.pendingNativeFrames;
while (unwound.length) {
pending.push(unwound.pop());
}
// Garbage collection is disabled during compiled code which can lead to OOM's if
// we consistently stay in compiled code. Most code unwinds often enough that we can
// force collection here since at the end of an unwind all frames are
// stored back on the heap.
ASM._collectALittle();
}
/**
* Walks the stack from the current fp to find the frame that will return
* to the removeFP and make it instead return to the newCallerFP.
*/
removeFrame(removeFP: number, newCallerFP: number, newCallerPC: number) {
var fp = this.fp;
release || assert(fp !== removeFP, "Cannot remove current fp.");
while ((i32[fp + FrameLayout.CallerFPOffset]) !== removeFP) {
fp = i32[fp + FrameLayout.CallerFPOffset];
}
release || assert(i32[fp + FrameLayout.CallerFPOffset] === removeFP, "Did not find the frame to remove.");
i32[fp + FrameLayout.CallerFPOffset] = newCallerFP;
i32[fp + FrameLayout.CallerRAOffset] = newCallerPC;
}
}
export function prepareInterpretedMethod(methodInfo: MethodInfo): Function {
var method = function fastInterpreterFrameAdapter() {
runtimeCounter && runtimeCounter.count("fastInterpreterFrameAdapter");
var calleeStats = methodInfo.stats;
calleeStats.interpreterCallCount++;
if (config.forceRuntimeCompilation ||
calleeStats.interpreterCallCount + calleeStats.backwardsBranchCount > ConfigThresholds.InvokeThreshold) {
compileAndLinkMethod(methodInfo);
if (methodInfo.state === MethodState.Compiled) {
return methodInfo.fn.apply(null, arguments);
}
}
var ctx = $.ctx;
var thread = ctx.nativeThread;
var callerFP = thread.fp;
var callerPC = thread.pc;
// release || traceWriter && traceWriter.writeLn(">> I");
thread.pushMarkerFrame(FrameType.ExitInterpreter);
var exitFP = thread.fp;
thread.pushFrame(methodInfo);
var calleeFP = thread.fp;
var frame = thread.frame;
var kinds = methodInfo.signatureKinds;
var index = 0;
if (!methodInfo.isStatic) {
frame.setParameter(Kind.Reference, index++, arguments[0]);
}
for (var i = 1, j = 1; i < kinds.length; i++) {
frame.setParameter(kinds[i], index++, arguments[j++]);
if (isTwoSlot(kinds[i])) {
frame.setParameter(kinds[i], index++, arguments[j++]);
}
}
if (methodInfo.isSynchronized) {
var monitorAddr = methodInfo.isStatic ? $.getClassObjectAddress(methodInfo.classInfo) : arguments[0];
i32[calleeFP + FrameLayout.MonitorOffset] = monitorAddr;
$.ctx.monitorEnter(getMonitor(monitorAddr));
release || assert(U !== VMState.Yielding, "Monitors should never yield.");
if (U === VMState.Pausing || U === VMState.Stopping) {
// Splice out the marker frame so the interpreter doesn't return early when execution is resumed.
// The simple solution of using the calleeFP to splice the frame cannot be used since the frame
// stack may have changed if an OSR occurred.
thread.removeFrame(exitFP, callerFP, callerPC);
return;
}
}
var v = interpret(thread);
if (U) {
// Splice out the marker frame so the interpreter doesn't return early when execution is resumed.
// The simple solution of using the calleeFP to splice the frame cannot be used since the frame
// stack may have changed if an OSR occurred.
thread.removeFrame(exitFP, callerFP, callerPC);
return;
}
thread.popMarkerFrame(FrameType.ExitInterpreter);
release || assert(callerFP === thread.fp, "callerFP === thread.fp");
// release || traceWriter && traceWriter.writeLn("<< I");
return v;
};
return method;
}
var args = new Array(16);
export const enum ExceptionType {
ArithmeticException,
ArrayIndexOutOfBoundsException,
NegativeArraySizeException,
NullPointerException
}
/**
* Debugging helper to make sure native methods were implemented correctly.
*/
function checkReturnValue(methodInfo: MethodInfo, l: any, h: number) {
if (U) {
if (typeof l !== "undefined") {
assert(false, "Expected undefined return value during unwind, got " + l + " in " + methodInfo.implKey);
}
return;
}
if (!(getKindCheck(methodInfo.returnKind)(l, h))) {
assert(false, "Expected " + getKindName(methodInfo.returnKind) + " return value, got low: " + l + " high: " + h + " in " + methodInfo.implKey);
}
}
/**
* Main interpreter loop. This method is carefully written to avoid memory allocation and
* function calls on fast paths. Therefore, everything is inlined, even if it makes the code
* look ugly.
*
* The interpreter loop caches the thread state in local variables. Doing so avoids a lot of
* property accesses but also makes the code brittle since you need to manually sync up the
* thread state with the local thead state at precise points.
*
* At call sites, caller frame |pc|s are always at the beggining of invoke bytecodes. In the
* interpreter return bytecodes advance the pc past the invoke bytecode. Native code that
* unwinds and resumes execution at a later point needs to adjust the pc accordingly.
*
* Bytecodes that construct exception objects must save the tread state before executing any
* code that may overwrite the frame. Use the |throwException| helper method to ensure that
* the thread state is property saved.
*/
export function interpret(thread: Thread) {
release || interpreterCount ++;
var frame = thread.frame;
// Special case where a |PushPendingFrames| marker is on top of the stack. This happens when
// native code is on top of the stack.
if (frame.type === FrameType.PushPendingFrames) {
thread.pushPendingNativeFrames();
frame = thread.frame;
}
release || assert(frame.type === FrameType.Interpreter, "Must begin with interpreter frame.");
var mi = frame.methodInfo;
release || assert(mi, "Must have method info.");
mi.stats.interpreterCallCount++;
if (config.forceRuntimeCompilation || (mi.state === MethodState.Cold &&
mi.stats.interpreterCallCount + mi.stats.backwardsBranchCount > ConfigThresholds.InvokeThreshold)) {
compileAndLinkMethod(mi);
// TODO call the compiled method.
}
var maxLocals = mi.codeAttribute.max_locals;
var ci = mi.classInfo;
var cp = ci.constantPool;
var code = mi ? mi.codeAttribute.code : null;
var fp = thread.fp | 0;
var lp = fp - maxLocals | 0;
var sp = thread.sp | 0;
var opPC = 0, pc = thread.pc | 0;
var tag: TAGS;
var type, size;
var value, index, arrayAddr: number, offset, buffer, tag: TAGS, targetPC, jumpOffset;
var address = 0, isStatic = false;
var ia = 0, ib = 0; // Integer Operands
var ll = 0, lh = 0; // Long Low / High
var classInfo: ClassInfo;
var otherClassInfo: ClassInfo;
var fieldInfo: FieldInfo;
var monitorAddr: number;
// HEAD
var lastPC = 0;
while (true) {
opPC = pc, op = code[pc], pc = pc + 1 | 0;
lastPC = opPC;
if (!release) {
assert(code === mi.codeAttribute.code, "Bad Code.");
assert(ci === mi.classInfo, "Bad Class Info.");
assert(cp === ci.constantPool, "Bad Constant Pool.");
assert(lp === fp - mi.codeAttribute.max_locals, "Bad lp.");
assert(fp >= (thread.tp >> 2), "Frame pointer is not less than than the top of the stack.");
assert(fp < (thread.tp + Constants.MAX_STACK_SIZE >> 2), "Frame pointer is not greater than the stack size.");
bytecodeCount++;
if (traceStackWriter) {
frame.set(thread, fp, sp, opPC); frame.trace(traceStackWriter);
traceStackWriter.writeLn();
traceStackWriter.greenLn(mi.implKey + ": PC: " + opPC + ", FP: " + fp + ", " + Bytecode.getBytecodesName(op));
}
}
try {
switch (op) {
case Bytecodes.NOP:
continue;
case Bytecodes.ACONST_NULL:
i32[sp] = Constants.NULL;
sp = sp + 1 | 0;
continue;
case Bytecodes.ICONST_M1:
case Bytecodes.ICONST_0:
case Bytecodes.ICONST_1:
case Bytecodes.ICONST_2:
case Bytecodes.ICONST_3:
case Bytecodes.ICONST_4:
case Bytecodes.ICONST_5:
i32[sp] = op - Bytecodes.ICONST_0 | 0;
sp = sp + 1 | 0;
continue;
case Bytecodes.FCONST_0:
case Bytecodes.FCONST_1:
case Bytecodes.FCONST_2:
f32[sp] = op - Bytecodes.FCONST_0 | 0;
sp = sp + 1 | 0;
continue;
case Bytecodes.DCONST_0:
i32[sp] = 0;
sp = sp + 1 | 0;
i32[sp] = 0;
sp = sp + 1 | 0;
continue;
case Bytecodes.DCONST_1:
i32[sp] = 0;
sp = sp + 1 | 0;
i32[sp] = 1072693248;
sp = sp + 1 | 0;
continue;
case Bytecodes.LCONST_0:
case Bytecodes.LCONST_1:
i32[sp] = op - Bytecodes.LCONST_0 | 0;
sp = sp + 1 | 0;
i32[sp] = 0;
sp = sp + 1 | 0;
continue;
case Bytecodes.BIPUSH:
i32[sp] = code[pc] << 24 >> 24;
sp = sp + 1 | 0;
pc = pc + 1 | 0;
continue;
case Bytecodes.SIPUSH:
i32[sp] = (code[pc] << 8 | code[pc + 1 | 0]) << 16 >> 16;
sp = sp + 1 | 0;
pc = pc + 2 | 0;
continue;
case Bytecodes.LDC:
case Bytecodes.LDC_W:
index = (op === Bytecodes.LDC) ? code[pc++] : code[pc++] << 8 | code[pc++];
offset = cp.entries[index];
buffer = cp.buffer;
tag = buffer[offset++];
if (tag === TAGS.CONSTANT_Integer || tag === TAGS.CONSTANT_Float) {
i32[sp++] = buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++];
} else if (tag === TAGS.CONSTANT_String) {
i32[sp++] = cp.resolve(index, tag, false);
} else {
release || assert(false, getTAGSName(tag));
}
continue;
case Bytecodes.LDC2_W:
index = code[pc++] << 8 | code[pc++];
offset = cp.entries[index];
buffer = cp.buffer;
tag = buffer[offset++];
if (tag === TAGS.CONSTANT_Long || tag === TAGS.CONSTANT_Double) {
i32[sp + 1] = buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++];
i32[sp ] = buffer[offset++] << 24 | buffer[offset++] << 16 | buffer[offset++] << 8 | buffer[offset++];
sp += 2;
} else {
release || assert(false, getTAGSName(tag));
}
continue;
case Bytecodes.ILOAD:
case Bytecodes.FLOAD:
case Bytecodes.ALOAD:
i32[sp] = i32[lp + code[pc] | 0];
sp = sp + 1 | 0;
pc = pc + 1 | 0;
continue;
case Bytecodes.LLOAD:
case Bytecodes.DLOAD:
offset = lp + code[pc] | 0;
i32[sp] = i32[offset];
i32[sp + 1 | 0] = i32[offset + 1 | 0];
sp = sp + 2 | 0;
pc = pc + 1 | 0;
continue;
case Bytecodes.ILOAD_0:
case Bytecodes.ILOAD_1:
case Bytecodes.ILOAD_2:
case Bytecodes.ILOAD_3:
i32[sp] = i32[(lp + op | 0) - Bytecodes.ILOAD_0 | 0];
sp = sp + 1 | 0;
continue;
case Bytecodes.FLOAD_0:
case Bytecodes.FLOAD_1:
case Bytecodes.FLOAD_2:
case Bytecodes.FLOAD_3:
i32[sp] = i32[(lp + op | 0) - Bytecodes.FLOAD_0 | 0];
sp = sp + 1 | 0;
continue;
case Bytecodes.ALOAD_0:
case Bytecodes.ALOAD_1:
case Bytecodes.ALOAD_2:
case Bytecodes.ALOAD_3:
i32[sp] = i32[(lp + op | 0) - Bytecodes.ALOAD_0 | 0];
sp = sp + 1 | 0;
continue;
case Bytecodes.LLOAD_0:
case Bytecodes.LLOAD_1:
case Bytecodes.LLOAD_2:
case Bytecodes.LLOAD_3:
offset = (lp + op | 0) - Bytecodes.LLOAD_0 | 0;
i32[sp] = i32[offset];
i32[sp + 1 | 0] = i32[offset + 1 | 0];
sp = sp + 2 | 0;
continue;
case Bytecodes.DLOAD_0:
case Bytecodes.DLOAD_1:
case Bytecodes.DLOAD_2:
case Bytecodes.DLOAD_3:
offset = (lp + op | 0) - Bytecodes.DLOAD_0 | 0;
i32[sp] = i32[offset];
i32[sp + 1 | 0] = i32[offset + 1 | 0];
sp = sp + 2 | 0;
continue;
case Bytecodes.IALOAD:
case Bytecodes.FALOAD:
index = i32[--sp];
arrayAddr = i32[--sp];
if ((index >>> 0) >= (i32[arrayAddr + Constants.ARRAY_LENGTH_OFFSET >> 2] >>> 0)) {
thread.throwException(fp, sp, opPC, ExceptionType.ArrayIndexOutOfBoundsException, index);
}
i32[sp++] = i32[(arrayAddr + Constants.ARRAY_HDR_SIZE >> 2) + index];
continue;
case Bytecodes.BALOAD:
index = i32[--sp];
arrayAddr = i32[--sp];
if ((index >>> 0) >= (i32[arrayAddr + Constants.ARRAY_LENGTH_OFFSET >> 2] >>> 0)) {
thread.throwException(fp, sp, opPC, ExceptionType.ArrayIndexOutOfBoundsException, index);
}
i32[sp++] = i8[arrayAddr + Constants.ARRAY_HDR_SIZE + index];
continue;
case Bytecodes.CALOAD:
index = i32[--sp];
arrayAddr = i32[--sp];
if ((index >>> 0) >= (i32[arrayAddr + Constants.ARRAY_LENGTH_OFFSET >> 2] >>> 0)) {
thread.throwException(fp, sp, opPC, ExceptionType.ArrayIndexOutOfBoundsException, index);
}
i32[sp++] = u16[(arrayAddr + Constants.ARRAY_HDR_SIZE >> 1) + index];
continue;
case Bytecodes.SALOAD:
index = i32[--sp];
arrayAddr = i32[--sp];
if ((index >>> 0) >= (i32[arrayAddr + Constants.ARRAY_LENGTH_OFFSET >> 2] >>> 0)) {
thread.throwException(fp, sp, opPC, ExceptionType.ArrayIndexOutOfBoundsException, index);
}
i32[sp++] = i16[(arrayAddr + Constants.ARRAY_HDR_SIZE >> 1) + index];
continue;
case Bytecodes.AALOAD:
index = i32[--sp];
arrayAddr = i32[--sp];
if (arrayAddr === Constants.NULL) {
thread.throwException(fp, sp, opPC, ExceptionType.NullPointerException);
continue;
}
if ((index >>> 0) >= (i32[arrayAddr + Constants.ARRAY_LENGTH_OFFSET >> 2] >>> 0)) {
thread.throwException(fp, sp, opPC, ExceptionType.ArrayIndexOutOfBoundsException, index);
}
i32[sp++] = i32[(arrayAddr + Constants.ARRAY_HDR_SIZE >> 2) + index];
continue;
case Bytecodes.ISTORE:
case Bytecodes.FSTORE:
case Bytecodes.ASTORE:
sp = sp - 1 | 0;