Skip to content

Pass system properties into Minecraft (+ some launch code cleanup) #3822

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ flate2 = "1.1.2"
fs4 = { version = "0.13.1", default-features = false }
futures = { version = "0.3.31", default-features = false }
futures-util = "0.3.31"
hashlink = "0.10.0"
hex = "0.4.3"
hickory-resolver = "0.25.2"
hmac = "0.12.1"
Expand Down
2 changes: 1 addition & 1 deletion apps/app-frontend/src/components/ui/JavaSelector.vue
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ async function handleJavaFileInput() {
const filePath = await open()

if (filePath) {
let result = await get_jre(filePath.path ?? filePath)
let result = await get_jre(filePath.path ?? filePath).catch(handleError)
if (!result) {
result = {
path: filePath.path ?? filePath,
Expand Down
4 changes: 2 additions & 2 deletions apps/app/src/api/jre.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ pub async fn jre_find_filtered_jres(
// Validates JRE at a given path
// Returns None if the path is not a valid JRE
#[tauri::command]
pub async fn jre_get_jre(path: PathBuf) -> Result<Option<JavaVersion>> {
jre::check_jre(path).await.map_err(|e| e.into())
pub async fn jre_get_jre(path: PathBuf) -> Result<JavaVersion> {
Ok(jre::check_jre(path).await?)
}

// Tests JRE of a certain version
Expand Down
1 change: 0 additions & 1 deletion apps/app/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"providerShortName": null,
"signingIdentity": null
},
"resources": [],
"shortDescription": "",
"linux": {
"deb": {
Expand Down
1 change: 1 addition & 0 deletions packages/app-lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ quick-xml = { workspace = true, features = ["async-tokio"] }
enumset.workspace = true
chardetng.workspace = true
encoding_rs.workspace = true
hashlink.workspace = true

chrono = { workspace = true, features = ["serde"] }
daedalus.workspace = true
Expand Down
34 changes: 17 additions & 17 deletions packages/app-lib/library/JavaInfo.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
public final class JavaInfo {
private static final String[] CHECKED_PROPERTIES = new String[] {
"os.arch",
"java.version"
};
private static final String[] CHECKED_PROPERTIES = new String[] {
"os.arch",
"java.version"
};

public static void main(String[] args) {
int returnCode = 0;
public static void main(String[] args) {
int returnCode = 0;

for (String key : CHECKED_PROPERTIES) {
String property = System.getProperty(key);
for (String key : CHECKED_PROPERTIES) {
String property = System.getProperty(key);

if (property != null) {
System.out.println(key + "=" + property);
} else {
returnCode = 1;
}
}

System.exit(returnCode);
if (property != null) {
System.out.println(key + "=" + property);
} else {
returnCode = 1;
}
}
}

System.exit(returnCode);
}
}
Binary file added packages/app-lib/library/MinecraftLaunch.class
Binary file not shown.
118 changes: 118 additions & 0 deletions packages/app-lib/library/MinecraftLaunch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;

public final class MinecraftLaunch {
public static void main(String[] args) throws IOException, ReflectiveOperationException {
final String mainClass = args[0];
final String[] gameArgs = Arrays.copyOfRange(args, 1, args.length);

System.setProperty("modrinth.process.args", String.join("\u001f", gameArgs));
parseInput();

relaunch(mainClass, gameArgs);
}

private static void parseInput() throws IOException {
final ByteArrayOutputStream line = new ByteArrayOutputStream();
while (true) {
final int b = System.in.read();
if (b < 0) {
throw new IllegalStateException("Stdin terminated while parsing");
}
if (b != '\n') {
line.write(b);
continue;
}
if (handleLine(line.toString("UTF-8"))) {
break;
}
line.reset();
}
}

private static boolean handleLine(String line) {
final String[] parts = line.split("\t", 2);
switch (parts[0]) {
case "property": {
final String[] keyValue = parts[1].split("\t", 2);
System.setProperty(keyValue[0], keyValue[1]);
return false;
}
case "launch":
return true;
}

System.err.println("Unknown input line " + line);
return false;
}

private static void relaunch(String mainClassName, String[] args) throws ReflectiveOperationException {
final int javaVersion = getJavaVersion();
final Class<?> mainClass = Class.forName(mainClassName);

if (javaVersion >= 25) {
Method mainMethod;
try {
mainMethod = findMainMethodJep512(mainClass);
} catch (ReflectiveOperationException e) {
System.err
.println("[MODRINTH] Unable to call JDK findMainMethod. Falling back to pre-Java 25 main method finding.");
// If the above fails due to JDK implementation details changing
try {
mainMethod = findSimpleMainMethod(mainClass);
} catch (ReflectiveOperationException innerE) {
e.addSuppressed(innerE);
throw e;
}
}
if (mainMethod == null) {
throw new IllegalArgumentException("Could not find main() method");
}

Object thisObject = null;
if (!Modifier.isStatic(mainMethod.getModifiers())) {
thisObject = mainClass.getDeclaredConstructor().newInstance();
}

final Object[] parameters = mainMethod.getParameterCount() > 0
? new Object[] { args }
: new Object[] {};

mainMethod.invoke(thisObject, parameters);
} else {
findSimpleMainMethod(mainClass).invoke(null, new Object[] { args });
}
}

private static int getJavaVersion() {
String javaVersion = System.getProperty("java.version");

final int dotIndex = javaVersion.indexOf('.');
if (dotIndex != -1) {
javaVersion = javaVersion.substring(0, dotIndex);
}

final int dashIndex = javaVersion.indexOf('-');
if (dashIndex != -1) {
javaVersion = javaVersion.substring(0, dashIndex);
}

return Integer.parseInt(javaVersion);
}

private static Method findMainMethodJep512(Class<?> mainClass) throws ReflectiveOperationException {
// BEWARE BELOW: This code may break if JDK internals to find the main method
// change.
final Class<?> methodFinderClass = Class.forName("jdk.internal.misc.MethodFinder");
final Method methodFinderMethod = methodFinderClass.getDeclaredMethod("findMainMethod", Class.class);
final Object result = methodFinderMethod.invoke(null, mainClass);
return (Method) result;
}

private static Method findSimpleMainMethod(Class<?> mainClass) throws NoSuchMethodException {
return mainClass.getMethod("main", String[].class);
}
}
16 changes: 8 additions & 8 deletions packages/app-lib/src/api/jre.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::path::PathBuf;
use sysinfo::{MemoryRefreshKind, RefreshKind};

use crate::util::io;
use crate::util::jre::extract_java_majorminor_version;
use crate::util::jre::extract_java_version;
use crate::{
LoadingBarType, State,
util::jre::{self},
Expand Down Expand Up @@ -38,9 +38,9 @@ pub async fn find_filtered_jres(
Ok(if let Some(java_version) = java_version {
jres.into_iter()
.filter(|jre| {
let jre_version = extract_java_majorminor_version(&jre.version);
let jre_version = extract_java_version(&jre.version);
if let Ok(jre_version) = jre_version {
jre_version.1 == java_version
jre_version == java_version
} else {
false
}
Expand Down Expand Up @@ -157,20 +157,20 @@ pub async fn auto_install_java(java_version: u32) -> crate::Result<PathBuf> {
}

// Validates JRE at a given at a given path
pub async fn check_jre(path: PathBuf) -> crate::Result<Option<JavaVersion>> {
Ok(jre::check_java_at_filepath(&path).await)
pub async fn check_jre(path: PathBuf) -> crate::Result<JavaVersion> {
jre::check_java_at_filepath(&path).await
}

// Test JRE at a given path
pub async fn test_jre(
path: PathBuf,
major_version: u32,
) -> crate::Result<bool> {
let Some(jre) = jre::check_java_at_filepath(&path).await else {
let Ok(jre) = jre::check_java_at_filepath(&path).await else {
return Ok(false);
};
let (major, _) = extract_java_majorminor_version(&jre.version)?;
Ok(major == major_version)
let version = extract_java_version(&jre.version)?;
Ok(version == major_version)
}

// Gets maximum memory in KiB.
Expand Down
34 changes: 18 additions & 16 deletions packages/app-lib/src/launcher/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use daedalus::{
modded::SidedDataEntry,
};
use dunce::canonicalize;
use std::collections::HashSet;
use hashlink::LinkedHashSet;
use std::io::{BufRead, BufReader};
use std::{collections::HashMap, path::Path};
use uuid::Uuid;
Expand All @@ -24,7 +24,7 @@ const TEMPORARY_REPLACE_CHAR: &str = "\n";
pub fn get_class_paths(
libraries_path: &Path,
libraries: &[Library],
client_path: &Path,
launcher_class_path: &[&Path],
java_arch: &str,
minecraft_updated: bool,
) -> crate::Result<String> {
Expand All @@ -48,20 +48,22 @@ pub fn get_class_paths(

Some(get_lib_path(libraries_path, &library.name, false))
})
.collect::<Result<HashSet<_>, _>>()?;

cps.insert(
canonicalize(client_path)
.map_err(|_| {
crate::ErrorKind::LauncherError(format!(
"Specified class path {} does not exist",
client_path.to_string_lossy()
))
.as_error()
})?
.to_string_lossy()
.to_string(),
);
.collect::<Result<LinkedHashSet<_>, _>>()?;

for launcher_path in launcher_class_path {
cps.insert(
canonicalize(launcher_path)
.map_err(|_| {
crate::ErrorKind::LauncherError(format!(
"Specified class path {} does not exist",
launcher_path.to_string_lossy()
))
.as_error()
})?
.to_string_lossy()
.to_string(),
);
}

Ok(cps
.into_iter()
Expand Down
Loading