//! Java agents of plugins (`[[contributes.javaAgents]]`): the JVM of an Application, //! Spring Boot or JAR Application configuration gets one `-javaagent:[=]` //! per plugin whose `java.agent` capability the user granted, for Run and Debug alike, //! plus any `vmOptions` the declaration lists (before the agent). //! //! An agent bound to a plugin executor (`executor = ""`, API 1.18) is added only to //! launches through that executor ("Run with <title>" / "Debug with <title>"), whose id is //! the plugin's id. //! //! The grant records the jar's content hash; an agent whose jar no longer has it is //! left out (with a console line) until the user approves it again. The desktop //! installs the [`JavaAgentSource`]; elsewhere (`openidea-server`) there is none, so //! remote projects never get an agent. use ide_language::ProgramPin; use parking_lot::RwLock; use std::path::{Path, PathBuf}; use std::sync::Arc; /// Run configuration kinds whose JVM gets the agents. pub const KINDS: &[&str] = &["application", "spring-boot", "jar-application"]; pub fn applies(kind: &str) -> bool { KINDS.contains(&kind) } /// An agent a plugin contributes, as it stands right before a launch. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ContributedAgent { pub plugin: String, /// The jar in the plugin's package (absolute). pub jar: PathBuf, pub args: Option<String>, /// Extra JVM flags (`vmOptions`), inserted before `-javaagent:`. pub vm_options: Vec<String>, /// When `Some("jetbrains")`, `vm_options` apply only on a JetBrains Runtime. pub jdk: Option<String>, /// The jar's hash recorded when the user granted `java.agent`; `None`: not granted. pub approved_hash: Option<String>, /// The title of the plugin executor the agent is bound to: added only to its launches. pub executor: Option<String>, } /// The agents of the enabled plugins. pub trait JavaAgentSource: Send + Sync { fn agents(&self) -> Vec<ContributedAgent>; } static SOURCE: RwLock<Option<Arc<dyn JavaAgentSource>>> = RwLock::new(None); /// Installs (or removes) the source [`current`] / [`current_for`] read. pub fn set_java_agent_source(source: Option<Arc<dyn JavaAgentSource>>) { *SOURCE.write() = source; } /// What a launch adds: VM options then `-javaagent:` options, and a console line per skip. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Agents { pub options: Vec<String>, pub notes: Vec<String>, } /// The agents the installed source allows now (none without a source); no JDK gate. pub fn current() -> Agents { current_for(None) } /// Like [`current`], gating `vmOptions` with `jdk = "jetbrains"` against `java`. pub fn current_for(java: Option<&Path>) -> Agents { current_for_executor(java, None) } /// Like [`current_for`] for a launch through `executor` (a plugin id) or a plain one. pub fn current_for_executor(java: Option<&Path>, executor: Option<&str>) -> Agents { let source = SOURCE.read().clone(); match source { Some(s) => for_executor(&s.agents(), java, executor), None => { Agents { options: Vec::new(), notes: executor.map(|e| missing_executor(e, None)).into_iter().collect() } } } } /// The agents a launch gets: those bound to no executor, plus the one of `executor` (a plugin /// id). A launch through an executor whose agent is not there or not granted says so. pub fn for_executor(agents: &[ContributedAgent], java: Option<&Path>, executor: Option<&str>) -> Agents { let chosen: Vec<ContributedAgent> = agents.iter().filter(|a| a.executor.is_none() || (executor == Some(a.plugin.as_str()))).cloned().collect(); let mut out = approved_for(&chosen, java); if let Some(executor) = executor { let own = agents.iter().find(|a| a.plugin == executor && a.executor.is_some()); if own.is_none_or(|a| a.approved_hash.is_none()) { out.notes.push(missing_executor(executor, own.and_then(|a| a.executor.as_deref()))); } } out } fn missing_executor(plugin: &str, title: Option<&str>) -> String { match title { Some(title) => format!( "{title} was not applied: the Java agent of plugin {plugin} needs the java.agent permission (Settings › Plugins)." ), None => format!("The executor of plugin {plugin} is not available: the plugin is disabled or was removed."), } } /// Granted agents whose jar still has the hash approved for it; an ungranted one is /// left out silently, a changed or missing jar with a note. pub fn approved(agents: &[ContributedAgent]) -> Agents { approved_for(agents, None) } /// Like [`approved`], applying `vmOptions` only when the JDK filter matches `java`. pub fn approved_for(agents: &[ContributedAgent], java: Option<&Path>) -> Agents { let mut out = Agents::default(); for agent in agents { let Some(hash) = &agent.approved_hash else { continue }; let pin = ProgramPin { path: agent.jar.clone(), hash: hash.clone() }; match pin.verify() { Ok(jar) => { push_vm_options(&mut out, agent, java); let opt = option(jar, agent.args.as_deref()); if !out.options.contains(&opt) { out.options.push(opt); } } Err(e) => out.notes.push(format!("The Java agent of plugin {} was not added: {e}", agent.plugin)), } } out } fn push_vm_options(out: &mut Agents, agent: &ContributedAgent, java: Option<&Path>) { if agent.vm_options.is_empty() { return; } if !jdk_allows(java, agent.jdk.as_deref()) { out.notes.push(format!( "JVM options of plugin {} were not added: they require a {} JDK.", agent.plugin, agent.jdk.as_deref().unwrap_or("matching") )); return; } for opt in &agent.vm_options { if !out.options.contains(opt) { out.options.push(opt.clone()); } } } /// `jdk = "jetbrains"` matches JetBrains Runtime; unknown `java` / unknown filter → skip options. pub fn jdk_allows(java: Option<&Path>, filter: Option<&str>) -> bool { match filter.map(str::trim).filter(|s| !s.is_empty()) { None => true, Some("jetbrains") => java.map(is_jetbrains_jdk).unwrap_or(false), Some(_) => false, } } fn is_jetbrains_jdk(java: &Path) -> bool { release_field(java, "IMPLEMENTOR").is_some_and(|v| v.to_ascii_lowercase().contains("jetbrains")) } /// The JVM a configuration whose command is `command` starts, for the JDK filter. A path is /// itself. A bare `java` is the first one on `search`, as the launch finds it; when that is /// no JDK's own launcher (macOS's `/usr/bin/java` stub, which runs `JAVA_HOME`'s), it is /// `java_home`'s. `None` when neither is found. pub fn launched_java(command: &str, search: &std::ffi::OsStr, java_home: Option<&Path>) -> Option<PathBuf> { let path = Path::new(command); if path.components().count() > 1 { return Some(path.to_path_buf()); } let windows = cfg!(windows); let found = ide_core::process::find_executable_in(command, search, windows, std::env::var("PATHEXT").ok().as_deref()); if let Some(java) = &found && release_field(java, "JAVA_VERSION").is_some() { return found; } let java = java_home.map(|home| home.join("bin").join(if windows { "java.exe" } else { "java" })); java.filter(|java| java.is_file()).or(found) } /// `KEY="value"` from the JDK `release` file next to `bin/java` (or JDK 8's `jre/bin/java`). fn release_field(java: &Path, key: &str) -> Option<String> { let java = std::fs::canonicalize(java).unwrap_or_else(|_| java.to_path_buf()); let prefix = format!("{key}="); java.ancestors().skip(2).take(2).find_map(|home| { let text = std::fs::read_to_string(home.join("release")).ok()?; text.lines().find_map(|l| { let l = l.trim(); l.strip_prefix(&prefix).map(|v| v.trim().trim_matches('"').to_owned()) }) }) } /// `-javaagent:<jar>[=<args>]`, one argument: the JVM takes the path as it is, spaces included. pub fn option(jar: &Path, args: Option<&str>) -> String { match args.filter(|a| !a.is_empty()) { Some(args) => format!("-javaagent:{}={args}", jar.display()), None => format!("-javaagent:{}", jar.display()), } } /// Adds `options` to `java` arguments after the VM options (before the main class or /// `-jar`), each as its own argument; one already there is not added again. pub fn add_to_args(args: &mut Vec<String>, options: &[String]) { let mut at = crate::java_cmdline::vm_options_end(args); for option in options { if args[..at].contains(option) { continue; } args.insert(at, option.clone()); at += 1; } } /// The same for a list of VM options (the Kotlin debugger's `vmArguments`). pub fn add_to_vm_args(vm_args: &mut Vec<String>, options: &[String]) { for option in options { if !vm_args.contains(option) { vm_args.push(option.clone()); } } } /// The same for VM options written as one line (java-debug's `vmArgs`): an option with /// spaces is quoted the way the debugger's launch arguments are. pub fn add_to_vm_args_text(vm_args: &str, options: &[String]) -> String { let present = split_text(vm_args); let mut out = vm_args.trim().to_owned(); for option in options { if present.contains(option) { continue; } if !out.is_empty() { out.push(' '); } out.push_str("e(option)); } out } /// As the frontend's `joinJavaArgs` writes one argument. fn quote(arg: &str) -> String { if !arg.is_empty() && !arg.contains(|c: char| c.is_whitespace() || c == '"') { return arg.to_owned(); } let mut out = String::from('"'); for c in arg.chars() { if c == '"' || c == '\\' { out.push('\\'); } out.push(c); } out.push('"'); out } /// Splits a line of arguments written by [`quote`] (or by hand: unquoted words). fn split_text(text: &str) -> Vec<String> { let mut out = Vec::new(); let mut chars = text.chars().peekable(); loop { while chars.next_if(|c| c.is_whitespace()).is_some() {} if chars.peek().is_none() { return out; } let mut arg = String::new(); let mut quoted = false; while let Some(c) = chars.next() { match c { '"' => quoted = !quoted, '\\' if quoted && matches!(chars.peek(), Some('"' | '\\')) => arg.extend(chars.next()), c if c.is_whitespace() && !quoted => break, c => arg.push(c), } } out.push(arg); } } #[cfg(test)] mod tests { use super::*; /// A JDK home with `bin/java` and a `release` file naming `implementor`. #[cfg(unix)] fn jdk(root: &Path, name: &str, implementor: &str) -> PathBuf { let home = root.join(name); std::fs::create_dir_all(home.join("bin")).unwrap(); std::fs::write(home.join("bin/java"), "#!/bin/sh\n").unwrap(); use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(home.join("bin/java"), std::fs::Permissions::from_mode(0o755)).unwrap(); std::fs::write(home.join("release"), format!("JAVA_VERSION=\"21\"\nIMPLEMENTOR=\"{implementor}\"\n")).unwrap(); home } #[cfg(unix)] #[test] fn a_bare_java_is_the_one_the_launch_finds() { use std::os::unix::fs::PermissionsExt; let dir = tempfile::tempdir().unwrap(); let jbr = jdk(dir.path(), "jbr", "JetBrains s.r.o."); let openjdk = jdk(dir.path(), "openjdk", "Eclipse Adoptium"); // A JDK's own launcher on the search path is what runs, whatever JAVA_HOME says. let search = std::env::join_paths([jbr.join("bin")]).unwrap(); let java = launched_java("java", &search, Some(&openjdk)).unwrap(); assert!(jdk_allows(Some(&java), Some("jetbrains"))); // A stub outside any JDK (macOS /usr/bin/java) runs JAVA_HOME's. let stub = dir.path().join("usr/bin"); std::fs::create_dir_all(&stub).unwrap(); std::fs::write(stub.join("java"), "#!/bin/sh\n").unwrap(); std::fs::set_permissions(stub.join("java"), std::fs::Permissions::from_mode(0o755)).unwrap(); let search = std::env::join_paths([stub]).unwrap(); let java = launched_java("java", &search, Some(&jbr)).unwrap(); assert!(jdk_allows(Some(&java), Some("jetbrains"))); assert!(!jdk_allows(launched_java("java", &search, Some(&openjdk)).as_deref(), Some("jetbrains"))); // A path is itself. assert_eq!(launched_java("/opt/jdk/bin/java", &search, Some(&jbr)), Some(PathBuf::from("/opt/jdk/bin/java"))); } fn strings(a: &[&str]) -> Vec<String> { a.iter().map(|s| (*s).to_owned()).collect() } struct Jar { _dir: tempfile::TempDir, path: PathBuf, hash: String, } /// An agent jar in a directory whose name has a space. fn jar() -> Jar { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("my plugins").join("agent.jar"); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, b"PK agent").unwrap(); let hash = ProgramPin::approve(&path).unwrap().hash; Jar { _dir: dir, path, hash } } fn agent(jar: &Jar, args: Option<&str>, granted: bool) -> ContributedAgent { ContributedAgent { plugin: "acme.spring".into(), jar: jar.path.clone(), args: args.map(str::to_owned), vm_options: Vec::new(), jdk: None, approved_hash: granted.then(|| jar.hash.clone()), executor: None, } } fn with_vm(mut agent: ContributedAgent, opts: &[&str], jdk: Option<&str>) -> ContributedAgent { agent.vm_options = opts.iter().map(|s| (*s).to_owned()).collect(); agent.jdk = jdk.map(str::to_owned); agent } #[test] fn only_granted_agents_with_their_approved_jar_are_added() { let jar = jar(); assert_eq!(approved(&[agent(&jar, None, false)]), Agents::default(), "no grant: nothing, silently"); let granted = approved(&[agent(&jar, Some("port=0"), true)]); assert_eq!(granted.options, [format!("-javaagent:{}=port=0", jar.path.display())]); assert!(granted.notes.is_empty()); std::fs::write(&jar.path, b"PK swapped").unwrap(); let changed = approved(&[agent(&jar, None, true)]); assert!(changed.options.is_empty()); assert_eq!(changed.notes.len(), 1); assert!(changed.notes[0].contains("acme.spring") && changed.notes[0].contains("changed since it was approved")); std::fs::remove_file(&jar.path).unwrap(); let missing = approved(&[agent(&jar, None, true)]); assert!(missing.options.is_empty() && missing.notes.len() == 1); } #[test] fn run_adds_one_argument_after_the_vm_options() { let jar = jar(); let options = approved(&[agent(&jar, None, true)]).options; let option = format!("-javaagent:{}", jar.path.display()); assert!(option.contains("my plugins"), "the path keeps its space, unquoted: {option}"); // Application / Spring Boot: after the user's VM options and the classpath, before the main class. let mut args = strings(&["-Xmx1g", "-cp", "/p/classes", "app.Main", "--server.port=0"]); add_to_args(&mut args, &options); assert_eq!(args, strings(&["-Xmx1g", "-cp", "/p/classes", &option, "app.Main", "--server.port=0"])); // Already there (the user added it, or a second pass): not added again. let again = args.clone(); add_to_args(&mut args, &options); assert_eq!(args, again); // JAR Application, Debug: after the JDWP agent and the user's options, before `-jar`. let jdwp = "-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0"; let mut args = strings(&[jdwp, "-Dx=1", "-jar", "app.jar", "-v"]); add_to_args(&mut args, &options); assert_eq!(args, strings(&[jdwp, "-Dx=1", &option, "-jar", "app.jar", "-v"])); // A program argument equal to the option is not a VM option. let mut args = strings(&["app.Main", &option]); add_to_args(&mut args, &options); assert_eq!(args, strings(&[&option, "app.Main", &option])); let mut untouched = strings(&["-cp", "x", "Main"]); add_to_args(&mut untouched, &[]); assert_eq!(untouched, strings(&["-cp", "x", "Main"])); } #[test] fn a_shortened_command_line_keeps_the_agent_as_its_own_argument() { let jar = jar(); let options = approved(&[agent(&jar, None, true)]).options; let classpath = vec!["/home/u/.m2/repository/org/x/lib/1.0/lib-1.0.jar"; 4000].join(":"); let mut args = strings(&["-Xmx1g", "-cp", &classpath, "app.Main"]); add_to_args(&mut args, &options); let dir = tempfile::tempdir().unwrap(); let jdk = dir.path().join("jdk"); std::fs::create_dir_all(jdk.join("bin")).unwrap(); std::fs::write(jdk.join("release"), "JAVA_VERSION=\"21.0.3\"").unwrap(); let shortened = crate::java_cmdline::shorten(&jdk.join("bin/java"), &args, dir.path(), false, dir.path()) .unwrap() .expect("too long for one argument"); assert_eq!(shortened.how, crate::java_cmdline::Shortening::ArgFile); // Only the classpath moves into the argfile; the agent stays one argument, path and all. assert_eq!(shortened.args.len(), 4); assert_eq!(shortened.args[2], options[0]); assert!(!std::fs::read_to_string(&shortened.file).unwrap().contains("javaagent")); } #[test] fn debug_adds_the_option_to_the_debuggers_vm_options() { let jar = jar(); let options = approved(&[agent(&jar, Some("trace sql"), true)]).options; let option = format!("-javaagent:{}=trace sql", jar.path.display()); assert_eq!(options, std::slice::from_ref(&option)); // java-debug: one line, quoted like the frontend quotes VM options with spaces. let text = add_to_vm_args_text("-Xmx1g -Dspring.output.ansi.enabled=always", &options); assert!(text.starts_with("-Xmx1g -Dspring.output.ansi.enabled=always \"-javaagent:"), "{text}"); assert_eq!(split_text(&text), strings(&["-Xmx1g", "-Dspring.output.ansi.enabled=always", &option])); assert_eq!(add_to_vm_args_text(&text, &options), text, "not added twice"); assert_eq!(split_text(&add_to_vm_args_text("", &options)), std::slice::from_ref(&option)); assert_eq!(add_to_vm_args_text(" -Xmx1g ", &[]), "-Xmx1g"); // The Kotlin debugger: a list. let mut list = strings(&["-Xmx1g"]); add_to_vm_args(&mut list, &options); add_to_vm_args(&mut list, &options); assert_eq!(list, strings(&["-Xmx1g", &option])); } #[test] fn quoting_round_trips() { for arg in ["plain", "with space", r#"q"uote"#, r"C:\Program Files\a.jar", ""] { assert_eq!(split_text("e(arg)), [arg.to_owned()], "{arg}"); } assert_eq!(split_text(" a \"b c\" d "), strings(&["a", "b c", "d"])); } #[test] fn kinds() { for kind in ["application", "spring-boot", "jar-application"] { assert!(applies(kind), "{kind}"); } for kind in ["junit", "maven", "gradle", "tomcat", "java-file", "remote-jvm-debug"] { assert!(!applies(kind), "{kind}"); } } #[test] fn vm_options_go_before_the_javaagent_and_dedupe() { let jar = jar(); let agent = with_vm(agent(&jar, None, true), &["-XX:+AllowEnhancedClassRedefinition", "-Xmx1g"], None); let granted = approved(&[agent]); let javaagent = format!("-javaagent:{}", jar.path.display()); assert_eq!(granted.options, ["-XX:+AllowEnhancedClassRedefinition".into(), "-Xmx1g".into(), javaagent.clone()]); let mut args = strings(&["-Xmx1g", "-cp", "/p/classes", "app.Main"]); add_to_args(&mut args, &granted.options); // User already has `-Xmx1g`: only the new flag and the agent are inserted. assert_eq!( args, strings(&["-Xmx1g", "-cp", "/p/classes", "-XX:+AllowEnhancedClassRedefinition", &javaagent, "app.Main"]) ); let mut again = strings(&["-XX:+AllowEnhancedClassRedefinition", "-cp", "x", "Main"]); add_to_args(&mut again, &["-XX:+AllowEnhancedClassRedefinition".into(), javaagent.clone()]); assert_eq!(again, strings(&["-XX:+AllowEnhancedClassRedefinition", "-cp", "x", &javaagent, "Main"])); } #[test] fn an_executor_agent_loads_only_through_its_executor() { let (plain_jar, bound_jar) = (jar(), jar()); let plain = agent(&plain_jar, None, true); let mut bound = agent(&bound_jar, None, true); bound.plugin = "acme.reload".into(); bound.executor = Some("Hot Reload".into()); let agents = [plain, bound.clone()]; let plain_opt = format!("-javaagent:{}", plain_jar.path.display()); let bound_opt = format!("-javaagent:{}", bound_jar.path.display()); let run = for_executor(&agents, None, None); assert_eq!(run.options, std::slice::from_ref(&plain_opt), "a plain launch leaves the executor's agent out"); assert!(run.notes.is_empty()); let with = for_executor(&agents, None, Some("acme.reload")); assert_eq!(with.options, [plain_opt.clone(), bound_opt]); assert!(with.notes.is_empty()); // Another plugin's executor id: only the plain agent, and a note. let other = for_executor(&agents, None, Some("acme.spring")); assert_eq!(other.options, std::slice::from_ref(&plain_opt)); assert_eq!(other.notes.len(), 1); bound.approved_hash = None; let ungranted = for_executor(&[bound], None, Some("acme.reload")); assert!(ungranted.options.is_empty()); assert!(ungranted.notes[0].starts_with("Hot Reload was not applied"), "{:?}", ungranted.notes); } #[test] fn jetbrains_vm_options_skip_on_other_jdks() { let jar = jar(); let dir = tempfile::tempdir().unwrap(); let jbr = dir.path().join("jbr"); std::fs::create_dir_all(jbr.join("bin")).unwrap(); std::fs::write(jbr.join("release"), "JAVA_VERSION=\"17\"\nIMPLEMENTOR=\"JetBrains s.r.o.\"\n").unwrap(); let temurin = dir.path().join("temurin"); std::fs::create_dir_all(temurin.join("bin")).unwrap(); std::fs::write(temurin.join("release"), "JAVA_VERSION=\"17\"\nIMPLEMENTOR=\"Eclipse Adoptium\"\n").unwrap(); let agent = with_vm(agent(&jar, None, true), &["-XX:+AllowEnhancedClassRedefinition"], Some("jetbrains")); let on_jbr = approved_for(std::slice::from_ref(&agent), Some(&jbr.join("bin/java"))); assert!(on_jbr.options.iter().any(|o| o == "-XX:+AllowEnhancedClassRedefinition")); assert!(on_jbr.notes.is_empty()); let on_other = approved_for(std::slice::from_ref(&agent), Some(&temurin.join("bin/java"))); assert!(!on_other.options.iter().any(|o| o == "-XX:+AllowEnhancedClassRedefinition")); assert!(on_other.options.iter().any(|o| o.starts_with("-javaagent:"))); assert_eq!(on_other.notes.len(), 1); let unknown = approved_for(&[agent], None); assert!(!unknown.options.iter().any(|o| o == "-XX:+AllowEnhancedClassRedefinition")); assert!(unknown.options.iter().any(|o| o.starts_with("-javaagent:"))); } }