From ad685ea19edc5ccc065d30823376ece176ee92cb Mon Sep 17 00:00:00 2001 From: Bert Verhelst Date: Sun, 29 Nov 2026 08:54:29 +0100 Subject: [PATCH] feat(debugger): Disassembly view and instruction stepping for native debugging (#6694) Native debug sessions whose adapter supports disassemble get a Disassembly tab showing the selected frame's instructions with the program counter highlighted, following stepping and frame selection, including frames without source. Show Disassembly is on the Frames list; Step Over Instruction and Step Into Instruction send steps with instruction granularity and are disabled with a reason when the adapter lacks it. Frames keep instructionPointerReference; when the PC is not where the requested window expects it, the view reads again from the PC. lldb-dap sends instruction bytes already spaced and pads mnemonics unevenly; the view strips the spacing before grouping the bytes and pads mnemonics to one width. Part of #5922 Co-authored-by: bertyhell <1710840+bertyhell@users.noreply.github.com> --- crates/ide-dap/src/disassembly.rs | 115 ++++++++ crates/ide-dap/src/lib.rs | 78 +++++- crates/ide-dap/src/tests.rs | 122 +++++++++ crates/ide-dap/tests/real_adapters.rs | 48 +++- crates/ide-host/src/ops/debug.rs | 26 ++ crates/ide-host/src/ops/stream_trace/tests.rs | 1 + e2e/debug.spec.ts | 111 ++++++++ src-tauri/tests/commands.snap | 2 + src/bindings.ts | 62 ++++- .../debugger/__tests__/actions.test.ts | 51 ++++ .../__tests__/disassemblyView.test.tsx | 245 ++++++++++++++++++ .../debugger/__tests__/executionState.test.ts | 25 ++ src/features/debugger/actions.ts | 52 ++++ .../disassembly/DisassemblyPane.module.css | 122 +++++++++ .../debugger/disassembly/DisassemblyPane.tsx | 175 +++++++++++++ .../debugger/disassembly/disassemblyState.ts | 94 +++++++ src/features/debugger/index.ts | 2 + src/features/debugger/state.ts | 27 +- src/features/debugger/ui/DebugToolWindow.tsx | 41 ++- src/platform/locales/text/en.json | 12 +- src/platform/locales/text/zh.json | 12 +- 21 files changed, 1407 insertions(+), 16 deletions(-) create mode 100644 crates/ide-dap/src/disassembly.rs create mode 100644 src/features/debugger/__tests__/disassemblyView.test.tsx create mode 100644 src/features/debugger/disassembly/DisassemblyPane.module.css create mode 100644 src/features/debugger/disassembly/DisassemblyPane.tsx create mode 100644 src/features/debugger/disassembly/disassemblyState.ts diff --git a/crates/ide-dap/src/disassembly.rs b/crates/ide-dap/src/disassembly.rs new file mode 100644 index 000000000..56981345f --- /dev/null +++ b/crates/ide-dap/src/disassembly.rs @@ -0,0 +1,115 @@ +//! Machine code of a native program (DAP `disassemble`), for the Disassembly view. + +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use specta::Type; + +/// The most instructions one request asks for. +pub const MAX_INSTRUCTIONS: u32 = 1000; + +/// One disassembled instruction. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct Instruction { + /// Address as the adapter writes it (`0x5555…`); also a memory reference for the next request. + pub address: String, + /// The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`). + pub instruction: String, + /// Its machine code as hex (`488b45d8`), when the adapter sends it. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub bytes: Option, + /// The function it belongs to, when the adapter names it (often on the first instruction only). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub symbol: Option, +} + +/// `disassemble`'s instructions in order; `None` for the padding adapters put where there is no +/// code (`presentationHint: "invalid"`, or no address). +pub(crate) fn instructions(body: &Value) -> Vec> { + let text = |i: &Value, k: &str| i.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_owned); + let Some(list) = body.get("instructions").and_then(Value::as_array) else { return Vec::new() }; + list.iter() + .map(|i| { + if i.get("presentationHint").and_then(Value::as_str) == Some("invalid") { + return None; + } + Some(Instruction { + address: text(i, "address")?, + instruction: text(i, "instruction").unwrap_or_default(), + bytes: text(i, "instructionBytes"), + symbol: text(i, "symbol"), + }) + }) + .collect() +} + +/// A memory reference or address as a number (`0x7ffd…` or decimal). +pub(crate) fn address(reference: &str) -> Option { + let r = reference.trim(); + match r.strip_prefix("0x").or_else(|| r.strip_prefix("0X")) { + Some(hex) => u128::from_str_radix(hex, 16).ok(), + None => r.parse().ok(), + } +} + +/// Whether the instruction at `index` is the one at `reference`. References that are not +/// addresses cannot be checked and pass. +pub(crate) fn at_index(instructions: &[Option], reference: &str, index: usize) -> bool { + let Some(want) = address(reference) else { return instructions.len() > index }; + instructions.get(index).and_then(Option::as_ref).and_then(|i| address(&i.address)) == Some(want) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn reads_gdbs_instructions() { + // GDB 17.1 at the reporter-style C fixture's loop line. + let body = json!({"instructions": [ + {"address": "0x5555555551f5", "instruction": "mov -0x2c(%rbp),%eax", "instructionBytes": "8b45d4", "line": 14}, + {"address": "0x5555555551f8", "instruction": "cltq", "instructionBytes": "4898", "symbol": "sum"}, + ]}); + let got = instructions(&body); + assert_eq!( + got[0], + Some(Instruction { + address: "0x5555555551f5".into(), + instruction: "mov -0x2c(%rbp),%eax".into(), + bytes: Some("8b45d4".into()), + symbol: None, + }) + ); + assert_eq!(got[1].as_ref().unwrap().symbol.as_deref(), Some("sum")); + } + + #[test] + fn padding_is_not_an_instruction() { + let body = json!({"instructions": [ + {"address": "0xfff0", "instruction": "", "presentationHint": "invalid"}, + {"instruction": "??"}, + {"address": "0x10000", "instruction": "nop"}, + ]}); + let got = instructions(&body); + assert_eq!((got[0].is_none(), got[1].is_none(), got[2].is_some()), (true, true, true)); + assert!(instructions(&json!({})).is_empty()); + } + + #[test] + fn finds_the_reference_by_its_address() { + let list = instructions(&json!({"instructions": [ + {"address": "0x00001000", "instruction": "push %rbp"}, + {"address": "0x1001", "instruction": "mov %rsp,%rbp"}, + ]})); + assert!(at_index(&list, "0x1001", 1)); + assert!(at_index(&list, "4097", 1)); + assert!(at_index(&list, "0X1000", 0)); + assert!(!at_index(&list, "0x1001", 0)); + assert!(!at_index(&list, "0x1001", 2)); + assert!(at_index(&list, "frame-3", 1), "opaque references cannot be checked"); + assert_eq!(address("0xffffffffffffffff1"), Some(0xffffffffffffffff1)); + } +} diff --git a/crates/ide-dap/src/lib.rs b/crates/ide-dap/src/lib.rs index 758860453..774155b07 100644 --- a/crates/ide-dap/src/lib.rs +++ b/crates/ide-dap/src/lib.rs @@ -13,6 +13,7 @@ pub mod attach; mod cargo; pub mod connection; mod debugpy; +mod disassembly; mod exception_classes; pub mod jdwp; mod js_cdp; @@ -27,6 +28,7 @@ pub mod unity; use adapter::{AdapterIo, AdapterLauncher, AdapterSpec, ProcessLauncher}; use connection::{Connection, DapError}; +pub use disassembly::{Instruction, MAX_INSTRUCTIONS}; pub use exception_classes::{ExceptionClassBreakpoint, ExceptionClassSupport}; use futures::future::join_all; use ide_core::{DebugSessionId, IdeError, IdeResult, RunId, SharedSink}; @@ -163,6 +165,10 @@ pub struct DebugCapabilities { pub stream_trace: bool, /// The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View. pub read_memory: bool, + /// The program's machine code can be disassembled ([`DebugManager::disassemble`]): the Disassembly view. + pub disassemble: bool, + /// Steps can move by one instruction ([`DebugManager::step_instruction`]). + pub instruction_stepping: bool, } /// Result of [`DebugManager::redefine_classes`]. @@ -229,6 +235,10 @@ pub struct StackFrame { pub column: u32, /// `subtle` frames (library/generated) are collapsed in the UI. pub presentation_hint: Option, + /// The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`). + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub instruction_pointer_reference: Option, } #[derive(Clone, Debug, Serialize, Deserialize, Type)] @@ -619,6 +629,11 @@ pub(crate) fn frame_from(f: &Value) -> StackFrame { line: (f.get("line").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1), column: (f.get("column").and_then(Value::as_u64).unwrap_or(0) as u32).saturating_sub(1), presentation_hint: hint, + instruction_pointer_reference: f + .get("instructionPointerReference") + .and_then(Value::as_str) + .filter(|r| !r.is_empty()) + .map(str::to_owned), } } @@ -696,6 +711,8 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities { live_evaluate: false, stream_trace: false, read_memory: has("supportsReadMemoryRequest"), + disassemble: has("supportsDisassembleRequest"), + instruction_stepping: has("supportsSteppingGranularity"), } } @@ -2037,6 +2054,22 @@ impl DebugManager { } pub async fn step(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> { + self.step_with(s, thread_id, kind, json!({ "threadId": thread_id })).await + } + + /// Step Over / Into Instruction: a step by one machine instruction (DAP `granularity`). + pub async fn step_instruction(&self, s: DebugSessionId, thread_id: i64, kind: StepKind) -> IdeResult<()> { + let session = self.session(s)?; + if !session.supports("supportsSteppingGranularity") { + return Err(IdeError::unavailable(format!( + "debug adapter `{}` cannot step by instruction", + session.adapter + ))); + } + self.step_with(s, thread_id, kind, json!({ "threadId": thread_id, "granularity": "instruction" })).await + } + + async fn step_with(&self, s: DebugSessionId, thread_id: i64, kind: StepKind, args: Value) -> IdeResult<()> { let command = match kind { StepKind::Over => "next", StepKind::Into => "stepIn", @@ -2048,7 +2081,7 @@ impl DebugManager { quirks.step_sent(); } let ticket = session.suspended.ticket(); - let sent = session.conn.request_timeout(command, json!({ "threadId": thread_id }), REQUEST_TIMEOUT).await; + let sent = session.conn.request_timeout(command, args, REQUEST_TIMEOUT).await; step_settled(&session, sent)?; // A step runs its thread; other threads stopped by their own events stay stopped. session.finish_resume(ticket, thread_id, false); @@ -2227,6 +2260,49 @@ impl DebugManager { memory::memory_block(&body, count) } + /// `count` instructions (at most [`MAX_INSTRUCTIONS`]) from `before` instructions ahead of + /// `memory_reference` (a frame's instruction pointer or an instruction's address). Adapters that + /// cannot disassemble backwards start at the reference instead. + pub async fn disassemble( + &self, + s: DebugSessionId, + memory_reference: String, + before: u32, + count: u32, + ) -> IdeResult> { + let session = self.session(s)?; + if !session.supports("supportsDisassembleRequest") { + return Err(IdeError::unavailable(format!("debug adapter `{}` cannot disassemble", session.adapter))); + } + let count = count.clamp(1, MAX_INSTRUCTIONS); + let before = before.min(count - 1); + let request = |offset: i64, count: u32| { + session.conn.request_timeout( + "disassemble", + json!({ + "memoryReference": memory_reference, + "offset": 0, + "instructionOffset": offset, + "instructionCount": count, + "resolveSymbols": true, + }), + REQUEST_TIMEOUT, + ) + }; + if before > 0 { + // GDB (up to 17 at least) answers a negative instruction offset with the instructions after + // the reference, or fails: only an answer with the reference in its place is used. + if let Ok(body) = request(-i64::from(before), count).await { + let instructions = disassembly::instructions(&body); + if disassembly::at_index(&instructions, &memory_reference, before as usize) { + return Ok(instructions.into_iter().flatten().collect()); + } + } + } + let body = request(0, count - before).await?; + Ok(disassembly::instructions(&body).into_iter().flatten().collect()) + } + pub fn capabilities(&self, s: DebugSessionId) -> IdeResult { Ok(session_capabilities(&*self.session(s)?)) } diff --git a/crates/ide-dap/src/tests.rs b/crates/ide-dap/src/tests.rs index cb7800b3a..4b71c289b 100644 --- a/crates/ide-dap/src/tests.rs +++ b/crates/ide-dap/src/tests.rs @@ -199,6 +199,18 @@ struct Script { /// Advertise `supportsReadMemoryRequest`: memory below 0x1010 reads as its low address byte, /// memory from there on is unmapped. read_memory: bool, + /// Advertise `supportsDisassembleRequest` and `supportsSteppingGranularity`, disassembling like + /// this adapter: 4-byte instructions from 0x1000 to 0x1100, nothing mapped around them. + disassemble: Option, +} + +#[derive(Clone, Copy, PartialEq)] +enum FakeDisassembler { + /// Negative instruction offsets work; unmapped places are `invalid` padding. + Lldb, + /// GDB 17: disassembles `instructionOffset + instructionCount` instructions from the reference and + /// drops the first `instructionOffset` of them, the way a Python slice does. + Gdb, } /// The answer to a request of the adapter's own: the response body, then events (name, body). @@ -247,6 +259,7 @@ impl Default for Script { accept: &[], custom: None, read_memory: false, + disassemble: None, } } } @@ -334,6 +347,8 @@ async fn fake_adapter(stream "supportsStepInTargetsRequest": true, "supportsRestartFrame": true, "supportsReadMemoryRequest": script.read_memory, + "supportsDisassembleRequest": script.disassemble.is_some(), + "supportsSteppingGranularity": script.disassemble.is_some(), "exceptionBreakpointFilters": [ {"filter": "raised", "label": "Raised"}, {"filter": "uncaught", "label": "Uncaught", "default": true, "description": "Uncaught exceptions"}, @@ -599,6 +614,35 @@ async fn fake_adapter(stream ); } } + "disassemble" => { + let args = &msg["arguments"]; + let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x"); + let pc = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0); + let (offset, count) = + (args["instructionOffset"].as_i64().unwrap(), args["instructionCount"].as_i64().unwrap()); + let insn = |a: i64| { + if (0x1000..0x1100).contains(&a) { + json!({"address": format!("{a:#x}"), "instruction": format!("insn {}", (a - 0x1000) / 4), "instructionBytes": "90909090"}) + } else { + json!({"address": format!("{a:#x}"), "instruction": "", "presentationHint": "invalid"}) + } + }; + let addresses: Option> = match script.disassemble.unwrap() { + FakeDisassembler::Lldb => Some((0..count).map(|i| pc + 4 * (offset + i)).collect()), + FakeDisassembler::Gdb if offset + count < 0 => None, + FakeDisassembler::Gdb => { + let all: Vec = (0..offset + count).map(|i| pc + 4 * i).collect(); + let from = if offset >= 0 { offset } else { (all.len() as i64 + offset).max(0) }; + Some(all[from as usize..].to_vec()) + } + }; + match addresses { + Some(a) => ok!(msg, json!({"instructions": a.into_iter().map(insn).collect::>()})), + None => send!( + json!({"type": "response", "request_seq": msg["seq"], "command": "disassemble", "success": false, "message": "Argument 'count' should be an non-negative integer."}) + ), + } + } "completions" => ok!( msg, json!({"targets": [ @@ -2042,6 +2086,84 @@ fn variables_keep_their_memory_reference() { assert!(json.get("memoryReference").is_none(), "absent, not null, for the UI's optional field"); } +#[tokio::test] +async fn disassembly_reads_instructions_around_the_instruction_pointer() { + let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() }); + let id = h.start(config()).await.unwrap(); + h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await; + let caps = h.manager.capabilities(id).unwrap(); + assert!(caps.disassemble && caps.instruction_stepping); + + let list = h.manager.disassemble(id, "0x1010".into(), 2, 5).await.unwrap(); + let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect(); + assert_eq!(addresses, ["0x1008", "0x100c", "0x1010", "0x1014", "0x1018"]); + assert_eq!((list[2].instruction.as_str(), list[2].bytes.as_deref()), ("insn 4", Some("90909090"))); + assert_eq!( + requests(&h, "disassemble")[0], + json!({"memoryReference": "0x1010", "offset": 0, "instructionOffset": -2, "instructionCount": 5, "resolveSymbols": true}) + ); + + // Before the first mapped instruction the adapter pads; the padding is not shown. + let list = h.manager.disassemble(id, "0x1004".into(), 4, 6).await.unwrap(); + let addresses: Vec<&str> = list.iter().map(|i| i.address.as_str()).collect(); + assert_eq!(addresses, ["0x1000", "0x1004", "0x1008"]); + + let _ = h.manager.disassemble(id, "0x1000".into(), 0, u32::MAX).await; + assert_eq!(requests(&h, "disassemble").last().unwrap()["instructionCount"], MAX_INSTRUCTIONS); + h.manager.stop(id).await.unwrap(); +} + +#[tokio::test] +async fn disassembly_starts_at_the_instruction_pointer_when_the_adapter_cannot_go_back() { + let h = harness(Script { disassemble: Some(FakeDisassembler::Gdb), ..Script::default() }); + let id = h.start(config()).await.unwrap(); + h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await; + // GDB's answer to "4 before" leaves out the instruction pointer; the view asks again from it. + let list = h.manager.disassemble(id, "0x1010".into(), 4, 10).await.unwrap(); + assert_eq!(list.first().map(|i| i.address.as_str()), Some("0x1010")); + assert_eq!(list.len(), 6); + let offsets: Vec = requests(&h, "disassemble").iter().map(|r| r["instructionOffset"].clone()).collect(); + assert_eq!(offsets, [json!(-4), json!(0)]); + h.manager.stop(id).await.unwrap(); +} + +#[tokio::test] +async fn instruction_steps_send_the_granularity_and_line_steps_do_not() { + let h = harness(Script { disassemble: Some(FakeDisassembler::Lldb), ..Script::default() }); + let id = h.start(config()).await.unwrap(); + h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await; + h.manager.step_instruction(id, 1, StepKind::Into).await.unwrap(); + assert_eq!(requests(&h, "stepIn").last().unwrap(), &json!({"threadId": 1, "granularity": "instruction"})); + h.manager.step(id, 1, StepKind::Over).await.unwrap(); + assert_eq!(requests(&h, "next").last().unwrap(), &json!({"threadId": 1})); + h.manager.stop(id).await.unwrap(); +} + +#[tokio::test] +async fn disassembly_and_instruction_steps_say_when_the_adapter_cannot() { + let h = harness(Script::default()); + let id = h.start(config()).await.unwrap(); + h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await; + let caps = h.manager.capabilities(id).unwrap(); + assert!(!caps.disassemble && !caps.instruction_stepping); + let err = h.manager.disassemble(id, "0x1000".into(), 0, 16).await.unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable); + assert!(err.to_string().contains("debug adapter `debugpy` cannot disassemble"), "{err}"); + let err = h.manager.step_instruction(id, 1, StepKind::Over).await.unwrap_err(); + assert_eq!(err.kind, ide_core::error::ErrorKind::Unavailable); + let sent = h.commands(); + assert!(!sent.iter().any(|c| c == "disassemble" || c == "next"), "nothing is sent to an adapter without support"); + h.manager.stop(id).await.unwrap(); +} + +#[test] +fn frames_keep_their_instruction_pointer() { + let f = frame_from(&json!({"id": 1, "name": "atoi", "line": 0, "instructionPointerReference": "0x7ffff7c4a2e0"})); + assert_eq!(f.instruction_pointer_reference.as_deref(), Some("0x7ffff7c4a2e0")); + let json = serde_json::to_value(frame_from(&json!({"id": 1, "name": "main"}))).unwrap(); + assert!(json.get("instructionPointerReference").is_none()); +} + #[tokio::test] async fn smart_step_into_and_reset_frame() { let h = harness(Script::default()); diff --git a/crates/ide-dap/tests/real_adapters.rs b/crates/ide-dap/tests/real_adapters.rs index dd3c2d362..b8022dda0 100644 --- a/crates/ide-dap/tests/real_adapters.rs +++ b/crates/ide-dap/tests/real_adapters.rs @@ -1,6 +1,6 @@ //! Drives real debug adapters against tiny programs (one per language), checking the //! launch templates and the IDEA-parity features: line / method breakpoints, Smart Step -//! Into, Reset Frame, Force Step Over, Force Run to Cursor, Set Value and the Memory View. +//! Into, Reset Frame, Force Step Over, Force Run to Cursor, Set Value, the Memory View and the Disassembly view. //! //! Ignored by default (needs the adapters installed). Run with //! `OPENIDEA_DAP_FIXTURES= cargo test -p ide-dap --test real_adapters -- --ignored --nocapture` @@ -307,6 +307,52 @@ async fn scenario(case: &Case) -> Result, String> { report.push("memory view: readMemory not supported".into()); } + // Disassembly: the instructions around the stop's instruction pointer, then two instruction steps, + // which stay on the loop line and inside the instructions shown. + let address = |a: &str| u128::from_str_radix(a.trim_start_matches("0x"), 16).ok(); + match (caps.disassemble, top.instruction_pointer_reference.clone()) { + (true, Some(pc)) => match m.disassemble(s, pc.clone(), 8, 24).await { + Ok(list) => { + let shown = |a: &str| list.iter().position(|i| address(&i.address) == address(a)); + match shown(&pc) { + Some(at) => report.push(format!( + "disassembly at {pc}: {} instructions, the instruction pointer is #{at}: `{}` ({:?})", + list.len(), + list[at].instruction, + list[at].bytes + )), + None => report.push(format!("disassembly at {pc}: FAILED, not among {list:?}")), + } + if caps.instruction_stepping { + let mut steps = vec![pc]; + for _ in 0..2 { + let seen = run.seen(); + m.step_instruction(s, thread, StepKind::Over).await.map_err(|e| e.message)?; + run.stopped_after(seen).await.ok_or("no stop after step over instruction")?; + let f = run.top(s, thread).await; + if f.line != case.loop_line { + report.push(format!( + "step over instruction: left the loop line for {}:{}", + f.name, + f.line + 1 + )); + } + steps.push(f.instruction_pointer_reference.unwrap_or_default()); + } + let all = steps.iter().all(|a| shown(a).is_some()); + report.push(format!("step over instruction: {} (all shown: {all})", steps.join(" -> "))); + } else { + report.push("instruction stepping: not supported".into()); + } + } + Err(e) => report.push(format!("disassembly at {pc}: FAILED {}", e.message)), + }, + (true, None) => report.push("disassembly: the top frame has no instruction pointer".into()), + (false, _) => report.push("disassembly: not supported".into()), + } + // Instruction steps resumed the thread: frame ids from before them may be gone. + let top = run.top(s, thread).await; + // Set Value on the first local that is an integer. let scopes = m.scopes(s, top.id).await.map_err(|e| e.message)?; for scope in scopes.iter().filter(|sc| !sc.expensive) { diff --git a/crates/ide-host/src/ops/debug.rs b/crates/ide-host/src/ops/debug.rs index 3a9729298..be55b3459 100644 --- a/crates/ide-host/src/ops/debug.rs +++ b/crates/ide-host/src/ops/debug.rs @@ -515,6 +515,17 @@ pub async fn debug_step(host: &Host, session: DebugSessionId, thread_id: i64, ki host.debugger.step(session, thread_id, kind).await } +/// Step Over / Into Instruction: a step by one machine instruction. +#[command(trust = trusted)] +pub async fn debug_step_instruction( + host: &Host, + session: DebugSessionId, + thread_id: i64, + kind: StepKind, +) -> IdeResult<()> { + host.debugger.step_instruction(session, thread_id, kind).await +} + #[command(trust = trusted)] pub async fn debug_run_to( host: &Host, @@ -570,6 +581,19 @@ pub async fn debug_read_memory( host.debugger.read_memory(session, memory_reference, offset, count).await } +/// Disassembly view: `count` instructions from `before` instructions ahead of `memory_reference` +/// (a frame's instruction pointer or an instruction's address). +#[command(trust = trusted)] +pub async fn debug_disassemble( + host: &Host, + session: DebugSessionId, + memory_reference: String, + before: u32, + count: u32, +) -> IdeResult> { + host.debugger.disassemble(session, memory_reference, before, count).await +} + /// Last known verification states of a file's breakpoints (refetch on `breakpointsChanged`). #[command(trust = trusted)] pub fn debug_breakpoint_states(host: &Host, path: PathBuf) -> IdeResult> { @@ -1079,6 +1103,7 @@ ide_command::domain!( debug_capabilities, debug_completions, debug_data_breakpoint_info, + debug_disassemble, debug_evaluate, debug_evaluate_in, debug_exception_filters, @@ -1117,6 +1142,7 @@ ide_command::domain!( debug_step, debug_step_in_target, debug_step_in_targets, + debug_step_instruction, debug_stop, debug_threads, debug_unity_processes, diff --git a/crates/ide-host/src/ops/stream_trace/tests.rs b/crates/ide-host/src/ops/stream_trace/tests.rs index 189159f51..8b3671284 100644 --- a/crates/ide-host/src/ops/stream_trace/tests.rs +++ b/crates/ide-host/src/ops/stream_trace/tests.rs @@ -45,6 +45,7 @@ fn frame(line: u32) -> StackFrame { line, column: 8, presentation_hint: None, + instruction_pointer_reference: None, } } diff --git a/e2e/debug.spec.ts b/e2e/debug.spec.ts index d7a42dac3..2615103b3 100644 --- a/e2e/debug.spec.ts +++ b/e2e/debug.spec.ts @@ -246,6 +246,117 @@ test("Memory View shows the bytes at an address expression with hex and ASCII al await expect(rows.nth(2).getByRole("gridcell").nth(1)).toHaveText(/^World!\.\./); }); +test("Disassembly shows the selected frame's instructions with the current one highlighted", async ({ + workbench: page, +}) => { + await stubDesktop(page); + await page.evaluate(async (id) => { + // GDB 17.1's `disassemble /r sum` of a C program (#5922), stopped at `sum+78` on the loop line. + const SUM = 0x5555555551a7; + const code: [number, string, string][] = [ + [62, "c745e000000000", "movl $0x0,-0x20(%rbp)"], + [69, "c745e400000000", "movl $0x0,-0x1c(%rbp)"], + [76, "eb26", "jmp 0x55555555521b "], + [78, "8b45e4", "mov -0x1c(%rbp),%eax"], + [81, "4898", "cltq"], + [83, "488d14c500000000", "lea 0x0(,%rax,8),%rdx"], + [91, "488b45d8", "mov -0x28(%rbp),%rax"], + [95, "4801d0", "add %rdx,%rax"], + [98, "488b00", "mov (%rax),%rax"], + [101, "4889c7", "mov %rax,%rdi"], + [104, "e875ffffff", "call 0x555555555189 "], + [109, "0145e0", "add %eax,-0x20(%rbp)"], + [112, "8345e401", "addl $0x1,-0x1c(%rbp)"], + [116, "8b45e4", "mov -0x1c(%rbp),%eax"], + [119, "3b45d4", "cmp -0x2c(%rbp),%eax"], + [122, "7cd2", "jl 0x5555555551f5 "], + [124, "8b45e0", "mov -0x20(%rbp),%eax"], + [127, "488b55f8", "mov -0x8(%rbp),%rdx"], + [131, "64482b142528000000", "sub %fs:0x28,%rdx"], + [140, "7405", "je 0x55555555523a "], + [142, "e836feffff", "call 0x555555555070 <__stack_chk_fail@plt>"], + [147, "c9", "leave"], + [148, "c3", "ret"], + ]; + const instructions = code.map(([offset, bytes, instruction]) => ({ + address: `0x${(SUM + offset).toString(16)}`, + instruction, + bytes, + })); + const h = window.__ipc.handlers; + const caps = { disassemble: true, instructionStepping: true }; + h.debug_capabilities = () => caps; + h.debug_disassemble = (args) => { + const at = instructions.findIndex((i) => BigInt(i.address) === BigInt(args.memoryReference as string)); + const from = Math.max(0, at - (args.before as number)); + return instructions.slice(from, from + (args.count as number)); + }; + h.debug_step_instruction = () => null; + const frame = (fid: number, name: string, line: number, pc: number) => ({ + id: fid, + name, + path: "/proj/main.c", + line, + column: 0, + presentationHint: null, + instructionPointerReference: `0x${pc.toString(16)}`, + }); + const debugPath = "/src/features/debugger/state.ts"; + const { adoptSession } = await import(/* @vite-ignore */ debugPath); + adoptSession(id, { + adapter: "gdb", + name: "app-c", + status: "paused", + stops: 1, + caps, + stoppedThread: 1, + selectedThread: 1, + threads: [{ id: 1, name: "main" }], + frames: [frame(0, "sum", 13, SUM + 78), frame(1, "run", 20, SUM + 109)], + selectedFrame: 0, + }); + const dockPath = "/src/workbench/toolwindows/store.ts"; + const layout = await import(/* @vite-ignore */ dockPath); + layout.moveToolWindow("debug", "bottom"); + layout.setToolWindowSize("bottom", 360); + layout.showToolWindow("debug", true); + }, SESSION); + + const debug = page.getByRole("region", { name: "Debug", exact: true }); + await debug.getByRole("tab", { name: "Disassembly" }).click(); + const grid = debug.getByRole("grid", { name: "Disassembly" }); + const current = grid.locator("[aria-current=location]"); + await expect(current.getByRole("rowheader")).toHaveText("0x00005555555551F5"); + await expect(current.getByRole("gridcell").nth(0)).toHaveText("8B 45 E4"); + await expect(current.getByRole("gridcell").nth(1)).toHaveText("mov -0x1c(%rbp),%eax"); + expect(await ipcCalls(page, "debug_disassemble")).toEqual([ + { session: SESSION, memoryReference: "0x5555555551f5", before: 32, count: 128 }, + ]); + // Monospaced columns: every row's instruction starts where the row above starts it. + const rows = grid.getByRole("row"); + const left = async (row: number) => (await rows.nth(row).getByRole("gridcell").nth(1).boundingBox())!.x; + expect(await left(5)).toBeCloseTo(await left(4), 0); + + await debug.getByRole("button", { name: "Step Over Instruction" }).click(); + expect(await ipcCalls(page, "debug_step_instruction")).toEqual([{ session: SESSION, threadId: 1, kind: "over" }]); + + // An adapter that cannot step by instruction: the button is disabled and its tooltip says why. + await page.evaluate(async (id) => { + const debugPath = "/src/features/debugger/state.ts"; + const { useDebug } = await import(/* @vite-ignore */ debugPath); + useDebug.setState((st: { sessions: Record }) => ({ + sessions: { + ...st.sessions, + [id]: { ...st.sessions[id], status: "paused", caps: { disassemble: true, instructionStepping: false } }, + }, + })); + }, SESSION); + const stepInto = debug.getByRole("button", { name: "Step Into Instruction" }); + await expect(stepInto).toBeDisabled(); + await stepInto.hover({ force: true }); + await expect(page.getByRole("tooltip")).toContainText("Instruction stepping is not supported by gdb"); +}); + test("Evaluate keeps a multiline expression and its result visible in a short dialog", async ({ workbench: page }) => { await page.setViewportSize({ width: 580, height: 420 }); await stubDesktop(page); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index a784f0ecb..296d2b9f8 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -182,6 +182,7 @@ debug_breakpoint_states trusted project_host bin debug_capabilities trusted project_host bindings sync debug_completions trusted project_host bindings async debug_data_breakpoint_info trusted project_host bindings async +debug_disassemble trusted project_host bindings async debug_evaluate trusted project_host bindings async debug_evaluate_in trusted project_host bindings async debug_exception_filters trusted project_host bindings sync @@ -230,6 +231,7 @@ debug_start trusted project_host bin debug_step trusted project_host bindings async debug_step_in_target trusted project_host bindings async debug_step_in_targets trusted project_host bindings async +debug_step_instruction trusted project_host bindings async debug_stop always project_host bindings async debug_stream_chains trusted project_host bindings async debug_stream_trace trusted project_host bindings async diff --git a/src/bindings.ts b/src/bindings.ts index ee90525d2..69cb9bf22 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -471,6 +471,11 @@ export const commands = { /** Completions for an expression typed in Evaluate (`line` / `column` 0-based, UTF-16). */ debugCompletions: (session: DebugSessionId, frameId: number | null, text: string, line: number, column: number) => typedError(__TAURI_INVOKE("debug_completions", { session, frameId, text, line, column })), debugDataBreakpointInfo: (session: DebugSessionId, container: number, name: string, frameId: number | null) => typedError(__TAURI_INVOKE("debug_data_breakpoint_info", { session, container, name, frameId })), + /** + * Disassembly view: `count` instructions from `before` instructions ahead of `memory_reference` + * (a frame's instruction pointer or an instruction's address). + */ + debugDisassemble: (session: DebugSessionId, memoryReference: string, before: number, count: number) => typedError(__TAURI_INVOKE("debug_disassemble", { session, memoryReference, before, count })), debugEvaluate: (session: DebugSessionId, frameId: number | null, expression: string) => typedError(__TAURI_INVOKE("debug_evaluate", { session, frameId, expression })), /** Evaluate with an explicit DAP context: `repl`, `watch`, `hover` or `clipboard`. */ debugEvaluateIn: (session: DebugSessionId, frameId: number | null, expression: string, context: string | null) => typedError(__TAURI_INVOKE("debug_evaluate_in", { session, frameId, expression, context })), @@ -560,21 +565,23 @@ export const commands = { /** 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 })), - debugStackTrace: (session: DebugSessionId, threadId: number) => typedError(__TAURI_INVOKE("debug_stack_trace", { session, threadId })), + debugStackTrace: (session: DebugSessionId, threadId: number) => typedError(__TAURI_INVOKE("debug_stack_trace", { session, threadId })), /** Starts a session owned by this window: its events (and those of child sessions) go here only. */ debugStart: (config: LaunchConfig) => typedError(__TAURI_INVOKE("debug_start", { config })), debugStep: (session: DebugSessionId, threadId: number, kind: StepKind) => typedError(__TAURI_INVOKE("debug_step", { session, threadId, kind })), debugStepInTarget: (session: DebugSessionId, threadId: number, targetId: number) => typedError(__TAURI_INVOKE("debug_step_in_target", { session, threadId, targetId })), /** Smart Step Into: the calls on the current line of `frame_id`. */ debugStepInTargets: (session: DebugSessionId, frameId: number) => typedError(__TAURI_INVOKE("debug_step_in_targets", { session, frameId })), + /** Step Over / Into Instruction: a step by one machine instruction. */ + debugStepInstruction: (session: DebugSessionId, threadId: number, kind: StepKind) => typedError(__TAURI_INVOKE("debug_step_instruction", { session, threadId, kind })), debugStop: (session: DebugSessionId) => typedError(__TAURI_INVOKE("debug_stop", { session })), /** The stream chains around `frame`'s line; `top`: it is the thread's top frame. */ - debugStreamChains: (session: DebugSessionId, frame: StackFrame, top: boolean) => typedError(__TAURI_INVOKE("debug_stream_chains", { session, frame, top })), + debugStreamChains: (session: DebugSessionId, frame: StackFrame_Deserialize, top: boolean) => typedError(__TAURI_INVOKE("debug_stream_chains", { session, frame, top })), /** * Traces chain `chain_index` of [`debug_stream_chains`], whose `range` the UI showed, while the * program runs it; cancelling `request` stops recording. */ - debugStreamTrace: (session: DebugSessionId, request: RequestId, threadId: number, frame: StackFrame, chainIndex: number, range: Range, onProgress: Channel) => typedError(__TAURI_INVOKE("debug_stream_trace", { session, request, threadId, frame, chainIndex, range, onProgress })), + debugStreamTrace: (session: DebugSessionId, request: RequestId, threadId: number, frame: StackFrame_Deserialize, chainIndex: number, range: Range, onProgress: Channel) => typedError(__TAURI_INVOKE("debug_stream_trace", { session, request, threadId, frame, chainIndex, range, onProgress })), /** Ends the running trace's terminal operation; `None` when no trace runs. */ debugStreamTraceAbort: (session: DebugSessionId) => typedError<{ kind: "interrupted" } | { kind: "stopped" } | /** Suspended threads that own a monitor the terminal may be waiting for: `(thread id, name)`. */ @@ -6307,6 +6314,10 @@ export type DebugCapabilities = { streamTrace: boolean, /** The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View. */ readMemory: boolean, + /** The program's machine code can be disassembled ([`DebugManager::disassemble`]): the Disassembly view. */ + disassemble: boolean, + /** Steps can move by one instruction ([`DebugManager::step_instruction`]). */ + instructionStepping: boolean, }; /** A completion the adapter offers for an expression (DAP `completions`). */ @@ -9453,6 +9464,33 @@ export type InstalledIntellijTheme = { active: boolean, }; +/** One disassembled instruction. */ +export type Instruction = Instruction_Serialize | Instruction_Deserialize; + +/** One disassembled instruction. */ +export type Instruction_Deserialize = { + /** Address as the adapter writes it (`0x5555…`); also a memory reference for the next request. */ + address: string, + /** The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`). */ + instruction: string, + /** Its machine code as hex (`488b45d8`), when the adapter sends it. */ + bytes?: string | null, + /** The function it belongs to, when the adapter names it (often on the first instruction only). */ + symbol?: string | null, +}; + +/** One disassembled instruction. */ +export type Instruction_Serialize = { + /** Address as the adapter writes it (`0x5555…`); also a memory reference for the next request. */ + address: string, + /** The instruction in the adapter's syntax (`mov -0x28(%rbp),%rax`). */ + instruction: string, + /** Its machine code as hex (`488b45d8`), when the adapter sends it. */ + bytes?: string | null, + /** The function it belongs to, when the adapter names it (often on the first instruction only). */ + symbol?: string | null, +}; + export type IntellijThemeFile = { /** The `themeProvider` id (what `laf.xml` names), or the file name without `.theme.json`. */ id: string, @@ -14475,7 +14513,9 @@ export type SshSigningKey = { inAgent: boolean, }; -export type StackFrame = { +export type StackFrame = StackFrame_Serialize | StackFrame_Deserialize; + +export type StackFrame_Deserialize = { id: number, name: string, path: IpcPath | null, @@ -14483,6 +14523,20 @@ export type StackFrame = { column: number, /** `subtle` frames (library/generated) are collapsed in the UI. */ presentationHint: string | null, + /** The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`). */ + instructionPointerReference?: string | null, +}; + +export type StackFrame_Serialize = { + id: number, + name: string, + path: IpcPath | null, + line: number, + column: number, + /** `subtle` frames (library/generated) are collapsed in the UI. */ + presentationHint: string | null, + /** The frame's program counter, for [`DebugManager::disassemble`] (DAP `instructionPointerReference`). */ + instructionPointerReference?: string | null, }; export type StagedText = { diff --git a/src/features/debugger/__tests__/actions.test.ts b/src/features/debugger/__tests__/actions.test.ts index 4f973ba99..1fd57c5fd 100644 --- a/src/features/debugger/__tests__/actions.test.ts +++ b/src/features/debugger/__tests__/actions.test.ts @@ -9,6 +9,7 @@ const ipc = vi.hoisted(() => { ok, runStop: vi.fn(() => ok(null)), debugStep: vi.fn(() => ok(null)), + debugStepInstruction: vi.fn(() => ok(null)), debugResume: vi.fn(() => ok(null)), debugForceStepOver: vi.fn(() => ok(null)), debugRunTo: vi.fn(() => ok(null)), @@ -107,6 +108,7 @@ import { forgetMemory, selectMemoryClass } from "../memory/memoryState"; import { forgetInstances, setInstancesLead, showInstances, useInstances } from "../memory/instancesState"; import { InstancesPane } from "../memory/InstancesPane"; import { forgetMemoryView, useMemoryView } from "../memoryView/memoryViewState"; +import { useDisassembly } from "../disassembly/disassemblyState"; const caps = (p: Partial = {}): DebugCapabilities => ({ restartFrame: false, @@ -125,6 +127,8 @@ const caps = (p: Partial = {}): DebugCapabilities => ({ liveEvaluate: false, streamTrace: false, readMemory: false, + disassemble: false, + instructionStepping: false, ...p, }); @@ -207,6 +211,9 @@ describe("debugger actions (IDEA parity)", () => { "debug.memory.showReferrers": undefined, "debug.memory.closeInstances": undefined, "debug.viewMemory": undefined, + "debug.showDisassembly": undefined, + "debug.stepOverInstruction": undefined, + "debug.stepIntoInstruction": undefined, "debug.toggleMethodBreakpoint": undefined, "debug.toggleFieldWatchpoint": undefined, "debug.traceStreamChain": undefined, @@ -657,6 +664,50 @@ describe("View Memory", () => { }); }); +describe("Disassembly and instruction steps", () => { + const notify = vi.fn(); + const show = vi.fn(); + beforeEach(() => { + provideNotificationService({ notify }); + provideToolWindowService({ show } as unknown as ToolWindowService); + useDisassembly.setState({ bySession: {}, revealPending: false }); + }); + + it.each([ + ["debug.stepOverInstruction", "Step Over Instruction"], + ["debug.stepIntoInstruction", "Step Into Instruction"], + ["debug.showDisassembly", "Disassembly"], + ])("%s says when the session's debugger cannot do it", async (id, what) => { + paused({ adapter: "debugpy" }); + await executeAction(id); + expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: `${what} is not supported by debugpy` })); + expect(ipc.debugStepInstruction).not.toHaveBeenCalled(); + expect(show).not.toHaveBeenCalled(); + expect(useDebug.getState().sessions[3]?.status).toBe("paused"); + }); + + it.each([ + ["debug.stepOverInstruction", "over"], + ["debug.stepIntoInstruction", "into"], + ] as const)("%s steps the paused thread by one instruction", async (id, kind) => { + paused({ adapter: "gdb", caps: caps({ instructionStepping: true }) }); + await executeAction(id); + await settle(); + expect(ipc.debugStepInstruction).toHaveBeenCalledWith(3, 1, kind); + expect(ipc.debugStep).not.toHaveBeenCalled(); + expect(useDebug.getState().sessions[3]).toMatchObject({ status: "running", frames: [] }); + }); + + it("opens the Disassembly view at a frame of the Frames list", async () => { + paused({ adapter: "lldb-dap", caps: caps({ disassemble: true }) }); + await executeAction("debug.showDisassembly", 70); + expect(show).toHaveBeenCalledWith("debug", true); + expect(useDisassembly.getState().revealPending).toBe(true); + expect(useDebug.getState().sessions[3]?.selectedFrame).toBe(70); + expect(notify).not.toHaveBeenCalled(); + }); +}); + describe("PHP debugging without Xdebug", () => { const php: RunConfig = { id: "php:index", diff --git a/src/features/debugger/__tests__/disassemblyView.test.tsx b/src/features/debugger/__tests__/disassemblyView.test.tsx new file mode 100644 index 000000000..95fed01d0 --- /dev/null +++ b/src/features/debugger/__tests__/disassemblyView.test.tsx @@ -0,0 +1,245 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; + +const ipc = vi.hoisted(() => ({ + debugDisassemble: vi.fn(), + debugScopes: vi.fn(), + debugVariables: vi.fn(), +})); + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { ...real, commands: { ...real.commands, ...ipc } }; +}); + +import type { DebugCapabilities, Instruction, StackFrame } from "@/platform/ipc"; +import { registerActions } from "@/platform/actions"; +import { setLocale } from "@/platform/i18n"; +import { hideContextMenu, useContextMenuStore } from "@/ui/Menu"; +import { useDebug, type DebugSession } from "../state"; +import { DebugToolWindow } from "../ui/DebugToolWindow"; +import { revealDisassembly, useDisassembly } from "../disassembly/disassemblyState"; +import { instructionText, spacedBytes } from "../disassembly/DisassemblyPane"; + +const ok = (data: T) => Promise.resolve({ status: "ok" as const, data }); +const fail = (message: string) => + Promise.resolve({ status: "error" as const, error: { kind: "invalidInput", message } }); + +/** A program of 4-byte instructions from 0x401000 (`sum`) to 0x402000; `before` works like lldb-dap's. */ +function program(reference: string, before: number, count: number): Instruction[] { + const start = Number(BigInt(reference)) - 4 * before; + return Array.from({ length: count }, (_, i) => start + 4 * i) + .filter((a) => a >= 0x401000 && a < 0x402000) + .map((a) => ({ + address: `0x${a.toString(16)}`, + instruction: `insn ${(a - 0x401000) / 4}`, + bytes: "488b45d8", + symbol: a === 0x401000 ? "sum" : null, + })); +} + +const caps = (p: Partial) => + ({ disassemble: true, instructionStepping: true, ...p }) as DebugCapabilities; + +const frame = (id: number, name: string, pc: string | null, path: string | null = "/p/main.c"): StackFrame => ({ + id, + name, + path, + line: 13, + column: 0, + presentationHint: null, + instructionPointerReference: pc, +}); + +const session: DebugSession = { + id: 1, + name: "app-c", + adapter: "gdb", + parent: null, + launch: null, + process: null, + status: "paused", + stoppedThread: 1, + stopReason: "breakpoint", + stopDescription: null, + threads: [{ id: 1, name: "main" }], + selectedThread: 1, + frames: [frame(0, "sum", "0x401100"), frame(1, "run", "0x401f00")], + selectedFrame: 0, + hits: 1, + stops: 1, + exitCode: null, + caps: caps({}), +}; + +const reads = () => ipc.debugDisassemble.mock.calls.map((c) => c.slice(1)); +const currentRow = () => screen.getAllByRole("row").find((r) => r.getAttribute("aria-current") === "location"); +const currentAddress = () => (currentRow() ? within(currentRow()!).getByRole("rowheader").textContent : null); +const patchSession = (p: Partial) => + act(() => useDebug.setState((s) => ({ sessions: { 1: { ...s.sessions[1]!, ...p } } }))); + +function openTab() { + render(); + fireEvent.click(screen.getByRole("tab", { name: "Disassembly" })); +} + +beforeEach(() => { + setLocale("en"); + useDisassembly.setState({ bySession: {}, revealPending: false }); + useDebug.setState({ sessions: { 1: session }, active: 1 }); + ipc.debugDisassemble.mockImplementation((_s: number, reference: string, before: number, count: number) => + Number(BigInt(reference)) < 0x1000 + ? fail(`disassemble failed: Cannot access memory at address ${reference}`) + : ok(program(reference, before, count)), + ); + ipc.debugScopes.mockImplementation(() => ok([])); + ipc.debugVariables.mockImplementation(() => ok([])); +}); + +afterEach(() => { + cleanup(); + hideContextMenu(); + vi.clearAllMocks(); +}); + +describe("Disassembly view", () => { + it("is a tab of sessions whose adapter disassembles, and only those", () => { + useDebug.setState({ sessions: { 1: { ...session, caps: caps({ disassemble: false }) } } }); + const { unmount } = render(); + expect(screen.queryByRole("tab", { name: "Disassembly" })).toBeNull(); + unmount(); + useDebug.setState({ sessions: { 1: session } }); + render(); + expect(screen.getByRole("tab", { name: "Disassembly" })).toBeTruthy(); + }); + + it("shows the selected frame's instructions with the current one highlighted", async () => { + openTab(); + await waitFor(() => expect(currentAddress()).toBe("0x00401100")); + expect(reads()).toEqual([["0x401100", 32, 128]]); + const row = currentRow()!; + const [bytes, instruction] = within(row).getAllByRole("gridcell"); + expect(bytes!.textContent).toBe("48 8B 45 D8"); + expect(instruction!.textContent).toBe("insn 64"); + expect(screen.getByRole("grid", { name: "Disassembly" })).toBeTruthy(); + }); + + it("moves the highlight through the instructions shown while stepping, and reads again past them", async () => { + openTab(); + await waitFor(() => expect(currentAddress()).toBe("0x00401100")); + // A step to an instruction already shown reads nothing. + patchSession({ status: "running", frames: [], selectedFrame: null }); + expect(screen.getByText("Instructions are shown while the program is paused.")).toBeTruthy(); + patchSession({ + status: "paused", + stops: 2, + stopReason: "step", + frames: [frame(0, "sum", "0x401104")], + selectedFrame: 0, + }); + await waitFor(() => expect(currentAddress()).toBe("0x00401104")); + expect(reads()).toHaveLength(1); + // One outside them (a call into another function) reads around it. + patchSession({ stops: 3, frames: [frame(0, "parse", "0x401e00")], selectedFrame: 0 }); + await waitFor(() => expect(currentAddress()).toBe("0x00401E00")); + expect(reads().at(-1)).toEqual(["0x401e00", 32, 128]); + }); + + it("follows frame selection, also to frames without source", async () => { + useDebug.setState({ + sessions: { + 1: { ...session, frames: [frame(9, "atoi@plt", "0x401040", null), ...session.frames], selectedFrame: 9 }, + }, + }); + openTab(); + await waitFor(() => expect(currentAddress()).toBe("0x00401040")); + expect(screen.getByText("atoi@plt")).toBeTruthy(); + // `sum` was shown at its start: its symbol labels the instructions that follow. + expect(screen.getByText("sum:")).toBeTruthy(); + patchSession({ selectedFrame: 0 }); + await waitFor(() => expect(currentAddress()).toBe("0x00401100")); + patchSession({ selectedFrame: 1 }); + await waitFor(() => expect(currentAddress()).toBe("0x00401F00")); + }); + + it("says why there is nothing to show, and does not ask again for the same address", async () => { + useDebug.setState({ sessions: { 1: { ...session, frames: [frame(0, "??", "0x10")] } } }); + openTab(); + expect((await screen.findByRole("alert")).textContent).toBe( + "disassemble failed: Cannot access memory at address 0x10", + ); + patchSession({ stops: 2 }); + expect(reads()).toHaveLength(1); + fireEvent.click(screen.getByRole("button", { name: "Refresh" })); + await waitFor(() => expect(reads()).toHaveLength(2)); + patchSession({ frames: [frame(0, "jit", null)] }); + expect(screen.getByText("The debugger gives no instruction address for this frame.")).toBeTruthy(); + }); + + it("offers instruction steps, disabled with the reason where the adapter has none", async () => { + const stepOver = vi.fn(); + const unregister = registerActions([ + { id: "debug.stepOverInstruction", title: "Step Over Instruction", run: stepOver }, + { id: "debug.stepIntoInstruction", title: "Step Into Instruction", run: vi.fn() }, + ]); + openTab(); + fireEvent.click(screen.getByRole("button", { name: "Step Over Instruction" })); + expect(stepOver).toHaveBeenCalled(); + patchSession({ caps: caps({ instructionStepping: false }) }); + const button = screen.getByRole("button", { name: "Step Over Instruction" }); + expect(button.hasAttribute("disabled")).toBe(true); + expect(button.getAttribute("data-tooltip") ?? button.getAttribute("title") ?? "").toContain( + "Instruction stepping is not supported by gdb", + ); + unregister(); + }); + + it("is offered on frames with an instruction address", async () => { + const show = vi.fn(); + const unregister = registerActions([ + { id: "debug.showDisassembly", title: "Show Disassembly", run: ({ arg }) => show(arg) }, + ]); + render(); + fireEvent.click(screen.getByRole("tab", { name: "Threads & Variables" })); + fireEvent.contextMenu(await screen.findByText("run")); + const item = useContextMenuStore + .getState() + .menu!.items.find((i) => "label" in i && i.label === "Show Disassembly") as { + run: () => void; + disabled?: boolean; + }; + expect(item.disabled).toBe(false); + act(() => item.run()); + await waitFor(() => expect(show).toHaveBeenCalledWith(1)); + hideContextMenu(); + patchSession({ caps: caps({ disassemble: false }) }); + fireEvent.contextMenu(await screen.findByText("run")); + const labels = useContextMenuStore.getState().menu!.items.map((i) => ("label" in i ? i.label : "-")); + expect(labels).not.toContain("Show Disassembly"); + unregister(); + }); + + it("comes to the front when Show Disassembly asks for it", () => { + render(); + fireEvent.click(screen.getByRole("tab", { name: "Console" })); + act(() => revealDisassembly()); + expect(screen.getByRole("tab", { name: "Disassembly" }).getAttribute("aria-selected")).toBe("true"); + expect(useDisassembly.getState().revealPending).toBe(false); + }); +}); + +describe("instruction text", () => { + it("spaces the bytes whether or not the adapter already did", () => { + expect(spacedBytes("488b45d8")).toBe("48 8B 45 D8"); + expect(spacedBytes("a1 03 5f f8")).toBe("A1 03 5F F8"); + expect(spacedBytes(null)).toBe(""); + }); + + it("pads lldb-dap's mnemonics to one width", () => { + expect(instructionText(" ldur x1, [x29, #-0x10]")).toBe("ldur x1, [x29, #-0x10]"); + expect(instructionText(" mov x9, sp")).toBe("mov x9, sp"); + expect(instructionText(" bl 0x10000062c ; hash at main.c:13")).toBe("bl 0x10000062c ; hash at main.c:13"); + expect(instructionText("mov -0x2c(%rbp),%eax")).toBe("mov -0x2c(%rbp),%eax"); + expect(instructionText(" ret")).toBe("ret"); + }); +}); diff --git a/src/features/debugger/__tests__/executionState.test.ts b/src/features/debugger/__tests__/executionState.test.ts index b9b9ff05f..821119d7b 100644 --- a/src/features/debugger/__tests__/executionState.test.ts +++ b/src/features/debugger/__tests__/executionState.test.ts @@ -30,6 +30,7 @@ import { adoptSession, handleDebugEvent, isThreadSuspended, + markInstructionStep, selectThread, resumeExecution, useDebug, @@ -82,6 +83,30 @@ describe("execution point state", () => { expect(useExecutionPoint.getState()).toMatchObject({ path, line: 9 }); }); + it("selects the frame without source an instruction step stopped in, and the first with source otherwise", async () => { + // GDB, one instruction into `atoi@plt` from `parse` (#5922): the innermost frame has no source. + const plt: StackFrame = { + id: 0, + name: "atoi@plt", + path: null, + line: 0, + column: 0, + presentationHint: null, + instructionPointerReference: "0x555555555090", + }; + ipc.debugStackTrace.mockResolvedValue(ipc.ok([plt, frame(5, 1)])); + markInstructionStep(1, true); + stopped(); + await settle(); + expect(useDebug.getState().sessions[1]?.selectedFrame).toBe(0); + expect(useExecutionPoint.getState().path).toBeNull(); + // Only that stop: the next (a line step, a breakpoint) selects the first frame with source again. + stopped(); + await settle(); + expect(useDebug.getState().sessions[1]?.selectedFrame).toBe(1); + expect(useExecutionPoint.getState()).toMatchObject({ path, line: 5 }); + }); + it("keeps a failed stack trace's reason for the frames list, and a retry loads the frames", async () => { const error = vi.spyOn(console, "error").mockImplementation(() => {}); ipc.debugStackTrace.mockResolvedValueOnce({ diff --git a/src/features/debugger/actions.ts b/src/features/debugger/actions.ts index 77e0949a7..5342980f8 100644 --- a/src/features/debugger/actions.ts +++ b/src/features/debugger/actions.ts @@ -56,6 +56,7 @@ import { refreshMemory, useMemory } from "./memory/memoryState"; import { closeInstances, instancesOutdated, showInstances, showReferrers, useInstances } from "./memory/instancesState"; import { jumpToClass } from "./memory/jumpToClass"; import { revealMemoryView, showMemoryAt } from "./memoryView/memoryViewState"; +import { revealDisassembly } from "./disassembly/disassemblyState"; import { captureHeap } from "./heap/heapState"; import { stopRecording, traceStreamChain } from "./streams/streamState"; import { isTracing, useStreamTrace } from "./streams/streamStore"; @@ -80,11 +81,13 @@ import { evaluate, isLive, justDetached, + markInstructionStep, pausedThread, rerunSession, revealFrame, rootOf, selectedFrame, + selectFrame, sessionSupports, showExecutionPoint, startBrowserSession, @@ -200,6 +203,20 @@ function viewMemory(reference: unknown) { toolWindowService().show("debug", true); } +/** + * Show Disassembly: the Disassembly view, at the frame `frameId` (from the Frames list) when given, + * otherwise at the selected frame. Adapters without `disassemble` say so instead. + */ +function showDisassembly(frameId: unknown) { + const s = activeSession(); + if (!s || !isLive(s)) return; + if (!sessionSupports("disassemble", s)) return notSupported("Disassembly", s); + if (typeof frameId === "number" && s.status === "paused" && s.frames.some((f) => f.id === frameId)) + selectFrame(s.id, frameId, false); + revealDisassembly(); + toolWindowService().show("debug", true); +} + /** * Smart Step Into: the calls on the current line, picked in the editor (the * dialog when they cannot be placed); one call (or none) steps straight in, like IDEA. @@ -524,6 +541,30 @@ export function registerDebugActions(): () => void { }, }); + // Its stop selects the frame that holds the program counter, also one without source. + const stepInstruction = (id: string, title: string, kind: "over" | "into", icon: string): Action => ({ + id, + title, + category: "Debug", + icon, + keywords: ["instruction", "assembly", "disassembly", "machine code"], + when: paused, + run: () => { + const t = pausedTarget(); + if (!t) return; + if (!sessionSupports("instructionStepping", t.s)) return notSupported(title, t.s); + markInstructionStep(t.s.id, true); + const sent = resumeExecution(t.s.id, () => call(commands.debugStepInstruction(t.s.id, t.thread, kind))); + void report( + title, + sent.catch((e: unknown) => { + markInstructionStep(t.s.id, false); + throw e; + }), + ); + }, + }); + return registerActions([ { id: "debug.pluginStart", @@ -920,6 +961,17 @@ export function registerDebugActions(): () => void { step("debug.stepOver", "Step Over", "over", "step-over"), step("debug.stepInto", "Step Into", "into", "step-into"), step("debug.stepOut", "Step Out", "out", "step-out"), + stepInstruction("debug.stepOverInstruction", "Step Over Instruction", "over", "step-over"), + stepInstruction("debug.stepIntoInstruction", "Step Into Instruction", "into", "step-into"), + { + // The Frames list passes the frame; without one, the selected frame. + id: "debug.showDisassembly", + title: "Show Disassembly", + category: "Debug", + keywords: ["assembly", "instructions", "machine code", "asm", "program counter"], + when: "debugSessionActive", + run: ({ arg }) => showDisassembly(arg), + }, { id: "debug.forceStepOver", title: "Force Step Over", diff --git a/src/features/debugger/disassembly/DisassemblyPane.module.css b/src/features/debugger/disassembly/DisassemblyPane.module.css new file mode 100644 index 000000000..13ff90bde --- /dev/null +++ b/src/features/debugger/disassembly/DisassemblyPane.module.css @@ -0,0 +1,122 @@ +.root { + display: flex; + flex-direction: column; + flex: 1; + min-width: 0; + min-height: 0; +} + +.toolbar { + flex: none; + display: flex; + align-items: center; + gap: var(--space-1); + padding: 4px 8px; + border-bottom: 1px solid var(--border); +} + +.frame { + margin-left: var(--space-2); + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--fg-subtle); + font-family: var(--font-mono); + font-size: var(--fs-code); +} + +.note, +.error { + flex: none; + padding: 4px 12px; + font-size: var(--fs-ui); + border-bottom: 1px solid var(--border); +} +.note { + color: var(--fg-subtle); +} +.error { + color: var(--fg); + background: var(--bg-feedback-error); + border-bottom-color: var(--border-feedback-error); + -webkit-user-select: text; + user-select: text; +} + +.empty { + flex: 1; + display: flex; + align-items: center; + justify-content: center; +} + +/* Every column is in the code font, so addresses, bytes and instructions line up from row to row. */ +.grid { + flex: 1; + min-height: 0; + overflow: auto; + padding: 4px 0; + font-family: var(--font-mono); + font-size: var(--fs-code); + line-height: var(--lh-code); + white-space: pre; + -webkit-user-select: text; + user-select: text; +} +.dimmed { + color: var(--fg-muted); +} + +.row { + display: flex; + align-items: center; + gap: 2ch; + padding: 0 12px 0 4px; + width: max-content; + min-width: 100%; +} +.head { + position: sticky; + top: -4px; + color: var(--fg-subtle); + background: var(--bg-app); +} +.row:not(.head, .symbol):hover { + background: var(--bg-hover); +} + +.marker { + display: inline-flex; + justify-content: center; + width: 12px; + flex: none; + color: var(--accent); +} +.address { + color: var(--fg-subtle); + min-width: 18ch; +} +.bytes { + color: var(--fg-subtle); +} +/* Disassemblers align operands with runs of spaces. */ +.instruction { + white-space: pre; +} + +.symbol { + padding-top: 4px; + color: var(--fg-strong); +} +.symbolName { + padding-left: calc(12px + 2ch); +} + +.current { + color: var(--fg-strong); + background: var(--bg-selected); +} +.current:hover { + background: var(--bg-selected); +} diff --git a/src/features/debugger/disassembly/DisassemblyPane.tsx b/src/features/debugger/disassembly/DisassemblyPane.tsx new file mode 100644 index 000000000..d5b4747c0 --- /dev/null +++ b/src/features/debugger/disassembly/DisassemblyPane.tsx @@ -0,0 +1,175 @@ +/** Disassembly tab of the Debug tool window: the selected frame's machine code around its program counter. */ +import { Fragment, useEffect, useMemo, useRef } from "react"; +import clsx from "clsx"; +import { EmptyState, Icon, IconButton, T } from "@/ui"; +import { formatMessage, useTx } from "@/platform/i18n"; +import type { Instruction } from "@/platform/ipc"; +import { formatAddress, parseAddress } from "../memoryView/bytes"; +import { selectedFrame, sessionSupports, type DebugSession } from "../state"; +import { readInstructions, sameAddress, showInstructionsAt, useDisassembly } from "./disassemblyState"; +import styles from "./DisassemblyPane.module.css"; + +const NONE: Instruction[] = []; + +/** `488b45d8` (GDB) or `48 8b 45 d8` (lldb-dap) as `48 8B 45 D8`. */ +export function spacedBytes(hex: string | null | undefined): string { + return (hex ?? "").replace(/\s+/g, "").toUpperCase().match(/../g)?.join(" ") ?? ""; +} + +/** + * The instruction with its mnemonic padded to one width: lldb-dap pads the mnemonic and operands + * of each instruction differently (` ldur x1, …`, ` mov x9, sp`). + */ +export function instructionText(text: string): string { + return text.trim().replace(/^(\S+)\s+/, (_, mnemonic: string) => `${mnemonic.padEnd(7)} `); +} + +/** The instruction's address in the address column (the adapter's text when it is not a number). */ +function addressText(i: Instruction, width: number): string { + const a = parseAddress(i.address); + return a === null ? i.address : formatAddress(a, width); +} + +export function DisassemblyPane({ session }: { session: DebugSession }) { + const tx = useTx(); + const id = session.id; + const entry = useDisassembly((s) => s.bySession[id]); + const paused = session.status === "paused"; + const frame = paused ? selectedFrame(session) : null; + const pc = frame?.instructionPointerReference ?? null; + + // Stepping and frame selection move the program counter: the view follows it. + useEffect(() => { + if (paused && pc) void showInstructionsAt(id, pc); + }, [id, paused, pc]); + + const instructions = entry?.instructions ?? NONE; + const width = useMemo( + () => (instructions.some((i) => (parseAddress(i.address) ?? 0n) > 0xffffffffn) ? 16 : 8), + [instructions], + ); + // As wide as the longest machine code shown, so every row's instruction starts in the same column. + const bytesWidth = useMemo( + () => ({ minWidth: `${Math.max(5, ...instructions.map((i) => spacedBytes(i.bytes).length))}ch` }), + [instructions], + ); + const current = useRef(null); + useEffect(() => { + current.current?.scrollIntoView?.({ block: "nearest" }); + }, [pc, instructions]); + + const stepping = sessionSupports("instructionStepping", session); + const noStepping = stepping + ? undefined + : formatMessage(tx("Instruction stepping is not supported by {adapter}"), { + adapter: session.adapter || tx("this debugger"), + }); + const busy = !!entry?.loading; + + return ( +
+
+ + + pc && void readInstructions(id, pc)} + /> + {frame && {frame.name}} +
+ {!paused && ( +
+ Instructions are shown while the program is paused. +
+ )} + {paused && frame && !pc && ( +
+ The debugger gives no instruction address for this frame. +
+ )} + {entry?.error && ( +
+ {entry.error} +
+ )} + {instructions.length > 0 ? ( +
+
+ + + {tx("Address")} + + + {tx("Bytes")} + + + {tx("Instruction")} + +
+ {instructions.map((i, n) => { + const isPc = !!pc && paused && sameAddress(i.address, pc); + const symbol = i.symbol && i.symbol !== instructions[n - 1]?.symbol ? i.symbol : null; + return ( + + {symbol && ( +
+ + {symbol}: + +
+ )} +
+ + {isPc && } + + + {addressText(i, width)} + + + {spacedBytes(i.bytes)} + + + {instructionText(i.instruction)} + +
+
+ ); + })} +
+ ) : ( + !entry?.error && + !busy && + paused && + !!pc && ( +
+ + No instructions at this address. + +
+ ) + )} +
+ ); +} diff --git a/src/features/debugger/disassembly/disassemblyState.ts b/src/features/debugger/disassembly/disassemblyState.ts new file mode 100644 index 000000000..dc07fb600 --- /dev/null +++ b/src/features/debugger/disassembly/disassemblyState.ts @@ -0,0 +1,94 @@ +/** Disassembly view (DAP `disassemble`): the instructions each session's view shows, and reading them. */ +import { create } from "zustand"; +import { call, commands, type DebugSessionId, type Instruction } from "@/platform/ipc"; +import { parseAddress } from "../memoryView/bytes"; +import { useDebug } from "../state"; + +/** Instructions read ahead of the program counter (adapters that cannot go back start at it), and in all. */ +export const BEFORE = 32; +export const COUNT = 128; + +export interface DisassemblyEntry { + instructions: Instruction[]; + /** The instruction pointer the last read was for. */ + reference: string | null; + error: string | null; + loading: boolean; +} + +interface DisassemblyState { + bySession: Record; + /** Set by Show Disassembly until the Debug tool window has brought the Disassembly view to the front. */ + revealPending: boolean; +} + +export const useDisassembly = create(() => ({ bySession: {}, revealPending: false })); + +const emptyEntry = (): DisassemblyEntry => ({ instructions: [], reference: null, error: null, loading: false }); + +/** The read each session waits for; a newer one (or `forgetDisassembly`) makes an older reply stale. */ +const inflight = new Map(); + +function patchEntry(id: DebugSessionId, patch: Partial) { + useDisassembly.setState((s) => ({ + bySession: { ...s.bySession, [id]: { ...(s.bySession[id] ?? emptyEntry()), ...patch } }, + })); +} + +/** Whether `a` and `b` are the same address (`0x00401000` and `0x401000`). */ +export function sameAddress(a: string, b: string): boolean { + const x = parseAddress(a); + return x === null ? a === b : x === parseAddress(b); +} + +/** Reads the instructions around `pc`, whatever is shown. */ +export async function readInstructions(id: DebugSessionId, pc: string): Promise { + const session = useDebug.getState().sessions[id]; + if (!session || session.status !== "paused") return; + const token = Symbol("disassembly"); + inflight.set(id, token); + patchEntry(id, { reference: pc, loading: true }); + try { + const instructions = await call(commands.debugDisassemble(id, pc, BEFORE, COUNT)); + if (inflight.get(id) !== token) return; + patchEntry(id, { instructions, error: null }); + } catch (e) { + if (inflight.get(id) !== token) return; + patchEntry(id, { instructions: [], error: e instanceof Error ? e.message : String(e) }); + } finally { + if (inflight.get(id) === token) { + inflight.delete(id); + patchEntry(id, { loading: false }); + } + } +} + +/** + * Shows the instructions around `pc`, the selected frame's instruction pointer. Instructions already + * shown stay when they hold it, so the highlight moves through them while stepping; a failed read is + * not repeated for the same `pc` (Refresh does that). + */ +export function showInstructionsAt(id: DebugSessionId, pc: string): Promise { + const entry = useDisassembly.getState().bySession[id]; + if (entry?.instructions.some((i) => sameAddress(i.address, pc))) return Promise.resolve(); + if (entry?.reference === pc && (entry.loading || entry.error)) return Promise.resolve(); + return readInstructions(id, pc); +} + +export function revealDisassembly(): void { + useDisassembly.setState({ revealPending: true }); +} + +/** The Debug tool window shows the Disassembly view: the request is done. */ +export function disassemblyRevealed(): void { + useDisassembly.setState({ revealPending: false }); +} + +export function forgetDisassembly(id: DebugSessionId): void { + inflight.delete(id); + useDisassembly.setState((s) => { + if (!(id in s.bySession)) return s; + const { [id]: _gone, ...rest } = s.bySession; + return { bySession: rest }; + }); +} diff --git a/src/features/debugger/index.ts b/src/features/debugger/index.ts index e49dd4860..2159f85c9 100644 --- a/src/features/debugger/index.ts +++ b/src/features/debugger/index.ts @@ -56,6 +56,7 @@ import { streamTraceKind } from "./streams/streamTraceKind"; import { installHeapContext } from "./heap/heapDumpFiles"; import { forgetMemory } from "./memory/memoryState"; import { forgetMemoryView } from "./memoryView/memoryViewState"; +import { forgetDisassembly } from "./disassembly/disassemblyState"; import { closeStaleStreamChooser, forgetStreamTrace } from "./streams/streamState"; /** Whether a breakpoint popover, debugger dialog or chooser is open. */ @@ -177,6 +178,7 @@ export function activate(): () => void { if (id in s.sessions) continue; forgetMemory(Number(id)); forgetMemoryView(Number(id)); + forgetDisassembly(Number(id)); forgetInstances(Number(id)); forgetHeapCapture(Number(id)); forgetStreamTrace(Number(id)); diff --git a/src/features/debugger/state.ts b/src/features/debugger/state.ts index 1dd122597..ef44268b4 100644 --- a/src/features/debugger/state.ts +++ b/src/features/debugger/state.ts @@ -1278,8 +1278,18 @@ export function topFrame(frames: StackFrame[]): StackFrame | null { return frames.find((f) => f.path && f.presentationHint !== "label") ?? frames[0] ?? null; } +/** Sessions whose next stop ends an instruction step: it selects the frame that holds the program counter. */ +const instructionSteps = new Set(); + +/** The step about to be sent moves by one instruction (`false`: it was not sent after all). */ +export function markInstructionStep(id: DebugSessionId, on: boolean) { + if (on) instructionSteps.add(id); + else instructionSteps.delete(id); +} + function markTerminated(id: DebugSessionId) { stopTaskbarFlash(); + instructionSteps.delete(id); forgetImports(id); const page = serverPages.get(id)?.page; if (serverPages.delete(id) && page != null) void stopSession(page); @@ -1333,8 +1343,11 @@ export function selectFrame(id: DebugSessionId, frameId: number, reveal = true) void loadLocals(id, frameId); } -/** `newStop`: false when returning to an earlier stop, whose breakpoint hit was handled when it happened. */ -async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean, newStop = true) { +/** + * `newStop`: false when returning to an earlier stop, whose breakpoint hit was handled when it happened. + * `exact`: select the innermost frame even without source (after an instruction step into a library). + */ +async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean, newStop = true, exact = false) { if (useDebug.getState().sessions[id]?.framesError) patch(id, { framesError: null }); const before = useDebug.getState().sessions[id]; let frames: StackFrame[] = []; @@ -1348,7 +1361,7 @@ async function loadFrames(id: DebugSessionId, threadId: number, reveal: boolean, const s = useDebug.getState().sessions[id]; if (!s || s.status !== "paused" || s.selectedThread !== threadId || s.frames !== before?.frames) return; patch(id, { frames, framesError }); - const top = topFrame(frames); + const top = exact ? (frames[0] ?? null) : topFrame(frames); if (newStop && top?.path && (s.stopReason === "breakpoint" || s.stopReason === "function breakpoint")) { void logSuspendingHit(id, top); consumeTemporary(top.path, top.line); @@ -1646,7 +1659,13 @@ export function handleDebugEvent(id: DebugSessionId, event: DebugEvent) { updateExecutionPoint(); void loadThreads(id); // The stop a stream trace ends in would bring the source tab over the trace tab that shows its result. - void loadFrames(id, event.threadId, !markTraceStop(id, event.threadId, s.stops + 1)); + void loadFrames( + id, + event.threadId, + !markTraceStop(id, event.threadId, s.stops + 1), + true, + instructionSteps.delete(id), + ); const dbg = workflowSettings().debugger; try { // A session debugged in place from Services shows its debugger there (#4773). diff --git a/src/features/debugger/ui/DebugToolWindow.tsx b/src/features/debugger/ui/DebugToolWindow.tsx index 6179e210d..5945349a6 100644 --- a/src/features/debugger/ui/DebugToolWindow.tsx +++ b/src/features/debugger/ui/DebugToolWindow.tsx @@ -61,6 +61,8 @@ import { pageProfileItems, useJsProfile } from "../js/profile"; import { MemoryView } from "../memory/MemoryView"; import { MemoryViewPane } from "../memoryView/MemoryViewPane"; import { memoryViewRevealed, useMemoryView } from "../memoryView/memoryViewState"; +import { DisassemblyPane } from "../disassembly/DisassemblyPane"; +import { disassemblyRevealed, useDisassembly } from "../disassembly/disassemblyState"; import { DebugConsole } from "./DebugConsole"; import { VariablesView, type VarRoot } from "./VariablesView"; import { useExpressionCompletion } from "./ExpressionCompletion"; @@ -131,7 +133,7 @@ function MoreActions() { ); } -type Tab = "variables" | "console" | "memory" | "memoryView" | "network"; +type Tab = "variables" | "console" | "memory" | "memoryView" | "disassembly" | "network"; /** The view the user last picked; the tool window opens on it again (Console until one is picked). */ let chosenTab: Tab = "console"; @@ -230,7 +232,11 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod }>(() => ({ session: undefined, status: undefined, - tab: useMemoryView.getState().revealPending ? "memoryView" : chosenTab, + tab: useDisassembly.getState().revealPending + ? "disassembly" + : useMemoryView.getState().revealPending + ? "memoryView" + : chosenTab, })); // View Memory brings the Memory View to the front, also in the tool window it opens (above). useEffect(() => { @@ -243,19 +249,31 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod reveal(useMemoryView.getState().revealPending, true); return useMemoryView.subscribe((s) => reveal(s.revealPending, false)); }, []); + // Show Disassembly does the same for the Disassembly view. + useEffect(() => { + const reveal = (pending: boolean, shown: boolean) => { + if (!pending) return; + disassemblyRevealed(); + chosenTab = "disassembly"; + if (!shown) setView((v) => (v.tab === "disassembly" ? v : { ...v, tab: "disassembly" })); + }; + reveal(useDisassembly.getState().revealPending, true); + return useDisassembly.subscribe((s) => reveal(s.revealPending, false)); + }, []); if (active && (view.session !== active.startedAt || view.status !== active.status)) setView({ session: active.startedAt, status: active.status, // A breakpoint or exception brings Threads & Variables to the front unless its Focus On Breakpoint // is off; finishing a step keeps the tab the user is on (e.g. Console, to watch the output while - // stepping), and so do Memory and the Memory View. + // stepping), and so do Memory, the Memory View and the Disassembly view. tab: active.status === "starting" ? "console" : active.status === "paused" && view.tab !== "memory" && view.tab !== "memoryView" && + view.tab !== "disassembly" && active.stopReason !== "step" && workflowSettings().debugger.variablesOnBreakpoint ? "variables" @@ -267,10 +285,13 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod const hasNetwork = !!active && sessionSupports("jsPage", active); // The native Memory View follows the adapter's `readMemory` support. const hasMemoryView = !!active && sessionSupports("readMemory", active); - // The selected session may be one without the Memory, Memory View or Network tab. + // So does the Disassembly view, its `disassemble` support. + const hasDisassembly = !!active && sessionSupports("disassemble", active); + // The selected session may be one without the Memory, Memory View, Disassembly or Network tab. const tab: Tab = (view.tab === "memory" && !hasMemory) || (view.tab === "memoryView" && !hasMemoryView) || + (view.tab === "disassembly" && !hasDisassembly) || (view.tab === "network" && !hasNetwork) ? "variables" : view.tab; @@ -332,6 +353,7 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod ["console", "Console"], ...(hasMemory ? [["memory", "Memory"] as const] : []), ...(hasMemoryView ? [["memoryView", "Memory View"] as const] : []), + ...(hasDisassembly ? [["disassembly", "Disassembly"] as const] : []), ...(hasNetwork ? [["network", "Network"] as const] : []), ] as const ).map(([id, label]) => ( @@ -382,6 +404,8 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod ) ) : tab === "memoryView" ? ( + ) : tab === "disassembly" ? ( + ) : tab === "network" ? ( ) : ( @@ -561,6 +585,15 @@ function FramesPane({ session }: { session: DebugSession }) { disabled: !paused || !sessionSupports("restartFrame", session), run: () => void executeAction("debug.resetFrame"), }, + ...(sessionSupports("disassemble", session) + ? [ + { + label: "Show Disassembly", + disabled: !paused || !item.frame.instructionPointerReference, + run: () => void executeAction("debug.showDisassembly", item.frame.id), + }, + ] + : []), { kind: "separator" }, { label: showAll ? "Hide Library Frames" : "Show All Frames", diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 95700b320..000df3bbb 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4670,5 +4670,15 @@ "Memory is read while the program is paused.": "Memory is read while the program is paused.", "The memory at {address} cannot be read.": "The memory at {address} cannot be read.", "Enter an address or an expression, or choose View Memory on a variable.": "Enter an address or an expression, or choose View Memory on a variable.", - "“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0].": "“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0]." + "“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0].": "“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0].", + "Disassembly": "Disassembly", + "Show Disassembly": "Show Disassembly", + "Step Over Instruction": "Step Over Instruction", + "Step Into Instruction": "Step Into Instruction", + "Instruction stepping is not supported by {adapter}": "Instruction stepping is not supported by {adapter}", + "this debugger": "this debugger", + "Instructions are shown while the program is paused.": "Instructions are shown while the program is paused.", + "The debugger gives no instruction address for this frame.": "The debugger gives no instruction address for this frame.", + "Bytes": "Bytes", + "No instructions at this address.": "No instructions at this address." } diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 7b45de287..59844b63b 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -11260,5 +11260,15 @@ "Memory is read while the program is paused.": "程序暂停时才会读取内存。", "The memory at {address} cannot be read.": "无法读取 {address} 处的内存。", "Enter an address or an expression, or choose View Memory on a variable.": "输入地址或表达式,或在变量上选择“查看内存”。", - "“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0].": "“{expression}”不是地址。请输入指针或地址,例如 &buffer[0]。" + "“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0].": "“{expression}”不是地址。请输入指针或地址,例如 &buffer[0]。", + "Disassembly": "反汇编", + "Show Disassembly": "显示反汇编", + "Step Over Instruction": "单步跳过指令", + "Step Into Instruction": "单步进入指令", + "Instruction stepping is not supported by {adapter}": "{adapter} 不支持按指令单步执行", + "this debugger": "此调试器", + "Instructions are shown while the program is paused.": "程序暂停时才会显示指令。", + "The debugger gives no instruction address for this frame.": "调试器没有提供此帧的指令地址。", + "Bytes": "字节", + "No instructions at this address.": "此地址没有指令。" }