Skip to content

Commit e0360df

Browse files
authored
Give native memory back after unmapping, and fail oversized mappings like HotSpot (#56)
1 parent b805c11 commit e0360df

9 files changed

Lines changed: 215 additions & 24 deletions

File tree

‎docs/support.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ java-web targets headless Java: console apps, libraries and javac.
99
- `java.desktop`'s headless parts work: 2D geometry, image pixels, `Graphics2D`
1010
drawing on a `BufferedImage`, and JavaBeans. So does `java.xml`, including
1111
XML Schema validation and DTDs from the JDK's built-in catalog.
12+
- File mappings are copies in the VM's 512 MB native memory, which is also
13+
shared with direct buffers and other native allocations. A mapping that does
14+
not fit fails with `IOException: Map failed` and an `OutOfMemoryError` cause.
15+
Read-write changes reach the file on force or unmap.
1216
- `Deflater` writes valid DEFLATE streams using stored blocks. Compression
1317
levels and strategies currently do not reduce output size; compressed bytes
1418
and compression ratios differ from HotSpot's zlib output.

‎src/memory.ts‎

Lines changed: 73 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { PendingThrow } from "./thread.ts";
66
const ALIGN = 16;
77
// Like a failed malloc in HotSpot, going past this throws OutOfMemoryError.
88
const LIMIT = 512 << 20;
9+
const MIN_SHRINK = 2 << 20;
910

1011
export class NativeMemory {
1112
buf: ArrayBuffer;
@@ -15,40 +16,79 @@ export class NativeMemory {
1516
private sizes = new Map<number, number>();
1617
// free blocks by size
1718
private free = new Map<number, number[]>();
19+
// end address to size, and start address to list index, for the free blocks
20+
private freeEnds = new Map<number, number>();
21+
private freeAt = new Map<number, number>();
22+
23+
private initial: number;
1824

1925
constructor(initial = 1 << 20) {
26+
this.initial = initial;
2027
this.buf = new ArrayBuffer(initial);
2128
this.u8 = new Uint8Array(this.buf);
2229
this.dv = new DataView(this.buf);
2330
}
2431

32+
private resize(size: number) {
33+
const next = new ArrayBuffer(size);
34+
new Uint8Array(next).set(this.u8.subarray(0, Math.min(this.top, size)));
35+
this.buf = next;
36+
this.u8 = new Uint8Array(next);
37+
this.dv = new DataView(next);
38+
}
39+
2540
private grow(need: number) {
2641
if (need > LIMIT) throw new PendingThrow("java/lang/OutOfMemoryError", `Unable to allocate ${need - this.buf.byteLength} bytes`);
2742
let size = this.buf.byteLength;
2843
while (size < need) size *= 2;
2944
size = Math.min(size, LIMIT);
30-
const next = new ArrayBuffer(size);
31-
new Uint8Array(next).set(this.u8);
32-
this.buf = next;
33-
this.u8 = new Uint8Array(next);
34-
this.dv = new DataView(next);
45+
try { this.resize(size); }
46+
catch (e) {
47+
if (e instanceof RangeError) throw new PendingThrow("java/lang/OutOfMemoryError", `Unable to allocate ${size} bytes`);
48+
throw e;
49+
}
50+
}
51+
52+
// The saved state of a snapshot: the bytes up to top and the block tables.
53+
restore(bytes: Uint8Array, top: number, sizes: Map<number, number>, free: Map<number, number[]>) {
54+
this.buf = new ArrayBuffer(Math.max(this.buf.byteLength, bytes.length));
55+
this.u8 = new Uint8Array(this.buf);
56+
this.dv = new DataView(this.buf);
57+
this.u8.set(bytes);
58+
this.top = top;
59+
this.sizes = sizes;
60+
this.free = free;
61+
this.freeEnds.clear();
62+
this.freeAt.clear();
63+
for (const [size, blocks] of free) {
64+
blocks.forEach((start, i) => { this.freeEnds.set(start + size, size); this.freeAt.set(start, i); });
65+
}
66+
}
67+
68+
// The order of a free list does not matter, so the last block fills the gap.
69+
private takeFree(size: number, list: number[], at: number): number {
70+
const addr = list[at];
71+
const last = list.pop()!;
72+
if (at < list.length) { list[at] = last; this.freeAt.set(last, at); }
73+
if (!list.length) this.free.delete(size);
74+
this.freeAt.delete(addr);
75+
this.freeEnds.delete(addr + size);
76+
return addr;
3577
}
3678

3779
malloc(n: number, alignment = ALIGN): number {
3880
const size = Math.max(ALIGN, Math.ceil(n / ALIGN) * ALIGN);
3981
const list = this.free.get(size);
4082
const reuse = list?.findIndex((addr) => addr % alignment === 0) ?? -1;
4183
if (list && reuse >= 0) {
42-
// the order of a free list does not matter, so the last block fills the gap
43-
const addr = list[reuse];
44-
list[reuse] = list[list.length - 1];
45-
list.pop();
84+
const addr = this.takeFree(size, list, reuse);
4685
this.sizes.set(addr, size);
4786
return addr;
4887
}
4988
const addr = Math.ceil(this.top / alignment) * alignment;
50-
this.top = addr + size;
51-
if (this.top > this.buf.byteLength) this.grow(this.top);
89+
const top = addr + size;
90+
if (top > this.buf.byteLength) this.grow(top);
91+
this.top = top;
5292
this.sizes.set(addr, size);
5393
return addr;
5494
}
@@ -57,9 +97,28 @@ export class NativeMemory {
5797
const size = this.sizes.get(addr);
5898
if (size === undefined) return;
5999
this.sizes.delete(addr);
60-
let list = this.free.get(size);
61-
if (!list) this.free.set(size, (list = []));
62-
list.push(addr);
100+
if (addr + size < this.top) {
101+
let list = this.free.get(size);
102+
if (!list) this.free.set(size, (list = []));
103+
this.freeAt.set(addr, list.push(addr) - 1);
104+
this.freeEnds.set(addr + size, size);
105+
return;
106+
}
107+
// Lower top over this block and any free blocks that end where it starts.
108+
let top = addr;
109+
for (let below = this.freeEnds.get(top); below !== undefined; below = this.freeEnds.get(top)) {
110+
top -= below;
111+
this.takeFree(below, this.free.get(below)!, this.freeAt.get(top)!);
112+
}
113+
this.top = Math.max(top, ALIGN);
114+
if (this.buf.byteLength >= MIN_SHRINK && this.top <= this.buf.byteLength / 4) {
115+
const size = Math.max(this.initial, 2 ** Math.ceil(Math.log2(this.top)));
116+
// best effort: a free must not fail
117+
if (size < this.buf.byteLength) {
118+
try { this.resize(size); }
119+
catch (e) { if (!(e instanceof RangeError)) throw e; }
120+
}
121+
}
63122
}
64123

65124
realloc(addr: number, n: number): number {

‎src/natives/nio.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ function writeBack(t: JThread, m: Mapping, base: number, addr: number, len: numb
333333
if (n <= 0) return true;
334334
const save = m.f.pos;
335335
m.f.pos = at;
336-
m.f.write(t.vm.mem.u8.slice(addr, addr + n), true);
336+
m.f.write(t.vm.mem.u8.subarray(addr, addr + n), true);
337337
m.f.pos = save;
338338
return flush(t, m.f);
339339
}
@@ -429,7 +429,13 @@ Object.assign(natives, {
429429
// writes only then.
430430
[`${UFD}map0(Ljava/io/FileDescriptor;IJJZ)J`]: (t: JThread, [fd, prot, pos, len]: any[]) => {
431431
const f = chanFile(t, fd);
432-
const addr = t.vm.mem.malloc(Number(len), 4096);
432+
let addr: number;
433+
try { addr = t.vm.mem.malloc(Number(len), 4096); }
434+
catch (e) {
435+
// FileChannelImpl retries once, then wraps this in IOException("Map failed")
436+
if (e instanceof PendingThrow) throw new PendingThrow("java/lang/OutOfMemoryError", "Map failed");
437+
throw e;
438+
}
433439
const save = f.pos;
434440
f.pos = Number(pos);
435441
const n = Math.min(f.size - Number(pos), Number(len));

‎src/snapshot.ts‎

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -417,14 +417,7 @@ export function restoreVM(vm: JVM, image: SnapshotImage, main: JThread) {
417417
vm.state.set(k, { next: fds.next, files });
418418
} else vm.state.set(k, d.dec(x));
419419
}
420-
const mem = vm.mem as any;
421-
mem.buf = new ArrayBuffer(Math.max(mem.buf.byteLength, v.mem.buf.length));
422-
mem.u8 = new Uint8Array(mem.buf);
423-
mem.dv = new DataView(mem.buf);
424-
mem.u8.set(v.mem.buf);
425-
mem.top = v.mem.top;
426-
mem.sizes = d.dec(v.mem.sizes);
427-
mem.free = d.dec(v.mem.free);
420+
vm.mem.restore(v.mem.buf, v.mem.top, d.dec(v.mem.sizes), d.dec(v.mem.free));
428421
d.flush();
429422

430423
const mainRec = image.threads[0];

‎test/java/MappedFile.java‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.io.RandomAccessFile;
2+
import java.nio.MappedByteBuffer;
3+
import java.nio.channels.FileChannel;
4+
import java.nio.file.Files;
5+
import java.nio.file.Path;
6+
import sun.misc.Unsafe;
7+
import java.lang.reflect.Field;
8+
9+
public class MappedFile {
10+
public static void main(String[] args) throws Exception {
11+
Path path = Files.createTempFile("mapped", ".bin");
12+
try {
13+
try (RandomAccessFile file = new RandomAccessFile(path.toFile(), "rw")) {
14+
file.setLength(4 * 1024 * 1024);
15+
MappedByteBuffer map = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, file.length());
16+
map.put(0, (byte) 17);
17+
map.put(2 * 1024 * 1024, (byte) 42);
18+
map.force();
19+
map.put(4 * 1024 * 1024 - 1, (byte) 99);
20+
Field field = Unsafe.class.getDeclaredField("theUnsafe");
21+
field.setAccessible(true);
22+
((Unsafe) field.get(null)).invokeCleaner(map);
23+
file.seek(0);
24+
System.out.println(file.read());
25+
file.seek(2 * 1024 * 1024);
26+
System.out.println(file.read());
27+
file.seek(file.length() - 1);
28+
System.out.println(file.read());
29+
}
30+
} finally {
31+
Files.delete(path);
32+
}
33+
}
34+
}

‎test/jtreg/passing.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1967,6 +1967,7 @@ java/nio/channels/DatagramChannel/ThereCanBeOnlyOne.java
19671967
java/nio/channels/DatagramChannel/Truncate.java
19681968
java/nio/channels/DatagramChannel/UseDGWithIPv6.java
19691969
java/nio/channels/FileChannel/Args.java
1970+
java/nio/channels/FileChannel/AtomicAppend.java
19701971
java/nio/channels/FileChannel/CloseDuringTransfer.java
19711972
java/nio/channels/FileChannel/ClosedByInterrupt.java
19721973
java/nio/channels/FileChannel/ClosedChannelTransfer.java

‎test/jtreg/times.tsv‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3065,6 +3065,7 @@
30653065
2080 java/lang/ClassLoader/LoadNullClass.java
30663066
2078 java/io/Serializable/InvalidObjectException/TestIoeConstructors.java
30673067
2077 java/io/Serializable/enum/array/Test.java
3068+
2076 java/nio/channels/FileChannel/AtomicAppend.java
30683069
2075 java/lang/Byte/Decode.java
30693070
2072 java/nio/channels/FileChannel/TransferTo6GBFile.java
30703071
2071 java/util/concurrent/forkjoin/AsyncShutdownNow.java

‎test/memory.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,79 @@ test("mapped allocations are page aligned and reusable", () => {
1010
mem.freeBlock(page);
1111
assert.equal(mem.malloc(128, 4096), page);
1212
});
13+
14+
test("releases a large top allocation and preserves live blocks", () => {
15+
const mem = new NativeMemory();
16+
const first = mem.malloc(32);
17+
mem.u8[first] = 123;
18+
const middle = mem.malloc(32);
19+
const large = mem.malloc(16 << 20, 4096);
20+
mem.freeBlock(middle);
21+
mem.freeBlock(large);
22+
assert.equal(mem.buf.byteLength, 1 << 20);
23+
assert.equal(mem.u8[first], 123);
24+
assert.equal(mem.malloc(32), middle);
25+
});
26+
27+
test("a failed allocation leaves memory usable", () => {
28+
const mem = new NativeMemory();
29+
const addr = mem.malloc(32);
30+
assert.throws(() => mem.malloc(512 << 20));
31+
assert.equal(mem.malloc(32), addr + 32);
32+
});
33+
34+
test("freeing blocks in any order lowers top over adjacent free blocks", () => {
35+
const mem = new NativeMemory();
36+
const a = mem.malloc(64);
37+
const b = mem.malloc(64);
38+
const c = mem.malloc(64);
39+
mem.freeBlock(b);
40+
mem.freeBlock(a);
41+
mem.freeBlock(c);
42+
assert.equal(mem.malloc(64), a);
43+
});
44+
45+
test("small frees keep the buffer", () => {
46+
const mem = new NativeMemory(4 << 20);
47+
const buf = mem.buf;
48+
mem.freeBlock(mem.malloc(32));
49+
assert.equal(mem.buf, buf);
50+
});
51+
52+
test("a restored memory lowers top over free blocks", () => {
53+
const mem = new NativeMemory();
54+
const a = mem.malloc(64);
55+
const b = mem.malloc(64);
56+
const c = mem.malloc(64);
57+
mem.freeBlock(b);
58+
const state = mem as any;
59+
const copy = new NativeMemory();
60+
copy.restore(state.u8.slice(0, state.top), state.top, new Map(state.sizes), new Map([...state.free].map(([k, v]) => [k, [...v]])));
61+
copy.freeBlock(c);
62+
copy.freeBlock(a);
63+
assert.equal(copy.malloc(64), a);
64+
assert.equal(copy.malloc(64), b);
65+
});
66+
67+
test("freeing many same-sized blocks then the top merges them all", () => {
68+
const mem = new NativeMemory();
69+
const blocks = Array.from({ length: 20000 }, () => mem.malloc(32));
70+
const top = mem.malloc(32);
71+
for (let i = blocks.length - 1; i >= 0; i--) mem.freeBlock(blocks[i]);
72+
mem.freeBlock(top);
73+
assert.equal(mem.malloc(32), blocks[0]);
74+
assert.equal(mem.malloc(32), blocks[1]);
75+
});
76+
77+
test("reused free blocks keep the merge index consistent", () => {
78+
const mem = new NativeMemory();
79+
const [a, b, c, d] = [mem.malloc(32), mem.malloc(32), mem.malloc(32), mem.malloc(32)];
80+
mem.freeBlock(a);
81+
mem.freeBlock(b);
82+
mem.freeBlock(c);
83+
assert.equal(mem.malloc(32), a);
84+
mem.freeBlock(d);
85+
assert.equal(mem.malloc(32), b);
86+
mem.freeBlock(a);
87+
assert.equal(mem.malloc(32), a);
88+
});

‎test/nio.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import { natives } from "../src/natives/nio.ts";
99
import { PendingThrow } from "../src/thread.ts";
1010
import type { JThread } from "../src/thread.ts";
1111
import { NodeBackend } from "../src/node.ts";
12+
import { NativeMemory } from "../src/memory.ts";
13+
import { OpenFile } from "../src/natives/io.ts";
1214

1315
function thread(backend: Backend): JThread {
1416
const fs = new VFS();
@@ -122,3 +124,18 @@ test("a large file on a read-only host mount uses a handle", async () => {
122124
rmSync(dir, { recursive: true, force: true });
123125
}
124126
});
127+
128+
test("map0 of a region that does not fit throws OutOfMemoryError for FileChannelImpl to wrap", () => {
129+
const backend = memory();
130+
const t = thread(backend);
131+
const vm = t.vm as any;
132+
vm.mem = new NativeMemory();
133+
vm.state.set("fds", { files: new Map([[3, new OpenFile("/file", new Uint8Array(1), false)]]) });
134+
vm.getField = () => 3;
135+
assert.throws(() => natives["sun/nio/ch/UnixFileDispatcherImpl.map0(Ljava/io/FileDescriptor;IJJZ)J"](t, [{}, 0, 0n, 600n << 20n]), (e) => {
136+
assert.ok(e instanceof PendingThrow);
137+
assert.equal(e.cls, "java/lang/OutOfMemoryError");
138+
assert.equal(e.msg, "Map failed");
139+
return true;
140+
});
141+
});

0 commit comments

Comments
 (0)