diff --git a/src/classfile.ts b/src/classfile.ts index 703a576..aa0bd6b 100644 --- a/src/classfile.ts +++ b/src/classfile.ts @@ -52,7 +52,7 @@ export interface ClassFile { renamedFrom?: string; minor: number; major: number; - cp: (CpEntry | undefined)[]; + cp: (CpEntry | string | undefined)[]; access: number; name: string; superName: string | null; @@ -181,14 +181,20 @@ function readCode(raw: Uint8Array, cp: ClassFile["cp"]): Code { return { maxStack, maxLocals, code, handlers, lines, localVars }; } +// UTF-8 entries are stored as strings to avoid an object per constant. +export function cpEntry(cp: ClassFile["cp"], i: number): CpEntry | undefined { + const e = cp[i]; + return typeof e === "string" ? { tag: Tag.Utf8, value: e, a: 0, b: 0 } : e; +} + export function utf8(cp: ClassFile["cp"], i: number): string { const e = cp[i]; - if (!e || e.tag !== Tag.Utf8) throw new ClassFormatError(`bad utf8 index ${i}`); - return e.value as string; + if (typeof e !== "string") throw new ClassFormatError(`bad utf8 index ${i}`); + return e; } export function className(cp: ClassFile["cp"], i: number): string { - const e = cp[i]; + const e = cpEntry(cp, i); if (!e || e.tag !== Tag.Class) throw new ClassFormatError(`bad class index ${i}`); return utf8(cp, e.a); } @@ -233,7 +239,7 @@ function parseBody(r: Reader, preview: boolean): ClassFile { a = r.u2(); b = r.u2(); break; default: throw new ClassFormatError(`bad constant pool tag ${tag} at ${i}`); } - cp[i] = { tag, value, a, b }; + cp[i] = tag === Tag.Utf8 ? value as string : { tag, value, a, b }; if (tag === Tag.Long || tag === Tag.Double) i++; } const access = r.u2(); diff --git a/src/indy.ts b/src/indy.ts index 6764476..2a0d411 100644 --- a/src/indy.ts +++ b/src/indy.ts @@ -5,7 +5,7 @@ // the same thing the JDK bootstraps do with the ClassFile API, minus the // cost of running that machinery in the interpreter. -import { Tag, className, utf8 } from "./classfile.ts"; +import { cpEntry, Tag, className, utf8 } from "./classfile.ts"; import { ClassWriter } from "./classwriter.ts"; import type { Code } from "./classwriter.ts"; import { @@ -42,14 +42,14 @@ export type BsmArg = export function cpArg(cls: JClass, idx: number): BsmArg { const cp = cls.cf!.cp; - const e = cp[idx]!; + const e = cpEntry(cp, idx)!; switch (e.tag) { case Tag.Integer: case Tag.Float: case Tag.Long: case Tag.Double: return { kind: "value", tag: e.tag, value: e.value }; case Tag.String: return { kind: "value", tag: e.tag, value: utf8(cp, e.a) }; case Tag.Class: return { kind: "class", name: className(cp, idx) }; case Tag.MethodType: return { kind: "mt", desc: utf8(cp, e.a) }; case Tag.MethodHandle: { - const ref = cp[e.b]!, nat = cp[ref.b]!; + const ref = cpEntry(cp, e.b)!, nat = cpEntry(cp, ref.b)!; return { kind: "mh", refKind: e.a, owner: className(cp, ref.a), name: utf8(cp, nat.a), desc: utf8(cp, nat.b), iface: ref.tag === Tag.InterfaceMethodref, @@ -434,9 +434,9 @@ function* methodHandleConstant(vm: JVM, t: JThread, cls: JClass, mh: MethodHandl function* dynamicConstant(vm: JVM, t: JThread, cls: JClass, idx: number): NativeGen { const cp = cls.cf!.cp; - const e = cp[idx]!; + const e = cpEntry(cp, idx)!; const bsm = cls.cf!.bootstrap[e.a]; - const nat = cp[e.b]!; + const nat = cpEntry(cp, e.b)!; const bsmHandle = yield* constantObject(vm, t, cls, bsm.ref); const type: JClass = yield* typeOf(t, cls, utf8(cp, nat.b)); const args = yield* staticArgs(vm, t, cls, bsm.args); @@ -455,7 +455,7 @@ function* staticArgs(vm: JVM, t: JThread, cls: JClass, idxs: number[]): NativeGe // The Java object for a loadable constant, boxing primitives. export function* constantObject(vm: JVM, t: JThread, cls: JClass, idx: number): NativeGen { const cp = cls.cf!.cp; - const e = cp[idx]!; + const e = cpEntry(cp, idx)!; switch (e.tag) { case Tag.Integer: return yield* box(t, "I", e.value); case Tag.Float: return yield* box(t, "F", e.value); @@ -467,7 +467,7 @@ export function* constantObject(vm: JVM, t: JThread, cls: JClass, idx: number): const cached = cls.ldc[idx]; if (cached !== undefined) { if (e.tag !== Tag.Dynamic) return cached; - const desc = utf8(cp, cp[e.b]!.b); + const desc = utf8(cp, cpEntry(cp, e.b)!.b); return isPrim(desc) ? yield* box(t, desc, cached) : cached; } let v: any; @@ -475,7 +475,7 @@ export function* constantObject(vm: JVM, t: JThread, cls: JClass, idx: number): else if (e.tag === Tag.MethodHandle) v = yield* methodHandleConstant(vm, t, cls, cpArg(cls, idx) as MethodHandleRef); else if (e.tag === Tag.Dynamic) { v = yield* dynamicConstant(vm, t, cls, idx); - const desc = utf8(cp, cp[e.b]!.b); + const desc = utf8(cp, cpEntry(cp, e.b)!.b); cls.ldc[idx] = isPrim(desc) && v !== null ? vm.getField(v, v.cls.name, "value") : v; return v; } @@ -487,10 +487,10 @@ export function* constantObject(vm: JVM, t: JThread, cls: JClass, idx: number): // ldc of a MethodType, MethodHandle or dynamic constant. export function* resolveConstant(vm: JVM, t: JThread, cls: JClass, idx: number): NativeGen { const cp = cls.cf!.cp; - const e = cp[idx]!; + const e = cpEntry(cp, idx)!; const v = yield* constantObject(vm, t, cls, idx); if (e.tag === Tag.Dynamic) { - const desc = utf8(cp, cp[e.b]!.b); + const desc = utf8(cp, cpEntry(cp, e.b)!.b); if (isPrim(desc)) return v === null ? null : vm.getField(v, v.cls.name, "value"); } return v; @@ -498,9 +498,9 @@ export function* resolveConstant(vm: JVM, t: JThread, cls: JClass, idx: number): function* linkGeneral(vm: JVM, t: JThread, cls: JClass, idx: number): NativeGen { const cp = cls.cf!.cp; - const e = cp[idx]!; + const e = cpEntry(cp, idx)!; const bsm = cls.cf!.bootstrap[e.a]; - const nat = cp[e.b]!; + const nat = cpEntry(cp, e.b)!; const bsmHandle = yield* constantObject(vm, t, cls, bsm.ref); const type = yield* methodType(vm, t, cls.loader, utf8(cp, nat.b)); const args = yield* staticArgs(vm, t, cls, bsm.args); @@ -515,9 +515,9 @@ function* linkGeneral(vm: JVM, t: JThread, cls: JClass, idx: number): NativeGen export function* linkCallSite(vm: JVM, t: JThread, cls: JClass, idx: number): Generator { const cp = cls.cf!.cp; - const e = cp[idx]!; + const e = cpEntry(cp, idx)!; const bsm = cls.cf!.bootstrap[e.a]; - const nat = cp[e.b]!; + const nat = cpEntry(cp, e.b)!; const name = utf8(cp, nat.a), desc = utf8(cp, nat.b); const ref = cpArg(cls, bsm.ref) as MethodHandleRef; const args = bsm.args.map((a) => cpArg(cls, a)); diff --git a/src/jit.ts b/src/jit.ts index 4c4dbb0..255f21a 100644 --- a/src/jit.ts +++ b/src/jit.ts @@ -14,7 +14,7 @@ // caller spill too, and later delivers its result through the frame like an // interpreted call. -import { Tag, utf8 } from "./classfile.ts"; +import { cpEntry, Tag, utf8 } from "./classfile.ts"; import { ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc, } from "./runtime.ts"; @@ -708,7 +708,7 @@ function insn(g: Gen, b: Body, pc: number) { case 0x11: emit(`${S(d)}=${s16(c, pc + 1)};`); break; case 0x12: case 0x13: case 0x14: { const i = op === 0x12 ? c[pc + 1] : idx2; - const e = cp[i]!; + const e = cpEntry(cp, i)!; if (e.tag === Tag.Integer || e.tag === Tag.Float || e.tag === Tag.Double) emit(`${S(d)}=${numLit(e.value as number)};`); else if (e.tag === Tag.Long) emit(`${S(d)}=${e.value}n;`); else { @@ -966,7 +966,7 @@ function fuseConcat(g: Gen, b: Body, pc: number): { pieces: string[]; end: numbe else if (op === 0x12 || op === 0x13) { const i = op === 0x12 ? c[p + 1] : u16(c, p + 1); const v = cls.ldc[i]; - if (cls.cf!.cp[i]!.tag !== Tag.String || v === undefined) return null; + if (cpEntry(cls.cf!.cp, i)!.tag !== Tag.String || v === undefined) return null; pieces.push(() => g.K(v)); p += op === 0x12 ? 2 : 3; } else return null; @@ -1249,12 +1249,12 @@ function stackDelta(cls: JClass, c: Uint8Array, pc: number): number { const op = c[pc]; const cp = cls.cf!.cp; const fieldSize = (idx: number) => { - const nat = cp[cp[idx]!.b]!; + const nat = cpEntry(cp, cpEntry(cp, idx)!.b)!; return isWide(utf8(cp, nat.b)) ? 2 : 1; }; const methodSlots = (idx: number, withReceiver: boolean) => { - const e = cp[idx]!; - const nat = cp[e.b]!; + const e = cpEntry(cp, idx)!; + const nat = cpEntry(cp, e.b)!; const { params, ret } = parseMethodDesc(utf8(cp, nat.b)); let n = withReceiver ? 1 : 0; for (const p of params) n += isWide(p) ? 2 : 1; diff --git a/src/jvm.ts b/src/jvm.ts index 6a8ad70..6f518be 100644 --- a/src/jvm.ts +++ b/src/jvm.ts @@ -2,7 +2,7 @@ // pool resolution, strings, monitors and the thread scheduler. import type { Assertions } from "./assertions.ts"; -import { BadMagic, ClassFormatError, MAX_MAJOR, Tag, UnsupportedVersion, className, parseClass, utf8 } from "./classfile.ts"; +import { cpEntry, BadMagic, ClassFormatError, MAX_MAJOR, Tag, UnsupportedVersion, className, parseClass, utf8 } from "./classfile.ts"; import type { ClassFile } from "./classfile.ts"; import { deliver, raise, runThread } from "./interp.ts"; import { NativeMemory } from "./memory.ts"; @@ -418,10 +418,10 @@ export class JVM { fieldRef(t: JThread, cls: JClass, idx: number): JField | undefined { const cp = cls.cf!.cp; - const e = cp[idx]!; + const e = cpEntry(cp, idx)!; const owner = cls.rcp[e.a] ?? this.classRef(t, cls, e.a); if (!owner) return undefined; - const nat = cp[e.b]!; + const nat = cpEntry(cp, e.b)!; const name = utf8(cp, nat.a); const f = owner.findField(name, utf8(cp, nat.b)); if (!f) throw new PendingThrow("java/lang/NoSuchFieldError", name); @@ -431,10 +431,10 @@ export class JVM { methodRef(t: JThread, cls: JClass, idx: number): JMethod | undefined { const cp = cls.cf!.cp; - const e = cp[idx]!; + const e = cpEntry(cp, idx)!; const owner = cls.rcp[e.a] ?? this.classRef(t, cls, e.a); if (!owner) return undefined; - const nat = cp[e.b]!; + const nat = cpEntry(cp, e.b)!; const name = utf8(cp, nat.a), desc = utf8(cp, nat.b); const m = this.resolveMethod(owner, name, desc); cls.rcp[idx] = m; @@ -471,7 +471,7 @@ export class JVM { // ldc / ldc_w / ldc2_w constant(t: JThread, cls: JClass, idx: number): any { const cp = cls.cf!.cp; - const e = cp[idx]!; + const e = cpEntry(cp, idx)!; let v: any; switch (e.tag) { case Tag.Integer: case Tag.Float: case Tag.Long: case Tag.Double: v = e.value; break; @@ -610,7 +610,7 @@ export class JVM { if (!f.isStatic) continue; const raw = f.attrs.get("ConstantValue"); if (!raw) continue; - const e = cp[(raw[0] << 8) | raw[1]]!; + const e = cpEntry(cp, (raw[0] << 8) | raw[1])!; c.statics[f.slot] = e.tag === Tag.String ? this.intern(utf8(cp, e.a)) : e.value; } } diff --git a/src/natives/npe.ts b/src/natives/npe.ts index 7796a08..4e7872b 100644 --- a/src/natives/npe.ts +++ b/src/natives/npe.ts @@ -3,7 +3,7 @@ // operand stack slot, then the message is built by walking back from the // bytecode that hit null. -import { Tag, className, utf8 } from "../classfile.ts"; +import { cpEntry, Tag, className, utf8 } from "../classfile.ts"; import type { ClassFile } from "../classfile.ts"; import type { JMethod } from "../runtime.ts"; import type { Natives } from "./util.ts"; @@ -248,10 +248,10 @@ class Builder { } private refDesc(i: number): string { - return utf8(this.cp, this.cp[this.cp[i]!.b]!.b); + return utf8(this.cp, cpEntry(this.cp, cpEntry(this.cp, i)!.b)!.b); } private refName(i: number): string { - return utf8(this.cp, this.cp[this.cp[i]!.b]!.a); + return utf8(this.cp, cpEntry(this.cp, cpEntry(this.cp, i)!.b)!.a); } private step(bci: number): number { @@ -291,12 +291,12 @@ class Builder { } else { switch (op) { case 0x12: case 0x13: case 0x14: { - const e = this.cp[op === 0x12 ? c[pos] : u16(c, pos)]!; + const e = cpEntry(this.cp, op === 0x12 ? c[pos] : u16(c, pos))!; if (e.tag === Tag.Integer) st.push(bci, INT); else if (e.tag === Tag.Long) st.push(bci, LONG); else if (e.tag === Tag.Float) st.push(bci, FLOAT); else if (e.tag === Tag.Double) st.push(bci, DOUBLE); - else if (e.tag === Tag.Dynamic) st.push(bci, descType(utf8(this.cp, this.cp[e.b]!.b)[0])); + else if (e.tag === Tag.Dynamic) st.push(bci, descType(utf8(this.cp, cpEntry(this.cp, e.b)!.b)[0])); else st.push(bci, OBJECT); break; } @@ -457,7 +457,7 @@ class Builder { } private methodName(i: number): string { - const e = this.cp[i]!; + const e = cpEntry(this.cp, i)!; const desc = this.refDesc(i); const params = paramDescs(desc).map(externalType).join(", "); return `${klassName(className(this.cp, e.a))}.${this.refName(i)}(${trimWellKnown(params)})`; @@ -531,7 +531,7 @@ class Builder { return true; case 0xb2: { const i = u16(c, pos); - this.out += `${klassName(className(this.cp, this.cp[i]!.a))}.${this.refName(i)}`; + this.out += `${klassName(className(this.cp, cpEntry(this.cp, i)!.a))}.${this.refName(i)}`; return true; } case 0xb4: diff --git a/src/natives/reflect.ts b/src/natives/reflect.ts index 4373782..71f067a 100644 --- a/src/natives/reflect.ts +++ b/src/natives/reflect.ts @@ -1,7 +1,7 @@ // Core reflection: Class metadata, Field/Method/Constructor objects, // invoke0/newInstance0 and ConstantPool. -import { Reader, Tag, className, utf8 } from "../classfile.ts"; +import { cpEntry, Reader, Tag, className, utf8 } from "../classfile.ts"; import { ACC_STATIC, ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, newArrayData, } from "../runtime.ts"; @@ -303,7 +303,7 @@ export const natives: Natives = { const cp = c.cf!.cp; const outer = yield* t.vm.loadClassGen(t, c.loader, className(cp, u16(raw, 0))); const nat = u16(raw, 2); - const e = nat ? cp[nat]! : null; + const e = nat ? cpEntry(cp, nat)! : null; return t.vm.newObjectArray("java/lang/Object", [ t.vm.mirror(outer), e ? t.vm.intern(utf8(cp, e.a)) : null, @@ -386,7 +386,7 @@ export const natives: Natives = { for (let i = 0; i < raw[0]; i++) { const nameIndex = u16(raw, 1 + i * 4), flags = u16(raw, 3 + i * 4); if (nameIndex >= cp.length) throw new PendingThrow("java/lang/IllegalArgumentException", "Constant pool index out of bounds"); - if (nameIndex !== 0 && cp[nameIndex]?.tag !== Tag.Utf8) throw new PendingThrow("java/lang/IllegalArgumentException", "Wrong type at constant pool index"); + if (nameIndex !== 0 && cpEntry(cp, nameIndex)?.tag !== Tag.Utf8) throw new PendingThrow("java/lang/IllegalArgumentException", "Wrong type at constant pool index"); const p = vm.newObject(pc); const name = nameIndex ? vm.str(utf8(cp, nameIndex)) : null; yield t.call(pc.methodMap.get(`(Ljava/lang/String;ILjava/lang/reflect/Executable;I)V`)!, p, name, flags, e, i); @@ -484,13 +484,13 @@ for (const [name, d] of Object.entries({ Boolean: "Z", Byte: "B", Char: "C", Sho Object.assign(natives, { [`${CP}getSize0(Ljava/lang/Object;)I`]: (t: JThread, [, o]: any[]) => cpOf(t, o).length, - [`${CP}getIntAt0(Ljava/lang/Object;I)I`]: (t: JThread, [, o, i]: any[]) => cpOf(t, o)[i]!.value, - [`${CP}getLongAt0(Ljava/lang/Object;I)J`]: (t: JThread, [, o, i]: any[]) => cpOf(t, o)[i]!.value, - [`${CP}getFloatAt0(Ljava/lang/Object;I)F`]: (t: JThread, [, o, i]: any[]) => cpOf(t, o)[i]!.value, - [`${CP}getDoubleAt0(Ljava/lang/Object;I)D`]: (t: JThread, [, o, i]: any[]) => cpOf(t, o)[i]!.value, + [`${CP}getIntAt0(Ljava/lang/Object;I)I`]: (t: JThread, [, o, i]: any[]) => cpEntry(cpOf(t, o), i)!.value, + [`${CP}getLongAt0(Ljava/lang/Object;I)J`]: (t: JThread, [, o, i]: any[]) => cpEntry(cpOf(t, o), i)!.value, + [`${CP}getFloatAt0(Ljava/lang/Object;I)F`]: (t: JThread, [, o, i]: any[]) => cpEntry(cpOf(t, o), i)!.value, + [`${CP}getDoubleAt0(Ljava/lang/Object;I)D`]: (t: JThread, [, o, i]: any[]) => cpEntry(cpOf(t, o), i)!.value, [`${CP}getUTF8At0(Ljava/lang/Object;I)Ljava/lang/String;`]: (t: JThread, [, o, i]: any[]) => t.vm.intern(utf8(cpOf(t, o), i)), - [`${CP}getStringAt0(Ljava/lang/Object;I)Ljava/lang/String;`]: (t: JThread, [, o, i]: any[]) => t.vm.intern(utf8(cpOf(t, o), cpOf(t, o)[i]!.a)), - [`${CP}getTagAt0(Ljava/lang/Object;I)B`]: (t: JThread, [, o, i]: any[]) => cpOf(t, o)[i]?.tag ?? 0, + [`${CP}getStringAt0(Ljava/lang/Object;I)Ljava/lang/String;`]: (t: JThread, [, o, i]: any[]) => t.vm.intern(utf8(cpOf(t, o), cpEntry(cpOf(t, o), i)!.a)), + [`${CP}getTagAt0(Ljava/lang/Object;I)B`]: (t: JThread, [, o, i]: any[]) => cpEntry(cpOf(t, o), i)?.tag ?? 0, [`${CP}getClassAt0(Ljava/lang/Object;I)Ljava/lang/Class;`]: function* (t: JThread, [, o, i]: any[]): NativeGen { const c = t.vm.classOf(o); return t.vm.mirror(yield* t.vm.loadClassGen(t, c.loader, className(c.cf!.cp, i))); @@ -502,16 +502,16 @@ Object.assign(natives, { }, [`${CP}getMemberRefInfoAt0(Ljava/lang/Object;I)[Ljava/lang/String;`]: (t: JThread, [, o, i]: any[]) => { const cp = cpOf(t, o); - const e = cp[i]!, nat = cp[e.b]!; + const e = cpEntry(cp, i)!, nat = cpEntry(cp, e.b)!; return t.vm.newObjectArray("java/lang/String", [className(cp, e.a), utf8(cp, nat.a), utf8(cp, nat.b)].map((s) => t.vm.intern(s))); }, [`${CP}getNameAndTypeRefInfoAt0(Ljava/lang/Object;I)[Ljava/lang/String;`]: (t: JThread, [, o, i]: any[]) => { const cp = cpOf(t, o); - const e = cp[i]!; + const e = cpEntry(cp, i)!; return t.vm.newObjectArray("java/lang/String", [utf8(cp, e.a), utf8(cp, e.b)].map((s) => t.vm.intern(s))); }, - [`${CP}getClassRefIndexAt0(Ljava/lang/Object;I)I`]: (t: JThread, [, o, i]: any[]) => cpOf(t, o)[i]!.a, + [`${CP}getClassRefIndexAt0(Ljava/lang/Object;I)I`]: (t: JThread, [, o, i]: any[]) => cpEntry(cpOf(t, o), i)!.a, [`${CP}getNameAndTypeRefIndexAt0(Ljava/lang/Object;I)I`]: (t: JThread, [, o, i]: any[]) => { - return cpOf(t, o)[i]!.b; + return cpEntry(cpOf(t, o), i)!.b; }, }); diff --git a/test/classfile.test.ts b/test/classfile.test.ts new file mode 100644 index 0000000..51a9fd7 --- /dev/null +++ b/test/classfile.test.ts @@ -0,0 +1,22 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { ClassFormatError, Tag, className, cpEntry, parseClass, utf8 } from "../src/classfile.ts"; +import { ClassWriter } from "../src/classwriter.ts"; + +test("constant pool retains UTF-8, references and wide constants", () => { + const w = new ClassWriter(1, "Example", "java/lang/Object"); + const empty = w.utf8(""); + const text = w.utf8("a\0\u03bb"); + const cls = w.cls("Example"); + const str = w.string("a\0\u03bb"); + const wide = w.long(-7n); + const cp = parseClass(w.toBytes()).cp; + assert.equal(utf8(cp, empty), ""); + assert.equal(utf8(cp, text), "a\0\u03bb"); + assert.equal(cpEntry(cp, text)?.tag, Tag.Utf8); + assert.equal(className(cp, cls), "Example"); + assert.equal(utf8(cp, cpEntry(cp, str)!.a), "a\0\u03bb"); + assert.equal(cpEntry(cp, wide)?.value, -7n); + assert.equal(cpEntry(cp, wide + 1), undefined); + assert.throws(() => utf8(cp, cls), ClassFormatError); +});