Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,12 @@ Node, which is how the tests run.
- **PendingThrow**: thrown by JS code to raise a new Java exception; the
interpreter builds it with its real constructor.
- **mirror**: the `java.lang.Class` object of a runtime class.
- **object layout**: a Java object is a JS object with `cls`, `s` (identity
hash, monitor and VM data, once it has any) and its instance fields as
properties `f0`, `f1`, ... (`JField.key`). Classes whose fields have the same
kinds share one generated constructor, so one JS shape. An object whose class
has a finalizer keeps its fields in a second object, `st`, that the Finalizer
also holds.
- **handle**: how the VM names a Java object it gave to JS; the page's proxy
holds it until the proxy is dropped.
- **wire value**: a value as it crosses between the VM and JS (library.ts).
Expand Down
2 changes: 1 addition & 1 deletion docs/node.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ resolves to the exit code. Its options:
- `stdout`, `stderr` (byte callbacks; default the process's), `input` (fixed stdin bytes)
- `env` (what `System.getenv()` returns; default the host's environment)
- `natives`: Java `native` methods in JS, as in the browser ([browser.md](browser.md))
- `assertions` (the flags, for example `["-ea"]`), `enablePreview`, `localeData`
- `assertions` (the flags, for example `["-ea"]`), `enablePreview`, `localeData`, `finalization` (`false` is `--finalization=disabled`)
- `hostName` (what `InetAddress.getLocalHost()` reports), `maxRssMb`, `jdk`, `debug`
- `maxDirectMemory` (`-XX:MaxDirectMemorySize`, in bytes), `onOutOfMemoryError` (`-XX:OnOutOfMemoryError` commands),
`vmOutputToStderr` (`-XX:+DisplayVMOutputToStderr`)
Expand Down
20 changes: 18 additions & 2 deletions docs/support.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,21 @@ java-web targets headless Java: console apps, libraries and javac.
processes do to a watched host directory, with Node's `fs.watch` (so a short-lived
entry can show as a delete without its create). Elsewhere it does not see
changes made outside the VM.
- Garbage collection is the JS engine's. Under Node, `System.gc()` collects: weak and
phantom references are cleared and enqueued, finalizers (off with
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
`--finalization=disabled`) and Cleaners run, and a class loader that nothing
refers to is unloaded with its classes and hidden classes. Soft references
are cleared before an `OutOfMemoryError`, and by `System.gc()` when more than
half the heap limit is in use. `System.gc()` collects only when a host collector
is available, so not under `--freeze-flags-after-init` without `--expose-gc`.
An object with a finalizer is finalized only if no cycle leads from its own
fields back to it (JS cannot finalize such an object): the VM drops the
finalizer of an object it finds on such a cycle, so the object is freed
without `finalize()` running, and a cycle it does not find (a class loader
with a `finalize()`) keeps the object for good. A local variable keeps its
object reachable until the method returns or the variable is overwritten,
even after its last use, so such an object is cleared or finalized later
than on HotSpot. In the browser `System.gc()` is a hint and the engine collects when it chooses.
- Not supported: GUI apps (AWT and Swing windows), `ConvolveOp`, child
processes in the browser, and native libraries other than JS natives.

Expand Down Expand Up @@ -128,8 +143,9 @@ Locales other than English need `cheerpjInit({ localeData: true })`, or
- TCP, UDP, IPv4 multicast, Unix domain sockets and `Pipe` work in both. Under
Node a Unix domain socket is a file on the host; in the browser it is a file
in the virtual file system.
- IPv4 only. Not supported: IPv6, asynchronous channels
(`AsynchronousSocketChannel`), SCTP, ICMP (`isReachable` is true for the
- Asynchronous channels (`AsynchronousSocketChannel`,
`AsynchronousServerSocketChannel`, `AsynchronousFileChannel`) work under Node.
- IPv4 only. Not supported: IPv6, SCTP, ICMP (`isReachable` is true for the
host's own addresses only) and inherited channels.
- `jdk.net` is in the image. Its socket options (TCP keep-alive time, interval
and probes, quick ack, don't fragment) keep their values on the socket and do
Expand Down
2 changes: 1 addition & 1 deletion src/indy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ export function invokePolymorphic(vm: JVM, t: JThread, f: Frame, m: JMethod): bo
let target = memberTarget(t, stack[f.sp - 1]);
if (m.name === "linkToStatic" && target.cls.state !== INITIALIZED && !vm.initialize(t, target.cls)) return false;
f.sp--;
if (m.name === "linkToVirtual" || m.name === "linkToInterface") {
if ((m.name === "linkToVirtual" || m.name === "linkToInterface") && !target.isPrivate) {
const recv = stack[f.sp - target.argSlots] as JObject | null;
if (recv === null) throw new PendingThrow("java/lang/NullPointerException");
const sel = recv.cls.selectMethod(target.key);
Expand Down
45 changes: 39 additions & 6 deletions src/interp.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Bytecode interpreter and the per-thread run loop.

import {
INITIALIZED, JArray, JClass, JMethod, JObject, isWide, longToFloat, newArrayData, sched,
INITIALIZED, JArray, JClass, JMethod, JObject, isWide, longToFloat, newArrayData, pin, sched,
} from "./runtime.ts";
import {
Frame, JThread, JavaThrow, MAX_DIRECT, NativeFrame, PendingThrow, RUNNABLE, TERMINATED, WAITING, fromNative,
Expand All @@ -10,6 +10,7 @@ import type { NativeGen } from "./thread.ts";
import type { JVM } from "./jvm.ts";
import { INTERPRET, PUSHED, compileIfHot, hooks, noteBackedge } from "./jit.ts";
import { unmountNative } from "./natives/continuation.ts";
import { registerFinalizer } from "./natives/ref.ts";

const MAX_FRAMES = 6000;

Expand Down Expand Up @@ -331,7 +332,19 @@ export function interpret(t: JThread, f: Frame, budget: number): number {
if (fld === undefined) { f.pc = ipc; f.sp = sp; return budget; }
o = stack[sp - 1];
if (o === null) npe();
stack[sp - 1] = o.f[fld.slot];
// a named load per slot: the engine caches each by shape, which a computed key cannot
switch (fld.slot) {
case 0: v = o.f0; break;
case 1: v = o.f1; break;
case 2: v = o.f2; break;
case 3: v = o.f3; break;
case 4: v = o.f4; break;
case 5: v = o.f5; break;
case 6: v = o.f6; break;
case 7: v = o.f7; break;
default: v = o[fld.key];
}
stack[sp - 1] = v;
if (fld.wide) stack[sp++] = undefined;
pc += 3;
break;
Expand All @@ -344,7 +357,17 @@ export function interpret(t: JThread, f: Frame, budget: number): number {
v = stack[--sp];
o = stack[--sp];
if (o === null) npe();
o.f[fld.slot] = v;
switch (fld.slot) {
case 0: o.f0 = v; break;
case 1: o.f1 = v; break;
case 2: o.f2 = v; break;
case 3: o.f3 = v; break;
case 4: o.f4 = v; break;
case 5: o.f5 = v; break;
case 6: o.f6 = v; break;
case 7: o.f7 = v; break;
default: o[fld.key] = v;
}
pc += 3;
break;
}
Expand Down Expand Up @@ -374,12 +397,20 @@ export function interpret(t: JThread, f: Frame, budget: number): number {
target = vm.specialTarget(cls, target);
} else if (!target.isPrivate) {
const cache = m.cache ??= [];
const ic = cache[ipc];
let ic = cache[ipc];
if (ic !== undefined && ic.c === o.cls) target = ic.m;
else {
const sel = o.cls.selectMethod(target.key);
if (!sel) throw new PendingThrow("java/lang/AbstractMethodError", `${o.cls.javaName}.${target.name}${target.desc}`);
cache[ipc] = { c: o.cls, m: sel };
if (ic === undefined) cache[ipc] = ic = { c: o.cls, m: sel, p: false };
else {
ic.c = o.cls;
ic.m = sel;
}
if (o.cls.unloadable && !ic.p) {
Comment thread
project516-review-bot[bot] marked this conversation as resolved.
Resolved
ic.p = true;
pin(ic);
}
target = sel;
}
}
Expand All @@ -403,7 +434,9 @@ export function interpret(t: JThread, f: Frame, budget: number): number {
if (c === undefined) { f.pc = ipc; f.sp = sp; return budget; }
if (c.state !== INITIALIZED && !vm.initialize(t, c)) { f.pc = ipc; f.sp = sp; return budget; }
if (c.access & 0x0600) throw new PendingThrow("java/lang/InstantiationError", c.javaName);
stack[sp++] = new JObject(c, c.template.slice());
const o = new c.ctor(c);
if (c.finalizable) registerFinalizer(vm, o);
stack[sp++] = o;
pc += 3;
break;
}
Expand Down
58 changes: 34 additions & 24 deletions src/jit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,7 @@
// interpreted call.

import { cpB, cpTag, cpValue, Tag, utf8 } from "./classfile.ts";
import {
ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc,
} from "./runtime.ts";
import { ACC_FINAL, INITIALIZED, JArray, JClass, JField, JMethod, JObject, isWide, longToFloat, newArrayData, parseMethodDesc, pin, dataOf, evalBlocked } from "./runtime.ts";
import { memberTarget } from "./natives/invoke.ts";
import { concatStrings } from "./natives/strings.ts";
import { Frame, JavaThrow, NativeFrame, PendingThrow, fromNative } from "./thread.ts";
Expand Down Expand Up @@ -74,6 +72,12 @@ export function restoreJit(vm: JVM, m: JMethod, code: SavedJit) {
m.hot = THRESHOLD - 1;
}

// A constant of compiled code that holds a class another loader can drop.
function namesUnloadable(v: unknown, caller: JClass): boolean {
const c = v instanceof JClass ? v : v instanceof JMethod || v instanceof JField ? v.cls : v instanceof JObject ? (dataOf(v) instanceof JClass ? dataOf(v) : v.cls) : null;
return c !== null && c !== caller && c.unloadable && (c.hidden || c.loader !== caller.loader);
}

function compile(t: JThread, m: JMethod) {
if (disabled || m.noJit || !m.code || m.name === "<clinit>" || m.code.code.length > MAX_CODE) return;
const vm = t.vm;
Expand All @@ -85,12 +89,13 @@ function compile(t: JThread, m: JMethod) {
if (vm.keepJit && !stats && !noInline) vm.jitCode.set(m, code);
}
const { src, consts } = code;
if (consts.some((v) => namesUnloadable(v, m.cls))) pin(m);
if (dump && m.toString().includes(dump)) console.error(`// ${m}\n${src}`);
m.jit = new Function("rt", "K", src)(runtime, consts) as Compiled;
if (stats) stats.set(`compiled ${m}`, src.length);
m.fallbacks = 0;
} catch (e) {
if (e instanceof EvalError || (e instanceof Error && /unsafe-eval|Content Security/i.test(e.message))) disabled = true;
if (evalBlocked(e)) disabled = true;
if (!(e instanceof Unsupported)) t.vm.debug("jit failed for", m.toString(), e);
if (stats) stats.set(`nojit ${m}: ${e instanceof Error ? e.message : e}`, 1e9);
m.noJit = true;
Expand Down Expand Up @@ -230,7 +235,7 @@ const runtime = {
virtualTarget(t: JThread, mn: JObject, recv: JObject | null, pc: number): JMethod {
const m = memberTarget(t, mn);
if (recv === null) npeAt(pc);
const sel = recv.cls.selectMethod(m.key);
const sel = m.isPrivate ? m : recv.cls.selectMethod(m.key);
if (!sel) throw new PendingThrow("java/lang/AbstractMethodError", `${recv.cls.javaName}.${m.name}${m.desc}`);
return sel;
},
Expand Down Expand Up @@ -348,7 +353,7 @@ const runtime = {
},
fcmp(a: number, b: number, nan: number) { return a > b ? 1 : a < b ? -1 : a === b ? 0 : nan; },
lcmp(a: bigint, b: bigint) { return a > b ? 1 : a < b ? -1 : 0; },
// cell: the inline cache, [receiver class, method, method key]
// cell: the inline cache, [receiver class, method, method key, registered by pin]
select(o: JObject | null, cell: any[], pc: number): JMethod {
if (o === null) return runtime.npe(pc);
if (cell[0] === o.cls) return cell[1];
Expand All @@ -357,6 +362,10 @@ const runtime = {
if (!m) throw new PendingThrow("java/lang/AbstractMethodError", `${o.cls.javaName}.${key}`);
cell[0] = o.cls;
cell[1] = m;
if (o.cls.unloadable && !cell[3]) {
cell[3] = true;
pin(cell);
}
return m;
},
isGen(r: any) { return r !== null && typeof r === "object" && typeof r.next === "function" && typeof r.throw === "function"; },
Expand Down Expand Up @@ -1010,11 +1019,11 @@ function insnCode(g: Gen, b: Body, pc: number) {
case 0xb4: case 0xb5: {
const fld = cls.rcp[idx2] as JField | undefined;
if (!fld) { emit(slow(pc, d)); break; }
if (op === 0xb4) emit(`${b.nn.has(d - 1) ? "" : `if(${top()}===null)np(${pc});`}${top()}=${top()}.f[${fld.slot}];`);
if (op === 0xb4) emit(`${b.nn.has(d - 1) ? "" : `if(${top()}===null)np(${pc});`}${top()}=${top()}.${fld.key};`);
else {
const k = fld.wide ? 2 : 1;
const obj = top(k);
emit(`${b.nn.has(d - 1 - k) ? "" : `if(${obj}===null)np(${pc});`}${obj}.f[${fld.slot}]=${fld.wide ? top(1) : top()};`);
emit(`${b.nn.has(d - 1 - k) ? "" : `if(${obj}===null)np(${pc});`}${obj}.${fld.key}=${fld.wide ? top(1) : top()};`);
}
break;
}
Expand Down Expand Up @@ -1043,8 +1052,8 @@ function insnCode(g: Gen, b: Body, pc: number) {
break;
}
const k = cls.rcp[idx2] as JClass | undefined;
if (!k || k.state !== INITIALIZED || k.access & 0x0600) { emit(slow(pc, d)); break; }
emit(`${S(d)}=new rt.JObject(${K(k)},${K(k)}.template.slice());`);
if (!k || k.state !== INITIALIZED || k.access & 0x0600 || k.finalizable) { emit(slow(pc, d)); break; }
emit(`${S(d)}=new ${K(k)}.ctor(${K(k)});`);
break;
}
case 0xbc: {
Expand Down Expand Up @@ -1077,11 +1086,12 @@ function insnCode(g: Gen, b: Body, pc: number) {
}
case 0xc2:
if (region) throw new NoInline();
emit(`if(${top()}===null)np(${pc});if(!vm.monitorEnter(t,${top()}))${g.exit(pc, d, EXIT_SUSPEND)}`);
// an idle or own monitor is taken inline, so the object's shape is seen by this site alone
emit(`if(${top()}===null)np(${pc});{const mo=${top()}.s;if(mo!==null&&typeof mo==="object"&&mo.owner===null&&t.mounted===null&&!t.blockedOnMonitor){mo.owner=t;mo.count=1}else if(mo!==null&&typeof mo==="object"&&mo.owner===t)mo.count++;else if(!vm.monitorEnter(t,${top()}))${g.exit(pc, d, EXIT_SUSPEND)}}`);
Comment thread
project516-review-bot[bot] marked this conversation as resolved.
Resolved
break;
case 0xc3:
if (region) throw new NoInline();
emit(`if(${top()}===null)np(${pc});vm.monitorExit(t,${top()});`);
emit(`if(${top()}===null)np(${pc});{const mo=${top()}.s;if(mo!==null&&typeof mo==="object"&&mo.owner===t){if(mo.count>1)mo.count--;else if(mo.entry===null&&t.mounted===null){mo.owner=null;mo.count=0}else vm.monitorExit(t,${top()})}else vm.monitorExit(t,${top()})}`);
break;
case 0xc4: {
const wop = c[pc + 1], i = u16(c, pc + 2);
Expand Down Expand Up @@ -1146,7 +1156,7 @@ function regionInvoke(g: Gen, b: Body, op: number, pc: number, d: number, target
let guard: JClass | null = null;
if (op === 0xb9 || !isFixed(op, callee)) {
const site = b.m.cache?.[pc];
if (!site || !site.m.code || site.m.isAbstract || site.m.polymorphic) throw new NoInline();
if (!site?.m?.code || site.m.isAbstract || site.m.polymorphic) throw new NoInline();
callee = site.m;
guard = site.c;
}
Expand Down Expand Up @@ -1179,7 +1189,7 @@ function numLit(v: number): string {

// Bodies that can be inlined at a call site: they neither call nor throw.
type Trivial =
| { kind: "empty" } | { kind: "get"; slot: number } | { kind: "set"; slot: number } | { kind: "const"; value: string }
| { kind: "empty" } | { kind: "get"; key: string } | { kind: "set"; key: string } | { kind: "const"; value: string }
| { kind: "expr"; build: (args: string[]) => string };

// Pure arithmetic on parameters, as one JS expression, or null. Only
Expand Down Expand Up @@ -1208,7 +1218,7 @@ function leafExpr(m: JMethod): ((args: string[]) => string) | null {
const c = code.code;
if (c.length > 32 || code.handlers.length > 0) return null;
// the expression is built from tokens: ["arg", slot] refers to a parameter
type Tok = string | ["arg", number] | ["field", number, number];
type Tok = string | ["arg", number] | ["field", number, string];
const stack: Tok[][] = [];
// negative literals in parentheses, so "a - -5" cannot become "a--5"
const lit = (s: string): Tok[] => [s.startsWith("-") ? `(${s})` : s];
Expand Down Expand Up @@ -1238,7 +1248,7 @@ function leafExpr(m: JMethod): ((args: string[]) => string) | null {
const a = stack.pop();
const fld = m.cls.rcp[(c[pc + 1] << 8) | c[pc + 2]] as JField | undefined;
if (!a || !fld || a.length !== 1 || !Array.isArray(a[0]) || a[0][0] !== "arg" || a[0][1] !== 0) return null;
push = [["field", 0, fld.slot]];
push = [["field", 0, fld.key]];
len = 3;
} else if (op >= 0xac && op <= 0xb0) {
if (pc + 1 !== c.length || stack.length !== 1) return null;
Expand All @@ -1253,7 +1263,7 @@ function leafExpr(m: JMethod): ((args: string[]) => string) | null {
function render(toks: Tok[], args: string[]): string {
return toks.map((x: any) => {
if (typeof x === "string") return x;
if (Array.isArray(x)) return x[0] === "arg" ? args[x[1]] : `${args[x[1]]}.f[${x[2]}]`;
if (Array.isArray(x)) return x[0] === "arg" ? args[x[1]] : `${args[x[1]]}.${x[2]}`;
if (x.op) return x.op(render(x.a, args), render(x.b, args));
return x.op1(render(x.a, args));
}).join("");
Expand All @@ -1275,12 +1285,12 @@ function trivialBody(m: JMethod): Trivial | null {
// aload_0 getfield xreturn
if (c.length === 5 && c[1] === 0xb4 && c[4] >= 0xac && c[4] <= 0xb0) {
const f = field();
return f ? { kind: "get", slot: f.slot } : null;
return f ? { kind: "get", key: f.key } : null;
}
// aload_0 xload_1 putfield return
if (c.length === 6 && [0x1b, 0x1f, 0x23, 0x27, 0x2b].includes(c[1]) && c[2] === 0xb5 && c[5] === 0xb1) {
const f = m.cls.rcp[(c[3] << 8) | c[4]] as JField | undefined;
return f ? { kind: "set", slot: f.slot } : null;
return f ? { kind: "set", key: f.key } : null;
}
const build = leafExpr(m);
return build ? { kind: "expr", build } : null;
Expand All @@ -1291,8 +1301,8 @@ function genInline(body: Trivial, res: string, args: string[], pc: number, check
switch (body.kind) {
case "empty": return nullCheck;
case "const": return `${nullCheck}${res}=${body.value};`;
case "get": return `${nullCheck}${res}=${args[0]}.f[${body.slot}];`;
case "set": return `${nullCheck}${args[0]}.f[${body.slot}]=${args[1]};`;
case "get": return `${nullCheck}${res}=${args[0]}.${body.key};`;
case "set": return `${nullCheck}${args[0]}.${body.key}=${args[1]};`;
case "expr": return `${nullCheck}${res}=${body.build(args)};`;
}
}
Expand All @@ -1314,7 +1324,7 @@ function genInvoke(
let seen = false;
if (guard !== null && !target.isPrivate) {
const site = g.top.m.cache?.[pc];
if (site && site.m.code && !site.m.isAbstract && !site.m.polymorphic) {
if (site?.m?.code && !site.m.isAbstract && !site.m.polymorphic) {
callee = site.m;
guard = site.c;
seen = true;
Expand Down Expand Up @@ -1345,7 +1355,7 @@ function genInvoke(
if (op === 0xb6 || op === 0xb9) {
if (target.isPrivate) parts.push(`tm=${K(target)};${known ? "" : `if(${args[0]}===null)np(${pc});`}`);
else {
const cell = K([null, null, target.key]);
const cell = K([null, null, target.key, false]);
parts.push(`ic=${cell};tm=${args[0]}!==null&&${args[0]}.cls===ic[0]?ic[1]:rt.select(${args[0]},ic,${pc});`);
}
} else if (op === 0xb7) {
Expand Down Expand Up @@ -1374,7 +1384,7 @@ function genGuardMiss(g: Gen, pc: number, next: number, d: number, target: JMeth
const args = Array.from({ length: n }, (_, i) => `s${base + i}`);
const ret = target.ret;
const xp = g.xcode(pc, base, EXIT_SUSPEND), xi = g.xcode(pc, d, EXIT_INTERPRET);
const cell = g.K([null, null, target.key]);
const cell = g.K([null, null, target.key, false]);
const call = n <= 4 ? `rt.callv(t,f,${cell},${pc},${xp},${xi},${args})` : `rt.callvMany(t,f,${cell},[${args}],${pc},${xp},${xi})`;
return `v=${call};if(v===rt.E){x=rt.xc;break X;}${ret === "V" ? "" : `s${base}=v;`}` +
`if(t.state!==0)${g.exit(next, ret === "V" ? base : base + (isWide(ret) ? 2 : 1), EXIT_SUSPEND)}`;
Expand Down
Loading