Skip to content

Commit 7cb565f

Browse files
committed
Stream sparse file writes without allocating their gaps.
1 parent 468c0f3 commit 7cb565f

7 files changed

Lines changed: 137 additions & 14 deletions

File tree

‎src/fs.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -297,14 +297,14 @@ export class VFS {
297297
return data;
298298
}
299299

300-
canOpenFile(path: string): boolean {
300+
canOpenFile(path: string, write: boolean): boolean {
301301
const r = this.resolve(path);
302-
return !!r && r[0].writable && !!r[0].openFile;
302+
return !!r && (!write || r[0].writable) && !!r[0].openFile;
303303
}
304304

305305
openFile(path: string, write: boolean, truncate: boolean, readable: boolean): FileHandle | undefined {
306306
const r = this.resolve(path);
307-
if (!r || !r[0].writable || !r[0].openFile) return undefined;
307+
if (!r || ((write || truncate) && !r[0].writable) || !r[0].openFile) return undefined;
308308
const h = r[0].openFile(r[1], write, truncate, readable);
309309
// writes through the handle are changes watchers see, as writes through VFS.write are
310310
return {

‎src/natives/io.ts‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ const closesHosts = new WeakSet<JVM>();
5454

5555
// A snapshot cannot hold a host handle, nor the opener a file may still need.
5656
export function streams(f: OpenFile): boolean {
57-
return !!f.contents.host || hostOpeners.has(f.contents);
57+
return f instanceof DirectoryFile || !!f.contents.host || hostOpeners.has(f.contents);
5858
}
5959

6060
// Host handles of files the program leaves open close when its VM exits.
@@ -120,17 +120,19 @@ export class OpenFile {
120120
return n;
121121
}
122122

123-
write(src: Uint8Array) {
123+
write(src: Uint8Array, atPosition = false) {
124+
if (this.append && !atPosition) this.pos = this.size;
124125
const host = this.contents.host;
125126
if (host) {
126127
hostCall(() => host.write(src, this.pos));
127128
this.pos += src.length;
128129
if (this.pos > this.size) this.size = this.pos;
129130
return;
130131
}
132+
const end = this.pos + src.length;
133+
if (end >= STREAM_MIN && this.stream()) return this.write(src, atPosition);
131134
// past the end, the gap reads as zeros (the buffer may hold bytes from before a truncation)
132135
if (this.pos > this.size) this.data.fill(0, this.size, Math.min(this.pos, this.data.length));
133-
const end = this.pos + src.length;
134136
if (end > this.data.length) {
135137
const next = new Uint8Array(Math.max(end, this.data.length * 2, 64));
136138
next.set(this.data.subarray(0, this.size));
@@ -140,7 +142,6 @@ export class OpenFile {
140142
this.pos = end;
141143
if (end > this.size) this.size = end;
142144
this.dirty = true;
143-
if (this.size >= STREAM_MIN) this.stream();
144145
}
145146

146147
setLength(n: number) {
@@ -197,6 +198,18 @@ export class OpenFile {
197198
close() { this.release(); }
198199
}
199200

201+
// A read-only directory descriptor can be opened, but cannot be read as bytes.
202+
class DirectoryFile extends OpenFile {
203+
constructor(path: string, size: number) {
204+
super(path, new Uint8Array(0), false);
205+
this.size = size;
206+
}
207+
208+
override read(): number {
209+
throw new PendingThrow("java/io/IOException", "Is a directory");
210+
}
211+
}
212+
200213
// Reads and writes a character device as a stream.
201214
class DeviceFile extends OpenFile {
202215
constructor(path: string) {
@@ -284,20 +297,25 @@ function notFound(path: string, why = "No such file or directory"): never {
284297
}
285298

286299
// Opens a path and returns its descriptor number.
287-
export function openFile(t: JThread, path: string, write: boolean, truncate: boolean, append: boolean, readable = true): number {
300+
export function openFile(t: JThread, path: string, write: boolean, truncate: boolean, append: boolean, readable = true, allowDirectory = false): number {
288301
const fs = t.vm.fs;
289302
const abs = resolvePath(t, path);
290303
syncPath(t, abs);
291304
const st = fs.stat(abs);
292-
if (st?.dir) notFound(path, "Is a directory");
305+
if (st?.dir) {
306+
if (!allowDirectory || write) notFound(path, "Is a directory");
307+
const tab = table(t);
308+
tab.files.set(tab.next, new DirectoryFile(abs, st.size));
309+
return tab.next++;
310+
}
293311
const shared = st ? [...table(t).files.values()].find((o) => o.path === abs && o.constructor === OpenFile)?.contents : undefined;
294312
if (st?.device || (st && !shared && !write && st.size >= LAZY_MIN && fs.canReadRange(abs))) {
295313
const tab = table(t);
296314
tab.files.set(tab.next, st.device ? new DeviceFile(abs) : new LazyFile(abs, st.size, fs));
297315
return tab.next++;
298316
}
299317
if (write && fs.denied(abs)) notFound(path, "Permission denied");
300-
if (st && !shared && !truncate && st.size >= STREAM_MIN && fs.canOpenFile(abs)) {
318+
if (st && !shared && !truncate && st.size >= STREAM_MIN && fs.canOpenFile(abs, write)) {
301319
const host = openHost(fs, abs, write, readable);
302320
if (host) {
303321
closeHostsOnExit(t.vm);
@@ -330,7 +348,7 @@ export function openFile(t: JThread, path: string, write: boolean, truncate: boo
330348
}
331349
const f = new OpenFile(abs, data, write, shared);
332350
// only a writer can grow a file, so read-only files never hold an opener
333-
if (write && !hostOpeners.has(f.contents) && fs.canOpenFile(abs)) {
351+
if (write && !hostOpeners.has(f.contents) && fs.canOpenFile(abs, true)) {
334352
const vm = t.vm;
335353
const c = f.contents;
336354
hostOpeners.set(c, (current) => {

‎src/natives/nio.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ export const natives: Natives = {
152152
if (st?.dir && write) unixError(EISDIR);
153153
if ((write || !st) && t.vm.fs.denied(abs)) unixError(EACCES);
154154
try {
155-
const fd = openFile(t, abs, write, (flags & O_TRUNC) !== 0, (flags & O_APPEND) !== 0, (flags & O_ACCMODE) !== 1);
155+
const fd = openFile(t, abs, write, (flags & O_TRUNC) !== 0, (flags & O_APPEND) !== 0, (flags & O_ACCMODE) !== 1, true);
156156
fileOf(t, fd).ino = fileInode(t, abs);
157157
return fd;
158158
} catch (e) {
@@ -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));
336+
m.f.write(t.vm.mem.u8.slice(addr, addr + n), true);
337337
m.f.pos = save;
338338
return flush(t, m.f);
339339
}

‎test/java/StreamingFile.java‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,15 @@
66

77
public class StreamingFile {
88
public static void main(String[] args) throws Exception {
9+
try (var directory = Files.newByteChannel(Path.of(""), java.nio.file.StandardOpenOption.READ,
10+
java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
11+
try {
12+
directory.read(ByteBuffer.allocate(1));
13+
System.out.println("directory readable");
14+
} catch (java.io.IOException e) {
15+
System.out.println(e.getClass().getName());
16+
}
17+
}
918
Path path = Files.createTempFile("streaming-file", ".bin");
1019
try (RandomAccessFile first = new RandomAccessFile(path.toFile(), "rw");
1120
RandomAccessFile second = new RandomAccessFile(path.toFile(), "rw")) {
@@ -28,6 +37,29 @@ public static void main(String[] args) throws Exception {
2837
} finally {
2938
Files.deleteIfExists(path);
3039
}
40+
Path sparse = Files.createTempFile("streaming-sparse", ".bin");
41+
try (RandomAccessFile file = new RandomAccessFile(sparse.toFile(), "rw");
42+
RandomAccessFile reader = new RandomAccessFile(sparse.toFile(), "r")) {
43+
file.write(17);
44+
file.seek(16L << 20);
45+
file.write(42);
46+
reader.seek(0);
47+
System.out.print(reader.read() + " ");
48+
reader.seek((16L << 20) - 1);
49+
System.out.println(reader.read() + " " + reader.read() + " " + reader.length());
50+
} finally {
51+
Files.deleteIfExists(sparse);
52+
}
53+
Path append = Files.createTempFile("streaming-append", ".bin");
54+
try (FileChannel channel = FileChannel.open(append, java.nio.file.StandardOpenOption.WRITE,
55+
java.nio.file.StandardOpenOption.APPEND)) {
56+
channel.write(ByteBuffer.wrap(new byte[] {1, 2}));
57+
channel.position(0);
58+
channel.write(ByteBuffer.wrap(new byte[] {3}));
59+
System.out.println(java.util.Arrays.toString(Files.readAllBytes(append)));
60+
} finally {
61+
Files.deleteIfExists(append);
62+
}
3163
Path big = Files.createTempFile("streaming-file", ".bin");
3264
try {
3365
try (RandomAccessFile out = new RandomAccessFile(big.toFile(), "rw")) {

‎test/jtreg/passing.txt‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,7 @@ java/io/FileDescriptor/RememberAppend.java
437437
java/io/FileDescriptor/Sharing.java
438438
java/io/FileDescriptor/Sync.java
439439
java/io/FileInputStream/Available.java
440+
java/io/FileInputStream/LargeFileAvailable.java
440441
java/io/FileInputStream/NegativeAvailable.java
441442
java/io/FileInputStream/OpenDir.java
442443
java/io/FileInputStream/OpsAfterClose.java
@@ -1923,6 +1924,8 @@ java/nio/channels/Channels/ReadOffset.java
19231924
java/nio/channels/Channels/ShortWrite.java
19241925
java/nio/channels/Channels/SocketChannelStreams.java
19251926
java/nio/channels/Channels/TinyBuffers.java
1927+
java/nio/channels/Channels/TransferTo_2GB_transferFrom.java
1928+
java/nio/channels/Channels/TransferTo_2GB_transferTo.java
19261929
java/nio/channels/Channels/Write.java
19271930
java/nio/channels/ConfigureBlocking.java
19281931
java/nio/channels/DatagramChannel/AdaptorAsyncCloseAfterReceive.java
@@ -1967,6 +1970,7 @@ java/nio/channels/FileChannel/GetClosedChannel.java
19671970
java/nio/channels/FileChannel/InterruptDeadlock.java
19681971
java/nio/channels/FileChannel/InterruptMapDeadlock.java
19691972
java/nio/channels/FileChannel/LongTransferTest.java
1973+
java/nio/channels/FileChannel/LoopingTruncate.java
19701974
java/nio/channels/FileChannel/MapAssertions.java
19711975
java/nio/channels/FileChannel/MapOverEnd.java
19721976
java/nio/channels/FileChannel/MapReadOnly.java
@@ -1984,8 +1988,11 @@ java/nio/channels/FileChannel/ReleaseOnCloseDeadlock.java
19841988
java/nio/channels/FileChannel/ScatteringRead.java
19851989
java/nio/channels/FileChannel/TempDirectBuffersReclamation.java
19861990
java/nio/channels/FileChannel/Transfer.java
1991+
java/nio/channels/FileChannel/Transfer2GPlus.java
1992+
java/nio/channels/FileChannel/Transfer4GBFile.java
19871993
java/nio/channels/FileChannel/TransferFromExtend.java
19881994
java/nio/channels/FileChannel/TransferOverlappedFileChannel.java
1995+
java/nio/channels/FileChannel/TransferTo6GBFile.java
19891996
java/nio/channels/FileChannel/TransferToAppending.java
19901997
java/nio/channels/FileChannel/TransferToChannel.java
19911998
java/nio/channels/FileChannel/TransferToNonWritable.java
@@ -2134,6 +2141,7 @@ java/nio/file/Files/Misc.java
21342141
java/nio/file/Files/Mismatch.java
21352142
java/nio/file/Files/NameLimits.java
21362143
java/nio/file/Files/ReadWriteString.java
2144+
java/nio/file/Files/SBC.java
21372145
java/nio/file/Files/StreamTest.java
21382146
java/nio/file/Files/probeContentType/ForceLoad.java
21392147
java/nio/file/Files/walkFileTree/MaxDepth.java
@@ -3342,10 +3350,12 @@ java/util/zip/ZipEntry/Clone.java
33423350
java/util/zip/ZipEntry/Constructor.java
33433351
java/util/zip/ZipEntry/MaxZipEntryFieldSizeTest.java
33443352
java/util/zip/ZipFile/Assortment.java
3353+
java/util/zip/ZipFile/CenSizeTooLarge.java
33453354
java/util/zip/ZipFile/ClearStaleZipFileInputStreams.java
33463355
java/util/zip/ZipFile/Comment.java
33473356
java/util/zip/ZipFile/Constructor.java
33483357
java/util/zip/ZipFile/CorruptedZipFiles.java
3358+
java/util/zip/ZipFile/EndOfCenValidation.java
33493359
java/util/zip/ZipFile/EnumerateAfterClose.java
33503360
java/util/zip/ZipFile/FinalizeInflater.java
33513361
java/util/zip/ZipFile/GetInputStreamNPETest.java
@@ -3468,3 +3478,4 @@ javax/xml/jaxp/transform/8062923/XslSubstringTest.java
34683478
javax/xml/jaxp/validation/8015092/XPathWhiteSpaceTest.java
34693479
javax/xml/jaxp/validation/8015243/AnyURITest.java
34703480
javax/xml/jaxp/validation/8049514/FeaturePropagationTest.java
3481+
jdk/nio/zipfs/EndOfCenValidation.java

‎test/jtreg/times.tsv‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22
108944 java/nio/Buffer/BulkPutBuffer.java
33
108484 java/net/httpclient/HandshakeFailureTest.java
44
108005 java/security/cert/CertPathValidator/crlDP/CheckAllCRLs.java
5+
105037 java/nio/channels/Channels/TransferTo_2GB_transferFrom.java
56
101333 java/net/httpclient/websocket/PendingPingBinaryClose.java
7+
101139 java/nio/channels/Channels/TransferTo_2GB_transferTo.java
68
100190 java/net/URL/EarlyOrDelayedParsing.java
79
97238 java/net/httpclient/websocket/PendingPongBinaryClose.java
810
93525 java/util/zip/DeInflate.java
@@ -410,6 +412,7 @@
410412
11071 java/text/Format/DateFormat/LenientSpaceParsingTest.java
411413
11063 java/beans/XMLEncoder/java_awt_CardLayout.java
412414
11038 java/security/Signature/NONEwithRSA.java
415+
11036 java/nio/channels/FileChannel/Transfer2GPlus.java
413416
11016 java/lang/reflect/Generics/ThreadSafety.java
414417
11011 java/util/concurrent/ConcurrentHashMap/ToArray.java
415418
11003 java/text/Format/DecimalFormat/MantissaDigits.java
@@ -913,6 +916,7 @@
913916
6451 java/util/Optional/BasicLong.java
914917
6449 java/net/httpclient/HttpResponseInputStreamTest.java
915918
6442 java/util/jar/JarFile/mrjar/TestVersionedStream.java
919+
6442 java/util/zip/ZipFile/CenSizeTooLarge.java
916920
6438 java/util/logging/LoggingDeadlock5.java
917921
6438 java/text/Format/DateFormat/Bug4845901.java
918922
6436 java/time/test/java/time/format/TestTextParser.java
@@ -2177,11 +2181,13 @@
21772181
3091 javax/xml/jaxp/Encodings/CheckEncodingPropertiesFile.java
21782182
3091 java/beans/Introspector/7122138/Test7122138.java
21792183
3090 java/lang/management/ClassLoadingMXBean/LoadCounts.java
2184+
3090 jdk/nio/zipfs/EndOfCenValidation.java
21802185
3089 java/util/logging/FileHandlerPatternExceptions.java
21812186
3089 java/net/URLClassLoader/closetest/GetResourceAsStream.java
21822187
3087 java/security/SecureRandom/NextBytesNull.java
21832188
3087 java/io/LineNumberReader/MarkSplitCRLF.java
21842189
3082 java/util/concurrent/ExecutorService/Invoke.java
2190+
3082 java/util/zip/ZipFile/EndOfCenValidation.java
21852191
3079 java/util/Vector/LastIndexOf.java
21862192
3079 java/security/spec/EllipticCurveMatch.java
21872193
3073 java/util/jar/JarFile/SignedJarFileGetInputStream.java
@@ -3011,6 +3017,7 @@
30113017
2078 java/io/Serializable/InvalidObjectException/TestIoeConstructors.java
30123018
2077 java/io/Serializable/enum/array/Test.java
30133019
2075 java/lang/Byte/Decode.java
3020+
2072 java/nio/channels/FileChannel/TransferTo6GBFile.java
30143021
2071 java/util/concurrent/forkjoin/AsyncShutdownNow.java
30153022
2070 java/nio/Buffer/Order.java
30163023
2070 java/math/BigInteger/CompareToTests.java
@@ -3078,6 +3085,7 @@
30783085
2010 java/lang/System/Logger/Level/LoggerLevelTest.java
30793086
2010 java/lang/Class/getMethod/NullInParamList.java
30803087
2007 java/nio/channels/AsynchronousChannelGroup/Unbounded.java
3088+
2006 java/nio/channels/FileChannel/Transfer4GBFile.java
30813089
2005 java/lang/Class/getDeclaredField/Exceptions.java
30823090
2004 java/util/concurrent/CopyOnWriteArrayList/EqualsRace.java
30833091
2000 java/util/logging/Reflect.java
@@ -3400,12 +3408,15 @@
34003408
1140 java/security/BasicPermission/ExitVMEquals.java
34013409
1133 java/security/BasicPermission/EqualsImplies.java
34023410
1128 java/lang/Throwable/LegacyChainedExceptionSerialization.java
3411+
1125 java/nio/file/Files/SBC.java
34033412
1122 java/nio/channels/FileChannel/ClosedChannelTransfer.java
34043413
1112 java/nio/channels/Selector/CloseThenRegister.java
34053414
1106 java/nio/channels/FileChannel/Force.java
34063415
1100 java/net/URLConnection/GetContentType.java
3416+
1077 java/io/FileInputStream/LargeFileAvailable.java
34073417
1074 java/nio/channels/Selector/SelectAfterRead.java
34083418
1070 java/nio/file/Files/FileAttributes.java
3419+
1038 java/nio/channels/FileChannel/LoopingTruncate.java
34093420
1036 java/net/URL/Constructor.java
34103421
1019 java/nio/channels/DatagramChannel/StressNativeSignal.java
34113422
1011 java/nio/channels/SocketChannel/CloseAfterConnect.java

‎test/nio.test.ts‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { test } from "node:test";
22
import assert from "node:assert/strict";
3-
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+
import { mkdtempSync, rmSync, truncateSync, writeFileSync } from "node:fs";
44
import { tmpdir } from "node:os";
55
import { join } from "node:path";
66
import { MemoryBackend, VFS } from "../src/fs.ts";
@@ -71,3 +71,54 @@ test("NodeBackend retains the errno from a failed chmod", () => {
7171
rmSync(dir, { recursive: true, force: true });
7272
}
7373
});
74+
75+
test("a sparse host file streams before allocating its gap", async () => {
76+
const { openFile, fileOf, closeFd } = await import("../src/natives/io.ts");
77+
const dir = mkdtempSync(join(tmpdir(), "java-web-sparse-"));
78+
const fs = new VFS();
79+
let largestWrite = 0;
80+
const backend = new NodeBackend(dir, true);
81+
const open = backend.openFile.bind(backend);
82+
backend.openFile = (...args) => {
83+
const handle = open(...args);
84+
const write = handle.write;
85+
handle.write = (src, pos) => { largestWrite = Math.max(largestWrite, src.length); write(src, pos); };
86+
return handle;
87+
};
88+
fs.mount("/", backend);
89+
const t = { vm: { fs, opts: {}, state: new Map(), exited: new Promise(() => {}) } } as unknown as JThread;
90+
try {
91+
const fd = openFile(t, "/file", true, false, false);
92+
const f = fileOf(t, fd);
93+
f.pos = 16 << 20;
94+
f.write(new Uint8Array([42]));
95+
assert.equal(f.data.length, 0);
96+
assert.ok(largestWrite < 1024, `host write was ${largestWrite} bytes`);
97+
assert.equal(f.size, (16 << 20) + 1);
98+
closeFd(t, fd);
99+
} finally {
100+
rmSync(dir, { recursive: true, force: true });
101+
}
102+
});
103+
104+
105+
test("a large file on a read-only host mount uses a handle", async () => {
106+
const { openFile, fileOf, closeFd } = await import("../src/natives/io.ts");
107+
const dir = mkdtempSync(join(tmpdir(), "java-web-readonly-"));
108+
const fs = new VFS();
109+
writeFileSync(join(dir, "file"), new Uint8Array([42]));
110+
truncateSync(join(dir, "file"), 6 << 20);
111+
fs.mount("/", new NodeBackend(dir));
112+
const t = { vm: { fs, opts: {}, state: new Map(), exited: new Promise(() => {}) } } as unknown as JThread;
113+
try {
114+
const fd = openFile(t, "/file", false, false, false);
115+
const f = fileOf(t, fd);
116+
assert.equal(f.data.length, 0);
117+
const byte = new Uint8Array(1);
118+
assert.equal(f.read(byte, 0, 1), 1);
119+
assert.equal(byte[0], 42);
120+
closeFd(t, fd);
121+
} finally {
122+
rmSync(dir, { recursive: true, force: true });
123+
}
124+
});

0 commit comments

Comments
 (0)