Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
@@ -0,0 +1,6 @@
# tools/survey
- Runs on exactly JDK 25: `JAVA_HOME=/usr/lib/jvm/java-25-openjdk ./incari survey`.
- `docs/port-backlog.md` is generated; change `rules.txt` and rerun (`--reclassify` is seconds),
never edit the backlog by hand. It must never contain game code.
- Test: `./gradlew :tools:survey:test`.
@@ -0,0 +1,47 @@
# tools/survey: the TeaVM compile survey
Compiles the whole client with TeaVM and records everything between it and a browser build:
missing classes and members, JDK classes TeaVM lacks, natives and reflection. Each finding is
triaged as **stub**, **shim**, **rewrite** or **delete** into
[`docs/port-backlog.md`](../../docs/port-backlog.md). `tools/webbuild` uses the same rules.
```sh
./incari fetch # once
JAVA_HOME=<JDK 25> ./incari survey # about a minute
JAVA_HOME=<JDK 25> ./incari survey --reclassify # re-triage the last run, seconds
```
`INCARI_SURVEY_OPTS=-Xmx20g` raises the heap (default 12 GB).
## How it works
1. **Class path:** the client jar plus libraries `rules.txt` marks `keep`. Libraries marked
`replace` or `delete` (LWJGL, JNA, OSHI…) stay off, so each call into them is a finding.
2. **Roots:** every method of every client class is an entry point (except `no-root` packages such
as data generators), since following `main()` misses code behind callbacks.
3. **Host JDK hidden,** so JDK classes TeaVM lacks are reported, not silently compiled in.
4. **Stub rounds:** missing symbols get default-returning stubs, and it recompiles until nothing new
turns up. Stubs are for analysis only; everything stubbed is still a finding.
5. **Scan and triage:** a bytecode scan adds reflection and missing-class references; each finding
takes the first matching rule in `rules.txt`.
## Files
| File | What |
| --- | --- |
| `rules.txt` | The policy: which libraries compile in, which packages aren't roots, a triage rule per work item |
| `Main`, `Roots`, `TeaVmSurvey`, `Stubs`, `BytecodeScanner`, `Backlog` | Orchestration, roots, compile rounds, scan, markdown |
| `docs/port-backlog.md` (tracked) | Counts and a table per work item: API and package names only, never game code |
| `work/survey/<version>/` (ignored) | Every call site, and the saved result `--reclassify` reuses |
## Invariants
- **Exactly JDK 25.** TeaVM can't read Java 26 classes, and "missing" depends on the JDK.
- **Deterministic:** sorted, no timestamps.
- **Every library has a rule,** and no committed backlog has unclassified findings.
## How to test
```sh
./gradlew :tools:survey:test # rules, stubs and roots; the full survey runs by hand
```
@@ -0,0 +1,32 @@
plugins {
application
}
dependencies {
// Reuses the build tool's workspace layout and version pin, so the survey always reads
// the same jars `incari fetch` downloaded.
implementation(project(":tools:build"))
implementation(libs.teavm.tooling)
implementation(libs.teavm.core)
implementation(libs.teavm.classlib)
implementation(libs.asm)
implementation(libs.gson)
testImplementation(platform(libs.junit.bom))
testImplementation(libs.junit.jupiter)
testImplementation(libs.assertj)
testRuntimeOnly(libs.junit.launcher)
}
application {
applicationName = "incari-survey"
mainClass = "incari.tools.survey.Main"
// TeaVM's dependency analysis over the whole client plus its libraries is memory-hungry.
// Override with INCARI_SURVEY_OPTS="-Xmx..." on smaller machines.
applicationDefaultJvmArgs = listOf("-Xmx12g", "-Dincari.teavm.version=${libs.versions.teavm.get()}")
}
tasks.test {
// SurveyRulesTest parses the real rules.txt from the module directory.
workingDir = projectDir
}
+187
View File
@@ -0,0 +1,187 @@
# TeaVM survey policy. Read by `./incari survey`; see tools/survey/README.md.
#
# Two kinds of lines:
# library <maven coordinate prefix> <keep|replace|delete> <reason>
# <stub|shim|rewrite|delete> <selector>=<glob>... <reason: the work item's name in the backlog>
#
# Triage rules are tried top to bottom; the first match wins, so put narrow rules first.
# Selectors: symbol (API used, owner#member), caller (class needing work), origin
# (minecraft, or a library's artifact id), kind (missing-class, missing-method, missing-field,
# unsupported-method, missing-supertype, native, host-jdk, reflection).
# Globs: * stays inside one name segment, ** matches anything.
# ---------------------------------------------------------------------------------------------
# Libraries. Only `keep` libraries are compiled with the game. The rest are left off the
# classpath on purpose, so every place the game calls them shows up as its own finding.
# Every non-native library in Mojang's version JSON must match one line.
# ---------------------------------------------------------------------------------------------
library org.lwjgl: replace Platform layer: WebGL2, canvas input, Web Audio, fonts
library net.java.dev.jna: delete Native interop; only OSHI and OS integration use it
library com.github.oshi: delete Hardware and OS telemetry
library com.mojang:jtracy: delete Tracy profiler (native)
library com.mojang:text2speech: replace Narrator; the browser has the Web Speech API
library ca.weblite:java-objc-bridge: delete macOS-only native bridge
library com.microsoft.azure:msal4j: delete Microsoft login; the browser build uses offline or Eagler identity
library com.azure:azure-json: delete Only used by msal4j
library com.ibm.icu:icu4j: replace Bidi text; the browser has Intl, or a minimal shim
library org.apache.logging.log4j:log4j-core: replace Console logging shim
library org.apache.logging.log4j:log4j-slf4j2-impl: replace Console logging shim
library io.netty:netty-buffer: keep FriendlyByteBuf extends ByteBuf; pure Java in heap mode
library io.netty:netty-common: keep Needed by netty-buffer
library io.netty:netty-transport: keep The game's Connection is a Netty pipeline; it runs over the WebSocket transport (ADR 0008)
library io.netty:netty-codec-base: keep The game's packet codecs extend its encoders and decoders
library io.netty:netty-handler: keep The read timeout and flow control in the game's pipeline
library io.netty:netty-resolver: keep Bootstrap's address resolution; WebSocket addresses need none
library io.netty: replace Native transports, compression and HTTP codecs: the browser has none of them
library at.yawk.lz4: keep Has a pure-Java implementation
library com.google. keep Guava, Gson, failureaccess: pure Java
library com.mojang:authlib: keep GameProfile and properties are used everywhere; its HTTP parts get cut
library com.mojang: keep Brigadier, DataFixerUpper codecs, logging, blocklist, patchy
library commons-codec: keep Pure Java
library commons-io: keep Pure Java
library org.apache.commons: keep commons-lang3, commons-compress: pure Java
library it.unimi.dsi:fastutil: keep Pure Java collections
library net.sf.jopt-simple: keep Command-line parsing for Main
library org.apache.logging.log4j:log4j-api: keep API only; backed by the console shim
library org.slf4j: keep API only; backed by the console shim
library org.jcraft:jorbis: keep Pure-Java Ogg Vorbis decoder, useful for Web Audio
library org.joml: keep Pure Java math
library org.jspecify: keep Annotations only
# ---------------------------------------------------------------------------------------------
# Analysis roots. Every class in the client jar is a root (see Roots.java) except these, which
# ship in the jar but never run in the client.
# ---------------------------------------------------------------------------------------------
no-root net.minecraft.data.** Data generators run at Mojang's build time
no-root net.minecraft.client.data.** Client-side data generators
no-root net.minecraft.gametest.** Automated game tests
no-root net.minecraft.server.Main Dedicated server entry point
no-root net.minecraft.server.Main$* Dedicated server entry point
no-root net.minecraft.server.Eula Dedicated server EULA file
no-root net.minecraft.server.ConsoleInput Dedicated server console
no-root net.minecraft.server.dedicated.** Dedicated server
no-root net.minecraft.server.gui.** Dedicated server Swing GUI
no-root net.minecraft.server.rcon.** Dedicated server remote console
no-root net.minecraft.server.jsonrpc.** Dedicated server management protocol
no-root net.minecraft.server.chase.** Debug tool that mirrors a player between servers
# ---------------------------------------------------------------------------------------------
# Triage. The reason is the work item's name in docs/port-backlog.md; rule lines that share a
# reason form one work item. Narrow rules first.
# ---------------------------------------------------------------------------------------------
# --- Delete: features the browser build strips --------------------------------------------
delete symbol=com.mojang.jtracy.** Tracy profiler hooks
delete caller=net.minecraft.util.profiling.jfr.** Java Flight Recorder profiling
delete symbol=jdk.jfr.** Java Flight Recorder profiling
delete symbol=io.netty.buffer.*Event Java Flight Recorder profiling
delete symbol=oshi.** OSHI hardware info (crash reports, telemetry)
delete symbol=com.sun.jna.** JNA Windows process inspection (crash reports)
delete symbol=ca.weblite.** macOS window integration
delete caller=com.mojang.renderpearl.backend.vulkan.** Vulkan backend (the browser gets WebGL2, later WebGPU)
delete symbol=org.lwjgl.vulkan.** Vulkan backend (the browser gets WebGL2, later WebGPU)
delete symbol=org.lwjgl.util.vma.** Vulkan backend (the browser gets WebGL2, later WebGPU)
delete symbol=org.lwjgl.sdl.SDLVulkan Vulkan backend (the browser gets WebGL2, later WebGPU)
delete caller=com.mojang.realmsclient.** Realms (Mojang's hosting service and its HTTP client)
delete caller=net.minecraft.server.dedicated.** Dedicated server code the client reaches (watchdog, properties)
delete caller=net.minecraft.server.chase.** Debug tool that mirrors a player between servers
delete caller=com.viaversion.viaversion.libs.snakeyaml.** Via's bundled YAML parser: Incari keeps Via's settings in memory (ADR 0017)
delete symbol=io.netty.channel.epoll.** Native socket transports (epoll, kqueue)
delete symbol=io.netty.channel.kqueue.** Native socket transports (epoll, kqueue)
delete symbol=java.net.DatagramSocket LAN world discovery and hosting (UDP multicast, server sockets)
delete symbol=java.net.DatagramPacket LAN world discovery and hosting (UDP multicast, server sockets)
delete symbol=java.net.MulticastSocket LAN world discovery and hosting (UDP multicast, server sockets)
delete symbol=java.net.ServerSocket LAN world discovery and hosting (UDP multicast, server sockets)
delete symbol=javax.naming.** DNS SRV lookup of server addresses (JNDI)
delete symbol=org.osgi.** Library support for optional runtimes (OSGi, Log4j 1, java.sql)
delete symbol=org.apache.log4j.** Library support for optional runtimes (OSGi, Log4j 1, java.sql)
delete symbol=java.sql.** Library support for optional runtimes (OSGi, Log4j 1, java.sql)
delete symbol=org.lwjgl.system.Configuration Native library loading and LWJGL setup
delete symbol=org.lwjgl.system.Platform** Native library loading and LWJGL setup
delete symbol=org.lwjgl.system.SharedLibrary Native library loading and LWJGL setup
delete symbol=org.lwjgl.system.Library Native library loading and LWJGL setup
delete symbol=org.lwjgl.Version Native library loading and LWJGL setup
delete symbol=org.lwjgl.util.shaderc.Shaderc#getLibrary Native library loading and LWJGL setup
delete symbol=org.lwjgl.util.spvc.Spvc#getLibrary Native library loading and LWJGL setup
delete symbol=java.lang.UnsatisfiedLinkError Native library loading and LWJGL setup
delete caller=io.netty.util.NetUtil symbol=java.lang.Process** Operating system queries in Netty (somaxconn through sysctl): a page runs no processes
delete symbol=javax.management.** JMX server monitoring (MBeans)
delete symbol=com.microsoft.aad.** Microsoft account services (login, server chat filter)
delete symbol=java.security.** Encryption and signing (Mojang auth, chat signing, key pairs); offline and Eagler modes don't use them
delete symbol=javax.security.** Encryption and signing (Mojang auth, chat signing, key pairs); offline and Eagler modes don't use them
delete symbol=javax.crypto.** Encryption and signing (Mojang auth, chat signing, key pairs); offline and Eagler modes don't use them
# --- Rewrite: the platform layer ------------------------------------------------------------
rewrite caller=com.mojang.renderpearl.backend.opengl.** OpenGL backend: replace with a WebGL2 GpuDevice backend
rewrite symbol=org.lwjgl.opengl.** OpenGL backend: replace with a WebGL2 GpuDevice backend
rewrite symbol=org.lwjgl.util.shaderc.** Shader toolchain: GLSL to SPIR-V (shaderc) and back (SPIRV-Cross) runs natively; move it to build time
rewrite symbol=org.lwjgl.util.spvc.** Shader toolchain: GLSL to SPIR-V (shaderc) and back (SPIRV-Cross) runs natively; move it to build time
rewrite symbol=org.lwjgl.BufferUtils Off-heap memory (MemoryUtil, MemoryStack, pointers): rewrite over ArrayBuffer
rewrite symbol=org.lwjgl.system.MemoryStack** Off-heap memory (MemoryUtil, MemoryStack, pointers): rewrite over ArrayBuffer
rewrite symbol=org.lwjgl.system.MemoryUtil** Off-heap memory (MemoryUtil, MemoryStack, pointers): rewrite over ArrayBuffer
rewrite symbol=org.lwjgl.PointerBuffer Off-heap memory (MemoryUtil, MemoryStack, pointers): rewrite over ArrayBuffer
rewrite symbol=org.lwjgl.system.** Off-heap memory (MemoryUtil, MemoryStack, pointers): rewrite over ArrayBuffer
rewrite symbol=org.lwjgl.sdl.** Window, input, clipboard and events (SDL3): canvas, Pointer Lock and DOM events
rewrite symbol=org.lwjgl.openal.** Audio (OpenAL): Web Audio
rewrite symbol=javax.sound.** Audio (OpenAL): Web Audio
rewrite symbol=org.lwjgl.stb.** Image decode and encode (STB): createImageBitmap or a pure-Java codec
rewrite symbol=com.mojang.blaze3d.platform.NativeImage$WriteCallback Image decode and encode (STB): createImageBitmap or a pure-Java codec
rewrite symbol=org.lwjgl.util.freetype.** TrueType fonts (FreeType): pre-baked glyph atlases, Canvas2D for pack fonts
rewrite caller=io.netty.channel.nio.** symbol=java.nio.** Netty's NIO transport (selectors, socket channels): in the browser, connections are WebSockets on local event loops
rewrite caller=io.netty.channel.socket.nio.** symbol=java.nio.** Netty's NIO transport (selectors, socket channels): in the browser, connections are WebSockets on local event loops
rewrite caller=io.netty.util.concurrent.FastThreadLocalThread symbol=java.lang.Thread#<init> Netty's own thread class (a ThreadGroup constructor TeaVM lacks): event loops get their threads from the game's factory
rewrite symbol=io.netty.** Netty channels and pipeline: WebSocket transport under Connection
rewrite symbol=java.net.** Socket addresses, proxies and HTTP: server addresses become WebSocket URLs, HTTP becomes fetch
rewrite kind=reflection origin=minecraft Game code using reflection: replace with direct references
rewrite kind=reflection origin=log4j-api Logging backend discovery (ServiceLoader, class loading): bind the console logger directly
rewrite kind=reflection origin=slf4j-api Logging backend discovery (ServiceLoader, class loading): bind the console logger directly
rewrite origin=slf4j-api symbol=java.lang.** Logging backend discovery (ServiceLoader, class loading): bind the console logger directly
rewrite symbol=org.apache.logging.log4j.core.** Logging backend discovery (ServiceLoader, class loading): bind the console logger directly
rewrite origin=log4j-api Logging backend discovery (ServiceLoader, class loading): bind the console logger directly
rewrite kind=reflection origin=gson Gson reflective type adapters: register explicit adapters, or keep Gson on JsonElement trees
rewrite kind=reflection Library reflection: steer the library off the reflective path, or declare it for TeaVM
rewrite symbol=java.lang.invoke.** VarHandle and MethodHandle (Netty, Guava atomics): the libraries probe for them and fall back when they throw; patch any game caller
# --- Shim: JDK APIs TeaVM's class library lacks --------------------------------------------
stub symbol=sun.misc.Unsafe sun.misc.Unsafe in libraries: stub it as unavailable so Netty, Guava and JOML take their safe fallbacks
stub symbol=jdk.internal.misc.Unsafe sun.misc.Unsafe in libraries: stub it as unavailable so Netty, Guava and JOML take their safe fallbacks
shim symbol=java.util.concurrent.CompletableFuture CompletableFuture (async loading everywhere): a single-threaded implementation over TeaVM coroutines
shim symbol=java.util.concurrent.CompletionException CompletableFuture (async loading everywhere): a single-threaded implementation over TeaVM coroutines
shim symbol=java.util.concurrent.*Executor* Executors, thread pools and futures: a coroutine scheduler, later Web Workers
shim symbol=java.util.concurrent.ForkJoin* Executors, thread pools and futures: a coroutine scheduler, later Web Workers
shim symbol=java.util.concurrent.*Future Executors, thread pools and futures: a coroutine scheduler, later Web Workers
shim symbol=java.util.concurrent.*Exception Executors, thread pools and futures: a coroutine scheduler, later Web Workers
shim symbol=net.minecraft.util.Util$2 Executors, thread pools and futures: a coroutine scheduler, later Web Workers
shim symbol=com.google.common.util.concurrent.** Executors, thread pools and futures: a coroutine scheduler, later Web Workers
shim symbol=java.util.concurrent.** Locks, atomics and concurrent queues: single-threaded shims
shim symbol=com.google.common.cache.LocalCache$Segment Locks, atomics and concurrent queues: single-threaded shims
shim symbol=com.google.common.collect.MapMakerInternalMap$Segment Locks, atomics and concurrent queues: single-threaded shims
shim symbol=io.netty.util.concurrent.MpscIntQueue** Locks, atomics and concurrent queues: single-threaded shims
shim symbol=java.time.** java.time (dates, durations, formatting): compile a java.time implementation for TeaVM
shim symbol=java.nio.file.** Filesystem (java.nio.file, channels, locks, watching): an in-memory file system kept in OPFS or IndexedDB (ADR 0011)
shim symbol=java.nio.channels.** Filesystem (java.nio.file, channels, locks, watching): an in-memory file system kept in OPFS or IndexedDB (ADR 0011)
shim symbol=java.io.FileInputStream#getChannel Filesystem (java.nio.file, channels, locks, watching): an in-memory file system kept in OPFS or IndexedDB (ADR 0011)
shim symbol=java.io.File#toPath Filesystem (java.nio.file, channels, locks, watching): an in-memory file system kept in OPFS or IndexedDB (ADR 0011)
shim symbol=com.ibm.icu.** Bidi text and localized dates (ICU): the browser's Intl, or a minimal shim
shim symbol=com.mojang.text2speech.** Narrator: Web Speech API
shim symbol=java.lang.ScopedValue** ScopedValue (Java 25): a thread-local style shim
# --- Stub: small gaps where a trivial implementation is enough ------------------------------
stub symbol=java.lang.management.** JVM memory, GC and thread stats (debug overlay, crash reports, watchdog): report browser numbers or zeros
stub symbol=java.lang.StackWalker** Caller lookup (StackWalker, modules): return nothing
stub symbol=java.lang.Module** Caller lookup (StackWalker, modules): return nothing
stub symbol=java.lang.System#exit Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
stub symbol=java.lang.System#getenv Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
stub symbol=java.lang.System#mapLibraryName Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
stub symbol=java.lang.Runtime Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
stub symbol=java.lang.SecurityManager Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
stub symbol=java.lang.RuntimePermission Process control (exit, shutdown hooks, environment, native libraries): no-ops in a browser tab
stub symbol=java.lang.Thread Thread details TeaVM lacks (ids, state, onSpinWait): trivial answers under coroutines
stub symbol=java.** Small JDK methods and classes TeaVM's class library lacks: add them to the class library
stub symbol=javax.** Small JDK methods and classes TeaVM's class library lacks: add them to the class library
@@ -0,0 +1,408 @@
package incari.tools.survey;
import incari.tools.build.Log;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Renders {@code docs/port-backlog.md} from the triaged findings.
*
* <p>The file is tracked, so it holds only API names, package names and counts: never game
* code, and never Mojang member names (callers are summarized by package). The output is
* sorted and has no timestamp, so rerunning the survey on the same inputs changes nothing.
*/
final class Backlog {
private static final int SYMBOLS_PER_ITEM = 12;
private static final int PACKAGES_PER_ITEM = 4;
private final String version;
private final String teavmVersion;
private final int jdk;
private final String entryPoint;
private final Set<String> reachableClasses;
private final Origins origins;
private final List<Main.LibraryDecision> libraries;
private final List<Main.Classified> findings;
Backlog(
String version,
String teavmVersion,
int jdk,
String entryPoint,
Set<String> reachableClasses,
Origins origins,
List<Main.LibraryDecision> libraries,
List<Main.Classified> findings) {
this.version = version;
this.teavmVersion = teavmVersion;
this.jdk = jdk;
this.entryPoint = entryPoint;
this.reachableClasses = reachableClasses;
this.origins = origins;
this.libraries = libraries;
this.findings = findings;
}
/** Counts for one category or work item. A call site is one distinct (symbol, caller, line). */
private record Tally(int items, long symbols, long sites) {}
private static Tally tally(List<Main.Classified> group) {
long symbols = group.stream().map(c -> c.finding().symbol()).distinct().count();
long items = group.stream()
.map(c -> c.rule() == null ? null : c.rule().reason())
.distinct()
.count();
return new Tally((int) items, symbols, group.size());
}
String render() {
Map<SurveyRules.Category, List<Main.Classified>> byCategory = new LinkedHashMap<>();
for (SurveyRules.Category category : SurveyRules.Category.values()) {
byCategory.put(category, new ArrayList<>());
}
List<Main.Classified> unclassified = new ArrayList<>();
for (Main.Classified c : findings) {
if (c.rule() == null) {
unclassified.add(c);
} else {
byCategory
.computeIfAbsent(c.rule().category(), k -> new ArrayList<>())
.add(c);
}
}
StringBuilder md = new StringBuilder();
md.append("# Port backlog: Minecraft ").append(version).append(" under TeaVM\n\n");
md.append("Generated by `./incari survey`. Don't edit it by hand: change `")
.append(Main.RULES_FILE)
.append("` and rerun.\n\n");
Tally total = tally(findings);
md.append("TeaVM ")
.append(teavmVersion)
.append(" (WebAssembly GC) reaches ")
.append(String.format(Locale.ROOT, "%,d", reachableClasses.size()))
.append(" classes when every client class is a root (not just what `")
.append(entryPoint)
.append("` reaches). ")
.append(String.format(Locale.ROOT, "%,d", total.sites()))
.append(" call sites use ")
.append(String.format(Locale.ROOT, "%,d", total.symbols()))
.append(" APIs the browser build can't provide as-is, grouped below into ")
.append(byCategory.values().stream()
.mapToInt(g -> tally(g).items())
.sum())
.append(" work items.\n\n");
md.append("## Summary\n\n");
md.append("| Category | Meaning | Work items | APIs | Call sites |\n");
md.append("| --- | --- | ---: | ---: | ---: |\n");
for (Map.Entry<SurveyRules.Category, List<Main.Classified>> entry : byCategory.entrySet()) {
Tally t = tally(entry.getValue());
md.append("| ")
.append(entry.getKey().title())
.append(" | ")
.append(entry.getKey().meaning())
.append(" | ")
.append(t.items())
.append(" | ")
.append(t.symbols())
.append(" | ")
.append(t.sites())
.append(" |\n");
}
if (!unclassified.isEmpty()) {
Tally t = tally(unclassified);
md.append("| Unclassified | No rule matched yet. | - | ")
.append(t.symbols())
.append(" | ")
.append(t.sites())
.append(" |\n");
}
md.append("| **Total** | | ")
.append(byCategory.values().stream()
.mapToInt(g -> tally(g).items())
.sum())
.append(" | ")
.append(total.symbols())
.append(" | ")
.append(total.sites())
.append(" |\n\n");
md.append("By kind of finding:\n\n");
md.append("| Kind | Call sites | What it means |\n| --- | ---: | --- |\n");
Map<Finding.Kind, Long> byKind = findings.stream()
.collect(Collectors.groupingBy(c -> c.finding().kind(), TreeMap::new, Collectors.counting()));
for (Map.Entry<Finding.Kind, Long> entry : byKind.entrySet()) {
md.append("| ")
.append(entry.getKey().label())
.append(" | ")
.append(entry.getValue())
.append(" | ")
.append(kindMeaning(entry.getKey()))
.append(" |\n");
}
md.append('\n');
for (Map.Entry<SurveyRules.Category, List<Main.Classified>> entry : byCategory.entrySet()) {
renderCategory(md, entry.getKey(), entry.getValue());
}
if (!unclassified.isEmpty()) {
md.append("## Unclassified\n\n");
md.append("No rule in `")
.append(Main.RULES_FILE)
.append("` matches these yet. Add rules until this section disappears.\n\n");
renderSymbols(md, unclassified, Integer.MAX_VALUE);
}
renderInputs(md);
md.append("## Reading this backlog\n\n");
md.append("- **It's the first layer.** TeaVM stops following calls at anything it can't resolve, so stubbing"
+ " these items uncovers more. Rerun the survey after each round of porting work.\n");
md.append("- **Call sites** are distinct (API, calling class, line) triples. Findings TeaVM reported inside JDK"
+ " or class-library code are charged to the nearest game or library method that calls into it.\n");
md.append("- **JDK classes TeaVM lacks.** Left alone, TeaVM would copy them from the JDK running the compile,"
+ " dragging in JDK internals that can't work in a browser. The survey hides the host JDK, so each is"
+ " listed where the game uses it.\n");
md.append("- **Whole client, not one path.** Every class in the client jar is an analysis root, except the"
+ " `no-root` packages in `")
.append(Main.RULES_FILE)
.append(
"` (data generators, dedicated server)."
+ " Code only the integrated server runs is included; singleplayer is deferred, but its code ships.\n");
md.append("- **Stubs let the analysis continue.** TeaVM stops at anything missing, so the survey compiles in"
+ " rounds, stubbing what each round reports, until nothing new appears. Stubbed items are still"
+ " findings.\n");
md.append("- **Full detail** (every call site with its method and line) is in `work/survey/")
.append(version)
.append("/findings.json` after a local run. It stays out of git because it names"
+ " Mojang methods.\n");
return md.toString();
}
/** The reason of the rule that classified {@code c}; category groups hold only classified findings. */
private static String ruleReason(Main.Classified c) {
SurveyRules.TriageRule rule = c.rule();
if (rule == null) {
throw new IllegalStateException(
"Unclassified finding in a category group: " + c.finding().symbol());
}
return rule.reason();
}
private void renderCategory(StringBuilder md, SurveyRules.Category category, List<Main.Classified> group) {
md.append("## ").append(category.title()).append("\n\n");
if (group.isEmpty()) {
md.append("Nothing in this category.\n\n");
return;
}
Tally t = tally(group);
md.append(category.meaning())
.append(' ')
.append(t.items())
.append(" work items, ")
.append(t.symbols())
.append(" APIs, ")
.append(t.sites())
.append(" call sites.\n\n");
// Several rule lines may share a reason: together they are one work item.
Map<String, List<Main.Classified>> byItem = group.stream()
.collect(Collectors.groupingBy(Backlog::ruleReason, LinkedHashMap::new, Collectors.toList()));
List<Map.Entry<String, List<Main.Classified>>> items = new ArrayList<>(byItem.entrySet());
items.sort(Comparator.<Map.Entry<String, List<Main.Classified>>>comparingInt(
e -> -e.getValue().size())
.thenComparing(Map.Entry::getKey));
md.append("| Work item | APIs | Call sites | Where the calls are |\n| --- | ---: | ---: | --- |\n");
for (Map.Entry<String, List<Main.Classified>> item : items) {
Tally it = tally(item.getValue());
md.append("| ")
.append(escape(item.getKey()))
.append(" | ")
.append(it.symbols())
.append(" | ")
.append(it.sites())
.append(" | ")
.append(callerSummary(item.getValue()))
.append(" |\n");
}
md.append('\n');
for (Map.Entry<String, List<Main.Classified>> item : items) {
md.append("### ").append(escape(item.getKey())).append("\n\n");
renderSymbols(md, item.getValue(), SYMBOLS_PER_ITEM);
}
}
private void renderSymbols(StringBuilder md, List<Main.Classified> group, int limit) {
Map<String, List<Main.Classified>> bySymbol = group.stream()
.collect(Collectors.groupingBy(c -> c.finding().symbol(), TreeMap::new, Collectors.toList()));
List<Map.Entry<String, List<Main.Classified>>> symbols = new ArrayList<>(bySymbol.entrySet());
symbols.sort(Comparator.<Map.Entry<String, List<Main.Classified>>>comparingInt(
e -> -e.getValue().size())
.thenComparing(Map.Entry::getKey));
md.append("| API | Kind | Call sites |\n| --- | --- | ---: |\n");
int shown = 0;
for (Map.Entry<String, List<Main.Classified>> symbol : symbols) {
if (shown++ == limit) {
int restSites = symbols.subList(limit, symbols.size()).stream()
.mapToInt(e -> e.getValue().size())
.sum();
md.append("| ...and ")
.append(symbols.size() - limit)
.append(" more | | ")
.append(restSites)
.append(" |\n");
break;
}
String kinds = symbol.getValue().stream()
.map(c -> c.finding().kind().label())
.distinct()
.sorted()
.collect(Collectors.joining(", "));
md.append("| `")
.append(symbol.getKey())
.append("` | ")
.append(kinds)
.append(" | ")
.append(symbol.getValue().size())
.append(" |\n");
}
md.append('\n');
}
/** "net.minecraft.client.renderer (40), guava (3)": where the calls come from, by package. */
private String callerSummary(List<Main.Classified> group) {
Map<String, Long> counts =
group.stream().collect(Collectors.groupingBy(c -> callerArea(c), HashMap::new, Collectors.counting()));
List<Map.Entry<String, Long>> sorted = new ArrayList<>(counts.entrySet());
sorted.sort(Map.Entry.<String, Long>comparingByValue().reversed().thenComparing(Map.Entry::getKey));
String shown = sorted.stream()
.limit(PACKAGES_PER_ITEM)
.map(e -> "`" + e.getKey() + "` (" + e.getValue() + ")")
.collect(Collectors.joining(", "));
return sorted.size() > PACKAGES_PER_ITEM
? shown + ", +" + (sorted.size() - PACKAGES_PER_ITEM) + " more"
: shown;
}
/** A Minecraft caller's package, or a library's name. Never a Mojang class or member name. */
private String callerArea(Main.Classified c) {
String caller = c.finding().caller();
if (caller == null) {
return "unknown";
}
String origin = origins.of(caller);
if (!Origins.MINECRAFT.equals(origin)) {
return origin;
}
int dot = caller.lastIndexOf('.');
return dot > 0 ? caller.substring(0, dot) : caller;
}
private void renderInputs(StringBuilder md) {
md.append("## Inputs\n\n");
md.append("- Minecraft ")
.append(version)
.append(", entry point `")
.append(entryPoint)
.append("` plus every client class except the `no-root` packages\n");
md.append("- TeaVM ")
.append(teavmVersion)
.append(", WebAssembly GC target, run on JDK ")
.append(jdk)
.append('\n');
Map<String, Long> reachable = reachableClasses.stream()
.collect(Collectors.groupingBy(this::originGroup, TreeMap::new, Collectors.counting()));
md.append("- Reachable classes by origin: ")
.append(reachable.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue()
.reversed()
.thenComparing(Map.Entry::getKey))
.map(e -> e.getKey() + " " + String.format(Locale.ROOT, "%,d", e.getValue()))
.collect(Collectors.joining(", ")))
.append("\n\n");
md.append("Libraries, as decided in `")
.append(Main.RULES_FILE)
.append("`. Only `keep` libraries are compiled;"
+ " calls into the others show up above as missing classes at their call sites.\n\n");
md.append("| Library | Decision | Why |\n| --- | --- | --- |\n");
for (Main.LibraryDecision lib : libraries.stream()
.sorted(Comparator.comparing((Main.LibraryDecision l) -> l.action())
.thenComparing(Main.LibraryDecision::coordinates))
.toList()) {
md.append("| `")
.append(lib.coordinates())
.append("` | ")
.append(lib.action().name().toLowerCase(Locale.ROOT))
.append(" | ")
.append(escape(lib.reason()))
.append(" |\n");
}
md.append('\n');
}
private String originGroup(String className) {
if (className.startsWith("incari.survey.")) {
return "survey roots";
}
if (!origins.appClass(className).equals(className)) {
return "generated lambda classes";
}
String origin = origins.of(className);
return switch (origin) {
case Origins.MINECRAFT -> "Minecraft";
case Origins.TEAVM -> "TeaVM class library";
case Origins.HOST_JDK -> "stubbed JDK classes";
case Origins.ABSENT -> "stubbed library classes";
default -> "libraries";
};
}
private static String kindMeaning(Finding.Kind kind) {
return switch (kind) {
case MISSING_CLASS ->
"TeaVM can't find the class: not in its class library, or in a library left off the classpath";
case MISSING_METHOD -> "The class exists in TeaVM's class library but lacks this method";
case MISSING_FIELD -> "The class exists but lacks this field";
case UNSUPPORTED_CLASS, UNSUPPORTED_METHOD -> "TeaVM knows it but can't support it on WebAssembly GC";
case MISSING_SUPERTYPE -> "A class extends or implements something that isn't on the classpath";
case MISSING_BOOTSTRAP -> "An invokedynamic TeaVM can't compile";
case NATIVE -> "A JNI method; nothing to call in a browser";
case HOST_JDK -> "A JDK class that TeaVM's class library doesn't have; the game or a library uses it here";
case REFLECTION -> "Reflective lookup that TeaVM's closed-world compile can't see";
case OTHER -> "Any other compiler error";
};
}
private static String escape(String text) {
return text.replace("|", "\\|");
}
void printSummary() {
Map<String, Long> counts = findings.stream()
.collect(Collectors.groupingBy(
c -> c.rule() == null
? "unclassified"
: c.rule().category().title().toLowerCase(Locale.ROOT),
TreeMap::new,
Collectors.counting()));
Function<String, Long> get = key -> counts.getOrDefault(key, 0L);
Log.info("Call sites: stub " + get.apply("stub") + ", shim " + get.apply("shim") + ", rewrite "
+ get.apply("rewrite") + ", delete " + get.apply("delete") + ", unclassified "
+ get.apply("unclassified"));
}
}
@@ -0,0 +1,242 @@
package incari.tools.survey;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.jspecify.annotations.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* Scans reachable game and library bytecode for two things TeaVM itself doesn't report.
*
* <ul>
* <li><b>Reflection.</b> TeaVM compiles a closed world: it keeps only what it can see being
* used. A class loaded by name, or a method looked up by string, is invisible to it
* unless declared ahead of time. Each hit is a place to replace with a direct reference.
* <li><b>Host-JDK references.</b> Instructions that name a JDK class TeaVM's class library
* lacks (see {@link Origins}). TeaVM compiles those from the host JDK, which compiles
* but often can't run in a browser. Scanning the declared owner at each instruction
* finds exactly the game code that names such a class, with none of the call graph's
* virtual-dispatch noise.
* </ul>
*/
public final class BytecodeScanner {
/** {@code owner -> method names} of reflective entry points. An empty set means "any method". */
private static final Map<String, Set<String>> REFLECTIVE = Map.ofEntries(
Map.entry(
"java/lang/Class",
Set.of(
"forName",
"newInstance",
"getDeclaredMethod",
"getDeclaredMethods",
"getMethod",
"getMethods",
"getDeclaredField",
"getDeclaredFields",
"getField",
"getFields",
"getDeclaredConstructor",
"getDeclaredConstructors",
"getConstructor",
"getConstructors",
"getRecordComponents",
"getDeclaredClasses",
"getAnnotation",
"getAnnotations",
"getDeclaredAnnotations",
"getGenericSuperclass",
"getGenericInterfaces")),
Map.entry(
"java/lang/ClassLoader",
Set.of(
"loadClass",
"getResource",
"getResources",
"getResourceAsStream",
"getSystemClassLoader",
"getSystemResource",
"getSystemResourceAsStream")),
Map.entry("java/lang/reflect/Method", Set.of("invoke")),
Map.entry("java/lang/reflect/Constructor", Set.of("newInstance")),
Map.entry("java/lang/reflect/Field", Set.of()),
Map.entry("java/lang/reflect/Proxy", Set.of("newProxyInstance")),
Map.entry("java/lang/reflect/RecordComponent", Set.of("getAccessor")),
Map.entry("java/util/ServiceLoader", Set.of("load", "loadInstalled")),
Map.entry("java/lang/invoke/MethodHandles", Set.of("lookup", "publicLookup", "privateLookupIn")),
// Unsafe isn't listed: it's a host-JDK class, reported as such at every use.
Map.entry("java/lang/invoke/MethodHandles$Lookup", Set.of()));
private BytecodeScanner() {}
/**
* Scans the given app jars, looking only inside {@code reachableMethods}
* ({@code owner#name(descriptor)}) so that dead code TeaVM drops anyway doesn't inflate the backlog.
*/
public static List<Finding> scan(
Map<Path, String> jars, Set<String> reachableClasses, Set<String> reachableMethods, Origins origins)
throws IOException {
List<Finding> findings = new ArrayList<>();
for (Path jar : jars.keySet()) {
try (JarFile file = new JarFile(jar.toFile())) {
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (!name.endsWith(".class") || name.startsWith("META-INF/")) {
continue;
}
String className = name.substring(0, name.length() - 6).replace('/', '.');
if (!reachableClasses.contains(className)) {
continue;
}
try (InputStream in = file.getInputStream(entry)) {
new ClassReader(in)
.accept(
new Visitor(className, reachableMethods, origins, findings),
ClassReader.SKIP_FRAMES);
}
}
}
}
return findings;
}
private static final class Visitor extends ClassVisitor {
private final String className;
private final Set<String> reachableMethods;
private final Origins origins;
private final List<Finding> findings;
Visitor(String className, Set<String> reachableMethods, Origins origins, List<Finding> findings) {
super(Opcodes.ASM9);
this.className = className;
this.reachableMethods = reachableMethods;
this.origins = origins;
this.findings = findings;
}
/** A reachable class extending or implementing something TeaVM can't see. */
@Override
public void visit(
int version,
int access,
String name,
@Nullable String signature,
@Nullable String superName,
String @Nullable [] interfaces) {
List<String> supertypes = new ArrayList<>();
if (superName != null) {
supertypes.add(superName);
}
if (interfaces != null) {
supertypes.addAll(List.of(interfaces));
}
for (String supertype : supertypes) {
String superClass = supertype.replace('/', '.');
String origin = origins.of(superClass);
if (Origins.ABSENT.equals(origin) || Origins.HOST_JDK.equals(origin)) {
Finding.Kind kind =
Origins.ABSENT.equals(origin) ? Finding.Kind.MISSING_SUPERTYPE : Finding.Kind.HOST_JDK;
findings.add(new Finding(
kind, superClass, className + " extends " + superClass, className, null, -1, null));
}
}
}
@Override
public @Nullable MethodVisitor visitMethod(
int access,
String name,
String descriptor,
@Nullable String signature,
String @Nullable [] exceptions) {
if (!reachableMethods.contains(className + "#" + name + descriptor)) {
return null;
}
String callerMethod = name + descriptor;
return new MethodVisitor(Opcodes.ASM9) {
private int line = -1;
@Override
public void visitLineNumber(int lineNumber, Label start) {
line = lineNumber;
}
@Override
public void visitMethodInsn(int opcode, String owner, String method, String desc, boolean isInterface) {
Set<String> names = REFLECTIVE.get(owner);
if (names != null && (names.isEmpty() || names.contains(method))) {
String symbol = owner.replace('/', '.') + "#" + method;
findings.add(new Finding(
Finding.Kind.REFLECTION, symbol, symbol + desc, className, callerMethod, line, null));
}
hostJdk(owner, method, desc);
}
@Override
public void visitFieldInsn(int opcode, String owner, String field, String desc) {
hostJdk(owner, field, null);
}
@Override
public void visitTypeInsn(int opcode, String type) {
hostJdk(type, null, null);
}
@Override
public void visitLdcInsn(Object value) {
if (value instanceof Type type && type.getSort() == Type.OBJECT) {
hostJdk(type.getInternalName(), null, null);
}
}
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler, @Nullable String type) {
if (type != null) {
hostJdk(type, null, null);
}
}
/*
* Records a reference to a class that isn't compiled from the game's own jars or
* TeaVM's class library: either copied from the host JDK, or absent entirely
* (a library the rules leave out). TeaVM names an absent class only once, at its
* first use; this finds every call site.
*/
private void hostJdk(String owner, @Nullable String member, @Nullable String desc) {
if (owner.startsWith("[")) {
return;
}
String ownerName = owner.replace('/', '.');
String origin = origins.of(ownerName);
Finding.@Nullable Kind kind =
switch (origin) {
case Origins.HOST_JDK -> Finding.Kind.HOST_JDK;
case Origins.ABSENT -> Finding.Kind.MISSING_CLASS;
default -> null;
};
if (kind == null) {
return;
}
String symbol = member != null ? ownerName + "#" + member : ownerName;
String detail = desc != null ? symbol + desc : symbol;
findings.add(new Finding(kind, symbol, detail, className, callerMethod, line, null));
}
};
}
}
}
@@ -0,0 +1,68 @@
package incari.tools.survey;
import org.jspecify.annotations.Nullable;
/**
* One place where the client (or a library it keeps) uses something the browser build
* can't provide as-is.
*
* @param kind what went wrong, e.g. a missing method or a reflective call
* @param symbol the thing that's missing or used: a class ({@code java.nio.file.Files}),
* method ({@code java.nio.file.Files#walk}) or field
* @param detail the full descriptor, for the machine-readable report
* @param caller the calling class, or {@code null} when TeaVM gives no location
* @param callerMethod the calling method's name and descriptor, or {@code null}
* @param line source line in the caller, or -1
* @param via for findings TeaVM reported inside JDK or class-library code, the method
* there that the game's {@code caller} reached it through; otherwise {@code null}
*/
public record Finding(
Kind kind,
String symbol,
String detail,
@Nullable String caller,
@Nullable String callerMethod,
int line,
@Nullable String via) {
public enum Kind {
MISSING_CLASS("missing class"),
MISSING_METHOD("missing method"),
MISSING_FIELD("missing field"),
UNSUPPORTED_CLASS("unsupported on target"),
UNSUPPORTED_METHOD("unsupported on target"),
MISSING_SUPERTYPE("missing supertype"),
MISSING_BOOTSTRAP("unsupported invokedynamic"),
NATIVE("native method"),
HOST_JDK("JDK class TeaVM lacks"),
REFLECTION("reflection"),
OTHER("other compiler error");
private final String label;
Kind(String label) {
this.label = label;
}
public String label() {
return label;
}
/** The name rules.txt uses: {@code MISSING_METHOD} -> {@code missing-method}. */
public String ruleName() {
return name().toLowerCase(java.util.Locale.ROOT).replace('_', '-');
}
}
/** The class that owns {@link #symbol}: {@code java.nio.file.Files#walk} → {@code java.nio.file.Files}. */
public String owner() {
int hash = symbol.indexOf('#');
return hash < 0 ? symbol : symbol.substring(0, hash);
}
/** The member part of {@link #symbol}, or {@code null} for a class. */
public @Nullable String member() {
int hash = symbol.indexOf('#');
return hash < 0 ? null : symbol.substring(hash + 1);
}
}
@@ -0,0 +1,41 @@
package incari.tools.survey;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import org.jspecify.annotations.Nullable;
/**
* Hides the running JDK's own class files from TeaVM. When TeaVM's class library has no
* replacement for a {@code java.*} class, TeaVM compiles the host JDK's class instead, pulling in
* JDK internals that can't run in a browser. Hidden, the gap shows up as a missing class at the
* place the game uses it, where Incari can fill it deliberately.
*/
public final class HostJdkHidingLoader extends ClassLoader {
private final Origins origins;
public HostJdkHidingLoader(ClassLoader parent, Origins origins) {
super(parent);
this.origins = origins;
}
@Override
public @Nullable URL getResource(String name) {
return hidden(name) ? null : super.getResource(name);
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
return hidden(name) ? Collections.emptyEnumeration() : super.getResources(name);
}
private boolean hidden(String name) {
if (!name.endsWith(".class")) {
return false;
}
String className = name.substring(0, name.length() - 6).replace('/', '.');
return Origins.HOST_JDK.equals(origins.of(className));
}
}
@@ -0,0 +1,199 @@
package incari.tools.survey;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import incari.tools.build.BuildConfig;
import incari.tools.build.CliException;
import incari.tools.build.FileTrees;
import incari.tools.build.GameFiles;
import incari.tools.build.Log;
import incari.tools.build.Workspace;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jspecify.annotations.Nullable;
/**
* {@code ./incari survey}: the TeaVM compile survey.
*
* <p>Compiles the pinned client with TeaVM (WebAssembly GC), collects everything that stands
* between it and a browser build, triages each finding with {@code tools/survey/rules.txt},
* and writes the outputs below. {@code --reclassify} skips the (slow) compile and reuses the
* last run's saved TeaVM result, for iterating on the rules.
* <ul>
* <li>{@code docs/port-backlog.md}: counts per category and one row per work item. Tracked.
* It holds API names and counts only, never game code.
* <li>{@code work/survey/<version>/findings.json}: every finding with its call site. Git-ignored.
* </ul>
*/
public final class Main {
static final String ENTRY_POINT = "net.minecraft.client.main.Main";
static final String RULES_FILE = "tools/survey/rules.txt";
static final String BACKLOG_FILE = "docs/port-backlog.md";
/**
* TeaVM compiles JDK classes it has no replacement for straight from the running JDK, so
* the JDK version changes the result. It also can't read class files newer than Java 25.
*/
static final int REQUIRED_JDK = 25;
private Main() {}
public static void main(String[] args) {
try {
run(List.of(args));
} catch (CliException e) {
System.err.println("error: " + e.getMessage());
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
}
static void run(List<String> args) throws Exception {
boolean reclassify = args.equals(List.of("--reclassify"));
if (!args.isEmpty() && !reclassify) {
throw new CliException("Usage: ./incari survey [--reclassify]");
}
int jdk = Runtime.version().feature();
if (jdk != REQUIRED_JDK) {
throw new CliException(
"The survey must run on JDK " + REQUIRED_JDK + " (this is JDK " + jdk + "). TeaVM compiles"
+ " missing JDK classes from the running JDK, so another version changes the result.\n"
+ "Point JAVA_HOME at a JDK " + REQUIRED_JDK
+ ", e.g. JAVA_HOME=/usr/lib/jvm/java-25-openjdk ./incari survey");
}
Workspace ws = Workspace.discover(Path.of(System.getProperty("incari.cwd", ".")));
BuildConfig config = BuildConfig.load(ws.repoRoot());
GameFiles game = GameFiles.load(ws, config);
SurveyRules rules = SurveyRules.load(ws.repoRoot().resolve(RULES_FILE));
Map<Path, String> jars = new LinkedHashMap<>();
jars.put(game.clientJar(), Origins.MINECRAFT);
List<LibraryDecision> libraries = new ArrayList<>();
for (GameFiles.LibraryJar lib : game.libraries()) {
String name = lib.library().name();
SurveyRules.LibraryRule rule = rules.library(name);
libraries.add(new LibraryDecision(name, rule.action(), rule.reason()));
if (rule.action() == SurveyRules.LibraryAction.KEEP) {
jars.put(lib.jar(), name.split(":", -1)[1]);
}
}
Origins origins = new Origins(jars, Main.class.getClassLoader());
Path outDir = ws.surveyDir(config.minecraftVersion());
Files.createDirectories(outDir);
Path teavmFindings = outDir.resolve("teavm-findings.json");
Path reachableClassesFile = outDir.resolve("reachable-classes.txt");
Path reachableMethodsFile = outDir.resolve("reachable-methods.txt");
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
TeaVmSurvey.Result result;
if (reclassify) {
if (!Files.isRegularFile(teavmFindings)) {
throw new CliException("No saved TeaVM result in " + outDir + ". Run ./incari survey first.");
}
Log.step("Reusing the saved TeaVM result (--reclassify)");
result = new TeaVmSurvey.Result(
List.of(gson.fromJson(Files.readString(teavmFindings), Finding[].class)),
new java.util.TreeSet<>(Files.readAllLines(reachableClassesFile)),
new java.util.HashSet<>(Files.readAllLines(reachableMethodsFile)));
} else {
Log.step("Compiling " + game.version().id() + " with TeaVM " + teavmVersion()
+ " (WebAssembly GC, in rounds; about a minute)");
long start = System.nanoTime();
Path rootsDir = outDir.resolve("roots");
FileTrees.deleteRecursively(rootsDir);
int rooted = Roots.generate(game.clientJar(), rules::isRooted, ENTRY_POINT, rootsDir);
Log.info("Rooting " + rooted + " client classes, so the whole client is analysed, not only what"
+ " main() reaches");
result = TeaVmSurvey.run(Roots.ENTRY, jars, rootsDir, origins, outDir);
Log.info("TeaVM analysis took " + (System.nanoTime() - start) / 1_000_000_000 + "s, "
+ result.reachableClasses().size() + " reachable classes");
Files.write(reachableClassesFile, result.reachableClasses());
Files.write(
reachableMethodsFile,
result.reachableAppMethods().stream().sorted().toList());
Files.writeString(teavmFindings, gson.toJson(result.findings()));
}
Log.step("Scanning reachable code for reflection and host-JDK references");
List<Finding> scanned =
BytecodeScanner.scan(jars, result.reachableClasses(), result.reachableAppMethods(), origins);
// For classes TeaVM can't see (libraries left off the classpath, host-JDK classes), the
// scan lists every call site in reachable game code, while TeaVM names each one once
// (or, once stubbed, per member).
// Keep TeaVM's entries only where the scan can't see: callers outside the game's jars.
Set<Finding> findings = new LinkedHashSet<>();
for (Finding f : result.findings()) {
if (f.caller() != null && f.caller().startsWith("incari.survey.roots.")) {
continue; // raised by the synthetic roots' own calls; the scan covers the real callers
}
boolean coveredByScan =
switch (f.kind()) {
case MISSING_CLASS, MISSING_METHOD, MISSING_FIELD ->
TeaVmSurvey.stubbedAsClass(origins, f.owner())
&& f.caller() != null
&& origins.isApp(f.caller());
// TeaVM reports these without the extending class; the scan names every one.
case MISSING_SUPERTYPE -> true;
default -> false;
};
if (!coveredByScan) {
findings.add(f);
}
}
findings.addAll(scanned);
List<Classified> classified = new ArrayList<>();
for (Finding finding : findings) {
@Nullable String origin = finding.caller() != null ? origins.of(finding.caller()) : null;
classified.add(new Classified(
finding, origin, rules.classify(finding, finding.kind().ruleName(), origin)));
}
List<Map<String, Object>> json = new ArrayList<>();
for (Classified c : classified) {
Map<String, Object> entry = new LinkedHashMap<>();
entry.put(
"category",
c.rule() != null ? c.rule().category().name().toLowerCase(java.util.Locale.ROOT) : "unclassified");
entry.put("rule", c.rule() != null ? c.rule().reason() : null);
entry.put("origin", c.origin());
entry.put("finding", c.finding());
json.add(entry);
}
Files.writeString(outDir.resolve("findings.json"), gson.toJson(json));
Backlog backlog = new Backlog(
game.version().id(),
teavmVersion(),
jdk,
ENTRY_POINT,
result.reachableClasses(),
origins,
libraries,
classified);
Files.writeString(ws.repoRoot().resolve(BACKLOG_FILE), backlog.render());
Log.step("Wrote " + BACKLOG_FILE + " and work/survey/" + game.version().id() + "/findings.json");
backlog.printSummary();
}
record LibraryDecision(String coordinates, SurveyRules.LibraryAction action, String reason) {}
/** A finding with its caller's origin and the rule that triaged it ({@code null}: unclassified). */
record Classified(Finding finding, @Nullable String origin, SurveyRules.@Nullable TriageRule rule) {}
/** Set by the Gradle build from the version catalog; TeaVM's jars don't record their own version. */
static String teavmVersion() {
return System.getProperty("incari.teavm.version", "unknown");
}
}
@@ -0,0 +1,113 @@
package incari.tools.survey;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Knows where each class comes from: the Minecraft client jar, one of its libraries, TeaVM's
* browser class library, or (the case worth flagging) the JDK running the survey.
*
* <p>That last one matters because TeaVM compiles a {@code java.*} class straight from the
* host JDK when its own class library has no replacement, dragging in JDK internals
* ({@code jdk.internal.*}, {@code sun.*}) that were never meant to run in a browser. The
* survey hides those classes from TeaVM and reports each use instead.
*/
public final class Origins {
public static final String MINECRAFT = "minecraft";
public static final String TEAVM = "teavm-classlib";
public static final String HOST_JDK = "host-jdk";
/** Nowhere: a library the rules leave off the classpath, or a class nobody ships. */
public static final String ABSENT = "absent";
private final Map<String, String> appClasses = new HashMap<>();
private final Map<String, Boolean> classlibCache = new HashMap<>();
private final Map<String, Boolean> jdkCache = new HashMap<>();
private final ClassLoader teavmLoader;
/**
* @param jars each app jar (client and kept libraries) mapped to its origin name
* @param teavmLoader a loader that can see TeaVM's class library
*/
public Origins(Map<Path, String> jars, ClassLoader teavmLoader) throws IOException {
this.teavmLoader = teavmLoader;
for (Map.Entry<Path, String> jar : jars.entrySet()) {
try (JarFile file = new JarFile(jar.getKey().toFile())) {
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
String name = entries.nextElement().getName();
if (name.endsWith(".class") && !name.startsWith("META-INF/")) {
appClasses.putIfAbsent(
name.substring(0, name.length() - 6).replace('/', '.'), jar.getValue());
}
}
}
}
}
/** {@link #MINECRAFT}, a library name, {@link #TEAVM}, {@link #HOST_JDK} or {@link #ABSENT}. */
public String of(String className) {
String app = appClasses.get(appClass(className));
if (app != null) {
return app;
}
if (isInClasslib(className)) {
return TEAVM;
}
return isInJdk(className) ? HOST_JDK : ABSENT;
}
/** True for code Incari compiles as part of the game: the client and its kept libraries. */
public boolean isApp(String className) {
return appClasses.containsKey(appClass(className));
}
/**
* The jar class behind a name. TeaVM compiles lambdas into synthetic classes named after
* their enclosing class ({@code net.minecraft.util.Util$makeIoExecutor$lambda$_20_0}) that
* exist in no jar; those belong to the enclosing class.
*/
public String appClass(String className) {
if (appClasses.containsKey(className)) {
return className;
}
int lambda = className.indexOf("$lambda$");
if (lambda > 0) {
String outer = className.substring(0, lambda);
for (int dollar = outer.length(); dollar > 0; dollar = outer.lastIndexOf('$', dollar - 1)) {
String candidate = outer.substring(0, dollar);
if (appClasses.containsKey(candidate)) {
return candidate;
}
}
}
return className;
}
private boolean isInJdk(String className) {
return jdkCache.computeIfAbsent(
className,
name -> ClassLoader.getPlatformClassLoader().getResource(name.replace('.', '/') + ".class") != null);
}
private boolean isInClasslib(String className) {
if (className.startsWith("org.teavm.")) {
return true;
}
String outer = className.contains("$") ? className.substring(0, className.indexOf('$')) : className;
return classlibCache.computeIfAbsent(outer, name -> {
// TeaVM's naming scheme: java.util.ArrayList -> org.teavm.classlib.java.util.TArrayList.
// Internal helpers skip the T (org.teavm.classlib.java.util.TemplateCollections).
int dot = name.lastIndexOf('.');
String dir = "org/teavm/classlib/" + name.substring(0, dot + 1).replace('.', '/');
String simple = name.substring(dot + 1);
return teavmLoader.getResource(dir + "T" + simple + ".class") != null
|| teavmLoader.getResource(dir + simple + ".class") != null;
});
}
}
@@ -0,0 +1,125 @@
package incari.tools.survey;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.jspecify.annotations.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
/**
* How the game's bytecode uses classes it doesn't ship: which members it touches, whether
* each is static, and which types it treats as interfaces.
*
* <p>The auto-stubber needs this to fake a missing class convincingly enough for TeaVM's
* analysis to continue. TeaVM's own error says only "method X not found", not whether X is
* static or lives on an interface.
*/
final class ReferenceIndex {
/** A member reference as seen at a call site. {@code nameAndDesc} is e.g. {@code "foo(I)V"} or {@code "bar:I"}. */
record Member(String owner, String nameAndDesc, boolean method, boolean isStatic) {}
private final Map<String, Map<String, Member>> byOwner = new HashMap<>();
private final Set<String> interfaces = new HashSet<>();
private final Set<String> superclasses = new HashSet<>();
static ReferenceIndex build(Iterable<Path> jars) throws IOException {
ReferenceIndex index = new ReferenceIndex();
for (Path jar : jars) {
try (JarFile file = new JarFile(jar.toFile())) {
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (!entry.getName().endsWith(".class") || entry.getName().startsWith("META-INF/")) {
continue;
}
try (InputStream in = file.getInputStream(entry)) {
new ClassReader(in)
.accept(index.new Visitor(), ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG);
}
}
}
}
return index;
}
/** Every member of {@code owner} (dotted name) the game references. */
Iterable<Member> membersOf(String owner) {
Map<String, Member> members = byOwner.get(owner);
return members != null ? members.values() : Set.of();
}
/** The recorded static-ness of a member, or {@code null} if the game never references it. */
@Nullable
Boolean isStatic(String owner, String nameAndDesc) {
Map<String, Member> members = byOwner.get(owner);
Member member = members != null ? members.get(nameAndDesc) : null;
return member != null ? member.isStatic() : null;
}
boolean usedAsInterface(String owner) {
return interfaces.contains(owner) && !superclasses.contains(owner);
}
private void add(String internalOwner, String nameAndDesc, boolean method, boolean isStatic) {
String owner = internalOwner.replace('/', '.');
byOwner.computeIfAbsent(owner, k -> new HashMap<>())
.putIfAbsent(nameAndDesc, new Member(owner, nameAndDesc, method, isStatic));
}
private final class Visitor extends ClassVisitor {
Visitor() {
super(Opcodes.ASM9);
}
@Override
public void visit(
int version,
int access,
String name,
@Nullable String signature,
@Nullable String superName,
String @Nullable [] ifaces) {
if (superName != null) {
superclasses.add(superName.replace('/', '.'));
}
if (ifaces != null) {
for (String iface : ifaces) {
interfaces.add(iface.replace('/', '.'));
}
}
}
@Override
public MethodVisitor visitMethod(
int access, String name, String descriptor, String signature, String[] exceptions) {
return new MethodVisitor(Opcodes.ASM9) {
@Override
public void visitMethodInsn(int opcode, String owner, String method, String desc, boolean isInterface) {
if (owner.startsWith("[")) {
return;
}
add(owner, method + desc, true, opcode == Opcodes.INVOKESTATIC);
if (isInterface) {
interfaces.add(owner.replace('/', '.'));
}
}
@Override
public void visitFieldInsn(int opcode, String owner, String field, String desc) {
add(owner, field + ":" + desc, false, opcode == Opcodes.GETSTATIC || opcode == Opcodes.PUTSTATIC);
}
};
}
}
}
@@ -0,0 +1,204 @@
package incari.tools.survey;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.function.Predicate;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.jspecify.annotations.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
/**
* Generates a synthetic entry point that calls every method of every client class.
*
* <p>Following the game from {@code main} alone reaches only part of it: TeaVM resolves a
* virtual call by the types that actually flow to it, so a screen created in an async
* callback, or a packet handler behind the network layer, looks unreachable once those are
* stubbed. The survey is meant to scope the whole client, so every method is made a root:
* static methods by {@code invokestatic}, constructors by {@code new}, everything else by
* {@code invokespecial} on a null receiver. TeaVM doesn't verify bytecode, so this links
* each method directly, private ones included, whatever its runtime receiver would be.
*
* <p>Each client class gets its own root method, so a call TeaVM decides never returns only
* hides the rest of that one class.
*/
final class Roots {
static final String ENTRY = "incari.survey.roots.Entry";
private static final String PACKAGE = "incari/survey/roots/";
/** Keeps each generated class well inside the constant-pool and method-count limits. */
private static final int CLASSES_PER_HOLDER = 150;
private Roots() {}
/**
* Writes the roots for {@code jar} into {@code dir}. {@code rooted} decides which classes
* become roots; {@code mainClass} is still called first, as the real entry point.
*
* @return the number of classes rooted
*/
static int generate(Path jar, Predicate<String> rooted, String mainClass, Path dir) throws IOException {
List<byte[]> classes = new ArrayList<>();
try (JarFile file = new JarFile(jar.toFile())) {
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (!name.endsWith(".class")
|| name.startsWith("META-INF/")
|| name.endsWith("package-info.class")
|| name.endsWith("module-info.class")) {
continue;
}
if (!rooted.test(name.substring(0, name.length() - 6).replace('/', '.'))) {
continue;
}
try (InputStream in = file.getInputStream(entry)) {
classes.add(in.readAllBytes());
}
}
}
List<String> holders = new ArrayList<>();
for (int start = 0; start < classes.size(); start += CLASSES_PER_HOLDER) {
String holder = PACKAGE + "Roots" + holders.size();
byte[] bytes = holder(holder, classes.subList(start, Math.min(start + CLASSES_PER_HOLDER, classes.size())));
write(dir, holder, bytes);
holders.add(holder);
}
write(dir, ENTRY.replace('.', '/'), entry(mainClass, holders));
return classes.size();
}
private static byte[] entry(String mainClass, List<String> holders) {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, ENTRY.replace('.', '/'), null, "java/lang/Object", null);
MethodVisitor mv =
cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESTATIC, mainClass.replace('.', '/'), "main", "([Ljava/lang/String;)V", false);
for (String holder : holders) {
mv.visitMethodInsn(Opcodes.INVOKESTATIC, holder, "run", "()V", false);
}
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
cw.visitEnd();
return cw.toByteArray();
}
private static byte[] holder(String name, List<byte[]> classes) {
// Straight-line code with no branches needs no stack map frames, so COMPUTE_MAXS is enough.
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cw.visit(Opcodes.V1_8, Opcodes.ACC_PUBLIC, name, null, "java/lang/Object", null);
MethodVisitor run = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "run", "()V", null, null);
run.visitCode();
for (int i = 0; i < classes.size(); i++) {
String method = "c" + i;
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC, method, "()V", null, null);
mv.visitCode();
ClassReader reader = new ClassReader(classes.get(i));
reader.accept(new CallEveryMethod(mv, reader.getClassName()), ClassReader.SKIP_CODE);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
run.visitMethodInsn(Opcodes.INVOKESTATIC, name, method, "()V", false);
}
run.visitInsn(Opcodes.RETURN);
run.visitMaxs(0, 0);
run.visitEnd();
cw.visitEnd();
return cw.toByteArray();
}
/** Emits one call per method of the visited class into {@code out}. */
private static final class CallEveryMethod extends ClassVisitor {
private final MethodVisitor out;
private final String owner;
private boolean isInterface;
private boolean isAbstract;
CallEveryMethod(MethodVisitor out, String owner) {
super(Opcodes.ASM9);
this.out = out;
this.owner = owner;
}
@Override
public void visit(
int version,
int access,
String name,
@Nullable String signature,
@Nullable String superName,
String @Nullable [] interfaces) {
isInterface = (access & Opcodes.ACC_INTERFACE) != 0;
isAbstract = (access & Opcodes.ACC_ABSTRACT) != 0;
}
@Override
public @Nullable MethodVisitor visitMethod(
int access,
String name,
String descriptor,
@Nullable String signature,
String @Nullable [] exceptions) {
if (name.equals("<clinit>") || (access & (Opcodes.ACC_ABSTRACT | Opcodes.ACC_NATIVE)) != 0) {
return null;
}
boolean isStatic = (access & Opcodes.ACC_STATIC) != 0;
boolean constructor = name.equals("<init>");
if (constructor && !isAbstract) {
// Instantiating also puts the class's type into circulation for virtual calls.
out.visitTypeInsn(Opcodes.NEW, owner);
out.visitInsn(Opcodes.DUP);
pushDefaults(descriptor);
out.visitMethodInsn(Opcodes.INVOKESPECIAL, owner, name, descriptor, false);
out.visitInsn(Opcodes.POP);
return null;
}
if (!isStatic) {
out.visitInsn(Opcodes.ACONST_NULL);
}
pushDefaults(descriptor);
out.visitMethodInsn(
isStatic ? Opcodes.INVOKESTATIC : Opcodes.INVOKESPECIAL, owner, name, descriptor, isInterface);
Type result = Type.getReturnType(descriptor);
if (result.getSize() == 2) {
out.visitInsn(Opcodes.POP2);
} else if (result.getSize() == 1) {
out.visitInsn(Opcodes.POP);
}
return null;
}
private void pushDefaults(String descriptor) {
for (Type arg : Type.getArgumentTypes(descriptor)) {
switch (arg.getSort()) {
case Type.BOOLEAN, Type.CHAR, Type.BYTE, Type.SHORT, Type.INT -> out.visitInsn(Opcodes.ICONST_0);
case Type.LONG -> out.visitInsn(Opcodes.LCONST_0);
case Type.FLOAT -> out.visitInsn(Opcodes.FCONST_0);
case Type.DOUBLE -> out.visitInsn(Opcodes.DCONST_0);
default -> out.visitInsn(Opcodes.ACONST_NULL);
}
}
}
}
private static void write(Path dir, String internalName, byte[] bytes) throws IOException {
Path file = dir.resolve(internalName + ".class");
Files.createDirectories(file.getParent());
Files.write(file, bytes);
}
}
@@ -0,0 +1,66 @@
package incari.tools.survey;
import java.util.Map;
import java.util.Set;
import org.teavm.model.AccessLevel;
import org.teavm.model.ClassHolder;
import org.teavm.model.ClassHolderTransformer;
import org.teavm.model.ClassHolderTransformerContext;
import org.teavm.model.ElementModifier;
import org.teavm.model.FieldHolder;
import org.teavm.model.MethodDescriptor;
import org.teavm.model.MethodHolder;
import org.teavm.model.ValueType;
import org.teavm.model.emit.ProgramEmitter;
/**
* Adds stub members to existing classes as TeaVM loads them (see {@link Stubs}).
*
* <p>TeaVM instantiates transformers by class name with a no-argument constructor, so the
* current round's members are handed over through a static field. The survey runs one
* compile at a time, so there's never more than one set in play.
*/
public final class StubTransformer implements ClassHolderTransformer {
static volatile Map<String, Set<Stubs.ExtraMember>> members = Map.of();
@Override
public void transformClass(ClassHolder cls, ClassHolderTransformerContext context) {
Set<Stubs.ExtraMember> extra = members.get(cls.getName());
if (extra == null) {
return;
}
for (Stubs.ExtraMember member : extra) {
if (member.method()) {
MethodDescriptor descriptor = MethodDescriptor.parse(member.nameAndDesc());
if (cls.getMethod(descriptor) != null) {
continue;
}
MethodHolder method = new MethodHolder(descriptor);
method.setLevel(AccessLevel.PUBLIC);
if (member.isStatic()) {
method.getModifiers().add(ElementModifier.STATIC);
}
ProgramEmitter pe = ProgramEmitter.create(method, context.getHierarchy());
if (descriptor.getResultType() == ValueType.VOID) {
pe.exit();
} else {
pe.defaultValue(descriptor.getResultType()).returnValue();
}
cls.addMethod(method);
} else {
String[] parts = member.nameAndDesc().split(":", 2);
if (cls.getField(parts[0]) != null) {
continue;
}
FieldHolder field = new FieldHolder(parts[0]);
field.setType(ValueType.parse(parts[1]));
field.setLevel(AccessLevel.PUBLIC);
if (member.isStatic()) {
field.getModifiers().add(ElementModifier.STATIC);
}
cls.addField(field);
}
}
}
}
@@ -0,0 +1,243 @@
package incari.tools.survey;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.teavm.model.FieldReference;
import org.teavm.model.MethodReference;
/**
* Stand-ins that let TeaVM's analysis continue past things that are missing.
*
* <p>TeaVM treats a call to a missing method as a throw, and its optimizer then drops
* everything after the call. One missing {@code Runtime.addShutdownHook} in {@code main}
* hides the entire game from the survey. So the survey runs in rounds: whatever TeaVM
* reports missing gets a stub that returns a default value, and the compile runs again,
* until nothing new turns up.
*
* <p>The stubs are only an analysis device. Everything stubbed is still reported as a
* finding; nothing here says the stub is the right fix.
*
* <p>Two kinds of stub:
* <ul>
* <li>classes TeaVM can't see (from libraries the rules leave out, or host-JDK classes its
* class library lacks) are generated as class files, with every member the game
* references, on a directory added to TeaVM's classpath;
* <li>members missing from classes that do exist (TeaVM's class library, the host JDK) are
* added by {@link StubTransformer} as TeaVM loads each class.
* </ul>
*/
final class Stubs {
/** A member to add to an existing class. {@code nameAndDesc}: {@code "foo(I)V"} or {@code "bar:I"}. */
record ExtraMember(String nameAndDesc, boolean method, boolean isStatic) {}
private final ReferenceIndex index;
private final Map<String, Set<ReferenceIndex.Member>> absentClasses = new LinkedHashMap<>();
private final Map<String, Set<ExtraMember>> extraMembers = new HashMap<>();
Stubs(ReferenceIndex index) {
this.index = index;
}
int absentClassCount() {
return absentClasses.size();
}
int extraMemberCount() {
return extraMembers.values().stream().mapToInt(Set::size).sum();
}
Map<String, Set<ExtraMember>> extraMembers() {
return extraMembers;
}
/** Stubs an absent class with every member the game references on it. Returns true if new. */
boolean addAbsentClass(String className) {
if (absentClasses.containsKey(className)) {
return false;
}
Set<ReferenceIndex.Member> members = new LinkedHashSet<>();
index.membersOf(className).forEach(members::add);
absentClasses.put(className, members);
return true;
}
/** Adds a method TeaVM reported missing. Returns true if it wasn't stubbed yet. */
boolean addMethod(MethodReference method, boolean ownerAbsent) {
String nameAndDesc = method.getName() + method.getDescriptor().signatureToString();
return addMember(method.getClassName(), nameAndDesc, true, ownerAbsent);
}
boolean addField(FieldReference field, boolean ownerAbsent) {
return addMember(field.getClassName(), field.getFieldName() + ":" + fieldDescriptor(field), false, ownerAbsent);
}
/** TeaVM's error doesn't carry the field's type: take it from a call site, else the JDK. */
private String fieldDescriptor(FieldReference field) {
String prefix = field.getFieldName() + ":";
for (ReferenceIndex.Member member : index.membersOf(field.getClassName())) {
if (!member.method() && member.nameAndDesc().startsWith(prefix)) {
return member.nameAndDesc().substring(prefix.length());
}
}
try {
Class<?> cls = Class.forName(field.getClassName(), false, ClassLoader.getPlatformClassLoader());
return Type.getDescriptor(cls.getDeclaredField(field.getFieldName()).getType());
} catch (ClassNotFoundException | NoSuchFieldException | LinkageError e) {
return "Ljava/lang/Object;";
}
}
private boolean addMember(String owner, String nameAndDesc, boolean method, boolean ownerAbsent) {
boolean isStatic = isStatic(owner, nameAndDesc, method);
if (ownerAbsent) {
boolean added = addAbsentClass(owner);
Set<ReferenceIndex.Member> members = absentClasses.get(owner);
if (members == null) {
throw new IllegalStateException("addAbsentClass didn't register " + owner);
}
return members.add(new ReferenceIndex.Member(owner, nameAndDesc, method, isStatic)) || added;
}
return extraMembers
.computeIfAbsent(owner, k -> new LinkedHashSet<>())
.add(new ExtraMember(nameAndDesc, method, isStatic));
}
/** Static-ness from the game's call sites, else from the host JDK's real class, else instance. */
private boolean isStatic(String owner, String nameAndDesc, boolean method) {
Boolean fromIndex = index.isStatic(owner, nameAndDesc);
if (fromIndex != null) {
return fromIndex;
}
try {
Class<?> cls = Class.forName(owner, false, ClassLoader.getPlatformClassLoader());
if (method) {
for (Method m : cls.getDeclaredMethods()) {
if (nameAndDesc.equals(m.getName() + Type.getMethodDescriptor(m))) {
return Modifier.isStatic(m.getModifiers());
}
}
} else {
String name = nameAndDesc.substring(0, nameAndDesc.indexOf(':'));
return Modifier.isStatic(cls.getDeclaredField(name).getModifiers());
}
} catch (ClassNotFoundException | NoSuchFieldException | LinkageError e) {
// Not a JDK class, or not a member of it: fall through to the default.
}
return false;
}
/** Writes every absent-class stub as a class file under {@code dir}. */
void writeClasses(Path dir) throws IOException {
for (Map.Entry<String, Set<ReferenceIndex.Member>> entry : absentClasses.entrySet()) {
byte[] bytes = generate(entry.getKey(), entry.getValue());
Path file = dir.resolve(entry.getKey().replace('.', '/') + ".class");
Files.createDirectories(file.getParent());
Files.write(file, bytes);
}
}
private byte[] generate(String className, Set<ReferenceIndex.Member> members) {
boolean isInterface = isInterface(className);
String internal = className.replace('.', '/');
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES) {
@Override
protected String getCommonSuperClass(String type1, String type2) {
return "java/lang/Object"; // stubs never merge types; avoid loading anything
}
};
int access = Opcodes.ACC_PUBLIC | (isInterface ? Opcodes.ACC_INTERFACE | Opcodes.ACC_ABSTRACT : 0);
cw.visit(Opcodes.V17, access, internal, null, "java/lang/Object", null);
boolean hasDefaultConstructor = false;
for (ReferenceIndex.Member member : members) {
if (!member.method()) {
String[] parts = member.nameAndDesc().split(":", 2);
int fieldAccess = Opcodes.ACC_PUBLIC | (member.isStatic() || isInterface ? Opcodes.ACC_STATIC : 0);
cw.visitField(fieldAccess, parts[0], parts[1], null, null).visitEnd();
continue;
}
int paren = member.nameAndDesc().indexOf('(');
String name = member.nameAndDesc().substring(0, paren);
String desc = member.nameAndDesc().substring(paren);
if (name.equals("<clinit>")) {
continue;
}
boolean constructor = name.equals("<init>");
if (constructor && isInterface) {
continue;
}
hasDefaultConstructor |= constructor && desc.equals("()V");
int methodAccess = Opcodes.ACC_PUBLIC | (member.isStatic() && !constructor ? Opcodes.ACC_STATIC : 0);
MethodVisitor mv = cw.visitMethod(methodAccess, name, desc, null, null);
mv.visitCode();
if (constructor) {
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
}
returnDefault(mv, Type.getReturnType(desc));
mv.visitMaxs(0, 0);
mv.visitEnd();
}
if (!isInterface && !hasDefaultConstructor) {
// Subclasses of a stubbed class call some super constructor; give them one to find.
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null);
mv.visitCode();
mv.visitVarInsn(Opcodes.ALOAD, 0);
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
cw.visitEnd();
return cw.toByteArray();
}
/** The real JDK class's shape when there is one; otherwise how the game uses the name. */
private boolean isInterface(String className) {
try {
return Class.forName(className, false, ClassLoader.getPlatformClassLoader())
.isInterface();
} catch (ClassNotFoundException | LinkageError e) {
return index.usedAsInterface(className);
}
}
private static void returnDefault(MethodVisitor mv, Type type) {
switch (type.getSort()) {
case Type.VOID -> mv.visitInsn(Opcodes.RETURN);
case Type.BOOLEAN, Type.CHAR, Type.BYTE, Type.SHORT, Type.INT -> {
mv.visitInsn(Opcodes.ICONST_0);
mv.visitInsn(Opcodes.IRETURN);
}
case Type.LONG -> {
mv.visitInsn(Opcodes.LCONST_0);
mv.visitInsn(Opcodes.LRETURN);
}
case Type.FLOAT -> {
mv.visitInsn(Opcodes.FCONST_0);
mv.visitInsn(Opcodes.FRETURN);
}
case Type.DOUBLE -> {
mv.visitInsn(Opcodes.DCONST_0);
mv.visitInsn(Opcodes.DRETURN);
}
default -> {
mv.visitInsn(Opcodes.ACONST_NULL);
mv.visitInsn(Opcodes.ARETURN);
}
}
}
}
@@ -0,0 +1,220 @@
package incari.tools.survey;
import incari.tools.build.CliException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.jspecify.annotations.Nullable;
/**
* The survey's policy file ({@code tools/survey/rules.txt}): which libraries are compiled
* with the game, and how each finding is triaged.
*
* <p>Three kinds of lines. Library lines decide the classpath:
* <pre>
* library org.lwjgl: replace Platform layer: graphics, windowing, input, audio
* </pre>
* {@code keep} compiles the library with the game. {@code replace} and {@code delete} leave it
* off the classpath, so every call into it shows up as a missing symbol at its call site.
*
* <p>No-root lines keep parts of the client jar that never run in the client (data
* generators, the dedicated server) out of the analysis roots (see {@link Roots}):
* <pre>
* no-root net.minecraft.data.** Data generators run at Mojang's build time
* </pre>
*
* <p>Triage lines sort findings. The first rule whose selectors all match wins:
* <pre>
* delete caller=net.minecraft.util.profiling.jfr.** JFR profiling, stripped
* shim symbol=java.nio.file.** Virtual filesystem over OPFS
* stub kind=reflection symbol=java.lang.Class#getGenericSuperclass ...
* </pre>
* Selectors: {@code symbol} (the missing or used thing, {@code owner#member}),
* {@code caller} (the class that needs work), {@code origin} ({@code minecraft} or a
* library name), {@code kind} ({@code reflection}, {@code native}, {@code host-jdk}, or a
* TeaVM problem such as {@code missing-method}). Globs: {@code *} matches within one name
* segment, {@code **} matches anything.
*/
public record SurveyRules(List<LibraryRule> libraries, List<NoRootRule> noRoots, List<TriageRule> triage) {
public enum Category {
STUB("Stub", "A no-op or trivial implementation is enough."),
SHIM("Shim", "Needs a real implementation, over a browser API or simpler Java."),
REWRITE("Rewrite", "The calling code has to change: a patch or a replacement class."),
DELETE("Delete", "The feature is stripped from the browser build.");
private final String title;
private final String meaning;
Category(String title, String meaning) {
this.title = title;
this.meaning = meaning;
}
public String title() {
return title;
}
public String meaning() {
return meaning;
}
}
public enum LibraryAction {
KEEP,
REPLACE,
DELETE
}
public record NoRootRule(Pattern classes, String reason) {}
/** Matches Maven coordinates by prefix, e.g. {@code "org.lwjgl:"} or {@code "io.netty:netty-buffer:"}. */
public record LibraryRule(String coordinatePrefix, LibraryAction action, String reason) {}
public record TriageRule(
Category category,
@Nullable Pattern symbol,
@Nullable Pattern caller,
@Nullable Pattern origin,
@Nullable String kind,
String reason,
int line) {
boolean matches(Finding finding, String kindName, @Nullable String origin) {
return (symbol == null
|| symbol.matcher(finding.symbol()).matches()
|| (finding.member() != null
&& symbol.matcher(finding.owner()).matches()
&& !symbol.pattern().contains("#")))
&& (caller == null
|| (finding.caller() != null
&& caller.matcher(finding.caller()).matches()))
&& (this.origin == null
|| (origin != null && this.origin.matcher(origin).matches()))
&& (kind == null || kind.equals(kindName));
}
}
public static SurveyRules load(Path file) throws IOException {
return parse(Files.readAllLines(file), file.getFileName().toString());
}
static SurveyRules parse(List<String> lines, String origin) {
List<LibraryRule> libraries = new ArrayList<>();
List<NoRootRule> noRoots = new ArrayList<>();
List<TriageRule> triage = new ArrayList<>();
for (int i = 0; i < lines.size(); i++) {
String raw = lines.get(i);
int hash = raw.indexOf(" #");
String line = (raw.startsWith("#") ? "" : hash >= 0 ? raw.substring(0, hash) : raw).strip();
if (line.isEmpty()) {
continue;
}
String where = origin + ":" + (i + 1);
String[] words = line.split("\\s+");
if (words[0].equals("library")) {
if (words.length < 4) {
throw new CliException(
where + ": expected: library <coordinate prefix> <keep|replace|delete> <reason>");
}
LibraryAction action = parseEnum(LibraryAction.class, words[2], where);
libraries.add(new LibraryRule(words[1], action, rest(words, 3)));
continue;
}
if (words[0].equals("no-root")) {
if (words.length < 3) {
throw new CliException(where + ": expected: no-root <class glob> <reason>");
}
noRoots.add(new NoRootRule(glob(words[1]), rest(words, 2)));
continue;
}
Category category = parseEnum(Category.class, words[0], where);
@Nullable Pattern symbol = null;
@Nullable Pattern caller = null;
@Nullable Pattern originPattern = null;
@Nullable String kind = null;
int w = 1;
for (; w < words.length && words[w].contains("="); w++) {
String[] kv = words[w].split("=", 2);
switch (kv[0]) {
case "symbol" -> symbol = glob(kv[1]);
case "caller" -> caller = glob(kv[1]);
case "origin" -> originPattern = glob(kv[1]);
case "kind" -> kind = kv[1];
default -> throw new CliException(where + ": unknown selector '" + kv[0] + "'");
}
}
if (w == 1) {
throw new CliException(where + ": a triage rule needs at least one selector");
}
if (w >= words.length) {
throw new CliException(where + ": a triage rule needs a reason after its selectors");
}
triage.add(new TriageRule(category, symbol, caller, originPattern, kind, rest(words, w), i + 1));
}
return new SurveyRules(List.copyOf(libraries), List.copyOf(noRoots), List.copyOf(triage));
}
/** The action for a library; libraries with no rule are an error, so none slips in unreviewed. */
public LibraryRule library(String coordinates) {
for (LibraryRule rule : libraries) {
if (coordinates.startsWith(rule.coordinatePrefix())) {
return rule;
}
}
throw new CliException("No library rule in rules.txt covers " + coordinates
+ ". Decide whether the browser build keeps, replaces or deletes it.");
}
/** Whether a client class becomes an analysis root (see {@link Roots}). */
public boolean isRooted(String className) {
for (NoRootRule rule : noRoots) {
if (rule.classes().matcher(className).matches()) {
return false;
}
}
return true;
}
/** The first matching rule, or {@code null} when nothing matches (reported as unclassified). */
public @Nullable TriageRule classify(Finding finding, String kindName, @Nullable String origin) {
for (TriageRule rule : triage) {
if (rule.matches(finding, kindName, origin)) {
return rule;
}
}
return null;
}
static Pattern glob(String glob) {
StringBuilder regex = new StringBuilder();
for (int i = 0; i < glob.length(); i++) {
char c = glob.charAt(i);
if (c == '*' && i + 1 < glob.length() && glob.charAt(i + 1) == '*') {
regex.append(".*");
i++;
} else if (c == '*') {
regex.append("[^.#]*");
} else {
regex.append(Pattern.quote(String.valueOf(c)));
}
}
return Pattern.compile(regex.toString());
}
private static String rest(String[] words, int from) {
return String.join(" ", java.util.Arrays.copyOfRange(words, from, words.length));
}
private static <E extends Enum<E>> E parseEnum(Class<E> type, String value, String where) {
try {
return Enum.valueOf(type, value.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
throw new CliException(where + ": unknown " + type.getSimpleName() + " '" + value + "'", e);
}
}
}
@@ -0,0 +1,348 @@
package incari.tools.survey;
import incari.tools.build.FileTrees;
import incari.tools.build.Log;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.teavm.dependency.DependencyInfo;
import org.teavm.diagnostics.DefaultProblemTextConsumer;
import org.teavm.diagnostics.Problem;
import org.teavm.model.CallLocation;
import org.teavm.model.ClassReader;
import org.teavm.model.ElementModifier;
import org.teavm.model.FieldReference;
import org.teavm.model.MethodReader;
import org.teavm.model.MethodReference;
import org.teavm.model.TextLocation;
import org.teavm.tooling.TeaVMTargetType;
import org.teavm.tooling.TeaVMTool;
import org.teavm.tooling.TeaVMToolException;
import org.teavm.tooling.TeaVMToolLog;
import org.teavm.vm.TeaVMOptimizationLevel;
/**
* Runs TeaVM's WebAssembly GC compile over the client and turns what it learns into findings.
*
* <p>Two sources from one compile: TeaVM's own errors (classes, methods and fields its class
* library doesn't have), and native (JNI) methods reachable in the game or its libraries,
* which TeaVM only rejects at code generation, a stage it never reaches while errors remain.
* It also returns the reachable game methods, so {@link BytecodeScanner} looks only at code
* that will actually be compiled.
*
* <p>Errors TeaVM reports inside JDK code it copied from the host (see {@link Origins}) keep
* that JDK class as their caller. Walking them up the call graph to game code doesn't work:
* virtual dispatch through {@code Object.hashCode()} and friends links almost everything to
* everything.
*
* <p>TeaVM doesn't follow calls into code it can't find, so this is the first layer: stubbing
* these items will uncover more behind them. Rerun the survey after each round.
*/
public final class TeaVmSurvey {
/**
* What the compile rounds found, and what TeaVM will compile.
*
* @param reachableAppMethods game and library methods TeaVM will compile, as
* {@code owner#name(descriptor)}; the bytecode scan only looks inside these
*/
public record Result(List<Finding> findings, Set<String> reachableClasses, Set<String> reachableAppMethods) {}
/** Rounds are cheap early and grow as more of the game becomes reachable; this is a safety net. */
private static final int MAX_ROUNDS = 40;
private TeaVmSurvey() {}
/**
* Compiles in rounds, stubbing whatever each round reports missing, until a round finds
* nothing new (see {@link Stubs}). Findings accumulate across rounds; reachability and
* natives come from the last, most complete round.
*/
public static Result run(String mainClass, Map<Path, String> appJars, Path rootsDir, Origins origins, Path workDir)
throws IOException, TeaVMToolException {
Stubs stubs = new Stubs(ReferenceIndex.build(appJars.keySet()));
Set<Finding> findings = new LinkedHashSet<>();
Path stubDir = workDir.resolve("stubs");
Analysis last = null;
for (int round = 1; ; round++) {
FileTrees.deleteRecursively(stubDir);
Files.createDirectories(stubDir);
stubs.writeClasses(stubDir);
StubTransformer.members = Map.copyOf(stubs.extraMembers());
List<Path> classpath = new ArrayList<>(appJars.keySet());
classpath.add(rootsDir);
classpath.add(stubDir);
long start = System.nanoTime();
last = compile(mainClass, classpath, origins, workDir.resolve("teavm-out"));
findings.addAll(last.findings);
int added = 0;
for (Problem problem : last.problems) {
added += stubFor(problem, stubs, origins) ? 1 : 0;
}
// TeaVM names a missing class once; stub every one that reachable code uses.
for (Finding f : BytecodeScanner.scan(appJars, last.reachableClasses, last.reachableAppMethods, origins)) {
if (f.kind() == Finding.Kind.MISSING_CLASS || f.kind() == Finding.Kind.HOST_JDK) {
added += stubs.addAbsentClass(f.owner()) ? 1 : 0;
}
}
Log.info(String.format(
Locale.ROOT,
"round %d: %,d reachable classes, %d problems, %d new stubs (%ds)",
round,
last.reachableClasses.size(),
last.problems.size(),
added,
(System.nanoTime() - start) / 1_000_000_000));
if (added == 0) {
break;
}
if (round == MAX_ROUNDS) {
Log.warn("Stopped after " + MAX_ROUNDS
+ " rounds with stubs still being added; the survey is incomplete.");
break;
}
}
findings.addAll(last.natives);
Log.info("Stubbed " + stubs.absentClassCount() + " absent classes and " + stubs.extraMemberCount()
+ " missing members to reach this point");
return new Result(
List.copyOf(findings), new TreeSet<>(last.reachableClasses), Set.copyOf(last.reachableAppMethods));
}
/** Registers a stub for what {@code problem} reports missing. True if it's new. */
private static boolean stubFor(Problem problem, Stubs stubs, Origins origins) {
Object[] params = problem.getParams();
String text = problem.getText();
if (text.contains("which is missing in the classpath")
&& params.length > 1
&& params[1] instanceof String cls) {
return stubs.addAbsentClass(cls);
}
if (params.length == 0) {
return false;
}
return switch (params[0]) {
case String cls when text.startsWith("Class {{c0}} was not found") -> stubs.addAbsentClass(cls);
case MethodReference method
when text.startsWith("Method {{m0}} was not found") ->
stubs.addMethod(method, stubbedAsClass(origins, method.getClassName()));
case FieldReference field
when text.startsWith("Field {{f0}} was not found") ->
stubs.addField(field, stubbedAsClass(origins, field.getClassName()));
default -> false;
};
}
/** Classes TeaVM can't see at all get generated stub class files, not transformer members. */
static boolean stubbedAsClass(Origins origins, String className) {
String origin = origins.of(className);
return Origins.ABSENT.equals(origin) || Origins.HOST_JDK.equals(origin);
}
/**
* Hides the host JDK's class files from TeaVM.
*
* <p>Left visible, TeaVM compiles any JDK class its class library lacks straight from the
* running JDK, and follows it into JDK internals (security, JMX, {@code jdk.internal}).
* That analysis is huge (tens of thousands of classes) and says nothing useful: the work
* item is the game's use of the missing class, not everything behind it. Hidden, each such
* class is reported missing and stubbed like any other. Class loading (TeaVM's own plugins)
* is untouched; only bytecode reads are filtered.
*/
private static Analysis compile(String mainClass, List<Path> classpath, Origins origins, Path outputDir)
throws IOException, TeaVMToolException {
URL[] urls = new URL[classpath.size()];
for (int i = 0; i < urls.length; i++) {
urls[i] = classpath.get(i).toUri().toURL();
}
// Parent = the survey's own loader, which carries TeaVM's class library (the
// browser-side java.* implementations the game will actually run against), minus the
// host JDK's class files (see HostJdkHidingLoader).
ClassLoader parent = new HostJdkHidingLoader(TeaVmSurvey.class.getClassLoader(), origins);
try (URLClassLoader loader = new URLClassLoader(urls, parent)) {
TeaVMTool tool = new TeaVMTool();
tool.setTargetType(TeaVMTargetType.WEBASSEMBLY_GC);
tool.setMainClass(mainClass);
tool.setClassLoader(loader);
tool.setTargetDirectory(outputDir.toFile());
tool.setOptimizationLevel(TeaVMOptimizationLevel.SIMPLE);
tool.setIncremental(false);
// Every client method is already a root (see Roots), so precise per-variable type
// flow adds little, and on the whole client it needs well over 20 GB. The fast mode
// resolves virtual calls by class hierarchy instead.
tool.setFastDependencyAnalysis(true);
tool.setLog(new QuietLog());
tool.getTransformers().add(StubTransformer.class.getName());
tool.generate();
DependencyInfo deps = tool.getDependencyInfo();
if (deps == null) {
throw new IllegalStateException("TeaVM produced no dependency information");
}
Analysis analysis = new Analysis(deps, origins);
for (Problem problem : tool.getProblemProvider().getProblems()) {
analysis.addProblem(problem);
}
analysis.scanReachableMethods();
return analysis;
}
}
private static final class Analysis {
private final DependencyInfo deps;
private final Origins origins;
private final List<Problem> problems = new ArrayList<>();
private final Set<Finding> findings = new LinkedHashSet<>();
private final Set<Finding> natives = new LinkedHashSet<>();
private final Set<String> reachableAppMethods = new HashSet<>();
private final Set<String> reachableClasses;
Analysis(DependencyInfo deps, Origins origins) {
this.deps = deps;
this.origins = origins;
this.reachableClasses = new HashSet<>(deps.getReachableClasses());
}
void addProblem(Problem problem) {
problems.add(problem);
findings.add(toFinding(problem));
}
/** Finds reachable natives, and records which game methods are reachable at all. */
void scanReachableMethods() {
for (MethodReference method : deps.getReachableMethods()) {
String owner = method.getClassName();
if (!origins.isApp(owner)) {
continue;
}
reachableAppMethods.add(
owner + "#" + method.getName() + method.getDescriptor().signatureToString());
if (isNative(method)) {
natives.add(new Finding(
Finding.Kind.NATIVE,
owner + "#" + method.getName(),
method.toString(),
owner,
method.getDescriptor().toString(),
-1,
null));
}
}
}
private boolean isNative(MethodReference method) {
ClassReader cls = deps.getClassSource().get(method.getClassName());
MethodReader reader = cls != null ? cls.getMethod(method.getDescriptor()) : null;
return reader != null && reader.hasModifier(ElementModifier.NATIVE);
}
}
static Finding toFinding(Problem problem) {
String text = problem.getText();
Object[] params = problem.getParams();
Object first = params.length > 0 ? params[0] : null;
Finding.Kind kind;
if (text.startsWith("Class {{c0}} was not found")) {
kind = Finding.Kind.MISSING_CLASS;
} else if (text.startsWith("Method {{m0}} was not found")) {
kind = Finding.Kind.MISSING_METHOD;
} else if (text.startsWith("Field {{f0}} was not found")) {
kind = Finding.Kind.MISSING_FIELD;
} else if (text.startsWith("Class {{c0}} is not supported")) {
kind = Finding.Kind.UNSUPPORTED_CLASS;
} else if (text.startsWith("Method {{m0}} is not supported")) {
kind = Finding.Kind.UNSUPPORTED_METHOD;
} else if (text.contains("which is missing in the classpath")) {
kind = Finding.Kind.MISSING_SUPERTYPE;
// The interesting symbol is the missing supertype, not the class extending it.
first = params.length > 1 ? params[1] : first;
} else if (text.startsWith("Bootstrap method {{m0}} was not found")) {
kind = Finding.Kind.MISSING_BOOTSTRAP;
} else {
kind = Finding.Kind.OTHER;
}
String symbol;
String detail;
switch (first) {
case MethodReference method -> {
symbol = method.getClassName() + "#" + method.getName();
detail = method.toString();
}
case FieldReference field -> {
symbol = field.getClassName() + "#" + field.getFieldName();
detail = field.toString();
}
case String className -> {
symbol = className;
detail = className;
}
case null, default -> {
symbol = kind == Finding.Kind.OTHER ? render(problem) : String.valueOf(first);
detail = render(problem);
}
}
CallLocation location = problem.getLocation();
MethodReference callerMethod = location != null ? location.getMethod() : null;
TextLocation source = location != null ? location.getSourceLocation() : null;
return new Finding(
kind,
symbol,
detail,
callerMethod != null ? callerMethod.getClassName() : null,
callerMethod != null ? callerMethod.getDescriptor().toString() : null,
source != null && !source.isEmpty() ? source.getLine() : -1,
null);
}
private static String render(Problem problem) {
DefaultProblemTextConsumer consumer = new DefaultProblemTextConsumer();
problem.render(consumer);
return consumer.getText();
}
/** TeaVM's progress chatter is noise here; its problems are collected separately. */
private static final class QuietLog implements TeaVMToolLog {
@Override
public void info(String text) {}
@Override
public void debug(String text) {}
@Override
public void warning(String text) {}
@Override
public void error(String text) {}
@Override
public void info(String text, Throwable e) {}
@Override
public void debug(String text, Throwable e) {}
@Override
public void warning(String text, Throwable e) {
Log.warn("TeaVM: " + text + ": " + e);
}
@Override
public void error(String text, Throwable e) {
Log.warn("TeaVM error: " + text + ": " + e);
}
}
}
@@ -0,0 +1,95 @@
package incari.tools.survey;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
class RootsTest {
@TempDir
Path dir;
@Test
void everyMethodOfEveryRootedClassIsCalledAndExcludedClassesAreNot() throws Exception {
Path jar = dir.resolve("client.jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
add(out, "game/Screen", Opcodes.ACC_PUBLIC, cw -> {
method(cw, Opcodes.ACC_PUBLIC, "<init>", "()V");
method(cw, Opcodes.ACC_PUBLIC, "render", "(IF)V");
method(cw, Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC, "helper", "(J)Ljava/lang/String;");
cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_ABSTRACT, "skipped", "()V", null, null)
.visitEnd();
});
add(
out,
"game/data/Generator",
Opcodes.ACC_PUBLIC,
cw -> method(cw, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "run", "()V"));
}
int rooted = Roots.generate(jar, name -> !name.startsWith("game.data."), "game.Main", dir.resolve("roots"));
assertThat(rooted).isEqualTo(1);
List<String> calls = calls(dir.resolve("roots/incari/survey/roots/Roots0.class"));
assertThat(calls)
.contains("game/Screen.<init>", "game/Screen.render", "game/Screen.helper")
.doesNotContain("game/Screen.skipped", "game/data/Generator.run");
assertThat(calls(dir.resolve("roots/incari/survey/roots/Entry.class")))
.containsExactly("game/Main.main", "incari/survey/roots/Roots0.run");
}
private static List<String> calls(Path classFile) throws IOException {
List<String> calls = new ArrayList<>();
new ClassReader(Files.readAllBytes(classFile))
.accept(
new ClassVisitor(Opcodes.ASM9) {
@Override
public MethodVisitor visitMethod(
int access, String name, String desc, String sig, String[] exceptions) {
return new MethodVisitor(Opcodes.ASM9) {
@Override
public void visitMethodInsn(
int opcode, String owner, String method, String d, boolean itf) {
if (!owner.startsWith("incari/survey/roots/Roots") || method.equals("run")) {
calls.add(owner + "." + method);
}
}
};
}
},
0);
return calls;
}
private static void add(JarOutputStream out, String name, int access, java.util.function.Consumer<ClassWriter> body)
throws IOException {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cw.visit(Opcodes.V17, access, name, null, "java/lang/Object", null);
body.accept(cw);
cw.visitEnd();
out.putNextEntry(new JarEntry(name + ".class"));
out.write(cw.toByteArray());
out.closeEntry();
}
private static void method(ClassWriter cw, int access, String name, String desc) {
MethodVisitor mv = cw.visitMethod(access, name, desc, null, null);
mv.visitCode();
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
}
}
@@ -0,0 +1,111 @@
package incari.tools.survey;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.teavm.model.MethodDescriptor;
import org.teavm.model.MethodReference;
/** Stub generation for absent classes, checked by loading the generated classes on the real JVM. */
class StubsTest {
@TempDir
Path dir;
@Test
void absentClassStubsCarryEveryReferencedMemberAndLoad() throws Exception {
// A "game" class that uses an absent library class three ways.
Path jar = jarWith("game/User", cw -> {
MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "use", "()V", null, null);
mv.visitCode();
mv.visitMethodInsn(Opcodes.INVOKESTATIC, "lib/Gl", "glDraw", "(II)I", false);
mv.visitInsn(Opcodes.POP);
mv.visitFieldInsn(Opcodes.GETSTATIC, "lib/Gl", "GL_TRIANGLES", "I");
mv.visitInsn(Opcodes.POP);
mv.visitTypeInsn(Opcodes.NEW, "lib/Window");
mv.visitInsn(Opcodes.DUP);
mv.visitLdcInsn("title");
mv.visitMethodInsn(Opcodes.INVOKESPECIAL, "lib/Window", "<init>", "(Ljava/lang/String;)V", false);
mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "lib/Window", "title", "()Ljava/lang/String;", false);
mv.visitInsn(Opcodes.POP);
mv.visitInsn(Opcodes.RETURN);
mv.visitMaxs(0, 0);
mv.visitEnd();
});
Stubs stubs = new Stubs(ReferenceIndex.build(java.util.List.of(jar)));
assertThat(stubs.addAbsentClass("lib.Gl")).isTrue();
assertThat(stubs.addAbsentClass("lib.Gl")).isFalse();
stubs.addAbsentClass("lib.Window");
// A member TeaVM reports later, which the game's own bytecode never showed.
stubs.addMethod(new MethodReference("lib.Window", MethodDescriptor.parse("close()V")), true);
stubs.writeClasses(dir);
try (URLClassLoader loader = new URLClassLoader(new URL[] {dir.toUri().toURL()}, null)) {
Class<?> gl = loader.loadClass("lib.Gl");
Method draw = gl.getMethod("glDraw", int.class, int.class);
assertThat(Modifier.isStatic(draw.getModifiers())).isTrue();
assertThat(draw.invoke(null, 1, 2)).isEqualTo(0);
assertThat(Modifier.isStatic(gl.getField("GL_TRIANGLES").getModifiers()))
.isTrue();
Class<?> window = loader.loadClass("lib.Window");
Object instance = window.getConstructor(String.class).newInstance("x");
assertThat(window.getMethod("title").invoke(instance)).isNull();
window.getMethod("close").invoke(instance);
// Always a no-arg constructor, for subclasses whose super call the index missed.
assertThat(window.getConstructor()).isNotNull();
}
}
@Test
void missingMembersOfExistingClassesGoToTheTransformerWithJdkStaticness() {
Stubs stubs = new Stubs(emptyIndex());
stubs.addMethod(new MethodReference("java.lang.System", MethodDescriptor.parse("exit(I)V")), false);
stubs.addMethod(
new MethodReference(
"java.lang.Runtime", MethodDescriptor.parse("addShutdownHook(Ljava/lang/Thread;)V")),
false);
assertThat(stubs.extraMembers().get("java.lang.System"))
.containsExactly(new Stubs.ExtraMember("exit(I)V", true, true));
assertThat(stubs.extraMembers().get("java.lang.Runtime"))
.containsExactly(new Stubs.ExtraMember("addShutdownHook(Ljava/lang/Thread;)V", true, false));
assertThat(stubs.absentClassCount()).isZero();
}
private ReferenceIndex emptyIndex() {
try {
return ReferenceIndex.build(java.util.List.of());
} catch (IOException e) {
throw new AssertionError(e);
}
}
private Path jarWith(String internalName, java.util.function.Consumer<ClassWriter> body) throws IOException {
ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
cw.visit(Opcodes.V17, Opcodes.ACC_PUBLIC, internalName, null, "java/lang/Object", null);
body.accept(cw);
cw.visitEnd();
Path jar = dir.resolve("game.jar");
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry(internalName + ".class"));
out.write(cw.toByteArray());
out.closeEntry();
}
return jar;
}
}
@@ -0,0 +1,108 @@
package incari.tools.survey;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import incari.tools.build.CliException;
import java.nio.file.Path;
import java.util.List;
import org.junit.jupiter.api.Test;
class SurveyRulesTest {
private static Finding finding(Finding.Kind kind, String symbol, String caller) {
return new Finding(kind, symbol, symbol, caller, "m()V", 1, null);
}
@Test
void globsDistinguishOneSegmentFromAnything() {
assertThat(SurveyRules.glob("java.nio.file.*")
.matcher("java.nio.file.Files")
.matches())
.isTrue();
assertThat(SurveyRules.glob("java.nio.file.*")
.matcher("java.nio.file.spi.FileSystemProvider")
.matches())
.isFalse();
assertThat(SurveyRules.glob("java.nio.**")
.matcher("java.nio.file.spi.FileSystemProvider#x")
.matches())
.isTrue();
assertThat(SurveyRules.glob("java.lang.Thread#set*")
.matcher("java.lang.Thread#setPriority")
.matches())
.isTrue();
assertThat(SurveyRules.glob("a$b").matcher("a$b").matches()).isTrue();
}
@Test
void firstMatchingRuleWinsAndAllSelectorsMustMatch() {
SurveyRules rules = SurveyRules.parse(
List.of(
"delete caller=net.minecraft.util.profiling.** Profiler",
"stub kind=missing-method symbol=java.lang.Thread#setPriority Thread priorities",
"shim symbol=java.lang.Thread Threads as coroutines"),
"rules.txt");
Finding priorityInProfiler = finding(
Finding.Kind.MISSING_METHOD, "java.lang.Thread#setPriority", "net.minecraft.util.profiling.Profiler");
Finding priority = finding(Finding.Kind.MISSING_METHOD, "java.lang.Thread#setPriority", "net.minecraft.Util");
Finding reflectivePriority =
finding(Finding.Kind.REFLECTION, "java.lang.Thread#setPriority", "net.minecraft.Util");
assertThat(rules.classify(priorityInProfiler, "missing-method", "minecraft")
.reason())
.isEqualTo("Profiler");
assertThat(rules.classify(priority, "missing-method", "minecraft").reason())
.isEqualTo("Thread priorities");
// A pattern without '#' matches every member of that class.
assertThat(rules.classify(reflectivePriority, "reflection", "minecraft").reason())
.isEqualTo("Threads as coroutines");
assertThat(rules.classify(finding(Finding.Kind.MISSING_METHOD, "java.util.X#y", "a.B"), "missing-method", "x"))
.isNull();
}
@Test
void originSelectorMatchesTheCallersJar() {
SurveyRules rules = SurveyRules.parse(List.of("shim origin=guava kind=host-jdk Guava's JDK internals"), "r");
Finding f = finding(Finding.Kind.HOST_JDK, "sun.misc.Unsafe#getUnsafe", "com.google.common.X");
assertThat(rules.classify(f, "host-jdk", "guava")).isNotNull();
assertThat(rules.classify(f, "host-jdk", "minecraft")).isNull();
}
@Test
void libraryRulesMatchByPrefixAndEveryLibraryNeedsOne() {
SurveyRules rules = SurveyRules.parse(
List.of(
"library io.netty:netty-buffer: keep Pure Java",
"library io.netty: replace WebSocket transport"),
"r");
assertThat(rules.library("io.netty:netty-buffer:4.2.16.Final").action())
.isEqualTo(SurveyRules.LibraryAction.KEEP);
assertThat(rules.library("io.netty:netty-handler:4.2.16.Final").action())
.isEqualTo(SurveyRules.LibraryAction.REPLACE);
assertThatThrownBy(() -> rules.library("org.example:new:1.0"))
.isInstanceOf(CliException.class)
.hasMessageContaining("org.example:new:1.0");
}
@Test
void malformedLinesNameTheirLocation() {
assertThatThrownBy(() -> SurveyRules.parse(List.of("fix symbol=a.B reason"), "r"))
.hasMessageContaining("r:1");
assertThatThrownBy(() -> SurveyRules.parse(List.of("stub symbol=a.B"), "r"))
.hasMessageContaining("reason");
assertThatThrownBy(() -> SurveyRules.parse(List.of("stub nope=a.B x"), "r"))
.hasMessageContaining("unknown selector");
assertThatThrownBy(() -> SurveyRules.parse(List.of("library a:"), "r"))
.hasMessageContaining("expected: library");
}
@Test
void theCheckedInRulesFileParses() throws Exception {
SurveyRules rules =
SurveyRules.load(Path.of(System.getProperty("user.dir")).resolve("rules.txt"));
assertThat(rules.libraries()).isNotEmpty();
assertThat(rules.triage()).isNotEmpty();
}
}