diff --git a/crates/ide-dap/src/exception_classes.rs b/crates/ide-dap/src/exception_classes.rs new file mode 100644 index 000000000..9d6f800b9 --- /dev/null +++ b/crates/ide-dap/src/exception_classes.rs @@ -0,0 +1,90 @@ +//! Exception breakpoints on a chosen class. The manager keeps one list; a session given a backend +//! for them at start arms it before `configurationDone`, so a throw in the program's first line +//! stops, and again after each `setExceptionBreakpoints`, which drops them in java-debug. + +use crate::session::Session; +use crate::{DebugManager, jvm_memory}; +use ide_jvm_inspect::ExceptionClassSpec; +use serde::{Deserialize, Serialize}; +use specta::Type; + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ExceptionClassBreakpoint { + pub id: String, + /// Fully qualified binary name (`com.acme.Outer$Inner`); its subclasses stop too. + pub class_name: String, + pub caught: bool, + pub uncaught: bool, + pub enabled: bool, + /// Patterns (`com.acme.*`, `*Test`, a full name) for the class whose code throws. + pub class_filters: Vec, + pub class_exclusion_filters: Vec, +} + +/// What a session's exception class breakpoints can do. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct ExceptionClassSupport { + /// Whose class names the session takes: `java`. + pub family: String, + pub condition: bool, + pub class_filters: bool, + /// Filters on the class whose code catches the exception. + pub catch_filters: bool, +} + +/// The JVM backends stop through java-debug's own exception events, which a condition or a +/// catch-location filter cannot veto. +pub(crate) fn support(s: &Session) -> Option { + s.exception_classes.is_some().then(|| ExceptionClassSupport { + family: "java".into(), + condition: false, + class_filters: true, + catch_filters: false, + }) +} + +fn spec(b: &ExceptionClassBreakpoint) -> ExceptionClassSpec { + ExceptionClassSpec { + id: b.id.clone(), + class_name: b.class_name.clone(), + caught: b.caught, + uncaught: b.uncaught, + enabled: b.enabled, + class_filters: b.class_filters.clone(), + class_exclusion_filters: b.class_exclusion_filters.clone(), + } +} + +impl DebugManager { + /// Arms the manager's list in `s`; the caller holds `s.exception_turn`. `clear`: also when the + /// list is empty, to take down what an earlier list armed. + pub(crate) async fn arm_exception_classes(&self, s: &Session, clear: bool) { + let Some(backend) = &s.exception_classes else { return }; + let specs: Vec<_> = self.exception_classes.lock().iter().map(spec).collect(); + // Without either, no VM is known yet: `configure` arms once it is. + let target = jvm_memory::vm_target(s); + if (specs.is_empty() && !clear) || (target.pid.is_none() && target.attach_port.is_none()) { + return; + } + match backend.set(&target, &specs).await { + Ok(states) => tracing::debug!("exception class breakpoints of session {}: {states:?}", s.id.0), + Err(e) => tracing::debug!("exception class breakpoints of session {} failed: {e}", s.id.0), + } + } + + /// Stores exception breakpoints on chosen classes (kept without a session, armed on start) + /// and arms them in every session that takes them. Also in one still starting: one that has + /// armed already would miss the list, and one that has not answers `vmNotFound` until then. + pub async fn set_exception_class_breakpoints(&self, list: Vec) { + *self.exception_classes.lock() = list; + for s in self.live_sessions() { + if s.exception_classes.is_none() || s.conn.is_closed() { + continue; + } + let _turn = s.exception_turn.lock().await; + self.arm_exception_classes(&s, true).await; + } + } +} diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 18f0a16f7..56c2bd9c4 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -12,6 +12,7 @@ pub mod adapter; pub mod attach; mod cargo; pub mod connection; +mod exception_classes; pub mod jdwp; mod js_cdp; mod js_debug; @@ -24,6 +25,7 @@ pub mod unity; 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_language::LanguageRegistry; @@ -283,6 +285,8 @@ pub struct SessionExceptionFilters { pub session: DebugSessionId, pub adapter: String, pub filters: Vec, + /// Set when the session takes exception breakpoints on a chosen class. + pub classes: Option, } /// What triggered a hot reload; `flutter debug_adapter` takes it as `reason`. @@ -336,6 +340,7 @@ pub struct DebugManager { states: Mutex>>, /// Explicit exception filter choices (filter id → enabled); unset filters use the adapter default. exception_choices: Mutex>, + exception_classes: Mutex>, function_breakpoints: Mutex>, data_breakpoints: Mutex>, /// In-flight stops, by session: a second Stop sets `stop_force`, the waiting one kills. @@ -788,6 +793,7 @@ impl DebugManager { breakpoints: Mutex::default(), states: Mutex::default(), exception_choices: Mutex::default(), + exception_classes: Mutex::default(), function_breakpoints: Mutex::default(), data_breakpoints: Mutex::default(), stopping: Mutex::default(), @@ -836,6 +842,18 @@ impl DebugManager { config: LaunchConfig, owner: SessionOwner, custom_command: impl FnOnce(&str) -> Option, + ) -> IdeResult { + self.start_with_exception_classes(config, owner, custom_command, None).await + } + + /// [`start_with`](Self::start_with), the session arming [`Self::set_exception_class_breakpoints`] + /// through `exception_classes`. + pub async fn start_with_exception_classes( + &self, + config: LaunchConfig, + owner: SessionOwner, + custom_command: impl FnOnce(&str) -> Option, + exception_classes: Option>, ) -> IdeResult { let mut arguments = launch_arguments(&config)?; // An IDE-side marker (never sent to the adapter): the session is a Flutter @@ -977,7 +995,19 @@ impl DebugManager { } } let port = debug_server.map(|s| s.port); - self.start_session(id, owner, config.name, config.adapter, None, config.request, arguments, spec, port).await + self.start_session( + id, + owner, + config.name, + config.adapter, + None, + config.request, + arguments, + spec, + port, + exception_classes, + ) + .await } /// `startDebugging` reverse request: a child session on the same adapter. @@ -1002,6 +1032,7 @@ impl DebugManager { configuration, parent.spec.clone(), parent.port, + None, ) .await .map(|_| ()) @@ -1019,6 +1050,7 @@ impl DebugManager { arguments: Value, spec: AdapterSpec, reuse_port: Option, + exception_classes: Option>, ) -> IdeResult { if request != "launch" && request != "attach" { return Err(IdeError::invalid(format!("request must be `launch` or `attach`, got `{request}`"))); @@ -1033,8 +1065,9 @@ impl DebugManager { let rdbg_pid = (adapter_name == "rdbg" && request == "launch") .then(|| io.child.as_ref().and_then(tokio::process::Child::id)) .flatten(); - let session = - Arc::new(Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child)); + let mut session = Session::new(id, owner, name, adapter_name, parent, request, conn, spec, io.port, io.child); + session.exception_classes = exception_classes; + 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()); } @@ -1259,8 +1292,12 @@ impl DebugManager { tracing::debug!("setDataBreakpoints failed: {e}"); } let has_filters = s.caps.lock().get("exceptionBreakpointFilters").and_then(Value::as_array).is_some(); - if has_filters { - let _ = self.send_exception_breakpoints(s).await; + { + let _turn = s.exception_turn.lock().await; + if has_filters { + let _ = self.send_exception_breakpoints(s).await; + } + self.arm_exception_classes(s, false).await; } if s.supports("supportsConfigurationDoneRequest") { if s.adapter == kotlin::ADAPTER { @@ -1481,6 +1518,7 @@ impl DebugManager { session: s.id, adapter: s.adapter.clone(), filters: exception_filters_from(&s.caps.lock()), + classes: exception_classes::support(s), }) .collect() } @@ -1496,9 +1534,11 @@ impl DebugManager { if exception_filters_from(&s.caps.lock()).is_empty() { continue; } + let _turn = s.exception_turn.lock().await; if let Err(e) = self.send_exception_breakpoints(&s).await { tracing::debug!("setExceptionBreakpoints on session {} failed: {e}", s.id.0); } + self.arm_exception_classes(&s, false).await; } Ok(()) } diff --git a/crates/ide-dap/src/session.rs b/crates/ide-dap/src/session.rs index 789a2c030..51e64beb1 100644 --- a/crates/ide-dap/src/session.rs +++ b/crates/ide-dap/src/session.rs @@ -118,6 +118,11 @@ pub(crate) struct Session { pub kotlin_mirror: Mutex>, pub jvm_memory: tokio::sync::Mutex, pub stream_tracer: parking_lot::Mutex>>, + /// Given at start: the class breakpoints must be armed before `configurationDone`. + pub(crate) exception_classes: Option>, + /// Held from `setExceptionBreakpoints`, which drops the class breakpoints, until they are + /// armed again, so that the last list armed is the manager's. + pub(crate) exception_turn: tokio::sync::Mutex<()>, pub(crate) stream_trace: parking_lot::Mutex>, /// The last trace that finished, until the stop its records were read in ends. pub(crate) stream_trace_done: parking_lot::Mutex>, @@ -286,6 +291,8 @@ impl Session { kotlin_mirror: Mutex::new(None), jvm_memory: tokio::sync::Mutex::default(), stream_tracer: parking_lot::Mutex::new(None), + exception_classes: None, + exception_turn: tokio::sync::Mutex::default(), stream_trace: parking_lot::Mutex::new(None), stream_trace_done: parking_lot::Mutex::new(None), quirks: kotlin_lsp::Quirks::default(), diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index 7a6b2d084..d57978aff 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -1,5 +1,6 @@ //! Protocol flow against an in-memory fake adapter. +mod exception_classes; mod jvm_inspect; mod stream_trace; diff --git a/crates/ide-dap/src/tests/exception_classes.rs b/crates/ide-dap/src/tests/exception_classes.rs new file mode 100644 index 000000000..4e00d97b1 --- /dev/null +++ b/crates/ide-dap/src/tests/exception_classes.rs @@ -0,0 +1,154 @@ +//! Exception breakpoints on a chosen class, armed through a session's backend. + +use super::*; +use ide_jvm_inspect::{ExceptionArmState, ExceptionClassBreakpoints, ExceptionClassSpec, InspectFuture, VmTarget}; + +/// The target, the list, and the DAP requests sent before it. +type ArmCall = (VmTarget, Vec, Vec); + +/// Records each list it is given with the DAP requests sent before it. +struct FakeArmer { + log: Log, + calls: Mutex>, +} + +impl FakeArmer { + fn new(h: &Harness) -> Arc { + Arc::new(Self { log: h.log.clone(), calls: Mutex::default() }) + } + + fn lists(&self) -> Vec> { + self.calls.lock().iter().map(|(_, specs, _)| specs.iter().map(|s| s.class_name.clone()).collect()).collect() + } + + /// The DAP requests sent before each call. + fn before(&self) -> Vec> { + self.calls.lock().iter().map(|(_, _, sent)| sent.clone()).collect() + } +} + +impl ExceptionClassBreakpoints for FakeArmer { + fn set<'a>( + &'a self, + target: &'a VmTarget, + breakpoints: &'a [ExceptionClassSpec], + ) -> InspectFuture<'a, Vec<(String, ExceptionArmState)>> { + let sent = self + .log + .lock() + .iter() + .filter(|m| m["type"] == "request") + .map(|m| m["command"].as_str().unwrap().to_owned()) + .collect(); + self.calls.lock().push((target.clone(), breakpoints.to_vec(), sent)); + let states = breakpoints.iter().map(|b| (b.id.clone(), ExceptionArmState::Armed)).collect(); + Box::pin(async move { Ok(states) }) + } +} + +fn class_bp(id: &str, class_name: &str) -> ExceptionClassBreakpoint { + ExceptionClassBreakpoint { + id: id.into(), + class_name: class_name.into(), + caught: true, + uncaught: true, + enabled: true, + class_filters: vec![], + class_exclusion_filters: vec![], + } +} + +/// A java-debug attach to a JVM on another machine: the target is known from the request alone. +fn attach() -> LaunchConfig { + LaunchConfig { + extra_json: Some(json!({"hostName": "10.0.0.5", "port": 5005}).to_string()), + ..java_config("attach") + } +} + +async fn start(h: &Harness, config: LaunchConfig, armer: &Arc) -> DebugSessionId { + let backend: Arc = armer.clone(); + h.manager.start_with_exception_classes(config, h.owner.clone(), |_| None, Some(backend)).await.unwrap() +} + +#[tokio::test] +async fn armed_after_the_exception_filters_and_before_configuration_done() { + let h = harness(Script::default()); + let armer = FakeArmer::new(&h); + let filtered = ExceptionClassBreakpoint { + caught: false, + enabled: false, + class_filters: vec!["com.acme.*".into()], + class_exclusion_filters: vec!["*Test".into()], + ..class_bp("b", "com.acme.Boom") + }; + h.manager.set_exception_class_breakpoints(vec![class_bp("a", "java.lang.IllegalStateException"), filtered]).await; + start(&h, attach(), &armer).await; + + assert_eq!(armer.before(), [["initialize", "attach", "setExceptionBreakpoints"]]); + let (target, specs, _) = armer.calls.lock()[0].clone(); + assert_eq!((target.pid, target.attach_host.as_deref(), target.attach_port), (None, Some("10.0.0.5"), Some(5005))); + assert_eq!( + specs[1], + ExceptionClassSpec { + id: "b".into(), + class_name: "com.acme.Boom".into(), + caught: false, + uncaught: true, + enabled: false, + class_filters: vec!["com.acme.*".into()], + class_exclusion_filters: vec!["*Test".into()], + } + ); + assert!(h.commands().contains(&"configurationDone".to_owned())); +} + +#[tokio::test] +async fn armed_again_after_every_set_exception_breakpoints() { + let h = harness(Script::default()); + let armer = FakeArmer::new(&h); + h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await; + start(&h, attach(), &armer).await; + h.manager.set_exception_breakpoints(BTreeMap::from([("raised".into(), true)])).await.unwrap(); + + assert_eq!(armer.lists(), [["com.acme.Boom"], ["com.acme.Boom"]]); + let last = armer.before().pop().unwrap(); + assert_eq!(last.iter().filter(|c| *c == "setExceptionBreakpoints").count(), 2, "{last:?}"); +} + +#[tokio::test] +async fn a_new_list_reaches_the_sessions_that_take_it() { + let h = harness(Script::default()); + let armer = FakeArmer::new(&h); + start(&h, attach(), &armer).await; + let other = h.start(attach()).await.unwrap(); + assert!(armer.lists().is_empty(), "nothing to arm at start"); + + h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await; + h.manager.set_exception_class_breakpoints(vec![]).await; + assert_eq!(armer.lists(), [vec!["com.acme.Boom".to_owned()], vec![]], "an empty list takes them down"); + + let filters = h.manager.exception_filters(None); + let support = |id| filters.iter().find(|f| f.session == id).unwrap().classes.clone(); + assert_eq!(support(other), None); + let java = filters.iter().find(|f| f.session != other).unwrap().session; + assert_eq!( + support(java), + Some(ExceptionClassSupport { + family: "java".into(), + condition: false, + class_filters: true, + catch_filters: false + }) + ); +} + +#[tokio::test] +async fn nothing_is_sent_before_the_jvm_is_known() { + let h = harness(Script::default()); + let armer = FakeArmer::new(&h); + h.manager.set_exception_class_breakpoints(vec![class_bp("a", "com.acme.Boom")]).await; + // The fake adapter sends no `process` event before `configurationDone`: no pid to name. + start(&h, java_config("launch"), &armer).await; + assert!(armer.lists().is_empty()); +} diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index 8d0dbb47f..30c075c20 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -129,7 +129,8 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide }; host.require_trust(window)?; let server_port = debug_server_port(&config); - let result = host.debugger.start_with(config, owner, custom).await; + let exception_classes = server_port.and_then(|port| exception_class_backend(host, window, port)); + let result = host.debugger.start_with_exception_classes(config, owner, custom, exception_classes).await; flush_output(); if let Ok(id) = &result { let sink = host.window_sink(label); @@ -208,6 +209,18 @@ fn attach_jvm_inspector(host: &Host, window: &str, session: DebugSessionId, port } } +/// Given before the session starts, unlike the inspector: the breakpoints are armed before +/// `configurationDone`, so a throw in `main`'s first line stops. +fn exception_class_backend( + host: &Host, + window: &str, + port: u16, +) -> Option> { + let project = host.project(window).ok()?; + let module = project.lsp.java_debug_server_module(port)?; + Some(std::sync::Arc::new(ide_lsp::JdtExceptionBreakpoints::new(project.lsp.clone(), module))) +} + /// A JVM the debugger starts itself: an Application or Spring Boot configuration, launched by /// java-debug, java-analyzer or the Kotlin debugger (JAR Application debugs through a run with a /// JDWP agent). @@ -453,6 +466,16 @@ pub async fn debug_set_exception_breakpoints( host.debugger.set_exception_breakpoints(choices).await } +/// Exception breakpoints on chosen classes (all sessions that take them, and later ones). +#[command(trust = trusted)] +pub async fn debug_set_exception_class_breakpoints( + host: &Host, + breakpoints: Vec, +) -> IdeResult<()> { + host.debugger.set_exception_class_breakpoints(breakpoints).await; + Ok(()) +} + #[allow(clippy::too_many_arguments)] #[command(trust = trusted)] pub async fn debug_set_variable( @@ -849,6 +872,7 @@ ide_command::domain!( debug_set_breakpoints, debug_set_data_breakpoints, debug_set_exception_breakpoints, + debug_set_exception_class_breakpoints, debug_set_function_breakpoints, debug_set_variable, debug_stack_trace, diff --git a/crates/ide-jvm-inspect/src/exceptions.rs b/crates/ide-jvm-inspect/src/exceptions.rs new file mode 100644 index 000000000..13290568c --- /dev/null +++ b/crates/ide-jvm-inspect/src/exceptions.rs @@ -0,0 +1,41 @@ +//! Exception breakpoints on a chosen class, armed inside the debuggee's VM by the debugger's own +//! connection. The adapter stops on them as on its own exception filters. + +use crate::{InspectFuture, VmTarget}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct ExceptionClassSpec { + /// Echoed back with the breakpoint's state. + pub id: String, + /// Binary name (`com.acme.Outer$Inner`); subclasses stop too. + pub class_name: String, + pub caught: bool, + pub uncaught: bool, + pub enabled: bool, + /// JDI class patterns (`com.acme.*`, `*Test`) matched against the class whose code throws. + pub class_filters: Vec, + pub class_exclusion_filters: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum ExceptionArmState { + Armed, + /// No class of that name is loaded yet; it is armed when one is. + Pending, + Disabled, + /// A stream trace silences the VM's breakpoints; applied when it ends. + Deferred, +} + +pub trait ExceptionClassBreakpoints: Send + Sync { + /// Replaces the VM's whole list; `(id, state)` per breakpoint, in order. The adapter can drop + /// these whenever it sets its own exception filters, so set them again after each time. + fn set<'a>( + &'a self, + target: &'a VmTarget, + breakpoints: &'a [ExceptionClassSpec], + ) -> InspectFuture<'a, Vec<(String, ExceptionArmState)>>; +} diff --git a/crates/ide-jvm-inspect/src/lib.rs b/crates/ide-jvm-inspect/src/lib.rs index f7c7cbf0e..adc28db73 100644 --- a/crates/ide-jvm-inspect/src/lib.rs +++ b/crates/ide-jvm-inspect/src/lib.rs @@ -1,9 +1,11 @@ //! Types and the [`JvmInspector`] trait for reading live JVM objects while a debug session is //! suspended. Implementations live elsewhere (jdtls bundle for Java, JDWP link for Kotlin). +mod exceptions; mod names; mod stream; +pub use exceptions::{ExceptionArmState, ExceptionClassBreakpoints, ExceptionClassSpec}; pub use names::{is_boxed, name_to_signature, signature_to_name, string_length}; pub use stream::{AbortState, CollectedTerminal, StreamTracer, TraceCollected, TraceId, TraceState}; diff --git a/crates/ide-lsp/src/jdtls.rs b/crates/ide-lsp/src/jdtls.rs index 0c2e37293..689abd96d 100644 --- a/crates/ide-lsp/src/jdtls.rs +++ b/crates/ide-lsp/src/jdtls.rs @@ -20,6 +20,7 @@ pub(crate) const SERVER: &str = "jdtls"; const GENERATED_SOURCES: &str = "openidea.java.generatedSources"; pub(crate) mod configuration; +pub(crate) mod exception_breakpoints; mod extract_interface; mod formatter; mod generated; diff --git a/crates/ide-lsp/src/jdtls/exception_breakpoints.rs b/crates/ide-lsp/src/jdtls/exception_breakpoints.rs new file mode 100644 index 000000000..89d9a9f94 --- /dev/null +++ b/crates/ide-lsp/src/jdtls/exception_breakpoints.rs @@ -0,0 +1,56 @@ +//! [`ExceptionClassBreakpoints`] over `openidea.jvm.exceptions.set` of the JVM inspector bundle that +//! runs inside jdtls (`java/jvm-inspect`). + +use super::jvm_inspect::{command_error, decode, target_json}; +use crate::LspManager; +use ide_jvm_inspect::{ + ExceptionArmState, ExceptionClassBreakpoints, ExceptionClassSpec, InspectError, InspectFuture, VmTarget, +}; +use serde::Deserialize; +use serde_json::json; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; +use tokio::time::timeout; + +/// The bundle waits for the inspect commands' turn, which a `classes` on a large heap can hold. +const COMMAND_TIMEOUT: Duration = Duration::from_secs(30); + +pub struct JdtExceptionBreakpoints { + lsp: Arc, + /// A path inside the module whose jdtls runs the debug session. + server: PathBuf, +} + +impl JdtExceptionBreakpoints { + pub fn new(lsp: Arc, server: PathBuf) -> Self { + Self { lsp, server } + } +} + +#[derive(Deserialize)] +struct WireState { + id: String, + state: ExceptionArmState, +} + +impl ExceptionClassBreakpoints for JdtExceptionBreakpoints { + fn set<'a>( + &'a self, + target: &'a VmTarget, + breakpoints: &'a [ExceptionClassSpec], + ) -> InspectFuture<'a, Vec<(String, ExceptionArmState)>> { + Box::pin(async move { + let arguments = vec![target_json(target), json!({ "breakpoints": breakpoints })]; + let reply = timeout( + COMMAND_TIMEOUT, + self.lsp.jdtls_command(&self.server, "openidea.jvm.exceptions.set", arguments), + ) + .await + .map_err(|_| InspectError::TimedOut)? + .map_err(command_error)?; + let states: Vec = decode(reply)?; + Ok(states.into_iter().map(|s| (s.id, s.state)).collect()) + }) + } +} diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs index 57628679c..a5331e60d 100644 --- a/crates/ide-lsp/src/lib.rs +++ b/crates/ide-lsp/src/lib.rs @@ -48,6 +48,7 @@ mod xml_catalog; pub use injections::{InjectedRange, InjectionProvider, MAX_INJECTED_DOCUMENT_BYTES}; pub use inspect::{CheckedServer, DocumentCheck, FileInspection, InspectHost, InspectOptions}; +pub use jdtls::exception_breakpoints::JdtExceptionBreakpoints; pub use jdtls::jvm_inspect::JdtJvmInspector; pub use jdtls::stream_trace::JdtStreamTracer; pub use kotlin_lsp::{KotlinDebugServer, KotlinDebugUnavailable}; diff --git a/crates/ide-lsp/tests/mock_server.rs b/crates/ide-lsp/tests/mock_server.rs index 458dbadda..28f08f01e 100644 --- a/crates/ide-lsp/tests/mock_server.rs +++ b/crates/ide-lsp/tests/mock_server.rs @@ -3714,6 +3714,62 @@ async fn stream_collect_fails_cleanly_on_a_step_beyond_u16() { assert!(matches!(error, InspectError::Failed(ref m) if m.contains("malformed")), "{error:?}"); } +#[tokio::test(flavor = "multi_thread")] +async fn exception_breakpoints_send_the_whole_list_and_decode_states() { + use ide_jvm_inspect::{ExceptionArmState, ExceptionClassBreakpoints, ExceptionClassSpec}; + let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]); + let (_, path) = h.open("Sample.java", "class Sample {}"); + h.wait_status("jdtls", ServerStatus::Ready).await; + let s = h.launcher.state("jdtls"); + let client = ide_lsp::JdtExceptionBreakpoints::new(h.mgr.clone(), path); + let specs = [ + ExceptionClassSpec { + id: "a".into(), + class_name: "com.acme.Boom".into(), + caught: true, + uncaught: false, + enabled: true, + class_filters: vec!["com.acme.*".into()], + class_exclusion_filters: vec![], + }, + ExceptionClassSpec { + id: "b".into(), + class_name: "java.lang.IllegalStateException".into(), + caught: true, + uncaught: true, + enabled: false, + class_filters: vec![], + class_exclusion_filters: vec!["*Test".into()], + }, + ]; + s.respond( + "workspace/executeCommand", + json!({"ok": [{"id": "a", "state": "pending"}, {"id": "b", "state": "disabled"}]}), + ); + let states = client.set(&stream_launch_target(), &specs).await.unwrap(); + assert_eq!(states, vec![("a".into(), ExceptionArmState::Pending), ("b".into(), ExceptionArmState::Disabled)]); + let asked = s.requested("workspace/executeCommand"); + assert_eq!(asked[0]["command"], "openidea.jvm.exceptions.set"); + assert_eq!( + asked[0]["arguments"], + json!([ + {"pid": 42, "host": null, "port": null, "generation": 3}, + {"breakpoints": [ + {"id": "a", "className": "com.acme.Boom", "caught": true, "uncaught": false, "enabled": true, + "classFilters": ["com.acme.*"], "classExclusionFilters": []}, + {"id": "b", "className": "java.lang.IllegalStateException", "caught": true, "uncaught": true, + "enabled": false, "classFilters": [], "classExclusionFilters": ["*Test"]}, + ]}, + ]) + ); + + s.respond("workspace/executeCommand", json!({"error": "noSession", "detail": "hotCodeReplace is never?"})); + assert_eq!( + client.set(&stream_launch_target(), &specs).await.unwrap_err(), + ide_jvm_inspect::InspectError::NoSession + ); +} + #[tokio::test(flavor = "multi_thread")] async fn debug_server_port_maps_to_module() { let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]); diff --git a/crates/ide-sdk/src/java.rs b/crates/ide-sdk/src/java.rs index 2cfc76717..aba77507c 100644 --- a/crates/ide-sdk/src/java.rs +++ b/crates/ide-sdk/src/java.rs @@ -1649,7 +1649,7 @@ pub fn jvm_inspect_bundle(data_dir: &Path) -> Option { install_bundle( data_dir, "jvm-inspect", - "1.1.1", + "1.2.0", include_bytes!("../../../java/jvm-inspect/openidea-jvm-inspect.jar"), ) } @@ -1745,7 +1745,7 @@ mod usages_bundle_tests { std::fs::write(dir.path().join(name), b"old").unwrap(); } let jar = super::jvm_inspect_bundle(dir.path()).unwrap(); - assert_eq!(jar, dir.path().join("jvm-inspect-1.1.1.jar")); + assert_eq!(jar, dir.path().join("jvm-inspect-1.2.0.jar")); assert_eq!(std::fs::read(&jar).unwrap(), include_bytes!("../../../java/jvm-inspect/openidea-jvm-inspect.jar")); assert!(!dir.path().join("jvm-inspect-0.9.0.jar").exists()); assert_eq!(std::fs::read(dir.path().join("java-usages-1.7.0.jar")).unwrap(), b"old"); diff --git a/java/jvm-inspect/MANIFEST.MF b/java/jvm-inspect/MANIFEST.MF index 40d85ff1b..202f77033 100644 --- a/java/jvm-inspect/MANIFEST.MF +++ b/java/jvm-inspect/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: OpenIDEA JVM inspect Bundle-SymbolicName: ai.openidea.jvminspect;singleton:=true -Bundle-Version: 1.1.1 +Bundle-Version: 1.2.0 Bundle-RequiredExecutionEnvironment: JavaSE-21 Require-Bundle: org.eclipse.jdt.ls.core,org.eclipse.core.runtime, org.eclipse.equinox.common,org.eclipse.jdt.debug,org.eclipse.core.resources diff --git a/java/jvm-inspect/README.md b/java/jvm-inspect/README.md index 688edd60f..dcd9fa444 100644 --- a/java/jvm-inspect/README.md +++ b/java/jvm-inspect/README.md @@ -3,7 +3,7 @@ An OSGi bundle loaded into JDT LS next to microsoft java-debug. While a Java debug session is suspended, it lists the instances of a class, the fields of an object and the objects that refer to it, and counts the instances of every loaded class; it also traces a stream chain while the program -runs it. It works on java-debug's own JDI connection to the debuggee, so no second debugger connects +runs it, and stops on the exceptions of a chosen class. It works on java-debug's own JDI connection to the debuggee, so no second debugger connects to the JVM. ## Commands @@ -159,6 +159,33 @@ waiting behind the command time out too. These two commands raise it to at least when done, put back the old value unless something else changed it meanwhile (java-debug applies its timeout setting to every VM when it changes). +## Exception breakpoints + +`openidea.jvm.exceptions.set` takes `target` first, then `{breakpoints: [{id, className, caught, +uncaught, enabled, classFilters, classExclusionFilters}]}`, and replaces the VM's whole list. `ok` +is `[{id, state}]` in the same order, `state` being `armed`, `pending` (the class is not loaded yet), +`disabled` (off, or neither `caught` nor `uncaught`) or `deferred`. A missing `id` or `className` is +an `executeCommand` error; a VM whose session java-debug did not register gives `noSession`. + +- Each breakpoint is a JDI exception request on every loaded class of that name, subclasses + included, plus a class-prepare request that arms classes loaded later or by another class loader. + java-debug turns every exception event into a stop, whoever made the request, so the stop, the + stack and `exceptionInfo` are java-debug's own. +- `classFilters` / `classExclusionFilters` are JDI class patterns (`com.acme.*`, `*Test`) matched + against the class whose code throws. +- java-debug deletes every exception request when it handles `setExceptionBreakpoints`. Send the + list again after each one, and before `configurationDone` to stop on a throw in `main`'s first line. +- One throw matched by two requests gives two stops. A request leaves out the caught or uncaught + throws that java-debug's enabled all-exception filters report, or an enabled breakpoint without + class filters on a superclass, or on the same class when that one comes earlier in the list or this + one has filters. Two breakpoints that both have class filters can still both stop on one throw. +- No conditions and no catch-location filters: java-debug stops on every exception event it gets, + and an event-hub subscriber cannot keep it from stopping. +- While a stream trace silences the VM's breakpoints, a new list is `deferred` and applied when the + trace ends, as is a class prepared meanwhile. Its requests are silenced and restored with the + rest; a trace that ends at an uncaught throw watches the throw itself only when no java-debug + request, nor a breakpoint without class filters, already stops there. + ## Internals it depends on java-debug is not pinned: the app installs the latest vscode-java-debug. The bundle reaches the VMs @@ -211,7 +238,7 @@ Java 21. The recorder is compiled by the `javac` on `PATH` with `--release 8`, s run Java 8. Build twice and compare: two builds of the checked-in jar gave ``` -4ab30723afe1254b991d9457ea66271109f397a17b238870572283aad73338ad openidea-jvm-inspect.jar +5278f1d38325551c5d4ab50b5140551f91c3bf5b9db536aeb276713578e0fd49 openidea-jvm-inspect.jar ``` Change `Bundle-Version` whenever the jar changes: OSGi caches bundles by version. @@ -243,3 +270,13 @@ PATH=/path/to/jdk25/bin:$PATH \ OPENIDEA_TEST_JAVA=/path/to/jdk11/bin/java:/path/to/jdk21/bin/java \ python3 -I tests/stream.py /path/to/jdtls /path/to/com.microsoft.java.debug.plugin-0.53.2.jar --bundle x.jar ``` + +`tests/exceptions.py` checks `openidea.jvm.exceptions.set` on the `java` on `PATH`: a throw in +`main`'s first line in a launch and in an attach, a class loaded late, class filters, the re-arm +after `setExceptionBreakpoints`, no double stop with java-debug's filters or a superclass breakpoint, +and a hot swap of the throwing class. It takes `--bundle` too: + +```sh +PATH=/path/to/jdk25/bin:$PATH \ +python3 -I tests/exceptions.py /path/to/jdtls /path/to/com.microsoft.java.debug.plugin-0.53.2.jar +``` diff --git a/java/jvm-inspect/openidea-jvm-inspect.jar b/java/jvm-inspect/openidea-jvm-inspect.jar index f2614c6b1..b9a17393f 100644 Binary files a/java/jvm-inspect/openidea-jvm-inspect.jar and b/java/jvm-inspect/openidea-jvm-inspect.jar differ diff --git a/java/jvm-inspect/plugin.xml b/java/jvm-inspect/plugin.xml index c471b3a89..aa3a95968 100644 --- a/java/jvm-inspect/plugin.xml +++ b/java/jvm-inspect/plugin.xml @@ -16,5 +16,8 @@ + + + diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/ExceptionBreakpoints.java b/java/jvm-inspect/src/ai/openidea/jvminspect/ExceptionBreakpoints.java new file mode 100644 index 000000000..41c7d47db --- /dev/null +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/ExceptionBreakpoints.java @@ -0,0 +1,253 @@ +package ai.openidea.jvminspect; + +import ai.openidea.jvminspect.InspectCommand.Failure; +import com.sun.jdi.ClassType; +import com.sun.jdi.ReferenceType; +import com.sun.jdi.VMDisconnectedException; +import com.sun.jdi.VirtualMachine; +import com.sun.jdi.event.ClassPrepareEvent; +import com.sun.jdi.event.Event; +import com.sun.jdi.request.ClassPrepareRequest; +import com.sun.jdi.request.EventRequest; +import com.sun.jdi.request.EventRequestManager; +import com.sun.jdi.request.ExceptionRequest; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Exception breakpoints on a chosen class, one list per VM, as exception requests of the bundle's own. + * java-debug turns every exception event into a stop, whoever made its request. It also deletes every + * exception request whenever it sets its own filters, so the client sends the list again after each + * {@code setExceptionBreakpoints}. Two requests that match one throw give two stops, so a request + * leaves out what an enabled java-debug filter or a breakpoint on a superclass already reports. + */ +final class ExceptionBreakpoints { + /** Marks the bundle's requests; the value is the {@link Spec}. Not {@link Silencer#OWN_PROPERTY}: a trace silences these. */ + static final String PROPERTY = "oi.exc"; + private static final Map VMS = new IdentityHashMap<>(); + + record Spec(String id, String className, boolean caught, boolean uncaught, boolean enabled, List classFilters, + List classExclusionFilters) { + /** From the Gson JSON of {@code executeCommand}. */ + static Spec of(Object json) { + Map m = (Map) json; + return new Spec(text(m, "id"), text(m, "className"), Boolean.TRUE.equals(m.get("caught")), Boolean.TRUE.equals(m.get("uncaught")), + !Boolean.FALSE.equals(m.get("enabled")), patterns(m.get("classFilters")), patterns(m.get("classExclusionFilters"))); + } + + boolean hasClassFilters() { + return !classFilters.isEmpty() || !classExclusionFilters.isEmpty(); + } + + private static String text(Map m, String key) { + if (!(m.get(key) instanceof String s) || s.isBlank()) throw new IllegalArgumentException("missing " + key); + return s.trim(); + } + + private static List patterns(Object json) { + if (!(json instanceof List list)) return List.of(); + return list.stream().filter(String.class::isInstance).map(s -> ((String) s).trim()).filter(s -> !s.isEmpty()).toList(); + } + } + + record Flags(boolean caught, boolean uncaught) { + boolean none() { + return !caught && !uncaught; + } + } + + private final VirtualMachine vm; + private JavaDebugSessions.Subscription subscription; + private List specs = List.of(); + /** The list to apply once the VM's stream trace no longer silences its breakpoints. */ + private List deferred; + private boolean javaDebugCaught; + private boolean javaDebugUncaught; + + private ExceptionBreakpoints(VirtualMachine vm) { + this.vm = vm; + } + + /** + * Replaces the VM's list. Under the inspect commands' lock, which a stream trace's {@code arm} holds + * too: a request made while a trace silences breakpoints would be on inside the trace. + * + * @return per breakpoint {@code {id, state}}: {@code armed}, {@code pending} (class not loaded yet), + * {@code disabled} or {@code deferred} (applied when the VM's stream trace ends) + */ + static List> set(VirtualMachine vm, List specs) throws Failure, ConnectedVms.Unsupported { + synchronized (InspectCommand.handlesFor(vm)) { + ExceptionBreakpoints state; + synchronized (VMS) { + state = VMS.computeIfAbsent(vm, ExceptionBreakpoints::new); + } + return state.replace(specs); + } + } + + /** Drops the lists of VMs java-debug no longer has; their requests went with the VM. */ + static void forgetGone(Set live) { + List gone = new ArrayList<>(); + synchronized (VMS) { + VMS.entrySet().removeIf(e -> !live.contains(e.getKey()) && gone.add(e.getValue())); + } + for (ExceptionBreakpoints state : gone) state.close(); + } + + /** + * After a stream trace switched the breakpoints back on: applies a list deferred meanwhile, before + * the trace decides whether it must watch an uncaught throw itself. Without the inspect commands' + * lock, which one of them can hold for seconds while the caller is java-debug's event thread or + * the trace's worker; the trace has stopped silencing, so no arm can be silencing meanwhile. + */ + static void traceEnded(VirtualMachine vm) { + ExceptionBreakpoints state; + synchronized (VMS) { + state = VMS.get(vm); + } + if (state != null) state.applyDeferred(); + } + + /** Whether {@code r} reports every throw of its type, for a trace deciding if it must watch one itself. */ + static boolean coversWholeType(EventRequest r) { + return !(r.getProperty(PROPERTY) instanceof Spec spec) || !spec.hasClassFilters(); + } + + /** + * What a request for {@code spec} on a type with the superclasses {@code supers} must still report: + * not what java-debug's own all-exception filters report, nor what an enabled breakpoint without + * class filters reports already: one on a superclass, or on the same class when it comes earlier or + * {@code spec} has filters. Two breakpoints with class filters can still both report one throw. + */ + static Flags uncovered(Spec spec, List supers, boolean javaDebugCaught, boolean javaDebugUncaught, List all) { + boolean caught = spec.caught() && !javaDebugCaught; + boolean uncaught = spec.uncaught() && !javaDebugUncaught; + boolean earlier = true; + for (Spec other : all) { + if (other == spec) { + earlier = false; + continue; + } + if (!other.enabled() || other.hasClassFilters()) continue; + boolean twin = other.className().equals(spec.className()) && (earlier || spec.hasClassFilters()); + if (twin || supers.contains(other.className())) { + caught &= !other.caught(); + uncaught &= !other.uncaught(); + } + } + return new Flags(caught, uncaught); + } + + private synchronized List> replace(List next) throws Failure, ConnectedVms.Unsupported { + subscribe(); + if (StreamCommand.silencing(vm)) { + deferred = next; + return states(next, "deferred"); + } + deferred = null; + return apply(next); + } + + private synchronized void applyDeferred() { + List next = deferred; + if (next == null || StreamCommand.silencing(vm)) return; + deferred = null; + try { + apply(next); + } catch (VMDisconnectedException e) { + // nothing left to arm + } + } + + private void subscribe() throws Failure, ConnectedVms.Unsupported { + if (subscription != null) return; + JavaDebugSessions.Hub hub = JavaDebugSessions.of(vm) + .orElseThrow(() -> new Failure("noSession", "java-debug registered no session for this VM (hotCodeReplace is never?)")); + subscription = hub.subscribe(this::onEvent, e -> { + // A failing listener only costs later class loads their requests. + }); + } + + private List> apply(List next) { + EventRequestManager erm = vm.eventRequestManager(); + List own = new ArrayList<>(); + for (EventRequest r : erm.exceptionRequests()) if (r.getProperty(PROPERTY) != null) own.add(r); + for (EventRequest r : erm.classPrepareRequests()) if (r.getProperty(PROPERTY) != null) own.add(r); + erm.deleteEventRequests(own); + specs = next; + javaDebugCaught = false; + javaDebugUncaught = false; + for (ExceptionRequest r : erm.exceptionRequests()) { + if (r.isEnabled() && r.exception() == null && r.getProperty(Silencer.OWN_PROPERTY) == null) { + javaDebugCaught |= r.notifyCaught(); + javaDebugUncaught |= r.notifyUncaught(); + } + } + List> out = new ArrayList<>(); + for (Spec spec : next) { + if (!spec.enabled() || (!spec.caught() && !spec.uncaught())) { + out.add(state(spec, "disabled")); + continue; + } + // A class loaded later, or by another class loader, gets its request when it is prepared. + ClassPrepareRequest prepare = erm.createClassPrepareRequest(); + prepare.addClassFilter(spec.className()); + prepare.putProperty(PROPERTY, spec); + prepare.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); + prepare.enable(); + List loaded = vm.classesByName(spec.className()); + for (ReferenceType type : loaded) arm(spec, type); + out.add(state(spec, loaded.isEmpty() ? "pending" : "armed")); + } + return out; + } + + private void arm(Spec spec, ReferenceType type) { + Flags flags = uncovered(spec, superclasses(type), javaDebugCaught, javaDebugUncaught, specs); + if (flags.none()) return; + ExceptionRequest r = vm.eventRequestManager().createExceptionRequest(type, flags.caught(), flags.uncaught()); + for (String pattern : spec.classFilters()) r.addClassFilter(pattern); + for (String pattern : spec.classExclusionFilters()) r.addClassExclusionFilter(pattern); + r.setSuspendPolicy(EventRequest.SUSPEND_EVENT_THREAD); + r.putProperty(PROPERTY, spec); + r.enable(); + } + + /** java-debug's event thread: the class-loading thread waits until this returns. */ + private synchronized void onEvent(JavaDebugSessions.HubEvent e) throws IllegalAccessException { + Event event = e.event(); + if (!(event instanceof ClassPrepareEvent prepared) || !(event.request() instanceof ClassPrepareRequest request)) return; + if (!(request.getProperty(PROPERTY) instanceof Spec spec) || !specs.contains(spec)) return; + // A request made now would be on inside the trace: the whole list is applied again after it. + if (StreamCommand.silencing(vm)) { + if (deferred == null) deferred = specs; + return; + } + arm(spec, prepared.referenceType()); + } + + private static List superclasses(ReferenceType type) { + List out = new ArrayList<>(); + for (ClassType t = type instanceof ClassType c ? c.superclass() : null; t != null; t = t.superclass()) out.add(t.name()); + return out; + } + + private synchronized void close() { + if (subscription != null) subscription.close(); + subscription = null; + } + + private static List> states(List specs, String state) { + List> out = new ArrayList<>(); + for (Spec spec : specs) out.add(state(spec, spec.enabled() ? state : "disabled")); + return Collections.unmodifiableList(out); + } + + private static Map state(Spec spec, String state) { + return Values.json("id", spec.id(), "state", state); + } +} diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/ExceptionCommand.java b/java/jvm-inspect/src/ai/openidea/jvminspect/ExceptionCommand.java new file mode 100644 index 000000000..97a733bf9 --- /dev/null +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/ExceptionCommand.java @@ -0,0 +1,46 @@ +package ai.openidea.jvminspect; + +import ai.openidea.jvminspect.InspectCommand.Failure; +import ai.openidea.jvminspect.VmSelector.Target; +import ai.openidea.jvminspect.VmSelector.VmInfo; +import com.sun.jdi.VMDisconnectedException; +import com.sun.jdi.VirtualMachine; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.jdt.ls.core.internal.IDelegateCommandHandler; + +/** + * {@code openidea.jvm.exceptions.set [target, {breakpoints}]}: the VM's exception breakpoints on a + * chosen class (see {@link ExceptionBreakpoints}). Replies have the shape of {@link InspectCommand}'s. + */ +public final class ExceptionCommand implements IDelegateCommandHandler { + @Override + public Object executeCommand(String command, List arguments, IProgressMonitor monitor) { + try { + List vms = InspectCommand.connected(); + Set live = Collections.newSetFromMap(new IdentityHashMap<>()); + for (VmInfo v : vms) live.add(v.vm()); + ExceptionBreakpoints.forgetGone(live); + VirtualMachine vm = InspectCommand.select(vms, Target.of(arguments.get(0))); + List specs = new ArrayList<>(); + Object list = ((Map) arguments.get(1)).get("breakpoints"); + if (list instanceof List items) { + for (Object item : items) specs.add(ExceptionBreakpoints.Spec.of(item)); + } + return InspectCommand.ok(ExceptionBreakpoints.set(vm, specs)); + } catch (Failure e) { + return InspectCommand.error(e.code, e.getMessage()); + } catch (ConnectedVms.Unsupported e) { + return InspectCommand.error("unsupported", e.getMessage()); + } catch (org.eclipse.jdi.TimeoutException e) { + return InspectCommand.error("timedOut", String.valueOf(e.getMessage())); + } catch (VMDisconnectedException e) { + return InspectCommand.error("vmNotFound", "the VM disconnected"); + } + } +} diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java b/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java index 4bf0ed2f3..cf0afa1c9 100644 --- a/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/RealRunTrace.java @@ -550,15 +550,16 @@ final class RealRunTrace { * Worker, before the trace parks on a terminal that threw. The client's step-out ends in the * program's catch, but an exception nothing catches ends the thread, with no stop left to read the * records in. This request stops the thread at that throw instead: java-debug reports every - * exception event as a stop. Not when an enabled request of java-debug's already stops there, - * since the throw would then be reported twice. + * exception event as a stop. Not when an enabled request of java-debug's, or an exception breakpoint + * without class filters, already stops there, since the throw would then be reported twice. */ private void watchUncaught(ObjectReference exception) { try { EventRequestManager manager = vm.eventRequestManager(); ReferenceType type = exception.referenceType(); for (ExceptionRequest r : manager.exceptionRequests()) { - if (r.isEnabled() && r.notifyUncaught() && r.getProperty(Silencer.OWN_PROPERTY) == null && covers(r.exception(), type)) { + if (r.isEnabled() && r.notifyUncaught() && r.getProperty(Silencer.OWN_PROPERTY) == null && covers(r.exception(), type) + && ExceptionBreakpoints.coversWholeType(r)) { return; } } @@ -789,6 +790,17 @@ final class RealRunTrace { } } } + ExceptionBreakpoints.traceEnded(vm); + } + + /** Some of the user's breakpoints are switched off for the trace. */ + boolean silencing() { + synchronized (silenceLock) { + for (Silencer s : silencers) { + if (s.size() > 0) return true; + } + return false; + } } /** diff --git a/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java b/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java index d1f8d3dbd..cec78b569 100644 --- a/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java +++ b/java/jvm-inspect/src/ai/openidea/jvminspect/StreamCommand.java @@ -150,6 +150,15 @@ public final class StreamCommand implements IDelegateCommandHandler { } } + /** The VM's trace has the user's breakpoints switched off. */ + static boolean silencing(VirtualMachine vm) { + RealRunTrace trace; + synchronized (TRACES) { + trace = TRACES.get(vm); + } + return trace != null && trace.silencing(); + } + private static RealRunTrace trace(VirtualMachine vm, Map args) throws Failure { long id = number(args, "traceId").longValue(); synchronized (TRACES) { diff --git a/java/jvm-inspect/tests/SelfTest.java b/java/jvm-inspect/tests/SelfTest.java index d10ef2246..a9575e9c1 100644 --- a/java/jvm-inspect/tests/SelfTest.java +++ b/java/jvm-inspect/tests/SelfTest.java @@ -45,6 +45,9 @@ public final class SelfTest { sessions_found_by_vm(); sessions_missing_field_is_unsupported(); hub_listener_parks_and_failures_are_swallowed(); + exception_spec_parsed_from_gson_json(); + exception_flags_leave_out_what_another_request_reports(); + exception_request_with_class_filters_covers_no_whole_type(); } /** Stands in for java-debug's provider: its manager has no {@code connectedVMs}. */ @@ -353,6 +356,70 @@ public final class SelfTest { pass("plan_parsed_from_gson_json"); } + static void exception_spec_parsed_from_gson_json() { + Map json = new LinkedHashMap<>(); + json.put("id", "b1"); + json.put("className", "java.lang.IllegalStateException"); + json.put("caught", true); + json.put("uncaught", false); + json.put("enabled", true); + json.put("classFilters", List.of("com.acme.*")); + ExceptionBreakpoints.Spec spec = ExceptionBreakpoints.Spec.of(json); + check(spec.id().equals("b1") && spec.className().equals("java.lang.IllegalStateException"), "id and class: " + spec); + check(spec.caught() && !spec.uncaught() && spec.enabled(), "flags: " + spec); + check(spec.classFilters().equals(List.of("com.acme.*")) && spec.classExclusionFilters().isEmpty(), "filters: " + spec); + check(spec.hasClassFilters(), "a spec with an include pattern has class filters"); + json.remove("className"); + try { + ExceptionBreakpoints.Spec.of(json); + throw new AssertionError("a spec without a class must be rejected"); + } catch (IllegalArgumentException e) { + check(e.getMessage().contains("className"), "detail names the member: " + e.getMessage()); + } + pass("exception_spec_parsed_from_gson_json"); + } + + static void exception_flags_leave_out_what_another_request_reports() { + ExceptionBreakpoints.Spec ise = spec("ise", "java.lang.IllegalStateException", true, true, true, List.of()); + List iseSupers = List.of("java.lang.RuntimeException", "java.lang.Exception", "java.lang.Throwable", "java.lang.Object"); + ExceptionBreakpoints.Flags all = ExceptionBreakpoints.uncovered(ise, iseSupers, false, false, List.of(ise)); + check(all.caught() && all.uncaught(), "nothing else reports it: both flags stay: " + all); + ExceptionBreakpoints.Flags anyCaught = ExceptionBreakpoints.uncovered(ise, iseSupers, true, false, List.of(ise)); + check(!anyCaught.caught() && anyCaught.uncaught(), "java-debug's caught filter reports every caught throw: " + anyCaught); + check(ExceptionBreakpoints.uncovered(ise, iseSupers, true, true, List.of(ise)).none(), "both java-debug filters: no request"); + ExceptionBreakpoints.Spec runtime = spec("rte", "java.lang.RuntimeException", true, false, true, List.of()); + ExceptionBreakpoints.Flags bySuper = ExceptionBreakpoints.uncovered(ise, iseSupers, false, false, List.of(runtime, ise)); + check(!bySuper.caught() && bySuper.uncaught(), "a breakpoint on a superclass reports the caught throws: " + bySuper); + ExceptionBreakpoints.Spec filtered = spec("f", "java.lang.RuntimeException", true, true, true, List.of("com.acme.*")); + ExceptionBreakpoints.Spec off = spec("off", "java.lang.RuntimeException", true, true, false, List.of()); + ExceptionBreakpoints.Flags narrow = ExceptionBreakpoints.uncovered(ise, iseSupers, false, false, List.of(filtered, off, ise)); + check(narrow.caught() && narrow.uncaught(), "a filtered or disabled superclass breakpoint covers nothing: " + narrow); + ExceptionBreakpoints.Spec twin = spec("twin", "java.lang.IllegalStateException", true, true, true, List.of()); + check(ExceptionBreakpoints.uncovered(twin, iseSupers, false, false, List.of(ise, twin)).none(), "the later of two equal breakpoints adds nothing"); + ExceptionBreakpoints.Flags first = ExceptionBreakpoints.uncovered(ise, iseSupers, false, false, List.of(ise, twin)); + check(first.caught() && first.uncaught(), "the earlier of two equal breakpoints keeps its flags: " + first); + ExceptionBreakpoints.Spec filteredIse = spec("fi", "java.lang.IllegalStateException", true, true, true, List.of("com.acme.*")); + check(ExceptionBreakpoints.uncovered(filteredIse, iseSupers, false, false, List.of(filteredIse, twin)).none(), + "an unfiltered breakpoint on the same class covers a filtered one before it"); + pass("exception_flags_leave_out_what_another_request_reports"); + } + + static void exception_request_with_class_filters_covers_no_whole_type() { + EventRequest plain = request(ExceptionRequest.class, true, false); + plain.putProperty(ExceptionBreakpoints.PROPERTY, spec("a", "java.lang.RuntimeException", true, true, true, List.of())); + EventRequest filtered = request(ExceptionRequest.class, true, false); + filtered.putProperty(ExceptionBreakpoints.PROPERTY, spec("b", "java.lang.RuntimeException", true, true, true, List.of("com.acme.*"))); + EventRequest javaDebugs = request(ExceptionRequest.class, true, false); + check(ExceptionBreakpoints.coversWholeType(plain), "an exception breakpoint without filters covers its type"); + check(!ExceptionBreakpoints.coversWholeType(filtered), "one with class filters may miss a throw"); + check(ExceptionBreakpoints.coversWholeType(javaDebugs), "java-debug's own requests have no filters the app sets"); + pass("exception_request_with_class_filters_covers_no_whole_type"); + } + + private static ExceptionBreakpoints.Spec spec(String id, String type, boolean caught, boolean uncaught, boolean enabled, List include) { + return new ExceptionBreakpoints.Spec(id, type, caught, uncaught, enabled, include, List.of()); + } + static void sessions_found_by_vm() throws Exception { Object vmA = new Object(); Object vmB = new Object(); diff --git a/java/jvm-inspect/tests/exceptions.py b/java/jvm-inspect/tests/exceptions.py new file mode 100644 index 000000000..b35de3abf --- /dev/null +++ b/java/jvm-inspect/tests/exceptions.py @@ -0,0 +1,248 @@ +"""Drive the exception breakpoint command inside a real JDT LS with java-debug. + +Usage: python3 -I exceptions.py /path/to/jdtls /path/to/com.microsoft.java.debug.plugin-.jar \ + [--bundle /path/to/openidea-jvm-inspect.jar] + +JDT LS and the debuggees run on the `java` on PATH (JDK 25 for 1.63.0). The breakpoints are set the +way ide-dap sets them: after `initialized`, `setExceptionBreakpoints`, then this command, then +`configurationDone`, and the command again after every later `setExceptionBreakpoints`. Prints +OK/FAIL per check. +""" +import json +import pathlib +import subprocess +import sys +import tempfile +import threading +import time + +sys.path.append(str(pathlib.Path(__file__).resolve().parent)) +sys.dont_write_bytecode = True # no __pycache__ in the source tree +from jdtls_harness import check, debug_session, finish, free_port, kill, report, start_jdtls, stop_jdtls, wait_ready # noqa: E402 + +COMMAND = 'openidea.jvm.exceptions.set' +# `// @name` names a line for `line('name')`. +PROGRAM = '''public class Exc { + static class Lazy { static void boom() { throw new Boom("lazy"); } } // @boom + static class Boom extends RuntimeException { Boom(String m) { super("boom: " + m); } } // @message + public static void main(String[] a) throws Exception { + try { throw new IllegalStateException("first line"); } catch (IllegalStateException e) { } // @first + try { Integer.parseInt("x"); } catch (NumberFormatException e) { } + try { Lazy.boom(); } catch (Boom e) { } + try { Lazy.boom(); } catch (Boom e) { } + try { Filtered.run(); } catch (UnsupportedOperationException e) { } + try { throw new IllegalStateException("second"); } catch (IllegalStateException e) { } // @second + try { Filtered.run(); } catch (UnsupportedOperationException e) { } + try { throw new IllegalStateException("third"); } catch (IllegalStateException e) { } // @third + throw new IllegalArgumentException("uncaught"); // @uncaught + } +} +class Filtered { static void run() { throw new UnsupportedOperationException("filtered"); } } // @filtered +''' + +args = sys.argv[1:] +bundle = pathlib.Path(__file__).resolve().parents[1] / 'openidea-jvm-inspect.jar' +if '--bundle' in args: + i = args.index('--bundle') + bundle = pathlib.Path(args[i + 1]).resolve() + del args[i:i + 2] +home, java_debug = (pathlib.Path(a).resolve() for a in args[:2]) +# resolved: on macOS the temp dir is under the /var symlink, and JDT LS matches canonical URIs +work = pathlib.Path(tempfile.mkdtemp(prefix='openidea-jvm-exceptions-')).resolve() +project = work / 'project' +(project / 'src').mkdir(parents=True) +source = project / 'src' / 'Exc.java' +source.write_text(PROGRAM) +classes = work / 'classes' +subprocess.run(['javac', '-g', '-d', str(classes), str(source)], check=True) +jdtls = lsp = None +jvms, launched = [], [] + + +def line(name): + return next(i for i, t in enumerate(PROGRAM.splitlines(), 1) if t.rstrip().endswith('// @' + name)) + + +def bp(id, class_name, caught=True, uncaught=True, enabled=True, include=(), exclude=()): + return {'id': id, 'className': class_name, 'caught': caught, 'uncaught': uncaught, 'enabled': enabled, + 'classFilters': list(include), 'classExclusionFilters': list(exclude)} + + +def arm(target, *breakpoints): + reply = lsp.command(COMMAND, target, {'breakpoints': list(breakpoints)}) + if 'ok' not in reply: + raise AssertionError(f'{COMMAND}: {reply}') + return {s['id']: s['state'] for s in reply['ok']} + + +def stop(d, what, timeout=30): + e = d.wait_event(lambda e: e['event'] in ('stopped', 'terminated'), timeout, what) + if e['event'] == 'terminated': + raise AssertionError(f'{what}: the debuggee terminated') + thread = e['body']['threadId'] + frames = d.request('stackTrace', {'threadId': thread})['body']['stackFrames'] + top = frames[0] if frames else {} + info = d.request('exceptionInfo', {'threadId': thread}).get('body', {}) + return e['body'], thread, top, info + + +def no_more_stops(d, seconds=2.0): + try: + d.wait_event(lambda e: e['event'] == 'stopped', seconds, 'stopped') + return False + except TimeoutError: + return True + + +def expect(d, name, reason_line, exception, what): + """The next stop is a java-debug exception stop at `reason_line` for `exception`, and the only one.""" + body, thread, top, info = stop(d, what) + check(f'{name}: {exception} stops at line {reason_line}', + body['reason'] == 'exception' and top['line'] == reason_line and info['exceptionId'] == exception, + (body, top.get('name'), top.get('line'), info)) + check(f'{name}: one stopped event', no_more_stops(d)) + return thread, info + + +def configure(d, target, *breakpoints, filters=()): + d.wait_event(lambda e: e['event'] == 'initialized', 60, 'initialized') + d.request('setExceptionBreakpoints', {'filters': list(filters)}) + states = arm(target, *breakpoints) + d.request('configurationDone') + return states + + +def launch_case(project_name, classpaths): + d = debug_session(lsp, 'openidea-jvm-exceptions') + d.start('launch', {'mainClass': 'Exc', 'projectName': project_name, 'modulePaths': [], 'classPaths': classpaths, + 'cwd': str(project), 'console': 'internalConsole', 'shortenCommandLine': 'none'}) + pid = d.wait_event(lambda e: e['event'] == 'processid', 60, 'processid')['body']['processId'] + launched.append(pid) + target = {'pid': pid, 'host': None, 'port': None, 'generation': 0} + exc_filter = 'Exc' + states = configure(d, target, + bp('ise', 'java.lang.IllegalStateException', uncaught=False, include=[exc_filter]), + bp('nfe', 'java.lang.NumberFormatException', enabled=False), + bp('boom', 'Exc$Boom'), + bp('uoe', 'java.lang.UnsupportedOperationException', exclude=['Filtered']), + bp('iae', 'java.lang.IllegalArgumentException', caught=False)) + print(' states before configurationDone:', json.dumps(states), flush=True) + # The JDK may have loaded a java.lang class before main; Exc$Boom is loaded by `Lazy.boom()` only. + check('launch: states before the program runs', states['nfe'] == 'disabled' and states['boom'] == 'pending' + and all(states[k] in ('pending', 'armed') for k in ('ise', 'uoe', 'iae')), states) + thread, _ = expect(d, 'launch start-up', line('first'), 'java.lang.IllegalStateException', 'first line') + + # java-debug re-applying its filters deletes every exception request; the client arms again. + d.request('setExceptionBreakpoints', {'filters': []}) + states = arm(target, bp('ise', 'java.lang.IllegalStateException', uncaught=False, include=[exc_filter]), + bp('nfe', 'java.lang.NumberFormatException', enabled=False), bp('boom', 'Exc$Boom'), + bp('uoe', 'java.lang.UnsupportedOperationException', exclude=['Filtered']), + bp('iae', 'java.lang.IllegalArgumentException', caught=False)) + check('launch: re-armed after setExceptionBreakpoints', states['ise'] == 'armed' and states['boom'] == 'pending', states) + d.request('continue', {'threadId': thread}) + thread, _ = expect(d, 'launch lazily loaded', line('boom'), 'Exc$Boom', 'boom') + d.request('continue', {'threadId': thread}) + thread, _ = expect(d, 'launch loaded class, second throw', line('boom'), 'Exc$Boom', 'boom again') + d.request('continue', {'threadId': thread}) + thread, _ = expect(d, 'launch class filter', line('second'), 'java.lang.IllegalStateException', 'second (UOE excluded in Filtered)') + + # A breakpoint on the superclass and the ISE one both report the caught `third`: one stop. + rte = bp('rte', 'java.lang.RuntimeException', uncaught=False) + states = arm(target, bp('ise', 'java.lang.IllegalStateException', uncaught=False, include=[exc_filter]), rte) + check('launch: superclass breakpoint armed', states == {'ise': 'armed', 'rte': 'armed'}, states) + d.request('continue', {'threadId': thread}) + thread, _ = expect(d, 'launch superclass', line('filtered'), 'java.lang.UnsupportedOperationException', 'UOE by RuntimeException') + d.request('continue', {'threadId': thread}) + thread, _ = expect(d, 'launch overlapping own breakpoints', line('third'), 'java.lang.IllegalStateException', 'third') + + # java-debug's own "Uncaught Exceptions" and the IAE breakpoint both report the last throw: one stop. + d.request('setExceptionBreakpoints', {'filters': ['uncaught']}) + states = arm(target, bp('iae', 'java.lang.IllegalArgumentException', caught=False)) + check('launch: covered by java-debug filter is still armed', states == {'iae': 'armed'}, states) + d.request('continue', {'threadId': thread}) + thread, _ = expect(d, 'launch overlapping java-debug filter', line('uncaught'), 'java.lang.IllegalArgumentException', 'uncaught') + d.request('continue', {'threadId': thread}) + d.wait_event(lambda e: e['event'] in ('terminated', 'exited'), 30, 'end') + d.request('disconnect', {'terminateDebuggee': True}, 20) + + +def hot_swap_case(project_name, classpaths): + """Hot swap of the exception class itself while its request is on it. Last: it edits the source.""" + d = debug_session(lsp, 'openidea-jvm-exceptions') + d.start('launch', {'mainClass': 'Exc', 'projectName': project_name, 'modulePaths': [], 'classPaths': classpaths, + 'cwd': str(project), 'console': 'internalConsole', 'shortenCommandLine': 'none'}) + pid = d.wait_event(lambda e: e['event'] == 'processid', 60, 'processid')['body']['processId'] + launched.append(pid) + target = {'pid': pid, 'host': None, 'port': None, 'generation': 0} + configure(d, target, bp('boom', 'Exc$Boom')) + thread, _ = expect(d, 'hot swap: before', line('boom'), 'Exc$Boom', 'boom') + text = PROGRAM.replace('"boom: "', '"BOOM: "') + lsp.notify('textDocument/didChange', {'textDocument': {'uri': source.as_uri(), 'version': 2}, + 'contentChanges': [{'text': text}]}) + source.write_text(text) + lsp.notify('textDocument/didSave', {'textDocument': {'uri': source.as_uri()}, 'text': text}) + lsp.request('java/buildWorkspace', False, 120) + # What the app's Reload Changed Classes sends (DebugManager::redefine_classes). + r = d.request('redefineClasses', {}, 60) + check('hot swap: java-debug redefines Exc$Boom', r['success'] and 'Exc$Boom' in r.get('body', {}).get('changedClasses', []), r) + # java-debug pops the frames of redefined classes and re-enters them (a `step` stop), so the throw runs again. + swapped = [] + for _ in range(4): + d.request('continue', {'threadId': thread}) + try: + body, thread, top, info = stop(d, 'after hot swap', 10) + except (TimeoutError, AssertionError): + break + print(' after hot swap:', body['reason'], top.get('name'), top.get('line'), info.get('description'), flush=True) + if body['reason'] == 'exception' and info.get('exceptionId') == 'Exc$Boom': + swapped.append(info.get('description', '')) + break + check('hot swap: the Exc$Boom breakpoint still stops, in the new constructor', + bool(swapped) and all('BOOM: lazy' in s for s in swapped), swapped) + d.request('disconnect', {'terminateDebuggee': True}, 20) + + +def attach_case(project_name): + port = free_port() + p = subprocess.Popen(['java', f'-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:{port}', + '-cp', str(classes), 'Exc'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) + jvms.append(p) + p.stdout.readline() # "Listening for transport dt_socket ..." + threading.Thread(target=lambda: [None for _ in p.stdout], daemon=True).start() + d = debug_session(lsp, 'openidea-jvm-exceptions') + d.start('attach', {'hostName': '127.0.0.1', 'port': port, 'timeout': 30000, 'projectName': project_name}) + target = {'pid': None, 'host': 'localhost', 'port': port, 'generation': 0} + states = configure(d, target, bp('ise', 'java.lang.IllegalStateException', uncaught=False)) + check('attach: pending before the program runs', states == {'ise': 'pending'}, states) + expect(d, 'attach start-up', line('first'), 'java.lang.IllegalStateException', 'first line') + d.request('disconnect', {'terminateDebuggee': True}, 20) + + +try: + wanted = [COMMAND, 'vscode.java.startDebugSession'] + jdtls, lsp, registered = start_jdtls(home, work, project, [java_debug, bundle], wanted) + if check('JDT LS registers the exception command and java-debug', all(c in registered for c in wanted), registered): + wait_ready(lsp) + lsp.notify('textDocument/didOpen', {'textDocument': {'uri': source.as_uri(), 'languageId': 'java', 'version': 1, + 'text': PROGRAM}}) + lsp.command('vscode.java.updateDebugSettings', json.dumps({'hotCodeReplace': 'auto', 'logLevel': 'WARNING'})) + for _ in range(30): + main = lsp.command('vscode.java.resolveMainClass', project.as_uri()) + if main: + break + time.sleep(2) + project_name = main[0].get('projectName') + _, classpaths = lsp.command('vscode.java.resolveClasspath', 'Exc', project_name) + for case in (lambda: launch_case(project_name, classpaths), lambda: attach_case(project_name), + lambda: hot_swap_case(project_name, classpaths)): + try: + case() + except Exception as e: + report('FAIL', 'case', repr(e)) +except Exception as e: + report('FAIL', 'harness', repr(e)) +finally: + kill(jvms, launched) + if lsp: + stop_jdtls(jdtls, lsp) +sys.exit(finish(work)) diff --git a/java/jvm-inspect/tests/stream.py b/java/jvm-inspect/tests/stream.py index c27802ab3..81208fbd9 100644 --- a/java/jvm-inspect/tests/stream.py +++ b/java/jvm-inspect/tests/stream.py @@ -1095,6 +1095,61 @@ def real_run_uncaught_throw_user_filter(): dbg.end() +def exception_breakpoints(dbg, *breakpoints): + """`openidea.jvm.exceptions.set`; returns breakpoint id → state.""" + return {s['id']: s['state'] for s in ok(lsp.command('openidea.jvm.exceptions.set', dbg.target, {'breakpoints': list(breakpoints)}))} + + +def exception_breakpoint(id, class_name, exclude=()): + return {'id': id, 'className': class_name, 'caught': True, 'uncaught': True, 'enabled': True, + 'classFilters': [], 'classExclusionFilters': list(exclude)} + + +@case +def real_run_uncaught_throw_exception_breakpoint(): + # A caught+uncaught breakpoint on the thrown class: silenced while the terminal runs (a stop inside + # its invoke would hang the trace), then the uncaught throw stops once, not once per request. + dbg = real('U') + try: + states = exception_breakpoints(dbg, exception_breakpoint('ae', 'java.lang.ArithmeticException')) + check('U-class: armed or pending', states['ae'] in ('armed', 'pending'), states) + trace, state, _ = run_until_parked(dbg, 'U', steps=(spec('map', 1),), step_kinds=('sync',)) + check('U-class: parked after the lambda threw', state['state'] == 'parked', state) + uncaught_stop(dbg, 'U-class', trace, 'java.lang.ArithmeticException') + finally: + dbg.end() + + +@case +def real_run_uncaught_throw_filtered_exception_breakpoint(): + # The breakpoint's class filter leaves out where the lambda throws: the trace still watches the throw. + dbg = real('U') + try: + exception_breakpoints(dbg, exception_breakpoint('ae', 'java.lang.ArithmeticException', exclude=['Real'])) + trace, state, _ = run_until_parked(dbg, 'U', steps=(spec('map', 1),), step_kinds=('sync',)) + check('U-class-filtered: parked after the lambda threw', state['state'] == 'parked', state) + uncaught_stop(dbg, 'U-class-filtered', trace, 'java.lang.ArithmeticException') + finally: + dbg.end() + + +@case +def exception_breakpoints_set_during_a_trace_wait_for_its_end(): + # Set while the trace silences breakpoints: nothing is armed inside it; the list is applied once the + # breakpoints are back on, before the trace decides whether to watch the uncaught throw itself. + dbg = real('U') + try: + trace = ok(arm(dbg, at='U', steps=(spec('map', 1),), step_kinds=('sync',)))['traceId'] + states = exception_breakpoints(dbg, exception_breakpoint('ae', 'java.lang.ArithmeticException')) + check('U-deferred: deferred while the trace silences', states == {'ae': 'deferred'}, states) + resume(dbg) + state = wait_until_done(dbg, trace) + check('U-deferred: parked after the lambda threw', state['state'] == 'parked', state) + uncaught_stop(dbg, 'U-deferred', trace, 'java.lang.ArithmeticException') + finally: + dbg.end() + + @case def real_run_uncaught_abort(): dbg = real('Ua') diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index c4cd38e92..aa7c1c7c3 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -186,6 +186,7 @@ debug_sessions always project_host bin debug_set_breakpoints trusted project_host bindings async debug_set_data_breakpoints trusted project_host bindings async debug_set_exception_breakpoints trusted project_host bindings async +debug_set_exception_class_breakpoints trusted project_host bindings async debug_set_function_breakpoints trusted project_host bindings async debug_set_variable trusted project_host bindings async debug_stack_trace trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index c65b82699..19f210410 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -456,6 +456,8 @@ export const commands = { /** Field watchpoints; states aligned with `breakpoints`. */ debugSetDataBreakpoints: (breakpoints: DataBreakpoint[]) => typedError(__TAURI_INVOKE("debug_set_data_breakpoints", { breakpoints })), debugSetExceptionBreakpoints: (choices: { [key in string]: boolean }) => typedError(__TAURI_INVOKE("debug_set_exception_breakpoints", { choices })), + /** Exception breakpoints on chosen classes (all sessions that take them, and later ones). */ + debugSetExceptionClassBreakpoints: (breakpoints: ExceptionClassBreakpoint[]) => typedError(__TAURI_INVOKE("debug_set_exception_class_breakpoints", { breakpoints })), /** Method breakpoints (all files); states aligned with `breakpoints`. */ debugSetFunctionBreakpoints: (breakpoints: FunctionBreakpoint[]) => typedError(__TAURI_INVOKE("debug_set_function_breakpoints", { breakpoints })), debugSetVariable: (session: DebugSessionId, container: number, name: string, evaluateName: string | null, frameId: number | null, value: string) => typedError(__TAURI_INVOKE("debug_set_variable", { session, container, name, evaluateName, frameId, value })), @@ -5973,6 +5975,28 @@ export type EventKind = "document-changed" | "websocket-ready" | "file-closed" | /** Problems of the window's files changed (a language server or a report). */ "problems-changed" | "scheduled"; +export type ExceptionClassBreakpoint = { + id: string, + /** Fully qualified binary name (`com.acme.Outer$Inner`); its subclasses stop too. */ + className: string, + caught: boolean, + uncaught: boolean, + enabled: boolean, + /** Patterns (`com.acme.*`, `*Test`, a full name) for the class whose code throws. */ + classFilters: string[], + classExclusionFilters: string[], +}; + +/** What a session's exception class breakpoints can do. */ +export type ExceptionClassSupport = { + /** Whose class names the session takes: `java`. */ + family: string, + condition: boolean, + classFilters: boolean, + /** Filters on the class whose code catches the exception. */ + catchFilters: boolean, +}; + /** An exception breakpoint filter offered by an adapter (`exceptionBreakpointFilters`). */ export type ExceptionFilter = { filter: string, @@ -11313,6 +11337,8 @@ export type SessionExceptionFilters = { session: DebugSessionId, adapter: string, filters: ExceptionFilter[], + /** Set when the session takes exception breakpoints on a chosen class. */ + classes: ExceptionClassSupport | null, }; /** A live session, as listed by [`DebugManager::sessions`]. */ diff --git a/src/features/debugger/__tests__/breakpointsDialog.test.tsx b/src/features/debugger/__tests__/breakpointsDialog.test.tsx index 1db6f7dd4..72ae830a2 100644 --- a/src/features/debugger/__tests__/breakpointsDialog.test.tsx +++ b/src/features/debugger/__tests__/breakpointsDialog.test.tsx @@ -2,6 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { act, cleanup, fireEvent, render, screen, within } from "@testing-library/react"; import { provideEditorService } from "@/workbench/contributions"; import { addBreakpoint, useBreakpoints } from "../breakpoints/store"; +import { useExceptionBreakpoints } from "../breakpoints/exceptions"; +import { loadExceptionClasses, removeAllExceptionClasses, useExceptionClasses } from "../breakpoints/exceptionClasses"; import { DebuggerOverlays } from "../ui/Overlays"; import { useOverlays } from "../ui/popoverStore"; @@ -57,4 +59,57 @@ describe("the Breakpoints dialog", () => { clickRow("main.py:7", 1); expect(breakpointAt(2).condition).toBe("value == 3"); }); + + describe("Java exception breakpoints", () => { + beforeEach(() => { + loadExceptionClasses("/p"); + removeAllExceptionClasses(); + useExceptionBreakpoints.setState({ root: "/p", choices: {} }); + }); + + const list = () => within(dialog()).getByRole("listbox", { name: "All breakpoints" }); + + it("shows java-debug's filters as Any exception, under the choices they had", () => { + render(); + expect(within(list()).getByText("Java Exception Breakpoints")).toBeTruthy(); + expect(within(dialog()).queryByRole("group", { name: "java-debug exception filters" })).toBeNull(); + fireEvent.click(within(list()).getByRole("checkbox", { name: "Enable Any exception" })); + expect(useExceptionBreakpoints.getState().choices).toEqual({ + "java-debug:caught": true, + "java-debug:uncaught": true, + }); + fireEvent.mouseDown(within(list()).getByRole("option", { name: /Any exception/ }), { button: 0 }); + const suspend = within(dialog()).getByRole("group", { name: "Suspend on" }); + fireEvent.click(within(suspend).getByRole("checkbox", { name: "Caught exception" })); + expect(useExceptionBreakpoints.getState().choices["java-debug:caught"]).toBe(false); + }); + + it("adds one for a class, with its class filters, and IDEA's other fields disabled", () => { + render(); + fireEvent.click(within(dialog()).getByRole("button", { name: "Add Java Exception Breakpoint" })); + fireEvent.change(within(dialog()).getByLabelText("Exception class name"), { + target: { value: " com.acme.Boom " }, + }); + const patterns = within(dialog()).getByLabelText("Class filter patterns") as HTMLInputElement; + expect(patterns.disabled).toBe(true); + fireEvent.click(within(dialog()).getByRole("checkbox", { name: "Class filters" })); + fireEvent.change(patterns, { target: { value: "com.acme.* -*Test" } }); + for (const field of ["Condition", "Catch class filters"]) { + expect((within(dialog()).getByRole("checkbox", { name: field }) as HTMLInputElement).disabled).toBe(true); + } + for (const input of ["Condition expression", "Catch class filter patterns"]) { + expect((within(dialog()).getByLabelText(input) as HTMLInputElement).disabled).toBe(true); + } + fireEvent.click(within(dialog()).getByRole("button", { name: "Done" })); + expect(useExceptionClasses.getState().list).toEqual([ + expect.objectContaining({ + className: "com.acme.Boom", + caught: true, + uncaught: true, + classFilters: "com.acme.* -*Test", + classFiltersEnabled: true, + }), + ]); + }); + }); }); diff --git a/src/features/debugger/__tests__/exceptionClasses.test.ts b/src/features/debugger/__tests__/exceptionClasses.test.ts new file mode 100644 index 000000000..3dca89e10 --- /dev/null +++ b/src/features/debugger/__tests__/exceptionClasses.test.ts @@ -0,0 +1,104 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { + addExceptionClass, + loadExceptionClasses, + parseClassFilters, + removeAllExceptionClasses, + removeExceptionClass, + sanitizeExceptionClasses, + toExceptionClassBreakpoints, + updateExceptionClass, + useExceptionClasses, +} from "../breakpoints/exceptionClasses"; + +beforeEach(() => { + localStorage.clear(); + loadExceptionClasses("/p"); + removeAllExceptionClasses(); +}); + +const names = () => useExceptionClasses.getState().list.map((b) => b.className); + +describe("exception breakpoints on a chosen class", () => { + it("are kept per project", () => { + const bp = addExceptionClass("java.lang.IllegalStateException"); + expect(bp).toMatchObject({ caught: true, uncaught: true, enabled: true, classFiltersEnabled: false }); + updateExceptionClass(bp.id, { caught: false, classFilters: "com.acme.*", classFiltersEnabled: true }); + loadExceptionClasses("/q"); + expect(names()).toEqual([]); + loadExceptionClasses("/p"); + expect(useExceptionClasses.getState().list).toEqual([ + { ...bp, caught: false, classFilters: "com.acme.*", classFiltersEnabled: true }, + ]); + removeExceptionClass(bp.id); + loadExceptionClasses("/p"); + expect(names()).toEqual([]); + }); + + it("splits class filters into included and excluded patterns", () => { + expect(parseClassFilters(" com.acme.* -*Test,org.Foo; -com.acme.gen.* ")).toEqual({ + include: ["com.acme.*", "org.Foo"], + exclude: ["*Test", "com.acme.gen.*"], + }); + expect(parseClassFilters("- ")).toEqual({ include: [], exclude: [] }); + }); + + it("send their filters only when on, muting, and no breakpoint without a class", () => { + const a = addExceptionClass("com.acme.Boom"); + updateExceptionClass(a.id, { classFilters: "com.acme.* -*Test", classFiltersEnabled: true, uncaught: false }); + const b = addExceptionClass(" java.io.IOException "); + updateExceptionClass(b.id, { classFilters: "com.acme.*", enabled: false }); + addExceptionClass(" "); + const { list } = useExceptionClasses.getState(); + expect(toExceptionClassBreakpoints(list, false)).toEqual([ + { + id: a.id, + className: "com.acme.Boom", + caught: true, + uncaught: false, + enabled: true, + classFilters: ["com.acme.*"], + classExclusionFilters: ["*Test"], + }, + { + id: b.id, + className: "java.io.IOException", + caught: true, + uncaught: true, + enabled: false, + classFilters: [], + classExclusionFilters: [], + }, + ]); + expect(toExceptionClassBreakpoints(list, true).map((x) => x.enabled)).toEqual([false, false]); + }); + + it("drop sanitized junk", () => { + expect( + sanitizeExceptionClasses([ + { className: "a.B", caught: false, classFilters: 3 }, + { caught: true }, + "x", + { id: "k", className: "c.D", uncaught: false, enabled: false, classFilters: "c.*", classFiltersEnabled: true }, + ]), + ).toEqual([ + expect.objectContaining({ + className: "a.B", + caught: false, + uncaught: true, + enabled: true, + classFilters: "", + classFiltersEnabled: false, + }), + { + id: "k", + className: "c.D", + caught: true, + uncaught: false, + enabled: false, + classFilters: "c.*", + classFiltersEnabled: true, + }, + ]); + }); +}); diff --git a/src/features/debugger/__tests__/exceptions.test.ts b/src/features/debugger/__tests__/exceptions.test.ts index 833c76508..9cc3d61b7 100644 --- a/src/features/debugger/__tests__/exceptions.test.ts +++ b/src/features/debugger/__tests__/exceptions.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it } from "vitest"; import type { ExceptionFilter } from "@/platform/ipc"; import { + anyException, exceptionGroups, isFilterEnabled, mergeKnown, @@ -47,4 +48,14 @@ describe("exception breakpoints", () => { expect(sanitizeChoices([1])).toEqual({}); expect(sanitizeKnown({ x: [f("a"), { nope: 1 }], y: "z" })).toEqual({ x: [f("a")] }); }); + + it("reads Any exception from the choices java-debug's filters were stored under", () => { + const known = { "java-debug": [f("caught"), f("uncaught")] }; + expect(anyException(known, {})).toEqual({ caught: false, uncaught: false }); + expect(anyException(known, { "java-debug:caught": true, uncaught: true })).toEqual({ + caught: true, + uncaught: true, + }); + expect(anyException({}, { "java-debug:uncaught": true })).toEqual({ caught: false, uncaught: true }); + }); }); diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index 2c4a9f715..ea358e07f 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -30,6 +30,7 @@ import { useBreakpoints, } from "./breakpoints/store"; import { removeAllSpecial, specialAt, toggleFieldAt, toggleMethodAt } from "./breakpoints/special"; +import { removeAllExceptionClasses } from "./breakpoints/exceptionClasses"; import { fieldAt, methodAt } from "./breakpoints/symbols"; import { toggleBreakpointSmart } from "./breakpoints/toggle"; import { @@ -1105,6 +1106,7 @@ export function registerDebugActions(): () => void { run: () => { removeAllBreakpoints(); removeAllSpecial(); + removeAllExceptionClasses(); }, }, { diff --git a/src/features/debugger/breakpoints/exceptionClasses.ts b/src/features/debugger/breakpoints/exceptionClasses.ts new file mode 100644 index 000000000..4f152a8c5 --- /dev/null +++ b/src/features/debugger/breakpoints/exceptionClasses.ts @@ -0,0 +1,154 @@ +/** + * Exception breakpoints on a chosen class (IDEA's Java Exception Breakpoints). A project-wide + * list, persisted like method breakpoints and mirrored to the backend, which arms it in every + * session that takes it. + */ +import { create } from "zustand"; +import { useProject } from "@/platform/project"; +import { call, commands, isTauri, type ExceptionClassBreakpoint } from "@/platform/ipc"; +import { newBreakpointId } from "./model"; +import { useBreakpoints } from "./store"; + +export interface ExceptionClassEntry { + id: string; + /** Fully qualified binary name; its subclasses stop too. */ + className: string; + caught: boolean; + uncaught: boolean; + enabled: boolean; + /** As typed: patterns for the class whose code throws, `-` before the excluded ones. */ + classFilters: string; + classFiltersEnabled: boolean; +} + +interface ExceptionClassState { + root: string | null; + list: ExceptionClassEntry[]; +} + +export const useExceptionClasses = create(() => ({ root: null, list: [] })); + +const STORAGE_PREFIX = "openidea.debugger.exceptionClasses:"; + +export function sanitizeExceptionClasses(raw: unknown): ExceptionClassEntry[] { + if (!Array.isArray(raw)) return []; + return raw + .filter((x): x is Record => !!x && typeof x === "object" && typeof x.className === "string") + .map((x) => ({ + id: typeof x.id === "string" ? x.id : newBreakpointId(), + className: x.className as string, + caught: x.caught !== false, + uncaught: x.uncaught !== false, + enabled: x.enabled !== false, + classFilters: typeof x.classFilters === "string" ? x.classFilters : "", + classFiltersEnabled: x.classFiltersEnabled === true, + })); +} + +/** IDEA's class filter field: patterns split by spaces, commas or semicolons. */ +export function parseClassFilters(text: string): { include: string[]; exclude: string[] } { + const include: string[] = []; + const exclude: string[] = []; + for (const token of text.split(/[\s,;]+/)) { + if (token.startsWith("-")) { + if (token.length > 1) exclude.push(token.slice(1)); + } else if (token) include.push(token); + } + return { include, exclude }; +} + +/** The backend list; one without a class yet is left out, muting disables the rest. */ +export function toExceptionClassBreakpoints( + list: readonly ExceptionClassEntry[], + muted: boolean, +): ExceptionClassBreakpoint[] { + return list + .filter((b) => b.className.trim()) + .map((b) => { + const filters = b.classFiltersEnabled ? parseClassFilters(b.classFilters) : { include: [], exclude: [] }; + return { + id: b.id, + className: b.className.trim(), + caught: b.caught, + uncaught: b.uncaught, + enabled: b.enabled && !muted, + classFilters: filters.include, + classExclusionFilters: filters.exclude, + }; + }); +} + +let timer: ReturnType | undefined; + +function scheduleSync() { + clearTimeout(timer); + timer = setTimeout(() => void syncExceptionClasses(), 120); +} + +async function syncExceptionClasses() { + const { root, list } = useExceptionClasses.getState(); + if (!isTauri() || !root || useProject.getState().project?.trusted === false) return; + try { + await call( + commands.debugSetExceptionClassBreakpoints(toExceptionClassBreakpoints(list, useBreakpoints.getState().muted)), + ); + } catch (e) { + console.warn("debugSetExceptionClassBreakpoints failed", e); + } +} + +export function loadExceptionClasses(root: string | null) { + let list: ExceptionClassEntry[] = []; + if (root) { + try { + list = sanitizeExceptionClasses(JSON.parse(localStorage.getItem(STORAGE_PREFIX + root) ?? "[]")); + } catch { + // Corrupt entry: start empty. + } + } + useExceptionClasses.setState({ root, list }); + scheduleSync(); +} + +function setList(list: ExceptionClassEntry[]) { + useExceptionClasses.setState({ list }); + const { root } = useExceptionClasses.getState(); + if (root) { + try { + localStorage.setItem(STORAGE_PREFIX + root, JSON.stringify(list)); + } catch { + // Storage unavailable: kept for this session only. + } + } + scheduleSync(); +} + +export function addExceptionClass(className: string): ExceptionClassEntry { + const bp: ExceptionClassEntry = { + id: newBreakpointId(), + className: className.trim(), + caught: true, + uncaught: true, + enabled: true, + classFilters: "", + classFiltersEnabled: false, + }; + setList([...useExceptionClasses.getState().list, bp]); + return bp; +} + +export function updateExceptionClass(id: string, patch: Partial>) { + setList(useExceptionClasses.getState().list.map((b) => (b.id === id ? { ...b, ...patch } : b))); +} + +export function removeExceptionClass(id: string) { + setList(useExceptionClasses.getState().list.filter((b) => b.id !== id)); +} + +export function removeAllExceptionClasses() { + setList([]); +} + +useBreakpoints.subscribe((s, prev) => { + if (s.muted !== prev.muted) scheduleSync(); +}); diff --git a/src/features/debugger/breakpoints/exceptions.ts b/src/features/debugger/breakpoints/exceptions.ts index 69d04f450..6dbd77f59 100644 --- a/src/features/debugger/breakpoints/exceptions.ts +++ b/src/features/debugger/breakpoints/exceptions.ts @@ -107,6 +107,26 @@ export function isFilterEnabled(filter: ExceptionFilter, choices: Record, + choices: Record, +): { caught: boolean; uncaught: boolean } { + const filters = known[ANY_EXCEPTION_ADAPTER] ?? BUILTIN_FILTERS[ANY_EXCEPTION_ADAPTER]!; + const on = (id: string) => { + const filter = filters.find((f) => f.filter === id); + return !!filter && isFilterEnabled(filter, choices, ANY_EXCEPTION_ADAPTER); + }; + return { caught: on("caught"), uncaught: on("uncaught") }; +} + +export function setAnyException(kind: "caught" | "uncaught", enabled: boolean) { + setExceptionFilter(ANY_EXCEPTION_ADAPTER, kind, enabled); +} + export interface ExceptionGroup { adapter: string; filters: Array; diff --git a/src/features/debugger/index.ts b/src/features/debugger/index.ts index dd45cd681..94e7633d3 100644 --- a/src/features/debugger/index.ts +++ b/src/features/debugger/index.ts @@ -22,6 +22,7 @@ import { registerDevToolsWindows } from "./flutter/devTools"; import { registerDebugTabActions } from "./tabActions"; import { loadBreakpoints } from "./breakpoints/store"; import { loadExceptionBreakpoints } from "./breakpoints/exceptions"; +import { loadExceptionClasses } from "./breakpoints/exceptionClasses"; import { loadJsBreakpoints, watchPageSessions } from "./js/eventBreakpoints"; import { watchNetworkSessions } from "./js/networkSessions"; import { loadResponseOverrides, watchOverrideSessions } from "./js/responseOverrides"; @@ -85,6 +86,7 @@ export function activate(): () => void { publishContext(); loadBreakpoints(useProject.getState().project?.root ?? null); loadExceptionBreakpoints(useProject.getState().project?.root ?? null); + loadExceptionClasses(useProject.getState().project?.root ?? null); loadSpecialBreakpoints(useProject.getState().project?.root ?? null); loadJsBreakpoints(useProject.getState().project?.root ?? null); loadResponseOverrides(useProject.getState().project?.root ?? null); @@ -180,6 +182,7 @@ export function activate(): () => void { loadWatches(root); loadBreakpoints(root); loadExceptionBreakpoints(root); + loadExceptionClasses(root); loadSpecialBreakpoints(root); loadJsBreakpoints(root); loadResponseOverrides(root); diff --git a/src/features/debugger/ui/ExceptionClassDetail.tsx b/src/features/debugger/ui/ExceptionClassDetail.tsx new file mode 100644 index 000000000..fedb36cb5 --- /dev/null +++ b/src/features/debugger/ui/ExceptionClassDetail.tsx @@ -0,0 +1,137 @@ +/** Details of the Breakpoints dialog's Java exception breakpoints: "Any exception" and one per class. */ +import { useEffect, useRef, useState, type MutableRefObject } from "react"; +import { Button, Checkbox, Icon, Input, T } from "@/ui"; +import { tx } from "@/platform/i18n"; +import { anyException, setAnyException, useExceptionBreakpoints } from "../breakpoints/exceptions"; +import { removeExceptionClass, updateExceptionClass, type ExceptionClassEntry } from "../breakpoints/exceptionClasses"; +import styles from "./Overlays.module.css"; + +function Notifications({ + caught, + uncaught, + onChange, +}: { + caught: boolean; + uncaught: boolean; + onChange: (kind: "caught" | "uncaught", on: boolean) => void; +}) { + return ( +
+ + Suspend on + + + onChange("caught", on)} label="Caught exception" /> + onChange("uncaught", on)} label="Uncaught exception" /> + +
+ ); +} + +/** A field IDEA has for Java exception breakpoints that java-debug cannot honour: shown disabled. */ +function UnsupportedField({ label, inputLabel }: { label: string; inputLabel: string }) { + return ( +
+ undefined} label={label} /> + +
+ ); +} + +export function AnyExceptionDetail() { + const known = useExceptionBreakpoints((s) => s.known); + const choices = useExceptionBreakpoints((s) => s.choices); + const { caught, uncaught } = anyException(known, choices); + return ( +
+
+ + + Any exception + +
+
+ Stops at every exception thrown in a Java debug session. +
+ +
+ ); +} + +export function ExceptionClassDetail({ + bp, + commitRef, +}: { + bp: ExceptionClassEntry; + commitRef: MutableRefObject<(() => void) | null>; +}) { + const [className, setClassName] = useState(bp.className); + const [filters, setFilters] = useState(bp.classFilters); + const draft = useRef({ className, filters }); + useEffect(() => { + draft.current = { className, filters }; + commitRef.current = () => + updateExceptionClass(bp.id, { className: draft.current.className.trim(), classFilters: draft.current.filters }); + return () => { + commitRef.current = null; + }; + }); + const title = bp.className || tx("No class chosen"); + return ( +
+
+ + + {title} + + +
+ updateExceptionClass(bp.id, { enabled })} label="Enabled" /> + + updateExceptionClass(bp.id, { [kind]: on })} + /> + +
+ updateExceptionClass(bp.id, { classFiltersEnabled })} + label="Class filters" + /> + setFilters(e.target.value)} + onBlur={() => updateExceptionClass(bp.id, { classFilters: filters })} + placeholder="com.example.* -com.example.generated.*" + aria-label="Class filter patterns" + /> + + Where the exception is thrown. Put - before a pattern to exclude it. + +
+ +
+ ); +} diff --git a/src/features/debugger/ui/Overlays.module.css b/src/features/debugger/ui/Overlays.module.css index c7e2b9a9f..9cfc8e709 100644 --- a/src/features/debugger/ui/Overlays.module.css +++ b/src/features/debugger/ui/Overlays.module.css @@ -221,6 +221,17 @@ font-size: var(--fs-small); } +.unsupportedField { + display: flex; + flex-direction: column; + gap: var(--space-1); +} + +/* A disabled control gets no pointer events in WebKit: the field shows the tooltip instead. */ +.unsupportedField > * { + pointer-events: none; +} + /* evaluate dialog */ .evalDialog { height: min(440px, 100%); diff --git a/src/features/debugger/ui/Overlays.tsx b/src/features/debugger/ui/Overlays.tsx index 17c16fc22..e15a3e24a 100644 --- a/src/features/debugger/ui/Overlays.tsx +++ b/src/features/debugger/ui/Overlays.tsx @@ -52,12 +52,23 @@ import { import { attachConfig, attachDetail, attachRows, type AttachRow } from "../attach"; import { openAttachPopup, installAttachAdapter } from "../attachPopup"; import { + ANY_EXCEPTION_ADAPTER, + anyException, exceptionGroups, filterHint, refreshExceptionFilters, + setAnyException, setExceptionFilter, useExceptionBreakpoints, } from "../breakpoints/exceptions"; +import { + addExceptionClass, + removeAllExceptionClasses, + updateExceptionClass, + useExceptionClasses, + type ExceptionClassEntry, +} from "../breakpoints/exceptionClasses"; +import { AnyExceptionDetail, ExceptionClassDetail } from "./ExceptionClassDetail"; import { EventBreakpointsSection } from "../js/EventBreakpointsSection"; import { StreamChainChooser } from "../streams/StreamChainChooser"; import { StreamAbortDialog } from "../streams/StreamAbortDialog"; @@ -388,7 +399,11 @@ interface BpRow { type DialogRow = | { type: "section"; key: string; label: string } | ({ type: "line"; key: string } & BpRow) - | { type: "special"; key: string; bp: SpecialBreakpoint }; + | { type: "special"; key: string; bp: SpecialBreakpoint } + | { type: "anyException"; key: string } + | { type: "exceptionClass"; key: string; bp: ExceptionClassEntry }; + +const ANY_EXCEPTION_KEY = "any-exception"; function BreakpointLocation({ path, line }: { path: string; line: number }) { return ( @@ -407,6 +422,10 @@ function BreakpointsDialog() { const methods = useSpecialBreakpoints((s) => s.methods); const fields = useSpecialBreakpoints((s) => s.fields); const specialStatus = useSpecialBreakpoints((s) => s.status); + const exceptionClasses = useExceptionClasses((s) => s.list); + const knownFilters = useExceptionBreakpoints((s) => s.known); + const filterChoices = useExceptionBreakpoints((s) => s.choices); + const any = anyException(knownFilters, filterChoices); const root = useProject((s) => s.project?.root ?? ""); const rows = useMemo(() => { const lines: DialogRow[] = Object.keys(byFile) @@ -425,8 +444,12 @@ function BreakpointsDialog() { "Field Watchpoints", fields.map((bp) => ({ type: "special" as const, key: bp.id, bp })), ); + section("Java Exception Breakpoints", [ + { type: "anyException", key: ANY_EXCEPTION_KEY }, + ...exceptionClasses.map((bp) => ({ type: "exceptionClass" as const, key: bp.id, bp })), + ]); return out; - }, [byFile, methods, fields]); + }, [byFile, methods, fields, exceptionClasses]); const items = rows.filter((r) => r.type !== "section"); const [selected, setSelected] = useState(null); // The shown breakpoint's typed fields, saved before it is closed or another one is shown: @@ -461,6 +484,7 @@ function BreakpointsDialog() { const removeAll = () => { removeAllBreakpoints(); removeAllSpecial(); + removeAllExceptionClasses(); }; return ( @@ -492,11 +516,17 @@ function BreakpointsDialog() { size="small" onClick={() => setSelected(addMethodBreakpoint("").id)} /> + setSelected(addExceptionClass("").id)} + /> r.type !== "anyException")} onClick={removeAll} /> @@ -505,7 +535,9 @@ function BreakpointsDialog() { items={rows} getKey={(r) => r.key} isSection={(r) => r.type === "section"} - renderSection={(r) =>
{r.type === "section" ? r.label : ""}
} + renderSection={(r) => ( +
{r.type === "section" ? tx(r.label) : ""}
+ )} activeIndex={current ? rows.indexOf(current) : -1} onActiveChange={(i) => { commitRef.current?.(); @@ -524,6 +556,40 @@ function BreakpointsDialog() { } renderItem={(r) => { if (r.type === "section") return null; + if (r.type === "anyException") { + return ( +
+ { + setAnyException("caught", on); + setAnyException("uncaught", on); + }} + aria-label={tx("Enable Any exception")} + /> + + + Any exception + +
+ ); + } + if (r.type === "exceptionClass") { + const name = r.bp.className || tx("No class chosen"); + return ( +
+ updateExceptionClass(r.bp.id, { enabled })} + aria-label={tx`Enable ${name}`} + /> + + + {name} + +
+ ); + } if (r.type === "special") { const st = specialStatus[r.bp.id]; return ( @@ -594,6 +660,10 @@ function BreakpointsDialog() { goTo(current)} commitRef={commitRef} /> ) : current?.type === "special" ? ( goTo(current)} commitRef={commitRef} /> + ) : current?.type === "exceptionClass" ? ( + + ) : current?.type === "anyException" ? ( + ) : null} @@ -606,7 +676,11 @@ function BreakpointsDialog() { function ExceptionBreakpoints({ open }: { open: boolean }) { const known = useExceptionBreakpoints((s) => s.known); const choices = useExceptionBreakpoints((s) => s.choices); - const groups = useMemo(() => exceptionGroups(known, choices), [known, choices]); + // java-debug's filters are "Any exception" in the list above. + const groups = useMemo( + () => exceptionGroups(known, choices).filter((g) => g.adapter !== ANY_EXCEPTION_ADAPTER), + [known, choices], + ); useEffect(() => { if (open) void refreshExceptionFilters(); }, [open]); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 6bd8d5a5a..0504208bb 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1995,6 +1995,23 @@ "Requests whose URL contains": "Requests whose URL contains", "Remove Request Breakpoint": "Remove Request Breakpoint", "Add Request Breakpoint": "Add Request Breakpoint", + "Java Exception Breakpoints": "Java Exception Breakpoints", + "Add Java Exception Breakpoint": "Add Java Exception Breakpoint", + "Any exception": "Any exception", + "Enable Any exception": "Enable Any exception", + "Stops at every exception thrown in a Java debug session.": "Stops at every exception thrown in a Java debug session.", + "No class chosen": "No class chosen", + "Exception class": "Exception class", + "Exception class name": "Exception class name", + "Caught exception": "Caught exception", + "Uncaught exception": "Uncaught exception", + "Class filters": "Class filters", + "Class filter patterns": "Class filter patterns", + "Where the exception is thrown. Put - before a pattern to exclude it.": "Where the exception is thrown. Put - before a pattern to exclude it.", + "Catch class filters": "Catch class filters", + "Catch class filter patterns": "Catch class filter patterns", + "Condition expression": "Condition expression", + "Not available with java-debug: it suspends at every exception it reports, so a condition or a catch location cannot let one pass.": "Not available with java-debug: it suspends at every exception it reports, so a condition or a catch location cannot let one pass.", "e.g. /api/": "e.g. /api/", "Part of a request URL": "Part of a request URL", "Mouse": "Mouse", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 0cbba3f7f..9a1a57092 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -1445,6 +1445,23 @@ "Everything is up to date": "一切都是最新的", "Exception Breakpoints": "异常断点", "Exception breakpoints": "异常断点", + "Java Exception Breakpoints": "Java 异常断点", + "Add Java Exception Breakpoint": "添加 Java 异常断点", + "Any exception": "任何异常", + "Enable Any exception": "启用“任何异常”", + "Stops at every exception thrown in a Java debug session.": "在 Java 调试会话中抛出的每个异常处停止。", + "No class chosen": "未选择类", + "Exception class": "异常类", + "Exception class name": "异常类名", + "Caught exception": "已捕获的异常", + "Uncaught exception": "未捕获的异常", + "Class filters": "类过滤器", + "Class filter patterns": "类过滤模式", + "Where the exception is thrown. Put - before a pattern to exclude it.": "按抛出异常的位置过滤。在模式前加 - 表示排除。", + "Catch class filters": "捕获类过滤器", + "Catch class filter patterns": "捕获类过滤模式", + "Condition expression": "条件表达式", + "Not available with java-debug: it suspends at every exception it reports, so a condition or a catch location cannot let one pass.": "java-debug 不支持:它会在报告的每个异常处挂起,条件或捕获位置都无法让异常跳过。", "Exclude": "排除", "Exclude / include (⌫)": "排除/包括 (⌫)", "Exclude patterns": "排除模式", diff --git a/src/platform/locales/textCatalog.test.ts b/src/platform/locales/textCatalog.test.ts index eafa0cfb6..280e35ebb 100644 --- a/src/platform/locales/textCatalog.test.ts +++ b/src/platform/locales/textCatalog.test.ts @@ -251,6 +251,7 @@ const UNTRANSLATED = new Set([ "className()", "claude, codex", "clean install -DskipTests", + "com.example.* -com.example.generated.*", "com.example.Main", "com.example.Service#process, main.run, parse", "docker-compose.yml; docker-compose.override.yml", @@ -258,6 +259,7 @@ const UNTRANSLATED = new Set([ "git pull --no-rebase --ff", "git pull --rebase", "go env GOPATH", + "java.lang.IllegalStateException, com.example.Outer$Failure", "kebab-case", "KEY=value; OTHER=value", "main.py",