Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.github.minecraft_ta.totalDebugCompanion.bytecode.RuntimeSnapshotBytecodeSource.Source;
import com.github.minecraft_ta.totaldebug.storage.AtomicFiles;
import com.github.minecraft_ta.totaldebug.storage.JsonFiles;
import com.github.minecraft_ta.totaldebug.storage.RuntimeInventory.ModuleKind;
import com.github.minecraft_ta.totaldebug.storage.RuntimeInventory.RuntimeModule;
import com.github.tth05.jindex.ClassIndex;
import com.google.gson.JsonArray;
Expand Down Expand Up @@ -119,6 +120,9 @@ static Manifest read(Path file) throws IOException {
if (JsonFiles.integer(json, "format") != FORMAT) {
throw new IOException("Unsupported runtime index format: " + file);
}
if (!javaVersion().equals(JsonFiles.string(json, "javaVersion"))) {
throw new IOException("The index holds the classes of another Java runtime: " + JsonFiles.string(json, "javaVersion"));
}
List<Source> sources = new ArrayList<>();
var ids = new HashSet<Integer>();
for (var value : JsonFiles.array(json, "sources")) {
Expand Down Expand Up @@ -154,12 +158,26 @@ static void requireSourcePaths(Manifest manifest) throws IOException {
if (!Files.isRegularFile(path) && !Files.isDirectory(path)) {
throw new IOException("Prepared runtime source is unavailable: " + path);
}
if (source.module().kind() == ModuleKind.JAVA_RUNTIME && !path.equals(javaHome())) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Normalize java.home before comparing cache paths

When Companion is launched with a valid but non-normalized java.home such as /opt/jdk/. or a relative path, every generated Java-runtime Source stores an absolute normalized path, but this comparison uses the raw system-property path. The paths therefore compare unequal; cached indexes are rejected, and rebuilding also fails when IndexCache.write validates the newly written manifest. Return an absolute normalized path from javaHome() before comparing it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 2751799: javaHome() returns the absolute, normalized path, as Source stores it. aJavaHomeWrittenWithRedundantPartsIsTheSameRuntime sets java.home to <home>/.; it fails without the fix.

throw new IOException("The index holds the classes of another Java runtime: " + path);
Comment on lines +161 to +162

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate JDK contents, not only its install path

When Companion uses a different JVM from the game—explicitly supported for IDE/offline launches—and that JVM is upgraded or replaced in place, the saved game inventory ID remains unchanged and this path equality still accepts the old cache. The loaded index then describes the previous JDK while RuntimeSnapshotBytecodeSource.readJdk reads classes from the current JRT filesystem, causing stale or missing search results and potentially mismatched class metadata. Persist and validate a Companion-JDK version/build fingerprint (for example, the runtime version plus the JDK release metadata), not just java.home.

AGENTS.md reference: AGENTS.md:L7-L7

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 747455e: the manifest records java.runtime.version (version and build) beside the path, and an index written on another build is rebuilt. anIndexWrittenOnAnotherBuildOfTheJavaRuntimeIsNotUsed changes the version under the same path.

}
}
}

/** The Java runtime whose classes an index holds: the one Companion runs on. */
static Path javaHome() {
return Path.of(System.getProperty("java.home")).toAbsolutePath().normalize();
}

/** The version and build of that runtime, which an update in place changes. */
static String javaVersion() {
return System.getProperty("java.runtime.version");
}

private static JsonObject toJson(Manifest manifest) {
JsonObject json = new JsonObject();
json.addProperty("format", FORMAT);
json.addProperty("javaVersion", javaVersion());
json.addProperty("sourceKind", manifest.identity().kind().name());
json.addProperty("sourceIdentity", manifest.identity().value());
if (!manifest.detail().isBlank()) json.addProperty("detail", manifest.detail());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,7 @@ private void buildOrLoad(Work work) {
}
checkpoint(work);
update(work, new Status(Phase.BUILDING, "Building class index", null));
return buildSnapshot(work, prepareInputs(inventory), IndexIdentity.runtime(inventory.id()), indexFile, inventory.javaHome());
return buildSnapshot(work, prepareInputs(inventory), IndexIdentity.runtime(inventory.id()), indexFile);
});
publishReady(work, ready);
} catch (CancellationException ignored) {
Expand Down Expand Up @@ -424,7 +424,7 @@ private void buildOrLoadLocal(Work work) throws IOException {
update(work, new Status(Phase.BUILDING, work.detail + "Building local mod index", null));
var prepared = LocalModSources.prepare(scan, () -> checkpoint(work));
work.sourceDetail = prepared.detail();
return buildSnapshot(work, prepared.inputs(), identity, indexFile, System.getProperty("java.home"));
return buildSnapshot(work, prepared.inputs(), identity, indexFile);
});
publishReady(work, ready);
}
Expand All @@ -433,8 +433,7 @@ private ReadySnapshot buildSnapshot(
Work work,
List<PreparedInput> prepared,
IndexIdentity identity,
Path indexFile,
String javaHome
Path indexFile
) throws IOException {
AtomicFiles.cleanupAbandonedStaging(indexFile.getParent());
checkpoint(work);
Expand All @@ -459,9 +458,10 @@ private ReadySnapshot buildSnapshot(
try (var phase = RuntimePhase.start("index.jdk-inputs")) {
addJdkClasses(jdkSourceId, indexSources);
}
// The JDK read is Companion's own, which the mod starts on the game's Java; a cache records it (IndexCache).
publishedSources.add(new RuntimeSnapshotBytecodeSource.Source(
jdkSourceId,
Path.of(javaHome),
IndexCache.javaHome(),
"jrt:/",
new RuntimeInventory.RuntimeModule(
"java-runtime",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ class CompanionRenderingDefaultsTest {
var builder = new ProcessBuilder(command).redirectErrorStream(true);
for (String name : List.of("JAVA_TOOL_OPTIONS", "JDK_JAVA_OPTIONS", "_JAVA_OPTIONS")) builder.environment().remove(name);
Process process = builder.start();
boolean finished = process.waitFor(15, TimeUnit.SECONDS);
// A JVM on the whole test class path starts slowly on a loaded runner; the wait ends when it exits.
boolean finished = process.waitFor(60, TimeUnit.SECONDS);
if (!finished) process.destroyForcibly().waitFor();
String output = new String(process.getInputStream().readAllBytes());
assertTrue(finished, output);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ void aNavigationShowingAHiddenLivePageReadsItOnce() throws Exception {
UiTestScope.showPages(panel);
panel.session().refresh();
});
Thread.sleep(500);
// A read asks for the snippets twice: whether the side can run, then to run.
UiTestScope.await(() -> reads.get() >= asked + 2);
assertEquals(asked + 2, reads.get(), "the navigation's read answers the read the live interval asked for");
} finally {
UiTestScope.onEdt(panel::dispose);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,48 @@ void roundTripsNativeIndexAndSourceIdentityAsOneFile() throws Exception {
assertThrows(IOException.class, () -> IndexCache.requireSources(manifest));
}
}

@Test
void anIndexOfAnotherJavaRuntimeIsNotUsed() throws Exception {
var java = new RuntimeInventory.RuntimeModule("java-runtime", "Java Runtime", RuntimeInventory.ModuleKind.JAVA_RUNTIME);
IndexCache.requireSourcePaths(new IndexCache.Manifest("test",
List.of(new RuntimeSnapshotBytecodeSource.Source(0, IndexCache.javaHome(), "jrt:/", java))));
var other = new IndexCache.Manifest("test",
List.of(new RuntimeSnapshotBytecodeSource.Source(0, this.home, "jrt:/", java)));
assertThrows(IOException.class, () -> IndexCache.requireSourcePaths(other));
}

@Test
void anIndexWrittenOnAnotherBuildOfTheJavaRuntimeIsNotUsed() throws Exception {
Path file = this.home.resolve("index.jindex");
var java = new RuntimeInventory.RuntimeModule("java-runtime", "Java Runtime", RuntimeInventory.ModuleKind.JAVA_RUNTIME);
var manifest = new IndexCache.Manifest("test",
List.of(new RuntimeSnapshotBytecodeSource.Source(0, IndexCache.javaHome(), "jrt:/", java)));
try (var input = IndexCacheTest.class.getResourceAsStream("IndexCacheTest.class");
ClassIndex index = ClassIndex.fromBytes(List.of(input.readAllBytes()));
ClassIndex ignored = IndexCache.write(file, index, manifest)) {
assertEquals(manifest, IndexCache.read(file));
}
String version = System.getProperty("java.runtime.version");
// The same path after an update in place.
System.setProperty("java.runtime.version", version + "-updated");
try {
assertThrows(IOException.class, () -> IndexCache.read(file));
} finally {
System.setProperty("java.runtime.version", version);
}
}

@Test
void aJavaHomeWrittenWithRedundantPartsIsTheSameRuntime() throws Exception {
var java = new RuntimeInventory.RuntimeModule("java-runtime", "Java Runtime", RuntimeInventory.ModuleKind.JAVA_RUNTIME);
String property = System.getProperty("java.home");
System.setProperty("java.home", Path.of(property, ".").toString());
try {
IndexCache.requireSourcePaths(new IndexCache.Manifest("test",
List.of(new RuntimeSnapshotBytecodeSource.Source(0, IndexCache.javaHome(), "jrt:/", java))));
} finally {
System.setProperty("java.home", property);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import com.github.minecraft_ta.totalDebugCompanion.navigation.WorldTab;
import com.github.minecraft_ta.totalDebugCompanion.project.ProjectScope;
import com.github.minecraft_ta.totalDebugCompanion.runtime.RuntimeIndexService;
import com.github.minecraft_ta.totalDebugCompanion.runtime.RuntimeTestSources;
import com.github.minecraft_ta.totalDebugCompanion.session.CompanionLaunchConfiguration;
import com.github.minecraft_ta.totalDebugCompanion.session.CompanionProfile;
import com.github.minecraft_ta.totalDebugCompanion.storage.ChangeRecord;
Expand Down Expand Up @@ -423,8 +424,7 @@ void theFirstAndTheLastChangeAddAndRemoveTheModpackRootAlone() throws Exception
private static void assertReveals(FileTreeView tree, Callable<CompletableFuture<Boolean>> reveal, String name) throws Exception {
CompletableFuture<Boolean> revealed = UiTestScope.onEdt(reveal);
assertTrue(revealed.get(10, TimeUnit.SECONDS), name + " is revealed");
settle();
assertEquals(name, UiTestScope.onEdt(() -> selectedName(tree)), name + " is selected");
UiTestScope.await(() -> name.equals(selectedName(tree)));
}

/** The catalog of a pack with one mod, {@code testmod}, ready. */
Expand All @@ -434,12 +434,21 @@ private void withCatalog(ProjectScope scope) throws Exception {
settle();
}

/** A mod archive in the game's {@code mods} folder, which the Runtime root lists before a game runs. */
/**
* A mod archive in the game's {@code mods} folder, which the Runtime root lists before a game runs, with its index
* already cached: the project loads it rather than indexing the JDK, which none of these tests is about.
*/
private static void modJar(Path game) throws Exception {
try (var zip = new ZipOutputStream(Files.newOutputStream(Files.createDirectories(game.resolve("mods")).resolve("sample.jar")))) {
zip.putNextEntry(new ZipEntry("pack.mcmeta"));
zip.write("{}".getBytes(StandardCharsets.UTF_8));
String fixture = Before.class.getName().replace('.', '/') + ".class";
zip.putNextEntry(new ZipEntry(fixture));
try (var bytes = ProjectTreeTest.class.getClassLoader().getResourceAsStream(fixture)) {
bytes.transferTo(zip);
}
}
RuntimeTestSources.writeLocalCache(game);
}

/** A script in a folder of the instance's Scripts. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,9 @@ void firstConstructionDoesNotDeadlockAwtClassInitialization() throws Exception {
"-cp", System.getProperty("java.class.path"), Probe.class.getName())
.redirectErrorStream(true).redirectOutput(output.toFile()).start();
try {
assertTrue(process.waitFor(5, TimeUnit.SECONDS),
() -> "Popup initialization did not finish within five seconds: " + output);
// A deadlock never ends; a minute leaves a slow start on a loaded runner its time.
assertTrue(process.waitFor(60, TimeUnit.SECONDS),
() -> "Popup initialization did not finish within a minute: " + output);
assertEquals(0, process.exitValue(), Files.readString(output));
} finally {
if (process.isAlive()) process.destroyForcibly().waitFor();
Expand Down