fix: launch with the selected JVM and own subprocess lifetimes
This commit is contained in:
1 parent
eb436c2ab8
commit
dc351df546
31 files changed
+3061
-820
No files matched your search
+455
-52
@@ -2,9 +2,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
collections::{BTreeMap, HashSet},
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -15,34 +14,177 @@ pub struct JavaInstallation {
|
||||
pub version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct JavaRuntime {
|
||||
pub major_version: u32,
|
||||
pub platform: crate::launch_profile::system::JavaPlatform,
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn resolve_java_path(instance_java: Option<&str>) -> String {
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
let environment = merge_environment(&settings.defaults.environment, &BTreeMap::new());
|
||||
resolve_java_path_in(
|
||||
instance_java.or(settings.paths.effective_java_path()),
|
||||
&std::env::current_dir().unwrap_or_default(),
|
||||
&environment,
|
||||
)
|
||||
}
|
||||
|
||||
/// Command uses the platform's environment-key comparison, including Windows Unicode casing.
|
||||
pub fn merge_environment(
|
||||
global: &BTreeMap<String, String>,
|
||||
instance: &BTreeMap<String, String>,
|
||||
) -> BTreeMap<String, String> {
|
||||
let mut command = std::process::Command::new("java");
|
||||
command.envs(global).envs(instance);
|
||||
command
|
||||
.get_envs()
|
||||
.map(|(name, value)| {
|
||||
(
|
||||
name.to_str()
|
||||
.expect("environment names originate from strings")
|
||||
.to_owned(),
|
||||
value
|
||||
.expect("only environment additions were configured")
|
||||
.to_str()
|
||||
.expect("environment values originate from strings")
|
||||
.to_owned(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// These lookups are for the ASCII variable names PATH, JAVA_HOME and JDK_HOME.
|
||||
fn environment_value(
|
||||
environment: &BTreeMap<String, String>,
|
||||
name: &str,
|
||||
) -> Option<std::ffi::OsString> {
|
||||
environment
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|(key, _)| {
|
||||
if cfg!(windows) {
|
||||
key.eq_ignore_ascii_case(name)
|
||||
} else {
|
||||
key.as_str() == name
|
||||
}
|
||||
})
|
||||
.map(|(_, value)| std::ffi::OsString::from(value))
|
||||
.or_else(|| std::env::var_os(name))
|
||||
}
|
||||
|
||||
pub fn resolve_java_path_in(
|
||||
configured: Option<&str>,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> String {
|
||||
let search_path = environment_value(environment, "PATH");
|
||||
let find = |name: &str| {
|
||||
if Path::new(name).components().count() > 1 {
|
||||
return which::which_in(name, None::<&std::ffi::OsStr>, cwd).ok();
|
||||
}
|
||||
search_path.as_deref().and_then(|path| {
|
||||
std::env::split_paths(path)
|
||||
.filter(|directory| !cfg!(windows) || !directory.as_os_str().is_empty())
|
||||
.find_map(|directory| {
|
||||
which::which_in(
|
||||
cwd.join(directory).join(name),
|
||||
None::<&std::ffi::OsStr>,
|
||||
cwd,
|
||||
)
|
||||
.ok()
|
||||
})
|
||||
})
|
||||
};
|
||||
if let Some(configured) = configured.filter(|path| !path.is_empty()) {
|
||||
return find(configured)
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| configured.to_owned());
|
||||
}
|
||||
if let Some(home) = environment_value(environment, "JAVA_HOME") {
|
||||
let bin = cwd
|
||||
.join(home)
|
||||
.join("bin")
|
||||
.join(if cfg!(windows) { "java.exe" } else { "java" });
|
||||
if bin.is_file() {
|
||||
return bin.to_string_lossy().into_owned();
|
||||
}
|
||||
}
|
||||
find("java")
|
||||
.map(|path| path.to_string_lossy().into_owned())
|
||||
.unwrap_or_else(|| "java".to_owned())
|
||||
}
|
||||
|
||||
/// Probe the selected executable, rather than inferring its architecture from rmcl.
|
||||
pub async fn probe_java(path: &Path) -> std::io::Result<JavaRuntime> {
|
||||
let (cwd, environment) = default_probe_context()?;
|
||||
probe_java_in(path, &cwd, &environment).await
|
||||
}
|
||||
|
||||
pub async fn probe_java_in(
|
||||
path: &Path,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> std::io::Result<JavaRuntime> {
|
||||
let output = java_version_output_in(path, cwd, environment).await?;
|
||||
if !output.status.success() {
|
||||
return Err(std::io::Error::other(format!(
|
||||
"Java settings probe exited with {}",
|
||||
output.status
|
||||
)));
|
||||
}
|
||||
parse_runtime_properties(&format!(
|
||||
"{}\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
))
|
||||
}
|
||||
|
||||
fn default_probe_context() -> std::io::Result<(PathBuf, BTreeMap<String, String>)> {
|
||||
Ok((
|
||||
std::env::current_dir()?,
|
||||
merge_environment(
|
||||
&crate::config::SETTINGS.read().defaults.environment,
|
||||
&BTreeMap::new(),
|
||||
),
|
||||
))
|
||||
}
|
||||
|
||||
fn parse_runtime_properties(output: &str) -> std::io::Result<JavaRuntime> {
|
||||
let property = |name: &str| -> std::io::Result<&str> {
|
||||
output
|
||||
.lines()
|
||||
.filter_map(|line| line.trim().split_once(" = "))
|
||||
.find_map(|(key, value)| (key == name).then_some(value.trim()))
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("Java probe did not report {name}"),
|
||||
)
|
||||
})
|
||||
};
|
||||
let major_version = parse_java_major_version(property("java.version")?).ok_or_else(|| {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, "Invalid Java java.version")
|
||||
})?;
|
||||
Ok(JavaRuntime {
|
||||
major_version,
|
||||
platform: crate::launch_profile::system::JavaPlatform::from_java_properties(
|
||||
property("os.name")?,
|
||||
property("os.arch")?,
|
||||
property("sun.arch.data.model")?,
|
||||
property("os.version")?,
|
||||
)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn detect_java_path() -> String {
|
||||
if let Ok(java_home) = std::env::var("JAVA_HOME") {
|
||||
let java_name = if cfg!(windows) { "java.exe" } else { "java" };
|
||||
let bin = std::path::Path::new(&java_home).join("bin").join(java_name);
|
||||
if bin.exists() {
|
||||
tracing::trace!("Detected Java from JAVA_HOME: {}", bin.display());
|
||||
return bin.to_string_lossy().to_string();
|
||||
}
|
||||
tracing::warn!(
|
||||
"JAVA_HOME is set to {}, but {} does not exist",
|
||||
java_home,
|
||||
bin.display()
|
||||
);
|
||||
}
|
||||
match which::which("java") {
|
||||
Ok(path) => {
|
||||
tracing::trace!("Detected Java from PATH: {}", path.display());
|
||||
path.to_string_lossy().to_string()
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"Could not find java on PATH, falling back to literal 'java': {}",
|
||||
e
|
||||
);
|
||||
"java".to_string()
|
||||
}
|
||||
}
|
||||
let Ok((cwd, environment)) = default_probe_context() else {
|
||||
return "java".to_owned();
|
||||
};
|
||||
resolve_java_path_in(None, &cwd, &environment)
|
||||
}
|
||||
|
||||
/// Finds Java executables in the environment and the conventional installation
|
||||
@@ -50,23 +192,39 @@ pub fn detect_java_path() -> String {
|
||||
/// opening the selector never walks an entire drive.
|
||||
#[must_use]
|
||||
pub fn discover_installations() -> Vec<JavaInstallation> {
|
||||
let Ok((cwd, environment)) = default_probe_context() else {
|
||||
return Vec::new();
|
||||
};
|
||||
discover_installations_in(&cwd, &environment)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn discover_installations_in(
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Vec<JavaInstallation> {
|
||||
let mut candidates = Vec::new();
|
||||
for variable in ["JAVA_HOME", "JDK_HOME"] {
|
||||
if let Ok(java_home) = std::env::var(variable) {
|
||||
add_java_home(Path::new(&java_home), &mut candidates);
|
||||
if let Some(java_home) = environment_value(environment, variable) {
|
||||
add_java_home(&cwd.join(java_home), &mut candidates);
|
||||
}
|
||||
}
|
||||
if let Ok(path) = which::which("java") {
|
||||
let search_path = environment_value(environment, "PATH");
|
||||
if let Ok(path) = which::which_in(
|
||||
resolve_java_path_in(None, cwd, environment),
|
||||
None::<&std::ffi::OsStr>,
|
||||
cwd,
|
||||
) {
|
||||
candidates.push(path);
|
||||
}
|
||||
if let Some(path) = std::env::var_os("PATH") {
|
||||
if let Some(path) = search_path {
|
||||
for directory in std::env::split_paths(&path) {
|
||||
let executable = if cfg!(target_os = "windows") {
|
||||
"java.exe"
|
||||
} else {
|
||||
"java"
|
||||
};
|
||||
candidates.push(directory.join(executable));
|
||||
candidates.push(cwd.join(directory).join(executable));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,7 +239,7 @@ pub fn discover_installations() -> Vec<JavaInstallation> {
|
||||
.filter_map(|path| {
|
||||
let identity = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());
|
||||
seen.insert(identity)
|
||||
.then(|| inspect_installation(&path))
|
||||
.then(|| inspect_installation_in(&path, cwd, environment))
|
||||
.flatten()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
@@ -96,25 +254,96 @@ pub fn discover_installations() -> Vec<JavaInstallation> {
|
||||
/// Reads the version reported by one Java executable.
|
||||
#[must_use]
|
||||
pub fn inspect_installation(path: &Path) -> Option<JavaInstallation> {
|
||||
let (cwd, environment) = default_probe_context().ok()?;
|
||||
inspect_installation_in(path, &cwd, &environment)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn inspect_installation_in(
|
||||
path: &Path,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Option<JavaInstallation> {
|
||||
let resolved = path
|
||||
.to_str()
|
||||
.map(|path| resolve_java_path_in(Some(path), cwd, environment));
|
||||
let path = resolved.as_deref().map_or(path, Path::new);
|
||||
path.is_file().then(|| JavaInstallation {
|
||||
version: java_version(path),
|
||||
version: java_version_in(path, cwd, environment),
|
||||
path: path.to_path_buf(),
|
||||
})
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn load_installation_cache(path: &Path) -> Option<Vec<JavaInstallation>> {
|
||||
let mut installations =
|
||||
serde_json::from_slice::<Vec<JavaInstallation>>(&std::fs::read(path).ok()?).ok()?;
|
||||
installations.retain(|installation| installation.path.is_file());
|
||||
(!installations.is_empty()).then_some(installations)
|
||||
let (cwd, environment) = default_probe_context().ok()?;
|
||||
load_installation_cache_in(path, &cwd, &environment)
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct InstallationCache {
|
||||
context: String,
|
||||
installations: Vec<JavaInstallation>,
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn probe_context_key(cwd: &Path, environment: &BTreeMap<String, String>) -> String {
|
||||
use sha2::Digest;
|
||||
let mut hash = sha2::Sha256::new();
|
||||
let mut add = |bytes: &[u8]| {
|
||||
hash.update((bytes.len() as u64).to_le_bytes());
|
||||
hash.update(bytes);
|
||||
};
|
||||
add(cwd.as_os_str().as_encoded_bytes());
|
||||
let mut ambient: Vec<_> = std::env::vars_os().collect();
|
||||
ambient.sort();
|
||||
for (key, value) in &ambient {
|
||||
add(key.as_encoded_bytes());
|
||||
add(value.as_encoded_bytes());
|
||||
}
|
||||
// Store a digest only; configured environment values may contain credentials.
|
||||
for (key, value) in merge_environment(environment, &BTreeMap::new()) {
|
||||
add(key.as_bytes());
|
||||
add(value.as_bytes());
|
||||
}
|
||||
format!("{:x}", hash.finalize())
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn load_installation_cache_in(
|
||||
path: &Path,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Option<Vec<JavaInstallation>> {
|
||||
let mut cache: InstallationCache = serde_json::from_slice(&std::fs::read(path).ok()?).ok()?;
|
||||
if cache.context != probe_context_key(cwd, environment) {
|
||||
return None;
|
||||
}
|
||||
cache
|
||||
.installations
|
||||
.retain(|installation| installation.path.is_file());
|
||||
(!cache.installations.is_empty()).then_some(cache.installations)
|
||||
}
|
||||
|
||||
pub fn save_installation_cache(
|
||||
path: &Path,
|
||||
installations: &[JavaInstallation],
|
||||
) -> std::io::Result<()> {
|
||||
let bytes = serde_json::to_vec_pretty(installations).map_err(std::io::Error::other)?;
|
||||
let (cwd, environment) = default_probe_context()?;
|
||||
save_installation_cache_in(path, installations, &cwd, &environment)
|
||||
}
|
||||
|
||||
pub fn save_installation_cache_in(
|
||||
path: &Path,
|
||||
installations: &[JavaInstallation],
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> std::io::Result<()> {
|
||||
let cache = InstallationCache {
|
||||
context: probe_context_key(cwd, environment),
|
||||
installations: installations.to_vec(),
|
||||
};
|
||||
let bytes = serde_json::to_vec_pretty(&cache).map_err(std::io::Error::other)?;
|
||||
crate::storage::write_atomic(path, &bytes)
|
||||
}
|
||||
|
||||
@@ -203,8 +432,18 @@ fn add_java_home(home: &Path, candidates: &mut Vec<PathBuf>) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn java_version(path: &Path) -> Option<String> {
|
||||
let output = Command::new(path).arg("-version").output().ok()?;
|
||||
pub fn java_version_in(
|
||||
path: &Path,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Option<String> {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.ok()?;
|
||||
let output = runtime
|
||||
.block_on(java_version_output_in(path, cwd, environment))
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
@@ -216,8 +455,36 @@ pub(crate) fn java_version(path: &Path) -> Option<String> {
|
||||
parse_java_version(&text)
|
||||
}
|
||||
|
||||
async fn java_version_output_in(
|
||||
path: &Path,
|
||||
cwd: &Path,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> std::io::Result<std::process::Output> {
|
||||
let java = path
|
||||
.to_str()
|
||||
.map(|path| resolve_java_path_in(Some(path), cwd, environment));
|
||||
let mut command = tokio::process::Command::new(java.as_deref().map_or(path, Path::new));
|
||||
command
|
||||
.args(["-XshowSettings:properties", "-version"])
|
||||
.current_dir(cwd)
|
||||
.envs(environment)
|
||||
.kill_on_drop(true);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(10), command.output())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
std::io::Error::new(std::io::ErrorKind::TimedOut, "Java version check timed out")
|
||||
})?
|
||||
}
|
||||
|
||||
fn parse_java_version(output: &str) -> Option<String> {
|
||||
output.lines().find_map(|line| {
|
||||
let line = line.trim();
|
||||
if let Some(version) = line.strip_prefix("java.version = ") {
|
||||
return Some(version.trim().to_owned());
|
||||
}
|
||||
if !line.starts_with("java version ") && !line.starts_with("openjdk version ") {
|
||||
return None;
|
||||
}
|
||||
line.split_once('"')
|
||||
.and_then(|(_, rest)| rest.split_once('"'))
|
||||
.map(|(version, _)| version.to_owned())
|
||||
@@ -246,16 +513,7 @@ pub(crate) fn parse_java_major_version(output: &str) -> Option<u32> {
|
||||
}
|
||||
|
||||
let start = output.find(|character: char| character.is_ascii_digit())?;
|
||||
let parts = output[start..]
|
||||
.split(|character: char| !character.is_ascii_digit())
|
||||
.filter(|part| !part.is_empty())
|
||||
.filter_map(|part| part.parse::<u32>().ok())
|
||||
.collect::<Vec<_>>();
|
||||
match parts.as_slice() {
|
||||
[1, legacy_major, ..] => Some(*legacy_major),
|
||||
[major, ..] => Some(*major),
|
||||
[] => None,
|
||||
}
|
||||
Some(java_major(Some(&output[start..]))).filter(|major| *major > 0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -299,4 +557,149 @@ mod tests {
|
||||
std::fs::remove_file(executable).unwrap();
|
||||
assert_eq!(load_installation_cache(&cache), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_properties_report_selected_java_architecture_and_os_version() {
|
||||
for (os, arch, bits, name, normalized) in [
|
||||
("Windows 10", "x86", "32", "windows", "x86"),
|
||||
("Windows 11", "amd64", "64", "windows", "x86_64"),
|
||||
("Mac OS X", "x86_64", "64", "osx", "x86_64"),
|
||||
("Mac OS X", "aarch64", "64", "osx", "arm64"),
|
||||
("Linux", "amd64", "64", "linux", "x86_64"),
|
||||
] {
|
||||
let properties = format!(
|
||||
"Property settings:\r\n java.version = 1.8.0_412\r\n os.name = {os}\r\n os.arch = {arch}\r\n sun.arch.data.model = {bits}\r\n os.version = 10.0\r\n"
|
||||
);
|
||||
let runtime = parse_runtime_properties(&properties).unwrap();
|
||||
assert_eq!(runtime.major_version, 8);
|
||||
assert_eq!(runtime.platform.os_name, name);
|
||||
assert_eq!(runtime.platform.arch, normalized);
|
||||
assert_eq!(runtime.platform.bitness.to_string(), bits);
|
||||
assert_eq!(runtime.platform.os_version, "10.0");
|
||||
assert!(
|
||||
parse_runtime_properties(&properties.replace("sun.arch.data.model =", "unknown ="))
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("sun.arch.data.model")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_runtime_properties_do_not_fall_back_to_the_launcher_architecture() {
|
||||
assert!(parse_runtime_properties("openjdk version \"25.0.1\"").is_err());
|
||||
assert!(
|
||||
crate::launch_profile::system::JavaPlatform::from_java_properties(
|
||||
"Windows 10",
|
||||
"../x86",
|
||||
"32",
|
||||
"10.0"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
crate::launch_profile::system::JavaPlatform::from_java_properties(
|
||||
"Mac OS X", "aarch64", "unknown", "15.0"
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn relative_java_search_paths_are_bound_to_the_execution_directory() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let temp =
|
||||
tempfile::tempdir_in(Path::new(env!("CARGO_MANIFEST_DIR")).join("target")).unwrap();
|
||||
let cwd = temp.path().join("minecraft");
|
||||
let java = cwd.join("bin/java");
|
||||
std::fs::create_dir_all(java.parent().unwrap()).unwrap();
|
||||
std::fs::write(&java, "#!/bin/sh\nexit 0\n").unwrap();
|
||||
std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
let environment = BTreeMap::from([
|
||||
("PATH".to_owned(), "bin".to_owned()),
|
||||
("JAVA_HOME".to_owned(), "missing-home".to_owned()),
|
||||
]);
|
||||
for configured in [None, Some("java"), Some("bin/java")] {
|
||||
assert_eq!(
|
||||
Path::new(&resolve_java_path_in(configured, &cwd, &environment)),
|
||||
java
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn installed_jdk_reports_runtime_properties_on_the_native_platform() {
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let environment = BTreeMap::new();
|
||||
let java = resolve_java_path_in(None, &cwd, &environment);
|
||||
let runtime = probe_java_in(Path::new(&java), &cwd, &environment)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(runtime.major_version >= 8);
|
||||
assert_eq!(
|
||||
runtime.platform.os_name,
|
||||
crate::launch_profile::system::mojang_os_name()
|
||||
);
|
||||
assert!(matches!(runtime.platform.bitness, 32 | 64));
|
||||
assert!(!runtime.platform.os_version.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn environment_overrides_follow_native_case_rules_and_are_deterministic() {
|
||||
let global = BTreeMap::from([
|
||||
("PATH".into(), "global".into()),
|
||||
("TÊST".into(), "global".into()),
|
||||
]);
|
||||
let instance = BTreeMap::from([
|
||||
("PATH".into(), "first".into()),
|
||||
("path".into(), "last".into()),
|
||||
("têst".into(), "instance".into()),
|
||||
]);
|
||||
let merged = merge_environment(&global, &instance);
|
||||
assert_eq!(
|
||||
environment_value(&instance, "PATH").unwrap(),
|
||||
std::ffi::OsString::from(if cfg!(windows) { "last" } else { "first" })
|
||||
);
|
||||
if cfg!(windows) {
|
||||
assert_eq!(merged.len(), 2);
|
||||
assert_eq!(merged["PATH"], "last");
|
||||
assert_eq!(merged["TÊST"], "instance");
|
||||
} else {
|
||||
assert_eq!(merged.len(), 4);
|
||||
assert_eq!(merged["PATH"], "first");
|
||||
assert_eq!(merged["path"], "last");
|
||||
assert_eq!(merged["TÊST"], "global");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installation_cache_is_bound_to_the_probe_context_without_storing_environment_values() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let executable = temp.path().join("java");
|
||||
std::fs::write(&executable, b"java").unwrap();
|
||||
let cache = temp.path().join("installations.json");
|
||||
let installations = vec![JavaInstallation {
|
||||
path: executable,
|
||||
version: Some("25.0.1".into()),
|
||||
}];
|
||||
let environment =
|
||||
BTreeMap::from([("PRIVATE_TEST_VALUE".into(), "sensitive-cache-value".into())]);
|
||||
save_installation_cache_in(&cache, &installations, temp.path(), &environment).unwrap();
|
||||
assert_eq!(
|
||||
load_installation_cache_in(&cache, temp.path(), &environment),
|
||||
Some(installations)
|
||||
);
|
||||
assert!(
|
||||
!std::fs::read_to_string(&cache)
|
||||
.unwrap()
|
||||
.contains("sensitive-cache-value")
|
||||
);
|
||||
let changed = BTreeMap::from([("PRIVATE_TEST_VALUE".into(), "another-value".into())]);
|
||||
assert!(load_installation_cache_in(&cache, temp.path(), &changed).is_none());
|
||||
assert!(
|
||||
load_installation_cache_in(&cache, &temp.path().join("other-cwd"), &environment)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
+298
-229
@@ -1,6 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
mod output;
|
||||
pub(crate) mod parser;
|
||||
mod patches;
|
||||
|
||||
@@ -8,12 +9,14 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
use super::process;
|
||||
use crate::auth::AccountType;
|
||||
use crate::instance::java::JavaRuntime;
|
||||
use crate::instance::models::{InstanceConfig, LaunchCommand, ModLoader, WindowMode};
|
||||
use crate::launch_profile::model::{Argument, LaunchProfile};
|
||||
use crate::launch_profile::rules::{self, FeatureSet, RuleAction, RuleContext};
|
||||
use crate::launch_profile::templates::TemplateContext;
|
||||
use crate::launch_profile::{render, resolve, system};
|
||||
use crate::launch_profile::{render, resolve};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum LaunchError {
|
||||
@@ -33,18 +36,44 @@ pub enum LaunchError {
|
||||
required: u32,
|
||||
detected: u32,
|
||||
},
|
||||
#[error("This instance requires Java {required}, but rmcl could not check {java}: {reason}")]
|
||||
#[error("Could not inspect Java runtime {java}: {reason}")]
|
||||
JavaCheckFailed {
|
||||
java: String,
|
||||
required: u32,
|
||||
reason: String,
|
||||
},
|
||||
#[error("Download error: {0}")]
|
||||
Download(#[from] crate::net::NetError),
|
||||
#[error("{0}")]
|
||||
Auth(String),
|
||||
#[error("{phase} command failed: {reason}")]
|
||||
Command { phase: &'static str, reason: String },
|
||||
#[error("Config sync error: {0}")]
|
||||
ConfigSync(#[from] crate::instance::config_sync::ConfigSyncError),
|
||||
#[error("Launch cancelled")]
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
struct LaunchCleanup(String);
|
||||
|
||||
impl Drop for LaunchCleanup {
|
||||
fn drop(&mut self) {
|
||||
crate::instance::runtime::cleanup_kill_sender(&self.0);
|
||||
if crate::instance::runtime::is_active(&self.0) {
|
||||
crate::instance::runtime::remove(&self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn wait_for_kill(receiver: &mut Option<tokio::sync::oneshot::Receiver<()>>) {
|
||||
if let Some(pending) = receiver {
|
||||
let result = pending.await;
|
||||
*receiver = None;
|
||||
if result.is_ok() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
|
||||
fn build_game_args(
|
||||
@@ -77,49 +106,16 @@ fn apply_window_mode(game_args: &mut Vec<String>, window_mode: WindowMode) {
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_java_version(java: &str, required: Option<u32>) -> Result<(), LaunchError> {
|
||||
fn check_java_version(
|
||||
java: &str,
|
||||
runtime: &JavaRuntime,
|
||||
required: Option<u32>,
|
||||
) -> Result<(), LaunchError> {
|
||||
let Some(required) = required.filter(|major| *major > 0) else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let mut command = tokio::process::Command::new(java);
|
||||
command.arg("-version").kill_on_drop(true);
|
||||
let output = tokio::time::timeout(std::time::Duration::from_secs(10), command.output())
|
||||
.await
|
||||
.map_err(|_| LaunchError::JavaCheckFailed {
|
||||
java: java.to_owned(),
|
||||
required,
|
||||
reason: "version check timed out".to_owned(),
|
||||
})?
|
||||
.map_err(|e| LaunchError::JavaCheckFailed {
|
||||
java: java.to_owned(),
|
||||
required,
|
||||
reason: e.to_string(),
|
||||
})?;
|
||||
|
||||
if !output.status.success() {
|
||||
return Err(LaunchError::JavaCheckFailed {
|
||||
java: java.to_owned(),
|
||||
required,
|
||||
reason: format!("`java -version` exited with {}", output.status),
|
||||
});
|
||||
}
|
||||
|
||||
let version_text = format!(
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
|
||||
let detected =
|
||||
crate::instance::java::parse_java_major_version(&version_text).ok_or_else(|| {
|
||||
LaunchError::JavaCheckFailed {
|
||||
java: java.to_owned(),
|
||||
required,
|
||||
reason: format!("could not parse `java -version` output: {version_text:?}"),
|
||||
}
|
||||
})?;
|
||||
|
||||
let detected = runtime.major_version;
|
||||
if detected < required {
|
||||
return Err(LaunchError::JavaTooOld {
|
||||
java: java.to_owned(),
|
||||
@@ -131,11 +127,7 @@ async fn check_java_version(java: &str, required: Option<u32>) -> Result<(), Lau
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// existing installs from rmcl <= 0.3.0 have meta.json files in the
|
||||
// stripped legacy format (no `arguments`, no `minecraftArguments`). every
|
||||
// real upstream profile has at least one of those fields. on detecting the
|
||||
// stripped format, re-fetch the version metadata from mojang's manifest
|
||||
// and overwrite the file with the raw upstream bytes.
|
||||
// rmcl <= 0.3.0 stripped upstream arguments from cached metadata.
|
||||
async fn migrate_legacy_meta_if_needed(
|
||||
meta_path: &Path,
|
||||
profile: &LaunchProfile,
|
||||
@@ -193,9 +185,6 @@ async fn migrate_legacy_meta_if_needed(
|
||||
Ok(Some(refreshed))
|
||||
}
|
||||
|
||||
// the forge/neoforge installer writes its version JSON to a path that's
|
||||
// loader-specific. encode the naming convention here so migration code
|
||||
// can find the original file when it needs to rebuild our cache.
|
||||
fn installer_version_dir_name(
|
||||
loader: ModLoader,
|
||||
game_version: &str,
|
||||
@@ -208,35 +197,19 @@ fn installer_version_dir_name(
|
||||
}
|
||||
}
|
||||
|
||||
// loader profiles installed by rmcl <= 0.3.0 are in our stripped
|
||||
// `{mainClass, libraries[, gameArguments]}` format, which silently drops
|
||||
// `inheritsFrom`, `arguments.jvm`, and conditional rules from upstream.
|
||||
// detect that shape (no inheritsFrom AND no arguments AND no
|
||||
// minecraftArguments - every real upstream profile has at least one) and
|
||||
// rebuild from the installer's original JSON if it's still on disk.
|
||||
// Recover JVM arguments and rules stripped by rmcl <= 0.3.0 from the installer original.
|
||||
async fn migrate_legacy_loader_profile_if_needed(
|
||||
profile_path: &Path,
|
||||
profile: &LaunchProfile,
|
||||
config: &InstanceConfig,
|
||||
instance_dir: &Path,
|
||||
) -> Result<Option<LaunchProfile>, LaunchError> {
|
||||
// Fabric and Quilt fetch their profiles from a network endpoint at
|
||||
// install time; there's no installer-written JSON on disk to recover
|
||||
// from. their upstream profiles also happen to match the "legacy
|
||||
// stripped" predicate (no inheritsFrom, no arguments), so without this
|
||||
// early return every Fabric/Quilt launch would incorrectly fail
|
||||
// migration. resolve() handles their lack of inheritsFrom via the
|
||||
// implicit fallback in the launch flow.
|
||||
// Fabric/Quilt profiles can omit these fields and have no installer original.
|
||||
if matches!(config.loader, ModLoader::Fabric | ModLoader::Quilt) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// tightened predicate per the spec: only treat a profile as "legacy
|
||||
// stripped" when our old `gameArguments` field is present. that field
|
||||
// is unique to rmcl <= 0.3.0's custom shape; no upstream profile
|
||||
// emits it. without this gate, an upstream profile that happens to
|
||||
// omit inheritsFrom/arguments/minecraftArguments would be mistakenly
|
||||
// re-extracted from the installer JSON.
|
||||
// gameArguments identifies rmcl's old shape, avoiding false positives on upstream profiles.
|
||||
let is_legacy = profile.inherits_from.is_none()
|
||||
&& profile.arguments.is_none()
|
||||
&& profile.minecraft_arguments.is_none()
|
||||
@@ -256,9 +229,6 @@ async fn migrate_legacy_loader_profile_if_needed(
|
||||
let Some(version_dir) =
|
||||
installer_version_dir_name(config.loader, &config.game_version, loader_version)
|
||||
else {
|
||||
// unreachable today: only Vanilla/Fabric/Quilt return None, and
|
||||
// Vanilla doesn't pass this code path (no loader profile to
|
||||
// migrate) while Fabric/Quilt are filtered above.
|
||||
return Err(LaunchError::Parse(format!(
|
||||
"Loader profile at {} is in an outdated format. Reinstall {} for this instance.",
|
||||
profile_path.display(),
|
||||
@@ -366,10 +336,32 @@ pub async fn build_launch_invocation(
|
||||
auth: &LaunchAuth<'_>,
|
||||
quick_play_world: Option<&str>,
|
||||
) -> Result<LaunchInvocation, LaunchError> {
|
||||
let instance_dir = instances_dir.join(&config.name);
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
build_launch_invocation_with_settings(
|
||||
config,
|
||||
instances_dir,
|
||||
meta_dir,
|
||||
auth,
|
||||
quick_play_world,
|
||||
&settings,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn build_launch_invocation_with_settings(
|
||||
config: &InstanceConfig,
|
||||
instances_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
auth: &LaunchAuth<'_>,
|
||||
quick_play_world: Option<&str>,
|
||||
settings: &crate::config::Config,
|
||||
) -> Result<LaunchInvocation, LaunchError> {
|
||||
let meta_dir = std::path::absolute(meta_dir)?;
|
||||
let meta_dir = meta_dir.as_path();
|
||||
let instance_dir = std::path::absolute(instances_dir.join(&config.name))?;
|
||||
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
let (window_mode, resolution) = {
|
||||
let defaults = &crate::config::SETTINGS.read().defaults;
|
||||
let defaults = &settings.defaults;
|
||||
(
|
||||
config.effective_window_mode(defaults.window_mode),
|
||||
config.effective_resolution(defaults.resolution),
|
||||
@@ -399,20 +391,6 @@ pub async fn build_launch_invocation(
|
||||
has_custom_resolution: resolution.map(|_| true),
|
||||
..Default::default()
|
||||
};
|
||||
let host_os_version = system::mojang_os_version();
|
||||
let rule_ctx = RuleContext {
|
||||
os_name: system::mojang_os_name(),
|
||||
os_version: &host_os_version,
|
||||
arch: system::mojang_arch_name(),
|
||||
features: ¤t_features,
|
||||
};
|
||||
|
||||
let asset_index_id = meta
|
||||
.asset_index
|
||||
.as_ref()
|
||||
.map(|ai| ai.id.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let lib_dir = metadata_paths.libraries();
|
||||
|
||||
let lv = config.loader_version.as_deref().unwrap_or("unknown");
|
||||
@@ -423,7 +401,7 @@ pub async fn build_launch_invocation(
|
||||
// if needed, and resolve `inheritsFrom` against the vanilla parent (which
|
||||
// the vanilla meta migration above ensured is fresh on disk). when no
|
||||
// loader is configured we use the already-loaded vanilla meta directly.
|
||||
let merged_profile: LaunchProfile = if let Some(filename) = &profile_filename {
|
||||
let mut merged_profile: LaunchProfile = if let Some(filename) = &profile_filename {
|
||||
let profile_path = metadata_paths.loader_profiles().join(filename);
|
||||
if !profile_path.exists() {
|
||||
return Err(LaunchError::MetaNotFound(
|
||||
@@ -458,7 +436,7 @@ pub async fn build_launch_invocation(
|
||||
meta.clone()
|
||||
};
|
||||
|
||||
let main_class = merged_profile
|
||||
let mut main_class = merged_profile
|
||||
.main_class
|
||||
.clone()
|
||||
.ok_or_else(|| LaunchError::Parse("merged profile missing mainClass".into()))?;
|
||||
@@ -467,12 +445,71 @@ pub async fn build_launch_invocation(
|
||||
return Err(LaunchError::NotSupported("Quick Play".to_owned()));
|
||||
}
|
||||
|
||||
// rebuild the classpath from the merged profile. vanilla-style libraries
|
||||
// have `downloads.artifact.path` set and live in meta_dir/libraries/.
|
||||
// loader-style libraries only have a maven coordinate; for forge/neoforge,
|
||||
// the installer drops some of them into <instance>/.minecraft/libraries/
|
||||
// so we check there first.
|
||||
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&settings.defaults.environment,
|
||||
&config.environment,
|
||||
);
|
||||
let java = crate::instance::java::resolve_java_path_in(
|
||||
config
|
||||
.java_path
|
||||
.as_deref()
|
||||
.or(settings.paths.effective_java_path()),
|
||||
&minecraft_dir,
|
||||
&environment,
|
||||
);
|
||||
let runtime =
|
||||
crate::instance::java::probe_java_in(Path::new(&java), &minecraft_dir, &environment)
|
||||
.await
|
||||
.map_err(|error| LaunchError::JavaCheckFailed {
|
||||
java: java.clone(),
|
||||
required: merged_profile
|
||||
.java_version
|
||||
.as_ref()
|
||||
.map_or(0, |version| version.major_version),
|
||||
reason: error.to_string(),
|
||||
})?;
|
||||
let platform = &runtime.platform;
|
||||
let patches = if config.loader == ModLoader::Forge {
|
||||
patches::load(&minecraft_dir, platform)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(patches) = &patches {
|
||||
merged_profile = resolve::merge_into(patches.profile.clone(), merged_profile);
|
||||
// The embedded version.json is a complete client profile. Appending
|
||||
// the old Forge arguments would run its tweakers a second time.
|
||||
merged_profile.arguments = patches.profile.arguments.clone();
|
||||
merged_profile.inherits_from = None;
|
||||
patches::strip_replaced_libs(&mut merged_profile);
|
||||
main_class = merged_profile
|
||||
.main_class
|
||||
.clone()
|
||||
.expect("validated patch main class");
|
||||
}
|
||||
check_java_version(
|
||||
&java,
|
||||
&runtime,
|
||||
merged_profile
|
||||
.java_version
|
||||
.as_ref()
|
||||
.map(|version| version.major_version),
|
||||
)?;
|
||||
let rule_ctx = RuleContext {
|
||||
os_name: platform.os_name,
|
||||
os_version: &platform.os_version,
|
||||
arch: &platform.arch,
|
||||
features: ¤t_features,
|
||||
};
|
||||
let asset_index_id = merged_profile
|
||||
.asset_index
|
||||
.as_ref()
|
||||
.map(|index| index.id.clone())
|
||||
.unwrap_or_default();
|
||||
let natives_dir = platform.natives_directory(meta_dir, &config.game_version);
|
||||
|
||||
// Forge installers can place libraries in the instance instead of the shared cache.
|
||||
let has_local_libs =
|
||||
matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge) && patches.is_none();
|
||||
let local_lib_dir = minecraft_dir.join("libraries");
|
||||
let library_directory = if has_local_libs {
|
||||
&local_lib_dir
|
||||
@@ -480,6 +517,35 @@ pub async fn build_launch_invocation(
|
||||
&lib_dir
|
||||
};
|
||||
|
||||
let mut to_download = Vec::new();
|
||||
for library in &merged_profile.libraries {
|
||||
if library
|
||||
.rules
|
||||
.as_ref()
|
||||
.is_some_and(|conditions| !rules::evaluate(conditions, &rule_ctx))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// Installer-owned artifacts are already in the instance's library directory.
|
||||
let local = has_local_libs
|
||||
&& crate::net::mojang::library_artifact_path(library)?
|
||||
.is_some_and(|path| local_lib_dir.join(path).is_file());
|
||||
let mut library = library.clone();
|
||||
if local && let Some(downloads) = &mut library.downloads {
|
||||
downloads.artifact = None;
|
||||
}
|
||||
to_download.push(library);
|
||||
}
|
||||
crate::net::mojang::download_profile_libraries(
|
||||
&crate::net::HttpClient::new(),
|
||||
&to_download,
|
||||
&lib_dir,
|
||||
&natives_dir,
|
||||
platform,
|
||||
¤t_features,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut classpath: Vec<PathBuf> = Vec::new();
|
||||
for lib in &merged_profile.libraries {
|
||||
if let Some(rules) = &lib.rules
|
||||
@@ -488,25 +554,10 @@ pub async fn build_launch_invocation(
|
||||
continue;
|
||||
}
|
||||
|
||||
// resolve a relative path for this library. prefer downloads.artifact.path
|
||||
// when present (vanilla-style), fall back to maven_coord_to_path(name)
|
||||
// for loader-style entries that only have a coord.
|
||||
let rel: PathBuf = match lib
|
||||
.downloads
|
||||
.as_ref()
|
||||
.and_then(|d| d.artifact.as_ref())
|
||||
.map(|a| PathBuf::from(&a.path))
|
||||
.or_else(|| {
|
||||
crate::instance::loader::maven::maven_coord_to_path(&lib.name).map(PathBuf::from)
|
||||
}) {
|
||||
Some(p) => p,
|
||||
None => continue,
|
||||
let Some(rel) = crate::net::mojang::library_artifact_path(lib)? else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// for forge/neoforge, the installer drops some libs (notably the
|
||||
// bootstrap library) into <instance>/.minecraft/libraries/ rather
|
||||
// than the shared meta cache. check there first regardless of
|
||||
// whether the lib has a downloads.artifact entry.
|
||||
if has_local_libs {
|
||||
let in_local = local_lib_dir.join(&rel);
|
||||
if in_local.exists() {
|
||||
@@ -524,14 +575,10 @@ pub async fn build_launch_invocation(
|
||||
.join(format!("{}.jar", config.game_version)),
|
||||
);
|
||||
|
||||
// apply loader-specific patches (lwjgl3ify for old forge on java 9+)
|
||||
let (patch_jvm_args, main_class, extra_args) = if matches!(config.loader, ModLoader::Forge) {
|
||||
match patches::apply(&minecraft_dir, &lib_dir, &mut classpath).await {
|
||||
Some(p) => (p.jvm_args, p.main_class, p.extra_args),
|
||||
None => (Vec::new(), main_class, Vec::new()),
|
||||
}
|
||||
let (main_class, extra_args, patch_jvm_args) = if let Some(patches) = patches {
|
||||
patches::apply(patches, &minecraft_dir, &lib_dir, &mut classpath).await?
|
||||
} else {
|
||||
(Vec::new(), main_class, Vec::new())
|
||||
(main_class, Vec::new(), Vec::new())
|
||||
};
|
||||
|
||||
let sep = if cfg!(windows) { ";" } else { ":" };
|
||||
@@ -541,32 +588,7 @@ pub async fn build_launch_invocation(
|
||||
.collect::<Vec<_>>()
|
||||
.join(sep);
|
||||
|
||||
let java = config
|
||||
.java_path
|
||||
.clone()
|
||||
.or_else(|| {
|
||||
crate::config::SETTINGS
|
||||
.read()
|
||||
.paths
|
||||
.effective_java_path()
|
||||
.map(str::to_owned)
|
||||
})
|
||||
.unwrap_or_else(crate::instance::java::detect_java_path);
|
||||
|
||||
check_java_version(
|
||||
&java,
|
||||
merged_profile
|
||||
.java_version
|
||||
.as_ref()
|
||||
.map(|version| version.major_version),
|
||||
)
|
||||
.await?;
|
||||
|
||||
let assets_root = metadata_paths.assets();
|
||||
let natives_dir = metadata_paths
|
||||
.versions()
|
||||
.join(&config.game_version)
|
||||
.join("natives");
|
||||
let version_type = merged_profile.type_.as_deref().unwrap_or("release");
|
||||
let resolution_width = resolution.map(|(width, _)| width.to_string());
|
||||
let resolution_height = resolution.map(|(_, height)| height.to_string());
|
||||
@@ -601,8 +623,7 @@ pub async fn build_launch_invocation(
|
||||
apply_custom_resolution(&mut game_args, resolution);
|
||||
apply_window_mode(&mut game_args, window_mode);
|
||||
|
||||
let (memory_min, memory_max, global_jvm_args, global_environment) = {
|
||||
let settings = crate::config::SETTINGS.read();
|
||||
let (memory_min, memory_max, global_jvm_args) = {
|
||||
(
|
||||
config
|
||||
.memory_min
|
||||
@@ -613,10 +634,12 @@ pub async fn build_launch_invocation(
|
||||
.clone()
|
||||
.unwrap_or_else(|| settings.defaults.memory_max.clone()),
|
||||
settings.defaults.jvm_args.clone(),
|
||||
settings.defaults.environment.clone(),
|
||||
)
|
||||
};
|
||||
let mut jvm_args: Vec<String> = vec![format!("-Xms{memory_min}"), format!("-Xmx{memory_max}")];
|
||||
if merged_profile.arguments.is_none() {
|
||||
jvm_args.push(format!("-Djava.library.path={}", natives_dir.display()));
|
||||
}
|
||||
jvm_args.extend(patch_jvm_args);
|
||||
jvm_args.extend(upstream_jvm_args);
|
||||
jvm_args.extend(global_jvm_args);
|
||||
@@ -625,9 +648,6 @@ pub async fn build_launch_invocation(
|
||||
jvm_args.push(format!("-Dorg.lwjgl.glfw.libname={glfw_path}"));
|
||||
}
|
||||
|
||||
let mut environment = global_environment;
|
||||
environment.extend(config.environment.clone());
|
||||
|
||||
Ok(LaunchInvocation {
|
||||
java,
|
||||
jvm_args,
|
||||
@@ -644,8 +664,12 @@ pub async fn build_launch_invocation(
|
||||
fn command_process(command: &str) -> tokio::process::Command {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let mut process = tokio::process::Command::new("cmd");
|
||||
process.args(["/C", command]);
|
||||
let mut process = tokio::process::Command::new("cmd.exe");
|
||||
// cmd parses shell text rather than CRT argv. /S removes this outer pair
|
||||
// of quotes; raw_arg preserves all quotes and metacharacters inside it.
|
||||
process
|
||||
.args(["/D", "/S", "/C"])
|
||||
.raw_arg(format!("\"{command}\""));
|
||||
process
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
@@ -683,29 +707,66 @@ async fn run_launch_command(
|
||||
.envs(&invocation.environment)
|
||||
.env("INST_NAME", &config.name)
|
||||
.env("INST_ID", &config.name)
|
||||
.env("INST_DIR", instance_dir)
|
||||
.env("INST_DIR", std::path::absolute(instance_dir)?)
|
||||
.env("INST_MC_DIR", &invocation.working_dir)
|
||||
.env("INST_JAVA", &invocation.java)
|
||||
.env("INST_JAVA_ARGS", invocation.jvm_args.join(" "));
|
||||
let output = process
|
||||
.output()
|
||||
.await
|
||||
.map_err(|error| LaunchError::Command {
|
||||
.env("INST_JAVA_ARGS", invocation.jvm_args.join(" "))
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
let (mut child, tree) =
|
||||
process::spawn_owned(&mut process).map_err(|error| LaunchError::Command {
|
||||
phase,
|
||||
reason: error.to_string(),
|
||||
})?;
|
||||
for line in String::from_utf8_lossy(&output.stdout).lines() {
|
||||
tracing::info!("[{}] [{}] {}", config.name, phase, line);
|
||||
let (sender, mut receiver) = tokio::sync::mpsc::channel(64);
|
||||
let mut readers = tokio::task::JoinSet::new();
|
||||
if let Some(stdout) = child.stdout.take() {
|
||||
readers.spawn(output::capture(
|
||||
stdout,
|
||||
parser::LogStream::Stdout,
|
||||
sender.clone(),
|
||||
Default::default(),
|
||||
));
|
||||
}
|
||||
for line in String::from_utf8_lossy(&output.stderr).lines() {
|
||||
tracing::warn!("[{}] [{}] {}", config.name, phase, line);
|
||||
if let Some(stderr) = child.stderr.take() {
|
||||
readers.spawn(output::capture(
|
||||
stderr,
|
||||
parser::LogStream::Stderr,
|
||||
sender.clone(),
|
||||
Default::default(),
|
||||
));
|
||||
}
|
||||
if output.status.success() {
|
||||
drop(sender);
|
||||
let log = |stream, line| match stream {
|
||||
parser::LogStream::Stdout => tracing::info!("[{}] [{}] {}", config.name, phase, line),
|
||||
parser::LogStream::Stderr => tracing::warn!("[{}] [{}] {}", config.name, phase, line),
|
||||
};
|
||||
let status = loop {
|
||||
tokio::select! {
|
||||
status = child.wait() => break status?,
|
||||
Some((stream, line)) = receiver.recv() => log(stream, line),
|
||||
}
|
||||
};
|
||||
let drain_deadline = tokio::time::sleep(std::time::Duration::from_secs(1));
|
||||
tokio::pin!(drain_deadline);
|
||||
loop {
|
||||
tokio::select! {
|
||||
line = receiver.recv() => match line { Some((stream, line)) => log(stream, line), None => break },
|
||||
_ = &mut drain_deadline => { tracing::warn!("[{phase}] Output pipes remained open after command exit"); break; },
|
||||
}
|
||||
}
|
||||
// Normal completion can intentionally leave a background command running.
|
||||
// Cancellation before this point still drops the armed process-tree guard.
|
||||
tree.detach().map_err(|error| LaunchError::Command {
|
||||
phase,
|
||||
reason: error.to_string(),
|
||||
})?;
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(LaunchError::Command {
|
||||
phase,
|
||||
reason: output.status.to_string(),
|
||||
reason: status.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -729,6 +790,13 @@ pub async fn launch(
|
||||
quick_play_world: Option<&str>,
|
||||
) -> Result<(), LaunchError> {
|
||||
let name = config.name.clone();
|
||||
let instance_lock = crate::instance::runtime::lock_instance(instances_dir, &name)
|
||||
.map_err(|error| LaunchError::Parse(error.to_string()))?;
|
||||
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
|
||||
let mut kill_rx = Some(kill_rx);
|
||||
crate::instance::runtime::register_kill(&name, kill_tx);
|
||||
let launch_cleanup = LaunchCleanup(name.clone());
|
||||
crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Authenticating);
|
||||
|
||||
let mut account_store = crate::auth::AccountStore::load();
|
||||
account_store
|
||||
@@ -749,7 +817,10 @@ pub async fn launch(
|
||||
}
|
||||
|
||||
let (token, new_refresh, new_expires) = match acc.account_type {
|
||||
AccountType::Microsoft => match crate::auth::refresh_and_get_token(&acc).await {
|
||||
AccountType::Microsoft => match tokio::select! {
|
||||
result = crate::auth::refresh_and_get_token(&acc) => result,
|
||||
_ = wait_for_kill(&mut kill_rx) => return Err(LaunchError::Cancelled),
|
||||
} {
|
||||
Ok(triple) => triple,
|
||||
Err(e) => return Err(LaunchError::Auth(format!("Authentication failed: {e}"))),
|
||||
},
|
||||
@@ -770,8 +841,10 @@ pub async fn launch(
|
||||
user_type,
|
||||
};
|
||||
|
||||
let invocation =
|
||||
build_launch_invocation(config, instances_dir, meta_dir, &auth, quick_play_world).await?;
|
||||
let invocation = tokio::select! {
|
||||
result = build_launch_invocation(config, instances_dir, meta_dir, &auth, quick_play_world) => result?,
|
||||
_ = wait_for_kill(&mut kill_rx) => return Err(LaunchError::Cancelled),
|
||||
};
|
||||
let instance_dir = instances_dir.join(&config.name);
|
||||
tracing::debug!(
|
||||
"[{}] Prepared launch invocation: working_dir={} classpath_entries={} jvm_args={} extra_args={} game_args={} main_class={}",
|
||||
@@ -788,21 +861,20 @@ pub async fn launch(
|
||||
meta_dir,
|
||||
&invocation.working_dir,
|
||||
)?;
|
||||
if let Err(error) = run_launch_command(
|
||||
if let Err(error) = tokio::select! {
|
||||
result = run_launch_command(
|
||||
"Pre-launch",
|
||||
&config.pre_launch_command,
|
||||
config,
|
||||
&invocation,
|
||||
&instance_dir,
|
||||
)
|
||||
.await
|
||||
{
|
||||
) => result,
|
||||
_ = wait_for_kill(&mut kill_rx) => Err(LaunchError::Cancelled),
|
||||
} {
|
||||
finish_config_sync(config_sync_lock, &invocation.working_dir, &name);
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
let (kill_tx, kill_rx) = tokio::sync::oneshot::channel::<()>();
|
||||
crate::instance::runtime::register_kill(&name, kill_tx);
|
||||
crate::instance::runtime::set_state(&name, crate::instance::runtime::RunState::Starting);
|
||||
tracing::info!(
|
||||
"[{}] Starting Minecraft ({} {})",
|
||||
@@ -835,6 +907,7 @@ pub async fn launch(
|
||||
cmd.envs(&invocation.environment);
|
||||
cmd.stdout(std::process::Stdio::piped());
|
||||
cmd.stderr(std::process::Stdio::piped());
|
||||
cmd.kill_on_drop(true);
|
||||
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
@@ -870,11 +943,11 @@ pub async fn launch(
|
||||
let invocation_for_post_exit = invocation.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
use std::io::Write;
|
||||
let _instance_lock = instance_lock;
|
||||
let _launch_cleanup = launch_cleanup;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::{Duration, sleep};
|
||||
use tokio::time::Duration;
|
||||
|
||||
use crate::instance::launch::parser::{LogStream, MinecraftLogParser};
|
||||
|
||||
@@ -887,6 +960,9 @@ pub async fn launch(
|
||||
let parser_task = tokio::spawn(async move {
|
||||
let mut parser = MinecraftLogParser::new();
|
||||
let idle_flush = Duration::from_millis(150);
|
||||
let mut flush_interval = tokio::time::interval(idle_flush);
|
||||
flush_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
flush_interval.tick().await;
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
@@ -900,7 +976,7 @@ pub async fn launch(
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
_ = sleep(idle_flush), if parser.has_pending() => {
|
||||
_ = flush_interval.tick(), if parser.has_pending() => {
|
||||
if let Some(event) = parser.flush() {
|
||||
emit_parsed_instance_log(&parser_name, event);
|
||||
}
|
||||
@@ -913,47 +989,28 @@ pub async fn launch(
|
||||
}
|
||||
});
|
||||
|
||||
let mut readers = tokio::task::JoinSet::new();
|
||||
if let Some(stdout) = child.stdout.take() {
|
||||
let w = log_writer.clone();
|
||||
let tx = log_tx.clone();
|
||||
let mut lines = tokio::io::BufReader::new(stdout).lines();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if let Ok(mut f) = w.lock()
|
||||
&& let Some(f) = f.as_mut()
|
||||
{
|
||||
let _ = writeln!(f, "{}", line);
|
||||
}
|
||||
if tx.send((LogStream::Stdout, line)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
tracing::trace!("Minecraft stdout capture task ended");
|
||||
});
|
||||
readers.spawn(output::capture(
|
||||
stdout,
|
||||
LogStream::Stdout,
|
||||
log_tx.clone(),
|
||||
log_writer.clone(),
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(stderr) = child.stderr.take() {
|
||||
let w = log_writer.clone();
|
||||
let tx = log_tx.clone();
|
||||
let mut lines = tokio::io::BufReader::new(stderr).lines();
|
||||
tokio::spawn(async move {
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if let Ok(mut f) = w.lock()
|
||||
&& let Some(f) = f.as_mut()
|
||||
{
|
||||
let _ = writeln!(f, "{}", line);
|
||||
}
|
||||
if tx.send((LogStream::Stderr, line)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
tracing::trace!("Minecraft stderr capture task ended");
|
||||
});
|
||||
readers.spawn(output::capture(
|
||||
stderr,
|
||||
LogStream::Stderr,
|
||||
log_tx.clone(),
|
||||
log_writer.clone(),
|
||||
));
|
||||
}
|
||||
drop(log_tx);
|
||||
|
||||
let (code, killed_by_user) = tokio::select! {
|
||||
_ = kill_rx => {
|
||||
_ = wait_for_kill(&mut kill_rx) => {
|
||||
tracing::info!("[{}] Kill requested, terminating process", name_for_task);
|
||||
let _ = child.kill().await;
|
||||
let _ = child.wait().await;
|
||||
@@ -963,23 +1020,46 @@ pub async fn launch(
|
||||
(result.ok().and_then(|s| s.code()), false)
|
||||
}
|
||||
};
|
||||
if tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while readers.join_next().await.is_some() {}
|
||||
})
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
tracing::warn!("Minecraft output pipes remained open after process exit");
|
||||
readers.abort_all();
|
||||
while readers.join_next().await.is_some() {}
|
||||
}
|
||||
let _ = parser_task.await;
|
||||
tracing::info!("[{}] Exited with code {:?}", name_for_task, code);
|
||||
|
||||
if let Err(error) = run_launch_command(
|
||||
"Post-exit",
|
||||
&post_exit_command,
|
||||
&config_for_post_exit,
|
||||
&invocation_for_post_exit,
|
||||
&instance_dir_owned,
|
||||
)
|
||||
.await
|
||||
if !killed_by_user
|
||||
&& let Err(error) = tokio::select! {
|
||||
result = run_launch_command(
|
||||
"Post-exit",
|
||||
&post_exit_command,
|
||||
&config_for_post_exit,
|
||||
&invocation_for_post_exit,
|
||||
&instance_dir_owned,
|
||||
) => result,
|
||||
_ = wait_for_kill(&mut kill_rx) => Err(LaunchError::Cancelled),
|
||||
}
|
||||
{
|
||||
tracing::warn!("[{}] {}", name_for_task, error);
|
||||
crate::feedback::errors::push_message(tracing::Level::WARN, error.to_string());
|
||||
}
|
||||
|
||||
finish_config_sync(config_sync_lock, &minecraft_dir_owned, &name_for_task);
|
||||
let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned);
|
||||
if let Err(e) = manager.touch_last_played(&name_for_task) {
|
||||
tracing::warn!(
|
||||
"Failed to update last_played for '{}': {}",
|
||||
name_for_task,
|
||||
e
|
||||
);
|
||||
}
|
||||
crate::instance::runtime::push_last_played(&name_for_task, chrono::Utc::now());
|
||||
crate::instance::runtime::cleanup_kill_sender(&name_for_task);
|
||||
if code == Some(0) || killed_by_user {
|
||||
crate::instance::runtime::remove(&name_for_task);
|
||||
tracing::debug!(
|
||||
@@ -1004,17 +1084,6 @@ pub async fn launch(
|
||||
pushed_at: std::time::Instant::now(),
|
||||
});
|
||||
}
|
||||
|
||||
let manager = crate::instance::InstanceManager::new(instances_dir_owned, meta_dir_owned);
|
||||
if let Err(e) = manager.touch_last_played(&name_for_task) {
|
||||
tracing::warn!(
|
||||
"Failed to update last_played for '{}': {}",
|
||||
name_for_task,
|
||||
e
|
||||
);
|
||||
}
|
||||
crate::instance::runtime::push_last_played(&name_for_task, chrono::Utc::now());
|
||||
crate::instance::runtime::cleanup_kill_sender(&name_for_task);
|
||||
});
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt};
|
||||
|
||||
use super::parser::LogStream;
|
||||
|
||||
pub(super) type LogWriter = Arc<Mutex<Option<std::fs::File>>>;
|
||||
|
||||
pub(super) async fn capture(
|
||||
reader: impl tokio::io::AsyncRead + Unpin,
|
||||
stream: LogStream,
|
||||
sender: tokio::sync::mpsc::Sender<(LogStream, String)>,
|
||||
writer: LogWriter,
|
||||
) {
|
||||
use std::io::Write;
|
||||
let mut reader = tokio::io::BufReader::new(reader);
|
||||
loop {
|
||||
let mut bytes = Vec::new();
|
||||
match (&mut reader)
|
||||
.take(64 * 1024)
|
||||
.read_until(b'\n', &mut bytes)
|
||||
.await
|
||||
{
|
||||
Ok(0) => break,
|
||||
Ok(_) => {}
|
||||
Err(error) => {
|
||||
tracing::warn!("Minecraft output read failed: {error}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Ok(mut file) = writer.lock()
|
||||
&& let Some(file) = file.as_mut()
|
||||
&& let Err(error) = file.write_all(&bytes)
|
||||
{
|
||||
tracing::warn!("Minecraft log write failed: {error}");
|
||||
}
|
||||
let line = String::from_utf8_lossy(&bytes)
|
||||
.trim_end_matches(['\r', '\n'])
|
||||
.to_owned();
|
||||
if sender.send((stream, line)).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn invalid_utf8_and_long_lines_keep_following_output() {
|
||||
let mut bytes = vec![b'x'; 128 * 1024];
|
||||
bytes.extend_from_slice(b"\ninvalid \xff\nlast\n");
|
||||
let (sender, mut receiver) = tokio::sync::mpsc::channel(8);
|
||||
capture(
|
||||
bytes.as_slice(),
|
||||
LogStream::Stdout,
|
||||
sender,
|
||||
Default::default(),
|
||||
)
|
||||
.await;
|
||||
let mut lines = Vec::new();
|
||||
while let Some((_, line)) = receiver.recv().await {
|
||||
lines.push(line);
|
||||
}
|
||||
assert!(lines.iter().all(|line| line.len() <= 64 * 1024));
|
||||
assert!(lines.iter().any(|line| line == "invalid �"));
|
||||
assert_eq!(lines.last().unwrap(), "last");
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,10 @@ impl MinecraftLogParser {
|
||||
|
||||
// only hard starts split events. this keeps stacktraces and native
|
||||
// loader bursts together even when they arrive one line at a time.
|
||||
if should_split(current.kind, analysis.kind) {
|
||||
if should_split(current.kind, analysis.kind)
|
||||
|| current.lines.len() >= 128
|
||||
|| current.lines.iter().map(String::len).sum::<usize>() >= 64 * 1024
|
||||
{
|
||||
let finished = self.current.take().map(finish_event);
|
||||
self.current = Some(PendingEvent::new(stream, line, normalized, analysis));
|
||||
finished.into_iter().collect()
|
||||
|
||||
+210
-160
@@ -7,54 +7,124 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::LaunchError;
|
||||
use crate::launch_profile::{model::LaunchProfile, system::JavaPlatform};
|
||||
|
||||
const LOG4J_FIXED_BASE: &str = "https://files.prismlauncher.org/maven/org/apache/logging/log4j";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct LwjglifyPatches {
|
||||
pub jvm_args: Vec<String>,
|
||||
pub main_class: String,
|
||||
// extra args inserted before game args (used by the shim to pass
|
||||
// the real main class name)
|
||||
pub extra_args: Vec<String>,
|
||||
pub profile: LaunchProfile,
|
||||
patches_path: PathBuf,
|
||||
}
|
||||
|
||||
pub async fn apply(
|
||||
pub fn load(
|
||||
minecraft_dir: &Path,
|
||||
lib_dir: &Path,
|
||||
classpath: &mut Vec<PathBuf>,
|
||||
) -> Option<LwjglifyPatches> {
|
||||
platform: &JavaPlatform,
|
||||
) -> Result<Option<LwjglifyPatches>, LaunchError> {
|
||||
use sha1::Digest;
|
||||
use std::io::Read;
|
||||
|
||||
let mods_dir = minecraft_dir.join("mods");
|
||||
let lwjgl3ify_jar = find_lwjgl3ify_jar(&mods_dir)?;
|
||||
let Some(lwjgl3ify_jar) = find_lwjgl3ify_jar(&mods_dir)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
let file = std::fs::File::open(&lwjgl3ify_jar)?;
|
||||
let mut archive = zip::ZipArchive::new(file).map_err(|error| {
|
||||
LaunchError::Parse(format!(
|
||||
"Invalid lwjgl3ify jar {}: {error}",
|
||||
lwjgl3ify_jar.display()
|
||||
))
|
||||
})?;
|
||||
let entry = archive
|
||||
.by_name("me/eigenraven/lwjgl3ify/relauncher/version.json")
|
||||
.map_err(|error| {
|
||||
LaunchError::Parse(format!(
|
||||
"lwjgl3ify bundled client profile is missing in {}: {error}",
|
||||
lwjgl3ify_jar.display()
|
||||
))
|
||||
})?;
|
||||
let mut profile: LaunchProfile = serde_json::from_reader(entry)?;
|
||||
if profile
|
||||
.main_class
|
||||
.as_deref()
|
||||
.is_none_or(|main| main.trim().is_empty())
|
||||
|| profile.arguments.is_none()
|
||||
|| profile
|
||||
.java_version
|
||||
.as_ref()
|
||||
.is_none_or(|version| version.major_version == 0)
|
||||
{
|
||||
return Err(LaunchError::Parse(
|
||||
"lwjgl3ify bundled client profile is missing mainClass, arguments or javaVersion"
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
for lib in &profile.libraries {
|
||||
if lib
|
||||
.downloads
|
||||
.as_ref()
|
||||
.is_none_or(|downloads| downloads.artifact.is_none() && lib.natives.is_none())
|
||||
{
|
||||
return Err(LaunchError::Parse(format!(
|
||||
"lwjgl3ify bundled library {} is missing download metadata",
|
||||
lib.name
|
||||
)));
|
||||
}
|
||||
}
|
||||
select_lwjgl_natives(&mut profile, platform)?;
|
||||
|
||||
let patch_artifact = profile
|
||||
.libraries
|
||||
.iter()
|
||||
.find(|lib| lib.name.ends_with(":forgePatches"))
|
||||
.and_then(|lib| lib.downloads.as_ref())
|
||||
.and_then(|downloads| downloads.artifact.as_ref())
|
||||
.ok_or_else(|| {
|
||||
LaunchError::Parse(
|
||||
"lwjgl3ify bundled profile is missing the forgePatches artifact".into(),
|
||||
)
|
||||
})?;
|
||||
let mut payload = Vec::new();
|
||||
archive
|
||||
.by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip")
|
||||
.map_err(|error| {
|
||||
LaunchError::Parse(format!(
|
||||
"lwjgl3ify forgePatches payload is missing: {error}"
|
||||
))
|
||||
})?
|
||||
.read_to_end(&mut payload)?;
|
||||
if payload.len() as u64 != patch_artifact.size
|
||||
|| !format!("{:x}", sha1::Sha1::digest(&payload)).eq_ignore_ascii_case(&patch_artifact.sha1)
|
||||
{
|
||||
return Err(LaunchError::Parse(
|
||||
"lwjgl3ify embedded forgePatches does not match its bundled profile".into(),
|
||||
));
|
||||
}
|
||||
profile
|
||||
.libraries
|
||||
.retain(|lib| !lib.name.ends_with(":forgePatches"));
|
||||
|
||||
// rfb only scans jars for plugin metadata. keeping the extracted
|
||||
// forgePatches payload as a zip makes it skip rfb-asm-safety and
|
||||
// rfb-modern-java, which GTNH needs on modern Java.
|
||||
let patches_dest = minecraft_dir.join(".forge-patches.jar");
|
||||
let patches_path = minecraft_dir.join(".forge-patches.jar");
|
||||
crate::storage::write_atomic(&patches_path, &payload)?;
|
||||
Ok(Some(LwjglifyPatches {
|
||||
profile,
|
||||
patches_path,
|
||||
}))
|
||||
}
|
||||
|
||||
if let Err(e) = extract_forge_patches(&lwjgl3ify_jar, &patches_dest) {
|
||||
tracing::warn!("Failed to extract lwjgl3ify forge patches: {e}");
|
||||
return None;
|
||||
}
|
||||
|
||||
classpath.insert(0, patches_dest.clone());
|
||||
|
||||
let mut jvm_args = parse_add_opens(&patches_dest).unwrap_or_default();
|
||||
|
||||
// RFB requires its own classloader to be the system classloader, and
|
||||
// its Main class handles bootstrapping into launchwrapper.
|
||||
// the other flags match lwjgl3ify's java9args.txt.
|
||||
jvm_args.extend([
|
||||
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader"
|
||||
.to_string(),
|
||||
"-Dfile.encoding=UTF-8".to_string(),
|
||||
]);
|
||||
|
||||
// forge patches replace launchwrapper, asm, and old lwjgl2.
|
||||
// lwjgl3ify redirects lwjgl2 calls to lwjgl3 at runtime, so lwjgl3
|
||||
// must be on the classpath (matching what prism does).
|
||||
strip_replaced_libs(classpath);
|
||||
add_lwjgl3(lib_dir, classpath);
|
||||
|
||||
replace_log4j_fixed(lib_dir, classpath).await;
|
||||
pub async fn apply(
|
||||
patches: LwjglifyPatches,
|
||||
minecraft_dir: &Path,
|
||||
lib_dir: &Path,
|
||||
classpath: &mut Vec<PathBuf>,
|
||||
) -> Result<(String, Vec<String>, Vec<String>), LaunchError> {
|
||||
classpath.insert(0, patches.patches_path);
|
||||
replace_log4j_fixed(lib_dir, classpath).await?;
|
||||
let mut jvm_args = Vec::new();
|
||||
|
||||
// on java 24+, SecurityManager.getClassContext() was reimplemented to use
|
||||
// StackWalker. log4j 2.0-beta9's ThrowableProxy calls getClassContext() to
|
||||
@@ -63,7 +133,7 @@ pub async fn apply(
|
||||
// ThrowableProxy... infinite recursion. we break the loop by providing a
|
||||
// log4j config that sets the root level to INFO, so the debug() call in
|
||||
// LaunchClassLoader is a no-op and never creates a ThrowableProxy.
|
||||
write_log4j_config(minecraft_dir, &mut jvm_args);
|
||||
write_log4j_config(minecraft_dir, &mut jvm_args)?;
|
||||
|
||||
// RfbSystemClassLoader discovers plugins differently depending on whether
|
||||
// the main class is loaded by the JVM directly or through the system
|
||||
@@ -72,81 +142,57 @@ pub async fn apply(
|
||||
// ClassCircularityErrors. we use a tiny shim jar that loads the real main
|
||||
// class through ClassLoader.getSystemClassLoader().loadClass(), matching
|
||||
// how prism's EntryPoint does it.
|
||||
let shim_path = deploy_shim(minecraft_dir);
|
||||
let shim_path = deploy_shim(minecraft_dir)?;
|
||||
classpath.insert(0, shim_path);
|
||||
|
||||
Some(LwjglifyPatches {
|
||||
Ok((
|
||||
"RmclShim".to_owned(),
|
||||
vec![
|
||||
patches
|
||||
.profile
|
||||
.main_class
|
||||
.expect("validated client main class"),
|
||||
],
|
||||
jvm_args,
|
||||
main_class: "RmclShim".to_string(),
|
||||
extra_args: vec!["com.gtnewhorizons.retrofuturabootstrap.Main".to_string()],
|
||||
})
|
||||
))
|
||||
}
|
||||
|
||||
const SHIM_JAR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rmcl-shim.jar"));
|
||||
|
||||
fn deploy_shim(minecraft_dir: &Path) -> PathBuf {
|
||||
fn deploy_shim(minecraft_dir: &Path) -> std::io::Result<PathBuf> {
|
||||
let dest = minecraft_dir.join(".rmcl-shim.jar");
|
||||
if let Err(e) = std::fs::write(&dest, SHIM_JAR) {
|
||||
tracing::warn!("Failed to write rmcl-shim.jar: {e}");
|
||||
}
|
||||
dest
|
||||
crate::storage::write_atomic(&dest, SHIM_JAR)?;
|
||||
Ok(dest)
|
||||
}
|
||||
|
||||
fn find_lwjgl3ify_jar(mods_dir: &Path) -> Option<PathBuf> {
|
||||
let entries = std::fs::read_dir(mods_dir).ok()?;
|
||||
for entry in entries.flatten() {
|
||||
fn find_lwjgl3ify_jar(mods_dir: &Path) -> std::io::Result<Option<PathBuf>> {
|
||||
let entries = match std::fs::read_dir(mods_dir) {
|
||||
Ok(entries) => entries,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let mut found = None;
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name();
|
||||
let name = name.to_string_lossy();
|
||||
if name.starts_with("lwjgl3ify") && name.ends_with(".jar") {
|
||||
return Some(entry.path());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn extract_forge_patches(lwjgl3ify_jar: &Path, dest: &Path) -> Result<(), std::io::Error> {
|
||||
use std::io::Read;
|
||||
|
||||
let file = std::fs::File::open(lwjgl3ify_jar)?;
|
||||
let mut archive = zip::ZipArchive::new(file)
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
|
||||
let mut entry = archive
|
||||
.by_name("me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip")
|
||||
.map_err(|e| std::io::Error::new(std::io::ErrorKind::NotFound, e))?;
|
||||
let mut buf = Vec::new();
|
||||
entry.read_to_end(&mut buf)?;
|
||||
std::fs::write(dest, &buf)
|
||||
}
|
||||
|
||||
fn parse_add_opens(patches_archive: &Path) -> Option<Vec<String>> {
|
||||
use std::io::Read;
|
||||
|
||||
let file = std::fs::File::open(patches_archive).ok()?;
|
||||
let mut archive = zip::ZipArchive::new(file).ok()?;
|
||||
let mut entry = archive.by_name("META-INF/MANIFEST.MF").ok()?;
|
||||
let mut manifest = String::new();
|
||||
entry.read_to_string(&mut manifest).ok()?;
|
||||
|
||||
// manifest continuation lines start with a single space
|
||||
let manifest = manifest.replace("\r\n ", "").replace("\n ", "");
|
||||
|
||||
let mut args = Vec::new();
|
||||
for line in manifest.lines() {
|
||||
if let Some(value) = line.strip_prefix("Add-Opens: ") {
|
||||
for module_package in value.split_whitespace() {
|
||||
args.push("--add-opens".to_string());
|
||||
args.push(format!("{module_package}=ALL-UNNAMED"));
|
||||
if found.is_some() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"Multiple lwjgl3ify jars found in mods",
|
||||
));
|
||||
}
|
||||
found = Some(entry.path());
|
||||
}
|
||||
}
|
||||
|
||||
Some(args)
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
// strips libraries from the classpath that are replaced by forge patches
|
||||
// or not needed with lwjgl3ify. matches what prism's component system does:
|
||||
// no old lwjgl2, no vanilla launchwrapper/asm, no extra vanilla-only libs.
|
||||
fn strip_replaced_libs(classpath: &mut Vec<PathBuf>) {
|
||||
pub fn strip_replaced_libs(profile: &mut LaunchProfile) {
|
||||
let replaced = [
|
||||
"launchwrapper-",
|
||||
"asm-all-",
|
||||
@@ -157,76 +203,83 @@ fn strip_replaced_libs(classpath: &mut Vec<PathBuf>) {
|
||||
"guava-15.",
|
||||
];
|
||||
|
||||
classpath.retain(|entry| {
|
||||
let name = entry
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy())
|
||||
.unwrap_or_default();
|
||||
let dominated = replaced.iter().any(|prefix| name.starts_with(prefix));
|
||||
profile.libraries.retain(|lib| {
|
||||
if lib.name.starts_with("org.lwjgl.lwjgl:") {
|
||||
return false;
|
||||
}
|
||||
let name = lib.name.split(':').collect::<Vec<_>>();
|
||||
let filename = match name.as_slice() {
|
||||
[_, artifact, version, ..] => format!("{artifact}-{version}"),
|
||||
_ => return true,
|
||||
};
|
||||
let dominated = replaced.iter().any(|prefix| filename.starts_with(prefix));
|
||||
if dominated {
|
||||
tracing::info!("Stripping {name} from classpath (replaced by forge-patches)");
|
||||
tracing::info!("Stripping {} (replaced by forge-patches)", lib.name);
|
||||
}
|
||||
!dominated
|
||||
});
|
||||
}
|
||||
|
||||
// adds lwjgl 3.3.3 to the classpath. lwjgl3ify redirects old lwjgl2 calls
|
||||
// to lwjgl3 at runtime, but the lwjgl3 jars need to be on the system
|
||||
// classpath for this to work. prism includes these via its org.lwjgl3
|
||||
// component; we add them from the meta library cache.
|
||||
fn add_lwjgl3(lib_dir: &Path, classpath: &mut Vec<PathBuf>) {
|
||||
let lwjgl3_modules = [
|
||||
"lwjgl",
|
||||
"lwjgl-freetype",
|
||||
"lwjgl-glfw",
|
||||
"lwjgl-jemalloc",
|
||||
"lwjgl-openal",
|
||||
"lwjgl-opengl",
|
||||
"lwjgl-stb",
|
||||
"lwjgl-tinyfd",
|
||||
];
|
||||
|
||||
let os_classifier = match std::env::consts::OS {
|
||||
"macos" => "natives-macos",
|
||||
"windows" => "natives-windows",
|
||||
_ => "natives-linux",
|
||||
// The bundled profile names natives as separate Maven artifacts and uses
|
||||
// OS-only rules for multiple CPU variants. Select exactly the selected JVM's variant.
|
||||
fn select_lwjgl_natives(
|
||||
profile: &mut LaunchProfile,
|
||||
platform: &JavaPlatform,
|
||||
) -> Result<(), LaunchError> {
|
||||
let classifier = match (platform.os_name, platform.arch.as_str(), platform.bitness) {
|
||||
("osx", "arm64", 64) => "natives-macos-arm64",
|
||||
("osx", "x86_64", 64) => "natives-macos",
|
||||
("windows", "arm64", 64) => "natives-windows-arm64",
|
||||
("windows", "x86", 32) => "natives-windows-x86",
|
||||
("windows", "x86_64", 64) => "natives-windows",
|
||||
("linux", "arm64", 64) => "natives-linux-arm64",
|
||||
("linux", "arm", 32) => "natives-linux-arm32",
|
||||
("linux", "ppc64le", 64) => "natives-linux-ppc64le",
|
||||
("linux", "x86_64", 64) => "natives-linux",
|
||||
_ => {
|
||||
return Err(LaunchError::Parse(format!(
|
||||
"lwjgl3ify does not support Java {} {} ({}-bit)",
|
||||
platform.os_name, platform.arch, platform.bitness
|
||||
)));
|
||||
}
|
||||
};
|
||||
|
||||
// insert lwjgl3 jars right after forge patches (position 1+)
|
||||
let mut insert_pos = 1.min(classpath.len());
|
||||
for module in &lwjgl3_modules {
|
||||
let base = if *module == "lwjgl" {
|
||||
lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar")
|
||||
} else {
|
||||
lib_dir.join(format!("org/lwjgl/{0}/3.3.3/{0}-3.3.3.jar", module))
|
||||
};
|
||||
if base.exists() {
|
||||
classpath.insert(insert_pos, base);
|
||||
insert_pos += 1;
|
||||
let native = |name: &str| -> Option<(String, String)> {
|
||||
let parts: Vec<_> = name.split(':').collect();
|
||||
match parts.as_slice() {
|
||||
["org.lwjgl", artifact, _, variant] if variant.starts_with("natives-") => {
|
||||
Some(((*artifact).to_owned(), (*variant).to_owned()))
|
||||
}
|
||||
["org.lwjgl", artifact, _] => artifact
|
||||
.split_once("-natives-")
|
||||
.map(|(module, variant)| (module.to_owned(), format!("natives-{variant}"))),
|
||||
_ => None,
|
||||
}
|
||||
|
||||
let natives = if *module == "lwjgl" {
|
||||
lib_dir.join(format!(
|
||||
"org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3-{os_classifier}.jar"
|
||||
))
|
||||
} else {
|
||||
lib_dir.join(format!(
|
||||
"org/lwjgl/{0}/3.3.3/{0}-3.3.3-{1}.jar",
|
||||
module, os_classifier
|
||||
))
|
||||
};
|
||||
let mut native_modules = std::collections::HashSet::new();
|
||||
let mut selected = std::collections::HashSet::new();
|
||||
profile.libraries.retain(|lib| {
|
||||
let Some((module, variant)) = native(&lib.name) else {
|
||||
return true;
|
||||
};
|
||||
if natives.exists() {
|
||||
classpath.insert(insert_pos, natives);
|
||||
insert_pos += 1;
|
||||
native_modules.insert(module.clone());
|
||||
if variant == classifier {
|
||||
selected.insert(module);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
if let Some(missing) = native_modules.difference(&selected).next() {
|
||||
return Err(LaunchError::Parse(format!(
|
||||
"lwjgl3ify bundled profile has no {classifier} for {missing}"
|
||||
)));
|
||||
}
|
||||
|
||||
tracing::info!("Added {} LWJGL 3.3.3 jars to classpath", insert_pos - 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Suppresses LaunchClassLoader's debug() call to avoid the
|
||||
// ThrowableProxy -> SecurityManager -> StackWalker recursion on Java 24+.
|
||||
fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) {
|
||||
fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) -> std::io::Result<()> {
|
||||
let config_path = minecraft_dir.join(".rmcl-log4j2.xml");
|
||||
let config = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Configuration status="WARN">
|
||||
@@ -255,15 +308,13 @@ fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) {
|
||||
</Configuration>
|
||||
"#;
|
||||
|
||||
if let Err(e) = std::fs::write(&config_path, config) {
|
||||
tracing::warn!("Failed to write log4j2 config: {e}");
|
||||
return;
|
||||
}
|
||||
crate::storage::write_atomic(&config_path, config.as_bytes())?;
|
||||
|
||||
jvm_args.push(format!(
|
||||
"-Dlog4j.configurationFile={}",
|
||||
config_path.display()
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// replaces log4j-api and log4j-core 2.0-beta9 in the classpath with
|
||||
@@ -272,7 +323,7 @@ fn write_log4j_config(minecraft_dir: &Path, jvm_args: &mut Vec<String>) {
|
||||
// on java 24+ uses StackWalker internally, triggering class loading
|
||||
// through LaunchClassLoader, which triggers more logging, infinite
|
||||
// recursion, stack overflow. the fixed builds patch this out.
|
||||
async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
|
||||
async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) -> Result<(), LaunchError> {
|
||||
let replacements = [
|
||||
(
|
||||
"log4j-api-2.0-beta9.jar",
|
||||
@@ -287,20 +338,18 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
|
||||
];
|
||||
|
||||
for (old_name, fixed_rel, url) in &replacements {
|
||||
if !classpath
|
||||
.iter()
|
||||
.any(|entry| entry.file_name().is_some_and(|name| name == *old_name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let fixed_path = lib_dir.join(fixed_rel);
|
||||
|
||||
if !fixed_path.exists() {
|
||||
tracing::info!("Downloading patched {old_name}...");
|
||||
if let Some(parent) = fixed_path.parent() {
|
||||
let _ = tokio::fs::create_dir_all(parent).await;
|
||||
}
|
||||
let client = crate::net::HttpClient::new();
|
||||
if let Err(e) = crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await {
|
||||
tracing::error!(
|
||||
"Failed to download patched {old_name}: {e}, continuing with unpatched version"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
crate::net::download_file(&client, url, &fixed_path, |_, _| {}).await?;
|
||||
}
|
||||
|
||||
for entry in classpath.iter_mut() {
|
||||
@@ -313,6 +362,7 @@ async fn replace_log4j_fixed(lib_dir: &Path, classpath: &mut [PathBuf]) {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Old Forge installers cannot run headless, so their profiles and libraries
|
||||
// must be extracted from the jar instead.
|
||||
|
||||
use std::path::Path;
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
@@ -48,17 +48,24 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&settings.defaults.environment,
|
||||
&Default::default(),
|
||||
);
|
||||
self.install_with_java(
|
||||
client,
|
||||
game_version,
|
||||
loader_version,
|
||||
instance_dir,
|
||||
meta_dir,
|
||||
None,
|
||||
settings.paths.effective_java_path(),
|
||||
&environment,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn install_with_java(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
@@ -67,6 +74,7 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
java_path: Option<&str>,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Result<(), InstallError> {
|
||||
let installer_jar = instance_dir
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
@@ -93,16 +101,9 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
return Err(e);
|
||||
}
|
||||
} else {
|
||||
let java_path = java_path.map(str::to_owned).unwrap_or_else(|| {
|
||||
crate::config::SETTINGS
|
||||
.read()
|
||||
.paths
|
||||
.effective_java_path()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(crate::instance::java::detect_java_path)
|
||||
});
|
||||
tracing::debug!("Running Forge installer with Java {}", java_path);
|
||||
if let Err(e) = run_forge_installer(&installer_jar, instance_dir, &java_path).await {
|
||||
if let Err(e) =
|
||||
run_forge_installer(&installer_jar, instance_dir, java_path, environment).await
|
||||
{
|
||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||
return Err(InstallError::Installer(e));
|
||||
}
|
||||
@@ -127,19 +128,26 @@ impl ModLoaderInstaller for ForgeInstaller {
|
||||
pub async fn run_forge_installer(
|
||||
installer_path: &Path,
|
||||
instance_dir: &Path,
|
||||
java_path: &str,
|
||||
java_path: Option<&str>,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Result<(), InstallerError> {
|
||||
use tokio::process::Command;
|
||||
|
||||
set_action("Running Forge installer...");
|
||||
let minecraft_dir = std::path::absolute(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))?;
|
||||
let java_path =
|
||||
crate::instance::java::resolve_java_path_in(java_path, &minecraft_dir, environment);
|
||||
tracing::debug!("Running Forge installer with Java {}", java_path);
|
||||
|
||||
let output = match Command::new(java_path)
|
||||
.arg("-jar")
|
||||
.arg(installer_path)
|
||||
.arg("--installClient")
|
||||
.current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))
|
||||
.output()
|
||||
.await
|
||||
let output = match crate::instance::process::output(
|
||||
Command::new(&java_path)
|
||||
.arg("-jar")
|
||||
.arg(std::path::absolute(installer_path)?)
|
||||
.arg("--installClient")
|
||||
.current_dir(&minecraft_dir)
|
||||
.envs(environment),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
@@ -347,12 +355,7 @@ pub(crate) async fn install_forge_from_profile(
|
||||
// inheritsFrom field - implicitly inherits from the configured game
|
||||
// version so vanilla libraries layer in via resolve().
|
||||
//
|
||||
// we use serde_json::to_vec (not the pretty-print variant via
|
||||
// save_profile_json) so the written file is content-faithful: every
|
||||
// field present in the installer's versionInfo round-trips. key order
|
||||
// and whitespace may differ from the original installer JSON because
|
||||
// the source is a serde_json::Value (which doesn't preserve order),
|
||||
// but no field is silently dropped.
|
||||
// Keep unknown installer fields instead of round-tripping a stripped profile model.
|
||||
let serialized = serde_json::to_vec(version_info).map_err(|e| {
|
||||
InstallError::Installer(InstallerError::Profile(format!(
|
||||
"Failed to serialize Forge profile: {e}"
|
||||
|
||||
@@ -8,7 +8,7 @@ pub mod neoforge;
|
||||
mod quilt;
|
||||
mod vanilla;
|
||||
|
||||
use std::path::Path;
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use thiserror::Error;
|
||||
@@ -63,6 +63,7 @@ pub trait ModLoaderInstaller: Send + Sync {
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), InstallError>;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn install_with_java(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
@@ -70,9 +71,9 @@ pub trait ModLoaderInstaller: Send + Sync {
|
||||
loader_version: &str,
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
java_path: Option<&str>,
|
||||
_java_path: Option<&str>,
|
||||
_environment: &BTreeMap<String, String>,
|
||||
) -> Result<(), InstallError> {
|
||||
let _ = java_path;
|
||||
self.install(client, game_version, loader_version, instance_dir, meta_dir)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::path::Path;
|
||||
use std::{collections::BTreeMap, path::Path};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
@@ -45,17 +45,24 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), InstallError> {
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&settings.defaults.environment,
|
||||
&Default::default(),
|
||||
);
|
||||
self.install_with_java(
|
||||
client,
|
||||
game_version,
|
||||
loader_version,
|
||||
instance_dir,
|
||||
meta_dir,
|
||||
None,
|
||||
settings.paths.effective_java_path(),
|
||||
&environment,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
async fn install_with_java(
|
||||
&self,
|
||||
client: &HttpClient,
|
||||
@@ -64,6 +71,7 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
instance_dir: &Path,
|
||||
meta_dir: &Path,
|
||||
java_path: Option<&str>,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Result<(), InstallError> {
|
||||
let installer_jar = instance_dir
|
||||
.join(crate::storage::MINECRAFT_DIR_NAME)
|
||||
@@ -73,16 +81,9 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
|
||||
neoforge_api::download_neoforge_installer(client, loader_version, &installer_jar).await?;
|
||||
|
||||
let java_path = java_path.map(str::to_owned).unwrap_or_else(|| {
|
||||
crate::config::SETTINGS
|
||||
.read()
|
||||
.paths
|
||||
.effective_java_path()
|
||||
.map(str::to_owned)
|
||||
.unwrap_or_else(crate::instance::java::detect_java_path)
|
||||
});
|
||||
tracing::debug!("Running NeoForge installer with Java {}", java_path);
|
||||
if let Err(e) = run_neoforge_installer(&installer_jar, instance_dir, &java_path).await {
|
||||
if let Err(e) =
|
||||
run_neoforge_installer(&installer_jar, instance_dir, java_path, environment).await
|
||||
{
|
||||
let _ = tokio::fs::remove_file(&installer_jar).await;
|
||||
return Err(InstallError::Installer(e));
|
||||
}
|
||||
@@ -102,20 +103,27 @@ impl ModLoaderInstaller for NeoForgeInstaller {
|
||||
pub async fn run_neoforge_installer(
|
||||
installer_path: &Path,
|
||||
instance_dir: &Path,
|
||||
java_path: &str,
|
||||
java_path: Option<&str>,
|
||||
environment: &BTreeMap<String, String>,
|
||||
) -> Result<(), InstallerError> {
|
||||
use tokio::process::Command;
|
||||
|
||||
set_action("Running NeoForge installer...");
|
||||
let minecraft_dir = std::path::absolute(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))?;
|
||||
let java_path =
|
||||
crate::instance::java::resolve_java_path_in(java_path, &minecraft_dir, environment);
|
||||
tracing::debug!("Running NeoForge installer with Java {}", java_path);
|
||||
|
||||
let output = match Command::new(java_path)
|
||||
.arg(format!("-Duser.home={}", instance_dir.display()))
|
||||
.arg("-jar")
|
||||
.arg(installer_path)
|
||||
.arg("--installClient")
|
||||
.current_dir(instance_dir.join(crate::storage::MINECRAFT_DIR_NAME))
|
||||
.output()
|
||||
.await
|
||||
let output = match crate::instance::process::output(
|
||||
Command::new(&java_path)
|
||||
.arg("-jar")
|
||||
.arg(std::path::absolute(installer_path)?)
|
||||
.arg("--installClient")
|
||||
.arg(&minecraft_dir)
|
||||
.current_dir(&minecraft_dir)
|
||||
.envs(environment),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// vanilla "installer". doesn't actually install anything since the launch
|
||||
// process already handles downloading vanilla assets/libraries. this just
|
||||
// exists so vanilla fits the same ModLoaderInstaller trait as everyone else.
|
||||
// InstanceManager prepares vanilla artifacts; this implements the shared loader contract.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
|
||||
+62
-7
@@ -123,7 +123,13 @@ impl InstanceManager {
|
||||
loader_version: Option<&str>,
|
||||
instance_dir: &std::path::Path,
|
||||
) -> Result<InstanceConfig, InstanceError> {
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
let instance_dir = std::path::absolute(instance_dir)?;
|
||||
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&settings.defaults.environment,
|
||||
&Default::default(),
|
||||
);
|
||||
tracing::debug!(
|
||||
"Preparing Minecraft directory for '{}': {}",
|
||||
name,
|
||||
@@ -134,6 +140,11 @@ impl InstanceManager {
|
||||
std::fs::create_dir_all(&path)?;
|
||||
tracing::trace!("Ensured instance subdirectory {}", path.display());
|
||||
}
|
||||
let java_path = crate::instance::java::resolve_java_path_in(
|
||||
settings.paths.effective_java_path(),
|
||||
&minecraft_dir,
|
||||
&environment,
|
||||
);
|
||||
|
||||
// forge insists on this file existing, even if it's empty json. thanks forge.
|
||||
let launcher_profiles_path = minecraft_dir.join("launcher_profiles.json");
|
||||
@@ -203,7 +214,19 @@ impl InstanceManager {
|
||||
crate::storage::write_atomic(&meta_json_path, &raw_meta_bytes)?;
|
||||
tracing::debug!("Saved version meta to {}", meta_json_path.display());
|
||||
|
||||
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
let runtime = crate::instance::java::probe_java_in(
|
||||
Path::new(&java_path),
|
||||
&minecraft_dir,
|
||||
&environment,
|
||||
)
|
||||
.await?;
|
||||
crate::net::mojang::download_libraries_for_platform(
|
||||
&self.client,
|
||||
&version_meta,
|
||||
&self.meta_dir,
|
||||
&runtime.platform,
|
||||
)
|
||||
.await?;
|
||||
|
||||
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
|
||||
@@ -225,12 +248,14 @@ impl InstanceManager {
|
||||
name
|
||||
);
|
||||
installer
|
||||
.install(
|
||||
.install_with_java(
|
||||
&self.client,
|
||||
game_version,
|
||||
effective_loader_version,
|
||||
instance_dir,
|
||||
&instance_dir,
|
||||
&self.meta_dir,
|
||||
Some(&java_path),
|
||||
&environment,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
@@ -240,7 +265,7 @@ impl InstanceManager {
|
||||
}
|
||||
})?;
|
||||
|
||||
let defaults = crate::config::SETTINGS.read().defaults.clone();
|
||||
let defaults = &settings.defaults;
|
||||
let config = InstanceConfig {
|
||||
name: name.to_string(),
|
||||
game_version: game_version.to_string(),
|
||||
@@ -273,6 +298,23 @@ impl InstanceManager {
|
||||
}
|
||||
|
||||
pub async fn repair_runtime_cache(&self, config: &InstanceConfig) -> Result<(), InstanceError> {
|
||||
validate_name(&config.name)?;
|
||||
let settings = crate::config::SETTINGS.read().clone();
|
||||
let instance_dir = std::path::absolute(self.instances_dir.join(&config.name))?;
|
||||
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
std::fs::create_dir_all(&minecraft_dir)?;
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&settings.defaults.environment,
|
||||
&config.environment,
|
||||
);
|
||||
let java_path = crate::instance::java::resolve_java_path_in(
|
||||
config
|
||||
.java_path
|
||||
.as_deref()
|
||||
.or(settings.paths.effective_java_path()),
|
||||
&minecraft_dir,
|
||||
&environment,
|
||||
);
|
||||
let task = crate::feedback::progress::ProgressTask::start(format!(
|
||||
"Rebuilding runtime for '{}'",
|
||||
config.name
|
||||
@@ -352,7 +394,19 @@ impl InstanceManager {
|
||||
if fetched_meta {
|
||||
crate::storage::write_atomic(&meta_path, &raw_meta)?;
|
||||
}
|
||||
crate::net::mojang::download_libraries(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
let runtime = crate::instance::java::probe_java_in(
|
||||
Path::new(&java_path),
|
||||
&minecraft_dir,
|
||||
&environment,
|
||||
)
|
||||
.await?;
|
||||
crate::net::mojang::download_libraries_for_platform(
|
||||
&self.client,
|
||||
&version_meta,
|
||||
&self.meta_dir,
|
||||
&runtime.platform,
|
||||
)
|
||||
.await?;
|
||||
crate::net::mojang::download_assets(&self.client, &version_meta, &self.meta_dir).await?;
|
||||
|
||||
if config.loader != ModLoader::Vanilla {
|
||||
@@ -368,9 +422,10 @@ impl InstanceManager {
|
||||
&self.client,
|
||||
&config.game_version,
|
||||
loader_version,
|
||||
&self.instances_dir.join(&config.name),
|
||||
&instance_dir,
|
||||
&self.meta_dir,
|
||||
config.java_path.as_deref(),
|
||||
Some(&java_path),
|
||||
&environment,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod loader;
|
||||
pub mod logs;
|
||||
pub mod manager;
|
||||
pub mod models;
|
||||
mod process;
|
||||
pub mod runtime;
|
||||
pub mod screenshots;
|
||||
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::io;
|
||||
use tokio::process::{Child, Command};
|
||||
|
||||
/// Own descendants until completion or cancellation.
|
||||
pub(super) fn spawn_owned(command: &mut Command) -> io::Result<(Child, ProcessTree)> {
|
||||
command.kill_on_drop(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
command.process_group(0);
|
||||
let child = command.spawn()?;
|
||||
let tree = ProcessTree(Some(
|
||||
child.id().expect("newly spawned child has an ID") as i32
|
||||
));
|
||||
Ok((child, tree))
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::spawn(command)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn output(command: &mut Command) -> io::Result<std::process::Output> {
|
||||
command
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped());
|
||||
let (child, _tree) = spawn_owned(command)?;
|
||||
child.wait_with_output().await
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
pub(super) struct ProcessTree(Option<i32>);
|
||||
|
||||
#[cfg(unix)]
|
||||
impl ProcessTree {
|
||||
pub(super) fn detach(mut self) -> io::Result<()> {
|
||||
self.0 = None;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for ProcessTree {
|
||||
fn drop(&mut self) {
|
||||
let Some(group) = self.0 else {
|
||||
return;
|
||||
};
|
||||
// SAFETY: a negative PID addresses only the group created for this command.
|
||||
if unsafe { libc::kill(-group, libc::SIGKILL) } == -1 {
|
||||
let error = io::Error::last_os_error();
|
||||
if error.raw_os_error() != Some(libc::ESRCH) {
|
||||
tracing::warn!("Failed to terminate process group {group}: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub(super) struct ProcessTree {
|
||||
_job: std::os::windows::io::OwnedHandle,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
impl ProcessTree {
|
||||
pub(super) fn detach(self) -> io::Result<()> {
|
||||
windows::set_kill_on_close(&self._job, false)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod windows {
|
||||
use super::*;
|
||||
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{HANDLE, INVALID_HANDLE_VALUE},
|
||||
System::{
|
||||
Diagnostics::ToolHelp::{
|
||||
CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First,
|
||||
Thread32Next,
|
||||
},
|
||||
JobObjects::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation,
|
||||
SetInformationJobObject,
|
||||
},
|
||||
Threading::{CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME},
|
||||
},
|
||||
};
|
||||
|
||||
fn own_handle(handle: HANDLE) -> io::Result<OwnedHandle> {
|
||||
if handle.is_null() || handle == INVALID_HANDLE_VALUE {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
// SAFETY: these APIs return a new handle owned by the caller.
|
||||
Ok(unsafe { OwnedHandle::from_raw_handle(handle) })
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_kill_on_close(job: &OwnedHandle, kill: bool) -> io::Result<()> {
|
||||
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
|
||||
BasicLimitInformation:
|
||||
windows_sys::Win32::System::JobObjects::JOBOBJECT_BASIC_LIMIT_INFORMATION {
|
||||
LimitFlags: if kill {
|
||||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
} else {
|
||||
0
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
// SAFETY: the buffer has the required size and lives through the call.
|
||||
if unsafe {
|
||||
SetInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
JobObjectExtendedLimitInformation,
|
||||
(&limits as *const JOBOBJECT_EXTENDED_LIMIT_INFORMATION).cast(),
|
||||
std::mem::size_of_val(&limits) as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn spawn(command: &mut Command) -> io::Result<(Child, ProcessTree)> {
|
||||
// SAFETY: null security/name pointers request a private, unnamed job.
|
||||
let job = own_handle(unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) })?;
|
||||
set_kill_on_close(&job, true)?;
|
||||
// Suspend before job assignment so the shell cannot spawn unowned children.
|
||||
command.creation_flags(CREATE_SUSPENDED);
|
||||
let child = command.spawn()?;
|
||||
let process = child
|
||||
.raw_handle()
|
||||
.ok_or_else(|| io::Error::other("Process handle is unavailable"))?;
|
||||
// SAFETY: both handles are live and the child has not started running.
|
||||
if unsafe { AssignProcessToJobObject(job.as_raw_handle(), process) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let tree = ProcessTree { _job: job };
|
||||
resume_main_thread(child.id().expect("newly spawned child has an ID"))?;
|
||||
Ok((child, tree))
|
||||
}
|
||||
|
||||
// Tokio retains the process handle but not the primary thread handle.
|
||||
fn resume_main_thread(pid: u32) -> io::Result<()> {
|
||||
// SAFETY: the snapshot and entry buffer are owned here.
|
||||
let snapshot = own_handle(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) })?;
|
||||
let mut entry = THREADENTRY32 {
|
||||
dwSize: std::mem::size_of::<THREADENTRY32>() as u32,
|
||||
..Default::default()
|
||||
};
|
||||
let mut found = unsafe { Thread32First(snapshot.as_raw_handle(), &mut entry) };
|
||||
while found != 0 {
|
||||
if entry.th32OwnerProcessID == pid {
|
||||
// A suspended, newly-created process has only its primary thread.
|
||||
let thread = own_handle(unsafe {
|
||||
OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID)
|
||||
})?;
|
||||
if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
found = unsafe { Thread32Next(snapshot.as_raw_handle(), &mut entry) };
|
||||
}
|
||||
Err(io::Error::other(format!(
|
||||
"Cannot find the primary thread of process {pid}"
|
||||
)))
|
||||
}
|
||||
}
|
||||
+23
-4
@@ -17,14 +17,11 @@ pub enum RunState {
|
||||
pub static RUNNING: LazyLock<Arc<Mutex<HashMap<String, RunState>>>> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
|
||||
|
||||
// queued up so the TUI event loop can flush these to disk in batch,
|
||||
// the child process monitor shouldn't be writing config files directly
|
||||
// The monitor persists timestamps; the TUI drains these to update its cached instances.
|
||||
type PendingLastPlayed = Arc<Mutex<Vec<(String, DateTime<Utc>)>>>;
|
||||
pub static PENDING_LAST_PLAYED: LazyLock<PendingLastPlayed> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
|
||||
|
||||
// oneshot channels to signal a running instance to stop.
|
||||
// send_kill fires the channel, the launch task receives it and kills the child process.
|
||||
type KillSenders = Arc<Mutex<HashMap<String, tokio::sync::oneshot::Sender<()>>>>;
|
||||
pub static KILL_SENDERS: LazyLock<KillSenders> =
|
||||
LazyLock::new(|| Arc::new(Mutex::new(HashMap::new())));
|
||||
@@ -114,6 +111,28 @@ pub fn cleanup_kill_sender(name: &str) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn lock_instance(
|
||||
root: &std::path::Path,
|
||||
name: &str,
|
||||
) -> Result<std::fs::File, crate::instance::manager::InstanceError> {
|
||||
crate::instance::manager::validate_name(name)?;
|
||||
let locks = root.join(".rmcl-locks");
|
||||
std::fs::create_dir_all(&locks)?;
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(locks.join(format!("{name}.lock")))?;
|
||||
match file.try_lock() {
|
||||
Ok(()) => Ok(file),
|
||||
Err(std::fs::TryLockError::WouldBlock) => Err(
|
||||
crate::instance::manager::InstanceError::InstanceRunning(name.to_owned()),
|
||||
),
|
||||
Err(std::fs::TryLockError::Error(error)) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests/runtime.rs"]
|
||||
mod tests;
|
||||
@@ -1,6 +1,22 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
#[test]
|
||||
fn plain_output_emits_before_eof_and_bounds_pending_lines() {
|
||||
let mut parser = super::MinecraftLogParser::new();
|
||||
let mut emitted = Vec::new();
|
||||
for _ in 0..300 {
|
||||
emitted.extend(parser.push_line(super::LogStream::Stdout, "plain output"));
|
||||
}
|
||||
assert!(!emitted.is_empty());
|
||||
emitted.extend(parser.flush());
|
||||
assert_eq!(
|
||||
emitted.iter().map(|event| event.lines.len()).sum::<usize>(),
|
||||
300
|
||||
);
|
||||
assert!(emitted.iter().all(|event| event.lines.len() <= 128));
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
fn parse_all(lines: &[(LogStream, &str)]) -> Vec<ParsedLogEvent> {
|
||||
|
||||
@@ -2,132 +2,241 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use super::*;
|
||||
use crate::launch_profile::model::Library;
|
||||
use serde_json::json;
|
||||
use std::io::Write;
|
||||
|
||||
fn make_zip(tmp: &Path, name: &str, entries: &[(&str, &[u8])]) -> PathBuf {
|
||||
let path = tmp.join(name);
|
||||
let file = std::fs::File::create(&path).unwrap();
|
||||
let mut zip = zip::ZipWriter::new(file);
|
||||
let opts: zip::write::SimpleFileOptions = Default::default();
|
||||
for (filename, bytes) in entries {
|
||||
zip.start_file(*filename, opts).unwrap();
|
||||
zip.start_file(*filename, zip::write::SimpleFileOptions::default())
|
||||
.unwrap();
|
||||
zip.write_all(bytes).unwrap();
|
||||
}
|
||||
zip.finish().unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
fn lib(name: &str) -> Library {
|
||||
Library {
|
||||
name: name.to_owned(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_replaced_libs_removes_dominated_prefixes() {
|
||||
let mut classpath = vec![
|
||||
PathBuf::from("/libs/launchwrapper-1.12.jar"),
|
||||
PathBuf::from("/libs/asm-all-5.0.3.jar"),
|
||||
PathBuf::from("/libs/lwjgl-2.9.4.jar"),
|
||||
PathBuf::from("/libs/lwjgl_util-2.9.4.jar"),
|
||||
PathBuf::from("/libs/commons-compress-1.4.1.jar"),
|
||||
PathBuf::from("/libs/commons-io-2.4.jar"),
|
||||
PathBuf::from("/libs/guava-15.0.jar"),
|
||||
PathBuf::from("/libs/log4j-core-2.0.jar"),
|
||||
PathBuf::from("/libs/guava-21.0.jar"),
|
||||
];
|
||||
strip_replaced_libs(&mut classpath);
|
||||
let mut profile = LaunchProfile {
|
||||
libraries: [
|
||||
"net.minecraft:launchwrapper:1.12",
|
||||
"org.ow2.asm:asm-all:5.0.3",
|
||||
"org.lwjgl.lwjgl:lwjgl:2.9.4",
|
||||
"org.lwjgl.lwjgl:lwjgl_util:2.9.4",
|
||||
"org.apache.commons:commons-compress:1.4.1",
|
||||
"commons-io:commons-io:2.4",
|
||||
"com.google.guava:guava:15.0",
|
||||
"org.apache.logging.log4j:log4j-core:2.0",
|
||||
"com.google.guava:guava:21.0",
|
||||
]
|
||||
.into_iter()
|
||||
.map(lib)
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
strip_replaced_libs(&mut profile);
|
||||
assert_eq!(
|
||||
classpath,
|
||||
vec![
|
||||
PathBuf::from("/libs/log4j-core-2.0.jar"),
|
||||
PathBuf::from("/libs/guava-21.0.jar"),
|
||||
profile
|
||||
.libraries
|
||||
.iter()
|
||||
.map(|lib| lib.name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
"org.apache.logging.log4j:log4j-core:2.0",
|
||||
"com.google.guava:guava:21.0",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strip_replaced_libs_keeps_unrelated_entries() {
|
||||
let mut classpath = vec![
|
||||
PathBuf::from("/libs/log4j-core-2.0.jar"),
|
||||
PathBuf::from("/libs/mixin-0.8.5.jar"),
|
||||
];
|
||||
let original = classpath.clone();
|
||||
strip_replaced_libs(&mut classpath);
|
||||
assert_eq!(classpath, original);
|
||||
let mut profile = LaunchProfile {
|
||||
libraries: vec![
|
||||
lib("org.apache.logging.log4j:log4j-core:2.0"),
|
||||
lib("org.spongepowered:mixin:0.8.5"),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let original = profile.clone();
|
||||
strip_replaced_libs(&mut profile);
|
||||
assert_eq!(profile, original);
|
||||
}
|
||||
|
||||
fn bundled_profile() -> LaunchProfile {
|
||||
// Same three-part native coordinates and overlapping OS rules as release 3.0.35.
|
||||
let mut libraries = Vec::new();
|
||||
for module in ["lwjgl", "lwjgl-sdl", "lwjgl-spng"] {
|
||||
libraries.push(json!({"name":format!("org.lwjgl:{module}:3.4.2"), "downloads":{"artifact":{
|
||||
"url":format!("https://example.invalid/{module}-3.4.2.jar"), "sha1":"0".repeat(40), "size":1,
|
||||
}}}));
|
||||
for (classifier, os) in [
|
||||
("natives-linux", "linux"),
|
||||
("natives-linux-arm64", "linux"),
|
||||
("natives-macos", "osx"),
|
||||
("natives-macos-arm64", "osx"),
|
||||
("natives-windows", "windows"),
|
||||
("natives-windows-x86", "windows"),
|
||||
("natives-windows-arm64", "windows"),
|
||||
] {
|
||||
libraries.push(json!({"name":format!("org.lwjgl:{module}-{classifier}:3.4.2"),
|
||||
"rules":[{"action":"allow", "os":{"name":os}}], "downloads":{"artifact":{
|
||||
"url":format!("https://example.invalid/{module}-3.4.2-{classifier}.jar"), "sha1":"0".repeat(40), "size":1,
|
||||
}}}));
|
||||
}
|
||||
}
|
||||
serde_json::from_value(json!({"id":"lwjgl3ify-client", "mainClass":"com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread",
|
||||
"javaVersion":{"majorVersion":25}, "libraries":libraries,
|
||||
"arguments":{"game":["--username", "${auth_player_name}"], "jvm":[
|
||||
{"rules":[{"action":"allow", "os":{"name":"osx"}}], "value":"-XstartOnFirstThread"},
|
||||
"--add-opens", "java.base/java.lang=ALL-UNNAMED",
|
||||
"-Djava.system.class.loader=com.gtnewhorizons.retrofuturabootstrap.RfbSystemClassLoader",
|
||||
]},
|
||||
})).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_add_opens_extracts_module_args() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let manifest = b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang java.base/java.util\n";
|
||||
let zip_path = make_zip(
|
||||
tmp.path(),
|
||||
fn bundled_natives_follow_selected_java_on_all_platforms() {
|
||||
for (os, arch, bits, expected) in [
|
||||
("Linux", "amd64", "64", "natives-linux"),
|
||||
("Linux", "aarch64", "64", "natives-linux-arm64"),
|
||||
("Mac OS X", "amd64", "64", "natives-macos"),
|
||||
("Mac OS X", "aarch64", "64", "natives-macos-arm64"),
|
||||
("Windows 10", "x86", "32", "natives-windows-x86"),
|
||||
("Windows 10", "amd64", "64", "natives-windows"),
|
||||
("Windows 10", "aarch64", "64", "natives-windows-arm64"),
|
||||
] {
|
||||
let platform = JavaPlatform::from_java_properties(os, arch, bits, "10.0").unwrap();
|
||||
let mut profile = bundled_profile();
|
||||
select_lwjgl_natives(&mut profile, &platform).unwrap();
|
||||
assert_eq!(profile.libraries.len(), 6);
|
||||
let natives: Vec<_> = profile
|
||||
.libraries
|
||||
.iter()
|
||||
.filter(|lib| lib.name.contains("-natives-"))
|
||||
.collect();
|
||||
assert_eq!(natives.len(), 3);
|
||||
assert!(
|
||||
natives
|
||||
.iter()
|
||||
.all(|lib| lib.name.ends_with(&format!("-{expected}:3.4.2")))
|
||||
);
|
||||
}
|
||||
let mut profile = bundled_profile();
|
||||
profile
|
||||
.libraries
|
||||
.retain(|lib| !lib.name.contains("lwjgl-spng-natives-windows-x86"));
|
||||
let platform = JavaPlatform::from_java_properties("Windows 10", "x86", "32", "10.0").unwrap();
|
||||
assert!(
|
||||
select_lwjgl_natives(&mut profile, &platform)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("lwjgl-spng")
|
||||
);
|
||||
}
|
||||
|
||||
fn write_mod(temp: &Path, mut profile: LaunchProfile) -> PathBuf {
|
||||
use sha1::Digest;
|
||||
let payload = make_zip(
|
||||
temp,
|
||||
"patches.zip",
|
||||
&[("META-INF/MANIFEST.MF", manifest)],
|
||||
&[("META-INF/MANIFEST.MF", b"Manifest-Version: 1.0\r\n")],
|
||||
);
|
||||
let args = parse_add_opens(&zip_path).expect("parsed");
|
||||
let payload = std::fs::read(payload).unwrap();
|
||||
profile.libraries.push(serde_json::from_value(json!({"name":"com.github.GTNewHorizons:lwjgl3ify:3.0.35:forgePatches",
|
||||
"downloads":{"artifact":{"url":"https://example.invalid/forgePatches.jar", "sha1":format!("{:x}", sha1::Sha1::digest(&payload)), "size":payload.len()}}
|
||||
})).unwrap());
|
||||
let mods = temp.join("mods");
|
||||
std::fs::create_dir_all(&mods).unwrap();
|
||||
make_zip(
|
||||
&mods,
|
||||
"lwjgl3ify-3.0.35.jar",
|
||||
&[
|
||||
(
|
||||
"me/eigenraven/lwjgl3ify/relauncher/version.json",
|
||||
&serde_json::to_vec(&profile).unwrap(),
|
||||
),
|
||||
(
|
||||
"me/eigenraven/lwjgl3ify/relauncher/forgePatches.zip",
|
||||
&payload,
|
||||
),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shim_forwards_the_metadata_client_entrypoint_and_payload_is_a_jar() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
write_mod(temp.path(), bundled_profile());
|
||||
let platform =
|
||||
JavaPlatform::from_java_properties("Mac OS X", "amd64", "64", "10.15.7").unwrap();
|
||||
let patches = load(temp.path(), &platform).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
"--add-opens",
|
||||
"java.base/java.lang=ALL-UNNAMED",
|
||||
"--add-opens",
|
||||
"java.base/java.util=ALL-UNNAMED",
|
||||
]
|
||||
patches.profile.java_version.as_ref().unwrap().major_version,
|
||||
25
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_add_opens_handles_continuation_lines() {
|
||||
// jar manifests wrap long lines: the line ends with a trailing space,
|
||||
// then the next physical line starts with a leading space marker.
|
||||
// when joined per the MANIFEST.MF spec, the trailing space remains
|
||||
// and the leading space marker is consumed, so the two values stay
|
||||
// separated by exactly one space when split_whitespace runs.
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let manifest =
|
||||
b"Manifest-Version: 1.0\nAdd-Opens: java.base/java.lang \n java.base/sun.security.util\n";
|
||||
let zip_path = make_zip(
|
||||
tmp.path(),
|
||||
"patches-continuation.zip",
|
||||
&[("META-INF/MANIFEST.MF", manifest)],
|
||||
assert!(
|
||||
!patches
|
||||
.profile
|
||||
.libraries
|
||||
.iter()
|
||||
.any(|lib| lib.name.ends_with(":forgePatches"))
|
||||
);
|
||||
let args = parse_add_opens(&zip_path).expect("parsed");
|
||||
let mut classpath = Vec::new();
|
||||
let (main, extra, _) = apply(
|
||||
patches,
|
||||
temp.path(),
|
||||
&temp.path().join("libraries"),
|
||||
&mut classpath,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(main, "RmclShim");
|
||||
assert_eq!(
|
||||
args,
|
||||
vec![
|
||||
"--add-opens",
|
||||
"java.base/java.lang=ALL-UNNAMED",
|
||||
"--add-opens",
|
||||
"java.base/sun.security.util=ALL-UNNAMED",
|
||||
]
|
||||
extra,
|
||||
["com.gtnewhorizons.retrofuturabootstrap.MainStartOnFirstThread"]
|
||||
);
|
||||
assert_eq!(classpath[1], temp.path().join(".forge-patches.jar"));
|
||||
let mut shim = zip::ZipArchive::new(std::fs::File::open(&classpath[0]).unwrap()).unwrap();
|
||||
assert!(shim.by_name("RmclShim.class").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_or_missing_bundled_metadata_is_an_error() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let platform = JavaPlatform::from_java_properties("Linux", "amd64", "64", "6.0").unwrap();
|
||||
assert!(load(temp.path(), &platform).unwrap().is_none());
|
||||
let mut incomplete = bundled_profile();
|
||||
incomplete.java_version = None;
|
||||
write_mod(temp.path(), incomplete);
|
||||
assert!(
|
||||
load(temp.path(), &platform)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("javaVersion")
|
||||
);
|
||||
let jar = write_mod(temp.path(), bundled_profile());
|
||||
std::fs::write(&jar, b"broken jar").unwrap();
|
||||
assert!(load(temp.path(), &platform).is_err());
|
||||
make_zip(
|
||||
jar.parent().unwrap(),
|
||||
"lwjgl3ify-3.0.35.jar",
|
||||
&[("other.txt", b"no metadata")],
|
||||
);
|
||||
assert!(
|
||||
load(temp.path(), &platform)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("bundled client profile")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_add_opens_returns_none_when_manifest_missing() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let zip_path = make_zip(tmp.path(), "no-manifest.zip", &[("other.txt", b"x")]);
|
||||
assert!(parse_add_opens(&zip_path).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_add_opens_returns_none_for_missing_file() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
assert!(parse_add_opens(&tmp.path().join("missing.zip")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_lwjgl3_inserts_only_jars_that_exist() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let lib_dir = tmp.path();
|
||||
|
||||
// pre-create only the lwjgl core jar; everything else absent so the
|
||||
// function should skip them silently. proves we don't insert paths
|
||||
// for jars that aren't there.
|
||||
let core_jar = lib_dir.join("org/lwjgl/lwjgl/3.3.3/lwjgl-3.3.3.jar");
|
||||
std::fs::create_dir_all(core_jar.parent().unwrap()).unwrap();
|
||||
std::fs::write(&core_jar, b"jar").unwrap();
|
||||
|
||||
let mut classpath = vec![PathBuf::from("/leading/forge-patches.jar")];
|
||||
add_lwjgl3(lib_dir, &mut classpath);
|
||||
|
||||
assert_eq!(classpath[0], PathBuf::from("/leading/forge-patches.jar"));
|
||||
assert_eq!(classpath[1], core_jar);
|
||||
assert_eq!(classpath.len(), 2);
|
||||
}
|
||||
@@ -1,6 +1,32 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
#[tokio::test]
|
||||
async fn dropping_the_kill_sender_does_not_request_cancellation_or_repoll_a_completed_receiver() {
|
||||
let (sender, receiver) = tokio::sync::oneshot::channel();
|
||||
let mut receiver = Some(receiver);
|
||||
drop(sender);
|
||||
for _ in 0..2 {
|
||||
assert!(
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_millis(5),
|
||||
super::wait_for_kill(&mut receiver)
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
let (sender, request) = tokio::sync::oneshot::channel();
|
||||
receiver = Some(request);
|
||||
sender.send(()).unwrap();
|
||||
tokio::time::timeout(
|
||||
std::time::Duration::from_secs(1),
|
||||
super::wait_for_kill(&mut receiver),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[rstest::rstest]
|
||||
@@ -173,9 +199,7 @@ fn preferred_account_falls_back_to_the_active_account() {
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn launch_commands_receive_instance_environment() {
|
||||
fn hook_fixture() -> (tempfile::TempDir, InstanceConfig, LaunchInvocation) {
|
||||
use chrono::Utc;
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
@@ -218,9 +242,20 @@ async fn launch_commands_receive_instance_environment() {
|
||||
environment: config.environment.clone(),
|
||||
working_dir: minecraft.clone(),
|
||||
};
|
||||
(temp, config, invocation)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn launch_commands_receive_instance_environment() {
|
||||
let (temp, config, invocation) = hook_fixture();
|
||||
let command = LaunchCommand {
|
||||
enabled: true,
|
||||
command: "printf '%s|%s' \"$CUSTOM_VALUE\" \"$INST_NAME\" > hook-result".to_owned(),
|
||||
command: if cfg!(windows) {
|
||||
"echo %CUSTOM_VALUE%^|%INST_NAME%>hook-result"
|
||||
} else {
|
||||
"printf '%s|%s' \"$CUSTOM_VALUE\" \"$INST_NAME\" > hook-result"
|
||||
}
|
||||
.to_owned(),
|
||||
};
|
||||
|
||||
run_launch_command("Pre-launch", &command, &config, &invocation, temp.path())
|
||||
@@ -228,16 +263,91 @@ async fn launch_commands_receive_instance_environment() {
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(minecraft.join("hook-result")).unwrap(),
|
||||
std::fs::read_to_string(invocation.working_dir.join("hook-result"))
|
||||
.unwrap()
|
||||
.trim_end(),
|
||||
"available|Hook Test"
|
||||
);
|
||||
}
|
||||
|
||||
// exercises the early-return branch of migrate_legacy_meta_if_needed.
|
||||
// a profile with either arguments or minecraftArguments is not legacy
|
||||
// and must produce Ok(None) without touching the network. covers both
|
||||
// shapes in one parameterised test so a regression that drops one of
|
||||
// the two predicate conditions is caught.
|
||||
#[cfg(windows)]
|
||||
#[tokio::test]
|
||||
async fn windows_hooks_preserve_quoted_paths_arguments_redirection_and_expansion() {
|
||||
let (temp, config, invocation) = hook_fixture();
|
||||
let script = invocation.working_dir.join("hook script with spaces.cmd");
|
||||
std::fs::write(&script, "@echo off\r\necho %1\r\necho %CUSTOM_VALUE%\r\necho %INST_NAME%\r\necho stderr value 1>&2\r\n").unwrap();
|
||||
let command = LaunchCommand {
|
||||
enabled: true,
|
||||
command: format!(
|
||||
"\"{}\" \"argument with spaces & |\" > \"result file.txt\" 2> \"error file.txt\"",
|
||||
script.display()
|
||||
),
|
||||
};
|
||||
run_launch_command("Pre-launch", &command, &config, &invocation, temp.path())
|
||||
.await
|
||||
.unwrap();
|
||||
let stdout = std::fs::read_to_string(invocation.working_dir.join("result file.txt")).unwrap();
|
||||
assert_eq!(
|
||||
stdout.lines().collect::<Vec<_>>(),
|
||||
["\"argument with spaces & |\"", "available", "Hook Test"]
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(invocation.working_dir.join("error file.txt"))
|
||||
.unwrap()
|
||||
.trim(),
|
||||
"stderr value"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelling_a_hook_terminates_its_descendants() {
|
||||
let (temp, config, invocation) = hook_fixture();
|
||||
let command = LaunchCommand { enabled: true, command: if cfg!(windows) {
|
||||
"powershell.exe -NoProfile -NonInteractive -Command \"[IO.File]::WriteAllText('child-ready','ready'); Start-Sleep -Milliseconds 1200; [IO.File]::WriteAllText('escaped','escaped')\""
|
||||
} else {
|
||||
"(printf ready > child-ready; sleep 1; printf escaped > escaped) & wait"
|
||||
}.to_owned() };
|
||||
{
|
||||
let future = run_launch_command("Pre-launch", &command, &config, &invocation, temp.path());
|
||||
tokio::pin!(future);
|
||||
let ready = async {
|
||||
while !invocation.working_dir.join("child-ready").is_file() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
result = &mut future => panic!("hook ended before cancellation: {result:?}"),
|
||||
result = tokio::time::timeout(std::time::Duration::from_secs(15), ready) => result.unwrap(),
|
||||
}
|
||||
// Dropping the future must close the job/kill the group, not only its shell.
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1600)).await;
|
||||
assert!(
|
||||
!invocation.working_dir.join("escaped").exists(),
|
||||
"hook descendant survived cancellation"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_hooks_can_leave_an_intentional_background_command() {
|
||||
let (temp, config, invocation) = hook_fixture();
|
||||
let command = LaunchCommand { enabled: true, command: if cfg!(windows) {
|
||||
"start \"\" /B powershell.exe -NoProfile -NonInteractive -Command \"Start-Sleep -Milliseconds 600; [IO.File]::WriteAllText('background-finished','done')\" >nul 2>nul"
|
||||
} else {
|
||||
"(sleep 0.6; printf done > background-finished) >/dev/null 2>&1 &"
|
||||
}.to_owned() };
|
||||
run_launch_command("Pre-launch", &command, &config, &invocation, temp.path())
|
||||
.await
|
||||
.unwrap();
|
||||
tokio::time::timeout(std::time::Duration::from_secs(15), async {
|
||||
while !invocation.working_dir.join("background-finished").is_file() {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("completed hook's background command was terminated");
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::modern_arguments(true, false)]
|
||||
#[case::legacy_minecraft_arguments(false, true)]
|
||||
@@ -268,9 +378,6 @@ async fn migrate_legacy_meta_skips_when_arguments_present(
|
||||
);
|
||||
}
|
||||
|
||||
// each loader maps to a distinct directory-naming branch. one rstest
|
||||
// exercises every variant so a regression that misorders the match
|
||||
// arms in installer_version_dir_name is caught.
|
||||
#[rstest::rstest]
|
||||
#[case::forge(ModLoader::Forge, "1.20.1", "47.2.0", Some("1.20.1-forge-47.2.0"))]
|
||||
#[case::neoforge(ModLoader::NeoForge, "1.21.1", "21.1.0", Some("neoforge-21.1.0"))]
|
||||
@@ -289,11 +396,6 @@ fn installer_version_dir_name_per_loader(
|
||||
);
|
||||
}
|
||||
|
||||
// exercises the modern-profile early-return in
|
||||
// migrate_legacy_loader_profile_if_needed. any of inheritsFrom,
|
||||
// arguments, minecraftArguments present (or game_arguments absent)
|
||||
// means "not legacy" and the function must return Ok(None) without
|
||||
// touching the installer JSON path.
|
||||
#[tokio::test]
|
||||
async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() {
|
||||
use LaunchProfile;
|
||||
@@ -350,8 +452,6 @@ async fn migrate_legacy_loader_profile_skips_modern_with_inherits_from() {
|
||||
async fn migrate_legacy_loader_profile_skips_fabric() {
|
||||
// a fresh upstream Fabric profile happens to match the "legacy"
|
||||
// shape (no inheritsFrom, no arguments, no minecraftArguments).
|
||||
// make sure the migration helper recognises this is Fabric and
|
||||
// returns Ok(None) instead of erroring with "reinstall Fabric".
|
||||
use LaunchProfile;
|
||||
use chrono::Utc;
|
||||
use tempfile::TempDir;
|
||||
|
||||
@@ -3,9 +3,6 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
// builds an in-memory zip in a tempdir with the given json as
|
||||
// install_profile.json. lets the legacy-install-profile detector be
|
||||
// tested without an actual forge installer.
|
||||
fn make_installer_zip(tmp: &std::path::Path, json: &serde_json::Value) -> std::path::PathBuf {
|
||||
use std::io::Write;
|
||||
let path = tmp.join("installer.jar");
|
||||
|
||||
@@ -3,9 +3,6 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
// the factory maps every ModLoader variant to its concrete installer.
|
||||
// covering all five arms catches a misordered match or a copy-paste typo
|
||||
// that would route, say, NeoForge to the Forge installer.
|
||||
#[rstest::rstest]
|
||||
#[case::vanilla(ModLoader::Vanilla)]
|
||||
#[case::forge(ModLoader::Forge)]
|
||||
@@ -24,8 +21,7 @@ fn save_installer_profile_copies_raw_bytes_verbatim() {
|
||||
let instance_dir = tmp.path().join("instance");
|
||||
let meta_dir = tmp.path().join("meta");
|
||||
|
||||
// a synthetic installer version JSON with the modern arguments
|
||||
// object - exactly the shape we used to strip.
|
||||
// Preserve modern JVM arguments that older rmcl caches stripped.
|
||||
let installer_json = br#"{
|
||||
"id": "1.20.1-forge-47.2.0",
|
||||
"inheritsFrom": "1.20.1",
|
||||
@@ -111,10 +107,6 @@ fn profile_filenames_match_launch_cache_names(
|
||||
);
|
||||
}
|
||||
|
||||
// shape-pinning test: a synthetic versionInfo from a 1.7.10 forge
|
||||
// install_profile.json must deserialise as a LaunchProfile so the
|
||||
// launch flow's render_args + resolve pipeline can consume it. no
|
||||
// filesystem round-trip; serde_json directly on the literal bytes.
|
||||
#[test]
|
||||
fn legacy_forge_version_info_deserialises_as_launch_profile() {
|
||||
let bytes = br#"{
|
||||
@@ -158,10 +150,6 @@ fn legacy_forge_version_info_deserialises_as_launch_profile() {
|
||||
assert!(profile.libraries[0].downloads.is_none());
|
||||
}
|
||||
|
||||
// shape-pinning test: a synthetic upstream fabric profile (no
|
||||
// inheritsFrom, no arguments, libraries with name+url) must
|
||||
// deserialise as a LaunchProfile so the install path can write it
|
||||
// through to disk and the launch flow can read it back.
|
||||
#[test]
|
||||
fn raw_fabric_profile_bytes_parse_as_launch_profile() {
|
||||
let bytes = br#"{
|
||||
@@ -190,3 +178,179 @@ fn raw_fabric_profile_bytes_parse_as_launch_profile() {
|
||||
Some("https://maven.fabricmc.net/")
|
||||
);
|
||||
}
|
||||
|
||||
fn recording_java(temp: &Path) -> String {
|
||||
let path = temp.join(if cfg!(windows) {
|
||||
"installer java.cmd"
|
||||
} else {
|
||||
"installer java.sh"
|
||||
});
|
||||
#[cfg(windows)]
|
||||
std::fs::write(&path, "@echo off\r\n(echo %~1\r\necho %~2\r\necho %~3\r\necho %~4\r\n)>installer-args.txt\r\necho %CD%>installer-cwd.txt\r\n(echo %INSTALLER_CONTEXT%\r\necho %INSTALLER_GLOBAL%\r\n)>installer-env.txt\r\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::write(
|
||||
&path,
|
||||
"#!/bin/sh\nprintf '%s\\n' \"$@\" > installer-args.txt\npwd > installer-cwd.txt\nprintf '%s\\n' \"$INSTALLER_CONTEXT\" \"$INSTALLER_GLOBAL\" > installer-env.txt\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
path.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
#[rstest::rstest]
|
||||
#[case::forge(false)]
|
||||
#[case::neoforge(true)]
|
||||
#[tokio::test]
|
||||
async fn installers_use_merged_environment_and_minecraft_cwd(#[case] neoforge: bool) {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let instance = temp.path().join("instance with spaces");
|
||||
let minecraft = instance.join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
std::fs::create_dir_all(&minecraft).unwrap();
|
||||
let installer = minecraft.join("neoforge installer.jar");
|
||||
let java = recording_java(temp.path());
|
||||
let environment = crate::instance::java::merge_environment(
|
||||
&BTreeMap::from([
|
||||
("PATH".to_owned(), "missing-global-java".to_owned()),
|
||||
("INSTALLER_CONTEXT".to_owned(), "global".to_owned()),
|
||||
("INSTALLER_GLOBAL".to_owned(), "global-only".to_owned()),
|
||||
]),
|
||||
&BTreeMap::from([
|
||||
(
|
||||
"PATH".to_owned(),
|
||||
temp.path().to_string_lossy().into_owned(),
|
||||
),
|
||||
("INSTALLER_CONTEXT".to_owned(), "selected".to_owned()),
|
||||
]),
|
||||
);
|
||||
let java_name = Path::new(&java).file_name().unwrap().to_str().unwrap();
|
||||
if neoforge {
|
||||
super::neoforge::run_neoforge_installer(
|
||||
&installer,
|
||||
&instance,
|
||||
Some(java_name),
|
||||
&environment,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
} else {
|
||||
super::forge::run_forge_installer(&installer, &instance, Some(java_name), &environment)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let args = std::fs::read_to_string(minecraft.join("installer-args.txt")).unwrap();
|
||||
let args: Vec<_> = args.lines().collect();
|
||||
assert_eq!(
|
||||
&args[..3],
|
||||
["-jar", &installer.to_string_lossy(), "--installClient"]
|
||||
);
|
||||
if neoforge {
|
||||
assert_eq!(args[3], minecraft.to_string_lossy());
|
||||
} else {
|
||||
assert!(args[3..].iter().all(|arg| arg.trim().is_empty()));
|
||||
}
|
||||
let cwd = std::fs::read_to_string(minecraft.join("installer-cwd.txt")).unwrap();
|
||||
assert_eq!(
|
||||
Path::new(cwd.trim()).canonicalize().unwrap(),
|
||||
minecraft.canonicalize().unwrap()
|
||||
);
|
||||
assert!(!args.iter().any(|arg| arg.starts_with("-Duser.home=")));
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(minecraft.join("installer-env.txt"))
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.collect::<Vec<_>>(),
|
||||
["selected", "global-only"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_installers_do_not_leave_java_or_its_descendants_running() {
|
||||
let fixture = tempfile::tempdir().unwrap();
|
||||
let classes = fixture.path().join("classes");
|
||||
std::fs::create_dir_all(&classes).unwrap();
|
||||
let source =
|
||||
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/InstallerLifetimeFixture.java");
|
||||
let compiler = std::process::Command::new("javac")
|
||||
.args(["-source", "8", "-target", "8"])
|
||||
.arg("-d")
|
||||
.arg(&classes)
|
||||
.arg(source)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
compiler.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&compiler.stderr)
|
||||
);
|
||||
let jar = fixture.path().join("installer fixture.jar");
|
||||
let packer = std::process::Command::new("jar")
|
||||
.arg("cfe")
|
||||
.arg(&jar)
|
||||
.arg("InstallerLifetimeFixture")
|
||||
.arg("-C")
|
||||
.arg(&classes)
|
||||
.arg(".")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(
|
||||
packer.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&packer.stderr)
|
||||
);
|
||||
let java = crate::instance::java::resolve_java_path_in(
|
||||
None,
|
||||
&std::env::current_dir().unwrap(),
|
||||
&Default::default(),
|
||||
);
|
||||
for neoforge in [false, true] {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let minecraft = temp.path().join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
std::fs::create_dir_all(&minecraft).unwrap();
|
||||
{
|
||||
let future = async {
|
||||
if neoforge {
|
||||
super::neoforge::run_neoforge_installer(
|
||||
&jar,
|
||||
temp.path(),
|
||||
Some(&java),
|
||||
&Default::default(),
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
super::forge::run_forge_installer(
|
||||
&jar,
|
||||
temp.path(),
|
||||
Some(&java),
|
||||
&Default::default(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
};
|
||||
tokio::pin!(future);
|
||||
let ready = async {
|
||||
while !minecraft.join("installer-ready").is_file()
|
||||
|| !minecraft.join("installer-child-ready").is_file()
|
||||
{
|
||||
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
|
||||
}
|
||||
};
|
||||
tokio::select! {
|
||||
result = &mut future => panic!("installer exited before cancellation: {result:?}"),
|
||||
result = tokio::time::timeout(std::time::Duration::from_secs(15), ready) => result.unwrap(),
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1600)).await;
|
||||
assert!(
|
||||
!minecraft.join("installer-survived").exists(),
|
||||
"Java process survived installer cancellation"
|
||||
);
|
||||
assert!(
|
||||
!minecraft.join("installer-child-survived").exists(),
|
||||
"Java descendant survived installer cancellation"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -311,3 +311,147 @@ fn instance_names_are_portable_components() {
|
||||
assert!(validate_name(name).is_ok(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn runtime_repair_uses_selected_java_cwd_environment_and_platform() {
|
||||
use sha1::{Digest, Sha1};
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Cursor, Write};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use wiremock::matchers::{method, path};
|
||||
use wiremock::{Mock, MockServer, ResponseTemplate};
|
||||
|
||||
const ROOT: &str = "RMCL_RUNTIME_CONTEXT_TEST";
|
||||
let Some(root) = std::env::var_os(ROOT) else {
|
||||
let temp =
|
||||
tempfile::tempdir_in(Path::new(env!("CARGO_MANIFEST_DIR")).join("target")).unwrap();
|
||||
let status = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"instance::manager::tests::runtime_repair_uses_selected_java_cwd_environment_and_platform",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(ROOT, temp.path())
|
||||
.env("HOME", temp.path())
|
||||
.env("XDG_CONFIG_HOME", temp.path().join("config"))
|
||||
.current_dir(temp.path())
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success());
|
||||
return;
|
||||
};
|
||||
let root = PathBuf::from(root);
|
||||
let config_dir = crate::config::get_config_path();
|
||||
assert!(config_dir.starts_with(&root));
|
||||
std::fs::create_dir_all(&config_dir).unwrap();
|
||||
let mut settings = crate::config::Config::default();
|
||||
settings.paths.java_path = Some("context-java".to_owned());
|
||||
settings.defaults.environment = BTreeMap::from([
|
||||
("PATH".to_owned(), "global-bin".to_owned()),
|
||||
("JAVA_HOME".to_owned(), "missing-home".to_owned()),
|
||||
("RUNTIME_GLOBAL".to_owned(), "global-only".to_owned()),
|
||||
("RUNTIME_SHARED".to_owned(), "global".to_owned()),
|
||||
]);
|
||||
std::fs::write(
|
||||
config_dir.join("config.toml"),
|
||||
toml::to_string(&settings).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.unwrap();
|
||||
runtime.block_on(async {
|
||||
let server = MockServer::start().await;
|
||||
let client_jar = b"client";
|
||||
let assets = br#"{"objects":{}}"#;
|
||||
for (endpoint, body) in [("/client.jar", client_jar.as_slice()), ("/assets.json", assets.as_slice())] {
|
||||
Mock::given(method("GET"))
|
||||
.and(path(endpoint))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(body.to_vec()))
|
||||
.expect(3)
|
||||
.mount(&server).await;
|
||||
}
|
||||
let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new()));
|
||||
archive.start_file("native.bin", zip::write::SimpleFileOptions::default()).unwrap();
|
||||
archive.write_all(b"selected-native").unwrap();
|
||||
let native = archive.finish().unwrap().into_inner();
|
||||
let hash = |bytes: &[u8]| format!("{:x}", Sha1::digest(bytes));
|
||||
let manager = InstanceManager::new("instances", "meta");
|
||||
let metadata = crate::storage::MetadataPaths::new(&manager.meta_dir);
|
||||
|
||||
for (name, os, java_os, java_arch, arch, bits) in [
|
||||
("global", "linux", "Linux", "aarch64", "arm64", 64),
|
||||
("override", "windows", "Windows 11", "i386", "x86", 32),
|
||||
("relative", "osx", "Mac OS X", "amd64", "x86_64", 64),
|
||||
] {
|
||||
let mut config = dummy_config(name);
|
||||
config.game_version = name.to_owned();
|
||||
let minecraft = root.join("instances").join(name).join(crate::storage::MINECRAFT_DIR_NAME);
|
||||
let bin = if name == "global" { "global-bin" } else { "instance-bin" };
|
||||
let java = minecraft.join(bin).join("context-java");
|
||||
std::fs::create_dir_all(java.parent().unwrap()).unwrap();
|
||||
std::fs::write(&java, "#!/bin/sh\nprintf '%s\\n' \"$0\" > probe-java.txt\npwd > probe-cwd.txt\nprintf '%s\\n' \"$RUNTIME_GLOBAL\" \"$RUNTIME_SHARED\" > probe-env.txt\nprintf 'java.version = 25\\nos.name = %s\\nos.arch = %s\\nsun.arch.data.model = %s\\nos.version = fixture-os\\n' \"$RUNTIME_OS\" \"$RUNTIME_ARCH\" \"$RUNTIME_BITS\" >&2\n").unwrap();
|
||||
std::fs::set_permissions(&java, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
config.environment = BTreeMap::from([
|
||||
("RUNTIME_OS".to_owned(), java_os.to_owned()),
|
||||
("RUNTIME_ARCH".to_owned(), java_arch.to_owned()),
|
||||
("RUNTIME_BITS".to_owned(), bits.to_string()),
|
||||
("RUNTIME_SHARED".to_owned(), "instance".to_owned()),
|
||||
]);
|
||||
if name != "global" {
|
||||
config.environment.insert("PATH".to_owned(), bin.to_owned());
|
||||
}
|
||||
if name == "relative" {
|
||||
config.java_path = Some("./instance-bin/context-java".to_owned());
|
||||
}
|
||||
|
||||
let mut libraries = Vec::new();
|
||||
for (library_os, library_arch) in [("linux", "arm64"), ("windows", "x86"), ("osx", "x86_64")] {
|
||||
let mut classifiers = serde_json::Map::new();
|
||||
for native_bits in [32, 64] {
|
||||
let endpoint = format!("/{name}-{library_os}-{native_bits}.jar");
|
||||
Mock::given(method("GET"))
|
||||
.and(path(&endpoint))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_bytes(native.clone()))
|
||||
.expect(u64::from(library_os == os && native_bits == bits))
|
||||
.mount(&server).await;
|
||||
classifiers.insert(format!("natives-{native_bits}"), serde_json::json!({
|
||||
"url": format!("{}{endpoint}", server.uri()),
|
||||
"path": format!("{name}/{library_os}-{native_bits}.jar"),
|
||||
"sha1": hash(&native), "size": native.len()
|
||||
}));
|
||||
}
|
||||
libraries.push(serde_json::json!({
|
||||
"name": format!("example:{library_os}:1"),
|
||||
"rules": [{ "action": "allow", "os": { "name": library_os, "arch": library_arch, "version": "^fixture-os$" } }],
|
||||
"natives": { (library_os): "natives-${arch}" },
|
||||
"downloads": { "classifiers": classifiers }
|
||||
}));
|
||||
}
|
||||
let version_dir = metadata.versions().join(name);
|
||||
std::fs::create_dir_all(&version_dir).unwrap();
|
||||
std::fs::write(version_dir.join("meta.json"), serde_json::to_vec(&serde_json::json!({
|
||||
"id": name, "mainClass": "fixture.Main", "arguments": { "game": [], "jvm": [] },
|
||||
"assetIndex": { "id": name, "url": format!("{}/assets.json", server.uri()), "sha1": hash(assets) },
|
||||
"downloads": { "client": { "url": format!("{}/client.jar", server.uri()), "sha1": hash(client_jar), "size": client_jar.len() } },
|
||||
"libraries": libraries
|
||||
})).unwrap()).unwrap();
|
||||
|
||||
manager.repair_runtime_cache(&config).await.unwrap();
|
||||
let selected_java = std::fs::read_to_string(minecraft.join("probe-java.txt")).unwrap();
|
||||
assert_eq!(Path::new(selected_java.trim()), java);
|
||||
let cwd = std::fs::read_to_string(minecraft.join("probe-cwd.txt")).unwrap();
|
||||
assert_eq!(Path::new(cwd.trim()).canonicalize().unwrap(), minecraft.canonicalize().unwrap());
|
||||
assert_eq!(std::fs::read_to_string(minecraft.join("probe-env.txt")).unwrap(), "global-only\ninstance\n");
|
||||
assert_eq!(std::fs::read(version_dir.join("natives").join(format!("{os}-{arch}-{bits}")).join("native.bin")).unwrap(), b"selected-native");
|
||||
for (library_os, _) in [("linux", "arm64"), ("windows", "x86"), ("osx", "x86_64")] {
|
||||
for native_bits in [32, 64] {
|
||||
assert_eq!(metadata.libraries().join(name).join(format!("{library_os}-{native_bits}.jar")).exists(), library_os == os && native_bits == bits);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -29,8 +29,7 @@ pub struct LaunchProfile {
|
||||
// present only in rmcl <= 0.3.0's stripped loader-profile shape.
|
||||
// we deserialize it so the launch-time legacy-detection predicate
|
||||
// can confirm "this really is our old format, not an upstream
|
||||
// profile that happens to omit arguments". skipped on serialize so
|
||||
// we never propagate this field outward.
|
||||
// profile that happens to omit arguments". The resolver discards this field.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub game_arguments: Option<Vec<String>>,
|
||||
}
|
||||
@@ -66,16 +65,29 @@ pub struct Library {
|
||||
pub downloads: Option<LibraryDownloads>,
|
||||
pub rules: Option<Vec<Rule>>,
|
||||
pub url: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub natives: Option<std::collections::HashMap<String, String>>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub extract: Option<LibraryExtract>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct LibraryDownloads {
|
||||
pub artifact: Option<Artifact>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub classifiers: Option<std::collections::HashMap<String, Artifact>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct LibraryExtract {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub exclude: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
|
||||
pub struct Artifact {
|
||||
pub url: String,
|
||||
#[serde(default)]
|
||||
pub path: String,
|
||||
pub sha1: String,
|
||||
pub size: u64,
|
||||
|
||||
@@ -1,15 +1,6 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// merge semantics (per the mojang launcher and the major third-party
|
||||
// launchers that interoperate with it):
|
||||
// - scalar fields: child wins if Some, else parent.
|
||||
// - libraries and arguments: parent ++ child (parent first). child
|
||||
// entries are appended after parent's.
|
||||
// - merge_into preserves parent's inherits_from so resolve() can keep
|
||||
// walking; resolve() clears the final result's inherits_from after
|
||||
// the loop exits.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::model::{Arguments, LaunchProfile};
|
||||
@@ -111,6 +102,14 @@ pub async fn resolve(
|
||||
let mut depth = 0;
|
||||
|
||||
while let Some(parent_id) = current.inherits_from.clone() {
|
||||
if !crate::storage::safe_relative_path(Path::new(&parent_id))
|
||||
|| Path::new(&parent_id).components().count() != 1
|
||||
{
|
||||
return Err(ResolveError::ParseError(
|
||||
parent_id,
|
||||
"Invalid inherited version ID".to_owned(),
|
||||
));
|
||||
}
|
||||
depth += 1;
|
||||
if depth > MAX_INHERITANCE_DEPTH {
|
||||
return Err(ResolveError::DepthExceeded(MAX_INHERITANCE_DEPTH));
|
||||
|
||||
@@ -16,7 +16,7 @@ pub struct OsCondition {
|
||||
pub arch: Option<String>,
|
||||
// mojang occasionally constrains natives selection on os.version with a
|
||||
// regex. rare in practice - when present, it's a substring/anchor match
|
||||
// against the host OS version reported by `system::mojang_os_version`.
|
||||
// against os.version reported by the selected Java runtime.
|
||||
pub version: Option<String>,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,73 @@
|
||||
// SPDX-FileCopyrightText: 2026 Constantin Bauer
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
// Mojang names some things differently from rust's std::env::consts (e.g. macOS
|
||||
// is "osx" in mojang profile rules), so this module is the single source
|
||||
// of truth for translating.
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
// Native libraries and rules describe the Java process, which can have a
|
||||
// different architecture from the launcher (for example, Intel Java on macOS ARM).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct JavaPlatform {
|
||||
pub os_name: &'static str,
|
||||
pub arch: String,
|
||||
pub bitness: u32,
|
||||
pub os_version: String,
|
||||
}
|
||||
|
||||
impl JavaPlatform {
|
||||
pub fn from_java_properties(
|
||||
os_name: &str,
|
||||
arch: &str,
|
||||
bitness: &str,
|
||||
os_version: &str,
|
||||
) -> std::io::Result<Self> {
|
||||
let invalid = |message| std::io::Error::new(std::io::ErrorKind::InvalidData, message);
|
||||
let os_name = match os_name {
|
||||
name if name.starts_with("Windows") => "windows",
|
||||
"Mac OS X" | "macOS" | "Darwin" => "osx",
|
||||
"Linux" => "linux",
|
||||
other => return Err(invalid(format!("Unsupported Java os.name: {other}"))),
|
||||
};
|
||||
let arch = match arch {
|
||||
"amd64" | "x86_64" | "x64" => "x86_64",
|
||||
"x86" | "i386" | "i486" | "i586" | "i686" => "x86",
|
||||
"aarch64" | "arm64" => "arm64",
|
||||
other => other,
|
||||
};
|
||||
if arch.is_empty()
|
||||
|| !arch
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
|
||||
{
|
||||
return Err(invalid(format!("Invalid Java os.arch: {arch}")));
|
||||
}
|
||||
let bitness = match bitness {
|
||||
"32" => 32,
|
||||
"64" => 64,
|
||||
other => {
|
||||
return Err(invalid(format!(
|
||||
"Invalid Java sun.arch.data.model: {other}"
|
||||
)));
|
||||
}
|
||||
};
|
||||
if os_version.is_empty() {
|
||||
return Err(invalid("Missing Java os.version".to_owned()));
|
||||
}
|
||||
Ok(Self {
|
||||
os_name,
|
||||
arch: arch.to_owned(),
|
||||
bitness,
|
||||
os_version: os_version.to_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn natives_directory(&self, meta_dir: &Path, version: &str) -> PathBuf {
|
||||
crate::storage::MetadataPaths::new(meta_dir)
|
||||
.versions()
|
||||
.join(version)
|
||||
.join("natives")
|
||||
.join(format!("{}-{}-{}", self.os_name, self.arch, self.bitness))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mojang_os_name() -> &'static str {
|
||||
match std::env::consts::OS {
|
||||
@@ -11,29 +75,3 @@ pub fn mojang_os_name() -> &'static str {
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn mojang_arch_name() -> &'static str {
|
||||
match std::env::consts::ARCH {
|
||||
"x86" => "x86",
|
||||
"x86_64" => "x86_64",
|
||||
"aarch64" => "arm64",
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
// the host OS version string. mojang rules occasionally constrain natives
|
||||
// selection on os.version with a regex (e.g. macOS 10.x-only natives).
|
||||
// rust's stdlib doesn't expose this, so we read it where it's cheap and
|
||||
// reliable: linux via /proc/sys/kernel/osrelease, other platforms return
|
||||
// empty. when the host string is empty, version-gated rules don't match
|
||||
// (conservative default in the rule evaluator) - which is fine because
|
||||
// real-world profiles using os.version are vanishingly rare.
|
||||
pub fn mojang_os_version() -> String {
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
if let Ok(s) = std::fs::read_to_string("/proc/sys/kernel/osrelease") {
|
||||
return s.trim().to_string();
|
||||
}
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
@@ -51,7 +51,6 @@ pub fn substitute(input: &str, ctx: &TemplateContext) -> String {
|
||||
rest = &after_open[close_rel + 1..];
|
||||
}
|
||||
None => {
|
||||
// unclosed `${...` - emit the rest literally and stop.
|
||||
out.push_str("${");
|
||||
out.push_str(after_open);
|
||||
return out;
|
||||
@@ -72,10 +71,21 @@ fn lookup(name: &str, ctx: &TemplateContext) -> Option<String> {
|
||||
"classpath" => ctx.classpath.to_string(),
|
||||
"game_directory" => ctx.game_directory.display().to_string(),
|
||||
"assets_root" => ctx.assets_root.display().to_string(),
|
||||
"game_assets" => ctx
|
||||
.assets_root
|
||||
.join("virtual")
|
||||
.join(ctx.assets_index_name)
|
||||
.display()
|
||||
.to_string(),
|
||||
"assets_index_name" => ctx.assets_index_name.to_string(),
|
||||
"auth_player_name" => ctx.auth_player_name.to_string(),
|
||||
"auth_uuid" => ctx.auth_uuid.to_string(),
|
||||
"auth_access_token" => ctx.auth_access_token.to_string(),
|
||||
"auth_session" => format!(
|
||||
"token:{}:{}",
|
||||
ctx.auth_access_token,
|
||||
ctx.auth_uuid.replace('-', "")
|
||||
),
|
||||
"auth_xuid" => ctx.auth_xuid.to_string(),
|
||||
"user_type" => ctx.user_type.to_string(),
|
||||
"user_properties" => ctx.user_properties.to_string(),
|
||||
|
||||
@@ -6,10 +6,6 @@ use crate::launch_profile::model::Arguments;
|
||||
use crate::launch_profile::rules::{FeatureSet, OsCondition, Rule, RuleAction};
|
||||
use std::path::PathBuf;
|
||||
|
||||
// owns the path buffers + FeatureSet so each test just calls
|
||||
// fx.template_ctx() and fx.rule_ctx() instead of declaring four PathBufs
|
||||
// and a RuleContext inline. all tests use linux/x86_64; if a test needs
|
||||
// a different OS it sets it explicitly.
|
||||
struct Fixture {
|
||||
lib: PathBuf,
|
||||
nat: PathBuf,
|
||||
@@ -181,10 +177,6 @@ fn missing_main_class_returns_error() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn end_to_end_resolve_then_render_modern_forge_shape() {
|
||||
// exercises the full pipeline: load a synthetic vanilla profile
|
||||
// from disk, load a synthetic loader profile with inheritsFrom,
|
||||
// resolve the chain, then render args. catches integration bugs
|
||||
// that unit tests of each layer would miss.
|
||||
use crate::launch_profile::resolve;
|
||||
use tempfile::TempDir;
|
||||
|
||||
|
||||
@@ -277,6 +277,29 @@ async fn resolve_returns_unchanged_when_no_inherits_from() {
|
||||
assert!(resolved.inherits_from.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inheritance_rejects_paths_outside_the_versions_directory() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let outside = temp.path().join("cache/minecraft/outside");
|
||||
std::fs::create_dir_all(&outside).unwrap();
|
||||
std::fs::write(
|
||||
outside.join("meta.json"),
|
||||
serde_json::to_vec(&empty_profile("outside")).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
for id in [
|
||||
"../outside".to_owned(),
|
||||
outside.to_string_lossy().into_owned(),
|
||||
] {
|
||||
let mut child = empty_profile("child");
|
||||
child.inherits_from = Some(id);
|
||||
assert!(matches!(
|
||||
resolve(child, temp.path()).await,
|
||||
Err(ResolveError::ParseError(_, _))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn resolve_single_level_inheritance_merges_parent() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
|
||||
@@ -4,10 +4,6 @@
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
// owns the path buffers so tests don't have to declare them inline; the
|
||||
// ctx() method borrows from self to build a TemplateContext with the
|
||||
// standard set of values. windows() returns a fixture with backslash
|
||||
// paths so the OS-independence test stays self-contained.
|
||||
struct Fixture {
|
||||
lib: PathBuf,
|
||||
nat: PathBuf,
|
||||
@@ -129,3 +125,17 @@ fn custom_resolution_is_substituted_when_present() {
|
||||
"1920x1080"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_164_arguments_resolve_session_and_virtual_assets() {
|
||||
let fixture = Fixture::unix();
|
||||
let mut context = fixture.ctx();
|
||||
context.assets_index_name = "legacy";
|
||||
let args = substitute(
|
||||
"--username ${auth_player_name} --session ${auth_session} --version ${version_name} --gameDir ${game_directory} --assetsDir ${game_assets}",
|
||||
&context,
|
||||
);
|
||||
assert!(!args.contains("${"));
|
||||
assert!(args.contains("--session token:token:00000000000000000000000000000000"));
|
||||
assert!(args.contains(&fixture.assets.join("virtual/legacy").display().to_string()));
|
||||
}
|
||||
+157
-91
@@ -2,12 +2,8 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
collections::{HashMap, HashSet},
|
||||
path::{Path, PathBuf},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -15,6 +11,9 @@ use tokio::task::JoinSet;
|
||||
|
||||
use super::{HttpClient, NetError, download_file};
|
||||
use crate::feedback::progress::{clear, set_action, set_progress, set_sub_action};
|
||||
use crate::launch_profile::{model, system::JavaPlatform};
|
||||
|
||||
pub use model::{Artifact, LibraryDownloads, LibraryExtract};
|
||||
|
||||
const MANIFEST_URL: &str = "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json";
|
||||
const ASSETS_BASE_URL: &str = "https://resources.download.minecraft.net";
|
||||
@@ -85,32 +84,6 @@ pub struct Library {
|
||||
pub extract: Option<LibraryExtract>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct LibraryExtract {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub exclude: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct LibraryDownloads {
|
||||
pub artifact: Option<Artifact>,
|
||||
// classifier -> download info (same shape as artifact). populated on
|
||||
// libraries that declare `natives`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub classifiers: Option<HashMap<String, Artifact>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Artifact {
|
||||
pub url: String,
|
||||
// empty when upstream omits it; callers fall back to deriving the
|
||||
// relative path from the library's maven coordinate.
|
||||
#[serde(default)]
|
||||
pub path: String,
|
||||
pub sha1: String,
|
||||
pub size: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct JavaVersion {
|
||||
@@ -120,6 +93,8 @@ pub struct JavaVersion {
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct AssetIndexContent {
|
||||
pub objects: HashMap<String, AssetObject>,
|
||||
#[serde(default, rename = "virtual")]
|
||||
pub virtual_assets: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
@@ -269,33 +244,77 @@ pub async fn download_libraries(
|
||||
client: &HttpClient,
|
||||
meta: &VersionMeta,
|
||||
meta_dir: &Path,
|
||||
) -> Result<(), NetError> {
|
||||
let java = crate::instance::java::resolve_java_path(None);
|
||||
let runtime = crate::instance::java::probe_java(Path::new(&java)).await?;
|
||||
download_libraries_for_platform(client, meta, meta_dir, &runtime.platform).await
|
||||
}
|
||||
|
||||
pub async fn download_libraries_for_platform(
|
||||
client: &HttpClient,
|
||||
meta: &VersionMeta,
|
||||
meta_dir: &Path,
|
||||
platform: &JavaPlatform,
|
||||
) -> Result<(), NetError> {
|
||||
if !crate::storage::safe_relative_path(Path::new(&meta.id))
|
||||
|| Path::new(&meta.id).components().count() != 1
|
||||
{
|
||||
return Err(NetError::Parse(format!(
|
||||
"Invalid Minecraft version ID: {}",
|
||||
meta.id
|
||||
)));
|
||||
}
|
||||
let libraries: Vec<_> = meta
|
||||
.libraries
|
||||
.iter()
|
||||
.map(|lib| model::Library {
|
||||
name: lib.name.clone(),
|
||||
downloads: Some(lib.downloads.clone()),
|
||||
rules: lib.rules.clone(),
|
||||
natives: lib.natives.clone(),
|
||||
extract: lib.extract.clone(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
download_profile_libraries(
|
||||
client,
|
||||
&libraries,
|
||||
&crate::storage::MetadataPaths::new(meta_dir).libraries(),
|
||||
&platform.natives_directory(meta_dir, &meta.id),
|
||||
platform,
|
||||
&crate::launch_profile::rules::FeatureSet::default(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn download_profile_libraries(
|
||||
client: &HttpClient,
|
||||
libraries: &[model::Library],
|
||||
lib_dir: &Path,
|
||||
natives_dir: &Path,
|
||||
platform: &JavaPlatform,
|
||||
features: &crate::launch_profile::rules::FeatureSet,
|
||||
) -> Result<(), NetError> {
|
||||
set_action("Downloading libraries...");
|
||||
tracing::debug!(
|
||||
"Resolving {} libraries for Minecraft {}",
|
||||
meta.libraries.len(),
|
||||
meta.id
|
||||
"Resolving {} libraries for Java {} {}",
|
||||
libraries.len(),
|
||||
platform.os_name,
|
||||
platform.arch
|
||||
);
|
||||
|
||||
let features = crate::launch_profile::rules::FeatureSet::default();
|
||||
let host_os_version = crate::launch_profile::system::mojang_os_version();
|
||||
let rule_ctx = crate::launch_profile::rules::RuleContext {
|
||||
os_name: crate::launch_profile::system::mojang_os_name(),
|
||||
os_version: &host_os_version,
|
||||
arch: crate::launch_profile::system::mojang_arch_name(),
|
||||
features: &features,
|
||||
os_name: platform.os_name,
|
||||
os_version: &platform.os_version,
|
||||
arch: &platform.arch,
|
||||
features,
|
||||
};
|
||||
|
||||
let natives_dir = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.versions()
|
||||
.join(&meta.id)
|
||||
.join("natives");
|
||||
|
||||
let mut downloads: Vec<(String, PathBuf, String, String, u64)> = Vec::new();
|
||||
// natives jars to unpack once every download has landed:
|
||||
// (jar path inside the library cache, extract.exclude prefixes)
|
||||
let mut natives_jars: Vec<(PathBuf, Vec<String>)> = Vec::new();
|
||||
for library in &meta.libraries {
|
||||
for library in libraries {
|
||||
if let Some(rules) = &library.rules
|
||||
&& !crate::launch_profile::rules::evaluate(rules, &rule_ctx)
|
||||
{
|
||||
@@ -303,20 +322,16 @@ pub async fn download_libraries(
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(artifact) = &library.downloads.artifact {
|
||||
let rel = library_relative_path(library, artifact.path.as_str()).ok_or_else(|| {
|
||||
NetError::Parse(format!("Invalid library path for {}", library.name))
|
||||
})?;
|
||||
let destination = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.libraries()
|
||||
.join(&rel);
|
||||
if let Some(artifact) = library.downloads.as_ref().and_then(|d| d.artifact.as_ref()) {
|
||||
let rel = library_artifact_path(library)?.expect("artifact has a path");
|
||||
let destination = lib_dir.join(&rel);
|
||||
if verify_cached(&destination, &artifact.sha1, artifact.size) {
|
||||
tracing::trace!("Library already cached: {}", rel);
|
||||
tracing::trace!("Library already cached: {}", rel.display());
|
||||
} else {
|
||||
downloads.push((
|
||||
artifact.url.clone(),
|
||||
destination,
|
||||
rel,
|
||||
rel.to_string_lossy().into_owned(),
|
||||
artifact.sha1.clone(),
|
||||
artifact.size,
|
||||
));
|
||||
@@ -324,18 +339,24 @@ pub async fn download_libraries(
|
||||
}
|
||||
|
||||
// native classifier jar (pre-1.13 era libraries). the jar itself is
|
||||
// cached alongside the other libraries; its contents get unpacked
|
||||
// into versions/<id>/natives where java.library.path points.
|
||||
// cached alongside the other libraries; extraction is isolated by Java architecture.
|
||||
if let Some(classifier) = library
|
||||
.natives
|
||||
.as_ref()
|
||||
.and_then(|n| n.get(crate::launch_profile::system::mojang_os_name()))
|
||||
&& let Some(info) = library
|
||||
.downloads
|
||||
.classifiers
|
||||
.as_ref()
|
||||
.and_then(|classifiers| classifiers.get(classifier))
|
||||
.and_then(|n| n.get(platform.os_name))
|
||||
.map(|classifier| classifier.replace("${arch}", &platform.bitness.to_string()))
|
||||
{
|
||||
let info = library
|
||||
.downloads
|
||||
.as_ref()
|
||||
.and_then(|downloads| downloads.classifiers.as_ref())
|
||||
.and_then(|classifiers| classifiers.get(&classifier))
|
||||
.ok_or_else(|| {
|
||||
NetError::Parse(format!(
|
||||
"Library {} declares missing native classifier {classifier}",
|
||||
library.name
|
||||
))
|
||||
})?;
|
||||
// the maven fallback must carry the classifier: it selects
|
||||
// <artifact>-<version>-<classifier>.jar, not the base jar.
|
||||
let rel = if !info.path.is_empty() {
|
||||
@@ -355,9 +376,7 @@ pub async fn download_libraries(
|
||||
library.name
|
||||
)));
|
||||
}
|
||||
let destination = crate::storage::MetadataPaths::new(meta_dir)
|
||||
.libraries()
|
||||
.join(&rel);
|
||||
let destination = lib_dir.join(&rel);
|
||||
if !verify_cached(&destination, &info.sha1, info.size) {
|
||||
downloads.push((
|
||||
info.url.clone(),
|
||||
@@ -386,23 +405,44 @@ pub async fn download_libraries(
|
||||
clear();
|
||||
result?;
|
||||
|
||||
for (jar, exclude) in &natives_jars {
|
||||
extract_natives(jar, &natives_dir, exclude)?;
|
||||
if !natives_jars.is_empty() {
|
||||
std::fs::create_dir_all(natives_dir)?;
|
||||
let lock = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(natives_dir.join(".extract.lock"))?;
|
||||
lock.lock()?;
|
||||
for (jar, exclude) in &natives_jars {
|
||||
extract_natives(jar, natives_dir, exclude)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn library_relative_path(library: &Library, recorded_path: &str) -> Option<String> {
|
||||
let path = if recorded_path.is_empty() {
|
||||
crate::instance::loader::maven::maven_coord_to_path(&library.name)?
|
||||
} else {
|
||||
recorded_path.to_owned()
|
||||
pub(crate) fn library_artifact_path(library: &model::Library) -> Result<Option<PathBuf>, NetError> {
|
||||
let recorded_path = match &library.downloads {
|
||||
Some(downloads) => match &downloads.artifact {
|
||||
Some(artifact) => &artifact.path,
|
||||
// A classifier-only library belongs in the extraction directory, not the classpath.
|
||||
None => return Ok(None),
|
||||
},
|
||||
None => "",
|
||||
};
|
||||
crate::storage::safe_relative_path(Path::new(&path)).then_some(path)
|
||||
let path = if recorded_path.is_empty() {
|
||||
crate::instance::loader::maven::maven_coord_to_path(&library.name)
|
||||
} else {
|
||||
Some(recorded_path.to_owned())
|
||||
}
|
||||
.filter(|path| crate::storage::safe_relative_path(Path::new(path)))
|
||||
.ok_or_else(|| NetError::Parse(format!("Invalid library path for {}", library.name)))?;
|
||||
Ok(Some(PathBuf::from(path)))
|
||||
}
|
||||
|
||||
fn extract_natives(jar: &Path, dest: &Path, exclude: &[String]) -> Result<(), NetError> {
|
||||
use std::io::Read;
|
||||
let file = std::fs::File::open(jar)?;
|
||||
let mut archive = zip::ZipArchive::new(file)
|
||||
.map_err(|e| NetError::Parse(format!("Invalid natives jar {}: {e}", jar.display())))?;
|
||||
@@ -432,11 +472,22 @@ fn extract_natives(jar: &Path, dest: &Path, exclude: &[String]) -> Result<(), Ne
|
||||
continue;
|
||||
}
|
||||
let out_path = dest.join(&rel);
|
||||
if let Some(parent) = out_path.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
let mut bytes = Vec::new();
|
||||
entry.read_to_end(&mut bytes)?;
|
||||
// Reusing a loaded DLL must not truncate or replace it on another launch.
|
||||
let cached = match std::fs::read(&out_path) {
|
||||
Ok(cached) => Some(cached),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
|
||||
Err(error) => {
|
||||
return Err(NetError::Parse(format!(
|
||||
"Could not read native {}: {error}",
|
||||
out_path.display()
|
||||
)));
|
||||
}
|
||||
};
|
||||
if cached.as_deref() != Some(bytes.as_slice()) {
|
||||
crate::storage::write_atomic(&out_path, &bytes)?;
|
||||
}
|
||||
let mut out = std::fs::File::create(&out_path)?;
|
||||
std::io::copy(&mut entry, &mut out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -509,6 +560,7 @@ pub async fn download_assets_from(
|
||||
};
|
||||
|
||||
let mut downloads = Vec::new();
|
||||
let mut hashes = HashSet::new();
|
||||
for object in asset_index.objects.values() {
|
||||
if object.hash.len() != 40 || !object.hash.bytes().all(|byte| byte.is_ascii_hexdigit()) {
|
||||
clear();
|
||||
@@ -526,7 +578,7 @@ pub async fn download_assets_from(
|
||||
.join(prefix)
|
||||
.join(&object.hash);
|
||||
|
||||
if verify_cached(&destination, &object.hash, object.size) {
|
||||
if !hashes.insert(&object.hash) || verify_cached(&destination, &object.hash, object.size) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -541,18 +593,32 @@ pub async fn download_assets_from(
|
||||
|
||||
if downloads.is_empty() {
|
||||
tracing::info!("All assets already cached");
|
||||
} else if let Err(error) = run_parallel_downloads(client, downloads, true).await {
|
||||
clear();
|
||||
return Ok(());
|
||||
return Err(error);
|
||||
}
|
||||
if asset_index.virtual_assets {
|
||||
let assets = crate::storage::MetadataPaths::new(meta_dir).assets();
|
||||
for (name, object) in &asset_index.objects {
|
||||
if !crate::storage::safe_relative_path(Path::new(name)) {
|
||||
clear();
|
||||
return Err(NetError::Parse(format!(
|
||||
"Invalid virtual asset path: {name}"
|
||||
)));
|
||||
}
|
||||
let destination = assets.join("virtual").join(&meta.asset_index.id).join(name);
|
||||
if !verify_cached(&destination, &object.hash, object.size) {
|
||||
let source = assets
|
||||
.join("objects")
|
||||
.join(&object.hash[..2])
|
||||
.join(&object.hash);
|
||||
let bytes = tokio::fs::read(source).await?;
|
||||
crate::storage::write_atomic(&destination, &bytes)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tracing::debug!(
|
||||
"Downloading {} missing asset(s) from index {}",
|
||||
downloads.len(),
|
||||
meta.asset_index.id
|
||||
);
|
||||
let result = run_parallel_downloads(client, downloads, true).await;
|
||||
clear();
|
||||
result
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Continue other downloads after one fails; report the first error afterward.
|
||||
@@ -567,7 +633,7 @@ async fn run_parallel_downloads(
|
||||
total_downloads,
|
||||
MAX_CONCURRENT_DOWNLOADS
|
||||
);
|
||||
let completed = Arc::new(AtomicU64::new(0));
|
||||
let mut completed = 0;
|
||||
let mut queue = downloads.into_iter();
|
||||
let mut set = JoinSet::new();
|
||||
|
||||
@@ -585,9 +651,9 @@ async fn run_parallel_downloads(
|
||||
while let Some(join_result) = set.join_next().await {
|
||||
match join_result {
|
||||
Ok(Ok(label)) => {
|
||||
let finished = completed.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
completed += 1;
|
||||
if report_count_progress {
|
||||
set_progress(finished, total_downloads);
|
||||
set_progress(completed, total_downloads);
|
||||
}
|
||||
set_sub_action(label);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user