From 342cb6c5004c6e56bced5f4446583f24fcdf9fb3 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Sun, 25 Oct 2026 03:32:23 +0000 Subject: [PATCH] Fix Java compiler/runtime selection during preparation Pair PATH tools from a compatible JDK and always forward its home to external preparers so Java 25 exporters run with a compatible runtime. Co-Authored-By: OpenCode gpt-6.1-sol --- crates/horizon-prepare/src/java.rs | 102 +++++++++----- .../horizon-prepare/tests/java_selection.rs | 133 ++++++++++++++++++ .../tests/support/java_probe.rs | 21 +++ launcher/src/backend.rs | 35 +++-- launcher/src/backend/java_tests.rs | 85 +++++++++++ 5 files changed, 323 insertions(+), 53 deletions(-) create mode 100644 crates/horizon-prepare/tests/java_selection.rs create mode 100644 crates/horizon-prepare/tests/support/java_probe.rs create mode 100644 launcher/src/backend/java_tests.rs diff --git a/crates/horizon-prepare/src/java.rs b/crates/horizon-prepare/src/java.rs index b4023b7d1..c5115be5e 100644 --- a/crates/horizon-prepare/src/java.rs +++ b/crates/horizon-prepare/src/java.rs @@ -36,41 +36,64 @@ fn executable(dir: &Path, name: &str) -> PathBuf { }) } -fn on_path(name: &str) -> Option { - std::env::split_paths(&std::env::var_os("PATH")?) - .map(|dir| executable(&dir, name)) - .find(|p| p.is_file()) +/// Resolve compiler symlinks before picking its sibling runtime. The first `java` on the +/// PATH may be an older, runtime-only install; it must not be paired with a newer `javac`. +fn path_jdks(path: &OsStr) -> Vec { + std::env::split_paths(path) + .map(|dir| executable(&dir, "javac")) + .filter(|javac| javac.is_file()) + .map(|javac| fs::canonicalize(&javac).unwrap_or(javac)) + .filter_map(|javac| { + let bin = javac.parent()?; + // macOS's system tools are dispatchers, not a JDK home: JAVA_HOME=/usr + // makes them call themselves. /usr/libexec/java_home finds the actual JDK. + if bin.file_name()? != "bin" + || (cfg!(target_os = "macos") && bin == Path::new("/usr/bin")) + { + return None; + } + Some(bin.parent()?.to_path_buf()) + }) + .collect() } -/// The major version `javac -version` reports ("javac 25.0.1" → 25; "javac 1.8.0" → 8). -fn javac_major(javac: &Path) -> Result { - let output = command(javac) +/// The major version `javac -version` or `java -version` reports, including Java 8's `1.8`. +fn tool_major(program: &Path, name: &str) -> Result { + let output = command(program) .arg("-version") .stdin(Stdio::null()) .output() - .map_err(|e| format!("{}: {e}", javac.display()))?; + .map_err(|e| format!("{}: {e}", program.display()))?; let text = String::from_utf8_lossy(&output.stdout).into_owned() + &String::from_utf8_lossy(&output.stderr); + // macOS ships /usr/bin/java and /usr/bin/javac as placeholders. + if text.contains("Unable to locate a Java Runtime") { + return Err(format!( + "{} is macOS's placeholder (no Java installed)", + program.display() + )); + } + if !output.status.success() { + return Err(format!( + "{} -version failed ({}): {}", + program.display(), + output.status, + text.trim() + )); + } + let marker = if name == "javac" { "javac" } else { "version" }; let version = text .split_whitespace() - .skip_while(|w| *w != "javac") + .skip_while(|w| *w != marker) .nth(1) .ok_or_else(|| { - // macOS ships /usr/bin/javac as a placeholder that only says no Java is installed. - if text.contains("Unable to locate a Java Runtime") { - format!( - "{} is macOS's placeholder (no Java installed)", - javac.display() - ) - } else { - format!( - "{} -version printed no version: {}", - javac.display(), - text.trim() - ) - } + format!( + "{} -version printed no version: {}", + program.display(), + text.trim() + ) })?; - let mut parts = version.split(['.', '-', '+', '_']); + let mut parts = version.trim_matches('"').split(['.', '-', '+', '_']); let first: u32 = parts.next().and_then(|p| p.parse().ok()).unwrap_or(0); Ok(if first == 1 { parts.next().and_then(|p| p.parse().ok()).unwrap_or(0) @@ -175,11 +198,10 @@ pub fn minecraft_runtimes(runtime: &Path) -> Vec { homes } -/// Finds a JDK with `javac` of at least `major`, the version research-lock.json pins: -/// `JAVA_HOME` when it holds one, else `javac` and `java` on the PATH (as the Python preparer -/// ran them), else, on macOS, the JDK `/usr/libexec/java_home -v ` reports, else the JDK -/// homes in `more` (the launcher's pick, Minecraft's own runtimes), else a JDK in the folders -/// installers put them in (`jdk_parents`). +/// Finds a JDK whose compiler and runtime are both at least `major`, the version +/// research-lock.json pins: `JAVA_HOME`, else JDKs on the PATH, else, on macOS, the JDK +/// `/usr/libexec/java_home -v ` reports, else the homes in `more` (the launcher's pick, +/// Minecraft's own runtimes), else the folders installers use (`jdk_parents`). pub fn find(major: i64, more: &[PathBuf]) -> Result { let need = format!( "Java {major} is needed (a JDK with javac, e.g. Eclipse Temurin {major}). \ @@ -194,8 +216,11 @@ pub fn find(major: i64, more: &[PathBuf]) -> Result { "JAVA_HOME", )); } - if let (Some(javac), Some(java)) = (on_path("javac"), on_path("java")) { - candidates.push((javac, java, "PATH")); + if let Some(path) = std::env::var_os("PATH") { + for home in path_jdks(&path) { + let bin = home.join("bin"); + candidates.push((executable(&bin, "javac"), executable(&bin, "java"), "PATH")); + } } if cfg!(target_os = "macos") { if let Ok(out) = command("/usr/libexec/java_home") @@ -239,10 +264,19 @@ pub fn find(major: i64, more: &[PathBuf]) -> Result { )); continue; } - match javac_major(&javac) { - Ok(found) if i64::from(found) >= major => return Ok(Jdk { javac, java }), - Ok(found) => problems.push(format!("{from} has Java {found} ({})", javac.display())), - Err(e) => problems.push(e), + let checked = [(&javac, "javac"), (&java, "java")] + .into_iter() + .try_for_each(|(program, name)| { + let found = tool_major(program, name)?; + if i64::from(found) >= major { + Ok(()) + } else { + Err(format!("{name} {found} ({})", program.display())) + } + }); + match checked { + Ok(()) => return Ok(Jdk { javac, java }), + Err(e) => problems.push(format!("{from}: {e}")), } } if problems.is_empty() { diff --git a/crates/horizon-prepare/tests/java_selection.rs b/crates/horizon-prepare/tests/java_selection.rs new file mode 100644 index 000000000..ba15304e6 --- /dev/null +++ b/crates/horizon-prepare/tests/java_selection.rs @@ -0,0 +1,133 @@ +//! Each scenario runs in its own process so Java discovery sees a controlled environment. +use horizon_prepare::java; +use std::{env, fs, path::Path, process::Command}; + +const TEST: &str = "selects_a_compatible_compiler_and_runtime"; +const CHILD: &str = "HORIZON_JAVA_SELECTION_CHILD"; +const ROOT: &str = "HORIZON_JAVA_SELECTION_ROOT"; + +fn tool(bin: &Path, name: &str) -> std::path::PathBuf { + bin.join(format!("{name}{}", env::consts::EXE_SUFFIX)) +} + +#[test] +fn selects_a_compatible_compiler_and_runtime() { + if let Ok(scenario) = env::var(CHILD) { + let root = std::path::PathBuf::from(env::var_os(ROOT).unwrap()); + if scenario.ends_with("error") { + // Use a future compiler version to keep real installed JDKs out of the result. + let error = java::find(255, &[]).err().expect("accepted an old runtime"); + let runtime = if scenario == "legacy-runtime-error" { + 8 + } else { + 21 + }; + assert!(error.contains(&format!("java {runtime} (")), "{error}"); + return; + } + let jdk = java::find(25, &[]).unwrap(); + let expected = root.join(if scenario == "target-release" { + "newer" + } else { + "jdk25" + }); + for (actual, name) in [(&jdk.javac, "javac"), (&jdk.java, "java")] { + assert_eq!( + fs::canonicalize(actual).unwrap(), + fs::canonicalize(tool(&expected.join("bin"), name)).unwrap() + ); + } + assert_eq!( + fs::canonicalize(jdk.home()).unwrap(), + fs::canonicalize(expected).unwrap() + ); + let log_path = root.join(format!("{scenario}.log")); + let log = fs::File::create(&log_path).unwrap(); + jdk.java(&[], None, &log).unwrap(); + assert_eq!(fs::read_to_string(log_path).unwrap().trim(), "java 25.0.1"); + return; + } + + let root = env::temp_dir().join(format!("horizon-java-selection-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let probe = tool(&root, "probe"); + let output = Command::new("rustc") + .arg(Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/support/java_probe.rs")) + .arg("-o") + .arg(&probe) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + for (home, compiler, runtime) in [ + ("jre21", None, "21.0.1"), + ("jdk21", Some("21.0.1"), "21.0.1"), + ("jdk25", Some("25.0.1"), "25.0.1"), + ("mixed", Some("25.0.1"), "21.0.1"), + ("failing", Some("25.0.1"), "25.0.1"), + ("newer", Some("26-ea+1"), "25.0.1"), + ("future", Some("255.0.1"), "21.0.1"), + ("legacy", Some("255.0.1"), "1.8.0_442"), + ] { + let bin = root.join(home).join("bin"); + fs::create_dir_all(&bin).unwrap(); + for (name, version) in [("javac", compiler), ("java", Some(runtime))] { + if let Some(version) = version { + fs::copy(&probe, tool(&bin, name)).unwrap(); + fs::write(bin.join(format!("{name}.version")), version).unwrap(); + } + } + } + fs::write(root.join("failing/bin/java.exit"), "7").unwrap(); + let scenarios = vec![ + ("older-runtime", None, vec!["jre21", "jdk25"]), + ("older-jdk", None, vec!["jdk21", "jdk25"]), + ("incompatible-home", Some("mixed"), vec!["jdk25"]), + ("failed-runtime", Some("failing"), vec!["jdk25"]), + ("target-release", Some("newer"), vec![]), + ("runtime-error", Some("future"), vec![]), + ("legacy-runtime-error", Some("legacy"), vec![]), + ]; + #[cfg(unix)] + let scenarios = { + let mut scenarios = scenarios; + let bin = root.join("shims/bin"); + fs::create_dir_all(&bin).unwrap(); + std::os::unix::fs::symlink(tool(&root.join("jdk25/bin"), "javac"), tool(&bin, "javac")) + .unwrap(); + std::os::unix::fs::symlink(tool(&root.join("jre21/bin"), "java"), tool(&bin, "java")) + .unwrap(); + scenarios.push(("symlinked-path", None, vec!["shims"])); + scenarios + }; + for (scenario, home, path) in scenarios { + let mut child = Command::new(env::current_exe().unwrap()); + child + .args(["--exact", TEST, "--nocapture"]) + .env(CHILD, scenario) + .env(ROOT, &root) + .env( + "PATH", + env::join_paths(path.iter().map(|home| root.join(home).join("bin"))).unwrap(), + ) + .env("HOME", &root) + .env("USERPROFILE", &root) + .env("ProgramFiles", &root) + .env("ProgramW6432", &root) + .env_remove("JAVA_HOME"); + if let Some(home) = home { + child.env("JAVA_HOME", root.join(home)); + } + let output = child.output().unwrap(); + assert!( + output.status.success(), + "{scenario}:\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + } + fs::remove_dir_all(root).unwrap(); +} diff --git a/crates/horizon-prepare/tests/support/java_probe.rs b/crates/horizon-prepare/tests/support/java_probe.rs new file mode 100644 index 000000000..607c837cc --- /dev/null +++ b/crates/horizon-prepare/tests/support/java_probe.rs @@ -0,0 +1,21 @@ +//! A fake Java tool for process-level JDK selection tests; no installed Java is needed. +use std::{env, fs, process}; + +fn main() { + let executable = env::current_exe().unwrap(); + let bin = executable.parent().unwrap(); + let tool = executable.file_stem().unwrap().to_str().unwrap(); + let version = fs::read_to_string(bin.join(format!("{tool}.version"))).unwrap(); + if env::args().nth(1).as_deref() == Some("-version") { + if tool == "javac" { + println!("javac {version}"); + } else { + eprintln!("openjdk version \"{version}\""); + } + } else { + println!("{tool} {version}"); + } + if let Ok(status) = fs::read_to_string(bin.join(format!("{tool}.exit"))) { + process::exit(status.parse().unwrap()); + } +} diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index efdfa2415..2f63951c8 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1022,21 +1022,18 @@ fn download_for_owner( } } -/// A JDK of at least `major` for the preparation. `None` when horizon-prepare finds one by -/// itself (JAVA_HOME, the PATH, an installed JDK): the preparation then runs as before, in an -/// unchanged environment (a JDK found on the PATH can be a stub such as macOS's -/// /usr/bin/javac, whose folder is no Java home: `JAVA_HOME=/usr` makes it call itself -/// forever). Else the home of the Java the official launcher downloaded into one of the -/// `games` folders, else of Minecraft's own Java downloaded from Mojang into Horizon's game -/// folder, the runtime the version JSON at `manifest` names (Mojang's runtimes are whole JDKs). +/// The home of a JDK whose compiler and runtime support `major`. Forward even an installed +/// JDK to external preparers: older versions may otherwise rediscover incompatible PATH tools. +/// Else try the official launcher's Java in `games`, then download the runtime named by +/// `manifest` into Horizon's game folder (Mojang's runtimes are whole JDKs). fn java( major: i64, games: &[PathBuf], manifest: &Path, log: &dyn Fn(String), -) -> Result, String> { - if horizon_prepare::java::find(major, &[]).is_ok() { - return Ok(None); +) -> Result { + if let Ok(jdk) = horizon_prepare::java::find(major, &[]) { + return Ok(jdk.home()); } let mut runtimes: Vec = Vec::new(); for home in games @@ -1048,7 +1045,7 @@ fn java( } } let missing = match horizon_prepare::java::find(major, &runtimes) { - Ok(jdk) => return Ok(Some(jdk.home())), + Ok(jdk) => return Ok(jdk.home()), Err(e) => e, }; let component = read_json(manifest) @@ -1073,7 +1070,7 @@ fn java( let home = mojang::java_runtime(&component, &runtime, 8, &fetch, log).map_err(|e| { format!("{missing}\n • Horizon also tried to download Minecraft's own Java from Mojang, but: {e}") })?; - horizon_prepare::java::find(major, &[home]).map(|jdk| Some(jdk.home())) + horizon_prepare::java::find(major, &[home]).map(|jdk| jdk.home()) } /// The dynamic loader glibc programs on x86-64 Linux start through. @@ -1196,14 +1193,12 @@ pub fn preparer( import: !reused, minecraft_dir: Some(minecraft.clone()), server_jar: (!reused).then_some(jar), - java_home: java_home.clone(), + java_home: Some(java_home.clone()), }; return Ok((Preparer::InProcess(options), minecraft)); } let mut cmd = Command::new(binary); - if let Some(home) = &java_home { - with_java(&mut cmd, home); - } + with_java(&mut cmd, &java_home); cmd.current_dir(&dir).arg("--root").arg(&dir); if !reused { cmd.args(["--prepare", "--server-jar"]).arg(&jar); @@ -1212,9 +1207,7 @@ pub fn preparer( return Ok((Preparer::Process(cmd), minecraft)); } let mut cmd = Command::new(python.unwrap()); - if let Some(home) = &java_home { - with_java(&mut cmd, home); - } + with_java(&mut cmd, &java_home); cmd.current_dir(&dir) .args(["-u", "tools/prepare_native_client.py"]); if !reused { @@ -2338,6 +2331,10 @@ impl Settings { #[path = "backend/release_loading_tests.rs"] mod release_loading_tests; +#[cfg(test)] +#[path = "backend/java_tests.rs"] +mod java_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/launcher/src/backend/java_tests.rs b/launcher/src/backend/java_tests.rs new file mode 100644 index 000000000..75914a1b0 --- /dev/null +++ b/launcher/src/backend/java_tests.rs @@ -0,0 +1,85 @@ +use super::*; + +#[test] +fn selected_jdk_reaches_external_preparers() { + const CHILD: &str = "HORIZON_LAUNCHER_JAVA_TEST"; + if let Some(root) = std::env::var_os(CHILD) { + let root = PathBuf::from(root); + let home = java(25, &[], &root.join("missing.json"), &|_| {}).unwrap(); + assert_eq!( + fs::canonicalize(&home).unwrap(), + fs::canonicalize(root.join("jdk25")).unwrap() + ); + // An older preparer invokes Java tools by name; both must now resolve to this JDK. + for name in ["java", "javac"] { + let mut cmd = crate::process::command(name); + with_java(&mut cmd, &home); + let output = cmd.arg("-version").output().unwrap(); + assert!(output.status.success()); + let text = String::from_utf8_lossy(&output.stdout).into_owned() + + &String::from_utf8_lossy(&output.stderr); + assert!(text.contains("25.0.1"), "{name}: {text}"); + assert_eq!( + cmd.get_envs() + .find(|(key, _)| *key == "JAVA_HOME") + .unwrap() + .1, + Some(home.as_os_str()) + ); + } + return; + } + + let root = std::env::temp_dir().join(format!("horizon-launcher-java-{}", std::process::id())); + fs::create_dir_all(&root).unwrap(); + let executable = + |bin: &Path, name: &str| bin.join(format!("{name}{}", std::env::consts::EXE_SUFFIX)); + let probe = executable(&root, "probe"); + let source = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../crates/horizon-prepare/tests/support/java_probe.rs"); + let output = crate::process::command("rustc") + .arg(source) + .arg("-o") + .arg(&probe) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + for (home, compiler, runtime) in [ + ("jre21", None, "21.0.1"), + ("jdk25", Some("25.0.1"), "25.0.1"), + ] { + let bin = root.join(home).join("bin"); + fs::create_dir_all(&bin).unwrap(); + for (name, version) in [("javac", compiler), ("java", Some(runtime))] { + if let Some(version) = version { + fs::copy(&probe, executable(&bin, name)).unwrap(); + fs::write(bin.join(format!("{name}.version")), version).unwrap(); + } + } + } + let output = crate::process::command(std::env::current_exe().unwrap()) + .args([ + "--exact", + "backend::java_tests::selected_jdk_reaches_external_preparers", + "--nocapture", + ]) + .env(CHILD, &root) + .env_remove("JAVA_HOME") + .env( + "PATH", + std::env::join_paths([root.join("jre21/bin"), root.join("jdk25/bin")]).unwrap(), + ) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + fs::remove_dir_all(root).unwrap(); +}