Skip to content
2 changes: 1 addition & 1 deletion docs/browser.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ compile loads over a thousand) and no library handles are live. Later library
starts with the same class path restore that image, after checking that the
files, missing paths and directory listings those calls used are unchanged. In
Chromium, the first javac compile after it takes about half the time of one
after a boot snapshot. An image is about 21 MB; it holds the JS the JIT
after a boot snapshot. An image is about 20 MB; it holds the JS the JIT
generated for the methods compiled so far, and a restored method compiles that
code on its first call. IndexedDB keeps the 2 most recent warm images separately
from boot snapshots. With `debug: true`, the console says whether a VM was
Expand Down
2 changes: 1 addition & 1 deletion docs/node.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ compile loads over a thousand) and no library handles are live. A later library
start with the same class path and working directory restores it, after
checking that the files, missing paths and directory listings those calls used
are unchanged. A first javac compile from it takes about a sixth of the time
of one after a boot snapshot. An image is about 21 MB, as it also holds the JS
of one after a boot snapshot. An image is about 20 MB, as it also holds the JS
the JIT generated for the methods compiled so far; a restored method compiles
that code on its first call instead of generating it again. Warm snapshots share the snapshot
directory and keep the 2 most recent. They build on boot snapshots, so with
Expand Down
133 changes: 95 additions & 38 deletions src/classfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ export interface CpEntry {
b: number;
}

// Utf8 and numeric values live in values. Other entries keep a and b as two
// u16 in one word of ab.
// Numeric values live in values. Other entries keep a and b as two u16 in one
// word of ab. A Utf8 entry keeps the offset of its bytes in ab, and its string
// in values once something asks for it.
export interface ConstantPool {
length: number;
values: (string | number | bigint | undefined)[];
tags: Uint8Array;
ab: Uint32Array;
bytes: Uint8Array;
}

export interface ExceptionEntry {
Expand All @@ -32,15 +34,52 @@ export interface ExceptionEntry {
catchType: number;
}

export interface Code {
maxStack: number;
maxLocals: number;
code: Uint8Array;
handlers: ExceptionEntry[];
// pairs of (start pc, line), sorted by pc
lines: number[] | null;
export class Code {
readonly maxStack: number;
readonly maxLocals: number;
readonly code: Uint8Array;
readonly handlers: ExceptionEntry[];
// raw LocalVariableTable attribute body, parsed on demand
localVars: Uint8Array | null;
readonly localVars: Uint8Array | null;
// the class's bytes, and where its LineNumberTable bodies start (-1 for none)
private bytes: Uint8Array;
private linesAt: number;
private moreLines: number[] | null;
private parsedLines: number[] | null | undefined;
constructor(maxStack: number, maxLocals: number, code: Uint8Array, handlers: ExceptionEntry[], bytes: Uint8Array, linesAt: number, moreLines: number[] | null, localVars: Uint8Array | null) {
this.maxStack = maxStack;
this.maxLocals = maxLocals;
this.code = code;
this.handlers = handlers;
this.bytes = bytes;
this.linesAt = linesAt;
this.moreLines = moreLines;
this.localVars = localVars;
}
// pairs of (start pc, line), sorted by pc
get lines(): number[] | null {
if (this.parsedLines !== undefined) return this.parsedLines;
let lines: number[] | null = null;
if (this.linesAt >= 0) {
const r = new Reader(this.bytes);
for (const at of [this.linesAt, ...(this.moreLines ?? [])]) {
r.pos = at;
lines ??= [];
for (let n = r.u2(); n > 0; n--) lines.push(r.u2(), r.u2());
}
}
if (lines && lines.length > 2) {
let sorted = true;
for (let i = 2; i < lines.length; i += 2) if (lines[i] < lines[i - 2]) { sorted = false; break; }
if (!sorted) {
const pairs: [number, number][] = [];
for (let i = 0; i < lines.length; i += 2) pairs.push([lines[i], lines[i + 1]]);
pairs.sort((a, b) => a[0] - b[0]);
lines = pairs.flat();
}
}
return this.parsedLines = lines;
}
}

export interface Member {
Expand Down Expand Up @@ -145,13 +184,28 @@ export function encodeMutf8(s: string): Uint8Array {
return Uint8Array.from(out);
}

const NO_ATTRS = new Map<string, Uint8Array>();
const NO_HANDLERS: ExceptionEntry[] = [];

function readMember(r: Reader, cp: ClassFile["cp"]): Member {
const access = r.u2();
const name = utf8(cp, r.u2());
const desc = utf8(cp, r.u2());
const attrs = readAttrs(r, cp);
const raw = attrs.get("Code");
return { access, name, desc, attrs, code: raw ? readCode(raw, cp) : null };
let attrs = NO_ATTRS;
let code: Code | null = null;
for (let n = r.u2(); n > 0; n--) {
const attr = utf8(cp, r.u2());
const length = r.u4();
if (attr === "Code") {
const end = r.pos + length;
code = readCode(r, cp);
r.pos = end;
} else {
if (attrs === NO_ATTRS) attrs = new Map();
attrs.set(attr, r.slice(length));
}
}
return { access, name, desc, attrs, code };
}

function readAttrs(r: Reader, cp: ClassFile["cp"]) {
Expand All @@ -163,38 +217,38 @@ function readAttrs(r: Reader, cp: ClassFile["cp"]) {
return attrs;
}

function readCode(raw: Uint8Array, cp: ClassFile["cp"]): Code {
const r = new Reader(raw);
function readCode(r: Reader, cp: ClassFile["cp"]): Code {
const maxStack = r.u2();
const maxLocals = r.u2();
const code = r.slice(r.u4());
const handlers: ExceptionEntry[] = [];
for (let n = r.u2(); n > 0; n--) {
let n = r.u2();
const handlers: ExceptionEntry[] = n === 0 ? NO_HANDLERS : [];
for (; n > 0; n--) {
handlers.push({ start: r.u2(), end: r.u2(), handler: r.u2(), catchType: r.u2() });
}
let lines: number[] | null = null;
let linesAt = -1;
let moreLines: number[] | null = null;
let localVars: Uint8Array | null = null;
for (const [name, body] of readAttrs(r, cp)) {
if (name === "LocalVariableTable") localVars = body;
if (name !== "LineNumberTable") continue;
const lr = new Reader(body);
lines ??= [];
for (let n = lr.u2(); n > 0; n--) lines.push(lr.u2(), lr.u2());
}
if (lines && lines.length > 2) {
const pairs: [number, number][] = [];
for (let i = 0; i < lines.length; i += 2) pairs.push([lines[i], lines[i + 1]]);
pairs.sort((a, b) => a[0] - b[0]);
lines = pairs.flat();
for (n = r.u2(); n > 0; n--) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: The attribute loop manually advances r.pos for LineNumberTable but uses r.slice(length) for all others. This relies on Reader.slice advancing the position (consistent with readMember and the old readAttrs). Worth a quick verify or a comment to avoid future confusion.

const name = utf8(cp, r.u2());
const length = r.u4();
if (name === "LineNumberTable") {
if (linesAt < 0) linesAt = r.pos;
else (moreLines ??= []).push(r.pos);
r.pos += length;
} else {
const body = r.slice(length);
if (name === "LocalVariableTable") localVars = body;
}
}
return { maxStack, maxLocals, code, handlers, lines, localVars };
return new Code(maxStack, maxLocals, code, handlers, r.bytes, linesAt, moreLines, localVars);
}

export function cpEntry(cp: ClassFile["cp"], i: number): CpEntry | undefined {
const tag = cp.tags[i];
if (!tag) return undefined;
const value = cp.values[i];
return { tag, value, a: cp.ab[i] >>> 16, b: cp.ab[i] & 0xffff };
if (tag === Tag.Utf8) return { tag, value: utf8(cp, i), a: 0, b: 0 };
return { tag, value: cp.values[i], a: cp.ab[i] >>> 16, b: cp.ab[i] & 0xffff };
}

export function cpTag(cp: ClassFile["cp"], i: number): number { return cp.tags[i]; }
Expand All @@ -204,8 +258,10 @@ export function cpValue(cp: ClassFile["cp"], i: number): number | bigint | undef

export function utf8(cp: ClassFile["cp"], i: number): string {
const s = cp.values[i];
if (typeof s !== "string") throw new ClassFormatError(`bad utf8 index ${i}`);
return s;
if (typeof s === "string") return s;
if (cp.tags[i] !== Tag.Utf8) throw new ClassFormatError(`bad utf8 index ${i}`);
const at = cp.ab[i], b = cp.bytes;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional: cp.ab[i] is overloaded: for Utf8 it holds the byte offset of the length field; for other tags it packs two u16 indexes. The utf8 guard on cp.tags[i] === Tag.Utf8 makes this safe, but a comment on the ConstantPool.ab field would clarify the dual meaning.

return cp.values[i] = decodeMutf8(b.subarray(at + 2, at + 2 + ((b[at] << 8) | b[at + 1])));
}

export function className(cp: ClassFile["cp"], i: number): string {
Expand Down Expand Up @@ -240,12 +296,13 @@ function parseBody(r: Reader, preview: boolean): ClassFile {
values: new Array(count),
tags: new Uint8Array(count),
ab: new Uint32Array(count),
bytes: r.bytes,
};
for (let i = 1; i < count; i++) {
const tag = r.u1();
let value: CpEntry["value"], a = 0, b = 0;
let value: CpEntry["value"], a = 0, b = 0, start = 0;
switch (tag) {
case Tag.Utf8: value = decodeMutf8(r.slice(r.u2())); break;
case Tag.Utf8: start = r.pos; r.pos += 2 + r.view.getUint16(r.pos); break;
case Tag.Integer: value = r.i4(); break;
case Tag.Float: value = r.view.getFloat32(r.pos); r.pos += 4; break;
case Tag.Long: value = r.view.getBigInt64(r.pos); r.pos += 8; break;
Expand All @@ -260,7 +317,7 @@ function parseBody(r: Reader, preview: boolean): ClassFile {
}
cp.tags[i] = tag;
if (value !== undefined) cp.values[i] = value;
cp.ab[i] = a << 16 | b;
cp.ab[i] = tag === Tag.Utf8 ? start : a << 16 | b;
if (tag === Tag.Long || tag === Tag.Double) i++;
}
const access = r.u2();
Expand Down
48 changes: 39 additions & 9 deletions src/jit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,40 @@ function fallback(t: JThread, f: Frame) {
return SUSPEND;
}

// An exception in compiled code: the pc of the handler (>= 0); an exit code
// to take, as -x - 2; or -1 when the frame is gone and the code returns.
function caught(t: JThread, f: Frame, pc: number, e: unknown): number {
const error = (at: number) => {
f.direct = false;
return -(at * exitCode(1, 0, 0) + EXIT_ERROR) - 2;
};
if (e instanceof JavaThrow) {
const h = hooks.findHandler(t, f, pc, e.obj);
if (h >= 0) return h;
if (h < -1) return error(pc);
hooks.popFrame(t, f);
if (f.direct) throw e;
hooks.raise(t, e.obj);
return -1;
}
return error(e instanceof PendingThrow && e.pc !== undefined ? e.pc : pc);
}

// Leaves compiled code through an exit once its frame is spilled.
function leave(t: JThread, f: Frame, x: number, xe: any): number {
switch (x & 7) {
case EXIT_FALLBACK: return fallback(t, f);
case EXIT_INTERPRET: return viaInterpreter(t, f);
case EXIT_RETHROW:
t.pushNative(runtime.rethrow(xe.obj), null, "V", false);
return 1;
case EXIT_ERROR:
hooks.handleError(t, xe);
return 1;
}
return 1;
}

// A call compiled code cannot make directly; not a reason to recompile.
function viaInterpreter(t: JThread, f: Frame) {
hooks.interpret(t, f, 1);
Expand Down Expand Up @@ -164,6 +198,8 @@ const runtime = {
concat: concatStrings,
fallback,
viaInterpreter,
caught,
leave,
basicTarget(t: JThread, mh: JObject | null, pc: number): JMethod {
if (mh === null) npeAt(pc);
const form = t.vm.getField(mh, "java/lang/invoke/MethodHandle", "form") as JObject;
Expand Down Expand Up @@ -599,24 +635,18 @@ function generate(t: JThread, m: JMethod): { src: string; consts: any[] } {
const fname = `${m.cls.name}_${m.name}`.replace(/[^A-Za-z0-9_$]/g, "_");
const out: string[] = [];
// direct calls pass arguments as parameters and a frame without arrays
out.push(`return function ${fname}(t,f${params.map((p) => "," + p).join("")}){let L=f.locals,S=f.stack;const vm=t.vm,H=rt.hooks;`);
out.push(`return (function ${fname}(t,f${params.map((p) => "," + p).join("")}){let L=f.locals,S=f.stack;const vm=t.vm,H=rt.hooks;`);
out.push(`let pc=f.pc,tm,cf,r,a,v,ic,ifs=0,dpc=0,dsp=0,x=0,xs=0,xe=null,${[...g.vars].join(",")};`);
out.push(`if(L===null){${params.map((p, i) => `${L(i)}=${p};`).join("")}}else{${Array.from({ length: nl }, (_, i) => `${L(i)}=L[${i}];`).join("")}${Array.from({ length: ns }, (_, i) => `${S(i)}=S[${i}];`).join("")}}`);
out.push(`X:{for(;;){try{switch(pc){`);
out.push(...top.out);
// a frame the interpreter left elsewhere steps to the next entry
out.push(`default:return rt.viaInterpreter(t,f);}}catch(e){`);
if (g.regions.length) out.push(deoptCatch(g));
out.push(`if(e instanceof rt.JavaThrow){const h=H.findHandler(t,f,pc,e.obj);if(h>=0){${S(0)}=e.obj;pc=h;continue;}`);
out.push(`if(h< -1){x=pc*${exitCode(1, 0, 0)}+${EXIT_ERROR};xe=e;if(f.direct)f.direct=false;break X;}`);
out.push(`H.popFrame(t,f);if(f.direct)throw e;H.raise(t,e.obj);return 1;}`);
out.push(`x=(e instanceof rt.PendingThrow&&e.pc!==undefined?e.pc:pc)*${exitCode(1, 0, 0)}+${EXIT_ERROR};xe=e;if(f.direct)f.direct=false;break X;}}}`);
out.push(`xs=rt.caught(t,f,pc,e);if(xs>=0){${S(0)}=e.obj;pc=xs;continue;}if(xs<-1){x=-xs-2;xe=e;break X;}return 1;}}}`);
// the shared exit: spill into the frame's arrays, then leave as x says
const stack = Array.from({ length: ns }, (_, i) => `case ${ns - i}:S[${ns - i - 1}]=${S(ns - i - 1)};`).join("");
out.push(`f.pc=x>>>13;xs=x>>>3&1023;${spillLocals()}switch(xs){${stack}}f.sp=xs;`);
out.push(`switch(x&7){case ${EXIT_FALLBACK}:return rt.fallback(t,f);case ${EXIT_INTERPRET}:return rt.viaInterpreter(t,f);` +
`case ${EXIT_RETHROW}:t.pushNative(rt.rethrow(xe.obj),null,"V",false);return 1;` +
`case ${EXIT_ERROR}:H.handleError(t,xe);return 1;}return 1;}`);
out.push(`f.pc=x>>>13;xs=x>>>3&1023;${spillLocals()}switch(xs){${stack}}f.sp=xs;return rt.leave(t,f,x,xe);})`);
return { src: out.join("\n"), consts };
}

Expand Down
5 changes: 4 additions & 1 deletion src/jvm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ const RESUMED = Object.freeze({ kind: "resume" }) as unknown as Request;
// LauncherHelper launch modes
export const LM_CLASS = 1, LM_JAR = 2;

const intrinsicClasses = new Set(Object.keys(intrinsics).map((k) => k.slice(0, k.indexOf("."))));

// Rejects run and startLibrary when a snapshot could not be restored. The
// snapshot is dropped, so a new VM with the same options boots.
export class SnapshotError extends Error {}
Expand Down Expand Up @@ -333,9 +335,10 @@ export class JVM {
}
c.instanceSlots = slot;
c.template = template;
const withIntrinsics = loader === null && intrinsicClasses.has(cf.name);
const poly = cf.name === "java/lang/invoke/MethodHandle" || cf.name === "java/lang/invoke/VarHandle";
for (const [i, mm] of cf.methods.entries()) {
const intrinsic = loader === null ? intrinsics[`${cf.name}.${mm.name}${mm.desc}`] : undefined;
const intrinsic = withIntrinsics ? intrinsics[`${cf.name}.${mm.name}${mm.desc}`] : undefined;
const m = new JMethod(c, intrinsic ? { ...mm, code: null, access: mm.access | ACC_NATIVE } : mm);
if (intrinsic) {
m.native = intrinsic;
Expand Down
52 changes: 52 additions & 0 deletions src/natives/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// collapses them. They follow AbstractStringBuilder.append,
// ensureCapacityNewCoder, newCapacity and String.<init>(AbstractStringBuilder,
// Void) of the pinned JDK, so buffer growth and string coders match.
// The jimage string reader is here too.

import { JArray, MAX_HEAP, newArrayData } from "../runtime.ts";
import type { JClass, JObject } from "../runtime.ts";
Expand Down Expand Up @@ -158,7 +159,58 @@ export function concatStrings(t: JThread, pc: number, parts: (JObject | null)[])
return str;
}

// ImageStringsReader.stringFromByteBuffer(buffer, offset): the modified UTF-8
// string at offset, read from the jimage's buffer. javac lists thousands of
// image locations, and the Java version gets each byte through a ByteBuffer.
function imageString(t: JThread, args: any[]): JObject {
const vm = t.vm;
const buf: JObject | null = args[0], offset: number = args[1];
if (buf === null) throw new PendingThrow("java/lang/NullPointerException");
const limit = buf.f[vm.slotOf("java/nio/Buffer", "limit")] as number;
const hb = buf.f[vm.slotOf("java/nio/ByteBuffer", "hb")] as JArray | null;
let bytes: ArrayLike<number>, base: number;
if (hb) {
bytes = hb.a as Int8Array;
base = buf.f[vm.slotOf("java/nio/ByteBuffer", "offset")] as number;
} else {
bytes = vm.mem.u8;
base = Number(buf.f[vm.slotOf("java/nio/Buffer", "address")] as bigint);
}
if (offset < 0) {
throw new PendingThrow("java/lang/IndexOutOfBoundsException", `Index ${offset} out of bounds for length ${limit}`);
}
let end = offset, ascii = true;
for (; end < limit && bytes[base + end] !== 0; end++) if (bytes[base + end] & 0x80) ascii = false;
if (end === limit) throw new PendingThrow("java/lang/InternalError", "No terminating zero byte for modified UTF-8 byte sequence");
slots(vm);
if (ascii) {
const value = newBytes(end - offset);
for (let i = offset; i < end; i++) value[i - offset] = bytes[base + i];
const s = vm.newObject(strClass);
fill(vm, s, value, 0);
return s;
}
let text = "";
for (let i = offset; i < end; i++) {
let ch = bytes[base + i] & 0xff;
if (ch & 0x80) {
let uch = ch & 0x7f, mask = 0x40;
while (uch & mask) {
ch = bytes[base + ++i] & 0xff;
if ((ch & 0xc0) !== 0x80) throw new PendingThrow("java/lang/InternalError", `Bad continuation in modified UTF-8 byte sequence: ${(ch << 24) >> 24}`);
uch = ((uch & ~mask) << 6) | (ch & 0x3f);
mask <<= 5;
}
if ((uch & 0xffff) !== uch) throw new PendingThrow("java/lang/InternalError", `UTF-32 char in modified UTF-8 byte sequence: ${uch}`);
ch = uch;
}
text += String.fromCharCode(ch);
}
return vm.str(text);
}

export const intrinsics: Natives = {
"jdk/internal/jimage/ImageStringsReader.stringFromByteBuffer(Ljava/nio/ByteBuffer;I)Ljava/lang/String;": imageString,
[`${ASB}.append(Ljava/lang/String;)L${ASB};`]: appendString,
"java/lang/StringBuilder.append(Ljava/lang/String;)Ljava/lang/StringBuilder;": appendString,
"java/lang/String.<init>(Ljava/lang/AbstractStringBuilder;Ljava/lang/Void;)V": stringFromBuilder,
Expand Down
Loading
Loading
⌂ Proxy