use std::collections::HashSet;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use super::tools::{compare_version_names, home_dir, is_executable_file, tool_bin};
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct JavaVersionInfo {
pub is_openj9: bool,
pub major: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum JdkRequirement {
HotSpotAny,
HotSpotGradle,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct JdkProbe {
pub java_home: Option<PathBuf>,
pub info: JavaVersionInfo,
pub has_javac_and_keytool: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SelectedJdk {
pub java_home: Option<PathBuf>,
pub switched: bool,
pub info: JavaVersionInfo,
}
fn contains_ascii_ignore_case(haystack: &str, needle: &str) -> bool {
let hb = haystack.as_bytes();
let nb = needle.as_bytes();
!nb.is_empty() && hb.windows(nb.len()).any(|w| w.eq_ignore_ascii_case(nb))
}
pub(crate) fn parse_java_version_output(output: &str) -> JavaVersionInfo {
let is_openj9 = contains_ascii_ignore_case(output, "openj9");
let major = parse_java_major_version(output);
JavaVersionInfo { is_openj9, major }
}
fn parse_java_major_version(output: &str) -> Option<u32> {
for line in output.lines() {
let Some(rest) = line.split("version \"").nth(1) else {
continue;
};
let ver = rest.split('"').next().unwrap_or("");
let mut parts = ver.split(['.', '_', '-', '+']).filter(|s| !s.is_empty());
let first: u32 = parts.next()?.parse().ok()?;
if first == 1 {
return parts.next().and_then(|s| s.parse::<u32>().ok());
}
return Some(first);
}
None
}
fn gradle_major_rank(major: u32) -> u8 {
match major {
21 => 0,
17 => 1,
22 => 2,
23 => 3,
18..=20 => 4,
_ => 255,
}
}
pub(crate) fn probe_satisfies(probe: &JdkProbe, req: JdkRequirement) -> bool {
if probe.info.is_openj9 || !probe.has_javac_and_keytool {
return false;
}
match req {
JdkRequirement::HotSpotAny => probe.info.major.is_some_and(|m| m >= 11),
JdkRequirement::HotSpotGradle => probe.info.major.is_some_and(|m| (17..=23).contains(&m)),
}
}
pub(crate) fn select_jdk(
default_probe: Option<&JdkProbe>,
candidates: &[JdkProbe],
req: JdkRequirement,
) -> Result<SelectedJdk, String> {
if let Some(def) = default_probe
&& probe_satisfies(def, req)
{
return Ok(SelectedJdk {
java_home: def.java_home.clone(),
switched: false,
info: def.info.clone(),
});
}
let chosen = match req {
JdkRequirement::HotSpotAny => candidates
.iter()
.filter(|c| c.java_home.is_some() && probe_satisfies(c, req))
.min_by_key(|c| {
let m = c.info.major.unwrap_or(0);
let tier = if m >= 17 { 0u8 } else { 1u8 };
(tier, std::cmp::Reverse(m))
}),
JdkRequirement::HotSpotGradle => candidates
.iter()
.filter(|c| c.java_home.is_some() && probe_satisfies(c, req))
.min_by_key(|c| {
let m = c.info.major.unwrap_or(0);
(gradle_major_rank(m), std::cmp::Reverse(m))
}),
};
if let Some(hit) = chosen {
return Ok(SelectedJdk {
java_home: hit.java_home.clone(),
switched: true,
info: hit.info.clone(),
});
}
let default_desc = match default_probe {
Some(p) if p.info.is_openj9 => "Eclipse OpenJ9".to_owned(),
Some(p) if !p.has_javac_and_keytool => format!(
"JRE {} (missing javac/keytool)",
p.info.major.map_or_else(|| "unknown".to_owned(), |m| m.to_string())
),
Some(p) => format!(
"JDK {}",
p.info.major.map_or_else(|| "unknown".to_owned(), |m| m.to_string())
),
None => "none on PATH".to_owned(),
};
match req {
JdkRequirement::HotSpotAny => Err(format!(
"default JVM ({default_desc}) cannot run Android d8/javac (requires HotSpot/JBR JDK 11+ with javac+keytool; OpenJ9 crashes d8, see docs/UPSTREAM.md); install Temurin 21 or Android Studio JBR or set JAVA_HOME"
)),
JdkRequirement::HotSpotGradle => Err(format!(
"default JVM ({default_desc}) is incompatible with Gradle 8.11.1 / AGP 8.8.2 (requires HotSpot/JBR JDK 17–23 with javac+keytool, not OpenJ9, JRE-only, or JDK 25+); install Temurin 21 or Android Studio JBR or set JAVA_HOME"
)),
}
}
pub(crate) fn jdk_tool(jdk: &SelectedJdk, tool: &str) -> PathBuf {
match &jdk.java_home {
Some(home) => tool_bin(&home.join("bin"), tool),
None => PathBuf::from(tool),
}
}
fn probe_java_binary(java_bin: &Path, java_home: Option<PathBuf>) -> Option<JdkProbe> {
let out = Command::new(java_bin).arg("-version").output().ok()?;
if !out.status.success() {
return None;
}
let combined = format!(
"{}\n{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
let info = parse_java_version_output(&combined);
let has_javac_and_keytool = match &java_home {
Some(home) => {
let bin = home.join("bin");
is_executable_file(&tool_bin(&bin, "javac"))
&& is_executable_file(&tool_bin(&bin, "keytool"))
}
None => {
Command::new("javac").arg("-version").output().is_ok_and(|o| o.status.success())
&& Command::new("keytool").arg("-help").output().is_ok()
}
};
Some(JdkProbe { java_home, info, has_javac_and_keytool })
}
fn collect_jvm_homes(dir: &Path, macos_bundle_layout: bool) -> Vec<PathBuf> {
let Ok(entries) = fs::read_dir(dir) else {
return Vec::new();
};
let mut dirs: Vec<(String, PathBuf)> = Vec::new();
for entry in entries.flatten() {
let name = entry.file_name().to_string_lossy().into_owned();
let home = if macos_bundle_layout {
entry.path().join("Contents/Home")
} else {
entry.path()
};
if home.join("bin").is_dir() {
dirs.push((name, home));
}
}
dirs.sort_by(|(a, _), (b, _)| compare_version_names(b, a));
dirs.into_iter().map(|(_, p)| p).collect()
}
pub(crate) fn discover_jdk(req: JdkRequirement) -> Result<SelectedJdk, String> {
let env_java_home = env::var_os("JAVA_HOME")
.map(PathBuf::from)
.filter(|p| !p.as_os_str().is_empty());
let default_probe = if let Some(home) = &env_java_home {
probe_java_binary(&tool_bin(&home.join("bin"), "java"), Some(home.clone()))
.or_else(|| probe_java_binary(Path::new("java"), None))
} else {
probe_java_binary(Path::new("java"), None)
};
if let Some(def) = &default_probe
&& probe_satisfies(def, req)
{
return Ok(SelectedJdk {
java_home: def.java_home.clone(),
switched: false,
info: def.info.clone(),
});
}
let mut candidate_homes: Vec<PathBuf> = Vec::new();
if let Some(home) = &env_java_home {
candidate_homes.push(home.clone());
}
if cfg!(windows) {
candidate_homes.push(PathBuf::from(r"C:\Program Files\Android\Android Studio\jbr"));
if let Some(local) = env::var_os("LOCALAPPDATA").map(PathBuf::from) {
candidate_homes.push(local.join(r"Programs\Android\Android Studio\jbr"));
}
for root in [
r"C:\Program Files\Eclipse Adoptium",
r"C:\Program Files\Java",
r"C:\Program Files\Microsoft",
] {
candidate_homes.extend(collect_jvm_homes(Path::new(root), false));
}
} else {
candidate_homes.push(PathBuf::from("/Applications/Android Studio.app/Contents/jbr/Contents/Home"));
candidate_homes.extend(collect_jvm_homes(Path::new("/Library/Java/JavaVirtualMachines"), true));
if let Some(home) = home_dir() {
candidate_homes.extend(collect_jvm_homes(
&home.join("Library/Java/JavaVirtualMachines"),
true,
));
}
for brew_jdk in [
"/opt/homebrew/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home",
"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home",
"/usr/local/opt/openjdk@21/libexec/openjdk.jdk/Contents/Home",
"/usr/local/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home",
] {
candidate_homes.push(PathBuf::from(brew_jdk));
}
candidate_homes.extend(collect_jvm_homes(Path::new("/usr/lib/jvm"), false));
}
let mut seen = HashSet::new();
let mut probes = Vec::new();
for home in candidate_homes {
let java_bin = tool_bin(&home.join("bin"), "java");
if !is_executable_file(&java_bin) {
continue;
}
let key = fs::canonicalize(&home).unwrap_or_else(|_| home.clone());
if !seen.insert(key) {
continue;
}
if let Some(probe) = probe_java_binary(&java_bin, Some(home)) {
probes.push(probe);
}
}
select_jdk(default_probe.as_ref(), &probes, req)
}
pub(crate) fn apply_jdk_env(cmd: &mut Command, jdk: &SelectedJdk) {
if let Some(home) = &jdk.java_home {
cmd.env("JAVA_HOME", home);
let bin = home.join("bin");
let existing = env::var_os("PATH").unwrap_or_default();
let mut paths = vec![bin];
paths.extend(env::split_paths(&existing));
if let Ok(joined) = env::join_paths(paths) {
cmd.env("PATH", joined);
}
}
}