diff --git a/crates/ide-dap/src/jvm_memory/mod.rs b/crates/ide-dap/src/jvm_memory/mod.rs index ce710d6f97..e2e519c094 100644 --- a/crates/ide-dap/src/jvm_memory/mod.rs +++ b/crates/ide-dap/src/jvm_memory/mod.rs @@ -1,5 +1,6 @@ //! Class-table snapshots of a debugged JVM, read over the HotSpot attach listener or, where -//! that is unavailable, counted by the debugger; and the JVM's objects through the debugger. +//! that is unavailable, counted by the debugger; the JVM's objects through the debugger; and +//! its thread dumps. mod fallback; mod heap; @@ -10,6 +11,7 @@ mod snapshot; pub(crate) mod test_support; #[cfg(test)] mod tests; +mod threads; use crate::session::Session; use crate::session::Suspension; @@ -28,6 +30,8 @@ pub(crate) use inspect::{fields, instances, referrers, set_inspector, vm_target, pub(crate) use scan::watch_for_attached_jvm; pub(crate) use scan::{JvmFinder, attach_target, find_attached_jvm, find_local_jvm, local_jdwp_port}; use snapshot::{AttachProbe, JdkProbe, take_snapshot}; +pub use threads::{JvmThreadDump, JvmThreadsResult, JvmThreadsUnavailable, run_jvm_thread_dump}; +pub(crate) use threads::{debugged_run_thread_dump, session_thread_dump}; pub const JVM_MEMORY_ADAPTERS: &[&str] = &["java-debug", crate::kotlin::ADAPTER, crate::kotlin_lsp::ADAPTER]; pub const HISTOGRAM_TIMEOUT: Duration = Duration::from_secs(10); @@ -190,6 +194,25 @@ fn histogram_pid(session: &Session) -> Result, JvmMemoryUnavailable> Ok(None) } +/// Whether `session` is a JVM session attached to `run` that may hold `pid`: its JVM is `pid` or +/// not located yet. +pub(crate) fn attached_to_run(session: &Session, run: ide_core::RunId, pid: u32) -> bool { + let located = session.jvm_pid.load(Ordering::Acquire); + session.run == Some(run) + && JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str()) + && !session.terminated.load(Ordering::Acquire) + && (located <= 0 || located == i64::from(pid)) +} + +/// Whether `session` debugs the JVM `pid`: the program it launched or the JVM its attach found. +pub(crate) fn debugs_jvm(session: &Session, pid: u32) -> bool { + let jvm = if session.request == "launch" { launch_pid(session) } else { session.jvm_pid.load(Ordering::Acquire) }; + JVM_MEMORY_ADAPTERS.contains(&session.adapter.as_str()) + && !session.terminated.load(Ordering::Acquire) + && jvm > 0 + && jvm == i64::from(pid) +} + /// The JVM a launch session started: the one the IDE started for an app-launched (Kotlin) /// session, else the program the adapter reported; 0 when neither is known. pub(crate) fn launch_pid(session: &Session) -> i64 { @@ -206,6 +229,8 @@ pub(crate) enum JvmTarget<'a> { /// The JVM of an attach session. While `pid` is 0 it is looked up by `jdwp_port`, which is /// `None` for a remote JVM. Attached { pid: &'a AtomicI64, jdwp_port: Option }, + /// A JVM the session debugs, found from outside it (in a run's process tree). + Known(i32), /// Known without asking any JVM: no histogram can be taken, for this reason. Unavailable(JvmMemoryUnavailable), } @@ -261,6 +286,7 @@ async fn histogram( fn lookup(target: JvmTarget<'_>) -> Result { match target { JvmTarget::Launched(pid) => Ok(Lookup::Tree(pid)), + JvmTarget::Known(pid) => Ok(Lookup::Known(pid)), JvmTarget::Attached { pid, jdwp_port } => match i32::try_from(pid.load(Ordering::Acquire)) { Ok(p) if p > 0 => Ok(Lookup::Known(p)), _ => jdwp_port.map(Lookup::Scan).ok_or(JvmMemoryUnavailable::AttachedJvmNotFound), diff --git a/crates/ide-dap/src/jvm_memory/snapshot.rs b/crates/ide-dap/src/jvm_memory/snapshot.rs index ddaddd02ea..ce674aca48 100644 --- a/crates/ide-dap/src/jvm_memory/snapshot.rs +++ b/crates/ide-dap/src/jvm_memory/snapshot.rs @@ -15,7 +15,8 @@ use std::time::Duration; const VERSION_TIMEOUT: Duration = Duration::from_secs(2); const FLAGS_TIMEOUT: Duration = Duration::from_secs(2); -/// The attach calls a snapshot or a heap dump makes, so tests can stand in for a JVM. +/// The attach calls a snapshot, a heap dump or a thread dump makes, so tests can stand in for a +/// JVM. pub(crate) trait AttachProbe: Send + Sync { fn has_listener(&self, pid: u32) -> bool; /// Asks only the JVMs whose pid `may_query` accepts. @@ -27,6 +28,11 @@ pub(crate) trait AttachProbe: Send + Sync { fn heap_dump(&self, pid: u32, path: &Path, timeout: Duration) -> Result; /// `None` where the free space is not known. fn free_bytes(&self, dir: &Path) -> Option; + fn thread_print(&self, pid: u32) -> Result; + /// Opens `pid`'s attach listener unless it runs; refuses a process not confirmed HotSpot. + fn ensure_listener(&self, pid: u32) -> Result<(), AttachError>; + /// Confirmed HotSpot and not one of Gradle's own JVMs; asks the JVM nothing. + fn is_application_jvm(&self, pid: u32) -> bool; } pub(super) struct JdkProbe { @@ -73,6 +79,18 @@ impl AttachProbe for JdkProbe { fn free_bytes(&self, dir: &Path) -> Option { ide_heap::free_bytes(dir) } + + fn thread_print(&self, pid: u32) -> Result { + ide_jvm_attach::thread_print(pid, ide_jvm_attach::THREAD_DUMP_TIMEOUT) + } + + fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> { + ide_jvm_attach::ensure_listener(pid, ide_jvm_attach::LISTENER_START_TIMEOUT) + } + + fn is_application_jvm(&self, pid: u32) -> bool { + ide_jvm_attach::is_application_jvm(pid) + } } fn alive(pid: u32) -> bool { diff --git a/crates/ide-dap/src/jvm_memory/tests.rs b/crates/ide-dap/src/jvm_memory/tests.rs index 003574ebe8..545573437b 100644 --- a/crates/ide-dap/src/jvm_memory/tests.rs +++ b/crates/ide-dap/src/jvm_memory/tests.rs @@ -3,6 +3,7 @@ use super::heap::*; use super::scan::*; use super::snapshot::*; use super::test_support::{BareSession, FakeInspector, bare_session, bare_session_of}; +use super::threads::*; use super::*; use ide_core::CancellationToken; use ide_jvm_attach::{AttachError, HeapDumpReply, HistogramRow, JavaVersion}; @@ -39,6 +40,13 @@ struct FakeProbe { free: Option, /// Answering this command stops the program: runs the hook. stops_on: Option<(&'static str, StopHook)>, + thread_dumps: parking_lot::Mutex>>, + /// Replies to `ensure_listener`, in order; `Ok` once empty. + listener_starts: parking_lot::Mutex>>, + /// Pids `is_application_jvm` confirms. + application_jvms: Vec, + /// Pids `ensure_listener` was asked for. + ensured: parking_lot::Mutex>, } type StopHook = Box; @@ -97,6 +105,10 @@ impl FakeProbe { dump_bytes: 64, free: None, stops_on: None, + thread_dumps: parking_lot::Mutex::new(VecDeque::new()), + listener_starts: parking_lot::Mutex::new(VecDeque::new()), + application_jvms: Vec::new(), + ensured: parking_lot::Mutex::new(Vec::new()), } } @@ -167,6 +179,20 @@ impl AttachProbe for FakeProbe { fn free_bytes(&self, _dir: &Path) -> Option { self.free } + fn thread_print(&self, _pid: u32) -> Result { + self.enter("thread_print"); + std::thread::sleep(self.delay); + self.leave(); + self.thread_dumps.lock().pop_front().expect("unexpected thread dump request") + } + fn ensure_listener(&self, pid: u32) -> Result<(), AttachError> { + self.record("ensure_listener"); + self.ensured.lock().push(pid); + self.listener_starts.lock().pop_front().unwrap_or(Ok(())) + } + fn is_application_jvm(&self, pid: u32) -> bool { + self.application_jvms.contains(&pid) + } } const FLAGS: &str = "-XX:+UseCompressedOops -XX:+StartAttachListener"; @@ -1160,6 +1186,341 @@ async fn jdk11_is_refused_while_the_link_is_suspended_before_dap_stops() { assert!(!dir.exists()); } +const THREADS: &str = "Full thread dump OpenJDK 64-Bit Server VM (21.0.5+11-LTS mixed mode, sharing):\n\n\"main\" #1 [259] prio=5 os_prio=31 cpu=31.20ms elapsed=1.70s tid=0x1 nid=259 runnable [0x2]\n java.lang.Thread.State: RUNNABLE\n"; + +fn dumping_threads(listener: u32, dumps: Vec>) -> FakeProbe { + let fake = FakeProbe::new(listener, Vec::new()); + *fake.thread_dumps.lock() = dumps.into(); + fake +} + +fn threads_unavailable(r: JvmThreadsResult) -> JvmThreadsUnavailable { + match r { + JvmThreadsResult::Unavailable { reason } => reason, + other => panic!("{other:?}"), + } +} + +fn threads_jvm(reason: JvmMemoryUnavailable) -> JvmThreadsUnavailable { + JvmThreadsUnavailable::Jvm { reason } +} + +#[test] +fn threads_while_running_start_the_listener() { + let fake = dumping_threads(99, vec![Ok(THREADS.into())]); + let r = dump_threads(&fake, 12, false); + let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") }; + assert_eq!((dump.text.as_str(), dump.pid, dump.java_version.as_str()), (THREADS, 12, "21.0.5")); + assert!(!dump.taken_while_suspended); + assert_eq!(*fake.commands.lock(), ["ensure_listener", "thread_print"]); +} + +#[test] +fn threads_while_suspended_without_listener_do_not_attach() { + let fake = dumping_threads(99, Vec::new()); + assert_eq!( + threads_unavailable(dump_threads(&fake, 12, true)), + threads_jvm(JvmMemoryUnavailable::ListenerNotRunning) + ); + assert!(fake.commands.lock().is_empty()); +} + +#[test] +fn threads_while_suspended_on_11_are_refused() { + let mut fake = dumping_threads(12, Vec::new()); + fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() }); + assert_eq!( + threads_unavailable(dump_threads(&fake, 12, true)), + threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 }) + ); + fake.version = None; + assert_eq!( + threads_unavailable(dump_threads(&fake, 12, true)), + threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 0 }) + ); + assert!(fake.commands.lock().is_empty()); +} + +#[test] +fn threads_while_suspended_on_17_use_the_running_listener() { + let mut fake = dumping_threads(12, vec![Ok(THREADS.into())]); + fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() }); + let r = dump_threads(&fake, 12, true); + let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") }; + assert!(dump.taken_while_suspended); + assert_eq!(dump.java_version, "17.0.13"); + assert_eq!(*fake.commands.lock(), ["thread_print"]); +} + +#[test] +fn threads_of_a_tree_without_a_listener_go_to_its_first_application_jvm() { + // A shell (10) started a Gradle client (11) that started the program's JVM (12). + let mut fake = dumping_threads(99, vec![Ok(THREADS.into())]); + fake.application_jvms = vec![12]; + let r = dump_tree(&fake, &[10, 11, 12], false); + let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") }; + assert_eq!(dump.pid, 12); + assert_eq!(*fake.ensured.lock(), [12]); + + // No JVM at all: the reported pid is asked, which tells an exited program from a non-JVM. + let fake = dumping_threads(99, Vec::new()); + *fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm)].into(); + assert_eq!( + threads_unavailable(dump_tree(&fake, &[10, 11], false)), + threads_jvm(JvmMemoryUnavailable::NoJvmProcess) + ); + assert_eq!(*fake.ensured.lock(), [10]); +} + +#[cfg(unix)] +#[tokio::test] +async fn launched_thread_dump_without_a_listener_finds_the_jvm_below_the_reported_pid() { + struct Child(std::process::Child); + impl Drop for Child { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + let child = Child(std::process::Command::new("sleep").arg("30").spawn().unwrap()); + let jvm = child.0.id(); + let state = tokio::sync::Mutex::new(JvmMemoryState::default()); + let mut fake = dumping_threads(0, vec![Ok(THREADS.into())]); + fake.application_jvms = vec![jvm]; + let fake = Arc::new(fake); + let probe: Arc = fake.clone(); + let target = JvmTarget::Launched(std::process::id() as i32); + let r = thread_dump(&state, || false, |_| probe, target).await.unwrap(); + let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") }; + assert_eq!(dump.pid, jvm); + assert_eq!(*fake.ensured.lock(), [jvm]); +} + +#[tokio::test] +async fn a_session_debugs_the_jvm_it_launched_or_found() { + let attach = bare_session("attach"); + attach.session.jvm_pid.store(4242, Ordering::Release); + assert!(debugs_jvm(&attach.session, 4242)); + assert!(!debugs_jvm(&attach.session, 4243)); + let launch = bare_session("launch"); + launch.session.debuggee_pid.store(77, Ordering::Release); + assert!(debugs_jvm(&launch.session, 77)); + let python = bare_session_of("debugpy", "attach"); + python.session.jvm_pid.store(4242, Ordering::Release); + assert!(!debugs_jvm(&python.session, 4242)); + attach.session.terminated.store(true, Ordering::Release); + assert!(!debugs_jvm(&attach.session, 4242)); + // An attach whose JVM is not found yet debugs no pid. + assert!(!debugs_jvm(&bare_session("attach").session, 0)); +} + +#[tokio::test] +async fn a_session_attached_to_a_run_may_hold_its_jvm_before_it_is_located() { + let run = ide_core::RunId(7); + let mut bare = bare_session("attach"); + Arc::get_mut(&mut bare.session).unwrap().run = Some(run); + // Gradle bootRun Debug opens no attach listener, so the attach-time scan finds no pid. + assert!(attached_to_run(&bare.session, run, 555)); + assert!(!attached_to_run(&bare.session, ide_core::RunId(8), 555)); + bare.session.jvm_pid.store(4242, Ordering::Release); + assert!(attached_to_run(&bare.session, run, 4242)); + assert!(!attached_to_run(&bare.session, run, 555), "another JVM of the same run"); + bare.session.terminated.store(true, Ordering::Release); + assert!(!attached_to_run(&bare.session, run, 4242)); + + let mut python = bare_session_of("debugpy", "attach"); + Arc::get_mut(&mut python.session).unwrap().run = Some(run); + assert!(!attached_to_run(&python.session, run, 555)); + assert!(!attached_to_run(&bare_session("attach").session, run, 555), "not linked to a run"); +} + +#[tokio::test] +async fn run_dump_through_a_linked_session_whose_jvm_is_not_located() { + // Stopped at a breakpoint, no listener: refused with the resume reason, no listener start. + let bare = stopped_attach(0); + let fake = Arc::new(dumping_threads(99, Vec::new())); + let probe: Arc = fake.clone(); + let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap(); + assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)); + assert!(fake.commands.lock().is_empty()); + + // Running: the run's JVM is dumped under the session's turn. + let bare = bare_session("attach"); + let fake = Arc::new(dumping_threads(99, vec![Ok(THREADS.into())])); + let probe: Arc = fake.clone(); + let r = known_pid_dump(&bare.session, |_| probe, 555).await.unwrap(); + let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") }; + assert_eq!((dump.pid, dump.taken_while_suspended), (555, false)); + assert_eq!(*fake.ensured.lock(), [555]); +} + +/// A run's JVM held at a breakpoint by a debugger attached to it (Debug of `spring-boot:run`). +fn stopped_attach(pid: u32) -> BareSession { + let bare = bare_session("attach"); + bare.session.jvm_pid.store(i64::from(pid), Ordering::Release); + bare.session.suspended.stopped(None, true); + bare +} + +#[tokio::test] +async fn run_dump_of_a_suspended_debugged_jvm_takes_the_suspended_path() { + let bare = stopped_attach(4242); + let mut fake = dumping_threads(4242, Vec::new()); + fake.version = Some(JavaVersion { major: 11, text: "11.0.25".into() }); + let fake = Arc::new(fake); + let probe: Arc = fake.clone(); + let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap(); + assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: 11 })); + assert!(fake.commands.lock().is_empty()); + + // No listener: none is started, the JVM's Signal Dispatcher being stopped. + let fake = Arc::new(dumping_threads(99, Vec::new())); + let probe: Arc = fake.clone(); + let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap(); + assert_eq!(threads_unavailable(r), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)); + assert!(fake.commands.lock().is_empty()); + + let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]); + fake.version = Some(JavaVersion { major: 17, text: "17.0.13".into() }); + let probe: Arc = Arc::new(fake); + let r = known_pid_dump(&bare.session, |_| probe, 4242).await.unwrap(); + let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") }; + assert!(dump.taken_while_suspended); + assert_eq!(dump.pid, 4242); +} + +#[tokio::test] +async fn run_dump_of_a_debugged_jvm_waits_for_the_session_turn() { + let bare = bare_session("attach"); + bare.session.jvm_pid.store(4242, Ordering::Release); + let fake = Arc::new(dumping_threads(99, Vec::new())); + let probe: Arc = fake.clone(); + + let histogram = bare.session.jvm_memory.lock().await; + let mut queued = Box::pin(known_pid_dump(&bare.session, |_| probe, 4242)); + assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err()); + // The program hits a breakpoint while the dump waits behind the session's histogram. + bare.session.suspended.stopped(None, true); + drop(histogram); + assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)); + assert!(fake.commands.lock().is_empty()); +} + +#[test] +fn threads_of_an_exited_program() { + let mut fake = dumping_threads(99, Vec::new()); + fake.alive = false; + *fake.listener_starts.lock() = vec![Err(AttachError::NoListener)].into(); + assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited)); + assert_eq!(threads_unavailable(dump_threads(&fake, 12, true)), threads_jvm(JvmMemoryUnavailable::ProgramExited)); +} + +#[test] +fn thread_dump_errors_map_to_reasons() { + let fake = dumping_threads(12, vec![Err(AttachError::Timeout)]); + assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::TimedOut)); + + let fake = dumping_threads(99, Vec::new()); + *fake.listener_starts.lock() = vec![Err(AttachError::ListenerDidNotStart)].into(); + assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), JvmThreadsUnavailable::ListenerDidNotStart); + assert_eq!(*fake.commands.lock(), ["ensure_listener"]); + + let mut fake = dumping_threads(99, Vec::new()); + *fake.listener_starts.lock() = vec![Err(AttachError::NotAJvm), Err(AttachError::NotAJvm)].into(); + assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::NoJvmProcess)); + fake.alive = false; + assert_eq!(threads_unavailable(dump_threads(&fake, 12, false)), threads_jvm(JvmMemoryUnavailable::ProgramExited)); + + let fake = dumping_threads(12, vec![Err(AttachError::Command { code: 1, message: "no".into() })]); + let JvmThreadsUnavailable::Failed { message } = threads_unavailable(dump_threads(&fake, 12, false)) else { + panic!("not a failure") + }; + assert!(message.contains("no"), "{message}"); +} + +#[test] +fn thread_results_serialize_with_camel_case_tags() { + let r = JvmThreadsResult::Unavailable { reason: threads_jvm(JvmMemoryUnavailable::ListenerNotRunning) }; + assert_eq!( + serde_json::to_value(r).unwrap(), + serde_json::json!({"status": "unavailable", "reason": {"kind": "jvm", "reason": {"kind": "listenerNotRunning"}}}) + ); + let r = JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::ListenerDidNotStart }; + assert_eq!( + serde_json::to_value(r).unwrap(), + serde_json::json!({"status": "unavailable", "reason": {"kind": "listenerDidNotStart"}}) + ); + let dump = JvmThreadDump { + text: "t".into(), + pid: 7, + java_version: String::new(), + taken_while_suspended: true, + elapsed_ms: 3, + }; + assert_eq!( + serde_json::to_value(JvmThreadsResult::Ready { dump }).unwrap(), + serde_json::json!({ + "status": "ready", + "dump": {"text": "t", "pid": 7, "javaVersion": "", "takenWhileSuspended": true, "elapsedMs": 3} + }) + ); +} + +#[cfg(unix)] +#[tokio::test(flavor = "multi_thread")] +async fn threads_take_the_memory_lock() { + let pid = std::process::id(); + let state = tokio::sync::Mutex::new(JvmMemoryState::default()); + let mut fake = dumping_threads(pid, vec![Ok(THREADS.into())]); + *fake.histograms.lock() = vec![Ok(HISTOGRAM.into())].into(); + fake.delay = Duration::from_millis(100); + let fake = Arc::new(fake); + let probe: Arc = fake.clone(); + let running = Suspension::default(); + let (classes, threads) = tokio::join!( + snapshot(&state, &running, |_| probe.clone(), JvmTarget::Launched(pid as i32), None), + thread_dump(&state, || false, |_| probe.clone(), JvmTarget::Launched(pid as i32)) + ); + assert!(matches!(classes.unwrap(), JvmMemoryResult::Ready { .. })); + let threads = threads.unwrap(); + assert!(matches!(threads, JvmThreadsResult::Ready { .. }), "{threads:?}"); + assert_eq!(fake.max_in_flight.load(Ordering::SeqCst), 1); + assert_eq!(*fake.commands.lock(), ["histogram", "ensure_listener", "thread_print"]); +} + +#[cfg(unix)] +#[tokio::test] +async fn queued_thread_dump_reads_suspension_under_the_lock() { + let pid = std::process::id(); + let state = tokio::sync::Mutex::new(JvmMemoryState::default()); + let suspended = Suspension::default(); + let fake = Arc::new(dumping_threads(0, Vec::new())); + let probe: Arc = fake.clone(); + + let running = state.lock().await; + let mut queued = Box::pin(thread_dump(&state, || suspended.get(), |_| probe, JvmTarget::Launched(pid as i32))); + assert!(tokio::time::timeout(Duration::from_millis(50), &mut queued).await.is_err()); + // The program hits a breakpoint while the dump waits behind a class-table request. + suspended.stopped(None, true); + drop(running); + assert_eq!(threads_unavailable(queued.await.unwrap()), threads_jvm(JvmMemoryUnavailable::ListenerNotRunning)); + assert!(fake.commands.lock().is_empty()); +} + +#[tokio::test] +async fn attached_thread_dump_keeps_the_scanned_jvm() { + let state = tokio::sync::Mutex::new(JvmMemoryState::default()); + let jvm_pid = AtomicI64::new(0); + let mut fake = dumping_threads(4242, vec![Ok(THREADS.into())]); + fake.jdwp = Some((5005, 4242)); + let probe: Arc = Arc::new(fake); + let target = JvmTarget::Attached { pid: &jvm_pid, jdwp_port: Some(5005) }; + let r = thread_dump(&state, || false, |_| probe, target).await.unwrap(); + let JvmThreadsResult::Ready { dump } = r else { panic!("{r:?}") }; + assert_eq!(dump.pid, 4242); + assert_eq!(jvm_pid.load(Ordering::SeqCst), 4242); +} + #[tokio::test] async fn capability_matches_memory() { for adapter in JVM_MEMORY_ADAPTERS.iter().copied().chain(["debugpy"]) { diff --git a/crates/ide-dap/src/jvm_memory/threads.rs b/crates/ide-dap/src/jvm_memory/threads.rs new file mode 100644 index 0000000000..7a94f36e46 --- /dev/null +++ b/crates/ide-dap/src/jvm_memory/threads.rs @@ -0,0 +1,181 @@ +//! A thread dump (`Thread.print -l`) of a debugged or running JVM. + +use super::heap::capture_suspended; +use super::snapshot::{AttachProbe, JdkProbe, attach_failure, gone, pick_jvm_pid}; +use super::{ + JvmMemoryState, JvmMemoryUnavailable, JvmTarget, histogram_pid, keep_found, lookup, resolve_jvm, + safe_while_suspended, session_target, until_located, +}; +use crate::session::Session; +use ide_core::{IdeError, IdeResult}; +use ide_jvm_attach::AttachError; +use serde::{Deserialize, Serialize}; +use specta::Type; +use std::sync::Arc; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct JvmThreadDump { + pub text: String, + pub pid: u32, + /// Empty when unknown. + pub java_version: String, + pub taken_while_suspended: bool, + /// Wall time of the `Thread.print` request. + pub elapsed_ms: u32, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(tag = "kind", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum JvmThreadsUnavailable { + /// The reason a class table could not be read applies to the dump too. + Jvm { + reason: JvmMemoryUnavailable, + }, + /// The JVM ignored the request to open its attach listener (`-XX:+DisableAttachMechanism`). + ListenerDidNotStart, + /// A run on a remote host, whose JVM this machine cannot attach to. + RemoteRun, + Failed { + message: String, + }, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(tag = "status", rename_all = "camelCase", rename_all_fields = "camelCase")] +pub enum JvmThreadsResult { + Ready { dump: JvmThreadDump }, + Unavailable { reason: JvmThreadsUnavailable }, +} + +/// A thread dump of `pid`, a JVM no debugger holds. Blocking for up to the listener start and +/// dump timeouts, so callers run it in `spawn_blocking`. +pub fn run_jvm_thread_dump(pid: u32) -> JvmThreadsResult { + dump_threads(&JdkProbe { suspended: false }, pid, false) +} + +pub(crate) async fn session_thread_dump(session: Arc) -> IdeResult { + until_located(&session).await; + let launched = histogram_pid(&session); + // Detached, so a caller that gives up cannot release the lock while the JVM is still + // answering and let a class-table request run next to it. + tokio::spawn(async move { + let target = session_target(&session, launched); + let probe = |suspended| -> Arc { Arc::new(JdkProbe { suspended }) }; + thread_dump(&session.jvm_memory, || capture_suspended(&session), probe, target).await + }) + .await + .map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))? +} + +/// A thread dump of `pid`, a run's JVM that `session` debugs, taken as the session's own dump +/// is: a JVM the debugger holds suspended is never asked to open a listener. +pub(crate) async fn debugged_run_thread_dump(session: Arc, pid: u32) -> IdeResult { + // Detached for the same reason as `session_thread_dump`. + tokio::spawn(async move { + let probe = |suspended| -> Arc { Arc::new(JdkProbe { suspended }) }; + known_pid_dump(&session, probe, pid).await + }) + .await + .map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))? +} + +pub(super) async fn known_pid_dump( + session: &Session, + probe: impl FnOnce(bool) -> Arc, + pid: u32, +) -> IdeResult { + let target = + i32::try_from(pid).map_or(JvmTarget::Unavailable(JvmMemoryUnavailable::NoJvmProcess), JvmTarget::Known); + thread_dump(&session.jvm_memory, || capture_suspended(session), probe, target).await +} + +/// Takes the class-table lock, so a dump never runs beside a histogram or heap dump of the same +/// session; `suspended` and then `probe` are read once it is held. +pub(super) async fn thread_dump( + state: &tokio::sync::Mutex, + suspended: impl FnOnce() -> bool, + probe: impl FnOnce(bool) -> Arc, + target: JvmTarget<'_>, +) -> IdeResult { + let _turn = state.lock().await; + let suspended = suspended(); + let lookup = match lookup(target) { + Ok(lookup) => lookup, + Err(reason) => return Ok(jvm(reason)), + }; + let probe = probe(suspended); + let (found, outcome) = tokio::task::spawn_blocking(move || match resolve_jvm(lookup, &*probe, suspended) { + Ok((tree, found)) => (found, dump_tree(&*probe, &tree, suspended)), + Err(reason) => (None, jvm(reason)), + }) + .await + .map_err(|e| IdeError::internal(format!("JVM thread dump failed: {e}")))?; + keep_found(target, found); + Ok(outcome) +} + +/// `tree` starts with the session's reported pid, followed by its descendants: the JVM is the +/// first with a listener, else the first application JVM (the reported pid may be a shell or a +/// Gradle client), else the reported pid. +pub(super) fn dump_tree(probe: &dyn AttachProbe, tree: &[i32], suspended: bool) -> JvmThreadsResult { + let jvm_pid = pick_jvm_pid(tree, |p| probe.has_listener(p)) + .or_else(|| pick_jvm_pid(tree, |p| probe.is_application_jvm(p))) + .or_else(|| tree.first().and_then(|&p| u32::try_from(p).ok()).filter(|&p| p > 0)); + match jvm_pid { + Some(pid) => dump_threads(probe, pid, suspended), + None => jvm(JvmMemoryUnavailable::NoJvmProcess), + } +} + +/// Blocking. A JVM a debugger holds suspended cannot open a listener (its Signal Dispatcher is +/// stopped), and one below 17 hangs even with one, so it is asked only when both are ruled out. +pub(crate) fn dump_threads(probe: &dyn AttachProbe, pid: u32, suspended: bool) -> JvmThreadsResult { + if suspended { + if !probe.has_listener(pid) { + return jvm(gone(probe, pid)); + } + } else if let Err(e) = probe.ensure_listener(pid) { + return failure(probe, pid, e); + } + let version = probe.version(pid); + if suspended && !safe_while_suspended(version.as_ref()) { + return jvm(JvmMemoryUnavailable::UnsafeWhileSuspended { java_major: version.map_or(0, |v| v.major) }); + } + + let started = std::time::Instant::now(); + let text = match probe.thread_print(pid) { + Ok(text) => text, + Err(e) => return failure(probe, pid, e), + }; + let elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX); + JvmThreadsResult::Ready { + dump: JvmThreadDump { + text, + pid, + java_version: version.map(|v| v.text).unwrap_or_default(), + taken_while_suspended: suspended, + elapsed_ms, + }, + } +} + +fn failure(probe: &dyn AttachProbe, pid: u32, error: AttachError) -> JvmThreadsResult { + let reason = match error { + AttachError::ListenerDidNotStart => JvmThreadsUnavailable::ListenerDidNotStart, + // A program that exited leaves no perf-data file, so it fails the HotSpot check too. + AttachError::NotAJvm if probe.alive(pid) => { + JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::NoJvmProcess } + } + AttachError::NotAJvm => JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ProgramExited }, + e => match attach_failure(probe, pid, e, "thread dump") { + Ok(reason) => JvmThreadsUnavailable::Jvm { reason }, + Err(e) => JvmThreadsUnavailable::Failed { message: e.message }, + }, + }; + JvmThreadsResult::Unavailable { reason } +} + +fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult { + JvmThreadsResult::Unavailable { reason: JvmThreadsUnavailable::Jvm { reason } } +} diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 13ccd5e712..4f84a8dee7 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -27,7 +27,7 @@ use adapter::{AdapterLauncher, AdapterSpec, ProcessLauncher}; use connection::{Connection, DapError}; pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport}; use futures::future::join_all; -use ide_core::{DebugSessionId, IdeError, IdeResult, SharedSink}; +use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink}; use ide_language::LanguageRegistry; pub use js_cdp::JsResponseRule; pub use js_debug::JsResponseBody; @@ -460,6 +460,15 @@ fn child_name(configuration: &Value, parent: &str) -> String { } } +/// `extra_json` key naming the run whose JVM an attach debugs; IDE-side, never sent to the +/// adapter. +pub const RUN_LINK: &str = "__openideaRun"; + +fn take_run_link(arguments: &mut Value) -> Option { + let run = arguments.as_object_mut()?.remove(RUN_LINK)?; + serde_json::from_value(run).ok() +} + /// Builds the `launch`/`attach` arguments: our fields first, then `extra_json` merged on top. pub fn launch_arguments(config: &LaunchConfig) -> IdeResult { // VS Code puts `type`, `request` and `name` in the arguments; js-debug picks launch @@ -1047,7 +1056,7 @@ impl DebugManager { adapter_name: String, parent: Option, request: String, - arguments: Value, + mut arguments: Value, spec: AdapterSpec, reuse_port: Option, exception_classes: Option>, @@ -1067,6 +1076,7 @@ impl DebugManager { .flatten(); let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child); session.exception_classes = exception_classes; + session.run = take_run_link(&mut arguments); let session = Arc::new(session); if let Some(launch_type) = arguments.get("type").and_then(Value::as_str) { let _ = session.launch_type.set(launch_type.to_owned()); @@ -1967,6 +1977,34 @@ impl DebugManager { jvm_memory::session_heap_dump(session, dir, cancel).await } + /// `Thread.print -l` of the session's JVM, taking the session's class-table turn. A JVM the + /// debugger holds suspended is asked only when it is 17 or later and its listener already + /// runs: otherwise the request would hang until the program resumes. + pub async fn jvm_thread_dump(&self, s: DebugSessionId) -> IdeResult { + let session = self.session(s)?; + jvm_memory::session_thread_dump(session).await + } + + /// `Thread.print -l` of `pid`, the JVM of `run`, when a live session debugs it (a build + /// tool's run started for Debug, Attach to Process): taken as [`Self::jvm_thread_dump`] takes + /// it, under that session's turn and suspension. `None` when no session debugs `pid`. + pub async fn debugged_jvm_thread_dump(&self, run: RunId, pid: u32) -> Option> { + let session = self.jvm_session_of(run, pid)?; + Some(jvm_memory::debugged_run_thread_dump(session, pid).await) + } + + /// A session attached to `run` first: one whose JVM is not located yet (its attach-time scan + /// found no listener) still holds `pid`. + fn jvm_session_of(&self, run: RunId, pid: u32) -> Option> { + let sessions = self.live_sessions(); + let linked = || sessions.iter().filter(|s| jvm_memory::attached_to_run(s, run, pid)); + linked() + .find(|s| jvm_memory::debugs_jvm(s, pid)) + .or_else(|| linked().next()) + .or_else(|| sessions.iter().find(|s| jvm_memory::debugs_jvm(s, pid))) + .cloned() + } + /// Gives the session the backend for [`Self::jvm_memory_instances`] and the debugger's class /// counts; the UI is told to reload the session's capabilities. pub fn set_jvm_inspector( diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs index d7aa4f656c..bcac6752e8 100644 --- a/crates/ide-dap/src/session.rs +++ b/crates/ide-dap/src/session.rs @@ -8,7 +8,7 @@ use crate::{Breakpoint, BreakpointState, DataBreakpoint, DebugManager, FunctionB use ide_core::event::DebugEvent; #[cfg(unix)] use ide_core::process::process_tree; -use ide_core::{DebugSessionId, IdeEvent, TaskId}; +use ide_core::{DebugSessionId, IdeEvent, RunId, TaskId}; use parking_lot::Mutex; use serde_json::{Value, json}; use std::collections::{BTreeSet, HashMap}; @@ -117,6 +117,9 @@ pub(crate) struct Session { pub jvm_located: watch::Sender, pub kotlin_mirror: Mutex>, pub jvm_memory: tokio::sync::Mutex, + /// The run whose JVM this session attached to (Debug of a build tool's run, Attach to + /// Process on a run): that run's thread dumps go through this session. + pub run: Option, pub stream_tracer: parking_lot::Mutex>>, /// Given at start: the class breakpoints must be armed before `configurationDone`. pub(crate) exception_classes: Option>, @@ -333,6 +336,7 @@ impl Session { jvm_located: watch::channel(false).0, kotlin_mirror: Mutex::new(None), jvm_memory: tokio::sync::Mutex::default(), + run: None, stream_tracer: parking_lot::Mutex::new(None), exception_classes: None, exception_turn: tokio::sync::Mutex::default(), diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index c9d1ba57e9..4628a54428 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -3074,6 +3074,55 @@ async fn local_attach_finds_its_jvm_before_the_debugger_connects() { assert_eq!(session.jvm_pid.load(Ordering::Acquire), 4242); } +/// Gradle bootRun Debug: the JVM has no attach listener, so the session never learns its pid. The +/// run's dump still goes through the session and, the program being stopped, signals nothing. +#[cfg(unix)] +#[tokio::test] +async fn a_run_dump_goes_through_the_session_attached_to_the_run() { + let h = harness(Script::default()); + let project = tempfile::tempdir().unwrap(); + let mut cfg = remote_attach("java-debug", project.path()); + let mut extra: Value = serde_json::from_str(cfg.extra_json.as_deref().unwrap()).unwrap(); + extra[RUN_LINK] = json!(7); + cfg.extra_json = Some(extra.to_string()); + let id = h.start(cfg).await.unwrap(); + h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await; + assert!(h.request("attach")["arguments"].get(RUN_LINK).is_none(), "IDE-side only"); + let session = h.manager.session(id).unwrap(); + assert_eq!((session.run, session.jvm_pid.load(Ordering::Acquire)), (Some(RunId(7)), 0)); + + // `sleep` stands in for the JVM: a SIGQUIT would end it. + let mut jvm = std::process::Command::new("sleep").arg("30").spawn().unwrap(); + let pid = jvm.id(); + assert_eq!(h.manager.jvm_session_of(RunId(7), pid).map(|s| s.id), Some(id)); + assert!(h.manager.jvm_session_of(RunId(8), pid).is_none()); + let dump = h.manager.debugged_jvm_thread_dump(RunId(7), pid).await.unwrap().unwrap(); + let alive = jvm.try_wait().unwrap().is_none(); + let _ = jvm.kill(); + let _ = jvm.wait(); + assert_eq!( + dump, + JvmThreadsResult::Unavailable { + reason: JvmThreadsUnavailable::Jvm { reason: JvmMemoryUnavailable::ListenerNotRunning } + } + ); + assert!(alive, "the stopped JVM was signalled"); +} + +/// A run's Dump Threads reaches the session attached to the run's JVM, not the plain run path. +#[cfg(unix)] +#[tokio::test] +async fn a_run_jvm_is_found_by_the_session_attached_to_it() { + let h = harness(Script::default()); + h.manager.set_jvm_finder(Arc::new(|port, _| (port == 5005).then_some(4242))); + let mut cfg = java_config("attach"); + cfg.extra_json = Some(json!({"hostName": "127.0.0.1", "port": 5005}).to_string()); + let id = h.start(cfg).await.unwrap(); + assert_eq!(h.manager.jvm_session_of(RunId(1), 4242).map(|s| s.id), Some(id)); + assert!(h.manager.jvm_session_of(RunId(1), 4243).is_none()); + assert!(h.manager.debugged_jvm_thread_dump(RunId(1), 4243).await.is_none()); +} + #[cfg(unix)] #[tokio::test] async fn local_attach_remembers_its_jdwp_port() { diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index 9e8530d78f..103e53657d 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -671,6 +671,13 @@ pub async fn debug_jvm_memory_classes( host.debugger.jvm_memory_classes(session).await } +/// A `Thread.print -l` of the debuggee JVM, or why it cannot be taken. +#[command(trust = trusted)] +pub async fn debug_jvm_thread_dump(host: &Host, window: &str, session: DebugSessionId) -> IdeResult { + host.require_trust(window)?; + host.debugger.jvm_thread_dump(session).await +} + /// Up to `limit` live instances of the class in the stopped JVM. #[command(trust = trusted)] pub async fn debug_jvm_memory_instances( @@ -867,6 +874,7 @@ ide_command::domain!( debug_jvm_memory_fields, debug_jvm_memory_instances, debug_jvm_memory_referrers, + debug_jvm_thread_dump, debug_listen_for_jvm, debug_pause, debug_redefine_classes, diff --git a/crates/ide-host/src/ops/mod.rs b/crates/ide-host/src/ops/mod.rs index 75cb53dcf2..912332a5e7 100644 --- a/crates/ide-host/src/ops/mod.rs +++ b/crates/ide-host/src/ops/mod.rs @@ -39,6 +39,7 @@ pub mod ssh; pub mod stream_trace; pub mod syntax; pub mod term; +pub mod thread_dump; pub mod tools; pub mod vcs; pub mod web; @@ -118,6 +119,7 @@ ide_command::domains!( stream_trace: crate::ops::stream_trace, syntax: crate::ops::syntax, term: crate::ops::term, + thread_dump: crate::ops::thread_dump, tools: crate::ops::tools, vcs: crate::ops::vcs, vcs_commands: crate::ops::vcs::commands, diff --git a/crates/ide-host/src/ops/thread_dump.rs b/crates/ide-host/src/ops/thread_dump.rs new file mode 100644 index 0000000000..82cbbc9fd7 --- /dev/null +++ b/crates/ide-host/src/ops/thread_dump.rs @@ -0,0 +1,108 @@ +use crate::Host; +use ide_command::command; +use ide_core::{IdeResult, RunId}; +use ide_dap::{JvmMemoryUnavailable, JvmThreadsResult, JvmThreadsUnavailable}; +use ide_jvm_attach::{ProcEntry, is_hotspot, process_table, select_run_jvm}; +use std::sync::Arc; + +/// A `Thread.print -l` of the JVM a run started: the deepest HotSpot JVM of the run's process +/// tree, else the one carrying `token` (the run's marker property). +#[command(trust = trusted)] +pub async fn run_jvm_thread_dump( + host: &Arc, + window: &str, + id: RunId, + token: Option, +) -> IdeResult { + host.require_trust(window)?; + let remote = host.remote.runs.contains(id); + let root = if remote { None } else { host.processes.pid(id) }; + let selected = host.blocking(move || Ok(run_jvm(remote, root, token.as_deref(), process_table, is_hotspot))); + let pid = match selected.await? { + Ok(pid) => pid, + Err(refused) => return Ok(refused), + }; + // A debugger attached to this run or JVM (Debug of a build tool's run, Attach to Process) + // may hold it suspended, which only its session knows. + if let Some(dump) = host.debugger.debugged_jvm_thread_dump(id, pid).await { + return dump; + } + // The attach handshake blocks for seconds. + host.blocking(move || Ok(ide_dap::run_jvm_thread_dump(pid))).await +} + +fn unavailable(reason: JvmThreadsUnavailable) -> JvmThreadsResult { + JvmThreadsResult::Unavailable { reason } +} + +fn jvm(reason: JvmMemoryUnavailable) -> JvmThreadsResult { + unavailable(JvmThreadsUnavailable::Jvm { reason }) +} + +/// The run's JVM, or why none can be dumped. `root` is the run's process while it runs; the +/// process table is read only once the cheaper reasons to refuse are ruled out. +fn run_jvm( + remote: bool, + root: Option, + token: Option<&str>, + table: impl FnOnce() -> Vec, + is_hotspot: impl Fn(u32) -> bool, +) -> Result { + if remote { + return Err(unavailable(JvmThreadsUnavailable::RemoteRun)); + } + let Some(root) = root else { return Err(jvm(JvmMemoryUnavailable::ProgramExited)) }; + if !cfg!(unix) { + return Err(jvm(JvmMemoryUnavailable::UnsupportedPlatform)); + } + select_run_jvm(&table(), root, token, is_hotspot).ok_or_else(|| jvm(JvmMemoryUnavailable::NoJvmProcess)) +} + +ide_command::domain!(thread_dump: run_jvm_thread_dump); + +#[cfg(test)] +mod tests { + use super::*; + + fn never_called() -> T { + panic!("not reached") + } + + fn proc(pid: u32, ppid: u32, command: &str) -> ProcEntry { + ProcEntry { pid, ppid, command: command.into() } + } + + #[test] + fn remote_run_is_refused() { + let result = run_jvm(true, Some(10), None, never_called, |_| never_called()); + assert_eq!(result, Err(unavailable(JvmThreadsUnavailable::RemoteRun))); + } + + #[test] + fn exited_run_reports_program_exited() { + let result = run_jvm(false, None, None, never_called, |_| never_called()); + assert_eq!(result, Err(jvm(JvmMemoryUnavailable::ProgramExited))); + } + + #[cfg(unix)] + #[test] + fn no_jvm_in_tree() { + let table = || vec![proc(10, 1, "sh -c run"), proc(11, 10, "sleep 100")]; + let result = run_jvm(false, Some(10), None, table, |_| false); + assert_eq!(result, Err(jvm(JvmMemoryUnavailable::NoJvmProcess))); + } + + #[cfg(unix)] + #[test] + fn finds_the_jvm_below_the_run() { + let table = || vec![proc(10, 1, "sh -c run"), proc(11, 10, "java -jar app.jar")]; + assert_eq!(run_jvm(false, Some(10), None, table, |pid| pid == 11), Ok(11)); + } + + #[cfg(not(unix))] + #[test] + fn unsupported_without_reading_the_process_table() { + let result = run_jvm(false, Some(10), None, never_called, |_| never_called()); + assert_eq!(result, Err(jvm(JvmMemoryUnavailable::UnsupportedPlatform))); + } +} diff --git a/crates/ide-host/tests/debug_jvm_memory_ipc.rs b/crates/ide-host/tests/debug_jvm_memory_ipc.rs index e803f02c2b..b137e96b85 100644 --- a/crates/ide-host/tests/debug_jvm_memory_ipc.rs +++ b/crates/ide-host/tests/debug_jvm_memory_ipc.rs @@ -26,13 +26,14 @@ async fn invoke(peer: &Peer, window: &str, cmd: &str, args: Value) -> Result [(&'static str, Value); 4] { +fn calls() -> [(&'static str, Value); 5] { let object = json!({"generation": 1, "id": 7}); [ ("debug_jvm_memory_classes", json!({"session": NO_SESSION})), ("debug_jvm_memory_instances", json!({"session": NO_SESSION, "className": "java.lang.String", "limit": 10})), ("debug_jvm_memory_fields", json!({"session": NO_SESSION, "object": object})), ("debug_jvm_memory_referrers", json!({"session": NO_SESSION, "object": object, "limit": 10})), + ("debug_jvm_thread_dump", json!({"session": NO_SESSION})), ] } @@ -80,3 +81,14 @@ async fn class_table_is_refused_in_restricted_mode() { let error = ide_host::ops::debug::debug_jvm_memory_classes(&host, "main", session).await.unwrap_err(); assert!(error.message.contains("Restricted Mode"), "{error:?}"); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn thread_dumps_are_refused_in_restricted_mode() { + let (host, _tmp) = host(false); + let session = ide_core::DebugSessionId(NO_SESSION as u32); + let error = ide_host::ops::debug::debug_jvm_thread_dump(&host, "main", session).await.unwrap_err(); + assert!(error.message.contains("Restricted Mode"), "{error:?}"); + let error = + ide_host::ops::thread_dump::run_jvm_thread_dump(&host, "main", ide_core::RunId(1), None).await.unwrap_err(); + assert!(error.message.contains("Restricted Mode"), "{error:?}"); +} diff --git a/crates/ide-jvm-attach/src/discover.rs b/crates/ide-jvm-attach/src/discover.rs index abe3dae42d..e273e1de5e 100644 --- a/crates/ide-jvm-attach/src/discover.rs +++ b/crates/ide-jvm-attach/src/discover.rs @@ -112,6 +112,7 @@ mod tests { #[test] fn scan_matches_port_not_first_listener() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let _a = fake_jvm(dir.path(), ".java_pid111", Some(5005)); let _b = fake_jvm(dir.path(), ".java_pid222", Some(6006)); @@ -120,6 +121,7 @@ mod tests { #[test] fn scan_returns_none_when_no_port_matches() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let _a = fake_jvm(dir.path(), ".java_pid111", Some(5005)); assert_eq!(find_in(dir.path(), 6006, SECOND, 2 * SECOND, ALL), None); @@ -127,6 +129,7 @@ mod tests { #[test] fn scan_skips_silent_listener_within_budget() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let _silent = fake_jvm(dir.path(), ".java_pid111", None); let _b = fake_jvm(dir.path(), ".java_pid222", Some(6006)); @@ -137,6 +140,7 @@ mod tests { #[test] fn scan_gives_up_at_the_budget_even_if_a_query_could_run_longer() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let _silent = fake_jvm(dir.path(), ".java_pid111", None); let started = Instant::now(); @@ -146,6 +150,7 @@ mod tests { #[test] fn scan_ignores_non_matching_names() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let _a = fake_jvm(dir.path(), ".java_pidabc", Some(6006)); let _b = fake_jvm(dir.path(), ".java_pid", Some(6006)); @@ -156,6 +161,7 @@ mod tests { #[test] fn scan_applies_the_socket_trust_checks() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let _a = fake_jvm(dir.path(), ".java_pid111", Some(6006)); fs::set_permissions(dir.path().join(".java_pid111"), fs::Permissions::from_mode(0o666)).unwrap(); @@ -170,6 +176,7 @@ mod tests { #[test] fn scan_never_asks_a_jvm_the_caller_rejects() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let _a = fake_jvm(dir.path(), ".java_pid111", Some(6006)); let offered = std::sync::Mutex::new(Vec::new()); diff --git a/crates/ide-jvm-attach/src/jvm.rs b/crates/ide-jvm-attach/src/jvm.rs index fb7f27cbb0..bfd9d98503 100644 --- a/crates/ide-jvm-attach/src/jvm.rs +++ b/crates/ide-jvm-attach/src/jvm.rs @@ -35,16 +35,7 @@ fn version_from(text: &str) -> Option { pub fn java_version_of(pid: u32) -> Option { #[cfg(any(target_os = "linux", target_os = "macos"))] { - let exe = std::fs::canonicalize(exe_path(pid)?).ok()?; - // `/bin/java`, or `/jre/bin/java` on JDK 8. - let home = exe.parent()?.parent()?; - // Only climb out of `jre/`, so a JDK without its own `release` cannot pick up an - // unrelated file in a shared parent such as `/usr/lib/jvm`. - let outer = if home.file_name().is_some_and(|n| n == "jre") { home.parent() } else { None }; - [Some(home), outer].into_iter().flatten().find_map(|dir| { - let contents = std::fs::read_to_string(dir.join("release")).ok()?; - parse_release(&contents) - }) + version_of_exe(&exe_path(pid)?) } #[cfg(not(any(target_os = "linux", target_os = "macos")))] { @@ -53,13 +44,41 @@ pub fn java_version_of(pid: u32) -> Option { } } +#[cfg(any(target_os = "linux", target_os = "macos", test))] +fn version_of_exe(exe: &std::path::Path) -> Option { + releases_of(exe).iter().find_map(|release| parse_release(release)) +} + +/// The `release` files of the JDK whose `java` executable is `exe`, nearest first. +#[cfg(any(target_os = "linux", target_os = "macos", test))] +fn releases_of(exe: &std::path::Path) -> Vec { + let Some(exe) = std::fs::canonicalize(exe).ok() else { return Vec::new() }; + // `/bin/java`, or `/jre/bin/java` on JDK 8. + let Some(home) = exe.parent().and_then(std::path::Path::parent) else { return Vec::new() }; + // Only climb out of `jre/`, so a JDK without its own `release` cannot pick up an + // unrelated file in a shared parent such as `/usr/lib/jvm`. + let outer = if home.file_name().is_some_and(|n| n == "jre") { home.parent() } else { None }; + [Some(home), outer] + .into_iter() + .flatten() + .filter_map(|dir| std::fs::read_to_string(dir.join("release")).ok()) + .collect() +} + +/// OpenJ9 (IBM Semeru) answers SIGQUIT by writing a `javacore` file into its working directory +/// instead of opening a listener. Its `release` files name it under varying keys. +#[cfg(any(target_os = "linux", target_os = "macos", test))] +pub(crate) fn is_openj9(exe: &std::path::Path) -> bool { + releases_of(exe).iter().any(|release| release.to_ascii_lowercase().contains("openj9")) +} + #[cfg(target_os = "linux")] -fn exe_path(pid: u32) -> Option { +pub(crate) fn exe_path(pid: u32) -> Option { std::fs::read_link(format!("/proc/{pid}/exe")).ok() } #[cfg(target_os = "macos")] -fn exe_path(pid: u32) -> Option { +pub(crate) fn exe_path(pid: u32) -> Option { use std::{ffi::c_void, os::unix::ffi::OsStringExt}; let mut buf = vec![0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize]; @@ -85,6 +104,7 @@ pub fn wants_listener_flag(jvm_args: &str) -> bool { #[cfg(test)] mod tests { use super::*; + use std::path::{Path, PathBuf}; #[test] fn release_versions() { @@ -100,6 +120,44 @@ mod tests { assert_eq!(parse_vm_version("OpenJDK 64-Bit Server VM version 25.512-b09\nJDK 8.0_512\n").unwrap().major, 8); } + fn fake_jdk(dir: &Path, java: &str, release: Option<&str>) -> PathBuf { + let exe = dir.join(java); + std::fs::create_dir_all(exe.parent().unwrap()).unwrap(); + std::fs::write(&exe, "").unwrap(); + if let Some(release) = release { + std::fs::write(dir.join("release"), release).unwrap(); + } + exe + } + + #[test] + fn version_of_a_jre_falls_back_to_the_jdk_release() { + let root = tempfile::tempdir().unwrap(); + let jdk = root.path().join("jdk8"); + let exe = fake_jdk(&jdk, "jre/bin/java", Some("JAVA_VERSION=\"1.8.0_512\"\n")); + assert_eq!(version_of_exe(&exe).map(|v| v.major), Some(8)); + // A `jre/release` without the version, as some JDK 8 builds ship. + std::fs::write(jdk.join("jre/release"), "IMPLEMENTOR=\"Oracle Corporation\"\n").unwrap(); + assert_eq!(version_of_exe(&exe).map(|v| v.major), Some(8)); + // Outside `jre/` nothing above the JDK is read. + let lone = fake_jdk(&root.path().join("jdk/x"), "bin/java", Some("IMPLEMENTOR=x\n")); + std::fs::write(root.path().join("jdk/release"), "JAVA_VERSION=\"17\"\n").unwrap(); + assert_eq!(version_of_exe(&lone), None); + } + + #[test] + fn openj9_is_told_by_its_release_file() { + let root = tempfile::tempdir().unwrap(); + let semeru = "IMPLEMENTOR=\"IBM Corporation\"\nJAVA_VERSION=\"21.0.5\"\nJVM_VARIANT=\"Openj9\"\n"; + let temurin = "IMPLEMENTOR=\"Eclipse Adoptium\"\nJAVA_VERSION=\"21.0.5\"\n"; + let only_build = "JAVA_VERSION=\"17\"\nBUILD_INFO=\"OpenJDK 17 with Eclipse OpenJ9 VM\"\n"; + assert!(is_openj9(&fake_jdk(&root.path().join("semeru"), "bin/java", Some(semeru)))); + assert!(is_openj9(&fake_jdk(&root.path().join("other-key"), "bin/java", Some(only_build)))); + assert!(is_openj9(&fake_jdk(&root.path().join("jdk8"), "jre/bin/java", Some(semeru)))); + assert!(!is_openj9(&fake_jdk(&root.path().join("temurin"), "bin/java", Some(temurin)))); + assert!(!is_openj9(&fake_jdk(&root.path().join("bare"), "bin/java", None))); + } + #[test] fn suspended_gate() { assert!(!histogram_safe_while_suspended(11)); diff --git a/crates/ide-jvm-attach/src/lib.rs b/crates/ide-jvm-attach/src/lib.rs index 45cb8a4222..9cc78a1239 100644 --- a/crates/ide-jvm-attach/src/lib.rs +++ b/crates/ide-jvm-attach/src/lib.rs @@ -2,8 +2,12 @@ mod discover; mod heap_dump; mod histogram; mod jvm; +mod listener; mod properties; mod socket; +#[cfg(all(test, unix))] +mod test_serial; +mod threads; pub use discover::find_jvm_by_jdwp_port; pub use heap_dump::{HeapDumpReply, dump_timeout, heap_dump, heap_dump_command, parse_heap_dump_reply, vm_flags}; @@ -12,5 +16,9 @@ pub use jvm::{ JavaVersion, START_LISTENER_FLAG, histogram_safe_while_suspended, java_version_of, parse_release, parse_vm_version, wants_listener_flag, }; +pub use listener::{LISTENER_START_TIMEOUT, ensure_listener, is_hotspot}; pub use properties::{jdwp_port, parse_properties}; pub use socket::{AttachError, MAX_OUTPUT, agent_properties, has_listener, jcmd, temp_dir}; +pub use threads::{ + ProcEntry, RUN_TOKEN_PROPERTY, THREAD_DUMP_TIMEOUT, is_application_jvm, process_table, select_run_jvm, thread_print, +}; diff --git a/crates/ide-jvm-attach/src/listener.rs b/crates/ide-jvm-attach/src/listener.rs new file mode 100644 index 0000000000..e4acbe8718 --- /dev/null +++ b/crates/ide-jvm-attach/src/listener.rs @@ -0,0 +1,395 @@ +use std::time::Duration; + +use crate::socket::AttachError; +#[cfg(unix)] +use crate::socket::{check_socket, has_listener, has_listener_at, socket_path, temp_dir}; +#[cfg(any(target_os = "linux", target_os = "macos", test))] +use std::time::UNIX_EPOCH; +#[cfg(unix)] +use std::{ + fs::{Metadata, OpenOptions}, + io, + os::unix::fs::{MetadataExt, OpenOptionsExt}, + path::{Path, PathBuf}, + time::{Instant, SystemTime}, +}; + +/// Default budget for `ensure_listener`. +pub const LISTENER_START_TIMEOUT: Duration = Duration::from_secs(5); + +#[cfg(unix)] +const POLL_INTERVAL: Duration = Duration::from_millis(50); + +/// True when `pid` is confirmed to be a HotSpot JVM: it has an attach listener, a perf-data +/// file of the current user written since it started, or runs an executable named `java` +/// (`-XX:-UsePerfData` JVMs). +pub fn is_hotspot(pid: u32) -> bool { + #[cfg(unix)] + { + signal_target(pid).is_some() && (has_listener(pid) || has_perf_data(pid) || runs_java(pid)) + } + #[cfg(not(unix))] + { + let _ = pid; + false + } +} + +/// Opens `pid`'s attach listener if it has none, as the JDK's attach API does: a +/// `.attach_pid` trigger file, then SIGQUIT. Refuses anything `is_hotspot` does not +/// confirm (`NotAJvm`), because SIGQUIT's default action terminates any other process, and a +/// socket that fails the ownership check (`ForeignListener`). +/// +/// Blocks for up to `timeout`. A JVM that ignores attach (`-XX:+DisableAttachMechanism`) still +/// handles the SIGQUIT: it prints a thread dump to its own stdout. +pub fn ensure_listener(pid: u32, timeout: Duration) -> Result<(), AttachError> { + #[cfg(unix)] + { + ensure_listener_at(&socket_path(pid), pid, timeout) + } + #[cfg(not(unix))] + { + let _ = (pid, timeout); + Err(AttachError::Unsupported) + } +} + +#[cfg(unix)] +fn ensure_listener_at(socket: &Path, pid: u32, timeout: Duration) -> Result<(), AttachError> { + // `has_listener` reads a socket that fails the trust check as absent; signalling past it + // would leave its owner answering in the JVM's place. + match check_socket(socket) { + Ok(()) => return Ok(()), + Err(AttachError::NoListener) => {} + Err(e) => return Err(e), + } + let Some(target) = signal_target(pid).filter(|_| is_hotspot(pid)) else { + return Err(AttachError::NotAJvm); + }; + let deadline = Instant::now() + timeout; + let _trigger = Trigger::create(pid)?; + signal(target, libc::SIGQUIT)?; + loop { + if has_listener_at(socket) { + return Ok(()); + } + signal(target, 0)?; + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return Err(AttachError::ListenerDidNotStart); + } + std::thread::sleep(remaining.min(POLL_INTERVAL)); + } +} + +/// `kill` treats 0 and negative pids as process groups, which would signal the IDE itself. +#[cfg(unix)] +fn signal_target(pid: u32) -> Option { + libc::pid_t::try_from(pid).ok().filter(|p| *p > 0) +} + +#[cfg(unix)] +fn signal(pid: libc::pid_t, signal: libc::c_int) -> Result<(), AttachError> { + // SAFETY: kill has no memory preconditions; `pid` is positive, so only that process is targeted. + if unsafe { libc::kill(pid, signal) } == 0 { + return Ok(()); + } + let err = io::Error::last_os_error(); + if err.raw_os_error() == Some(libc::ESRCH) { Err(AttachError::NoListener) } else { Err(err.into()) } +} + +/// `.attach_pid`, removed on every path out of `ensure_listener`. +#[cfg(unix)] +struct Trigger(PathBuf); + +#[cfg(unix)] +impl Trigger { + fn create(pid: u32) -> Result { + let name = format!(".attach_pid{pid}"); + // HotSpot looks in its working directory before the temp dir; through /proc that also + // reaches a JVM in another mount namespace. + #[cfg(target_os = "linux")] + let candidates = [PathBuf::from(format!("/proc/{pid}/cwd")).join(&name), temp_dir().join(&name)]; + #[cfg(not(target_os = "linux"))] + let candidates = [temp_dir().join(&name)]; + let mut failure = None; + for path in candidates { + match create_private(&path) { + Ok(()) => return Ok(Self(path)), + Err(e) => failure = Some(e), + } + } + Err(failure.expect("at least one candidate").into()) + } +} + +#[cfg(unix)] +impl Drop for Trigger { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.0); + } +} + +/// `create_new` refuses to follow a symlink planted in a shared directory. +#[cfg(unix)] +fn create_private(path: &Path) -> io::Result<()> { + match OpenOptions::new().write(true).create_new(true).mode(0o600).open(path) { + Ok(_) => Ok(()), + // Left by an attempt that died before its cleanup; nobody else's file is adopted. + Err(e) if e.kind() == io::ErrorKind::AlreadyExists && owned_regular_file(path) => Ok(()), + Err(e) => Err(e), + } +} + +#[cfg(unix)] +fn owned_regular_file(path: &Path) -> bool { + std::fs::symlink_metadata(path).is_ok_and(|meta| owned_regular(&meta)) +} + +#[cfg(unix)] +fn owned_regular(meta: &Metadata) -> bool { + // SAFETY: geteuid has no preconditions and cannot fail. + meta.is_file() && meta.uid() == unsafe { libc::geteuid() } +} + +/// `/hsperfdata_/`, which HotSpot writes unless run with `-XX:-UsePerfData`. +/// Ownership matters outside macOS, where the directory sits in a shared `/tmp`. +#[cfg(unix)] +fn has_perf_data(pid: u32) -> bool { + let Some(user) = effective_user_name() else { return false }; + let path = temp_dir().join(format!("hsperfdata_{user}")).join(pid.to_string()); + std::fs::symlink_metadata(path).is_ok_and(|meta| { + owned_regular(&meta) && meta.modified().is_ok_and(|modified| written_since_start(modified, process_start(pid))) + }) +} + +/// Absorbs the coarser clock of the start time: Linux knows the boot time only to the second. +#[cfg(unix)] +const START_SLACK: Duration = Duration::from_secs(2); + +/// A perf-data file older than the process was left by a JVM that died without removing it +/// (SIGKILL) and whose pid was reused. An unknown start time proves nothing. +#[cfg(unix)] +fn written_since_start(modified: SystemTime, started: Option) -> bool { + started.and_then(|start| start.checked_sub(START_SLACK)).is_some_and(|earliest| modified >= earliest) +} + +#[cfg(target_os = "macos")] +fn process_start(pid: u32) -> Option { + let pid = libc::c_int::try_from(pid).ok()?; + // SAFETY: proc_bsdinfo is plain data; all-zero is a valid value. + let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() }; + let size = std::mem::size_of::() as libc::c_int; + // SAFETY: `info` is writable for `size` bytes, the most PROC_PIDTBSDINFO writes. + let written = unsafe { libc::proc_pidinfo(pid, libc::PROC_PIDTBSDINFO, 0, (&raw mut info).cast(), size) }; + if written != size { + return None; + } + Some(UNIX_EPOCH + Duration::from_secs(info.pbi_start_tvsec) + Duration::from_micros(info.pbi_start_tvusec)) +} + +#[cfg(target_os = "linux")] +fn process_start(pid: u32) -> Option { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?; + let system = std::fs::read_to_string("/proc/stat").ok()?; + // SAFETY: sysconf has no preconditions. + let ticks_per_sec = unsafe { libc::sysconf(libc::_SC_CLK_TCK) }; + start_from_proc(&stat, &system, u64::try_from(ticks_per_sec).ok().filter(|t| *t > 0)?) +} + +#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))] +fn process_start(_pid: u32) -> Option { + None +} + +/// `/proc//stat` field 22 is the start in clock ticks since boot; `btime` in `/proc/stat` +/// is the boot time in seconds since the epoch. +#[cfg(any(target_os = "linux", test))] +fn start_from_proc(stat: &str, system: &str, ticks_per_sec: u64) -> Option { + // The command name (field 2) may contain spaces and parentheses; the fields after it start at 3. + let ticks: u64 = stat.rsplit_once(')')?.1.split_whitespace().nth(22 - 3)?.parse().ok()?; + let boot: u64 = system.lines().find_map(|line| line.strip_prefix("btime "))?.trim().parse().ok()?; + let since_boot = Duration::from_millis(ticks.checked_mul(1000)? / ticks_per_sec); + Some(UNIX_EPOCH + Duration::from_secs(boot) + since_boot) +} + +/// HotSpot names the perf-data directory after the effective user's passwd entry. +#[cfg(unix)] +fn effective_user_name() -> Option { + let mut buf = vec![0 as libc::c_char; 4096]; + // SAFETY: passwd is plain data; all-zero is a valid value. + let mut pwd: libc::passwd = unsafe { std::mem::zeroed() }; + let mut result: *mut libc::passwd = std::ptr::null_mut(); + // SAFETY: every pointer refers to a live local buffer of the stated size. + let rc = unsafe { libc::getpwuid_r(libc::geteuid(), &mut pwd, buf.as_mut_ptr(), buf.len(), &mut result) }; + if rc != 0 || result.is_null() || pwd.pw_name.is_null() { + return None; + } + // SAFETY: on success `pw_name` is a NUL-terminated string inside `buf`. + let name = unsafe { std::ffi::CStr::from_ptr(pwd.pw_name) }; + Some(name.to_string_lossy().into_owned()) +} + +#[cfg(any(target_os = "linux", target_os = "macos"))] +fn runs_java(pid: u32) -> bool { + crate::jvm::exe_path(pid) + .is_some_and(|exe| exe.file_name().is_some_and(|name| name == "java") && !crate::jvm::is_openj9(&exe)) +} + +#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))] +fn runs_java(_pid: u32) -> bool { + false +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::process::Command; + + /// Kills the child even when an assertion fails. + struct ChildGuard(std::process::Child); + + impl Drop for ChildGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + + fn spawn_sleep() -> ChildGuard { + ChildGuard(Command::new("sleep").arg("30").spawn().expect("spawn sleep")) + } + + #[test] + fn is_hotspot_false_for_sleep() { + let _serial = crate::test_serial::hold(); + let sleep = spawn_sleep(); + assert!(!is_hotspot(sleep.0.id())); + } + + /// `sleep` copied to `/bin/java`: confirmed HotSpot by its name alone, unless the + /// JDK's `release` file says OpenJ9. + #[cfg(any(target_os = "linux", target_os = "macos"))] + fn sleep_as_java(release: &str) -> (tempfile::TempDir, ChildGuard) { + let jdk = tempfile::tempdir().unwrap(); + let java = jdk.path().join("bin/java"); + std::fs::create_dir(java.parent().unwrap()).unwrap(); + let sleep = ["/bin/sleep", "/usr/bin/sleep"].into_iter().find(|p| Path::new(p).exists()).expect("sleep"); + std::fs::copy(sleep, &java).unwrap(); + std::fs::write(jdk.path().join("release"), release).unwrap(); + let child = ChildGuard(Command::new(&java).arg("30").spawn().expect("spawn java")); + (jdk, child) + } + + #[cfg(any(target_os = "linux", target_os = "macos"))] + #[test] + fn an_executable_named_java_is_hotspot_unless_its_jdk_is_openj9() { + let _serial = crate::test_serial::hold(); + let (_jdk, hotspot) = sleep_as_java("IMPLEMENTOR=\"Eclipse Adoptium\"\nJAVA_VERSION=\"21.0.5\"\n"); + assert!(is_hotspot(hotspot.0.id())); + let (_jdk, openj9) = sleep_as_java("IMPLEMENTOR=\"IBM Corporation\"\nJVM_VARIANT=\"Openj9\"\n"); + let pid = openj9.0.id(); + assert!(!is_hotspot(pid)); + let result = ensure_listener(pid, Duration::from_millis(500)); + assert!(matches!(result, Err(AttachError::NotAJvm)), "{result:?}"); + } + + #[test] + fn ensure_listener_refuses_a_non_jvm() { + let _serial = crate::test_serial::hold(); + let sleep = spawn_sleep(); + let pid = sleep.0.id(); + let result = ensure_listener(pid, Duration::from_millis(500)); + assert!(matches!(result, Err(AttachError::NotAJvm)), "{result:?}"); + // SAFETY: signal 0 only checks that the pid exists. + assert_eq!(unsafe { libc::kill(pid as libc::pid_t, 0) }, 0, "the process must still be alive"); + } + + #[test] + fn foreign_socket_is_refused_without_a_signal() { + let _serial = crate::test_serial::hold(); + use std::os::unix::{fs::PermissionsExt, net::UnixListener}; + + let dir = tempfile::tempdir().unwrap(); + let socket = dir.path().join(".java_pid1"); + let _listener = UnixListener::bind(&socket).unwrap(); + std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o666)).unwrap(); + let sleep = spawn_sleep(); + let pid = sleep.0.id(); + let result = ensure_listener_at(&socket, pid, Duration::from_millis(500)); + assert!(matches!(result, Err(AttachError::ForeignListener)), "{result:?}"); + assert!(!temp_dir().join(format!(".attach_pid{pid}")).exists()); + // SAFETY: signal 0 only checks that the pid exists. + assert_eq!(unsafe { libc::kill(pid as libc::pid_t, 0) }, 0, "the process must still be alive"); + } + + #[test] + fn perf_data_counts_only_when_written_since_the_process_started() { + let start = UNIX_EPOCH + Duration::from_secs(1_700_000_000); + assert!(!written_since_start(start - Duration::from_secs(60), Some(start))); + assert!(!written_since_start(start - Duration::from_secs(3), Some(start))); + assert!(written_since_start(start - Duration::from_secs(1), Some(start))); + assert!(written_since_start(start + Duration::from_secs(5), Some(start))); + assert!(!written_since_start(start + Duration::from_secs(5), None)); + } + + #[test] + fn our_own_start_time_is_known_and_recent() { + let start = process_start(std::process::id()).expect("start time of this process"); + let age = SystemTime::now().duration_since(start).expect("started in the past"); + assert!(age < Duration::from_secs(24 * 3600), "{age:?}"); + } + + #[test] + fn start_time_from_proc_files() { + let stat = "1234 (my (odd) proc) S 1 1234 1234 0 -1 4194560 100 0 0 0 1 2 0 0 20 0 1 0 5000 1000 50"; + let system = "cpu 1 2 3 +btime 1700000000 +processes 9 +"; + let start = start_from_proc(stat, system, 100).unwrap(); + assert_eq!(start, UNIX_EPOCH + Duration::from_secs(1_700_000_050)); + assert_eq!( + start_from_proc( + stat, + "cpu 1 2 3 +", + 100 + ), + None + ); + assert_eq!(start_from_proc("1234 (short) S 1", system, 100), None); + } + + #[test] + fn process_group_pids_are_never_signalled() { + for pid in [0, u32::MAX, i32::MAX as u32 + 1] { + assert!(!is_hotspot(pid), "{pid}"); + let result = ensure_listener(pid, Duration::from_millis(100)); + assert!(matches!(result, Err(AttachError::NotAJvm)), "{pid}: {result:?}"); + } + } + + #[test] + fn trigger_file_is_private_and_removed_on_drop() { + use std::os::unix::fs::PermissionsExt; + + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(".attach_pid1"); + create_private(&path).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600); + create_private(&path).expect("our own leftover is reused"); + drop(Trigger(path.clone())); + assert!(!path.exists()); + } + + #[test] + fn trigger_file_refuses_a_planted_symlink() { + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().join("elsewhere"); + let path = dir.path().join(".attach_pid1"); + std::os::unix::fs::symlink(&target, &path).unwrap(); + assert!(create_private(&path).is_err()); + assert!(!target.exists()); + } +} diff --git a/crates/ide-jvm-attach/src/socket.rs b/crates/ide-jvm-attach/src/socket.rs index a438474304..2c1a15f58b 100644 --- a/crates/ide-jvm-attach/src/socket.rs +++ b/crates/ide-jvm-attach/src/socket.rs @@ -28,6 +28,10 @@ pub enum AttachError { Unsupported, #[error("the JVM has no attach listener")] NoListener, + #[error("the process is not a HotSpot JVM")] + NotAJvm, + #[error("the JVM did not open its attach listener; it may run with -XX:+DisableAttachMechanism")] + ListenerDidNotStart, #[error("the attach socket is not private to the current user")] ForeignListener, #[error("the attach listener refused the connection")] @@ -98,14 +102,14 @@ pub fn jcmd(pid: u32, command_line: &str, timeout: Duration) -> Result PathBuf { +pub(crate) fn socket_path(pid: u32) -> PathBuf { temp_dir().join(format!(".java_pid{pid}")) } /// Same trust rule as the JDK's `VirtualMachineImpl`: only talk to a socket we own and /// nobody else can reach, otherwise another user could answer in the JVM's place. #[cfg(unix)] -fn check_socket(path: &Path) -> Result<(), AttachError> { +pub(crate) fn check_socket(path: &Path) -> Result<(), AttachError> { // No symlink following: in a sticky, world-writable /tmp anyone can plant a symlink to a // socket we own, pass this check, then re-point it before connect. let meta = match std::fs::symlink_metadata(path) { @@ -397,6 +401,7 @@ mod tests { #[test] fn sends_v1_jcmd_request_and_returns_body() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let (path, listener) = bind_private(dir.path()); let server = serve_once(listener, b"0\nhello\n"); @@ -407,6 +412,7 @@ mod tests { #[test] fn sends_v1_agent_properties_request_and_parses_body() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let (path, listener) = bind_private(dir.path()); let server = serve_once(listener, b"0\n#Mon\nsun.jdwp.listenerAddress=dt_socket\\:64390\n"); @@ -417,6 +423,7 @@ mod tests { #[test] fn nonzero_code_is_command_error() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let (path, listener) = bind_private(dir.path()); let _server = serve_once(listener, b"-1\njava.lang.IllegalArgumentException: Unknown diagnostic command"); @@ -431,6 +438,7 @@ mod tests { #[test] fn jcmd_times_out_when_listener_never_answers() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let (path, listener) = bind_private(dir.path()); let (release, hold) = mpsc::channel::<()>(); @@ -448,6 +456,7 @@ mod tests { #[test] fn stale_socket_maps_to_refused() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let (path, listener) = bind_private(dir.path()); drop(listener); @@ -458,6 +467,7 @@ mod tests { #[test] fn rejects_socket_with_group_or_other_permissions() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let (path, _listener) = bind_private(dir.path()); fs::set_permissions(&path, fs::Permissions::from_mode(0o666)).unwrap(); @@ -468,6 +478,7 @@ mod tests { #[test] fn output_over_limit_is_too_large() { + let _serial = crate::test_serial::hold(); let (mut reader, mut writer) = UnixStream::pair().unwrap(); writer.write_all(b"0\n").unwrap(); writer.write_all(&[b'x'; 100]).unwrap(); @@ -479,6 +490,7 @@ mod tests { #[test] fn symlink_to_our_own_private_socket_is_rejected() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let (target, _listener) = bind_private(dir.path()); let link = dir.path().join(".java_pid2"); @@ -491,6 +503,7 @@ mod tests { #[test] fn peer_uid_check_passes_for_our_own_listener() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let (path, listener) = bind_private(dir.path()); let stream = connect_before(&path, Instant::now() + Duration::from_secs(1)).unwrap(); @@ -500,6 +513,7 @@ mod tests { #[test] fn connect_before_maps_missing_socket_to_no_listener() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let deadline = Instant::now() + Duration::from_secs(1); let missing = connect_before(&dir.path().join("nope"), deadline); @@ -510,6 +524,7 @@ mod tests { /// connect must give up within its deadline instead of hanging. #[test] fn connect_before_gives_up_on_a_full_backlog() { + let _serial = crate::test_serial::hold(); let dir = tempfile::tempdir().unwrap(); let (path, _listener) = bind_private(dir.path()); let mut held = Vec::new(); diff --git a/crates/ide-jvm-attach/src/test_serial.rs b/crates/ide-jvm-attach/src/test_serial.rs new file mode 100644 index 0000000000..1bdb47d428 --- /dev/null +++ b/crates/ide-jvm-attach/src/test_serial.rs @@ -0,0 +1,10 @@ +use std::sync::{Mutex, MutexGuard}; + +static SERIAL: Mutex<()> = Mutex::new(()); + +/// Held for a whole test that binds or accepts on a socket or spawns a process. macOS sets +/// close-on-exec on a new socket only after `socket()` returns, so a child spawned meanwhile by +/// another test inherits the listening fd and keeps a dropped listener connectable. +pub fn hold() -> MutexGuard<'static, ()> { + SERIAL.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} diff --git a/crates/ide-jvm-attach/src/threads.rs b/crates/ide-jvm-attach/src/threads.rs new file mode 100644 index 0000000000..dbdf4049ad --- /dev/null +++ b/crates/ide-jvm-attach/src/threads.rs @@ -0,0 +1,281 @@ +use std::collections::{HashMap, HashSet, VecDeque}; +use std::process::Command; +use std::time::Duration; + +use crate::listener::is_hotspot; +use crate::socket::{AttachError, jcmd}; + +/// Default budget for `thread_print`; a dump of a healthy JVM takes milliseconds, so this only +/// bounds a JVM stuck at a safepoint. +pub const THREAD_DUMP_TIMEOUT: Duration = Duration::from_secs(10); + +/// System property the IDE adds to a run's JVM so it can be found even when the build tool +/// forks it outside the run's process tree (a Gradle daemon). +pub const RUN_TOKEN_PROPERTY: &str = "-Dopenidea.run.token="; + +/// Gradle's own JVMs: the client that waits for the build, the daemon that runs it, and the +/// workers and Kotlin compile daemon it forks (beside the application under `--no-daemon`). +/// None is the application, even when it is the only JVM under the run's root. +const GRADLE_JVM_MARKERS: [&str; 5] = [ + "org.gradle.wrapper.GradleWrapperMain", + "org.gradle.launcher.GradleMain", + "org.gradle.launcher.daemon", + "org.gradle.process.internal.worker.GradleWorkerMain", + "org.jetbrains.kotlin.daemon.KotlinCompileDaemon", +]; + +/// `Thread.print -l` also lists the owned `java.util.concurrent` locks, which deadlock +/// reports need. +pub fn thread_print(pid: u32, timeout: Duration) -> Result { + jcmd(pid, "Thread.print -l", timeout) +} + +#[derive(Debug, Clone, PartialEq)] +pub struct ProcEntry { + pub pid: u32, + pub ppid: u32, + /// The full argv joined by spaces, as `ps` prints it. + pub command: String, +} + +/// Every process of the machine; empty when `ps` is unavailable. +pub fn process_table() -> Vec { + let Ok(out) = Command::new("ps").args(["-A", "-o", "pid=,ppid=,command="]).output() else { + return Vec::new(); + }; + String::from_utf8_lossy(&out.stdout).lines().filter_map(parse_ps_line).collect() +} + +fn parse_ps_line(line: &str) -> Option { + let (pid, rest) = line.trim_start().split_once(char::is_whitespace)?; + let (ppid, command) = rest.trim_start().split_once(char::is_whitespace)?; + Some(ProcEntry { pid: pid.parse().ok()?, ppid: ppid.parse().ok()?, command: command.trim().to_string() }) +} + +/// The JVM that runs a run configuration: the deepest HotSpot JVM below `root` that is not +/// Gradle's own (a Maven `spring-boot:run` forks the application under the Maven JVM), else +/// the one carrying `token` (a Gradle daemon forks it outside the run's tree, which then holds +/// only the Gradle client). Ties go to the highest pid. +pub fn select_run_jvm( + table: &[ProcEntry], + root: u32, + token: Option<&str>, + is_hotspot: impl Fn(u32) -> bool, +) -> Option { + // The tree first: a token is only as unique as the configuration and project it names. + deepest_jvm_in_tree(table, root, &is_hotspot).or_else(|| { + let wanted = format!("{RUN_TOKEN_PROPERTY}{}", token.filter(|token| !token.is_empty())?); + table + .iter() + // The Gradle client carries the token too: a delegated run passes it on its command line. + .filter(|entry| { + entry.command.split_whitespace().any(|arg| arg == wanted) + && !is_gradle_jvm(&entry.command) + && is_hotspot(entry.pid) + }) + .map(|entry| entry.pid) + .max() + }) +} + +/// Confirmed HotSpot (`is_hotspot`) and, by its command line, not one of Gradle's own JVMs. +pub fn is_application_jvm(pid: u32) -> bool { + is_hotspot(pid) && !command_line(pid).is_some_and(|command| is_gradle_jvm(&command)) +} + +fn command_line(pid: u32) -> Option { + let out = Command::new("ps").args(["-o", "command=", "-p", &pid.to_string()]).output().ok()?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_owned()) +} + +fn is_gradle_jvm(command: &str) -> bool { + GRADLE_JVM_MARKERS.iter().any(|marker| command.contains(marker)) +} + +fn deepest_jvm_in_tree(table: &[ProcEntry], root: u32, is_hotspot: &dyn Fn(u32) -> bool) -> Option { + let mut children: HashMap> = HashMap::new(); + for entry in table { + children.entry(entry.ppid).or_default().push(entry); + } + let by_pid: HashMap = table.iter().map(|entry| (entry.pid, entry)).collect(); + + let mut seen = HashSet::from([root]); + let mut queue = VecDeque::from([(root, 0usize)]); + let mut best: Option<(usize, u32)> = None; + while let Some((pid, depth)) = queue.pop_front() { + let is_app_jvm = by_pid.get(&pid).is_some_and(|entry| !is_gradle_jvm(&entry.command)) && is_hotspot(pid); + if is_app_jvm && best.is_none_or(|found| (depth, pid) > found) { + best = Some((depth, pid)); + } + for child in children.get(&pid).into_iter().flatten() { + if seen.insert(child.pid) { + queue.push_back((child.pid, depth + 1)); + } + } + } + best.map(|(_, pid)| pid) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry(pid: u32, ppid: u32, command: &str) -> ProcEntry { + ProcEntry { pid, ppid, command: command.to_string() } + } + + fn any_pid(_: u32) -> bool { + true + } + + /// The shell at pid 10 is not a JVM, as the real `is_hotspot` would say. + fn not_the_shell(pid: u32) -> bool { + pid != 10 + } + + fn gradle_run() -> Vec { + vec![ + entry(10, 1, "/bin/zsh"), + entry(11, 10, "/jdk/bin/java -classpath wrapper.jar org.gradle.wrapper.GradleWrapperMain run"), + entry(50, 40, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main"), + ] + } + + #[test] + fn select_falls_back_to_the_token_when_the_tree_holds_only_gradle() { + let table = gradle_run(); + assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(50)); + assert_eq!(select_run_jvm(&table, 10, Some("cfg-2"), not_the_shell), None); + } + + #[test] + fn select_skips_the_gradle_client_that_carries_the_token() { + let client = |pid| { + entry( + pid, + 10, + "/jdk/bin/java -Dopenidea.run.token=cfg-1 -classpath wrapper.jar org.gradle.wrapper.GradleWrapperMain run", + ) + }; + let app = entry(50, 40, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main"); + for client_pid in [11, 99] { + let table = vec![entry(10, 1, "/bin/zsh"), client(client_pid), app.clone()]; + assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(50), "client {client_pid}"); + } + // Only the client carries it: the tree rules apply, which skip the client too. + let table = vec![entry(10, 1, "/bin/zsh"), client(11), entry(12, 11, "/jdk/bin/java -cp app Main")]; + assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(12)); + let alone = vec![entry(10, 1, "/bin/zsh"), client(11)]; + assert_eq!(select_run_jvm(&alone, 10, Some("cfg-1"), not_the_shell), None); + let launcher = entry(13, 10, "java -Dopenidea.run.token=cfg-1 org.gradle.launcher.GradleMain run"); + assert_eq!(select_run_jvm(&[entry(10, 1, "sh"), launcher], 10, Some("cfg-1"), not_the_shell), None); + } + + #[test] + fn select_prefers_the_run_tree_over_a_token_elsewhere() { + // Another worktree's delegated JVM carries the same token as this plain run. + let table = vec![ + entry(10, 1, "/bin/zsh"), + entry(11, 10, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main"), + entry(50, 40, "/jdk/bin/java -Dopenidea.run.token=cfg-1 -cp app Main"), + ]; + assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), not_the_shell), Some(11)); + } + + #[test] + fn select_picks_deepest_jvm_in_tree() { + let table = vec![ + entry(10, 1, "/bin/zsh"), + entry(11, 10, "/jdk/bin/java -classpath maven.jar org.codehaus.plexus.classworlds.launcher.Launcher"), + entry(12, 11, "/jdk/bin/java -cp app Main"), + ]; + assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(12)); + } + + #[test] + fn select_ignores_token_substring() { + let table = vec![entry(50, 1, "java -Dopenidea.run.token=cfg-10 -cp app Main")]; + assert_eq!(select_run_jvm(&table, 10, Some("cfg-1"), any_pid), None); + assert_eq!(select_run_jvm(&table, 10, Some("cfg-10"), any_pid), Some(50)); + } + + #[test] + fn select_none_when_tree_has_no_jvm() { + let table = vec![entry(10, 1, "/bin/zsh"), entry(11, 10, "/bin/sleep 5"), entry(12, 1, "java -cp app Main")]; + assert_eq!(select_run_jvm(&table, 10, None, |pid| pid == 12), None); + } + + #[test] + fn select_treats_an_empty_token_as_no_token() { + // "-Dopenidea.run.token=" with nothing after it must not tag every such process. + let table = + vec![entry(50, 1, "java -Dopenidea.run.token= -cp app Main"), entry(10, 1, "sh"), entry(11, 10, "java a")]; + assert_eq!(select_run_jvm(&table, 10, Some(""), not_the_shell), Some(11)); + } + + #[test] + fn select_takes_the_highest_pid_among_equally_deep_jvms() { + let table = vec![entry(10, 1, "sh"), entry(11, 10, "java a"), entry(12, 10, "java b")]; + assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(12)); + let tagged = vec![entry(5, 1, "java -Dopenidea.run.token=t"), entry(7, 1, "java -Dopenidea.run.token=t")]; + assert_eq!(select_run_jvm(&tagged, 10, Some("t"), any_pid), Some(7)); + } + + #[test] + fn select_skips_tagged_processes_that_are_not_a_hotspot_jvm() { + let table = vec![entry(50, 1, "native -Dopenidea.run.token=t"), entry(10, 1, "sh"), entry(11, 10, "java a")]; + assert_eq!(select_run_jvm(&table, 10, Some("t"), |pid| pid == 11), Some(11)); + } + + #[test] + fn select_includes_the_root_itself() { + let table = vec![entry(10, 1, "java -cp app Main")]; + assert_eq!(select_run_jvm(&table, 10, None, any_pid), Some(10)); + } + + #[test] + fn select_survives_a_parent_cycle() { + let table = vec![entry(10, 11, "sh"), entry(11, 10, "java a")]; + assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(11)); + } + + #[test] + fn select_skips_gradle_workers_and_the_kotlin_daemon() { + // `--no-daemon`: the build's helper JVMs sit beside the application in the run's tree. + let worker = "/jdk/bin/java -cp gradle-worker.jar worker.org.gradle.process.internal.worker.GradleWorkerMain 'Gradle Worker Daemon 1'"; + let kotlin = "/jdk/bin/java -cp kotlin-compiler-embeddable.jar org.jetbrains.kotlin.daemon.KotlinCompileDaemon --daemon-runFilesPath x"; + let build = + entry(11, 10, "/jdk/bin/java -cp gradle-launcher.jar org.gradle.launcher.GradleMain --no-daemon run"); + let table = vec![ + entry(10, 1, "/bin/zsh"), + build.clone(), + entry(12, 11, "/jdk/bin/java -cp app Main"), + entry(20, 11, worker), + entry(21, 11, kotlin), + ]; + assert_eq!(select_run_jvm(&table, 10, None, not_the_shell), Some(12)); + let helpers = vec![entry(10, 1, "/bin/zsh"), build, entry(20, 11, worker), entry(21, 11, kotlin)]; + assert_eq!(select_run_jvm(&helpers, 10, None, not_the_shell), None); + } + + #[cfg(unix)] + #[test] + fn command_line_of_a_process_and_a_sleep_is_no_application_jvm() { + let mut sleep = Command::new("sleep").arg("30").spawn().expect("spawn sleep"); + let pid = sleep.id(); + let (command, application) = (command_line(pid), is_application_jvm(pid)); + let _ = sleep.kill(); + let _ = sleep.wait(); + assert_eq!(command.as_deref(), Some("sleep 30")); + assert!(!application); + assert_eq!(command_line(pid), None, "an ended process has no command line"); + } + + #[test] + fn parses_ps_lines_with_arguments_and_padding() { + let parsed = parse_ps_line(" 123 45 /jdk/bin/java -Dk=v -cp a b").unwrap(); + assert_eq!(parsed, entry(123, 45, "/jdk/bin/java -Dk=v -cp a b")); + assert_eq!(parse_ps_line(" PID PPID COMMAND"), None); + assert_eq!(parse_ps_line(" 7 1"), None); + } +} diff --git a/crates/ide-jvm-attach/tests/real_jvm.rs b/crates/ide-jvm-attach/tests/real_jvm.rs index 8aa545fed2..ff9f7d5996 100644 --- a/crates/ide-jvm-attach/tests/real_jvm.rs +++ b/crates/ide-jvm-attach/tests/real_jvm.rs @@ -8,11 +8,31 @@ use std::sync::mpsc; use std::time::{Duration, Instant}; use ide_jvm_attach::{ - AttachError, HeapDumpReply, agent_properties, find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command, - histogram_safe_while_suspended, java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply, - parse_release, vm_flags, + AttachError, HeapDumpReply, LISTENER_START_TIMEOUT, THREAD_DUMP_TIMEOUT, agent_properties, ensure_listener, + find_jvm_by_jdwp_port, has_listener, heap_dump, heap_dump_command, histogram_safe_while_suspended, is_hotspot, + java_version_of, jcmd, jdwp_port, parse_class_histogram, parse_heap_dump_reply, parse_release, process_table, + select_run_jvm, temp_dir, thread_print, vm_flags, }; +/// Two threads that each hold one monitor and wait for the other's after 200 ms. +const DEADLOCK_JAVA: &str = r#" +public class Deadlock { + static final Object A = new Object(), B = new Object(); + + static void sleep(long ms) { + try { Thread.sleep(ms); } catch (InterruptedException e) { throw new RuntimeException(e); } + } + + public static void main(String[] args) { + new Thread(() -> { synchronized (A) { sleep(200); synchronized (B) { } } }, "sync-1").start(); + new Thread(() -> { synchronized (B) { sleep(200); synchronized (A) { } } }, "sync-2").start(); + System.out.println("READY"); + System.out.flush(); + sleep(60_000); + } +} +"#; + const MAIN_JAVA: &str = r#" import java.util.ArrayList; import java.util.List; @@ -168,15 +188,19 @@ fn finds_a_real_jvm_by_its_jdwp_port() { /// Compiles `MAIN_JAVA` with the `javac` next to `java`, since JDK 8 has no source launcher. fn launch_main(java: &Path, dir: &Path, jvm_args: &[&str]) -> JvmGuard { - let source = dir.join("Main.java"); - std::fs::write(&source, MAIN_JAVA).unwrap(); + launch_class(java, dir, "Main", MAIN_JAVA, jvm_args) +} + +fn launch_class(java: &Path, dir: &Path, class: &str, source_text: &str, jvm_args: &[&str]) -> JvmGuard { + let source = dir.join(format!("{class}.java")); + std::fs::write(&source, source_text).unwrap(); let status = Command::new(java.with_file_name("javac")).arg("-d").arg(dir).arg(&source).status().expect("javac"); assert!(status.success(), "javac failed"); let child = Command::new(java) .args(jvm_args) .arg("-cp") .arg(dir) - .arg("Main") + .arg(class) .current_dir(dir) .stdout(Stdio::piped()) .stderr(Stdio::piped()) @@ -310,3 +334,55 @@ fn dumps_while_suspended() { assert!(guard.0.try_wait().unwrap().is_none(), "the JVM exited after resume"); vm_flags(pid, Duration::from_secs(10)).expect("the attach listener answers after resume"); } + +#[test] +#[ignore = "needs a real JDK >= 8: set OPENIDEA_TEST_JAVA to its bin/java"] +fn ensure_listener_starts_a_listener_on_demand() { + let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else { + eprintln!("OPENIDEA_TEST_JAVA is not set; skipping"); + return; + }; + let dir = tempfile::tempdir().unwrap(); + let mut guard = launch_main(&java, dir.path(), &[]); + let pid = guard.0.id(); + wait_for_ready(&output_lines(&mut guard.0)); + assert!(!has_listener(pid), "the JVM opened its listener without being asked"); + assert!(is_hotspot(pid)); + + let started = Instant::now(); + ensure_listener(pid, LISTENER_START_TIMEOUT).unwrap(); + eprintln!("on-demand listener for pid {pid} in {:?}", started.elapsed()); + assert!(has_listener(pid)); + jcmd(pid, "VM.version", Duration::from_secs(10)).expect("the new listener answers"); + + let trigger = format!(".attach_pid{pid}"); + for parent in [temp_dir(), dir.path().to_path_buf()] { + assert!(!parent.join(&trigger).exists(), "trigger file left in {parent:?}"); + } + ensure_listener(pid, LISTENER_START_TIMEOUT).expect("an open listener is accepted as is"); +} + +#[test] +#[ignore = "needs a real JDK >= 8: set OPENIDEA_TEST_JAVA to its bin/java"] +fn thread_print_reports_a_deadlock() { + let Some(java) = std::env::var_os("OPENIDEA_TEST_JAVA").map(PathBuf::from) else { + eprintln!("OPENIDEA_TEST_JAVA is not set; skipping"); + return; + }; + let dir = tempfile::tempdir().unwrap(); + let mut guard = launch_class(&java, dir.path(), "Deadlock", DEADLOCK_JAVA, &["-XX:+StartAttachListener"]); + let pid = guard.0.id(); + wait_for_ready(&output_lines(&mut guard.0)); + wait_for_listener(pid); + // The threads take their first monitor at once and the second after 200 ms. + std::thread::sleep(Duration::from_secs(1)); + + let dump = thread_print(pid, THREAD_DUMP_TIMEOUT).unwrap(); + assert!(dump.contains("Found one Java-level deadlock"), "{dump}"); + assert!(dump.contains("sync-1") && dump.contains("sync-2"), "{dump}"); + + // The run's JVM is found through the real process table, as the dump action does. + let table = process_table(); + assert!(table.iter().any(|entry| entry.pid == pid && entry.command.contains("Deadlock"))); + assert_eq!(select_run_jvm(&table, pid, None, is_hotspot), Some(pid)); +} diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rs index 742eb88470..917427faba 100644 --- a/crates/ide-run/src/process.rs +++ b/crates/ide-run/src/process.rs @@ -822,6 +822,17 @@ impl ProcessManager { Ok(()) } + /// The launched process's pid while it runs; `None` for an unknown or exited run, whose pid + /// the system may already have given to something else. + pub fn pid(&self, id: RunId) -> Option { + let entry = self.entry(id).ok()?; + if entry.exited.load(Ordering::Acquire) { + return None; + } + let pid = entry.pid.lock(); + *pid + } + /// Returns `None` while running, or the exit code once output has drained. pub fn exit_code(&self, id: RunId) -> IdeResult>> { let entry = self.entry(id)?; diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 2845b39c02..f23af7b9e6 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -3,8 +3,8 @@ //! This crate is glue only. `commands/.rs` holds the commands only the desktop runs; the //! Tauri adapters of project-host commands are derived from their `ide-host` declarations. No //! domain logic lives here. -// `commands::catalogue!` recurses a few times per command domain. -#![recursion_limit = "256"] +// `commands::catalogue!` recurses once per command, so the limit grows with the command count. +#![recursion_limit = "512"] mod application_focus; mod cli; diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 6a38a4e9da..997d731b59 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -180,6 +180,7 @@ debug_jvm_memory_classes trusted project_host bin debug_jvm_memory_fields trusted project_host bindings async debug_jvm_memory_instances trusted project_host bindings async debug_jvm_memory_referrers trusted project_host bindings async +debug_jvm_thread_dump trusted project_host bindings async debug_listen_for_jvm trusted project_host bindings async debug_pause trusted project_host bindings async debug_redefine_classes trusted project_host bindings async @@ -575,6 +576,7 @@ run_gradle_init_script trusted project_host bin run_gradle_jvm_args_script always project_host bindings async run_import_configs trusted project_host bindings async run_import_sources trusted project_host bindings async +run_jvm_thread_dump trusted project_host bindings async run_list always project_host bindings sync run_resize trusted project_host bindings sync run_save_configs trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index 1dfdc31143..206c1808d4 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -455,6 +455,8 @@ export const commands = { debugJvmMemoryInstances: (session: DebugSessionId, className: string, limit: number) => typedError(__TAURI_INVOKE("debug_jvm_memory_instances", { session, className, limit })), /** The objects that hold a reference to `object`; `limit` 0 selects the default. */ debugJvmMemoryReferrers: (session: DebugSessionId, object: JvmObjectRef, limit: number) => typedError(__TAURI_INVOKE("debug_jvm_memory_referrers", { session, object, limit })), + /** A `Thread.print -l` of the debuggee JVM, or why it cannot be taken. */ + debugJvmThreadDump: (session: DebugSessionId) => typedError(__TAURI_INVOKE("debug_jvm_thread_dump", { session })), /** * Remote JVM Debug in listen mode: waits (cancellable through `request`) for the remote * JVM to connect to `host:port`; returns the loopback port java-debug attaches to. @@ -1559,6 +1561,11 @@ export const commands = { runImportConfigs: (source: RunImportSource, existing: RunConfig_Deserialize[]) => typedError(__TAURI_INVOKE("run_import_configs", { source, existing })), /** Project files run configurations can be imported from (`.vscode/launch.json`). */ runImportSources: () => typedError(__TAURI_INVOKE("run_import_sources")), + /** + * A `Thread.print -l` of the JVM a run started: the deepest HotSpot JVM of the run's process + * tree, else the one carrying `token` (the run's marker property). + */ + runJvmThreadDump: (id: RunId, token: string | null) => typedError(__TAURI_INVOKE("run_jvm_thread_dump", { id, token })), runList: () => __TAURI_INVOKE("run_list"), /** Terminal size of a run started with "Emulate terminal in output console". */ runResize: (id: RunId, cols: number, rows: number) => typedError(__TAURI_INVOKE("run_resize", { id, cols, rows })), @@ -8797,6 +8804,26 @@ export type JvmReferrer = { export type JvmReferrersResult = { status: "ready"; referrers: JvmReferrer[]; truncated: boolean } | { status: "unavailable"; reason: JvmInspectUnavailable }; +export type JvmThreadDump = { + text: string, + pid: number, + /** Empty when unknown. */ + javaVersion: string, + takenWhileSuspended: boolean, + /** Wall time of the `Thread.print` request. */ + elapsedMs: number, +}; + +export type JvmThreadsResult = { status: "ready"; dump: JvmThreadDump } | { status: "unavailable"; reason: JvmThreadsUnavailable }; + +export type JvmThreadsUnavailable = +/** The reason a class table could not be read applies to the dump too. */ +{ kind: "jvm"; reason: JvmMemoryUnavailable } | +/** The JVM ignored the request to open its attach listener (`-XX:+DisableAttachMechanism`). */ +{ kind: "listenerDidNotStart" } | +/** A run on a remote host, whose JVM this machine cannot attach to. */ +{ kind: "remoteRun" } | { kind: "failed"; message: string }; + export type JvmTypeKind = "class" | "abstractClass" | "interface" | "enum" | "record" | "annotation" | "exception" | "object"; export type JvmValue = { kind: "null" } | { kind: "primitive"; typeName: string; text: string } | diff --git a/src/features/debugger/__tests__/actions.test.ts b/src/features/debugger/__tests__/actions.test.ts index a1c57fb0d5..265a99e258 100644 --- a/src/features/debugger/__tests__/actions.test.ts +++ b/src/features/debugger/__tests__/actions.test.ts @@ -609,6 +609,18 @@ describe("output class breakpoint restrictions", () => { }); }); +it("links an attach to the run it debugs, so the run's thread dumps go through the session", async () => { + useProject.setState({ project: { root: "/p" } as never }); + const target = { name: "app", adapter: "debugpy", hostName: "127.0.0.1", port: 41234, remoteRoot: "/app" }; + const extra = (call: number) => JSON.parse(ipc.debugStart.mock.calls[call]![0].extraJson!); + ipc.debugStart.mockClear(); + await executeAction("debug.attach", { ...target, process: 31 }); + await executeAction("debug.attach", target); + const { __openideaRun: run, ...linked } = extra(0); + expect(run).toBe(31); + expect(extra(1)).toEqual(linked); +}); + it("stops the waiting Python container if attaching fails", async () => { useProject.setState({ project: { root: "/p" } as never }); ipc.debugStart.mockResolvedValueOnce({ diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index f16641f65b..ad147600cd 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -112,6 +112,15 @@ function isAttachableTarget( return typeof a.attachable?.pid === "number" && typeof a.attachable.kind === "string"; } +/** + * Names the run the attach debugs (`RUN_LINK` in ide-dap, kept from the adapter): the run's Dump + * Threads then goes through the session, which knows whether the JVM is stopped. + */ +function linkedToRun(launch: LaunchConfig, run: RunId): LaunchConfig { + const extra = launch.extraJson ? (JSON.parse(launch.extraJson) as Record) : {}; + return { ...launch, extraJson: JSON.stringify({ ...extra, __openideaRun: run }) }; +} + function errorText(e: unknown) { return e instanceof Error ? e.message : String(e); } @@ -539,6 +548,7 @@ export function registerDebugActions(): () => void { else if (isJavaAttachTarget(arg)) launch = await javaAttachConfig(arg, root); else return; const process = (arg.process ?? null) as RunId | null; + if (process != null) launch = linkedToRun(launch, process); // Another JVM of the same run (a Gradle test worker, the one just detached) keeps it. const shared = process != null && @@ -622,6 +632,27 @@ export function registerDebugActions(): () => void { if (s && sessionSupports("jvmHeap", s)) void captureHeap(s.id); }, }, + { + id: "debug.dumpThreads", + title: "Dump Threads", + category: "Debug", + icon: "thread-dump", + keywords: ["thread dump", "jstack", "deadlock", "threads"], + when: "debugHasJvmMemory", + indicatesRunning: true, + run: async () => { + const s = activeSession(); + if (!s || !sessionSupports("jvmMemory", s)) return; + const session = s.id; + const name = s.name; + // The Run tool window shows the dump; its tab takes the next one through `take` on Refresh. + await executeAction("run.openThreadDump", { + title: tx`Threads: ${name}`, + source: { session }, + take: () => call(commands.debugJvmThreadDump(session)), + }); + }, + }, { id: "debug.startPageProfile", title: "Start CPU Profile", diff --git a/src/features/debugger/ui/DebugToolWindow.tsx b/src/features/debugger/ui/DebugToolWindow.tsx index 19d66d71f9..fb8e10a2d8 100644 --- a/src/features/debugger/ui/DebugToolWindow.tsx +++ b/src/features/debugger/ui/DebugToolWindow.tsx @@ -96,6 +96,8 @@ const MORE_ITEMS: MenuItem[] = [ { kind: "separator" }, { kind: "action", action: "debug.evaluate", icon: "evaluate-expression" }, { kind: "action", action: "debug.resetFrame", icon: "reset-frame" }, + { kind: "separator" }, + { kind: "action", action: "debug.dumpThreads", icon: "thread-dump" }, ]; function MoreActions() { diff --git a/src/features/run/RunView.tsx b/src/features/run/RunView.tsx index 646ddbbad6..53a9580c70 100644 --- a/src/features/run/RunView.tsx +++ b/src/features/run/RunView.tsx @@ -51,6 +51,8 @@ import { rerunFailedConfigs } from "./testing/rerun"; import { formatDuration, nodeOutput } from "./testing"; import { TestStatusBar, TestTreeView } from "./TestTreeView"; import { StackTracePanel, useStackTraces, type StackTraceTab } from "./stackTrace"; +import { ThreadDumpPanel } from "./threadDump/ThreadDumpPanel"; +import { isJvmRun } from "./threadDump/actions"; import { closeRunTab, runTabMenu } from "./runTabs"; import { showApplicationUpdate, useApplicationUpdates } from "./applicationUpdate"; import { isUpdatable } from "./updatePolicies"; @@ -112,8 +114,11 @@ export function SessionPanel({ const hasTests = !!rt?.tests; const canUpdateApplication = isUpdatable(session.config); const hasFlutterActions = supportsHotReload(session.config); + const canDumpThreads = isJvmRun(session.config); // Eight standard buttons with group spacing and insets, then 24 px plus gap per extra button. - const fullToolbarWidth = 228 + 26 * (Number(hasTests) + Number(canUpdateApplication) + 2 * Number(hasFlutterActions)); + const fullToolbarWidth = + 228 + + 26 * (Number(hasTests) + Number(canUpdateApplication) + Number(canDumpThreads) + 2 * Number(hasFlutterActions)); useLayoutEffect(() => { const pane = body.current; if (!hasRuntime || !pane || (!showLifecycle && !hasTests)) return; @@ -280,6 +285,15 @@ export function SessionPanel({ onClick={() => showApplicationUpdate(session.id)} /> )} + {canDumpThreads && ( + + )} {hasFlutterActions && ( <> {stopButton} @@ -549,6 +563,8 @@ export function RunView() { > {"session" in current ? ( + ) : current.trace.kind === "threads" ? ( + ) : ( )} diff --git a/src/features/run/gradleBoot.gradle b/src/features/run/gradleBoot.gradle index a6dfa1e471..409312d62f 100644 --- a/src/features/run/gradleBoot.gradle +++ b/src/features/run/gradleBoot.gradle @@ -1,11 +1,14 @@ -// OpenIDEA: BootRun is a JavaExec task; give its forked application JVM a dynamic -// JDWP port instead of Gradle's fixed 5005. The property is added by jdwpLaunch. +// OpenIDEA: BootRun is a JavaExec task; mark its forked application JVM with the run token +// and, for Debug, give it a dynamic JDWP port instead of Gradle's fixed 5005. The debug +// property is added by jdwpLaunch. import org.gradle.util.GradleVersion // `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added. def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) } gradle.projectsEvaluated { allprojects { each(tasks.matching { it.name == 'bootRun' }) { task -> + def token = System.getProperty('openidea.run.token') + if (token) task.jvmArgs('-Dopenidea.run.token=' + token) if (System.getProperty('openidea.run.debug') == 'true') { task.debug = false task.doFirst { diff --git a/src/features/run/gradleRun.gradle b/src/features/run/gradleRun.gradle index 01381a4aac..7c41b06114 100644 --- a/src/features/run/gradleRun.gradle +++ b/src/features/run/gradleRun.gradle @@ -23,6 +23,8 @@ allprojects { p -> if (t.hasProperty('mainClass')) t.mainClass.set(main) else t.main = main t.args(list('openidea.run.args')) t.jvmArgs(list('openidea.run.jvmArgs')) + def token = System.getProperty('openidea.run.token') + if (token) t.jvmArgs('-Dopenidea.run.token=' + token) // The IDE attaches to this JVM, not to the Gradle daemon; port 0 prints the one picked. if (Boolean.getBoolean('openidea.run.debug')) { // Opens the attach socket for the memory view, unless the VM options decide about it. diff --git a/src/features/run/gradleRun.test.ts b/src/features/run/gradleRun.test.ts index 8269509bcf..0e64cf95a0 100644 --- a/src/features/run/gradleRun.test.ts +++ b/src/features/run/gradleRun.test.ts @@ -5,7 +5,9 @@ import { applicationConfig } from "./application"; import { DELEGATED_ATTACH_LISTENER, DELEGATED_DEBUG, + DELEGATED_TOKEN, delegatedGradleConfig, + runJvmToken, gradleDelegation, gradleBootLaunch, gradleTestLaunch, @@ -85,6 +87,7 @@ describe("Build and run using: Gradle", () => { '-Dopenidea.run.args=["--port","8081 x"]', '-Dopenidea.run.jvmArgs=["-Xmx1g"]', `-Dopenidea.run.workingDir=${CORE}`, + `${DELEGATED_TOKEN}${runJvmToken(app, ROOT)}`, ":billing:core:openideaRun", ]); }); @@ -97,6 +100,36 @@ describe("Build and run using: Gradle", () => { expect(run.args.slice(-2)).toEqual(["--offline", ":app:openideaRun"]); }); + it("delegated run passes a stable token", () => { + const app = applicationConfig({ className: "a.Main" }, "app/src/main/java/a/Main.java", []); + const token = (c: RunConfig) => c.args.filter((a) => a.startsWith(DELEGATED_TOKEN)); + const first = token(delegatedGradleConfig(app, "app", ctx)!); + // A per-launch value would miss Gradle's configuration cache on every launch. + expect(first).toEqual([`${DELEGATED_TOKEN}${runJvmToken(app, ROOT)}`]); + expect(token(delegatedGradleConfig(app, "app", { ...ctx, configurationCache: true })!)).toEqual(first); + }); + + it("token escapes unsafe characters", () => { + expect(runJvmToken({ id: "app:Main Class/x\\y" }, ROOT)).toMatch(/^app_Main_Class_x_y-[A-Za-z0-9]+$/); + expect(runJvmToken({ id: "a.b-c_9" }, ROOT)).toMatch(/^a\.b-c_9-[A-Za-z0-9]+$/); + }); + + it("token names the project as well as the configuration", () => { + const app = { id: "application:app:com.example.DemoApplication" }; + expect(runJvmToken(app, ROOT)).toBe(runJvmToken({ ...app }, ROOT)); + // Two worktrees of one project, or two projects with the same main class. + expect(runJvmToken(app, "/w/shop-feature")).not.toBe(runJvmToken(app, ROOT)); + expect(runJvmToken(app, "/w/other")).not.toBe(runJvmToken(app, ROOT)); + }); + + it("init scripts hand the token to the forked JVM in Run and Debug alike", () => { + for (const script of [RUN_SCRIPT, BOOT_SCRIPT]) { + const token = script.indexOf("jvmArgs('-Dopenidea.run.token=' + token)"); + expect(token).toBeGreaterThan(-1); + expect(token).toBeLessThan(script.indexOf("openidea.run.debug")); + } + }); + it("reuses Gradle's configuration cache on Gradle 8.1+ wrappers", () => { const app = applicationConfig({ className: "a.Main" }, "app/src/main/java/a/Main.java", []); const run = delegatedGradleConfig(app, "app", { ...ctx, configurationCache: true })!; @@ -266,6 +299,7 @@ describe("Gradle test runs", () => { describe("Gradle launch routing", () => { const boot = { + id: "boot", kind: "gradle", command: "./gradlew", args: [":module:bootRun"], @@ -296,6 +330,21 @@ describe("Gradle launch routing", () => { expect(boot.args).toEqual([":module:bootRun"]); expect(test.args).toEqual([":module:test"]); }); + + it("marks the forked BootRun JVM with a stable per-configuration token", async () => { + useProject.setState({ project: { root: ROOT } as ProjectInfo, settings: null }); + const named = { ...boot, id: "boot app/1" } as RunConfig; + const first = await gradleBootLaunch(named); + expect(first.args.filter((a) => a.startsWith(DELEGATED_TOKEN))).toEqual([ + `${DELEGATED_TOKEN}${runJvmToken(named, ROOT)}`, + ]); + expect((await gradleBootLaunch(named)).args).toEqual(first.args); + // Debug adds its flag after the token; the token stays and is not repeated. + const debug = jdwpLaunch(first)!; + expect(debug.args).toContain(DELEGATED_DEBUG); + expect(debug.args.filter((a) => a.startsWith(DELEGATED_TOKEN))).toHaveLength(1); + expect((await gradleBootLaunch(first)).args.filter((a) => a.startsWith(DELEGATED_TOKEN))).toHaveLength(1); + }); }); describe("delegation across independent builds", () => { diff --git a/src/features/run/gradleRun.ts b/src/features/run/gradleRun.ts index 190c130133..7192d5d645 100644 --- a/src/features/run/gradleRun.ts +++ b/src/features/run/gradleRun.ts @@ -20,8 +20,29 @@ export const DELEGATED_MAIN = "-Dopenidea.run.main="; export const DELEGATED_DEBUG = "-Dopenidea.run.debug=true"; /** Lets the init script start the debugged JVM's attach listener (the memory view needs it; not on Windows). */ export const DELEGATED_ATTACH_LISTENER = "-Dopenidea.run.attachListener=true"; +/** + * Names the application JVM for the thread dump, which finds it by this argument. A Gradle run forks + * it under the daemon, outside the run's process tree; the init scripts pass it on. + */ +export const DELEGATED_TOKEN = "-Dopenidea.run.token="; const TASK = "openideaRun"; +/** + * Stable per configuration of the project at `root`: a per-launch value would change the Gradle + * command line and miss its configuration cache on every launch. The project's share keeps two + * worktrees, or two projects with the same main class, apart. + */ +export function runJvmToken(config: Pick, root: string): string { + return `${config.id.replace(/[^A-Za-z0-9._-]/g, "_")}-${shortHash(root)}`; +} + +/** FNV-1a (32 bits) in base 36. */ +function shortHash(text: string): string { + let hash = 0x811c9dc5; + for (let i = 0; i < text.length; i++) hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193); + return (hash >>> 0).toString(36); +} + const isAbsolute = (p: string) => p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p); const absolute = (root: string, p: string) => (isAbsolute(p) ? p : p ? `${root}/${p}` : root); @@ -74,6 +95,7 @@ export function delegatedGradleConfig(config: RunConfig, module: string, ctx: De `-Dopenidea.run.args=${JSON.stringify(parsed.programArgs)}`, `-Dopenidea.run.jvmArgs=${JSON.stringify(parsed.vmArgs)}`, `-Dopenidea.run.workingDir=${config.cwd ? absolute(ctx.root, config.cwd) : dir}`, + `${DELEGATED_TOKEN}${runJvmToken(config, ctx.root)}`, ...(ctx.offline ? ["--offline"] : []), // Problems only warn: a build with incompatible plugins still runs, uncached. ...(ctx.configurationCache ? ["--configuration-cache", "--configuration-cache-problems=warn"] : []), @@ -138,7 +160,14 @@ export async function gradleTestLaunch(config: T): Promise< export async function gradleBootLaunch(config: T): Promise { if (!isTauri() || !isGradleCommand(config) || !config.args.some((a) => /(^|:)bootRun$/.test(a))) return config; try { - return withTestEvents(config, await writeScript("openidea-gradle-boot", BOOT_SCRIPT)); + const marked = withTestEvents(config, await writeScript("openidea-gradle-boot", BOOT_SCRIPT)); + // The forked bootRun JVM is outside the run's process tree; the init script hands the token on. + return marked.args.some((a) => a.startsWith(DELEGATED_TOKEN)) + ? marked + : { + ...marked, + args: [...marked.args, `${DELEGATED_TOKEN}${runJvmToken(config, useProject.getState().project?.root ?? "")}`], + }; } catch (e) { console.warn("Gradle BootRun init script not written", e); return config; diff --git a/src/features/run/index.ts b/src/features/run/index.ts index 82629bc686..42f4783437 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -83,6 +83,7 @@ import { runGutter } from "./runGutter"; import { markdownCommandGutter } from "./markdownCommands"; import { gradleDelegation } from "./gradleRun"; import { activateStackTrace, useStackTraces } from "./stackTrace"; +import { activateThreadDumps } from "./threadDump/actions"; import { clearRuntimeCache } from "./runtimes"; import { adoptTemporary, @@ -485,6 +486,7 @@ export function activate(): () => void { onWorkflowSettingsChange((w) => w.console, applyConsoleSettings), registerExternalTools(), activateStackTrace(), + activateThreadDumps(), listenForApplicationDeactivation(), installBuildTomcatSync(), trackRecentConfigurations(), diff --git a/src/features/run/stackTrace.test.ts b/src/features/run/stackTrace.test.ts index c5789aed7f..ec3d757e2e 100644 --- a/src/features/run/stackTrace.test.ts +++ b/src/features/run/stackTrace.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import { addStackTrace, countFrames, normalizeTrace, traceTitle, useStackTraces } from "./stackTrace"; import { useRun } from "./store"; +import jdk25Sync from "./threadDump/__fixtures__/jdk25-sync.txt?raw"; const JVM = `Exception in thread "main" java.lang.IllegalStateException: boom\r \tat com.acme.OrderController.list(OrderController.kt:22) \r @@ -36,8 +37,20 @@ describe("Analyze Stack Trace", () => { const s = useStackTraces.getState(); expect(useRun.getState().activeSession).toBe(id); const tab = s.tabs.find((t) => t.id === id)!; + if (tab.kind !== "trace") throw new Error("expected a trace tab"); expect(tab.title).toBe("IllegalStateException"); expect(tab.model.lines.map((l) => l.text)).toHaveLength(3); expect(tab.model.lines[1]!.text).toContain("OrderController.kt:22"); }); + + it("opens a pasted thread dump in the thread viewer", () => { + const id = addStackTrace(jdk25Sync)!; + const tab = useStackTraces.getState().tabs.find((t) => t.id === id)!; + expect(useRun.getState().activeSession).toBe(id); + if (tab.kind !== "threads") throw new Error("expected a thread dump tab"); + expect(tab.title).toBe("Thread dump"); + expect(tab.source).toBeNull(); + expect(tab.dump.deadlocks).toHaveLength(1); + expect(tab.dump.threads[tab.selected!]!.name).toBe("sync-1"); + }); }); diff --git a/src/features/run/stackTrace.tsx b/src/features/run/stackTrace.tsx index a12cb16750..a29ae67945 100644 --- a/src/features/run/stackTrace.tsx +++ b/src/features/run/stackTrace.tsx @@ -19,13 +19,19 @@ import { useRun } from "./store"; import styles from "./StackTrace.module.css"; import { tx } from "@/platform/i18n"; import { readClipboardPlainText } from "@/platform/clipboard"; +import { isThreadDump, parseThreadDump, type ThreadDump } from "./threadDump/parse"; +import { threadDumpTab, type ThreadDumpSource, type ThreadDumpTab } from "./threadDump/store"; -export interface StackTraceTab { +export interface TraceTab { + kind: "trace"; id: string; title: string; model: ConsoleModel; } +/** A tab of the Run tool window that is not a run session: a stack trace or a thread dump. */ +export type StackTraceTab = TraceTab | ThreadDumpTab; + interface StackTraceState { tabs: StackTraceTab[]; /** Text of the open "Analyze Stack Trace" dialog, or null when closed. */ @@ -67,16 +73,43 @@ export function countFrames(text: string): number { return text.split("\n").filter((l) => findOutputLinks(l).some((k) => k.kind === "file")).length; } -export function addStackTrace(raw: string): string | null { - const text = normalizeTrace(raw); - if (!text) return null; +function openTab(tab: StackTraceTab): string { + useStackTraces.setState((s) => ({ tabs: [...s.tabs, tab] })); + useRun.setState({ activeSession: tab.id }); + return tab.id; +} + +function addTrace(text: string, title: string): string { const model = new ConsoleModel(); model.append({ kind: "stdout", text }); model.flush(); - const id = `trace-${++seq}`; - useStackTraces.setState((s) => ({ tabs: [...s.tabs, { id, title: traceTitle(text), model }] })); - useRun.setState({ activeSession: id }); - return id; + return openTab({ kind: "trace", id: `trace-${++seq}`, title, model }); +} + +function addThreads(text: string, title: string, source: ThreadDumpSource | null, dump: ThreadDump): string { + return openTab(threadDumpTab(`trace-${++seq}`, title, text, source, dump)); +} + +/** Opens a pasted trace, or a pasted thread dump in the thread viewer. */ +export function addStackTrace(raw: string): string | null { + const text = normalizeTrace(raw); + if (!text) return null; + const dump = isThreadDump(text) ? parseThreadDump(text) : null; + return dump ? addThreads(text, tx("Thread dump"), null, dump) : addTrace(text, traceTitle(text)); +} + +/** Opens a dump in the thread viewer; text that holds no thread opens as a plain trace. */ +export function addThreadDump(raw: string, meta: { title: string; source: ThreadDumpSource | null }): string { + const text = normalizeTrace(raw); + const dump = parseThreadDump(text); + return dump ? addThreads(text, meta.title, meta.source, dump) : addTrace(text, meta.title); +} + +/** Replaces a thread dump tab, e.g. with its next dump or the user's selection. */ +export function updateThreadDump(id: string, update: (tab: ThreadDumpTab) => ThreadDumpTab) { + useStackTraces.setState((s) => ({ + tabs: s.tabs.map((t) => (t.id === id && t.kind === "threads" ? update(t) : t)), + })); } export function closeStackTrace(id: string) { @@ -149,7 +182,7 @@ function StackTraceDialog({ initial }: { initial: string }) { } /** A trace tab's console in the Run tool window. */ -export function StackTracePanel({ tab }: { tab: StackTraceTab }) { +export function StackTracePanel({ tab }: { tab: TraceTab }) { const root = useProject((s) => s.project?.root ?? "/"); return ( |]/g, "-")}.txt`, + filters: [{ name: tx("Text file"), extensions: ["txt"] }], + }); + if (!picked) return; + const path = ipcPath(picked); + try { + // The save dialog already confirmed replacing the file, and the backend only creates new ones. + const kind = await call(commands.fsEntryKind(path)).catch(() => null); + if (kind === "dir") throw new Error(tx`${path} is a directory`); + if (kind === "file") await call(commands.fsDelete(path)); + await call(commands.fsCreateFileBytes(path, toBase64(new TextEncoder().encode(tab.text)))); + } catch (e) { + notifications().notify({ + group: "run", + level: "error", + title: "Cannot save the thread dump", + body: e instanceof Error ? e.message : String(e), + }); + } +} + +function DeadlockBanner({ dump, onSelect }: { dump: ThreadDump; onSelect: (name: string) => void }) { + if (!dump.deadlocks.length) return null; + const link = ({ thread, waitsFor: lock, heldBy: owner }: DeadlockLink, key: number) => ( + + {key > 0 && " → "} + + + ); + return ( +
+ {dump.deadlocks.map((cycle, i) => ( +
+ + Deadlock: + + {/* The cycle closes on its first thread. */} + {[...cycle, ...cycle.slice(0, 1)].map(link)} +
+ ))} +
+ ); +} + +export function ThreadDumpPanel({ tab }: { tab: ThreadDumpTab }) { + const root = useProject((s) => s.project?.root ?? "/"); + const { dump, filter, hideJvm, selected, refresh } = tab; + const shown = useMemo(() => visibleThreads(dump, filter, hideJvm), [dump, filter, hideJvm]); + const counts = useMemo(() => stateCounts(dump.threads, shown), [dump, shown]); + const thread = selected === null ? undefined : dump.threads[selected]; + const model = useMemo(() => { + const m = new ConsoleModel(); + if (thread) m.append({ kind: "stdout", text: threadStackText(thread) }); + m.flush(); + return m; + }, [thread]); + const [refreshing, setRefreshing] = useState(false); + const set = (patch: Partial>) => + updateThreadDump(tab.id, (t) => ({ ...t, ...patch })); + const selectNamed = (name: string) => { + const i = dump.threads.findIndex((t) => t.name === name); + if (i >= 0) set({ selected: i }); + }; + const runRefresh = async () => { + if (!refresh) return; + setRefreshing(true); + try { + await refresh(); + } catch (e) { + notifications().notify({ + group: "run", + level: "error", + title: "Cannot take a new thread dump", + body: e instanceof Error ? e.message : String(e), + }); + } finally { + setRefreshing(false); + } + }; + + return ( +
+ +
+ +
+ {tab.source && ( + void runRefresh()} + /> + )} + void writeClipboardText(tab.text)} /> + {/* Like Save Heap Dump As…: local windows only. */} + {!isRemoteWindow() && void saveDump(tab)} />} +
+
+ + +
+ set({ filter: value })} + placeholder="Filter threads" + aria-label="Filter threads" + /> + set({ hideJvm: !hideJvm })} + /> +
+
+ {counts.map(([state, n]) => ( + {`${state} ${n}`} + ))} +
+ String(i)} + activeIndex={selected === null ? -1 : shown.indexOf(selected)} + onActiveChange={(i) => set({ selected: shown[i] ?? null })} + renderItem={(i) => { + const t = dump.threads[i]!; + return ( + <> + + + {t.name} + + {t.deadlocked && } + + ); + }} + /> +
+ + + {}} + cwd={root} + aria-label={thread ? tx`Stack of ${thread.name}` : tx("Thread stack")} + /> + +
+
+
+ ); +} diff --git a/src/features/run/threadDump/__fixtures__/jdk11-sync.txt b/src/features/run/threadDump/__fixtures__/jdk11-sync.txt new file mode 100644 index 0000000000..dd3bf3a01c --- /dev/null +++ b/src/features/run/threadDump/__fixtures__/jdk11-sync.txt @@ -0,0 +1,156 @@ +57166: +2026-11-23 22:06:05 +Full thread dump OpenJDK 64-Bit Server VM (11.0.29+7 mixed mode): + +Threads class SMR info: +_java_thread_list=0x00000076454903e0, length=12, elements={ +0x0000000104878000, 0x000000764503b000, 0x0000007645438000, 0x0000007645439000, +0x000000764543a000, 0x000000764543b000, 0x000000764546c000, 0x000000764546d000, +0x000000764546f000, 0x0000007645130000, 0x0000007645131000, 0x0000007645132000 +} + +"main" #1 prio=5 os_prio=31 cpu=31.97ms elapsed=1.75s tid=0x0000000104878000 nid=0x1203 waiting on condition [0x000000016c086000] + java.lang.Thread.State: TIMED_WAITING (sleeping) + at java.lang.Thread.sleep(java.base@11.0.29/Native Method) + at Deadlock.sleep(Deadlock.java:7) + at Deadlock.main(Deadlock.java:31) + + Locked ownable synchronizers: + - None + +"Reference Handler" #2 daemon prio=10 os_prio=31 cpu=0.03ms elapsed=1.74s tid=0x000000764503b000 nid=0x5203 waiting on condition [0x000000016ceda000] + java.lang.Thread.State: RUNNABLE + at java.lang.ref.Reference.waitForReferencePendingList(java.base@11.0.29/Native Method) + at java.lang.ref.Reference.processPendingReferences(java.base@11.0.29/Reference.java:241) + at java.lang.ref.Reference$ReferenceHandler.run(java.base@11.0.29/Reference.java:213) + + Locked ownable synchronizers: + - None + +"Finalizer" #3 daemon prio=8 os_prio=31 cpu=0.08ms elapsed=1.74s tid=0x0000007645438000 nid=0x5003 in Object.wait() [0x000000016d0e6000] + java.lang.Thread.State: WAITING (on object monitor) + at java.lang.Object.wait(java.base@11.0.29/Native Method) + - waiting on <0x0000007018709008> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.ref.ReferenceQueue.remove(java.base@11.0.29/ReferenceQueue.java:155) + - waiting to re-lock in wait() <0x0000007018709008> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.ref.ReferenceQueue.remove(java.base@11.0.29/ReferenceQueue.java:176) + at java.lang.ref.Finalizer$FinalizerThread.run(java.base@11.0.29/Finalizer.java:170) + + Locked ownable synchronizers: + - None + +"Signal Dispatcher" #4 daemon prio=9 os_prio=31 cpu=0.12ms elapsed=1.74s tid=0x0000007645439000 nid=0x5503 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Service Thread" #5 daemon prio=9 os_prio=31 cpu=0.01ms elapsed=1.74s tid=0x000000764543a000 nid=0x7d03 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"C2 CompilerThread0" #6 daemon prio=9 os_prio=31 cpu=3.37ms elapsed=1.74s tid=0x000000764543b000 nid=0x7b03 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + No compile task + + Locked ownable synchronizers: + - None + +"C1 CompilerThread0" #9 daemon prio=9 os_prio=31 cpu=5.76ms elapsed=1.74s tid=0x000000764546c000 nid=0x5803 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + No compile task + + Locked ownable synchronizers: + - None + +"Sweeper thread" #10 daemon prio=9 os_prio=31 cpu=0.01ms elapsed=1.74s tid=0x000000764546d000 nid=0x7703 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Common-Cleaner" #11 daemon prio=8 os_prio=31 cpu=0.04ms elapsed=1.73s tid=0x000000764546f000 nid=0x5a03 in Object.wait() [0x000000016e052000] + java.lang.Thread.State: TIMED_WAITING (on object monitor) + at java.lang.Object.wait(java.base@11.0.29/Native Method) + - waiting on <0x0000007018619758> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.ref.ReferenceQueue.remove(java.base@11.0.29/ReferenceQueue.java:155) + - waiting to re-lock in wait() <0x0000007018619758> (a java.lang.ref.ReferenceQueue$Lock) + at jdk.internal.ref.CleanerImpl.run(java.base@11.0.29/CleanerImpl.java:148) + at java.lang.Thread.run(java.base@11.0.29/Thread.java:829) + at jdk.internal.misc.InnocuousThread.run(java.base@11.0.29/InnocuousThread.java:161) + + Locked ownable synchronizers: + - None + +"sync-1" #12 prio=5 os_prio=31 cpu=1.96ms elapsed=1.72s tid=0x0000007645130000 nid=0x5b03 waiting for monitor entry [0x000000016e25e000] + java.lang.Thread.State: BLOCKED (on object monitor) + at Deadlock.lambda$syncPair$0(Deadlock.java:10) + - waiting to lock <0x000000701861e2a0> (a java.lang.Object) + - locked <0x000000701861e290> (a java.lang.Object) + at Deadlock$$Lambda$1/0x0000007300060c40.run(Unknown Source) + at java.lang.Thread.run(java.base@11.0.29/Thread.java:829) + + Locked ownable synchronizers: + - None + +"sync-2" #13 prio=5 os_prio=31 cpu=1.95ms elapsed=1.72s tid=0x0000007645131000 nid=0x5e03 waiting for monitor entry [0x000000016e46a000] + java.lang.Thread.State: BLOCKED (on object monitor) + at Deadlock.lambda$syncPair$1(Deadlock.java:11) + - waiting to lock <0x000000701861e290> (a java.lang.Object) + - locked <0x000000701861e2a0> (a java.lang.Object) + at Deadlock$$Lambda$2/0x0000007300061840.run(Unknown Source) + at java.lang.Thread.run(java.base@11.0.29/Thread.java:829) + + Locked ownable synchronizers: + - None + +"Attach Listener" #14 daemon prio=9 os_prio=31 cpu=0.32ms elapsed=0.11s tid=0x0000007645132000 nid=0x6003 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"VM Thread" os_prio=31 cpu=0.72ms elapsed=1.75s tid=0x0000007645111000 nid=0x5403 runnable + +"GC Thread#0" os_prio=31 cpu=0.16ms elapsed=1.75s tid=0x000000764502c000 nid=0x3103 runnable + +"G1 Main Marker" os_prio=31 cpu=0.06ms elapsed=1.75s tid=0x000000764502d000 nid=0x3f03 runnable + +"G1 Conc#0" os_prio=31 cpu=0.01ms elapsed=1.75s tid=0x000000764502d800 nid=0x3303 runnable + +"G1 Refine#0" os_prio=31 cpu=0.05ms elapsed=1.75s tid=0x000000764502e800 nid=0x3403 runnable + +"G1 Young RemSet Sampling" os_prio=31 cpu=0.18ms elapsed=1.75s tid=0x000000764502f000 nid=0x3503 runnable +"VM Periodic Task Thread" os_prio=31 cpu=0.79ms elapsed=1.73s tid=0x0000007645113000 nid=0x7503 waiting on condition + +JNI global refs: 6, weak refs: 0 + + +Found one Java-level deadlock: +============================= +"sync-1": + waiting to lock monitor 0x000000764541de80 (object 0x000000701861e2a0, a java.lang.Object), + which is held by "sync-2" +"sync-2": + waiting to lock monitor 0x000000764541df40 (object 0x000000701861e290, a java.lang.Object), + which is held by "sync-1" + +Java stack information for the threads listed above: +=================================================== +"sync-1": + at Deadlock.lambda$syncPair$0(Deadlock.java:10) + - waiting to lock <0x000000701861e2a0> (a java.lang.Object) + - locked <0x000000701861e290> (a java.lang.Object) + at Deadlock$$Lambda$1/0x0000007300060c40.run(Unknown Source) + at java.lang.Thread.run(java.base@11.0.29/Thread.java:829) +"sync-2": + at Deadlock.lambda$syncPair$1(Deadlock.java:11) + - waiting to lock <0x000000701861e290> (a java.lang.Object) + - locked <0x000000701861e2a0> (a java.lang.Object) + at Deadlock$$Lambda$2/0x0000007300061840.run(Unknown Source) + at java.lang.Thread.run(java.base@11.0.29/Thread.java:829) + +Found 1 deadlock. + diff --git a/src/features/run/threadDump/__fixtures__/jdk17-juc.txt b/src/features/run/threadDump/__fixtures__/jdk17-juc.txt new file mode 100644 index 0000000000..441c9d517a --- /dev/null +++ b/src/features/run/threadDump/__fixtures__/jdk17-juc.txt @@ -0,0 +1,191 @@ +60412: +2026-11-23 22:06:43 +Full thread dump OpenJDK 64-Bit Server VM (17.0.21+9 mixed mode, sharing): + +Threads class SMR info: +_java_thread_list=0x0000007a5f8afc40, length=14, elements={ +0x00000001033b4360, 0x0000007a5ec5c600, 0x0000007a5ec5cc00, 0x0000007a5ec5d800, +0x0000007a5ec5de00, 0x0000007a5ec5e400, 0x0000007a5ec5ea00, 0x0000007a5ec5f000, +0x0000007a5ec5f600, 0x0000007a5e914000, 0x0000007a5e914600, 0x0000007a5e915200, +0x0000007a5e915800, 0x0000007a5e915e00 +} + +"main" #1 prio=5 os_prio=31 cpu=15.70ms elapsed=1.68s tid=0x00000001033b4360 nid=0xe03 waiting on condition [0x000000016d596000] + java.lang.Thread.State: TIMED_WAITING (sleeping) + at java.lang.Thread.sleep(java.base@17.0.21/Native Method) + at Deadlock.sleep(Deadlock.java:7) + at Deadlock.main(Deadlock.java:31) + + Locked ownable synchronizers: + - None + +"Reference Handler" #2 daemon prio=10 os_prio=31 cpu=0.04ms elapsed=1.67s tid=0x0000007a5ec5c600 nid=0x5703 waiting on condition [0x000000016e3ea000] + java.lang.Thread.State: RUNNABLE + at java.lang.ref.Reference.waitForReferencePendingList(java.base@17.0.21/Native Method) + at java.lang.ref.Reference.processPendingReferences(java.base@17.0.21/Reference.java:253) + at java.lang.ref.Reference$ReferenceHandler.run(java.base@17.0.21/Reference.java:215) + + Locked ownable synchronizers: + - None + +"Finalizer" #3 daemon prio=8 os_prio=31 cpu=0.09ms elapsed=1.67s tid=0x0000007a5ec5cc00 nid=0x5803 in Object.wait() [0x000000016e5f6000] + java.lang.Thread.State: WAITING (on object monitor) + at java.lang.Object.wait(java.base@17.0.21/Native Method) + - waiting on <0x0000007018402f40> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.ref.ReferenceQueue.remove(java.base@17.0.21/ReferenceQueue.java:155) + - locked <0x0000007018402f40> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.ref.ReferenceQueue.remove(java.base@17.0.21/ReferenceQueue.java:176) + at java.lang.ref.Finalizer$FinalizerThread.run(java.base@17.0.21/Finalizer.java:172) + + Locked ownable synchronizers: + - None + +"Signal Dispatcher" #4 daemon prio=9 os_prio=31 cpu=0.14ms elapsed=1.67s tid=0x0000007a5ec5d800 nid=0x6103 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Service Thread" #5 daemon prio=9 os_prio=31 cpu=0.02ms elapsed=1.67s tid=0x0000007a5ec5de00 nid=0x6303 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Monitor Deflation Thread" #6 daemon prio=9 os_prio=31 cpu=0.14ms elapsed=1.67s tid=0x0000007a5ec5e400 nid=0x6503 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"C2 CompilerThread0" #7 daemon prio=9 os_prio=31 cpu=1.09ms elapsed=1.67s tid=0x0000007a5ec5ea00 nid=0x6703 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + No compile task + + Locked ownable synchronizers: + - None + +"C1 CompilerThread0" #10 daemon prio=9 os_prio=31 cpu=1.04ms elapsed=1.67s tid=0x0000007a5ec5f000 nid=0x6803 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + No compile task + + Locked ownable synchronizers: + - None + +"Sweeper thread" #11 daemon prio=9 os_prio=31 cpu=0.01ms elapsed=1.67s tid=0x0000007a5ec5f600 nid=0x7003 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Notification Thread" #12 daemon prio=9 os_prio=31 cpu=0.02ms elapsed=1.67s tid=0x0000007a5e914000 nid=0x6e03 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Common-Cleaner" #13 daemon prio=8 os_prio=31 cpu=0.04ms elapsed=1.67s tid=0x0000007a5e914600 nid=0x6b03 in Object.wait() [0x000000016f97a000] + java.lang.Thread.State: TIMED_WAITING (on object monitor) + at java.lang.Object.wait(java.base@17.0.21/Native Method) + - waiting on <0x00000070184192e0> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.ref.ReferenceQueue.remove(java.base@17.0.21/ReferenceQueue.java:155) + - locked <0x00000070184192e0> (a java.lang.ref.ReferenceQueue$Lock) + at jdk.internal.ref.CleanerImpl.run(java.base@17.0.21/CleanerImpl.java:140) + at java.lang.Thread.run(java.base@17.0.21/Thread.java:840) + at jdk.internal.misc.InnocuousThread.run(java.base@17.0.21/InnocuousThread.java:162) + + Locked ownable synchronizers: + - None + +"juc-1" #14 prio=5 os_prio=31 cpu=0.32ms elapsed=1.67s tid=0x0000007a5e915200 nid=0x8003 waiting on condition [0x000000016fb86000] + java.lang.Thread.State: WAITING (parking) + at jdk.internal.misc.Unsafe.park(java.base@17.0.21/Native Method) + - parking to wait for <0x000000701841c728> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) + at java.util.concurrent.locks.LockSupport.park(java.base@17.0.21/LockSupport.java:211) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@17.0.21/AbstractQueuedSynchronizer.java:715) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@17.0.21/AbstractQueuedSynchronizer.java:938) + at java.util.concurrent.locks.ReentrantLock$Sync.lock(java.base@17.0.21/ReentrantLock.java:153) + at java.util.concurrent.locks.ReentrantLock.lock(java.base@17.0.21/ReentrantLock.java:322) + at Deadlock.lambda$jucPair$2(Deadlock.java:15) + at Deadlock$$Lambda$1/0x0000008001000a08.run(Unknown Source) + at java.lang.Thread.run(java.base@17.0.21/Thread.java:840) + + Locked ownable synchronizers: + - <0x000000701841c6f8> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) + +"juc-2" #15 prio=5 os_prio=31 cpu=0.17ms elapsed=1.67s tid=0x0000007a5e915800 nid=0x8203 waiting on condition [0x000000016fd92000] + java.lang.Thread.State: WAITING (parking) + at jdk.internal.misc.Unsafe.park(java.base@17.0.21/Native Method) + - parking to wait for <0x000000701841c6f8> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) + at java.util.concurrent.locks.LockSupport.park(java.base@17.0.21/LockSupport.java:211) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@17.0.21/AbstractQueuedSynchronizer.java:715) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@17.0.21/AbstractQueuedSynchronizer.java:938) + at java.util.concurrent.locks.ReentrantLock$Sync.lock(java.base@17.0.21/ReentrantLock.java:153) + at java.util.concurrent.locks.ReentrantLock.lock(java.base@17.0.21/ReentrantLock.java:322) + at Deadlock.lambda$jucPair$3(Deadlock.java:16) + at Deadlock$$Lambda$2/0x0000008001000c28.run(Unknown Source) + at java.lang.Thread.run(java.base@17.0.21/Thread.java:840) + + Locked ownable synchronizers: + - <0x000000701841c728> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) + +"Attach Listener" #16 daemon prio=9 os_prio=31 cpu=0.36ms elapsed=0.10s tid=0x0000007a5e915e00 nid=0x8403 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"VM Periodic Task Thread" os_prio=31 cpu=0.95ms elapsed=1.67s tid=0x00000001033d2c20 nid=0x6a03 waiting on condition + +"VM Thread" os_prio=31 cpu=0.46ms elapsed=1.68s tid=0x00000001033c7da0 nid=0x4d03 runnable + +"G1 Service" os_prio=31 cpu=0.19ms elapsed=1.68s tid=0x00000001033c2e70 nid=0x5203 runnable + +"G1 Refine#0" os_prio=31 cpu=0.02ms elapsed=1.68s tid=0x00000001033c2500 nid=0x5403 runnable + +"G1 Conc#0" os_prio=31 cpu=0.01ms elapsed=1.68s tid=0x00000001033c0110 nid=0x3503 runnable + +"G1 Main Marker" os_prio=31 cpu=0.02ms elapsed=1.68s tid=0x00000001033bf7a0 nid=0x3303 runnable + +"GC Thread#0" os_prio=31 cpu=0.02ms elapsed=1.68s tid=0x00000001033be940 nid=0x3203 runnable + +JNI global refs: 6, weak refs: 0 + + +Found one Java-level deadlock: +============================= +"juc-1": + waiting for ownable synchronizer 0x000000701841c728, (a java.util.concurrent.locks.ReentrantLock$NonfairSync), + which is held by "juc-2" + +"juc-2": + waiting for ownable synchronizer 0x000000701841c6f8, (a java.util.concurrent.locks.ReentrantLock$NonfairSync), + which is held by "juc-1" + +Java stack information for the threads listed above: +=================================================== +"juc-1": + at jdk.internal.misc.Unsafe.park(java.base@17.0.21/Native Method) + - parking to wait for <0x000000701841c728> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) + at java.util.concurrent.locks.LockSupport.park(java.base@17.0.21/LockSupport.java:211) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@17.0.21/AbstractQueuedSynchronizer.java:715) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@17.0.21/AbstractQueuedSynchronizer.java:938) + at java.util.concurrent.locks.ReentrantLock$Sync.lock(java.base@17.0.21/ReentrantLock.java:153) + at java.util.concurrent.locks.ReentrantLock.lock(java.base@17.0.21/ReentrantLock.java:322) + at Deadlock.lambda$jucPair$2(Deadlock.java:15) + at Deadlock$$Lambda$1/0x0000008001000a08.run(Unknown Source) + at java.lang.Thread.run(java.base@17.0.21/Thread.java:840) +"juc-2": + at jdk.internal.misc.Unsafe.park(java.base@17.0.21/Native Method) + - parking to wait for <0x000000701841c6f8> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) + at java.util.concurrent.locks.LockSupport.park(java.base@17.0.21/LockSupport.java:211) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@17.0.21/AbstractQueuedSynchronizer.java:715) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@17.0.21/AbstractQueuedSynchronizer.java:938) + at java.util.concurrent.locks.ReentrantLock$Sync.lock(java.base@17.0.21/ReentrantLock.java:153) + at java.util.concurrent.locks.ReentrantLock.lock(java.base@17.0.21/ReentrantLock.java:322) + at Deadlock.lambda$jucPair$3(Deadlock.java:16) + at Deadlock$$Lambda$2/0x0000008001000c28.run(Unknown Source) + at java.lang.Thread.run(java.base@17.0.21/Thread.java:840) + +Found 1 deadlock. + diff --git a/src/features/run/threadDump/__fixtures__/jdk21-mixed.txt b/src/features/run/threadDump/__fixtures__/jdk21-mixed.txt new file mode 100644 index 0000000000..6a185d807d --- /dev/null +++ b/src/features/run/threadDump/__fixtures__/jdk21-mixed.txt @@ -0,0 +1,187 @@ +62886: +2026-11-23 22:07:19 +Full thread dump OpenJDK 64-Bit Server VM (21.0.4+7-LTS mixed mode): + +Threads class SMR info: +_java_thread_list=0x000000763f0d1660, length=13, elements={ +0x00000001022d3010, 0x00000001022e9810, 0x000000763f0ac000, 0x000000763f0ac700, +0x000000763f0ace00, 0x000000763f0ad500, 0x000000763e86e000, 0x000000763e86e800, +0x000000763f0adc00, 0x000000763f0ae300, 0x000000763f0aea00, 0x000000763f0af100, +0x000000763f0af800 +} + +"main" #1 [4867] prio=5 os_prio=31 cpu=37.38ms elapsed=1.71s tid=0x00000001022d3010 nid=4867 waiting on condition [0x000000016de4a000] + java.lang.Thread.State: TIMED_WAITING (sleeping) + at java.lang.Thread.sleep0(java.base@21.0.4/Native Method) + at java.lang.Thread.sleep(java.base@21.0.4/Thread.java:509) + at Deadlock.sleep(Deadlock.java:7) + at Deadlock.main(Deadlock.java:31) + + Locked ownable synchronizers: + - None + +"Reference Handler" #9 [29443] daemon prio=10 os_prio=31 cpu=0.22ms elapsed=1.69s tid=0x00000001022e9810 nid=29443 waiting on condition [0x000000016efc2000] + java.lang.Thread.State: RUNNABLE + at java.lang.ref.Reference.waitForReferencePendingList(java.base@21.0.4/Native Method) + at java.lang.ref.Reference.processPendingReferences(java.base@21.0.4/Reference.java:246) + at java.lang.ref.Reference$ReferenceHandler.run(java.base@21.0.4/Reference.java:208) + + Locked ownable synchronizers: + - None + +"Finalizer" #10 [29187] daemon prio=8 os_prio=31 cpu=0.08ms elapsed=1.69s tid=0x000000763f0ac000 nid=29187 in Object.wait() [0x000000016f1ce000] + java.lang.Thread.State: WAITING (on object monitor) + at java.lang.Object.wait0(java.base@21.0.4/Native Method) + - waiting on <0x0000007018409ac0> (a java.lang.ref.NativeReferenceQueue$Lock) + at java.lang.Object.wait(java.base@21.0.4/Object.java:366) + at java.lang.Object.wait(java.base@21.0.4/Object.java:339) + at java.lang.ref.NativeReferenceQueue.await(java.base@21.0.4/NativeReferenceQueue.java:48) + at java.lang.ref.ReferenceQueue.remove0(java.base@21.0.4/ReferenceQueue.java:158) + at java.lang.ref.NativeReferenceQueue.remove(java.base@21.0.4/NativeReferenceQueue.java:89) + - locked <0x0000007018409ac0> (a java.lang.ref.NativeReferenceQueue$Lock) + at java.lang.ref.Finalizer$FinalizerThread.run(java.base@21.0.4/Finalizer.java:173) + + Locked ownable synchronizers: + - None + +"Signal Dispatcher" #11 [28931] daemon prio=9 os_prio=31 cpu=0.11ms elapsed=1.69s tid=0x000000763f0ac700 nid=28931 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Service Thread" #12 [24835] daemon prio=9 os_prio=31 cpu=0.01ms elapsed=1.69s tid=0x000000763f0ace00 nid=24835 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Monitor Deflation Thread" #13 [28419] daemon prio=9 os_prio=31 cpu=0.10ms elapsed=1.69s tid=0x000000763f0ad500 nid=28419 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"C2 CompilerThread0" #14 [25091] daemon prio=9 os_prio=31 cpu=3.16ms elapsed=1.69s tid=0x000000763e86e000 nid=25091 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + No compile task + + Locked ownable synchronizers: + - None + +"C1 CompilerThread0" #17 [25603] daemon prio=9 os_prio=31 cpu=6.21ms elapsed=1.69s tid=0x000000763e86e800 nid=25603 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + No compile task + + Locked ownable synchronizers: + - None + +"Notification Thread" #18 [27907] daemon prio=9 os_prio=31 cpu=0.03ms elapsed=1.68s tid=0x000000763f0adc00 nid=27907 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Common-Cleaner" #19 [26371] daemon prio=8 os_prio=31 cpu=0.27ms elapsed=1.68s tid=0x000000763f0ae300 nid=26371 waiting on condition [0x0000000170022000] + java.lang.Thread.State: TIMED_WAITING (parking) + at jdk.internal.misc.Unsafe.park(java.base@21.0.4/Native Method) + - parking to wait for <0x00000070185b3ba8> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject) + at java.util.concurrent.locks.LockSupport.parkNanos(java.base@21.0.4/LockSupport.java:269) + at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(java.base@21.0.4/AbstractQueuedSynchronizer.java:1847) + at java.lang.ref.ReferenceQueue.await(java.base@21.0.4/ReferenceQueue.java:71) + at java.lang.ref.ReferenceQueue.remove0(java.base@21.0.4/ReferenceQueue.java:143) + at java.lang.ref.ReferenceQueue.remove(java.base@21.0.4/ReferenceQueue.java:218) + at jdk.internal.ref.CleanerImpl.run(java.base@21.0.4/CleanerImpl.java:140) + at java.lang.Thread.runWith(java.base@21.0.4/Thread.java:1596) + at java.lang.Thread.run(java.base@21.0.4/Thread.java:1583) + at jdk.internal.misc.InnocuousThread.run(java.base@21.0.4/InnocuousThread.java:186) + + Locked ownable synchronizers: + - None + +"mix-1" #20 [27395] prio=5 os_prio=31 cpu=0.16ms elapsed=1.67s tid=0x000000763f0aea00 nid=27395 waiting on condition [0x000000017022e000] + java.lang.Thread.State: WAITING (parking) + at jdk.internal.misc.Unsafe.park(java.base@21.0.4/Native Method) + - parking to wait for <0x00000070185b8470> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) + at java.util.concurrent.locks.LockSupport.park(java.base@21.0.4/LockSupport.java:221) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@21.0.4/AbstractQueuedSynchronizer.java:754) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@21.0.4/AbstractQueuedSynchronizer.java:990) + at java.util.concurrent.locks.ReentrantLock$Sync.lock(java.base@21.0.4/ReentrantLock.java:153) + at java.util.concurrent.locks.ReentrantLock.lock(java.base@21.0.4/ReentrantLock.java:322) + at Deadlock.lambda$mixedPair$4(Deadlock.java:20) + - locked <0x00000070185b8378> (a java.lang.Object) + at Deadlock$$Lambda/0x0000008000000a00.run(Unknown Source) + at java.lang.Thread.runWith(java.base@21.0.4/Thread.java:1596) + at java.lang.Thread.run(java.base@21.0.4/Thread.java:1583) + + Locked ownable synchronizers: + - None + +"mix-2" #21 [26883] prio=5 os_prio=31 cpu=0.20ms elapsed=1.67s tid=0x000000763f0af100 nid=26883 waiting for monitor entry [0x000000017043a000] + java.lang.Thread.State: BLOCKED (on object monitor) + at Deadlock.lambda$mixedPair$5(Deadlock.java:21) + - waiting to lock <0x00000070185b8378> (a java.lang.Object) + at Deadlock$$Lambda/0x0000008000000c18.run(Unknown Source) + at java.lang.Thread.runWith(java.base@21.0.4/Thread.java:1596) + at java.lang.Thread.run(java.base@21.0.4/Thread.java:1583) + + Locked ownable synchronizers: + - <0x00000070185b8470> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) + +"Attach Listener" #22 [32771] daemon prio=9 os_prio=31 cpu=0.33ms elapsed=0.10s tid=0x000000763f0af800 nid=32771 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"VM Thread" os_prio=31 cpu=0.53ms elapsed=1.70s tid=0x000000763f06e400 nid=19715 runnable + +"VM Periodic Task Thread" os_prio=31 cpu=0.56ms elapsed=1.71s tid=0x00000001022e3a10 nid=20739 waiting on condition + +"G1 Service" os_prio=31 cpu=0.05ms elapsed=1.71s tid=0x000000763f06c800 nid=21507 runnable + +"G1 Refine#0" os_prio=31 cpu=0.01ms elapsed=1.71s tid=0x000000763f06c000 nid=13315 runnable + +"G1 Conc#0" os_prio=31 cpu=0.01ms elapsed=1.71s tid=0x00000001022dc870 nid=13059 runnable + +"G1 Main Marker" os_prio=31 cpu=0.02ms elapsed=1.71s tid=0x00000001022dbe70 nid=14595 runnable + +"GC Thread#0" os_prio=31 cpu=0.01ms elapsed=1.71s tid=0x00000001022db0f0 nid=12547 runnable + +JNI global refs: 6, weak refs: 0 + + +Found one Java-level deadlock: +============================= +"mix-1": + waiting for ownable synchronizer 0x00000070185b8470, (a java.util.concurrent.locks.ReentrantLock$NonfairSync), + which is held by "mix-2" + +"mix-2": + waiting to lock monitor 0x000000763f091500 (object 0x00000070185b8378, a java.lang.Object), + which is held by "mix-1" + +Java stack information for the threads listed above: +=================================================== +"mix-1": + at jdk.internal.misc.Unsafe.park(java.base@21.0.4/Native Method) + - parking to wait for <0x00000070185b8470> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) + at java.util.concurrent.locks.LockSupport.park(java.base@21.0.4/LockSupport.java:221) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@21.0.4/AbstractQueuedSynchronizer.java:754) + at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquire(java.base@21.0.4/AbstractQueuedSynchronizer.java:990) + at java.util.concurrent.locks.ReentrantLock$Sync.lock(java.base@21.0.4/ReentrantLock.java:153) + at java.util.concurrent.locks.ReentrantLock.lock(java.base@21.0.4/ReentrantLock.java:322) + at Deadlock.lambda$mixedPair$4(Deadlock.java:20) + - locked <0x00000070185b8378> (a java.lang.Object) + at Deadlock$$Lambda/0x0000008000000a00.run(Unknown Source) + at java.lang.Thread.runWith(java.base@21.0.4/Thread.java:1596) + at java.lang.Thread.run(java.base@21.0.4/Thread.java:1583) +"mix-2": + at Deadlock.lambda$mixedPair$5(Deadlock.java:21) + - waiting to lock <0x00000070185b8378> (a java.lang.Object) + at Deadlock$$Lambda/0x0000008000000c18.run(Unknown Source) + at java.lang.Thread.runWith(java.base@21.0.4/Thread.java:1596) + at java.lang.Thread.run(java.base@21.0.4/Thread.java:1583) + +Found 1 deadlock. + diff --git a/src/features/run/threadDump/__fixtures__/jdk25-none.txt b/src/features/run/threadDump/__fixtures__/jdk25-none.txt new file mode 100644 index 0000000000..7fcccd2848 --- /dev/null +++ b/src/features/run/threadDump/__fixtures__/jdk25-none.txt @@ -0,0 +1,135 @@ +65756: +2026-11-23 22:08:00 +Full thread dump OpenJDK 64-Bit Server VM (25.0.3+9-LTS mixed mode, sharing): + +Threads class SMR info: +_java_thread_list=0x00000077b6dc0aa0, length=12, elements={ +0x00000001057f9680, 0x00000001058162e0, 0x0000000105816ae0, 0x00000077b6d2c000, +0x00000077b6d2c800, 0x00000077b6d2d000, 0x00000077b6c8e800, 0x00000077b6c8f200, +0x00000077b6d2d800, 0x00000077b6d2e000, 0x00000077b6d2e800, 0x00000077b6d2f000 +} + +"main" #3 [5123] prio=5 os_prio=31 cpu=15.18ms elapsed=1.70s tid=0x00000001057f9680 nid=5123 waiting on condition [0x000000016b0ee000] + java.lang.Thread.State: TIMED_WAITING (sleeping) + at java.lang.Thread.sleepNanos0(java.base@25.0.3/Native Method) + at java.lang.Thread.sleepNanos(java.base@25.0.3/Thread.java:509) + at java.lang.Thread.sleep(java.base@25.0.3/Thread.java:540) + at Deadlock.sleep(Deadlock.java:7) + at Deadlock.main(Deadlock.java:31) + + Locked ownable synchronizers: + - None + +"Reference Handler" #14 [30211] daemon prio=10 os_prio=31 cpu=0.07ms elapsed=1.69s tid=0x00000001058162e0 nid=30211 waiting on condition [0x000000016c2f2000] + java.lang.Thread.State: RUNNABLE + at java.lang.ref.Reference.waitForReferencePendingList(java.base@25.0.3/Native Method) + at java.lang.ref.Reference.processPendingReferences(java.base@25.0.3/Reference.java:246) + at java.lang.ref.Reference$ReferenceHandler.run(java.base@25.0.3/Reference.java:208) + + Locked ownable synchronizers: + - None + +"Finalizer" #15 [25603] daemon prio=8 os_prio=31 cpu=0.04ms elapsed=1.69s tid=0x0000000105816ae0 nid=25603 in Object.wait() [0x000000016c4fe000] + java.lang.Thread.State: WAITING (on object monitor) + at java.lang.Object.wait0(java.base@25.0.3/Native Method) + - waiting on <0x0000007018402358> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.Object.wait(java.base@25.0.3/Object.java:389) + at java.lang.Object.wait(java.base@25.0.3/Object.java:351) + at java.lang.ref.ReferenceQueue.remove0(java.base@25.0.3/ReferenceQueue.java:137) + at java.lang.ref.ReferenceQueue.remove(java.base@25.0.3/ReferenceQueue.java:215) + - locked <0x0000007018402358> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.ref.Finalizer$FinalizerThread.run(java.base@25.0.3/Finalizer.java:165) + + Locked ownable synchronizers: + - None + +"Signal Dispatcher" #16 [29955] daemon prio=9 os_prio=31 cpu=0.18ms elapsed=1.69s tid=0x00000077b6d2c000 nid=29955 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Service Thread" #17 [29443] daemon prio=9 os_prio=31 cpu=0.03ms elapsed=1.69s tid=0x00000077b6d2c800 nid=29443 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Monitor Deflation Thread" #18 [28931] daemon prio=9 os_prio=31 cpu=0.10ms elapsed=1.69s tid=0x00000077b6d2d000 nid=28931 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"C2 CompilerThread0" #19 [28675] daemon prio=9 os_prio=31 cpu=1.45ms elapsed=1.69s tid=0x00000077b6c8e800 nid=28675 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + No compile task + + Locked ownable synchronizers: + - None + +"C1 CompilerThread0" #22 [26371] daemon prio=9 os_prio=31 cpu=1.12ms elapsed=1.69s tid=0x00000077b6c8f200 nid=26371 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + No compile task + + Locked ownable synchronizers: + - None + +"Notification Thread" #23 [27907] daemon prio=9 os_prio=31 cpu=0.01ms elapsed=1.69s tid=0x00000077b6d2d800 nid=27907 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Common-Cleaner" #24 [26627] daemon prio=8 os_prio=31 cpu=0.04ms elapsed=1.68s tid=0x00000077b6d2e000 nid=26627 in Object.wait() [0x000000016d352000] + java.lang.Thread.State: TIMED_WAITING (on object monitor) + at java.lang.Object.wait0(java.base@25.0.3/Native Method) + - waiting on <0x0000007018412468> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.Object.wait(java.base@25.0.3/Object.java:389) + at java.lang.ref.ReferenceQueue.remove0(java.base@25.0.3/ReferenceQueue.java:123) + at java.lang.ref.ReferenceQueue.remove(java.base@25.0.3/ReferenceQueue.java:201) + - locked <0x0000007018412468> (a java.lang.ref.ReferenceQueue$Lock) + at jdk.internal.ref.CleanerImpl.run(java.base@25.0.3/CleanerImpl.java:146) + at java.lang.Thread.runWith(java.base@25.0.3/Thread.java:1487) + at java.lang.Thread.run(java.base@25.0.3/Thread.java:1474) + at jdk.internal.misc.InnocuousThread.run(java.base@25.0.3/InnocuousThread.java:148) + + Locked ownable synchronizers: + - None + +"idle" #25 [27139] prio=5 os_prio=31 cpu=0.05ms elapsed=1.68s tid=0x00000077b6d2e800 nid=27139 waiting on condition [0x000000016d55e000] + java.lang.Thread.State: TIMED_WAITING (sleeping) + at java.lang.Thread.sleepNanos0(java.base@25.0.3/Native Method) + at java.lang.Thread.sleepNanos(java.base@25.0.3/Thread.java:509) + at java.lang.Thread.sleep(java.base@25.0.3/Thread.java:540) + at Deadlock.sleep(Deadlock.java:7) + at Deadlock.lambda$main$0(Deadlock.java:29) + at Deadlock$$Lambda/0x000007f801040210.run(Unknown Source) + at java.lang.Thread.runWith(java.base@25.0.3/Thread.java:1487) + at java.lang.Thread.run(java.base@25.0.3/Thread.java:1474) + + Locked ownable synchronizers: + - None + +"Attach Listener" #26 [32771] daemon prio=9 os_prio=31 cpu=0.48ms elapsed=0.11s tid=0x00000077b6d2f000 nid=32771 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"VM Thread" os_prio=31 cpu=0.83ms elapsed=1.69s tid=0x00000077b7072000 nid=19459 runnable + +"VM Periodic Task Thread" os_prio=31 cpu=0.15ms elapsed=1.69s tid=0x00000077b7071400 nid=17159 waiting on condition + +"G1 Service" os_prio=31 cpu=0.04ms elapsed=1.70s tid=0x000000010580a790 nid=21507 runnable + +"G1 Refine#0" os_prio=31 cpu=0.01ms elapsed=1.70s tid=0x0000000105809cd0 nid=16643 runnable + +"G1 Conc#0" os_prio=31 cpu=0.02ms elapsed=1.70s tid=0x0000000105806f10 nid=13827 runnable + +"G1 Main Marker" os_prio=31 cpu=0.02ms elapsed=1.70s tid=0x0000000105806450 nid=14339 runnable + +"GC Thread#0" os_prio=31 cpu=0.01ms elapsed=1.70s tid=0x00000001058053a0 nid=12803 runnable + +JNI global refs: 6, weak refs: 0 + diff --git a/src/features/run/threadDump/__fixtures__/jdk25-sync.txt b/src/features/run/threadDump/__fixtures__/jdk25-sync.txt new file mode 100644 index 0000000000..58f2debbba --- /dev/null +++ b/src/features/run/threadDump/__fixtures__/jdk25-sync.txt @@ -0,0 +1,176 @@ +65274: +2026-11-23 22:07:54 +Full thread dump OpenJDK 64-Bit Server VM (25.0.3+9-LTS mixed mode, sharing): + +Threads class SMR info: +_java_thread_list=0x00000077ded023e0, length=13, elements={ +0x0000000102ec7000, 0x00000077dd008000, 0x00000077dd008800, 0x00000077dd009000, +0x00000077dd009800, 0x00000077dd00a000, 0x00000077df0a1e00, 0x00000077df0a2800, +0x00000077dd00a800, 0x00000077dd00b000, 0x00000077dd00b800, 0x00000077ded14000, +0x00000077ded14800 +} + +"main" #3 [4611] prio=5 os_prio=31 cpu=19.48ms elapsed=1.71s tid=0x0000000102ec7000 nid=4611 waiting on condition [0x000000016dafe000] + java.lang.Thread.State: TIMED_WAITING (sleeping) + at java.lang.Thread.sleepNanos0(java.base@25.0.3/Native Method) + at java.lang.Thread.sleepNanos(java.base@25.0.3/Thread.java:509) + at java.lang.Thread.sleep(java.base@25.0.3/Thread.java:540) + at Deadlock.sleep(Deadlock.java:7) + at Deadlock.main(Deadlock.java:31) + + Locked ownable synchronizers: + - None + +"Reference Handler" #14 [29699] daemon prio=10 os_prio=31 cpu=0.11ms elapsed=1.69s tid=0x00000077dd008000 nid=29699 waiting on condition [0x000000016ec76000] + java.lang.Thread.State: RUNNABLE + at java.lang.ref.Reference.waitForReferencePendingList(java.base@25.0.3/Native Method) + at java.lang.ref.Reference.processPendingReferences(java.base@25.0.3/Reference.java:246) + at java.lang.ref.Reference$ReferenceHandler.run(java.base@25.0.3/Reference.java:208) + + Locked ownable synchronizers: + - None + +"Finalizer" #15 [25091] daemon prio=8 os_prio=31 cpu=0.04ms elapsed=1.69s tid=0x00000077dd008800 nid=25091 in Object.wait() [0x000000016ee82000] + java.lang.Thread.State: WAITING (on object monitor) + at java.lang.Object.wait0(java.base@25.0.3/Native Method) + - waiting on <0x0000007018402358> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.Object.wait(java.base@25.0.3/Object.java:389) + at java.lang.Object.wait(java.base@25.0.3/Object.java:351) + at java.lang.ref.ReferenceQueue.remove0(java.base@25.0.3/ReferenceQueue.java:137) + at java.lang.ref.ReferenceQueue.remove(java.base@25.0.3/ReferenceQueue.java:215) + - locked <0x0000007018402358> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.ref.Finalizer$FinalizerThread.run(java.base@25.0.3/Finalizer.java:165) + + Locked ownable synchronizers: + - None + +"Signal Dispatcher" #16 [29443] daemon prio=9 os_prio=31 cpu=0.15ms elapsed=1.69s tid=0x00000077dd009000 nid=29443 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Service Thread" #17 [29187] daemon prio=9 os_prio=31 cpu=0.05ms elapsed=1.69s tid=0x00000077dd009800 nid=29187 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Monitor Deflation Thread" #18 [25859] daemon prio=9 os_prio=31 cpu=0.14ms elapsed=1.69s tid=0x00000077dd00a000 nid=25859 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"C2 CompilerThread0" #19 [26371] daemon prio=9 os_prio=31 cpu=2.69ms elapsed=1.69s tid=0x00000077df0a1e00 nid=26371 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + No compile task + + Locked ownable synchronizers: + - None + +"C1 CompilerThread0" #22 [28675] daemon prio=9 os_prio=31 cpu=1.52ms elapsed=1.69s tid=0x00000077df0a2800 nid=28675 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + No compile task + + Locked ownable synchronizers: + - None + +"Notification Thread" #23 [27139] daemon prio=9 os_prio=31 cpu=0.02ms elapsed=1.69s tid=0x00000077dd00a800 nid=27139 runnable [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"Common-Cleaner" #24 [28419] daemon prio=8 os_prio=31 cpu=0.04ms elapsed=1.68s tid=0x00000077dd00b000 nid=28419 in Object.wait() [0x000000016fcd6000] + java.lang.Thread.State: TIMED_WAITING (on object monitor) + at java.lang.Object.wait0(java.base@25.0.3/Native Method) + - waiting on <0x0000007018412468> (a java.lang.ref.ReferenceQueue$Lock) + at java.lang.Object.wait(java.base@25.0.3/Object.java:389) + at java.lang.ref.ReferenceQueue.remove0(java.base@25.0.3/ReferenceQueue.java:123) + at java.lang.ref.ReferenceQueue.remove(java.base@25.0.3/ReferenceQueue.java:201) + - locked <0x0000007018412468> (a java.lang.ref.ReferenceQueue$Lock) + at jdk.internal.ref.CleanerImpl.run(java.base@25.0.3/CleanerImpl.java:146) + at java.lang.Thread.runWith(java.base@25.0.3/Thread.java:1487) + at java.lang.Thread.run(java.base@25.0.3/Thread.java:1474) + at jdk.internal.misc.InnocuousThread.run(java.base@25.0.3/InnocuousThread.java:148) + + Locked ownable synchronizers: + - None + +"sync-1" #25 [28163] prio=5 os_prio=31 cpu=0.21ms elapsed=1.68s tid=0x00000077dd00b800 nid=28163 waiting for monitor entry [0x000000016fee2000] + java.lang.Thread.State: BLOCKED (on object monitor) + at Deadlock.lambda$syncPair$0(Deadlock.java:10) + - waiting to lock <0x0000007018419290> (a java.lang.Object) + - locked <0x0000007018419280> (a java.lang.Object) + at Deadlock$$Lambda/0x00000f8001040210.run(Unknown Source) + at java.lang.Thread.runWith(java.base@25.0.3/Thread.java:1487) + at java.lang.Thread.run(java.base@25.0.3/Thread.java:1474) + + Locked ownable synchronizers: + - None + +"sync-2" #26 [32771] prio=5 os_prio=31 cpu=0.13ms elapsed=1.68s tid=0x00000077ded14000 nid=32771 waiting for monitor entry [0x00000001700ee000] + java.lang.Thread.State: BLOCKED (on object monitor) + at Deadlock.lambda$syncPair$1(Deadlock.java:11) + - waiting to lock <0x0000007018419280> (a java.lang.Object) + - locked <0x0000007018419290> (a java.lang.Object) + at Deadlock$$Lambda/0x00000f8001040438.run(Unknown Source) + at java.lang.Thread.runWith(java.base@25.0.3/Thread.java:1487) + at java.lang.Thread.run(java.base@25.0.3/Thread.java:1474) + + Locked ownable synchronizers: + - None + +"Attach Listener" #27 [33027] daemon prio=9 os_prio=31 cpu=0.48ms elapsed=0.11s tid=0x00000077ded14800 nid=33027 waiting on condition [0x0000000000000000] + java.lang.Thread.State: RUNNABLE + + Locked ownable synchronizers: + - None + +"VM Thread" os_prio=31 cpu=0.61ms elapsed=1.69s tid=0x00000077decae400 nid=19971 runnable + +"VM Periodic Task Thread" os_prio=31 cpu=0.23ms elapsed=1.70s tid=0x00000077decad800 nid=17935 waiting on condition + +"G1 Service" os_prio=31 cpu=0.03ms elapsed=1.71s tid=0x00000077dec58f00 nid=21251 runnable + +"G1 Refine#0" os_prio=31 cpu=0.03ms elapsed=1.71s tid=0x00000077dec58a00 nid=21507 runnable + +"G1 Conc#0" os_prio=31 cpu=0.01ms elapsed=1.71s tid=0x00000077dec58500 nid=13571 runnable + +"G1 Main Marker" os_prio=31 cpu=0.01ms elapsed=1.71s tid=0x00000077dec58000 nid=14083 runnable + +"GC Thread#0" os_prio=31 cpu=0.01ms elapsed=1.71s tid=0x0000000102ecf460 nid=14339 runnable + +JNI global refs: 6, weak refs: 0 + + +Found one Java-level deadlock: +============================= +"sync-1": + waiting to lock monitor 0x00000077decc2680 (object 0x0000007018419290, a java.lang.Object), + which is held by "sync-2" + +"sync-2": + waiting to lock monitor 0x00000077decc25a0 (object 0x0000007018419280, a java.lang.Object), + which is held by "sync-1" + +Java stack information for the threads listed above: +=================================================== +"sync-1": + at Deadlock.lambda$syncPair$0(Deadlock.java:10) + - waiting to lock <0x0000007018419290> (a java.lang.Object) + - locked <0x0000007018419280> (a java.lang.Object) + at Deadlock$$Lambda/0x00000f8001040210.run(Unknown Source) + at java.lang.Thread.runWith(java.base@25.0.3/Thread.java:1487) + at java.lang.Thread.run(java.base@25.0.3/Thread.java:1474) +"sync-2": + at Deadlock.lambda$syncPair$1(Deadlock.java:11) + - waiting to lock <0x0000007018419280> (a java.lang.Object) + - locked <0x0000007018419290> (a java.lang.Object) + at Deadlock$$Lambda/0x00000f8001040438.run(Unknown Source) + at java.lang.Thread.runWith(java.base@25.0.3/Thread.java:1487) + at java.lang.Thread.run(java.base@25.0.3/Thread.java:1474) + +Found 1 deadlock. + diff --git a/src/features/run/threadDump/__tests__/ThreadDumpPanel.test.tsx b/src/features/run/threadDump/__tests__/ThreadDumpPanel.test.tsx new file mode 100644 index 0000000000..ce61595bb1 --- /dev/null +++ b/src/features/run/threadDump/__tests__/ThreadDumpPanel.test.tsx @@ -0,0 +1,231 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; +import { commands } from "@/platform/ipc"; +import { usePlatform } from "@/platform/platformInfo"; +import { addThreadDump, updateThreadDump, useStackTraces } from "../../stackTrace"; +import { ThreadDumpPanel } from "../ThreadDumpPanel"; +import { withDumpText, type ThreadDumpTab } from "../store"; +import jdk25Sync from "../__fixtures__/jdk25-sync.txt?raw"; +import jdk25None from "../__fixtures__/jdk25-none.txt?raw"; + +const clipboard = vi.hoisted(() => ({ writeClipboardText: vi.fn(async (_text: string) => {}) })); +vi.mock("@/platform/clipboard", async (orig) => ({ ...(await orig()), ...clipboard })); +const notify = vi.hoisted(() => vi.fn()); +vi.mock("@/workbench/contributions", async (orig) => ({ + ...(await orig()), + notifications: () => ({ notify }), +})); +const dialog = vi.hoisted(() => ({ save: vi.fn(async (): Promise => null) })); +vi.mock("@/platform/dialog", () => dialog); +const remote = vi.hoisted(() => ({ isRemoteWindow: vi.fn(() => false) })); +vi.mock("@/platform/remote", async (orig) => ({ ...(await orig()), ...remote })); + +vi.mock("@tanstack/react-virtual", () => ({ + useVirtualizer: ({ count }: { count: number }) => ({ + getTotalSize: () => count * 20, + getVirtualItems: () => + Array.from({ length: count }, (_, index) => ({ index, start: index * 20, key: index, size: 20 })), + scrollToIndex: () => {}, + measureElement: () => {}, + measure: () => {}, + }), +})); + +function threadsTab(id: string): ThreadDumpTab { + const tab = useStackTraces.getState().tabs.find((t) => t.id === id); + if (tab?.kind !== "threads") throw new Error("expected a thread dump tab"); + return tab; +} + +function Harness({ id }: { id: string }) { + const tab = useStackTraces((s) => s.tabs.find((t) => t.id === id)); + return tab?.kind === "threads" ? : null; +} + +function open(text: string, source: ThreadDumpTab["source"] = null) { + const id = addThreadDump(text, { title: "Threads: App", source }); + render(); + return id; +} + +const rows = () => within(screen.getByRole("listbox", { name: "Threads" })).getAllByRole("option"); +const rowNames = () => rows().map((r) => r.textContent); +const selectedName = () => rows().find((r) => r.getAttribute("aria-selected") === "true")?.textContent; + +beforeEach(() => { + usePlatform.setState({ os: "macos" }); + useStackTraces.setState({ tabs: [] }); + clipboard.writeClipboardText.mockClear(); + notify.mockClear(); + remote.isRemoteWindow.mockReturnValue(false); +}); + +describe("ThreadDumpPanel", () => { + it("names the deadlock cycle and selects a thread from it", () => { + open(jdk25Sync); + const banner = screen.getByRole("alert"); + expect(banner.textContent).toContain("sync-1 → sync-2 → sync-1"); + expect(selectedName()).toBe("sync-1"); + fireEvent.click(within(banner).getAllByRole("button", { name: "sync-2" })[0]!); + expect(selectedName()).toBe("sync-2"); + expect(screen.getByRole("log").textContent).toContain("Deadlock.java:11"); + }); + + it("marks deadlocked threads in the list", () => { + open(jdk25Sync); + const marked = rows().filter((r) => within(r).queryByLabelText("Deadlocked")); + expect(marked.map((r) => r.textContent)).toEqual(["sync-1", "sync-2"]); + }); + + it("filters the list by thread name", () => { + open(jdk25Sync); + fireEvent.change(screen.getByRole("textbox", { name: "Filter threads" }), { target: { value: "SYNC" } }); + expect(rowNames()).toEqual(["sync-1", "sync-2"]); + }); + + it("hides JVM threads until the toggle shows them", () => { + open(jdk25Sync); + expect(rowNames()).toEqual(["main", "sync-1", "sync-2"]); + const toggle = screen.getByRole("button", { name: "Hide JVM threads" }); + expect(toggle.getAttribute("aria-pressed")).toBe("true"); + fireEvent.click(toggle); + expect(rowNames()).toContain("Reference Handler"); + expect(rowNames()).toContain("VM Thread"); + }); + + it("counts the listed threads per state", () => { + open(jdk25Sync); + const counts = screen.getByTestId("thread-state-counts").textContent; + expect(counts).toContain("BLOCKED 2"); + expect(counts).toContain("TIMED_WAITING 1"); + }); + + it("selects main when no thread is deadlocked, and shows no banner", () => { + open(jdk25None); + expect(screen.queryByRole("alert")).toBeNull(); + expect(selectedName()).toBe("main"); + }); + + it("copies the whole dump", () => { + open(jdk25Sync); + fireEvent.click(screen.getByRole("button", { name: "Copy" })); + const copied = clipboard.writeClipboardText.mock.calls[0]?.[0] ?? ""; + expect(copied).toContain("Full thread dump"); + expect(copied).toContain("Found one Java-level deadlock:"); + }); + + it("offers Refresh only for a dump taken from a run or debug session", () => { + open(jdk25Sync); + expect(screen.queryByRole("button", { name: "Refresh" })).toBeNull(); + }); + + it("refreshes through the tab's refresh function", () => { + const id = open(jdk25Sync, { run: 7, token: "cfg" }); + const refresh = vi.fn(async () => {}); + act(() => updateThreadDump(id, (t) => ({ ...t, refresh }))); + fireEvent.click(screen.getByRole("button", { name: "Refresh" })); + expect(refresh).toHaveBeenCalledOnce(); + }); + + it("reports a refresh that fails", async () => { + const id = open(jdk25Sync, { session: 3 }); + act(() => updateThreadDump(id, (t) => ({ ...t, refresh: async () => Promise.reject(new Error("gone")) }))); + fireEvent.click(screen.getByRole("button", { name: "Refresh" })); + await waitFor(() => + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ title: "Cannot take a new thread dump", body: "gone" }), + ), + ); + }); +}); + +describe("Save As…", () => { + const ok = { status: "ok", data: null } as const; + let onDisk: Record; + let written: { path: string; text: string }[]; + + beforeEach(() => { + onDisk = {}; + written = []; + dialog.save.mockResolvedValue("/out/dump.txt"); + vi.spyOn(commands, "fsEntryKind").mockImplementation(async (path) => + onDisk[path] + ? { status: "ok", data: onDisk[path] } + : { status: "error", error: { kind: "NotFound", message: path } as never }, + ); + vi.spyOn(commands, "fsDelete").mockImplementation(async (path) => { + delete onDisk[path]; + return ok; + }); + vi.spyOn(commands, "fsCreateFileBytes").mockImplementation(async (path, data) => { + if (onDisk[path]) return { status: "error", error: { kind: "AlreadyExists", message: path } as never }; + written.push({ path, text: new TextDecoder().decode(Uint8Array.from(atob(data), (c) => c.charCodeAt(0))) }); + return ok; + }); + }); + afterEach(() => vi.restoreAllMocks()); + + const save = () => fireEvent.click(screen.getByRole("button", { name: "Save As…" })); + + it("writes the whole dump to a .txt file named after the tab", async () => { + const id = open(jdk25Sync); + save(); + await waitFor(() => expect(written).toHaveLength(1)); + expect(dialog.save).toHaveBeenCalledWith(expect.objectContaining({ defaultPath: "Threads- App.txt" })); + expect(written[0]).toEqual({ path: "/out/dump.txt", text: threadsTab(id).text }); + expect(commands.fsDelete).not.toHaveBeenCalled(); + }); + + it("replaces an existing file", async () => { + onDisk["/out/dump.txt"] = "file"; + open(jdk25Sync); + save(); + await waitFor(() => expect(written).toHaveLength(1)); + expect(commands.fsDelete).toHaveBeenCalledWith("/out/dump.txt"); + }); + + it("refuses to replace a directory", async () => { + onDisk["/out/dump.txt"] = "dir"; + open(jdk25Sync); + save(); + await waitFor(() => + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ title: "Cannot save the thread dump", body: "/out/dump.txt is a directory" }), + ), + ); + expect(commands.fsDelete).not.toHaveBeenCalled(); + expect(written).toEqual([]); + }); + + it("reports a failed write", async () => { + vi.mocked(commands.fsCreateFileBytes).mockResolvedValue({ + status: "error", + error: { kind: "PermissionDenied", message: "read-only volume" } as never, + }); + open(jdk25Sync); + save(); + await waitFor(() => + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "Cannot save the thread dump" })), + ); + }); + + it("is not offered in a remote window", () => { + remote.isRemoteWindow.mockReturnValue(true); + open(jdk25Sync); + expect(screen.queryByRole("button", { name: "Save As…" })).toBeNull(); + }); +}); + +describe("withDumpText", () => { + it("keeps the selected thread, filter and toggle across a new dump", () => { + const id = addThreadDump(jdk25Sync, { title: "Threads: App", source: null }); + const before = { ...threadsTab(id), filter: "s", hideJvm: false }; + const main = before.dump.threads.findIndex((t) => t.name === "main"); + const after = withDumpText({ ...before, selected: main }, jdk25None); + expect(after.text).toBe(jdk25None); + expect(after.filter).toBe("s"); + expect(after.hideJvm).toBe(false); + expect(after.dump.threads[after.selected!]!.name).toBe("main"); + expect(after.dump.deadlocks).toEqual([]); + }); +}); diff --git a/src/features/run/threadDump/__tests__/actions.test.ts b/src/features/run/threadDump/__tests__/actions.test.ts new file mode 100644 index 0000000000..f86a6933bf --- /dev/null +++ b/src/features/run/threadDump/__tests__/actions.test.ts @@ -0,0 +1,204 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { executeAction, getAction, isActionEnabled } from "@/platform/actions"; +import { commands, type JvmThreadsResult, type JvmThreadsUnavailable, type RunConfig } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import type { ProjectInfo } from "@/platform/ipc"; +import { runJvmToken } from "../../gradleRun"; +import { useStackTraces } from "../../stackTrace"; +import { useRun, type RunSession, type SessionStatus } from "../../store"; +import { activateThreadDumps } from "../actions"; +import type { ThreadDumpTab } from "../store"; +import { threadsUnavailableText } from "../unavailableText"; +import jdk25Sync from "../__fixtures__/jdk25-sync.txt?raw"; +import jdk25None from "../__fixtures__/jdk25-none.txt?raw"; + +const notify = vi.hoisted(() => vi.fn()); +const showToolWindow = vi.hoisted(() => vi.fn()); +vi.mock("@/workbench/contributions", async (orig) => { + const actual = await orig(); + return { + ...actual, + notifications: () => ({ notify }), + toolWindowService: () => ({ show: showToolWindow }), + }; +}); + +function config(kind: string, patch: Partial = {}): RunConfig { + return { + id: `${kind}:App`, + name: "App", + kind, + command: "", + args: [], + cwd: null, + env: {}, + detected: false, + isTest: false, + debugAdapter: null, + ...patch, + }; +} + +function start(c: RunConfig, status: SessionStatus = "running") { + const session: RunSession = { + id: "s1", + config: c, + runId: 7, + status, + exitCode: null, + startedAt: 0, + endedAt: null, + stdinClosed: false, + }; + useRun.setState({ sessions: [session], activeSession: session.id }); +} + +const ready = (text: string): JvmThreadsResult => ({ + status: "ready", + dump: { text, pid: 42, javaVersion: "25", takenWhileSuspended: false, elapsedMs: 80 }, +}); +const unavailable = (reason: JvmThreadsUnavailable): JvmThreadsResult => ({ status: "unavailable", reason }); +const answer = (result: JvmThreadsResult) => ({ status: "ok" as const, data: result }); + +const enabled = () => isActionEnabled(getAction("run.dumpThreads")!); + +function onlyTab(): ThreadDumpTab { + const [tab, ...rest] = useStackTraces.getState().tabs; + if (tab?.kind !== "threads" || rest.length) throw new Error("expected one thread dump tab"); + return tab; +} + +const ROOT = "/w/demo"; + +let dispose: () => void; +beforeEach(() => { + useProject.setState({ project: { root: ROOT } as ProjectInfo, settings: null }); + dispose = activateThreadDumps(); + useStackTraces.setState({ tabs: [], dialog: null }); + notify.mockClear(); + showToolWindow.mockClear(); +}); +afterEach(() => { + dispose(); + vi.restoreAllMocks(); + useRun.setState({ sessions: [], activeSession: null }); +}); + +describe("run.dumpThreads", () => { + it("is disabled for a Node run and enabled for a running Java application", () => { + start(config("npm", { command: "npm", args: ["run", "dev"] })); + expect(enabled()).toBe(false); + start(config("application")); + expect(enabled()).toBe(true); + start(config("application"), "finished"); + expect(enabled()).toBe(false); + }); + + it("counts the Maven and Gradle tasks that run the application", () => { + start(config("gradle", { args: [":app:bootRun"] })); + expect(enabled()).toBe(true); + start(config("maven", { args: ["spring-boot:run"] })); + expect(enabled()).toBe(true); + start(config("gradle", { args: ["build"] })); + expect(enabled()).toBe(false); + start(config("maven", { args: ["test"], isTest: true })); + expect(enabled()).toBe(false); + }); + + it("opens the dump in a threads tab titled by the configuration", async () => { + const app = config("application"); + start(app); + vi.spyOn(commands, "runJvmThreadDump").mockResolvedValue(answer(ready(jdk25Sync))); + await executeAction("run.dumpThreads"); + const tab = onlyTab(); + expect(tab.title).toBe("Threads: App"); + expect(tab.source).toEqual({ run: 7, token: runJvmToken(app, ROOT) }); + expect(tab.dump.deadlocks).toHaveLength(1); + expect(showToolWindow).toHaveBeenCalledWith("run", true); + expect(notify).not.toHaveBeenCalled(); + }); + + it("passes the token of a Gradle-delegated session", async () => { + start(config("application", { id: "app:Main Class" })); + const dump = vi.spyOn(commands, "runJvmThreadDump").mockResolvedValue(answer(ready(jdk25Sync))); + await executeAction("run.dumpThreads"); + expect(dump).toHaveBeenCalledWith(7, runJvmToken({ id: "app:Main Class" }, ROOT)); + expect(dump.mock.calls[0]![1]).toMatch(/^app_Main_Class-/); + }); + + it("notifies why no dump was taken", async () => { + start(config("application")); + vi.spyOn(commands, "runJvmThreadDump").mockResolvedValue(answer(unavailable({ kind: "remoteRun" }))); + await executeAction("run.dumpThreads"); + expect(useStackTraces.getState().tabs).toEqual([]); + expect(showToolWindow).not.toHaveBeenCalled(); + expect(notify).toHaveBeenCalledWith( + expect.objectContaining({ body: "Thread dumps are not available for remote runs yet." }), + ); + }); + + it("reads a failed request as a failed dump", async () => { + start(config("application")); + vi.spyOn(commands, "runJvmThreadDump").mockResolvedValue({ + status: "error", + error: { kind: "internal", message: "boom", data: null }, + } as never); + await executeAction("run.dumpThreads"); + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ body: "Could not dump the threads: boom" })); + }); + + it("refreshes into the same tab and throws why it could not, leaving the notification to the tab", async () => { + start(config("application")); + const dump = vi.spyOn(commands, "runJvmThreadDump").mockResolvedValue(answer(ready(jdk25Sync))); + await executeAction("run.dumpThreads"); + const id = onlyTab().id; + + dump.mockResolvedValue(answer(ready(jdk25None))); + await onlyTab().refresh!(); + expect(onlyTab().id).toBe(id); + expect(onlyTab().dump.deadlocks).toEqual([]); + + dump.mockResolvedValue(answer(unavailable({ kind: "jvm", reason: { kind: "programExited" } }))); + await expect(onlyTab().refresh!()).rejects.toThrow("The program has exited."); + expect(notify).not.toHaveBeenCalled(); + }); +}); + +describe("run.openThreadDump", () => { + it("opens a debug session's dump and takes the next one with the same request", async () => { + const take = vi.fn(async () => ready(jdk25Sync)); + await executeAction("run.openThreadDump", { title: "Threads: Debug App", source: { session: 3 }, take }); + const tab = onlyTab(); + expect(tab.title).toBe("Threads: Debug App"); + expect(tab.source).toEqual({ session: 3 }); + take.mockResolvedValue(ready(jdk25None)); + await tab.refresh!(); + expect(take).toHaveBeenCalledTimes(2); + expect(onlyTab().dump.deadlocks).toEqual([]); + }); +}); + +describe("threadsUnavailableText", () => { + it.each<[JvmThreadsUnavailable, string]>([ + [ + { kind: "jvm", reason: { kind: "listenerNotRunning" } }, + "Resume the program to dump its threads: the JVM has no attach listener while it is stopped.", + ], + [ + { kind: "jvm", reason: { kind: "unsafeWhileSuspended", javaMajor: 11 } }, + "Resume the program to dump its threads: Java 11 cannot answer while the debugger stops it.", + ], + [ + { kind: "listenerDidNotStart" }, + "The JVM did not accept the request. It may run with -XX:+DisableAttachMechanism.", + ], + [{ kind: "jvm", reason: { kind: "noJvmProcess" } }, "No Java process was found for this run."], + [{ kind: "jvm", reason: { kind: "programExited" } }, "The program has exited."], + [{ kind: "jvm", reason: { kind: "unsupportedPlatform" } }, "Thread dumps are not available on this platform yet."], + [{ kind: "remoteRun" }, "Thread dumps are not available for remote runs yet."], + [{ kind: "jvm", reason: { kind: "timedOut" } }, "The JVM did not answer in time."], + [{ kind: "failed", message: "socket closed" }, "Could not dump the threads: socket closed"], + ])("explains %j", (reason, text) => { + expect(threadsUnavailableText(reason)).toBe(text); + }); +}); diff --git a/src/features/run/threadDump/__tests__/parse.test.ts b/src/features/run/threadDump/__tests__/parse.test.ts new file mode 100644 index 0000000000..c835ee86d9 --- /dev/null +++ b/src/features/run/threadDump/__tests__/parse.test.ts @@ -0,0 +1,201 @@ +import { describe, expect, it } from "vitest"; +import { isThreadDump, parseThreadDump } from "../parse"; +import jdk11Sync from "../__fixtures__/jdk11-sync.txt?raw"; +import jdk17Juc from "../__fixtures__/jdk17-juc.txt?raw"; +import jdk21Mixed from "../__fixtures__/jdk21-mixed.txt?raw"; +import jdk25None from "../__fixtures__/jdk25-none.txt?raw"; +import jdk25Sync from "../__fixtures__/jdk25-sync.txt?raw"; + +function parsed(text: string) { + const dump = parseThreadDump(text); + if (!dump) throw new Error("expected a thread dump"); + return dump; +} + +function thread(text: string, name: string) { + const found = parsed(text).threads.find((t) => t.name === name); + if (!found) throw new Error(`no thread ${name}`); + return found; +} + +describe("parseThreadDump", () => { + it("reads the header after jcmd's pid line", () => { + expect(parsed(jdk25Sync).header).toBe( + "Full thread dump OpenJDK 64-Bit Server VM (25.0.3+9-LTS mixed mode, sharing):", + ); + }); + + it("links a two-monitor deadlock and flags both threads", () => { + const dump = parsed(jdk25Sync); + expect(dump.deadlocks).toHaveLength(1); + expect(dump.deadlocks[0]).toMatchObject([ + { thread: "sync-1", heldBy: "sync-2" }, + { thread: "sync-2", heldBy: "sync-1" }, + ]); + const firstFrames = { + "sync-1": "at Deadlock.lambda$syncPair$0(Deadlock.java:10)", + "sync-2": "at Deadlock.lambda$syncPair$1(Deadlock.java:11)", + }; + for (const [name, frame] of Object.entries(firstFrames)) { + const t = thread(jdk25Sync, name); + expect(t.deadlocked).toBe(true); + expect(t.state).toBe("BLOCKED"); + expect(t.stateDetail).toBe("on object monitor"); + expect(t.frames[0]).toBe(frame); + } + expect(thread(jdk25Sync, "main").deadlocked).toBe(false); + }); + + it("does not duplicate threads from the deadlock stack section", () => { + const names = parsed(jdk25Sync).threads.map((t) => t.name); + expect(names.filter((n) => n === "sync-1")).toHaveLength(1); + expect(thread(jdk25Sync, "sync-1").frames).toHaveLength(6); + }); + + it("records held and awaited locks in one format", () => { + const sync1 = thread(jdk25Sync, "sync-1"); + expect(sync1.waitsOn).toBe("java.lang.Object <0x0000007018419290>"); + expect(sync1.holds).toEqual(["java.lang.Object <0x0000007018419280>"]); + expect(parsed(jdk25Sync).deadlocks[0]?.[0]?.waitsFor).toBe(sync1.waitsOn); + }); + + it("names the ownable synchronizer a thread waits for", () => { + const [first, second] = parsed(jdk21Mixed).deadlocks[0] ?? []; + expect(first?.thread).toBe("mix-1"); + expect(first?.waitsFor).toContain("ReentrantLock$NonfairSync"); + expect(second?.waitsFor).toContain("java.lang.Object"); + expect(thread(jdk21Mixed, "mix-1").waitsOn).toContain("ReentrantLock$NonfairSync"); + expect(thread(jdk21Mixed, "mix-1").state).toBe("WAITING"); + expect(thread(jdk21Mixed, "mix-1").stateDetail).toBe("parking"); + expect(thread(jdk21Mixed, "mix-2").holds).toEqual([first?.waitsFor]); + }); + + it("links a pure java.util.concurrent deadlock", () => { + const dump = parsed(jdk17Juc); + expect(dump.deadlocks).toHaveLength(1); + expect(dump.deadlocks[0]).toHaveLength(2); + expect(dump.deadlocks[0]?.every((l) => l.waitsFor.includes("ReentrantLock$NonfairSync"))).toBe(true); + }); + + it("parses JDK 11 headers that have no [nid] column", () => { + const main = thread(jdk11Sync, "main"); + expect(main.number).toBe(1); + expect(main.state).toBe("TIMED_WAITING"); + expect(main.stateDetail).toBe("sleeping"); + expect(thread(jdk11Sync, "Reference Handler").daemon).toBe(true); + expect(parsed(jdk11Sync).deadlocks[0]).toHaveLength(2); + }); + + it("reports no deadlocks and classifies JVM threads", () => { + const dump = parsed(jdk25None); + expect(dump.deadlocks).toEqual([]); + expect(dump.threads.some((t) => t.deadlocked)).toBe(false); + expect(thread(jdk25None, "main").internal).toBe(false); + expect(thread(jdk25None, "main").daemon).toBe(false); + expect(thread(jdk25None, "Reference Handler").internal).toBe(true); + expect(thread(jdk25None, "VM Thread").internal).toBe(true); + expect(thread(jdk25None, "VM Thread").number).toBeNull(); + expect(thread(jdk25None, "VM Thread").state).toBe("UNKNOWN"); + expect(thread(jdk25None, "C2 CompilerThread0").internal).toBe(true); + }); + + it("keeps lock lines in frames and leaves the ownable section out of them", () => { + const finalizer = thread(jdk25None, "Finalizer"); + expect(finalizer.frames.some((f) => f.startsWith("- waiting on <0x"))).toBe(true); + expect(finalizer.frames.every((f) => /^(at |- )/.test(f))).toBe(true); + expect(finalizer.frames.some((f) => f === "- None")).toBe(false); + }); + + it("accepts CRLF line endings and leading prompt lines", () => { + const pasted = `$ jstack 65274\r\nAttaching to process...\r\n${jdk25Sync.replace(/\n/g, "\r\n")}`; + const dump = parsed(pasted); + expect(dump.threads.length).toBe(parsed(jdk25Sync).threads.length); + expect(dump.deadlocks[0]).toHaveLength(2); + expect(thread(pasted, "sync-1").frames[0]).toBe("at Deadlock.lambda$syncPair$0(Deadlock.java:10)"); + }); + + it("separates several deadlock cycles", () => { + const cycle = (a: string, b: string) => `Found one Java-level deadlock: +============================= +"${a}": + waiting to lock monitor 0x01 (object 0x0a, a java.lang.Object), + which is held by "${b}" +"${b}": + waiting to lock monitor 0x02 (object 0x0b, a java.lang.Object), + which is held by "${a}" + +Java stack information for the threads listed above: +=================================================== +"${a}": + at X.run(X.java:1) +"${b}": + at X.run(X.java:2) + +`; + const text = `Full thread dump VM (x): + +"a" #1 prio=5 os_prio=0 tid=0x1 nid=0x1 waiting for monitor entry + java.lang.Thread.State: BLOCKED (on object monitor) + at X.run(X.java:1) + +"c" #2 prio=5 os_prio=0 tid=0x2 nid=0x2 waiting for monitor entry + java.lang.Thread.State: BLOCKED (on object monitor) + at X.run(X.java:1) + +${cycle("a", "b")}${cycle("c", "d")}Found 2 deadlocks. +`; + const dump = parsed(text); + expect(dump.deadlocks.map((links) => links.map((l) => l.thread))).toEqual([ + ["a", "b"], + ["c", "d"], + ]); + expect(dump.threads.map((t) => t.name)).toEqual(["a", "c"]); + expect(dump.threads.every((t) => t.deadlocked)).toBe(true); + }); + + it("returns null when there is no thread header", () => { + expect(parseThreadDump("")).toBeNull(); + expect( + parseThreadDump('Exception in thread "main" java.lang.IllegalStateException\n\tat A.b(A.java:1)'), + ).toBeNull(); + }); + + it("parses 5,000 threads quickly", () => { + const blocks = Array.from( + { length: 5000 }, + (_, i) => + `"worker-${i}" #${i + 20} [${i}] prio=5 os_prio=31 cpu=1.00ms elapsed=2.00s tid=0x${i.toString(16)} nid=${i} waiting on condition [0x0] + java.lang.Thread.State: WAITING (parking) + at jdk.internal.misc.Unsafe.park(java.base@21.0.4/Native Method) + - parking to wait for <0x${i.toString(16)}> (a java.util.concurrent.locks.ReentrantLock$NonfairSync) + at java.util.concurrent.locks.LockSupport.park(java.base@21.0.4/LockSupport.java:221) + at app.Worker.run(Worker.java:${i}) + + Locked ownable synchronizers: + - None +`, + ); + const text = `Full thread dump VM (21):\n\n${blocks.join("\n")}`; + const start = performance.now(); + const dump = parsed(text); + const elapsed = performance.now() - start; + expect(dump.threads).toHaveLength(5000); + expect(elapsed).toBeLessThan(200); + }); +}); + +describe("isThreadDump", () => { + it("accepts real dumps, with or without the jcmd pid line", () => { + for (const text of [jdk11Sync, jdk17Juc, jdk21Mixed, jdk25None, jdk25Sync]) { + expect(isThreadDump(text)).toBe(true); + } + expect(isThreadDump(jdk25Sync.replace(/^\d+:\n/, ""))).toBe(true); + }); + + it("rejects an ordinary exception trace", () => { + expect(isThreadDump('Exception in thread "main" java.lang.RuntimeException: boom\n\tat A.main(A.java:3)\n')).toBe( + false, + ); + expect(isThreadDump("")).toBe(false); + }); +}); diff --git a/src/features/run/threadDump/actions.ts b/src/features/run/threadDump/actions.ts new file mode 100644 index 0000000000..ef77ef3b55 --- /dev/null +++ b/src/features/run/threadDump/actions.ts @@ -0,0 +1,130 @@ +/** Dump Threads of a Run session, and the tab a debug session's dump opens in (`run.openThreadDump`). */ +import { registerActions } from "@/platform/actions"; +import { setContext } from "@/platform/context"; +import { tx } from "@/platform/i18n"; +import { call, commands, type JvmThreadsResult, type RunConfig } from "@/platform/ipc"; +import { isJvmApplication } from "@/platform/javaLaunch"; +import { useProject } from "@/platform/project"; +import { notifications, toolWindowService } from "@/workbench/contributions"; +import { runJvmToken } from "../gradleRun"; +import { addThreadDump, normalizeTrace, updateThreadDump } from "../stackTrace"; +import { useRun, type RunSession } from "../store"; +import { withDumpText, type ThreadDumpSource } from "./store"; +import { threadsUnavailableText } from "./unavailableText"; + +/** `run.openThreadDump`'s argument: the debugger takes its dumps through its own command. */ +interface ThreadDumpRequest { + title: string; + source: ThreadDumpSource; + take: () => Promise; +} + +const KEYWORDS = ["thread dump", "jstack", "deadlock", "threads"]; + +const GRADLE_BOOT_RUN = /(^|:)bootRun$/; +/** Forked under Maven's JVM (`spring-boot:run`) or run inside it (`exec:java`, `jetty:run`). */ +const MAVEN_RUN_GOAL = /^[\w.-]+(:[\w.-]+)*:(run|run-war|run-exploded|java)$/; + +/** + * Gradle's `run` task is left out: its JVM forks under the daemon without the run token, so the + * dump could not find it. + */ +export function isJvmRun(config: RunConfig): boolean { + if (config.isTest) return false; + if (isJvmApplication(config) || config.kind === "jar-application") return true; + if (config.kind === "gradle") return config.args.some((a) => GRADLE_BOOT_RUN.test(a)); + if (config.kind === "maven") return config.args.some((a) => MAVEN_RUN_GOAL.test(a)); + return false; +} + +/** The running JVM session `id` names, else the active tab's. */ +function jvmRunSession(id?: string): RunSession | undefined { + const { sessions, activeSession } = useRun.getState(); + const s = sessions.find((x) => x.id === (id ?? activeSession)); + return s && s.status === "running" && s.runId !== null && isJvmRun(s.config) ? s : undefined; +} + +/** The dump's text; a dump that was not taken throws why. */ +async function dumpText(take: () => Promise): Promise { + const result = await take().catch((e: unknown): JvmThreadsResult => ({ + status: "unavailable", + reason: { kind: "failed", message: e instanceof Error ? e.message : String(e) }, + })); + if (result.status === "ready") return result.dump.text; + throw new Error(threadsUnavailableText(result.reason)); +} + +async function openThreadDump({ title, source, take }: ThreadDumpRequest) { + let text: string; + try { + text = await dumpText(take); + } catch (e) { + notifications().notify({ group: "run", level: "warning", title: "Dump Threads", body: (e as Error).message }); + return; + } + const id = addThreadDump(text, { title, source }); + // A debug session's dump opens here too, so the Run tool window may be hidden. + toolWindowService().show("run", true); + // The tab reports a failed refresh itself, so this one only throws. + const refresh = async () => { + const next = normalizeTrace(await dumpText(take)); + updateThreadDump(id, (t) => withDumpText(t, next)); + }; + updateThreadDump(id, (t) => ({ ...t, refresh })); +} + +function isDumpRequest(arg: unknown): arg is ThreadDumpRequest { + return ( + typeof arg === "object" && + arg !== null && + "title" in arg && + typeof arg.title === "string" && + "source" in arg && + "take" in arg && + typeof arg.take === "function" + ); +} + +function dumpRunThreads(sessionId?: string): Promise | undefined { + const s = jvmRunSession(sessionId); + if (!s || s.runId === null) return; + const run = s.runId; + const config = s.config; + // Every run passes its token: only Gradle runs carry it, the others are found in the run's process tree. + const token = runJvmToken(config, useProject.getState().project?.root ?? ""); + const name = config.name; + return openThreadDump({ + title: tx`Threads: ${name}`, + source: { run, token }, + take: () => call(commands.runJvmThreadDump(run, token)), + }); +} + +export function activateThreadDumps(): () => void { + const sync = () => setContext("run.jvmRunning", !!jvmRunSession()); + sync(); + const disposers = [ + useRun.subscribe(sync), + registerActions([ + { + id: "run.dumpThreads", + title: "Dump Threads", + category: "Run", + icon: "thread-dump", + keywords: KEYWORDS, + when: "run.jvmRunning", + indicatesRunning: true, + // `arg`: a Run tab's session id; the active tab's otherwise. + run: ({ arg }) => dumpRunThreads(typeof arg === "string" ? arg : undefined), + }, + { + id: "run.openThreadDump", + title: "Open Thread Dump", + category: "Run", + hidden: true, + run: ({ arg }) => (isDumpRequest(arg) ? openThreadDump(arg) : undefined), + }, + ]), + ]; + return () => disposers.forEach((d) => d()); +} diff --git a/src/features/run/threadDump/parse.ts b/src/features/run/threadDump/parse.ts new file mode 100644 index 0000000000..99a6114bbc --- /dev/null +++ b/src/features/run/threadDump/parse.ts @@ -0,0 +1,200 @@ +// Parser for HotSpot `Thread.print` / jstack text. Tolerates a leading ":" line, prompt +// noise and CRLF, because users paste dumps from arbitrary terminals. + +export type ThreadState = "RUNNABLE" | "BLOCKED" | "WAITING" | "TIMED_WAITING" | "NEW" | "TERMINATED" | "UNKNOWN"; + +export interface DumpThread { + name: string; + number: number | null; + daemon: boolean; + state: ThreadState; + stateDetail: string; + /** Raw `at …` / `- …` lines, left-trimmed, so the console's link parser can read them. */ + frames: string[]; + /** Monitors and ownable synchronizers, formatted as ` <
>`. */ + holds: string[]; + /** The lock the thread is blocked on or parked for, in the same format as `holds`. */ + waitsOn: string | null; + internal: boolean; + deadlocked: boolean; +} + +export interface DeadlockLink { + thread: string; + waitsFor: string; + heldBy: string; +} + +export interface ThreadDump { + header: string; + threads: DumpThread[]; + deadlocks: DeadlockLink[][]; +} + +// Only real thread headers carry tid/nid; the deadlock report's `"name":` lines do not. +const THREAD_HEADER_SOURCE = String.raw`^"(.*)"\s+(.*\b(?:tid|nid)=.*)$`; +const THREAD_HEADER = new RegExp(THREAD_HEADER_SOURCE); +const THREAD_HEADER_ANYWHERE = new RegExp(THREAD_HEADER_SOURCE, "m"); + +const STATE_LINE = /^java\.lang\.Thread\.State:\s*([A-Z_]+)(?:\s*\((.*)\))?/; +const FRAME_LINE = /^(?:at |- )/; +const LOCK_LINE = + /^-\s+(waiting to lock|waiting on|parking to wait for|waiting to re-lock in wait\(\)|locked)\s+<(0x[0-9a-f]+)>\s+\((?:an? )?(.+)\)\s*$/; +const OWNABLE_LINE = /^-\s+<(0x[0-9a-f]+)>\s+\((?:an? )?(.+)\)\s*$/; +const OWNABLE_HEADING = /^Locked ownable synchronizers:/; + +const DEADLOCK_START = /^Found one Java-level deadlock:/; +const DEADLOCK_STACKS = /^Java stack information for the threads listed above:/; +const DEADLOCK_THREAD = /^"(.*)":\s*$/; +const DEADLOCK_MONITOR = /^waiting to lock monitor 0x[0-9a-f]+ \(object (0x[0-9a-f]+), (?:an? )?(.+?)\),?$/; +const DEADLOCK_OWNABLE = /^waiting for ownable synchronizer (0x[0-9a-f]+), \((?:an? )?(.+?)\),?$/; +const DEADLOCK_HELD_BY = /^which is held by "(.*)"\s*$/; + +const STATES = new Set(["RUNNABLE", "BLOCKED", "WAITING", "TIMED_WAITING", "NEW", "TERMINATED"]); + +// JVM-owned threads that still get a `#n` id in the dump; native ones (VM Thread, GC workers) +// have none and are caught by the missing number. +const INTERNAL_NAMES = new Set([ + "Reference Handler", + "Finalizer", + "Signal Dispatcher", + "Attach Listener", + "Common-Cleaner", + "Notification Thread", + "Service Thread", + "Monitor Deflation Thread", + "Sweeper thread", +]); +const INTERNAL_PATTERN = /^(?:C[12] CompilerThread|G1 |GC Thread|VM Thread|VM Periodic Task Thread|ZGC |Shenandoah )/; + +function lockLabel(type: string, address: string): string { + return `${type} <${address}>`; +} + +function isInternal(name: string, number: number | null): boolean { + return number === null || INTERNAL_NAMES.has(name) || INTERNAL_PATTERN.test(name); +} + +function newThread(name: string, attrs: string): DumpThread { + const number = /^#(\d+)\b/.exec(attrs)?.[1]; + const prioAt = attrs.search(/(?:^|\s)prio=/); + const flags = prioAt < 0 ? attrs : attrs.slice(0, prioAt); + const parsedNumber = number === undefined ? null : Number(number); + return { + name, + number: parsedNumber, + daemon: /\bdaemon\b/.test(flags), + state: "UNKNOWN", + stateDetail: "", + frames: [], + holds: [], + waitsOn: null, + internal: isInternal(name, parsedNumber), + deadlocked: false, + }; +} + +function applyStackLine(thread: DumpThread, line: string): void { + thread.frames.push(line); + const lock = LOCK_LINE.exec(line); + if (!lock) return; + const label = lockLabel(lock[3] ?? "", lock[2] ?? ""); + if (lock[1] === "locked") thread.holds.push(label); + else thread.waitsOn ??= label; +} + +function deadlockWaitsFor(line: string): string | null { + const monitor = DEADLOCK_MONITOR.exec(line); + if (monitor) return lockLabel(monitor[2] ?? "", monitor[1] ?? ""); + const ownable = DEADLOCK_OWNABLE.exec(line); + if (ownable) return lockLabel(ownable[2] ?? "", ownable[1] ?? ""); + return line.startsWith("waiting") ? line.replace(/,$/, "") : null; +} + +export function isThreadDump(text: string): boolean { + return THREAD_HEADER_ANYWHERE.test(text); +} + +export function parseThreadDump(text: string): ThreadDump | null { + const threads: DumpThread[] = []; + const deadlocks: DeadlockLink[][] = []; + let header = ""; + let current: DumpThread | null = null; + let inOwnable = false; + // Threads are listed first; once the deadlock report starts, `"name":` lines and `at` lines + // describe the same threads again and must not be read as new ones. + let section: "threads" | "links" | "stacks" = "threads"; + let cycle: DeadlockLink[] | null = null; + let linkThread = ""; + let linkWaitsFor = ""; + + for (const rawLine of text.split("\n")) { + const line = rawLine.trimEnd(); + const trimmed = line.trimStart(); + + if (DEADLOCK_START.test(trimmed)) { + section = "links"; + current = null; + cycle = []; + deadlocks.push(cycle); + linkThread = ""; + linkWaitsFor = ""; + continue; + } + + if (section === "threads") { + if (!header && trimmed.startsWith("Full thread dump")) { + header = trimmed; + continue; + } + const start = THREAD_HEADER.exec(line); + if (start) { + current = newThread(start[1] ?? "", start[2] ?? ""); + threads.push(current); + inOwnable = false; + continue; + } + if (!current) continue; + const state = STATE_LINE.exec(trimmed); + if (state) { + const name = state[1] ?? ""; + current.state = STATES.has(name) ? (name as ThreadState) : "UNKNOWN"; + current.stateDetail = state[2] ?? ""; + } else if (OWNABLE_HEADING.test(trimmed)) { + inOwnable = true; + } else if (inOwnable) { + const ownable = OWNABLE_LINE.exec(trimmed); + if (ownable) current.holds.push(lockLabel(ownable[2] ?? "", ownable[1] ?? "")); + } else if (FRAME_LINE.test(trimmed)) { + applyStackLine(current, trimmed); + } + continue; + } + + if (DEADLOCK_STACKS.test(trimmed)) { + section = "stacks"; + continue; + } + if (section !== "links" || !cycle) continue; + + const owner = DEADLOCK_THREAD.exec(trimmed); + if (owner) { + linkThread = owner[1] ?? ""; + linkWaitsFor = ""; + continue; + } + const waitsFor = deadlockWaitsFor(trimmed); + if (waitsFor !== null) { + linkWaitsFor = waitsFor; + continue; + } + const heldBy = DEADLOCK_HELD_BY.exec(trimmed); + if (heldBy && linkThread) cycle.push({ thread: linkThread, waitsFor: linkWaitsFor, heldBy: heldBy[1] ?? "" }); + } + + if (threads.length === 0) return null; + + const deadlocked = new Set(deadlocks.flatMap((links) => links.map((l) => l.thread))); + for (const t of threads) t.deadlocked = deadlocked.has(t.name); + return { header, threads, deadlocks }; +} diff --git a/src/features/run/threadDump/store.ts b/src/features/run/threadDump/store.ts new file mode 100644 index 0000000000..afe95babb7 --- /dev/null +++ b/src/features/run/threadDump/store.ts @@ -0,0 +1,95 @@ +// A thread dump tab's state: the dump and how the user is looking at it. The tab lives in the +// Run tool window's tab list (`useStackTraces`), so these are plain functions over a tab. +import type { DebugSessionId, RunId } from "@/platform/ipc"; +import { parseThreadDump, type DumpThread, type ThreadDump, type ThreadState } from "./parse"; + +/** Where the dump was taken; `null` for a pasted one, which cannot be taken again. */ +export type ThreadDumpSource = { run: RunId; token: string } | { session: DebugSessionId }; + +export interface ThreadDumpTab { + kind: "threads"; + id: string; + title: string; + text: string; + dump: ThreadDump; + source: ThreadDumpSource | null; + /** Takes a new dump into this tab; set by whoever can take one, and reports its own failures. */ + refresh?: () => Promise; + /** Index into `dump.threads`: names need not be unique. */ + selected: number | null; + filter: string; + hideJvm: boolean; +} + +const EMPTY_DUMP: ThreadDump = { header: "", threads: [], deadlocks: [] }; + +/** Indices of the threads the list shows, in dump order. */ +export function visibleThreads(dump: ThreadDump, filter: string, hideJvm: boolean): number[] { + const needle = filter.trim().toLowerCase(); + const shown: number[] = []; + dump.threads.forEach((t, i) => { + if (hideJvm && t.internal) return; + if (needle && !t.name.toLowerCase().includes(needle)) return; + shown.push(i); + }); + return shown; +} + +/** First deadlocked thread, else `main`, else the first one listed. */ +function defaultSelection(dump: ThreadDump, hideJvm: boolean): number | null { + const { threads } = dump; + const deadlocked = threads.findIndex((t) => t.deadlocked); + if (deadlocked >= 0) return deadlocked; + const main = threads.findIndex((t) => t.name === "main"); + if (main >= 0) return main; + return visibleThreads(dump, "", hideJvm)[0] ?? (threads.length ? 0 : null); +} + +export function threadDumpTab( + id: string, + title: string, + text: string, + source: ThreadDumpSource | null, + dump: ThreadDump, +): ThreadDumpTab { + const hideJvm = true; + return { + kind: "threads", + id, + title, + text, + dump, + source, + selected: defaultSelection(dump, hideJvm), + filter: "", + hideJvm, + }; +} + +/** A new dump in the same tab: the filter, the toggle and the selected thread (by name) stay. */ +export function withDumpText(tab: ThreadDumpTab, text: string): ThreadDumpTab { + const dump = parseThreadDump(text) ?? EMPTY_DUMP; + const name = tab.selected === null ? undefined : tab.dump.threads[tab.selected]?.name; + const kept = name === undefined ? -1 : dump.threads.findIndex((t) => t.name === name); + return { ...tab, text, dump, selected: kept >= 0 ? kept : defaultSelection(dump, tab.hideJvm) }; +} + +/** Listed threads per state, in the order states first appear. */ +export function stateCounts(threads: readonly DumpThread[], shown: readonly number[]): [ThreadState, number][] { + const counts = new Map(); + for (const i of shown) { + const state = threads[i]!.state; + counts.set(state, (counts.get(state) ?? 0) + 1); + } + return [...counts]; +} + +/** The selected thread's console text, laid out as in the dump so the frames read the same. */ +export function threadStackText(t: DumpThread): string { + const head = [`"${t.name}"`, t.number === null ? null : `#${t.number}`, t.daemon ? "daemon" : null] + .filter(Boolean) + .join(" "); + const state = + t.state === "UNKNOWN" ? [] : [` java.lang.Thread.State: ${t.state}${t.stateDetail ? ` (${t.stateDetail})` : ""}`]; + return [head, ...state, ...t.frames.map((f) => `\t${f}`)].join("\n"); +} diff --git a/src/features/run/threadDump/unavailableText.ts b/src/features/run/threadDump/unavailableText.ts new file mode 100644 index 0000000000..fae4e193fd --- /dev/null +++ b/src/features/run/threadDump/unavailableText.ts @@ -0,0 +1,44 @@ +import { tx } from "@/platform/i18n"; +import type { JvmMemoryUnavailable, JvmThreadsUnavailable } from "@/platform/ipc"; + +/** Why no thread dump was taken, as the user reads it. */ +export function threadsUnavailableText(reason: JvmThreadsUnavailable): string { + switch (reason.kind) { + case "jvm": + return jvmText(reason.reason); + case "listenerDidNotStart": + return tx("The JVM did not accept the request. It may run with -XX:+DisableAttachMechanism."); + case "remoteRun": + return tx("Thread dumps are not available for remote runs yet."); + case "failed": { + const message = reason.message; + return tx`Could not dump the threads: ${message}`; + } + } +} + +function jvmText(reason: JvmMemoryUnavailable): string { + switch (reason.kind) { + // Only a stopped JVM answers this: a running one has its listener started for the dump. + case "listenerNotRunning": + return tx("Resume the program to dump its threads: the JVM has no attach listener while it is stopped."); + case "unsafeWhileSuspended": { + const n = reason.javaMajor; + return n > 0 + ? tx`Resume the program to dump its threads: Java ${n} cannot answer while the debugger stops it.` + : tx("Resume the program to dump its threads: this Java version cannot answer while the debugger stops it."); + } + case "noJvmProcess": + return tx("No Java process was found for this run."); + case "programExited": + return tx("The program has exited."); + case "unsupportedPlatform": + return tx("Thread dumps are not available on this platform yet."); + case "timedOut": + return tx("The JVM did not answer in time."); + case "attachedJvmNotFound": + return tx("Could not find the debugged JVM on this computer."); + case "listenModeNotSupported": + return tx("Thread dumps are not available when the IDE listens for the JVM to connect."); + } +} diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 3c497e6b2a..1d154df68c 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -2420,6 +2420,33 @@ "MCP Server Settings…": "MCP Server Settings…", "The MCP server is off": "The MCP server is off", "Archived ({count})": "Archived ({count})", + "Deadlock:": "Deadlock:", + "Waits for {lock}, held by {owner}": "Waits for {lock}, held by {owner}", + "Deadlocked": "Deadlocked", + "Thread dump actions": "Thread dump actions", + "Save As…": "Save As…", + "Text file": "Text file", + "Cannot save the thread dump": "Cannot save the thread dump", + "Cannot take a new thread dump": "Cannot take a new thread dump", + "Thread dump": "Thread dump", + "Filter threads": "Filter threads", + "Hide JVM threads": "Hide JVM threads", + "Threads": "Threads", + "Stack of {name}": "Stack of {name}", + "Thread stack": "Thread stack", + "Dump Threads": "Dump Threads", + "Open Thread Dump": "Open Thread Dump", + "Threads: {name}": "Threads: {name}", + "Could not dump the threads: {message}": "Could not dump the threads: {message}", + "The JVM did not accept the request. It may run with -XX:+DisableAttachMechanism.": "The JVM did not accept the request. It may run with -XX:+DisableAttachMechanism.", + "Thread dumps are not available for remote runs yet.": "Thread dumps are not available for remote runs yet.", + "Resume the program to dump its threads: the JVM has no attach listener while it is stopped.": "Resume the program to dump its threads: the JVM has no attach listener while it is stopped.", + "Resume the program to dump its threads: Java {n} cannot answer while the debugger stops it.": "Resume the program to dump its threads: Java {n} cannot answer while the debugger stops it.", + "Resume the program to dump its threads: this Java version cannot answer while the debugger stops it.": "Resume the program to dump its threads: this Java version cannot answer while the debugger stops it.", + "No Java process was found for this run.": "No Java process was found for this run.", + "Thread dumps are not available on this platform yet.": "Thread dumps are not available on this platform yet.", + "Could not find the debugged JVM on this computer.": "Could not find the debugged JVM on this computer.", + "Thread dumps are not available when the IDE listens for the JVM to connect.": "Thread dumps are not available when the IDE listens for the JVM to connect.", "Insert": "Insert", "Drop to reference": "Drop to reference", "Folder reference {name}": "Folder reference {name}", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 40cdf5892b..b738685bb0 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -2818,6 +2818,33 @@ "Put Label": "添加标签", "Put Label…": "添加标签…", "Put a stack trace or a complete thread dump here:": "在此处放入堆栈跟踪或完整的线程转储:", + "Deadlock:": "死锁:", + "Waits for {lock}, held by {owner}": "等待 {lock},该锁由 {owner} 持有", + "Deadlocked": "已死锁", + "Thread dump actions": "线程转储操作", + "Save As…": "另存为…", + "Text file": "文本文件", + "Cannot save the thread dump": "无法保存线程转储", + "Cannot take a new thread dump": "无法获取新的线程转储", + "Thread dump": "线程转储", + "Filter threads": "过滤线程", + "Hide JVM threads": "隐藏 JVM 线程", + "Threads": "线程", + "Stack of {name}": "{name} 的堆栈", + "Thread stack": "线程堆栈", + "Dump Threads": "转储线程", + "Open Thread Dump": "打开线程转储", + "Threads: {name}": "线程:{name}", + "Could not dump the threads: {message}": "无法转储线程:{message}", + "The JVM did not accept the request. It may run with -XX:+DisableAttachMechanism.": "JVM 未接受该请求。它可能以 -XX:+DisableAttachMechanism 运行。", + "Thread dumps are not available for remote runs yet.": "远程运行暂不支持线程转储。", + "Resume the program to dump its threads: the JVM has no attach listener while it is stopped.": "请恢复程序后再转储线程:JVM 停止时没有附加监听器。", + "Resume the program to dump its threads: Java {n} cannot answer while the debugger stops it.": "请恢复程序后再转储线程:调试器使其停止时,Java {n} 无法响应。", + "Resume the program to dump its threads: this Java version cannot answer while the debugger stops it.": "请恢复程序后再转储线程:调试器使其停止时,此 Java 版本无法响应。", + "No Java process was found for this run.": "未找到此运行的 Java 进程。", + "Thread dumps are not available on this platform yet.": "此平台暂不支持线程转储。", + "Could not find the debugged JVM on this computer.": "在此计算机上找不到被调试的 JVM。", + "Thread dumps are not available when the IDE listens for the JVM to connect.": "当 IDE 监听 JVM 连接时,无法进行线程转储。", "Put the caret on a method declaration, or add a method breakpoint by name in View Breakpoints.": "请将光标放在方法声明上,或在“查看断点”中按名称添加方法断点。", "Python Debugger": "Python 调试器", "Python Interpreter": "Python 解释器", diff --git a/src/ui/icons.tsx b/src/ui/icons.tsx index b8a6c4b64e..bba3f94b10 100644 --- a/src/ui/icons.tsx +++ b/src/ui/icons.tsx @@ -488,6 +488,7 @@ const ICONS = { "thread-running": "openidea/debugger/threadRunning", "thread-suspended": "openidea/debugger/threadSuspended", "thread-breakpoint": "openidea/debugger/threadBreakpoint", + "thread-dump": "openidea/debugger/threadDump", "step-over": "run/stepOver", "step-into": "run/stepInto", "step-out": "run/stepOut", diff --git a/src/ui/openidea/debugger/threadDump.svg b/src/ui/openidea/debugger/threadDump.svg new file mode 100644 index 0000000000..0b4cd8795a --- /dev/null +++ b/src/ui/openidea/debugger/threadDump.svg @@ -0,0 +1,5 @@ + + + + +