Skip to content

Commit 4b9bf35

Browse files
committed
perf: add app.pack for what typical programs read beyond boot, and record javac.pack from a realistic compile
1 parent c34bf53 commit 4b9bf35

15 files changed

Lines changed: 306 additions & 33 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ Node, which is how the tests run.
3333
- The release form is an npm package of the built files only
3434
(`java-web.js`, `java-web-worker.js`, `node.js` (the Node entry), `cli.js` (the
3535
`java-web` command), `boot.pack`, the `jdk/*.jar` image files,
36-
`jdk/javac.pack`, and OpenJDK's notices in `jdk/legal/`), versioned, with
36+
`jdk/app.pack`, `jdk/javac.pack`, and OpenJDK's notices in `jdk/legal/`), versioned, with
3737
nothing built at install. A GitHub Actions workflow triggered by a release
3838
publishes it to npm; never publish by hand.
3939

‎docs/browser.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@ next to itself, or where `cheerpjInit({ runtime: "/path/to/dist/" })` says.
99
image, so a page reads only the classes it needs. `jdk/image.jar` holds
1010
`java.base` and the files around the classes, each other module is in
1111
`jdk/<module>.jar`, and `jdk/ct.sym.jar` holds what `javac --release` reads.
12-
`boot.pack` holds what a typical start reads, and `jdk/javac.pack` what javac
13-
adds. A host that compresses ranged responses still works, at the cost of one
12+
`boot.pack` holds what a bare start reads. `jdk/app.pack` holds what a
13+
typical program reads beyond that, and `jdk/javac.pack` what javac adds; a
14+
page fetches each the first time it reads a class in it. A host that compresses ranged responses still works, at the cost of one
1415
full download of each image file a page reads.
1516
- A host can leave out the `jdk/<module>.jar` of a module its pages never
1617
load, and `jdk/ct.sym.jar` when nothing compiles with `--release`. A class of

‎docs/development.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,9 @@ at `build/hotspot`. The build links the selected modules into `build/jdk/lib/mod
1010
`lib/packages.txt` indexes packages for the boot class loader. `pnpm build`
1111
puts it, with the files around it, in `dist/jdk/image.jar` and, for each module
1212
but `java.base`, `dist/jdk/<module>.jar`, all read by byte range.
13-
It packs the byte ranges a typical start reads into `boot.pack`, and those javac
14-
adds into `jdk/javac.pack`. Without `localeData`, the VM leaves `jdk.localedata`
13+
It packs the byte ranges a bare start reads into `boot.pack`, those the programs
14+
in `scripts/packs` read beyond that into `jdk/app.pack` (with every `java.base`
15+
part javac reads), and the rest of what their compile reads into `jdk/javac.pack`. Without `localeData`, the VM leaves `jdk.localedata`
1516
out with `jdk.module.limitmods`, as `--limit-modules` does.
1617

1718
```sh

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
"dist/node.d.ts",
3737
"dist/boot.pack",
3838
"dist/jdk/*.jar",
39+
"dist/jdk/app.pack",
3940
"dist/jdk/javac.pack",
4041
"dist/jdk/legal/"
4142
],

‎scripts/build-web.ts‎

Lines changed: 54 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -103,24 +103,44 @@ class Recorder implements Backend {
103103
return d;
104104
}
105105
}
106-
const recorder = new Recorder(new NodeBackend(jdk));
107-
for (const main of ["Hello", "Primes", "Shapes"]) {
106+
// Runs main over the JDK through rec, with app mounted at /app.
107+
async function record(rec: Recorder, app: string, classpath: string[], main: string, args: string[] = []) {
108108
const vfs = new VFS();
109109
vfs.mount("/", new MemoryBackend());
110-
vfs.mount("/jdk", recorder);
110+
vfs.mount("/jdk", rec);
111111
vfs.mount("/tmp", new MemoryBackend());
112-
vfs.mount("/app", new NodeBackend(dist));
112+
vfs.mount("/app", new NodeBackend(app));
113113
const vm = new JVM({
114-
fs: vfs, javaHome: "/jdk", classpath: ["/app/samples"], cwd: "/tmp",
114+
fs: vfs, javaHome: "/jdk", classpath, cwd: "/tmp",
115115
props: { "java.io.tmpdir": "/tmp", "user.home": "/tmp" },
116116
stdout: () => {}, stderr: (b) => process.stderr.write(b),
117117
});
118-
const code = await vm.run(LM_CLASS, main, main === "Primes" ? ["100"] : []);
118+
const code = await vm.run(LM_CLASS, main, args);
119119
if (code !== 0) throw new Error(`${main} exited with ${code}`);
120120
}
121+
const recorder = new Recorder(new NodeBackend(jdk));
122+
for (const main of ["Hello", "Primes", "Shapes"]) await record(recorder, dist, ["/app/samples"], main, main === "Primes" ? ["100"] : []);
123+
124+
// The programs scripts/packs holds, built into build/packs: a typical program
125+
// run from jars, and a compile with a jar classpath and an annotation processor.
126+
const packs = join(root, "scripts", "packs"), fixtures = join(root, "build", "packs");
127+
rmSync(fixtures, { recursive: true, force: true });
128+
const javacTo = (out: string, ...args: string[]) => execFileSync(hotspot("javac"), ["-d", join(fixtures, out), ...args]);
129+
javacTo("lib", join(packs, "lib", "Lib.java"));
130+
javacTo("proc", join(packs, "proc", "Generate.java"), join(packs, "proc", "GenerateProcessor.java"));
131+
mkdirSync(join(fixtures, "proc", "META-INF", "services"), { recursive: true });
132+
writeFileSync(join(fixtures, "proc", "META-INF", "services", "javax.annotation.processing.Processor"), "proc.GenerateProcessor\n");
133+
javacTo("app", "-cp", join(fixtures, "lib"), join(packs, "App.java"));
134+
cpSync(join(packs, "app.properties"), join(fixtures, "app", "app.properties"));
135+
javacTo("driver", join(packs, "Compile.java"));
136+
for (const d of ["lib", "proc", "app"]) execFileSync(hotspot("jar"), ["cf", join(fixtures, `${d}.jar`), "-C", join(fixtures, d), "."]);
137+
cpSync(join(packs, "src"), join(fixtures, "src"), { recursive: true });
138+
const appRecorder = new Recorder(new NodeBackend(jdk));
139+
await record(appRecorder, fixtures, ["/app/app.jar", "/app/lib.jar"], "App");
121140

122-
// Record what a javax.tools compile reads on top of that.
141+
// Record what javac reads: the compile above, and the one the browser self test runs.
123142
const javacRecorder = new Recorder(new NodeBackend(jdk));
143+
await record(javacRecorder, fixtures, ["/app/driver"], "Compile", ["/app/lib.jar:/app/proc.jar", "/app/proc.jar", "/tmp", "/app/src/Model.java", "/app/src/Uses.java"]);
124144
{
125145
const vfs = new VFS();
126146
vfs.mount("/", new MemoryBackend());
@@ -139,7 +159,6 @@ const javacRecorder = new Recorder(new NodeBackend(jdk));
139159
if (r !== "true ") throw new Error(`javac in the VM failed: ${r}`);
140160
vm.halt(0);
141161
}
142-
const javacFiles = [...javacRecorder.seen].filter((p) => !recorder.seen.has(p)).sort();
143162

144163
// Sorted [start, end) spans covering the given ones. Spans less than GAP apart
145164
// join, since a pack entry costs more than a few bytes of filler.
@@ -167,11 +186,26 @@ function subtract(spans: [number, number][], covered: [number, number][]): [numb
167186
}
168187
return out;
169188
}
189+
// boot.pack holds what a bare start reads. app.pack, fetched the first time a
190+
// program reads one of its parts, holds what the typical program reads beyond
191+
// that and every java.base part javac reads. javac.pack holds the rest of what
192+
// javac reads: the compiler's own modules.
193+
const linked = new Set(/^MODULES="(.*)"$/m.exec(readFileSync(join(jdk, "release"), "utf8"))![1].split(" "));
194+
const compiler = merge(moduleRuns(readFileSync(join(jdk, "lib", "modules")))
195+
.filter(([m]) => m !== "java.base" && linked.has(m)).map(([, s, e]): [number, number] => [s, e]));
170196
const bootRanges = new Map([...recorder.ranges].map(([p, r]) => [p, merge(r)]));
171-
const javacRanges = new Map([...javacRecorder.ranges].map(([p, r]) => [p, subtract(merge(r), bootRanges.get(p) ?? [])]));
172-
const rangeEntries = (ranges: Map<string, [number, number][]>, src: Recorder) =>
173-
[...ranges].flatMap(([p, spans]) => spans.map(([s, e]): [string, Uint8Array] => [`@${s}:${p}`, src.readRange(p, s, e - s)!]));
174-
const inJavacPack = new Set(javacFiles);
197+
const beyondBoot = (rec: Recorder) => new Map([...rec.ranges].map(([p, r]) => [p, subtract(merge(r), bootRanges.get(p) ?? [])]));
198+
const appRanges = beyondBoot(appRecorder), javacRanges = new Map<string, [number, number][]>();
199+
for (const [p, r] of beyondBoot(javacRecorder)) {
200+
const own = p === "/lib/modules" ? subtract(r, subtract(r, compiler)) : [];
201+
appRanges.set(p, merge([...(appRanges.get(p) ?? []), ...subtract(r, own)]));
202+
javacRanges.set(p, own);
203+
}
204+
const jdkFiles = new NodeBackend(jdk);
205+
const rangeEntries = (ranges: Map<string, [number, number][]>) =>
206+
[...ranges].flatMap(([p, spans]) => spans.map(([s, e]): [string, Uint8Array] => [`@${s}:${p}`, jdkFiles.readRange(p, s, e - s)!]));
207+
const appFiles = [...new Set([...appRecorder.seen, ...javacRecorder.seen])].filter((p) => !recorder.seen.has(p)).sort();
208+
const inAppPack = new Set(appFiles);
175209

176210
// A jimage's resources as runs of one module's, [module, start, end) in image
177211
// order. Empty resources and module-info.class are left out: jlink puts the
@@ -213,7 +247,6 @@ function moduleRuns(image: Uint8Array): [string, number, number][] {
213247
// may never read go in their own files, which a host can leave out: each
214248
// module of lib/modules but java.base in jdk/<module>.jar, and lib/ct.sym
215249
// (javac --release) in jdk/ct.sym.jar.
216-
const linked = new Set(/^MODULES="(.*)"$/m.exec(readFileSync(join(jdk, "release"), "utf8"))![1].split(" "));
217250
const imageSizes = new Map<string, number>();
218251
// appends data to jdk/<name>.jar, returning where it starts there
219252
const put = (name: string, data: Uint8Array) => {
@@ -250,7 +283,7 @@ const walk = (dir: string) => {
250283
});
251284
} else {
252285
const image = rel === "/lib/ct.sym" ? "ct.sym" : "image";
253-
lines.push(`f ${rel} ${st.size} ${image}:${put(image, readFileSync(p))}${inJavacPack.has(rel) ? " javac" : ""}`);
286+
lines.push(`f ${rel} ${st.size} ${image}:${put(image, readFileSync(p))}${inAppPack.has(rel) ? " app" : ""}`);
254287
}
255288
}
256289
};
@@ -297,15 +330,17 @@ const lazySpans = (name: string, ranges: Map<string, [number, number][]>): [stri
297330
return [`@lazy:${name}:${p}`, data];
298331
});
299332
const boot = writePack(join(dist, "boot.pack"), [
300-
...rangeEntries(bootRanges, recorder),
333+
...rangeEntries(bootRanges),
334+
...lazySpans("app", appRanges),
301335
...lazySpans("javac", javacRanges),
302336
["/index.prefix", prefixCode(lines)],
303337
...[...recorder.seen].sort().map((p): [string, Uint8Array] => [p, recorder.read(p)!]),
304338
]);
305-
const javacPack = writePack(join(dist, "jdk", "javac.pack"), [
306-
...javacFiles.map((p): [string, Uint8Array] => [p, javacRecorder.read(p)!]),
307-
...rangeEntries(javacRanges, javacRecorder),
339+
const appPack = writePack(join(dist, "jdk", "app.pack"), [
340+
...appFiles.map((p): [string, Uint8Array] => [p, jdkFiles.read(p)!]),
341+
...rangeEntries(appRanges),
308342
]);
343+
const javacPack = writePack(join(dist, "jdk", "javac.pack"), rangeEntries(javacRanges));
309344
const mb = (n: number) => `${(n / 2 ** 20).toFixed(0)} MB`;
310345
const others = [...imageSizes].filter(([n]) => n !== "image").reduce((n, [, size]) => n + size, 0);
311-
console.log(`dist/ ready: boot.pack ${boot}, jdk/javac.pack ${javacPack}, jdk/image.jar ${mb(imageSizes.get("image")!)}, ${imageSizes.size - 1} more images ${mb(others)}`);
346+
console.log(`dist/ ready: boot.pack ${boot}, jdk/app.pack ${appPack}, jdk/javac.pack ${javacPack}, jdk/image.jar ${mb(imageSizes.get("image")!)}, ${imageSizes.size - 1} more images ${mb(others)}`);

‎scripts/packs/App.java‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
import java.math.BigDecimal;
2+
import java.math.BigInteger;
3+
import java.math.RoundingMode;
4+
import java.nio.file.Files;
5+
import java.nio.file.Path;
6+
import java.time.Duration;
7+
import java.time.Instant;
8+
import java.time.LocalDateTime;
9+
import java.time.ZoneOffset;
10+
import java.time.ZonedDateTime;
11+
import java.time.format.DateTimeFormatter;
12+
import java.util.ArrayList;
13+
import java.util.Collections;
14+
import java.util.List;
15+
import java.util.Map;
16+
import java.util.Optional;
17+
import java.util.Properties;
18+
import java.util.Random;
19+
import java.util.TreeMap;
20+
import java.util.concurrent.CompletableFuture;
21+
import java.util.concurrent.ExecutorService;
22+
import java.util.concurrent.Executors;
23+
import java.util.concurrent.Future;
24+
import java.util.concurrent.atomic.AtomicInteger;
25+
import java.util.regex.Pattern;
26+
import java.util.stream.Collectors;
27+
import java.util.stream.IntStream;
28+
import lib.Lib;
29+
30+
// A typical program, run from a jar: what it reads beyond a bare start goes in app.pack.
31+
public class App {
32+
record Point(int x, int y) {}
33+
34+
enum Kind { A, B, C }
35+
36+
public static void main(String[] args) throws Exception {
37+
List<Point> points = IntStream.range(0, 50).mapToObj(i -> new Point(i, i * i)).collect(Collectors.toList());
38+
Map<Boolean, Long> parts = points.stream().collect(Collectors.partitioningBy(p -> p.x() % 2 == 0, Collectors.counting()));
39+
TreeMap<String, Integer> kinds = new TreeMap<>();
40+
for (Kind k : Kind.values()) kinds.put(k.name(), k.ordinal());
41+
String shape = switch (points.get(3)) {
42+
case Point(int x, int y) when x > 1 -> "big " + y;
43+
default -> "small";
44+
};
45+
BigDecimal price = new BigDecimal("1.10").multiply(BigDecimal.valueOf(3)).setScale(1, RoundingMode.HALF_UP);
46+
BigInteger factorial = BigInteger.ONE;
47+
for (int i = 1; i < 30; i++) factorial = factorial.multiply(BigInteger.valueOf(i));
48+
Instant start = Instant.now();
49+
String when = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(LocalDateTime.ofInstant(start, ZoneOffset.UTC))
50+
+ " " + Duration.ofMillis(1500) + " " + ZonedDateTime.now().getZone();
51+
52+
ExecutorService pool = Executors.newFixedThreadPool(2);
53+
Future<Integer> sum = pool.submit(() -> points.stream().mapToInt(Point::y).sum());
54+
CompletableFuture<String> upper = CompletableFuture.supplyAsync(() -> "async", pool).thenApply(String::toUpperCase);
55+
AtomicInteger ticks = new AtomicInteger();
56+
Thread worker = new Thread(() -> {
57+
synchronized (ticks) {
58+
ticks.incrementAndGet();
59+
}
60+
});
61+
worker.start();
62+
worker.join();
63+
int total = sum.get();
64+
String async = upper.get();
65+
pool.shutdown();
66+
67+
Path file = Files.createTempFile("app", ".txt");
68+
Files.writeString(file, shape + "\n" + price + "\n");
69+
List<String> lines = Files.readAllLines(file);
70+
Files.delete(file);
71+
72+
Properties props = new Properties();
73+
try (var in = App.class.getResourceAsStream("/app.properties")) {
74+
props.load(in);
75+
}
76+
System.getLogger("app").log(System.Logger.Level.DEBUG, "not shown");
77+
List<Integer> shuffled = new ArrayList<>(List.of(1, 2, 3, 4, 5));
78+
Collections.shuffle(shuffled, new Random(1));
79+
boolean digits = Pattern.compile("\\d+").matcher("abc123").find();
80+
String parsed;
81+
try {
82+
parsed = String.valueOf(Integer.parseInt("x"));
83+
} catch (NumberFormatException e) {
84+
parsed = e.getClass().getSimpleName() + " at " + e.getStackTrace()[0].getMethodName();
85+
}
86+
System.out.println(String.format("%s %s %s %s %d %s %d %s %s %s %s %b %s %s %s", parts, kinds, shape, price, factorial.bitLength(),
87+
when.length() > 0, total, async, ticks, lines, shuffled, digits, parsed, props.getProperty("name"),
88+
Optional.of(Lib.greet("app")).map(String::strip).orElse("")));
89+
}
90+
}

‎scripts/packs/Compile.java‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import java.nio.file.Path;
2+
import java.util.ArrayList;
3+
import java.util.Arrays;
4+
import java.util.List;
5+
import java.util.Locale;
6+
import javax.tools.JavaCompiler;
7+
import javax.tools.StandardJavaFileManager;
8+
import javax.tools.StandardLocation;
9+
import javax.tools.ToolProvider;
10+
11+
// Compile CLASSPATH PROCESSORPATH OUTDIR SOURCE...: a javax.tools compile with
12+
// a jar classpath and an annotation processor, for javac.pack.
13+
public class Compile {
14+
public static void main(String[] args) throws Exception {
15+
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
16+
StandardJavaFileManager fm = javac.getStandardFileManager(null, Locale.ROOT, null);
17+
fm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, List.of(Path.of(args[2])));
18+
fm.setLocationFromPaths(StandardLocation.SOURCE_OUTPUT, List.of(Path.of(args[2])));
19+
List<String> options = new ArrayList<>(List.of("-classpath", args[0], "-processorpath", args[1], "-g", "-XDstringConcat=inline"));
20+
List<Path> sources = Arrays.stream(args, 3, args.length).map(Path::of).toList();
21+
List<String> diags = new ArrayList<>();
22+
boolean ok = javac.getTask(null, fm, d -> diags.add(d.toString()), options, null, fm.getJavaFileObjectsFromPaths(sources)).call();
23+
if (!ok) throw new IllegalStateException(String.join("\n", diags));
24+
}
25+
}

‎scripts/packs/app.properties‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
name=app

‎scripts/packs/lib/Lib.java‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package lib;
2+
3+
// A library the packed program and compile take from a jar.
4+
public final class Lib {
5+
public interface Named {
6+
String name();
7+
8+
default String label() {
9+
return "<" + name() + ">";
10+
}
11+
}
12+
13+
public static String greet(String who) {
14+
return "hello " + who + " ";
15+
}
16+
}

‎scripts/packs/proc/Generate.java‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package proc;
2+
3+
import java.lang.annotation.ElementType;
4+
import java.lang.annotation.Retention;
5+
import java.lang.annotation.RetentionPolicy;
6+
import java.lang.annotation.Target;
7+
8+
@Retention(RetentionPolicy.SOURCE)
9+
@Target(ElementType.TYPE)
10+
public @interface Generate {}

0 commit comments

Comments
 (0)