Skip to content

Commit cf6854f

Browse files
authored
Fix class initialization and bytecode edge cases (#22)
1 parent 03bb1cd commit cf6854f

7 files changed

Lines changed: 135 additions & 9 deletions

File tree

‎src/interp.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// Bytecode interpreter and the per-thread run loop.
22

33
import {
4-
INITIALIZED, JArray, JClass, JMethod, JObject, isWide, newArrayData,
4+
INITIALIZED, JArray, JClass, JMethod, JObject, isWide, longToFloat, newArrayData,
55
} from "./runtime.ts";
66
import {
77
Frame, JThread, JavaThrow, NativeFrame, PendingThrow, RUNNABLE, TERMINATED, WAITING, fromNative,
@@ -149,9 +149,12 @@ export function interpret(t: JThread, f: Frame, budget: number): number {
149149
case 0x47: case 0x48: case 0x49: case 0x4a: sp -= 2; locals[code[pc] - 0x47] = stack[sp]; pc++; break;
150150
case 0x4b: case 0x4c: case 0x4d: case 0x4e: locals[code[pc] - 0x4b] = stack[--sp]; pc++; break;
151151
// array stores
152-
case 0x4f: case 0x51: case 0x54: case 0x55: case 0x56:
152+
case 0x4f: case 0x51: case 0x55: case 0x56:
153153
v = stack[--sp]; idx = stack[--sp]; o = stack[--sp];
154154
arr(o, idx)[idx] = v; pc++; break;
155+
case 0x54:
156+
v = stack[--sp]; idx = stack[--sp]; o = stack[--sp];
157+
arr(o, idx)[idx] = o!.cls.name === "[Z" ? v & 1 : v; pc++; break;
155158
case 0x50: case 0x52:
156159
sp -= 2; v = stack[sp]; idx = stack[--sp]; o = stack[--sp];
157160
arr(o, idx)[idx] = v; pc++; break;
@@ -230,7 +233,7 @@ export function interpret(t: JThread, f: Frame, budget: number): number {
230233
case 0x86: stack[sp - 1] = Math.fround(stack[sp - 1]); pc++; break;
231234
case 0x87: stack[sp++] = undefined; pc++; break;
232235
case 0x88: sp--; stack[sp - 1] = Number(BigInt.asIntN(32, stack[sp - 1])); pc++; break;
233-
case 0x89: sp--; stack[sp - 1] = Math.fround(Number(stack[sp - 1])); pc++; break;
236+
case 0x89: sp--; stack[sp - 1] = longToFloat(stack[sp - 1]); pc++; break;
234237
case 0x8a: stack[sp - 2] = Number(stack[sp - 2]); pc++; break;
235238
case 0x8b: stack[sp - 1] = f2i(stack[sp - 1]); pc++; break;
236239
case 0x8c: stack[sp - 1] = f2l(stack[sp - 1]); stack[sp++] = undefined; pc++; break;

‎src/jit.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
import { Tag, utf8 } from "./classfile.ts";
1818
import {
19-
ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, newArrayData, parseMethodDesc,
19+
ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc,
2020
} from "./runtime.ts";
2121
import { memberTarget } from "./natives/invoke.ts";
2222
import { concatStrings } from "./natives/strings.ts";
@@ -223,6 +223,7 @@ const runtime = {
223223
},
224224
PUSHED,
225225
INTERPRET,
226+
longToFloat,
226227
npe: npeAt,
227228
arr(o: JArray | null, i: number, pc?: number): any {
228229
if (o === null) throw at(new PendingThrow("java/lang/NullPointerException"), pc);
@@ -744,9 +745,12 @@ function insn(g: Gen, b: Body, pc: number) {
744745
case 0x43: case 0x44: case 0x45: case 0x46: emit(`${L(op - 0x43)}=${top()};`); break;
745746
case 0x47: case 0x48: case 0x49: case 0x4a: emit(`${L(op - 0x47)}=${top(1)};`); break;
746747
case 0x4b: case 0x4c: case 0x4d: case 0x4e: emit(`${L(op - 0x4b)}=${top()};`); break;
747-
case 0x4f: case 0x51: case 0x54: case 0x55: case 0x56:
748+
case 0x4f: case 0x51: case 0x55: case 0x56:
748749
emit(`if(${top(2)}===null)rt.npe(${pc});a=${top(2)}.a;if(${top(1)}>>>0>=a.length)rt.arr(${top(2)},${top(1)},${pc});a[${top(1)}]=${top()};`);
749750
break;
751+
case 0x54:
752+
emit(`if(${top(2)}===null)rt.npe(${pc});a=${top(2)}.a;if(${top(1)}>>>0>=a.length)rt.arr(${top(2)},${top(1)},${pc});a[${top(1)}]=${top(2)}.cls.name==="[Z"?${top()}&1:${top()};`);
753+
break;
750754
case 0x50: case 0x52:
751755
emit(`if(${top(3)}===null)rt.npe(${pc});a=${top(3)}.a;if(${top(2)}>>>0>=a.length)rt.arr(${top(3)},${top(2)},${pc});a[${top(2)}]=${top(1)};`);
752756
break;
@@ -800,7 +804,7 @@ function insn(g: Gen, b: Body, pc: number) {
800804
case 0x86: emit(`${top()}=Math.fround(${top()});`); break;
801805
case 0x87: break;
802806
case 0x88: emit(`${top(1)}=Number(BigInt.asIntN(32,${top(1)}));`); break;
803-
case 0x89: emit(`${top(1)}=Math.fround(Number(${top(1)}));`); break;
807+
case 0x89: emit(`${top(1)}=rt.longToFloat(${top(1)});`); break;
804808
case 0x8a: emit(`${top(1)}=Number(${top(1)});`); break;
805809
case 0x8b: emit(`${top()}=rt.f2i(${top()});`); break;
806810
case 0x8c: emit(`${top()}=rt.f2l(${top()});`); break;
@@ -1039,7 +1043,7 @@ const BINARY: Record<number, (a: string, b: string) => string> = {
10391043
const UNARY: Record<number, (a: string) => string> = {
10401044
0x74: (a) => `((-${a})|0)`, 0x75: (a) => `BigInt.asIntN(64,-${a})`, 0x76: (a) => `(-${a})`, 0x77: (a) => `(-${a})`,
10411045
0x85: (a) => `BigInt(${a})`, 0x86: (a) => `Math.fround(${a})`, 0x87: (a) => a, 0x88: (a) => `Number(BigInt.asIntN(32,${a}))`,
1042-
0x89: (a) => `Math.fround(Number(${a}))`, 0x8a: (a) => `Number(${a})`, 0x8b: (a) => `rt.f2i(${a})`, 0x8c: (a) => `rt.f2l(${a})`,
1046+
0x89: (a) => `rt.longToFloat(${a})`, 0x8a: (a) => `Number(${a})`, 0x8b: (a) => `rt.f2i(${a})`, 0x8c: (a) => `rt.f2l(${a})`,
10431047
0x8d: (a) => a, 0x8e: (a) => `rt.f2i(${a})`, 0x8f: (a) => `rt.f2l(${a})`, 0x90: (a) => `Math.fround(${a})`,
10441048
0x91: (a) => `((${a}<<24)>>24)`, 0x92: (a) => `(${a}&65535)`, 0x93: (a) => `((${a}<<16)>>16)`,
10451049
};

‎src/jvm.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -495,8 +495,17 @@ export class JVM {
495495
c.initThread = t;
496496
try {
497497
if (!c.isInterface && c.superclass && c.superclass.state !== INITIALIZED) yield* this.initGen(t, c.superclass);
498-
for (const i of c.interfaces) {
499-
if (i.state !== INITIALIZED && i.methods.some((m) => !m.isAbstract && !m.isStatic)) yield* this.initGen(t, i);
498+
if (!c.isInterface && c.interfaces.length) {
499+
const seen = new Set<JClass>();
500+
const interfaces: JClass[] = [];
501+
const visit = (i: JClass) => {
502+
if (seen.has(i)) return;
503+
seen.add(i);
504+
for (const parent of i.interfaces) visit(parent);
505+
if (i.methods.some((m) => !m.isAbstract && !m.isStatic)) interfaces.push(i);
506+
};
507+
for (const i of c.interfaces) visit(i);
508+
for (const i of interfaces) if (i.state !== INITIALIZED) yield* this.initGen(t, i);
500509
}
501510
this.applyConstantValues(c);
502511
const clinit = c.methodMap.get("<clinit>()V");

‎src/runtime.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,15 @@ export type ArrayData =
168168
| Int8Array | Uint16Array | Int16Array | Int32Array | Float32Array | Float64Array
169169
| BigInt64Array | (JObject | null)[];
170170

171+
// Preserve discarded bits as a sticky bit before rounding a long to float.
172+
export function longToFloat(v: bigint): number {
173+
const negative = v < 0n;
174+
const magnitude = negative ? -v : v;
175+
if (magnitude < (1n << 53n)) return Math.fround(Number(v));
176+
const rounded = (magnitude >> 11n) | ((magnitude & 2047n) === 0n ? 0n : 1n);
177+
return Math.fround(Number(negative ? -rounded : rounded) * 2048);
178+
}
179+
171180
export class JArray extends JObject {
172181
a: ArrayData;
173182
constructor(cls: JClass, a: ArrayData) {

‎test/java/BooleanStore.java‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
public class BooleanStore {
2+
public static class Stores {
3+
public static int store(boolean[] values) {
4+
values[0] = true;
5+
return values[0] ? 1 : 0;
6+
}
7+
}
8+
9+
static class Loader extends ClassLoader {
10+
Class<?> define(byte[] bytes) { return defineClass(null, bytes, 0, bytes.length); }
11+
}
12+
13+
public static void main(String[] args) throws Exception {
14+
try {
15+
Stores.store(null);
16+
} catch (NullPointerException e) {
17+
System.out.println("null store: " + e.getClass().getName());
18+
}
19+
byte[] bytes;
20+
try (var in = BooleanStore.class.getResourceAsStream("BooleanStore$Stores.class")) {
21+
bytes = in.readAllBytes();
22+
}
23+
int changes = 0;
24+
for (int i = 0; i < bytes.length - 1; i++) {
25+
if (bytes[i] == 4 && bytes[i + 1] == 0x54) {
26+
bytes[i] = 5;
27+
changes++;
28+
}
29+
}
30+
if (changes != 1) throw new AssertionError(changes);
31+
var method = new Loader().define(bytes).getMethod("store", boolean[].class);
32+
for (int i = 0; i < 1000; i++) {
33+
int value = (int) method.invoke(null, new boolean[] { true });
34+
if (i == 0 || i == 999) System.out.println(value);
35+
}
36+
try {
37+
method.invoke(null, (Object) null);
38+
} catch (java.lang.reflect.InvocationTargetException e) {
39+
System.out.println("hot null store: " + e.getCause().getClass().getName());
40+
}
41+
}
42+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
public class InterfaceInitialization {
2+
static String mark(String name) {
3+
System.out.println(name);
4+
return name;
5+
}
6+
7+
interface Root {
8+
String VALUE = mark("root");
9+
default void root() {}
10+
}
11+
interface Middle extends Root {}
12+
interface Left extends Middle {
13+
String VALUE = mark("left");
14+
default void left() {}
15+
}
16+
interface Right extends Root {
17+
String VALUE = mark("right");
18+
default void right() {}
19+
}
20+
static class Impl implements Left, Right {
21+
static String VALUE = mark("class");
22+
}
23+
24+
interface Parent {
25+
String VALUE = mark("parent");
26+
default void parent() {}
27+
}
28+
interface Child extends Parent {
29+
String VALUE = mark("child");
30+
}
31+
interface PrivateOnly {
32+
String VALUE = mark("private interface");
33+
private void helper() {}
34+
}
35+
static class PrivateImpl implements PrivateOnly {
36+
static String VALUE = mark("private class");
37+
}
38+
39+
public static void main(String[] args) {
40+
System.out.println(Child.VALUE);
41+
System.out.println(Impl.VALUE);
42+
System.out.println(PrivateImpl.VALUE);
43+
}
44+
}

‎test/java/LongToFloat.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
public class LongToFloat {
2+
static float convert(long value) { return (float) value; }
3+
4+
public static void main(String[] args) {
5+
long midpoint = (1L << 62) + (1L << 38);
6+
long[] values = {0, 1, -1, midpoint - 1, midpoint, midpoint + 1,
7+
-midpoint - 1, -midpoint, -midpoint + 1, Long.MIN_VALUE, Long.MAX_VALUE};
8+
for (int run = 0; run < 1000; run++) {
9+
for (long value : values) {
10+
int bits = Float.floatToRawIntBits(convert(value));
11+
if (run == 0 || run == 999) System.out.println(bits);
12+
}
13+
}
14+
}
15+
}

0 commit comments

Comments
 (0)