Skip to content

Commit fef033f

Browse files
authored
Fix OnOutOfMemoryError, MaxDirectMemorySize, access times and WatchService failures (#67)
1 parent 316cc11 commit fef033f

20 files changed

Lines changed: 483 additions & 56 deletions

‎docs/node.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ resolves to the exit code. Its options:
4949
- `natives`: Java `native` methods in JS, as in the browser ([browser.md](browser.md))
5050
- `assertions` (the flags, for example `["-ea"]`), `enablePreview`, `localeData`
5151
- `hostName` (what `InetAddress.getLocalHost()` reports), `maxRssMb`, `jdk`, `debug`
52+
- `maxDirectMemory` (`-XX:MaxDirectMemorySize`, in bytes), `onOutOfMemoryError` (`-XX:OnOutOfMemoryError` commands),
53+
`vmOutputToStderr` (`-XX:+DisplayVMOutputToStderr`)
5254
- `fetch`: sockets stay inside the VM, and `http:` requests go to this `fetch`, as in the browser
5355

5456
- `snapshotDir`: where boot snapshots are kept, or `null` for none (see below)

‎docs/support.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,18 @@ java-web targets headless Java: console apps, libraries and javac.
2929
host's inode numbers and link counts, and the modes `open` and `mkdir` ask
3030
for, less the process's umask. In-memory files get synthetic inode numbers, a
3131
link count of 1 and default modes.
32-
- `-XX:OnOutOfMemoryError` runs no command, and `StackWalker`
32+
- `-XX:OnOutOfMemoryError` runs its commands under Node only, and `StackWalker`
3333
has no live locals or operands. A virtual thread that yields while it
3434
holds a monitor stays pinned to its carrier.
3535
- `ThreadMXBean` describes threads and finds deadlocks, but has no CPU times
3636
and no blocked or waited times (contention monitoring is off). Thread dumps
3737
find a frame's locked monitors from its synchronized blocks as compilers emit
3838
them, and list a monitor taken any other way with stack depth -1.
3939
- `WatchService` reports files the program itself, or another thread in the
40-
same VM, creates, changes or deletes. It does not see changes made outside
41-
the VM, including by child processes the program starts.
40+
same VM, creates, changes or deletes. Under Node it also reports what other
41+
processes do to a watched host directory, with Node's `fs.watch` (so a short-lived
42+
entry can show as a delete without its create). Elsewhere it does not see
43+
changes made outside the VM.
4244
- Not supported: GUI apps (AWT and Swing windows), `ConvolveOp`, child
4345
processes in the browser, and native libraries other than JS natives.
4446

‎src/fs.ts‎

Lines changed: 67 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,13 @@ export interface Stat {
1616
// the modification time in nanoseconds, when it was set with more precision
1717
// than mtime keeps
1818
mtimeNs?: bigint;
19+
// the access time, when the backend keeps one (mtime otherwise), and in nanoseconds
20+
atime?: number;
21+
atimeNs?: bigint;
1922
// permission and special bits, when the backend can report them
2023
mode?: number;
24+
// a socket, FIFO or device on the host, which cannot be opened here
25+
special?: boolean;
2126
// a character device; it streams and is never read whole
2227
device?: boolean;
2328
// lstat of a symbolic link: the length of its target, which is also its size
@@ -60,8 +65,8 @@ export interface Backend {
6065
rename?(from: string, to: string): boolean;
6166
// the file system holding path: block size and block counts, as statvfs gives them
6267
space?(path: string): Space | null;
63-
// sets the modification time, in milliseconds since the epoch
64-
setMtime?(path: string, ms: number, noFollow?: boolean): boolean;
68+
// sets the modification time, and the access time when given, in milliseconds since the epoch
69+
setMtime?(path: string, ms: number, noFollow?: boolean, atimeMs?: number): boolean;
6570
// whether the host refuses to write the file, or to create it when it is missing
6671
denied?(path: string): boolean;
6772
// sets the permission bits to f(current bits)
@@ -76,6 +81,10 @@ export interface Backend {
7681
link?(existing: string, path: string): string | undefined;
7782
// the path with every link resolved, where the missing tail stays as written
7883
realpath?(path: string): string | null;
84+
// reports changes others make to a directory's entries (name "" is the directory itself); returns what stops it
85+
watch?(path: string, onEvent: (name: string, event: "create" | "modify" | "delete") => void): (() => void) | null;
86+
// changes whenever the entry's content or times do, or is "" when it is missing
87+
signature?(path: string): string;
7988
}
8089

8190
export interface WarmTrace {
@@ -104,7 +113,7 @@ export function normalize(path: string): string {
104113

105114
export class VFS {
106115
// path -> the time a VM set, and the mtime the backend reported right after
107-
private setTimes = new Map<string, { ms: number; ns: bigint }>();
116+
private setTimes = new Map<string, { ms: number; ns: bigint; atime?: { ms: number; ns: bigint } }>();
108117
private mounts: { prefix: string; backend: Backend }[] = [];
109118
private hidden: string[] = [];
110119
private warmTrace: WarmTrace | null = null;
@@ -229,6 +238,51 @@ export class VFS {
229238
private changedNormalized(path: string, event: "create" | "modify" | "delete") {
230239
for (const watcher of this.watchers) watcher(path, event);
231240
this.warmChanged?.add(path);
241+
if (this.hostWatches.size === 0) return;
242+
const watch = this.hostWatches.get(parentOf(path));
243+
if (watch) watch.own.set(path.slice(path.lastIndexOf("/") + 1), this.signature(path));
244+
}
245+
246+
// Host directories being watched: the entries as the VM last left them, so
247+
// that only changes others make reach watchers a second time.
248+
private hostWatches = new Map<string, { stop: () => void; refs: number; own: Map<string, string> }>();
249+
250+
private signature(path: string): string {
251+
const r = this.resolve(path);
252+
return (r && r[0].signature?.(r[1])) ?? "";
253+
}
254+
255+
// Starts reporting what others do to a directory on a host backend, as
256+
// inotify does; the VM's own changes already reach watchers. Returns what stops it.
257+
watchDirectory(path: string): () => void {
258+
const dir = normalize(path);
259+
let watch = this.hostWatches.get(dir);
260+
if (!watch) {
261+
const r = this.resolve(dir);
262+
const stop = r?.[0].watch?.(r[1], (name, event) => this.hostChanged(dir, name, event));
263+
if (!stop) return () => {};
264+
watch = { stop, refs: 0, own: new Map() };
265+
this.hostWatches.set(dir, watch);
266+
}
267+
const w = watch;
268+
w.refs++;
269+
let done = false;
270+
return () => {
271+
if (done) return;
272+
done = true;
273+
if (--w.refs === 0) {
274+
w.stop();
275+
if (this.hostWatches.get(dir) === w) this.hostWatches.delete(dir);
276+
}
277+
};
278+
}
279+
280+
private hostChanged(dir: string, name: string, event: "create" | "modify" | "delete") {
281+
const watch = this.hostWatches.get(dir);
282+
if (!watch) return;
283+
const path = name === "" ? dir : (dir === "/" ? "" : dir) + "/" + name;
284+
if (name !== "" && watch.own.get(name) === this.signature(path)) return;
285+
for (const watcher of this.watchers) watcher(path, event);
232286
}
233287

234288
resolvePath(path: string): string {
@@ -289,7 +343,10 @@ export class VFS {
289343
const s = r ? r[0].stat(r[1]) : null;
290344
if (s) {
291345
const set = this.setTimes.get(n);
292-
if (set?.ms === s.mtime) return { ...s, mtimeNs: set.ns };
346+
if (set?.ms === s.mtime) {
347+
const atime = set.atime && set.atime.ms === s.atime ? { atimeNs: set.atime.ns } : {};
348+
return { ...s, mtimeNs: set.ns, ...atime };
349+
}
293350
if (set) this.setTimes.delete(n);
294351
return s;
295352
}
@@ -474,16 +531,18 @@ export class VFS {
474531
// ns, when given, is the exact time asked for. Hosts keep times as floating
475532
// point seconds or milliseconds, which lose nanoseconds, so stat reports ns
476533
// for as long as the file keeps the time this set.
477-
setMtime(path: string, ms: number, ns?: bigint, noFollow = false): boolean {
534+
setMtime(path: string, ms: number, ns?: bigint, noFollow = false, atime?: { ms: number; ns: bigint }): boolean {
478535
const r = this.resolve(path);
479-
if (!r || !r[0].writable || !r[0].setMtime?.(r[1], ms, noFollow)) return false;
536+
if (!r || !r[0].writable || !r[0].setMtime?.(r[1], ms, noFollow, atime?.ms)) return false;
480537
this.changed(path, "modify");
481538
if (noFollow) return true;
482539
const n = normalize(path);
483540
const st = ns === undefined ? null : r[0].stat(r[1]);
484541
// only a time the host kept, give or take its rounding; a host can clamp it
485-
if (st && Math.abs(st.mtime - ms) < 1) this.setTimes.set(n, { ms: st.mtime, ns: ns! });
486-
else this.setTimes.delete(n);
542+
if (st && Math.abs(st.mtime - ms) < 1) {
543+
const kept = atime && st.atime !== undefined && Math.abs(st.atime - atime.ms) < 1;
544+
this.setTimes.set(n, { ms: st.mtime, ns: ns!, ...(kept ? { atime: { ms: st.atime!, ns: atime.ns } } : {}) });
545+
} else this.setTimes.delete(n);
487546
return true;
488547
}
489548

‎src/jvm.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ export interface JvmOptions {
5757
loadNativeLibrary?: (path: string) => Promise<void>;
5858
// told when Java closes a file it wrote
5959
fileClosed?: (path: string) => void;
60+
// runs before the first OutOfMemoryError the VM throws is created
61+
onOutOfMemory?: (message: string | null) => void;
6062
// log VM internals to the host console
6163
debug?: boolean;
6264
assertions?: Assertions;
@@ -837,6 +839,7 @@ export class JVM {
837839

838840
*newThrowable(t: JThread, name: string, msg: string | null, cause: JObject | null = null,
839841
ctor?: { desc: string; args: any[] }): NativeGen {
842+
if (name === "java/lang/OutOfMemoryError") this.reportOutOfMemory(msg);
840843
const c = this.loadBootOrFail(name);
841844
if (c.state !== INITIALIZED) yield* this.initGen(t, c);
842845
const o = this.newObject(c);
@@ -852,6 +855,13 @@ export class JVM {
852855
return o;
853856
}
854857

858+
private oomReported = false;
859+
private reportOutOfMemory(msg: string | null) {
860+
if (this.oomReported || !this.opts.onOutOfMemory) return;
861+
this.oomReported = true;
862+
this.opts.onOutOfMemory(msg);
863+
}
864+
855865
// native: the native method throwing it, shown in its stack trace
856866
throwNew(t: JThread, name: string, msg: string | null, ctor?: { desc: string; args: any[] }, native: JMethod | null = null) {
857867
const vm = this;

‎src/natives/io.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -412,9 +412,9 @@ export function syncPath(t: JThread, abs: string) {
412412
}
413413

414414
// Pending writes go out first, so closing the file later does not change the time again.
415-
export function setMtime(t: JThread, abs: string, ms: number, ns?: bigint, noFollow = false): boolean {
415+
export function setMtime(t: JThread, abs: string, ms: number, ns?: bigint, noFollow = false, atime?: { ms: number; ns: bigint }): boolean {
416416
syncPath(t, abs);
417-
return t.vm.fs.setMtime(abs, ms, ns, noFollow);
417+
return t.vm.fs.setMtime(abs, ms, ns, noFollow, atime);
418418
}
419419

420420
// write(2) on a descriptor opened read-only fails with EBADF.

‎src/natives/nio.ts‎

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@ import { closeFd, DirectoryFile, newFd, fileInode, fileOf, flush, flushOrThrow,
1010
import type { OpenFile } from "./io.ts";
1111
import type { Natives } from "./util.ts";
1212

13-
export const EPERM = 1, ENOENT = 2, EINTR = 4, EIO = 5, EBADF = 9, ENOMEM = 12, EACCES = 13,
13+
export const EPERM = 1, ENOENT = 2, EINTR = 4, EIO = 5, ENXIO = 6, EBADF = 9, ENOMEM = 12, EACCES = 13,
1414
EEXIST = 17, EXDEV = 18, ENOTDIR = 20, EISDIR = 21, EINVAL = 22, ENOSPC = 28, EROFS = 30,
1515
ENOTEMPTY = 39, ENOSYS = 38, ENAMETOOLONG = 36, ELOOP = 40, ENOTSUP = 95, ESTALE = 116, EDQUOT = 122;
1616

1717
const MESSAGES: Record<number, string> = {
18-
[EPERM]: "Operation not permitted", [EINTR]: "Interrupted system call", [EIO]: "Input/output error",
18+
[EPERM]: "Operation not permitted", [ENXIO]: "No such device or address", [EINTR]: "Interrupted system call", [EIO]: "Input/output error",
1919
[ENOMEM]: "Cannot allocate memory", [ENOSPC]: "No space left on device",
2020
[ELOOP]: "Too many levels of symbolic links", [ENOTSUP]: "Operation not supported", [ESTALE]: "Stale file handle",
2121
[ENAMETOOLONG]: "File name too long", [EDQUOT]: "Disk quota exceeded",
@@ -103,10 +103,12 @@ function renameAbs(t: JThread, from: string, to: string) {
103103
}
104104

105105
function openAbs(t: JThread, abs: string, flags: number, mode: number): number {
106+
// before any stat that follows the link, which would touch its access time
107+
if (flags & O_NOFOLLOW && !(flags & O_CREAT && flags & O_EXCL) && t.vm.fs.lstat(abs)?.link !== undefined) unixError(ELOOP);
106108
const st = t.vm.fs.stat(abs);
107109
if ((flags & O_CREAT) && (flags & O_EXCL) && (st || t.vm.fs.lstat(abs))) unixError(EEXIST);
110+
if (st?.special) unixError(ENXIO);
108111
if (!st && !(flags & O_CREAT)) unixError(ENOENT);
109-
if (flags & O_NOFOLLOW && t.vm.fs.lstat(abs)?.link !== undefined) unixError(ELOOP);
110112
if (flags & O_DIRECTORY && st && !st.dir) unixError(ENOTDIR);
111113
const write = (flags & O_ACCMODE) !== 0;
112114
if (st?.dir && write) unixError(EISDIR);
@@ -162,25 +164,30 @@ function fillAttrs(t: JThread, attrs: JObject, p: string, follow = true): number
162164
return 0;
163165
}
164166

167+
// seconds and nanoseconds of a time kept as milliseconds, or exactly as nanoseconds
168+
function splitTime(ms: number, ns?: bigint): [bigint, bigint] {
169+
if (ns === undefined) return [BigInt(Math.floor(ms / 1000)), BigInt(Math.floor((ms % 1000) * 1e6))];
170+
const sec = ns / 1_000_000_000n, nsec = ns % 1_000_000_000n;
171+
// before 1970: whole seconds round down, nanoseconds stay positive
172+
return nsec < 0n ? [sec - 1n, nsec + 1_000_000_000n] : [sec, nsec];
173+
}
174+
165175
function fillStat(t: JThread, attrs: JObject, st: Stat, writable: boolean, ino: number, size = st.size, nlink = 1) {
166176
const vm = t.vm, A = "sun/nio/fs/UnixFileAttributes";
167177
const mode = st.device ? S_IFCHR | 0o666 : (st.link !== undefined ? S_IFLNK : st.dir ? S_IFDIR : S_IFREG) | (st.mode ?? (st.dir ? (writable ? 0o755 : 0o555) : (writable ? 0o644 : 0o444)));
168-
let sec = BigInt(Math.floor(st.mtime / 1000)), nsec = BigInt(Math.floor((st.mtime % 1000) * 1e6));
169-
if (st.mtimeNs !== undefined) {
170-
sec = st.mtimeNs / 1_000_000_000n;
171-
nsec = st.mtimeNs % 1_000_000_000n;
172-
// before 1970: whole seconds round down, nanoseconds stay positive
173-
if (nsec < 0n) [sec, nsec] = [sec - 1n, nsec + 1_000_000_000n];
174-
}
178+
const [sec, nsec] = splitTime(st.mtime, st.mtimeNs);
175179
vm.setField(attrs, A, "st_mode", mode);
176180
vm.setField(attrs, A, "st_ino", BigInt(ino));
177181
vm.setField(attrs, A, "st_dev", 1n);
178182
vm.setField(attrs, A, "st_nlink", nlink);
179183
vm.setField(attrs, A, "st_uid", 1000);
180184
vm.setField(attrs, A, "st_gid", 1000);
181185
vm.setField(attrs, A, "st_size", BigInt(size));
182-
for (const k of ["st_atime_sec", "st_mtime_sec", "st_ctime_sec"]) vm.setField(attrs, A, k, sec);
183-
for (const k of ["st_atime_nsec", "st_mtime_nsec", "st_ctime_nsec"]) vm.setField(attrs, A, k, nsec);
186+
for (const k of ["st_mtime_sec", "st_ctime_sec"]) vm.setField(attrs, A, k, sec);
187+
for (const k of ["st_mtime_nsec", "st_ctime_nsec"]) vm.setField(attrs, A, k, nsec);
188+
const [asec, ansec] = splitTime(st.atime ?? st.mtime, st.atimeNs);
189+
vm.setField(attrs, A, "st_atime_sec", asec);
190+
vm.setField(attrs, A, "st_atime_nsec", ansec);
184191
}
185192

186193
// open mount table handles: whether the one entry has been read
@@ -310,15 +317,15 @@ export const natives: Natives = {
310317
[`${N}chown0(JII)V`]: () => undefined,
311318
[`${N}lchown0(JII)V`]: () => undefined,
312319
[`${N}fchown0(III)V`]: () => undefined,
313-
// times in nanoseconds; only the modification time is kept
314-
[`${N}utimensat0(IJJJI)V`]: (t, [dfd, p, , mtime, flags]) => {
320+
// times in nanoseconds; in-memory files keep only the modification time
321+
[`${N}utimensat0(IJJJI)V`]: (t, [dfd, p, atime, mtime, flags]) => {
315322
const abs = pathAt(t, dfd, p);
316323
if (!t.vm.fs.lstat(abs)) unixError(ENOENT);
317-
if (!setMtime(t, abs, Number(mtime) / 1e6, BigInt(mtime), (flags & AT_SYMLINK_NOFOLLOW) !== 0)) unixError(EROFS);
324+
if (!setMtime(t, abs, Number(mtime) / 1e6, BigInt(mtime), (flags & AT_SYMLINK_NOFOLLOW) !== 0, { ms: Number(atime) / 1e6, ns: BigInt(atime) })) unixError(EROFS);
318325
},
319-
[`${N}futimens0(IJJ)V`]: (t, [fd, , mtime]) => {
326+
[`${N}futimens0(IJJ)V`]: (t, [fd, atime, mtime]) => {
320327
const f = fileOf(t, fd);
321-
if (!setMtime(t, f.path, Number(mtime) / 1e6, BigInt(mtime))) unixError(EROFS);
328+
if (!setMtime(t, f.path, Number(mtime) / 1e6, BigInt(mtime), false, { ms: Number(atime) / 1e6, ns: BigInt(atime) })) unixError(EROFS);
322329
},
323330
[`${N}opendir0(J)J`]: (t, [p]) => {
324331
const abs = path(t, p);

0 commit comments

Comments
 (0)