Skip to content

Commit fd14d91

Browse files
authored
Implement the java.util.prefs file natives (#43)
1 parent 9afafdf commit fd14d91

3 files changed

Lines changed: 113 additions & 0 deletions

File tree

‎src/natives/io.ts‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,10 +356,74 @@ function pathOf(t: JThread, file: JObject): string {
356356
return t.vm.jsString(t.vm.getField(file, "java/io/File", "path"));
357357
}
358358

359+
// java.util.prefs lock files: fcntl locks, which only this VM's threads can
360+
// contend for here. path -> readers, or -1 while one writer holds it.
361+
interface PrefsLock { path: string; shared: boolean }
362+
function prefsLocks(t: JThread) {
363+
let s = t.vm.state.get("prefsLocks") as { held: Map<string, number>; fds: Map<number, PrefsLock> } | undefined;
364+
if (!s) t.vm.state.set("prefsLocks", (s = { held: new Map(), fds: new Map() }));
365+
return s;
366+
}
367+
// Linux errno numbers of the codes Node reports by name
368+
const ERRNO_NUMBER: Record<string, number> = {
369+
EPERM: 1, ENOENT: 2, EIO: 5, EBADF: 9, EAGAIN: 11, ENOMEM: 12, EACCES: 13, ENOTDIR: 20, EINVAL: 22, ENFILE: 23,
370+
EMFILE: 24, ENOSPC: 28, EROFS: 30, ENAMETOOLONG: 36, ELOOP: 40, ENOTSUP: 95, EOPNOTSUPP: 95, EDQUOT: 122,
371+
};
372+
373+
function intPair(t: JThread, a: number, b: number): JArray {
374+
const arr = t.vm.newArray(t.vm.primClass("I"), 2);
375+
(arr.a as Int32Array).set([a, b]);
376+
return arr;
377+
}
378+
359379
const FOS = "java/io/FileOutputStream", FIS = "java/io/FileInputStream", RAF = "java/io/RandomAccessFile";
360380
const UFS = "java/io/UnixFileSystem";
361381

362382
export const natives: Natives = {
383+
// the errno of chmod(2), or 0
384+
"java/util/prefs/FileSystemPreferences.chmod(Ljava/lang/String;I)I": (t, [name, mode]) => {
385+
const abs = resolvePath(t, t.vm.jsString(name));
386+
if (!t.vm.fs.stat(abs)) return ERRNO_NUMBER.ENOENT;
387+
const ok = t.vm.fs.chmod(abs, (m) => (m & ~0o7777) | (mode & 0o7777));
388+
return ok === false ? ERRNO_NUMBER[t.vm.fs.chmodError(abs) ?? "EIO"] ?? ERRNO_NUMBER.EIO : 0;
389+
},
390+
// [fd, errno]; fd 0 when the file could not be opened or locked
391+
"java/util/prefs/FileSystemPreferences.lockFile0(Ljava/lang/String;IZ)[I": (t, [name, mode, shared]) => {
392+
const abs = resolvePath(t, t.vm.jsString(name));
393+
let fd: number;
394+
try {
395+
fd = openFile(t, abs, !shared, false, false);
396+
} catch {
397+
return intPair(t, 0, t.vm.fs.stat(abs) ? ERRNO_NUMBER.EACCES : ERRNO_NUMBER.ENOENT);
398+
}
399+
// the requested mode, as HotSpot's fchmod gives it; a failure is ignored there too
400+
if (!shared) t.vm.fs.chmod(abs, (m) => (m & ~0o7777) | (mode & 0o7777));
401+
const { held, fds } = prefsLocks(t);
402+
const now = held.get(abs) ?? 0;
403+
if (shared ? now < 0 : now !== 0) {
404+
closeFd(t, fd);
405+
return intPair(t, 0, ERRNO_NUMBER.EAGAIN);
406+
}
407+
held.set(abs, shared ? now + 1 : -1);
408+
fds.set(fd, { path: abs, shared: !!shared });
409+
return intPair(t, fd, 0);
410+
},
411+
"java/util/prefs/FileSystemPreferences.unlockFile0(I)I": (t, [fd]) => {
412+
const { held, fds } = prefsLocks(t);
413+
const lock = fds.get(fd);
414+
if (lock) {
415+
fds.delete(fd);
416+
const now = held.get(lock.path) ?? 0;
417+
if (lock.shared && now > 1) held.set(lock.path, now - 1);
418+
else held.delete(lock.path);
419+
}
420+
try {
421+
closeFd(t, fd);
422+
} catch {
423+
return ERRNO_NUMBER.EIO;
424+
}
425+
return 0;
426+
},
363427
// serialization: the default serialVersionUID depends on whether the class
364428
// itself declares a static initializer
365429
"java/io/ObjectStreamClass.initNative()V": () => undefined,

‎test/java/Prefs.java‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.nio.file.*;
2+
import java.util.Comparator;
3+
import java.util.logging.Level;
4+
import java.util.logging.Logger;
5+
import java.util.prefs.Preferences;
6+
7+
// User preferences are stored in files under java.util.prefs.userRoot, which
8+
// FileSystemPreferences locks and chmods as on HotSpot.
9+
public class Prefs {
10+
// Its log lines carry the time; HotSpot logs the same ones. Held here, since
11+
// the log manager keeps loggers weakly and a collected one forgets its level.
12+
static final Logger PREFS_LOG = Logger.getLogger("java.util.prefs");
13+
14+
public static void main(String[] args) throws Exception {
15+
PREFS_LOG.setLevel(Level.OFF);
16+
// a fresh root, not the user's own preferences
17+
Path root = Files.createTempDirectory("prefs");
18+
System.setProperty("java.util.prefs.userRoot", root.toString());
19+
Preferences node = Preferences.userRoot().node("java-web-test");
20+
try {
21+
node.put("greeting", "hello");
22+
node.putInt("count", 3);
23+
node.flush();
24+
node.sync();
25+
System.out.println(node.get("greeting", "?") + " " + node.getInt("count", 0) + " " + String.join(",", node.keys()));
26+
// what reached the backing file, read apart from the cached node
27+
try (var files = Files.walk(root)) {
28+
for (Path f : files.filter(f -> f.endsWith(Path.of("java-web-test", "prefs.xml"))).toList()) {
29+
System.out.println(root.relativize(f));
30+
for (String line : Files.readAllLines(f)) if (line.contains("<entry")) System.out.println(line.strip());
31+
}
32+
}
33+
} finally {
34+
node.removeNode();
35+
Preferences.userRoot().flush();
36+
try (var files = Files.walk(root)) {
37+
files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
38+
}
39+
}
40+
}
41+
}

‎test/jtreg/passing.txt‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3246,6 +3246,14 @@ java/util/logging/TestLoggingWithMainAppContext.java
32463246
java/util/logging/TestMainAppContext.java
32473247
java/util/logging/TestUILoggerContext.java
32483248
java/util/logging/XMLFormatterDate.java
3249+
java/util/prefs/AddNodeChangeListener.java
3250+
java/util/prefs/CodePointZeroPrefsTest.java
3251+
java/util/prefs/CommentsInXml.java
3252+
java/util/prefs/ConflictInFlush.java
3253+
java/util/prefs/ExportNode.java
3254+
java/util/prefs/ExportSubtree.java
3255+
java/util/prefs/RemoveNullKeyCheck.java
3256+
java/util/prefs/RemoveUnregedListener.java
32493257
java/util/prefs/SerializeExceptions.java
32503258
java/util/regex/ImmutableMatchResultTest.java
32513259
java/util/regex/NamedGroupsTests.java

0 commit comments

Comments
 (0)