From c4b2d24d7e1c6dfe7ca35c156fcbad1eb28f2c0c Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Sun, 6 Dec 2026 20:29:20 +0800 Subject: [PATCH] fix(core): keep the IDE's temporary files in a folder only this user can open (#8378) Several features wrote into fixed or guessable names directly under the system temporary folder, which every user shares on Linux: the terminal's shell integration scripts, Gradle init scripts, Java argument files, binaries and classes of single-file runs, jdtls' temporary folder, the TypeScript watch scratch folder, Claude and Copilot session files, the Android emulator and Xcode build logs, CPU profiles, `devicectl` output and the throwaway Docker config. Another local user could create those folders first and have the IDE user run their code, or read and overwrite the files. They now all live under `/openidea-` (`ide_core::private_temp`), created owner-only; a name that belongs to someone else or is a symbolic link is never used, and a folder of a random name takes its place for that run. Co-authored-by: rohitdanda <10144914+rohitdanda@users.noreply.github.com> --- crates/ide-agent/src/native/claude/mod.rs | 8 +- crates/ide-agent/src/native/copilot/mod.rs | 3 +- crates/ide-android/src/lib.rs | 2 +- crates/ide-build/src/compile/tsc_watch.rs | 7 +- crates/ide-core/src/lib.rs | 1 + crates/ide-core/src/private_temp.rs | 97 +++++++++++++++++++++ crates/ide-dap/src/js_debug.rs | 4 +- crates/ide-dap/src/session.rs | 4 +- crates/ide-docker/src/connection.rs | 7 +- crates/ide-host/src/mcp/run/output.rs | 26 +----- crates/ide-host/src/ops/run.rs | 8 +- crates/ide-host/src/ops/run/commands.rs | 6 +- crates/ide-host/src/ops/run/java_file.rs | 6 +- crates/ide-host/src/ops/sdk.rs | 10 ++- crates/ide-run/src/gradle_jvm.rs | 6 +- crates/ide-run/src/java_cmdline.rs | 4 +- crates/ide-run/src/process.rs | 11 ++- crates/ide-run/src/simulator.rs | 3 +- crates/ide-run/tests/integration/process.rs | 2 +- crates/ide-sdk/src/jdtls_workspaces.rs | 10 ++- crates/ide-sdk/src/locate.rs | 7 +- crates/ide-terminal/src/integration.rs | 13 +-- 22 files changed, 156 insertions(+), 89 deletions(-) create mode 100644 crates/ide-core/src/private_temp.rs diff --git a/crates/ide-agent/src/native/claude/mod.rs b/crates/ide-agent/src/native/claude/mod.rs index ac6d2109e9..13175e5304 100644 --- a/crates/ide-agent/src/native/claude/mod.rs +++ b/crates/ide-agent/src/native/claude/mod.rs @@ -3,9 +3,9 @@ //! //! Each ACP session runs its own `claude` process, whose session id is the ACP one. //! The CLI writes a session's transcript only once it has a message, so a fork or an -//! undo that has not been prompted yet is kept as a pending start (`/openidea-claude/ -//! .json`): loading that session, from this connection or a fresh one, starts it that -//! way. +//! undo that has not been prompted yet is kept as a pending start (`claude/.json` in this +//! user's temporary folder, `ide_core::private_temp`): loading that session, from this +//! connection or a fresh one, starts it that way. pub(crate) mod cli; pub(crate) mod history; @@ -62,7 +62,7 @@ pub(crate) fn connect( args: spec.args.clone(), env: spec.env.clone(), config_dir: cli::config_dir(&spec.env), - pending_dir: std::env::temp_dir().join("openidea-claude"), + pending_dir: ide_core::private_temp::dir("claude")?, cwd: cwd.to_path_buf(), }; let shim = Shim::new(config, Arc::new(cli::Process), Arc::from(on_stderr)); diff --git a/crates/ide-agent/src/native/copilot/mod.rs b/crates/ide-agent/src/native/copilot/mod.rs index 25432b5e09..6585bee74a 100644 --- a/crates/ide-agent/src/native/copilot/mod.rs +++ b/crates/ide-agent/src/native/copilot/mod.rs @@ -1404,8 +1404,7 @@ fn write_temp_image(session_id: &str, mime: &str, base64_data: &str) -> Option

IdeResult<()> { fn start_emulator(emulator: &Path, avd: &str) -> IdeResult<()> { let name: String = avd.chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect(); - let log_path = std::env::temp_dir().join(format!("openidea-emulator-{name}.log")); + let log_path = ide_core::private_temp::dir("android")?.join(format!("emulator-{name}.log")); let log = std::fs::File::create(&log_path)?; let mut cmd = Command::new(emulator); cmd.arg("-avd").arg(avd); diff --git a/crates/ide-build/src/compile/tsc_watch.rs b/crates/ide-build/src/compile/tsc_watch.rs index 4ab908a889..6fa963c89b 100644 --- a/crates/ide-build/src/compile/tsc_watch.rs +++ b/crates/ide-build/src/compile/tsc_watch.rs @@ -213,11 +213,8 @@ impl Scratch { use std::hash::{Hash, Hasher}; let mut hash = std::collections::hash_map::DefaultHasher::new(); config.hash(&mut hash); - let dir = std::env::temp_dir().join("openidea-tsc-watch").join(format!( - "{}-{:016x}", - std::process::id(), - hash.finish() - )); + let dir = + ide_core::private_temp::dir("tsc-watch")?.join(format!("{}-{:016x}", std::process::id(), hash.finish())); // Fresh: a `.tsbuildinfo` left by an earlier run would make tsc skip unchanged projects. let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir)?; diff --git a/crates/ide-core/src/lib.rs b/crates/ide-core/src/lib.rs index b283d33d57..4a50a06fba 100644 --- a/crates/ide-core/src/lib.rs +++ b/crates/ide-core/src/lib.rs @@ -24,6 +24,7 @@ pub mod network_path; pub mod output_encoding; pub mod output_rate; pub mod platform; +pub mod private_temp; pub mod process; pub mod project_dir; pub mod project_env; diff --git a/crates/ide-core/src/private_temp.rs b/crates/ide-core/src/private_temp.rs new file mode 100644 index 0000000000..0e53f81f71 --- /dev/null +++ b/crates/ide-core/src/private_temp.rs @@ -0,0 +1,97 @@ +//! Folders of this user in the system temporary folder. +//! +//! `/tmp` is shared by every user on Linux, so a fixed name there (`/tmp/openidea-gradle`) can be +//! created first by another user, who then controls the scripts, argument files and binaries +//! written into it. Everything goes under `/openidea-`, created owner-only; when that +//! name belongs to someone else or is a symbolic link, under a folder of a random name instead. + +use std::io; +use std::path::PathBuf; + +/// `/openidea-/`, created when missing. `name` is a plain folder name. +pub fn dir(name: &str) -> io::Result { + debug_assert!(!name.is_empty() && !name.contains(['/', '\\']), "{name}"); + let dir = root()?.join(name); + std::fs::create_dir_all(&dir)?; + Ok(dir) +} + +#[cfg(unix)] +fn root() -> io::Result { + use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt}; + static TAKEN: std::sync::OnceLock = std::sync::OnceLock::new(); + if let Some(own) = TAKEN.get() { + return Ok(own.clone()); + } + // SAFETY: `geteuid` has no preconditions and cannot fail. + let uid = unsafe { libc::geteuid() }; + let root = std::env::temp_dir().join(format!("openidea-{uid}")); + match std::fs::DirBuilder::new().mode(0o700).create(&root) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {} + Err(e) => return Err(e), + } + let meta = std::fs::symlink_metadata(&root)?; + if !meta.is_dir() || meta.uid() != uid { + // Someone else took the name: a fresh folder of a random name for the rest of this run, + // rather than no temporary files at all. + let own = unique(&root)?; + return Ok(TAKEN.get_or_init(|| own).clone()); + } + if meta.mode() & 0o077 != 0 { + std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700))?; + } + Ok(root) +} + +/// `-XXXXXX`, created owner-only by `mkdtemp`. +#[cfg(unix)] +fn unique(root: &std::path::Path) -> io::Result { + use std::os::unix::ffi::{OsStrExt, OsStringExt}; + let mut template = root.as_os_str().as_bytes().to_vec(); + template.extend_from_slice(b"-XXXXXX\0"); + // SAFETY: `template` is a writable, NUL-terminated buffer that outlives the call. + if unsafe { libc::mkdtemp(template.as_mut_ptr().cast()) }.is_null() { + return Err(io::Error::last_os_error()); + } + template.pop(); + Ok(PathBuf::from(std::ffi::OsString::from_vec(template))) +} + +/// The temporary folder is the user's own (`%LOCALAPPDATA%\Temp`). +#[cfg(not(unix))] +fn root() -> io::Result { + Ok(std::env::temp_dir().join("openidea")) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + + #[test] + fn folders_are_under_an_owner_only_root() { + let made = dir("private-temp-test").unwrap(); + let root = made.parent().unwrap(); + let meta = std::fs::symlink_metadata(root).unwrap(); + assert_eq!(meta.mode() & 0o777, 0o700); + assert_eq!(meta.uid(), unsafe { libc::geteuid() }); + assert!(root.starts_with(std::env::temp_dir())); + assert!(made.is_dir()); + // A root left group- or world-accessible is narrowed again. + std::fs::set_permissions(root, std::fs::Permissions::from_mode(0o755)).unwrap(); + dir("private-temp-test").unwrap(); + assert_eq!(std::fs::symlink_metadata(root).unwrap().mode() & 0o777, 0o700); + let _ = std::fs::remove_dir(&made); + } + + #[test] + fn a_taken_name_falls_back_to_a_fresh_owner_only_folder() { + let tmp = tempfile::tempdir().unwrap(); + let a = unique(&tmp.path().join("openidea-1")).unwrap(); + let b = unique(&tmp.path().join("openidea-1")).unwrap(); + assert_ne!(a, b); + assert!(a.file_name().unwrap().to_string_lossy().starts_with("openidea-1-")); + assert_eq!(std::fs::symlink_metadata(&a).unwrap().mode() & 0o777, 0o700); + } +} diff --git a/crates/ide-dap/src/js_debug.rs b/crates/ide-dap/src/js_debug.rs index b87541e589..d0724cc054 100644 --- a/crates/ide-dap/src/js_debug.rs +++ b/crates/ide-dap/src/js_debug.rs @@ -78,8 +78,8 @@ impl DebugManager { }; self.js_page_request(s, "stopProfile", json!({})).await?; static HANDED_OVER: AtomicU32 = AtomicU32::new(0); - let dir = std::env::temp_dir().join(format!( - "openidea-js-profile-{}-{}-{}", + let dir = ide_core::private_temp::dir("js-profile")?.join(format!( + "{}-{}-{}", std::process::id(), s.0, HANDED_OVER.fetch_add(1, Ordering::Relaxed) diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs index c508c03ec0..c1173e67f6 100644 --- a/crates/ide-dap/src/session.rs +++ b/crates/ide-dap/src/session.rs @@ -1373,7 +1373,7 @@ fn json_args_len(args: &Value, key: &str) -> usize { pub(crate) fn shorten_java_analyzer_classpath(s: &Arc, args: &mut Value) -> ide_core::IdeResult<()> { let cwd = args.get("cwd").and_then(Value::as_str).map(PathBuf::from).unwrap_or_else(|| s.spec.cwd.clone()); if let Some(jar) = - shorten_java_analyzer_classpath_with(args, &cwd, cfg!(windows), &ide_run::java_cmdline::default_temp_dir())? + shorten_java_analyzer_classpath_with(args, &cwd, cfg!(windows), &ide_run::java_cmdline::default_temp_dir()?)? { s.temp_files.lock().push(TempFile(jar)); } @@ -1444,7 +1444,7 @@ pub(crate) async fn start_kotlin_debuggee(s: &Arc, args: &mut Value) -> &java_args, &s.spec.cwd, cfg!(windows), - &ide_run::java_cmdline::default_temp_dir(), + &ide_run::java_cmdline::default_temp_dir()?, )? { java_args = shortened.args; s.temp_files.lock().push(TempFile(shortened.file)); diff --git a/crates/ide-docker/src/connection.rs b/crates/ide-docker/src/connection.rs index a402d51f4f..07d3b8fac5 100644 --- a/crates/ide-docker/src/connection.rs +++ b/crates/ide-docker/src/connection.rs @@ -304,13 +304,8 @@ impl TempConfig { pub fn new() -> IdeResult { let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0); - let dir = std::env::temp_dir().join(format!("openidea-docker-{}-{nanos}", std::process::id())); + let dir = ide_core::private_temp::dir("docker")?.join(format!("{}-{nanos}", std::process::id())); std::fs::create_dir_all(&dir)?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let _ = std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)); - } if let Some(contexts) = user_config_dir().map(|d| d.join("contexts")).filter(|d| d.is_dir()) { let _ = copy_dir(&contexts, &dir.join("contexts")); } diff --git a/crates/ide-host/src/mcp/run/output.rs b/crates/ide-host/src/mcp/run/output.rs index 3f228c41a8..8233da6be0 100644 --- a/crates/ide-host/src/mcp/run/output.rs +++ b/crates/ide-host/src/mcp/run/output.rs @@ -117,31 +117,7 @@ fn remove_old_logs(dir: &Path, max_age: std::time::Duration) { /// A directory only this user can read: output may hold secrets, and `/tmp` is shared on Linux. fn output_dir() -> IdeResult { - #[cfg(unix)] - { - use std::os::unix::fs::{DirBuilderExt, MetadataExt}; - let uid = rustix::process::getuid().as_raw(); - let dir = std::env::temp_dir().join(format!("openidea-mcp-{uid}")); - match std::fs::DirBuilder::new().mode(0o700).create(&dir) { - Ok(()) => {} - Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} - Err(e) => return Err(e.into()), - } - let meta = std::fs::symlink_metadata(&dir)?; - if !meta.is_dir() || meta.uid() != uid || meta.mode() & 0o077 != 0 { - return Err(ide_core::IdeError::new( - ide_core::error::ErrorKind::PermissionDenied, - format!("{} is not a private directory of this user", dir.display()), - )); - } - Ok(dir) - } - #[cfg(not(unix))] - { - let dir = std::env::temp_dir().join("openidea-mcp"); - std::fs::create_dir_all(&dir)?; - Ok(dir) - } + Ok(ide_core::private_temp::dir("mcp")?) } #[cfg(test)] diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs index 9d652fe8e6..c07f9b1441 100644 --- a/crates/ide-host/src/ops/run.rs +++ b/crates/ide-host/src/ops/run.rs @@ -736,10 +736,10 @@ fn split_build_log( let name: String = config.id.chars().map(|c| if c.is_ascii_alphanumeric() || "._-".contains(c) { c } else { '_' }).collect(); let project_key = project.cache_dir.file_name().unwrap_or_default(); - let path = std::env::temp_dir().join("openidea-xcode-build").join(project_key).join(format!("{name}.log")); - let file = std::fs::create_dir_all(path.parent().unwrap_or(&path)) - .and_then(|()| std::fs::File::create(&path)) - .map(std::io::BufWriter::new); + let dir = ide_core::private_temp::dir("xcode-build").map(|d| d.join(project_key)); + let path = dir.as_ref().map(|d| d.join(format!("{name}.log"))).unwrap_or_default(); + let file = + dir.and_then(std::fs::create_dir_all).and_then(|()| std::fs::File::create(&path)).map(std::io::BufWriter::new); let file = match file { Ok(file) => Some(file), Err(e) => { diff --git a/crates/ide-host/src/ops/run/commands.rs b/crates/ide-host/src/ops/run/commands.rs index d1f9cc7d0b..c302f41d4a 100644 --- a/crates/ide-host/src/ops/run/commands.rs +++ b/crates/ide-host/src/ops/run/commands.rs @@ -173,7 +173,8 @@ pub async fn run_env_files(files: Vec) -> IdeResult) -> IdeResult { // The forked JVMs: `bootRun`, `run`, tests; the path is for `--init-script`. tokio::task::spawn_blocking(move || { - ide_run::gradle_jvm::write_init_script(&ide_run::gradle_jvm::default_dir(), &jvm_args) + ide_run::gradle_jvm::default_dir() + .and_then(|dir| ide_run::gradle_jvm::write_init_script(&dir, &jvm_args)) .map(|p| p.to_string_lossy().into_owned()) .map_err(|e| IdeError::internal(format!("cannot write the Gradle init script: {e}"))) }) @@ -189,7 +190,8 @@ pub async fn run_gradle_init_script(name: String, text: String) -> IdeResult Option { } /// A stable directory per source file, so a rebuild reuses classes of unchanged files. -fn compile_dir(file: &Path) -> PathBuf { +fn compile_dir(file: &Path) -> std::io::Result { let mut hasher = std::collections::hash_map::DefaultHasher::new(); file.hash(&mut hasher); let stem: String = file @@ -201,7 +201,7 @@ fn compile_dir(file: &Path) -> PathBuf { .chars() .map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '-' }) .collect(); - std::env::temp_dir().join("openidea-run").join(format!("java-{stem}-{:x}", hasher.finish())) + Ok(ide_core::private_temp::dir("run")?.join(format!("java-{stem}-{:x}", hasher.finish()))) } /// Replaces `config` with `java -cp ` after compiling the file with the @@ -274,7 +274,7 @@ pub(super) async fn prepare( } let sources = module.as_ref().map(|m| m.sources.as_slice()).unwrap_or_default(); let libraries = module.as_ref().map(|m| m.libraries.as_slice()).unwrap_or_default(); - let out = compile_dir(&file); + let out = compile_dir(&file).map_err(|e| IdeError::internal(format!("Cannot create the output folder ({e})")))?; std::fs::create_dir_all(&out).map_err(|e| IdeError::internal(format!("Cannot create {} ({e})", out.display())))?; let mut args: Vec = vec!["-g".into(), "-d".into(), out.to_string_lossy().into_owned()]; if !libraries.is_empty() { diff --git a/crates/ide-host/src/ops/sdk.rs b/crates/ide-host/src/ops/sdk.rs index bb67b55496..69376c397d 100644 --- a/crates/ide-host/src/ops/sdk.rs +++ b/crates/ide-host/src/ops/sdk.rs @@ -408,10 +408,12 @@ pub async fn sdk_locate_tools( near: Option, ) -> IdeResult { host.require_trust_if_project(window)?; - blocking_value(move || LocatedTools { - tools: ide_sdk::locate::locate_tools(&names, near.as_deref()), - compile_dir: ide_sdk::locate::compile_dir().into(), - macos_sysroot: ide_sdk::locate::macos_sysroot().map(Into::into), + blocking(move || { + Ok(LocatedTools { + tools: ide_sdk::locate::locate_tools(&names, near.as_deref()), + compile_dir: ide_sdk::locate::compile_dir()?.into(), + macos_sysroot: ide_sdk::locate::macos_sysroot().map(Into::into), + }) }) .await } diff --git a/crates/ide-run/src/gradle_jvm.rs b/crates/ide-run/src/gradle_jvm.rs index 4e9875de93..67058993e3 100644 --- a/crates/ide-run/src/gradle_jvm.rs +++ b/crates/ide-run/src/gradle_jvm.rs @@ -54,9 +54,9 @@ pub fn init_script(jvm_args: &[String]) -> String { ) } -/// Where the scripts are written. -pub fn default_dir() -> PathBuf { - std::env::temp_dir().join("openidea-gradle") +/// Where the scripts are written: a folder of this user, as Gradle runs what it finds there. +pub fn default_dir() -> std::io::Result { + ide_core::private_temp::dir("gradle") } /// Writes the script for `jvm_args` under `dir` (named by its content, so launches share diff --git a/crates/ide-run/src/java_cmdline.rs b/crates/ide-run/src/java_cmdline.rs index 8b681062b8..e6a725793d 100644 --- a/crates/ide-run/src/java_cmdline.rs +++ b/crates/ide-run/src/java_cmdline.rs @@ -238,8 +238,8 @@ pub fn shorten_classpath_to_jar( } /// Where launches put their pathing jars / argfiles. -pub fn default_temp_dir() -> PathBuf { - std::env::temp_dir().join("openidea-classpath") +pub fn default_temp_dir() -> std::io::Result { + ide_core::private_temp::dir("classpath") } fn temp_file(dir: &Path, ext: &str) -> PathBuf { diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rs index 5dd55c7e62..437fc7f628 100644 --- a/crates/ide-run/src/process.rs +++ b/crates/ide-run/src/process.rs @@ -271,7 +271,8 @@ fn shorten_java(inv: &mut Invocation, config: &RunConfig, cwd: &Path) -> IdeResu } else { inv.program.clone() }; - let dir = crate::java_cmdline::default_temp_dir(); + let dir = crate::java_cmdline::default_temp_dir() + .map_err(|e| IdeError::internal(format!("cannot shorten the command line: {e}")))?; let shortened = crate::java_cmdline::shorten(&java, &inv.args, cwd, cfg!(windows), &dir) .map_err(|e| IdeError::internal(format!("cannot shorten the command line: {e}")))?; let Some(s) = shortened else { return Ok(TempFile(None)) }; @@ -307,11 +308,9 @@ fn match_console_encoding( env.vars.extend(fix.env); let mut prepend = fix.java_args; if fix.gradle_init_script { - match crate::gradle_jvm::write_script( - &crate::gradle_jvm::default_dir(), - "file-encoding", - output_encoding::GRADLE_FILE_ENCODING_SCRIPT, - ) { + match crate::gradle_jvm::default_dir().and_then(|dir| { + crate::gradle_jvm::write_script(&dir, "file-encoding", output_encoding::GRADLE_FILE_ENCODING_SCRIPT) + }) { Ok(script) => prepend.extend(["--init-script".to_owned(), script.to_string_lossy().into_owned()]), Err(e) => tracing::warn!("cannot write the Gradle file.encoding init script: {e}"), } diff --git a/crates/ide-run/src/simulator.rs b/crates/ide-run/src/simulator.rs index 2c2137e233..f47a56b255 100644 --- a/crates/ide-run/src/simulator.rs +++ b/crates/ide-run/src/simulator.rs @@ -128,7 +128,8 @@ pub fn parse_devices(json: &str) -> IdeResult> { /// `devicectl` (Xcode 15 and later) is missing or fails. `dir` picks the project's Xcode. pub fn devices(dir: &Path) -> Vec { let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_nanos(); - let file = std::env::temp_dir().join(format!("openidea-devicectl-{}-{stamp}.json", std::process::id())); + let Ok(out) = ide_core::private_temp::dir("devicectl") else { return Vec::new() }; + let file = out.join(format!("{}-{stamp}.json", std::process::id())); let path = file.to_string_lossy().into_owned(); let listed = run_in(Some(dir), "xcrun", &["devicectl", "list", "devices", "--quiet", "--json-output", &path]); let json = std::fs::read_to_string(&file); diff --git a/crates/ide-run/tests/integration/process.rs b/crates/ide-run/tests/integration/process.rs index d757cccc6b..8d6a8e343c 100644 --- a/crates/ide-run/tests/integration/process.rs +++ b/crates/ide-run/tests/integration/process.rs @@ -624,7 +624,7 @@ fn long_java_classpath_is_shortened() { let file = first .split(' ') .map(|a| a.trim_matches('\'').trim_start_matches('@')) - .find(|a| a.contains("openidea-classpath")) + .find(|a| a.contains("/classpath/classpath-")) .unwrap_or_else(|| panic!("no pathing jar / argfile in {first}")); assert!(!Path::new(file).exists(), "{file} not deleted"); } diff --git a/crates/ide-sdk/src/jdtls_workspaces.rs b/crates/ide-sdk/src/jdtls_workspaces.rs index 78d5d4c6b3..26ecd60d8e 100644 --- a/crates/ide-sdk/src/jdtls_workspaces.rs +++ b/crates/ide-sdk/src/jdtls_workspaces.rs @@ -28,8 +28,8 @@ fn workspace(cfg: &LanguageServerConfig) -> Option<&Path> { cfg.args.iter().position(|a| a == "-data").and_then(|i| cfg.args.get(i + 1)).map(Path::new) } -/// jdtls' temporary folder for `workspace`: `/.tmp`, or a folder of its own in the -/// system temporary folder when the workspace path has whitespace (macOS's `Application Support`). +/// jdtls' temporary folder for `workspace`: `/.tmp`, or a folder of its own in this +/// user's temporary folder when the workspace path has whitespace (macOS's `Application Support`). /// Buildship writes its Gradle init script there and later splits the stored arguments at spaces, /// so a path with a space reaches Gradle cut off and every Gradle import fails. fn temp_dir(workspace: &Path) -> PathBuf { @@ -42,8 +42,10 @@ fn temp_dir(workspace: &Path) -> PathBuf { .to_string_lossy() .bytes() .fold(0xcbf2_9ce4_8422_2325_u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)); - let shared = std::env::temp_dir().join(format!("openidea-jdtls-{hash:016x}")); - if has_whitespace(&shared) { own } else { shared } + match ide_core::private_temp::dir("jdtls") { + Ok(dir) if !has_whitespace(&dir) => dir.join(format!("{hash:016x}")), + _ => own, + } } fn has_whitespace(path: &Path) -> bool { diff --git a/crates/ide-sdk/src/locate.rs b/crates/ide-sdk/src/locate.rs index ca0b4a5ad1..8153aa6963 100644 --- a/crates/ide-sdk/src/locate.rs +++ b/crates/ide-sdk/src/locate.rs @@ -116,9 +116,10 @@ fn jdk_tool(name: &str, jdks: &[crate::java::Jdk]) -> Option { Some(jdk.home.join("bin").join(crate::exe(name))).filter(|p| p.is_file()) } -/// Directory for binaries compiled from single source files (`rustc`, `clang`). -pub fn compile_dir() -> PathBuf { - std::env::temp_dir().join("openidea-run") +/// Directory for binaries compiled from single source files (`rustc`, `clang`): a folder of this +/// user, as the binaries in it are run. +pub fn compile_dir() -> std::io::Result { + ide_core::private_temp::dir("run") } /// The macOS SDK to pass to `clang -isysroot`. A newer compiler (e.g. Homebrew LLVM) diff --git a/crates/ide-terminal/src/integration.rs b/crates/ide-terminal/src/integration.rs index 95b92569b4..519a4674dd 100644 --- a/crates/ide-terminal/src/integration.rs +++ b/crates/ide-terminal/src/integration.rs @@ -178,15 +178,11 @@ const POWERSHELL_ARGS: [&str; 5] = ["-ExecutionPolicy", "Bypass", "-NoExit", "-C /// Directory holding the generated startup files (written on demand). Keyed by the scripts' /// content as well as the version, so builds with different scripts (a dev build next to a /// release, two checkouts on one machine) never rewrite each other's files under a starting shell. -fn scripts_dir() -> PathBuf { +fn scripts_dir() -> std::io::Result { use std::hash::{Hash, Hasher}; let mut hasher = std::hash::DefaultHasher::new(); (ZSHENV, ZPROFILE, ZSHRC, ZLOGIN, BASHRC).hash(&mut hasher); - std::env::temp_dir().join(format!( - "openidea-shell-integration-{}-{:016x}", - env!("CARGO_PKG_VERSION"), - hasher.finish() - )) + ide_core::private_temp::dir(&format!("shell-integration-{}-{:016x}", env!("CARGO_PKG_VERSION"), hasher.finish())) } /// Writes through a temporary file and a rename, so a shell (or another process doing the @@ -228,10 +224,9 @@ pub(crate) fn apply(shell_name: &str, args: &mut Vec, env: &mut BTreeMap return false; } let shell_name = if windows_bash { "bash" } else { shell_name }; - let dir = scripts_dir(); let result = match shell_name { "zsh" => (|| -> std::io::Result<()> { - let zdir = dir.join("zsh"); + let zdir = scripts_dir()?.join("zsh"); write_if_changed(&zdir.join(".zshenv"), ZSHENV)?; write_if_changed(&zdir.join(".zprofile"), ZPROFILE)?; write_if_changed(&zdir.join(".zshrc"), ZSHRC)?; @@ -249,7 +244,7 @@ pub(crate) fn apply(shell_name: &str, args: &mut Vec, env: &mut BTreeMap return false; } (|| -> std::io::Result<()> { - let rc = dir.join("bash").join("openidea.bashrc"); + let rc = scripts_dir()?.join("bash").join("openidea.bashrc"); write_if_changed(&rc, BASHRC)?; if args.iter().any(|a| a == "-l" || a == "--login") { env.insert("OPENIDEA_LOGIN".into(), "1".into());