feat(debugger): native Memory View for C/C++ debugging (#6674)

Native debug sessions whose adapter supports readMemory get a read-only Memory View tab: an address or expression field, address/hex/ASCII rows aligned to 16 bytes with the target byte marked, paging and a re-read after each stop. View Memory is offered on variables and watches that carry a memoryReference. The client now declares supportsMemoryReferences in initialize and keeps memoryReference on variables and evaluation results; adapter errors are shown without ending the session.

Closes #5921

Co-authored-by: bertyhell <[email protected]>
Цей коміт міститься в:
Bert Verhelstтаbertyhell authored and GitHub committed 2026-11-29 15:52:32 +08:00
1 джерело 68abe345cc
коміт 5fb8f21c60
22 files changed
+1311 -11

No files matched your search

+44 -1
Переглянути файл
@@ -20,6 +20,7 @@ mod js_debug;
mod jvm_memory;
pub mod kotlin;
pub mod kotlin_lsp;
mod memory;
mod session;
mod stream_trace;
pub mod unity;
@@ -33,6 +34,7 @@ use ide_language::LanguageRegistry;
pub use js_cdp::JsResponseRule;
pub use js_debug::JsResponseBody;
pub use jvm_memory::*;
pub use memory::{MAX_READ, MemoryBlock};
use parking_lot::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -159,6 +161,8 @@ pub struct DebugCapabilities {
/// A stream chain can be traced while the program runs it ([`DebugManager::stream_trace`]).
/// Can change during the session, like `jvm_instances`.
pub stream_trace: bool,
/// The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View.
pub read_memory: bool,
}
/// Result of [`DebugManager::redefine_classes`].
@@ -249,6 +253,10 @@ pub struct Variable {
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
#[specta(optional)]
pub lazy: bool,
/// Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[specta(optional)]
pub memory_reference: Option<String>,
}
/// A completion the adapter offers for an expression (DAP `completions`).
@@ -687,6 +695,7 @@ pub(crate) fn capabilities_from(caps: &Value) -> DebugCapabilities {
js_page: false,
live_evaluate: false,
stream_trace: false,
read_memory: has("supportsReadMemoryRequest"),
}
}
@@ -775,9 +784,15 @@ pub(crate) fn variable_from(v: &Value) -> Variable {
variables_reference: v.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: s("evaluateName"),
lazy: v.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
memory_reference: memory_reference(v),
}
}
/// A variable's or evaluation result's `memoryReference`.
fn memory_reference(v: &Value) -> Option<String> {
v.get("memoryReference").and_then(Value::as_str).filter(|r| !r.is_empty()).map(str::to_owned)
}
async fn session_variables(session: &Session, reference: i64) -> IdeResult<Vec<Variable>> {
let body =
session.conn.request_timeout("variables", json!({ "variablesReference": reference }), REQUEST_TIMEOUT).await?;
@@ -801,6 +816,7 @@ async fn resolve_in(session: &Session, variable: Variable) -> IdeResult<Variable
value: value.value,
variables_reference: value.variables_reference,
lazy: value.lazy,
memory_reference: value.memory_reference.or(variable.memory_reference),
},
_ => variable,
})
@@ -1333,7 +1349,7 @@ impl DebugManager {
"supportsProgressReporting": true,
// kotlin-lsp sends `invalidated` either way.
"supportsInvalidatedEvent": is_kotlin_lsp,
"supportsMemoryReferences": false,
"supportsMemoryReferences": true,
"supportsArgsCanBeInterpretedByShell": false,
}),
INIT_TIMEOUT,
@@ -1791,6 +1807,7 @@ impl DebugManager {
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: evaluate_name.or(Some(name)),
lazy: false,
memory_reference: memory_reference(&body),
})
}
@@ -1928,6 +1945,7 @@ impl DebugManager {
variables_reference: body.get("variablesReference").and_then(Value::as_i64).unwrap_or(0),
evaluate_name: Some(expression),
lazy: body.pointer("/presentationHint/lazy").and_then(Value::as_bool).unwrap_or(false),
memory_reference: memory_reference(&body),
};
if !session.spec.resolve_lazy_variables {
return Ok(result);
@@ -2184,6 +2202,31 @@ impl DebugManager {
Ok(())
}
/// `count` bytes (at most [`MAX_READ`]) from `offset` bytes after `memory_reference`, which
/// comes from a variable, an evaluation result or an earlier read's address.
pub async fn read_memory(
&self,
s: DebugSessionId,
memory_reference: String,
offset: i64,
count: u32,
) -> IdeResult<MemoryBlock> {
let session = self.session(s)?;
if !session.supports("supportsReadMemoryRequest") {
return Err(IdeError::unavailable(format!("debug adapter `{}` cannot read memory", session.adapter)));
}
let count = count.min(MAX_READ);
let body = session
.conn
.request_timeout(
"readMemory",
json!({ "memoryReference": memory_reference, "offset": offset, "count": count }),
REQUEST_TIMEOUT,
)
.await?;
memory::memory_block(&body, count)
}
pub fn capabilities(&self, s: DebugSessionId) -> IdeResult<DebugCapabilities> {
Ok(session_capabilities(&*self.session(s)?))
}
+88
Переглянути файл
@@ -0,0 +1,88 @@
//! Raw memory of a native program (DAP `readMemory`), for the Memory View.
use base64::Engine;
use ide_core::{IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use specta::Type;
/// The most bytes one read asks for: a few pages of the view, never a whole mapping.
pub const MAX_READ: u32 = 64 * 1024;
/// Answer of `readMemory`: `data` starts at `address`; the `unreadable_bytes` after it could not be read.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct MemoryBlock {
/// Address of the first byte, as the adapter writes it (`0x7ffd…`; may be wider than 53 bits).
pub address: String,
pub data: Vec<u8>,
pub unreadable_bytes: u32,
}
/// `readMemory`'s body for a read of `count` bytes. Adapters leave `data` out (or empty) when
/// nothing could be read; the bytes asked for then count as unreadable.
pub(crate) fn memory_block(body: &Value, count: u32) -> IdeResult<MemoryBlock> {
let address = match body.get("address") {
Some(Value::String(a)) if !a.is_empty() => a.clone(),
Some(Value::Number(n)) => n.to_string(),
_ => return Err(IdeError::internal("the debug adapter answered readMemory without an address")),
};
let mut data = match body.get("data").and_then(Value::as_str) {
Some(b64) if !b64.is_empty() => base64::engine::general_purpose::STANDARD
.decode(b64)
.map_err(|e| IdeError::internal(format!("the debug adapter sent memory that is not base64: {e}")))?,
_ => Vec::new(),
};
data.truncate(count as usize);
// At most the rest of what was asked for (the data is never more than that).
let rest = count - data.len() as u32;
let unreadable_bytes = match body.get("unreadableBytes").and_then(Value::as_u64) {
Some(n) => n.min(u64::from(rest)) as u32,
None if data.is_empty() => count,
None => 0,
};
Ok(MemoryBlock { address, data, unreadable_bytes })
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn decodes_the_bytes_and_keeps_the_address_as_written() {
// The reporter's `&msg[0]` (#5921): "Hello, World!\n" and its terminator.
let body = json!({"address": "0x000000016FDFE9A0", "data": "SGVsbG8sIFdvcmxkIQoA"});
let block = memory_block(&body, 15).unwrap();
assert_eq!(block.address, "0x000000016FDFE9A0");
assert_eq!(block.data, b"Hello, World!\n\0");
assert_eq!(block.unreadable_bytes, 0);
}
#[test]
fn missing_data_is_unreadable_not_empty() {
let block = memory_block(&json!({"address": "0x0"}), 256).unwrap();
assert!(block.data.is_empty());
assert_eq!(block.unreadable_bytes, 256);
let block = memory_block(&json!({"address": "0x0", "data": "", "unreadableBytes": 16}), 256).unwrap();
assert_eq!(block.unreadable_bytes, 16);
}
#[test]
fn a_partial_read_reports_the_rest_as_unreadable() {
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 13}), 16).unwrap();
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1, 2][..], 13));
// Counts that disagree with the request are clamped to it.
let block = memory_block(&json!({"address": "0x1000", "data": "AAEC", "unreadableBytes": 99}), 16).unwrap();
assert_eq!(block.unreadable_bytes, 13);
let block = memory_block(&json!({"address": "0x1000", "data": "AAECAw=="}), 2).unwrap();
assert_eq!((block.data.as_slice(), block.unreadable_bytes), (&[0u8, 1][..], 0));
}
#[test]
fn rejects_answers_without_an_address_or_with_bad_data() {
assert!(memory_block(&json!({"data": "AA=="}), 1).is_err());
assert!(memory_block(&json!({"address": "0x10", "data": "not base64!"}), 1).is_err());
assert_eq!(memory_block(&json!({"address": 4096, "data": "AA=="}), 1).unwrap().address, "4096");
}
}
+90
Переглянути файл
@@ -6,6 +6,7 @@ mod stream_trace;
use super::*;
use crate::adapter::{AdapterIo, LaunchFuture};
use base64::Engine;
use ide_core::IdeEvent;
use ide_core::event::DebugEvent;
use ide_jsonrpc::framing;
@@ -195,6 +196,9 @@ struct Script {
accept: &'static [&'static str],
/// Requests of the adapter's own answered with a body and followed by events.
custom: Option<fn(&Value) -> Option<CustomReply>>,
/// Advertise `supportsReadMemoryRequest`: memory below 0x1010 reads as its low address byte,
/// memory from there on is unmapped.
read_memory: bool,
}
/// The answer to a request of the adapter's own: the response body, then events (name, body).
@@ -242,6 +246,7 @@ impl Default for Script {
empty_thread_responses: 0,
accept: &[],
custom: None,
read_memory: false,
}
}
}
@@ -328,6 +333,7 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
"supportsDataBreakpoints": true,
"supportsStepInTargetsRequest": true,
"supportsRestartFrame": true,
"supportsReadMemoryRequest": script.read_memory,
"exceptionBreakpointFilters": [
{"filter": "raised", "label": "Raised"},
{"filter": "uncaught", "label": "Uncaught", "default": true, "description": "Uncaught exceptions"},
@@ -570,7 +576,29 @@ async fn fake_adapter<S: AsyncRead + AsyncWrite + Unpin + Send + 'static>(stream
]})
),
},
"evaluate" if msg["arguments"]["expression"] == "&msg[0]" => ok!(
msg,
json!({"result": "0x1000 \"Hello\"", "type": "char *", "variablesReference": 1, "memoryReference": "0x1000"})
),
"evaluate" => ok!(msg, json!({"result": "42", "type": "int", "variablesReference": 0})),
"readMemory" => {
let args = &msg["arguments"];
let reference = args["memoryReference"].as_str().unwrap().trim_start_matches("0x");
let start = i64::from_str_radix(reference, 16).unwrap() + args["offset"].as_i64().unwrap_or(0);
let count = args["count"].as_i64().unwrap();
const END: i64 = 0x1010;
if start >= END {
send!(
json!({"type": "response", "request_seq": msg["seq"], "command": "readMemory", "success": false, "message": format!("Cannot access memory at address {start:#x}")})
);
} else {
let bytes: Vec<u8> = (start..(start + count).min(END)).map(|a| a as u8).collect();
ok!(
msg,
json!({"address": format!("{start:#x}"), "data": base64::engine::general_purpose::STANDARD.encode(&bytes), "unreadableBytes": count - bytes.len() as i64})
);
}
}
"completions" => ok!(
msg,
json!({"targets": [
@@ -1952,6 +1980,68 @@ async fn function_and_data_breakpoints_are_stored_and_sent() {
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn memory_view_reads_memory_from_a_reference() {
let h = harness(Script { read_memory: true, ..Script::default() });
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert_eq!(
h.request("initialize")["arguments"]["supportsMemoryReferences"],
true,
"adapters only send references when asked"
);
assert!(h.manager.capabilities(id).unwrap().read_memory);
let pointer = h.manager.evaluate_in(id, Some(10), "&msg[0]".into(), Some("watch".into())).await.unwrap();
assert_eq!(pointer.memory_reference.as_deref(), Some("0x1000"));
let plain = h.manager.evaluate(id, Some(10), "n".into()).await.unwrap();
assert_eq!(plain.memory_reference, None);
let block = h.manager.read_memory(id, "0x1000".into(), 0, 8).await.unwrap();
assert_eq!(block, MemoryBlock { address: "0x1000".into(), data: (0..8).collect(), unreadable_bytes: 0 });
assert_eq!(h.request("readMemory")["arguments"], json!({"memoryReference": "0x1000", "offset": 0, "count": 8}));
// Paging back and forth goes through `offset` on the same reference; the end of the mapping
// comes back as unreadable bytes.
let block = h.manager.read_memory(id, "0x1000".into(), 8, 16).await.unwrap();
assert_eq!((block.address.as_str(), block.data.len(), block.unreadable_bytes), ("0x1008", 8, 8));
assert_eq!(block.data[0], 0x08);
// Unmapped memory is the adapter's error, and the session goes on.
let err = h.manager.read_memory(id, "0x1000".into(), 0x20, 16).await.unwrap_err();
assert!(err.to_string().contains("Cannot access memory at address 0x1020"), "{err}");
assert!(!h.manager.threads(id).await.unwrap().is_empty());
let _ = h.manager.read_memory(id, "0x1000".into(), 0, u32::MAX).await;
let last = h.log.lock().iter().rev().find(|m| m["command"] == "readMemory").cloned().unwrap();
assert_eq!(last["arguments"]["count"], MAX_READ, "one read never asks for more than a few pages");
h.manager.stop(id).await.unwrap();
}
#[tokio::test]
async fn memory_view_says_when_the_adapter_cannot_read_memory() {
let h = harness(Script::default());
let id = h.start(config()).await.unwrap();
h.wait_event(|e| matches!(e, DebugEvent::Stopped { .. })).await;
assert!(!h.manager.capabilities(id).unwrap().read_memory);
let err = h.manager.read_memory(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 read memory"), "{err}");
assert!(!h.commands().iter().any(|c| c == "readMemory"), "nothing is sent to an adapter without support");
h.manager.stop(id).await.unwrap();
}
#[test]
fn variables_keep_their_memory_reference() {
let v = variable_from(
&json!({"name": "words", "value": "0x4010", "variablesReference": 3, "memoryReference": "0x4010"}),
);
assert_eq!(v.memory_reference.as_deref(), Some("0x4010"));
assert_eq!(variable_from(&json!({"name": "n", "value": "1", "memoryReference": ""})).memory_reference, None);
let json = serde_json::to_value(variable_from(&json!({"name": "n", "value": "1"}))).unwrap();
assert!(json.get("memoryReference").is_none(), "absent, not null, for the UI's optional field");
}
#[tokio::test]
async fn smart_step_into_and_reset_frame() {
let h = harness(Script::default());
+29 -2
Переглянути файл
@@ -1,11 +1,12 @@
//! 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 and Set Value.
//! Into, Reset Frame, Force Step Over, Force Run to Cursor, Set Value and the Memory View.
//!
//! Ignored by default (needs the adapters installed). Run with
//! `OPENIDEA_DAP_FIXTURES=<dir> cargo test -p ide-dap --test real_adapters -- --ignored --nocapture`
//! where `<dir>` holds `py/app.py`, `node/app.js`, `go/demo` (built with `-N -l`),
//! `rust/target/debug/demo` and `c/main`. Adapters not found on `PATH` are skipped.
//! `rust/target/debug/demo` and `c/main` (whose loop function also has a `char msg[]` local, for
//! the Memory View). Adapters not found on `PATH` are skipped.
use ide_core::event::DebugEvent;
use ide_core::{DebugSessionId, IdeEvent, SharedSink};
@@ -280,6 +281,32 @@ async fn scenario(case: &Case) -> Result<Vec<String>, String> {
let caps = m.capabilities(s).map_err(|e| e.message)?;
report.push(format!("capabilities: {caps:?}"));
// Memory View: the bytes at an address expression (the C fixture's `msg`), and an unmapped address.
if caps.read_memory {
match m.evaluate_in(s, Some(top.id), "&msg[0]".into(), Some("watch".into())).await {
Ok(v) => match v.memory_reference {
Some(r) => match m.read_memory(s, r.clone(), 0, 16).await {
Ok(b) => report.push(format!(
"memory view `&msg[0]` ({r}): {} = {:02x?} {:?}, {} unreadable",
b.address,
b.data,
String::from_utf8_lossy(&b.data),
b.unreadable_bytes
)),
Err(e) => report.push(format!("memory view `&msg[0]`: FAILED {}", e.message)),
},
None => report.push(format!("memory view `&msg[0]` = {}: no memory reference", v.value)),
},
Err(e) => report.push(format!("memory view `&msg[0]`: not evaluated ({})", e.message)),
}
match m.read_memory(s, "0x0".into(), 0, 16).await {
Ok(b) => report.push(format!("memory view 0x0: {} bytes, {} unreadable", b.data.len(), b.unreadable_bytes)),
Err(e) => report.push(format!("memory view 0x0: error `{}`", e.message)),
}
} else {
report.push("memory view: readMemory not supported".into());
}
// 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) {
+14
Переглянути файл
@@ -557,6 +557,19 @@ pub async fn debug_evaluate_in(
host.debugger.evaluate_in(session, frame_id, expression, context).await
}
/// Memory View: `count` bytes from `offset` bytes after `memory_reference` (a variable's,
/// an evaluation result's or an earlier read's address).
#[command(trust = trusted)]
pub async fn debug_read_memory(
host: &Host,
session: DebugSessionId,
memory_reference: String,
offset: i64,
count: u32,
) -> IdeResult<ide_dap::MemoryBlock> {
host.debugger.read_memory(session, memory_reference, offset, 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<Vec<BreakpointState>> {
@@ -1083,6 +1096,7 @@ ide_command::domain!(
debug_jvm_thread_dump,
debug_listen_for_jvm,
debug_pause,
debug_read_memory,
debug_redefine_classes,
debug_replace_breakpoints,
debug_resolve_variable,
+54
Переглянути файл
@@ -192,6 +192,60 @@ test("Memory gives class filtering the available toolbar width and exposes chang
await expect(changed).toBeChecked();
});
test("Memory View shows the bytes at an address expression with hex and ASCII aligned", async ({ workbench: page }) => {
await stubDesktop(page);
await page.evaluate(async (id) => {
// The reporter's `msg` (#5921) where GDB put it, 9 bytes into its row; other bytes count up.
const msg = "Hello, World!\n\0";
const at = 0x7fffffff9f69;
const h = window.__ipc.handlers;
const caps = { readMemory: true };
h.debug_capabilities = () => caps;
h.debug_evaluate_in = (args) => ({
name: args.expression,
value: '0x7fffffff9f69 "Hello, World!\\n"',
typeName: "const char *",
variablesReference: 0,
evaluateName: args.expression,
memoryReference: "0x7fffffff9f69",
});
h.debug_read_memory = (args) => {
const start = Number(args.memoryReference) + (args.offset as number);
const data = Array.from({ length: args.count as number }, (_, i) => {
const a = start + i;
return a >= at && a < at + msg.length ? msg.charCodeAt(a - at) : a & 0xff;
});
return { address: `0x${start.toString(16)}`, data, unreadableBytes: 0 };
};
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 });
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: "Memory View" }).click();
const field = debug.getByRole("textbox", { name: "Address or expression" });
await field.fill("&msg[0]");
await field.press("Enter");
const grid = debug.getByRole("grid", { name: "Memory", exact: true });
await expect(grid.getByRole("rowheader", { name: "0x00007FFFFFFF9F60" })).toBeVisible();
expect(await ipcCalls(page, "debug_read_memory")).toEqual([
{ session: SESSION, memoryReference: "0x7fffffff9f69", offset: -9, count: 256 },
]);
// Monospaced columns: each row's hex and ASCII start where the row above starts them.
const rows = grid.getByRole("row");
const left = async (row: number, cell: number) =>
(await rows.nth(row).getByRole("gridcell").nth(cell).boundingBox())!.x;
for (const cell of [0, 1]) expect(await left(2, cell)).toBeCloseTo(await left(1, cell), 0);
await expect(rows.nth(1).getByRole("gridcell").nth(1)).toHaveText("`abcdefghHello, ");
await expect(rows.nth(2).getByRole("gridcell").nth(1)).toHaveText(/^World!\.\./);
});
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);
+1
Переглянути файл
@@ -209,6 +209,7 @@ debug_jvm_memory_referrers trusted project_host bin
debug_jvm_thread_dump trusted project_host bindings async
debug_listen_for_jvm trusted project_host bindings async
debug_pause trusted project_host bindings async
debug_read_memory trusted project_host bindings async
debug_redefine_classes trusted project_host bindings async
debug_replace_breakpoints trusted project_host bindings async
debug_resolve_variable trusted project_host bindings async
+19
Переглянути файл
@@ -531,6 +531,11 @@ export const commands = {
*/
debugListenForJvm: (request: RequestId, host: string, port: number) => typedError<number, IdeError>(__TAURI_INVOKE("debug_listen_for_jvm", { request, host, port })),
debugPause: (session: DebugSessionId, threadId: number) => typedError<null, IdeError>(__TAURI_INVOKE("debug_pause", { session, threadId })),
/**
* Memory View: `count` bytes from `offset` bytes after `memory_reference` (a variable's,
* an evaluation result's or an earlier read's address).
*/
debugReadMemory: (session: DebugSessionId, memoryReference: string, offset: number, count: number) => typedError<MemoryBlock, IdeError>(__TAURI_INVOKE("debug_read_memory", { session, memoryReference, offset, count })),
/** HotSwap (Reload Changed Classes) in a java-debug session. */
debugRedefineClasses: (session: DebugSessionId) => typedError<HotSwapResult, IdeError>(__TAURI_INVOKE("debug_redefine_classes", { session })),
/** Replaces all of this window's line breakpoints with `files`. */
@@ -6300,6 +6305,8 @@ export type DebugCapabilities = {
* Can change during the session, like `jvm_instances`.
*/
streamTrace: boolean,
/** The program's raw memory can be read ([`DebugManager::read_memory`]): the Memory View. */
readMemory: boolean,
};
/** A completion the adapter offers for an expression (DAP `completions`). */
@@ -10966,6 +10973,14 @@ export type McpTransport = "stdio" | "http" | "sse";
*/
export type McpUiRequest = { type: "confirm"; client: string; tool: string; subject: string; project: string; detail: string | null } | { type: "openFile"; path: IpcPath; line: number | null; column: number | null } | { type: "agentRun"; name: string; command: string; cwd: IpcPath; env: { [key in string]: string } } | { type: "runConfiguration"; config: unknown };
/** Answer of `readMemory`: `data` starts at `address`; the `unreadable_bytes` after it could not be read. */
export type MemoryBlock = {
/** Address of the first byte, as the adapter writes it (`0x7ffd…`; may be wider than 53 bits). */
address: string,
data: number[],
unreadableBytes: number,
};
export type MemoryCategory =
/** The backend and its WebView processes. */
"app" | "languageServer" |
@@ -15435,6 +15450,8 @@ export type Variable_Deserialize = {
* `variables` returns for `variables_reference` holds the value and its children.
*/
lazy?: boolean,
/** Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`). */
memoryReference?: string | null,
};
export type Variable_Serialize = {
@@ -15449,6 +15466,8 @@ export type Variable_Serialize = {
* `variables` returns for `variables_reference` holds the value and its children.
*/
lazy?: boolean,
/** Where the value points to or is stored, for [`DebugManager::read_memory`] (DAP `memoryReference`). */
memoryReference?: string | null,
};
/** Version Control › Confirmation. */
+41 -1
Переглянути файл
@@ -37,6 +37,9 @@ const ipc = vi.hoisted(() => {
]),
),
debugScopes: vi.fn(() => ok([])),
debugReadMemory: vi.fn((_s: number, reference: string, offset: number, count: number) =>
ok({ address: reference, data: Array<number>(count).fill(offset & 0xff), unreadableBytes: 0 }),
),
debugStart: vi.fn((_launch: { extraJson: string | null }) => ok(42)),
debugSetBreakpoints: vi.fn(() => ok([])),
debugBreakpointStates: vi.fn(() => ok([])),
@@ -82,7 +85,11 @@ import { clearContext, setContext } from "@/platform/context";
import { intellijMacos } from "@/platform/keymaps/intellij-macos";
import type { DebugCapabilities, RunConfig } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { provideNotificationService } from "@/workbench/contributions";
import {
provideNotificationService,
provideToolWindowService,
type ToolWindowService,
} from "@/workbench/contributions";
import { registerDebugActions } from "../actions";
import { breakpointsOf, loadBreakpoints, toggleBreakpoint, updateBreakpoint } from "../breakpoints/store";
import {
@@ -99,6 +106,7 @@ import { useOverlays } from "../ui/popoverStore";
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";
const caps = (p: Partial<DebugCapabilities> = {}): DebugCapabilities => ({
restartFrame: false,
@@ -116,6 +124,7 @@ const caps = (p: Partial<DebugCapabilities> = {}): DebugCapabilities => ({
jsPage: false,
liveEvaluate: false,
streamTrace: false,
readMemory: false,
...p,
});
@@ -197,6 +206,7 @@ describe("debugger actions (IDEA parity)", () => {
"debug.memory.jumpToSource": undefined,
"debug.memory.showReferrers": undefined,
"debug.memory.closeInstances": undefined,
"debug.viewMemory": undefined,
"debug.toggleMethodBreakpoint": undefined,
"debug.toggleFieldWatchpoint": undefined,
"debug.traceStreamChain": undefined,
@@ -617,6 +627,36 @@ describe("debugger actions (IDEA parity)", () => {
});
});
describe("View Memory", () => {
const notify = vi.fn();
const show = vi.fn();
beforeEach(() => {
provideNotificationService({ notify });
provideToolWindowService({ show } as unknown as ToolWindowService);
useMemoryView.setState({ bySession: {}, revealPending: false });
});
it("says when the session's debugger cannot read memory", async () => {
paused({ adapter: "debugpy" });
await executeAction("debug.viewMemory", "0x7fffffff9f69");
expect(notify).toHaveBeenCalledWith(expect.objectContaining({ title: "View Memory is not supported by debugpy" }));
expect(ipc.debugReadMemory).not.toHaveBeenCalled();
expect(show).not.toHaveBeenCalled();
});
it("opens the Memory View at a variable's memory reference", async () => {
paused({ adapter: "lldb-dap", caps: caps({ readMemory: true }) });
await executeAction("debug.viewMemory", "0x7fffffff9f69");
expect(show).toHaveBeenCalledWith("debug", true);
expect(useMemoryView.getState().revealPending).toBe(true);
await settle();
expect(ipc.debugReadMemory).toHaveBeenCalledWith(3, "0x7fffffff9f69", -9, 256);
expect(useMemoryView.getState().bySession[3]).toMatchObject({ expression: "0x7fffffff9f69", start: -9 });
expect(notify).not.toHaveBeenCalled();
forgetMemoryView(3);
});
});
describe("PHP debugging without Xdebug", () => {
const php: RunConfig = {
id: "php:index",
+70
Переглянути файл
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import {
PAGE_BYTES,
ROW_BYTES,
addressWidth,
asciiChar,
formatAddress,
hexByte,
memoryRows,
parseAddress,
rowOffset,
} from "../memoryView/bytes";
// The reporter's `constexpr char msg[] = "Hello, World!\n";` (#5921), as `memory read` printed it.
const MSG = [0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21, 0x0a, 0x00];
describe("parseAddress", () => {
it.each([
["0x7fffffff9f69", 0x7fffffff9f69n],
["0X16FDFE9A0", 0x16fdfe9a0n],
["140737488330601", 140737488330601n],
// A value that starts with its address: GDB's and LLDB's `char *`.
['0x000000016fdfe9a0 "Hello, World!\\n"', 0x16fdfe9a0n],
// Past 2^53, where a Number would round.
["0xfffffffffffffff1", 0xfffffffffffffff1n],
])("%s", (text, address) => {
expect(parseAddress(text)).toBe(address);
});
it.each(["", "{...}", "1.5", "-4", "msg", "0xzz", "12abc", '"0x10"'])("%s is not an address", (text) => {
expect(parseAddress(text)).toBeNull();
});
});
describe("rows", () => {
it("starts rows at multiples of 16 and keeps hex and ASCII byte for byte", () => {
// GDB put the reporter's string at an address 9 bytes into its row: the page starts 9 bytes earlier.
const target = 0x7fffffff9f69n;
expect(rowOffset(target)).toBe(9);
const start = target - BigInt(rowOffset(target));
const data = [...Array<number>(9).fill(0xaa), ...MSG];
const rows = memoryRows(start, data, 0);
expect(rows.map((r) => r.address)).toEqual([0x7fffffff9f60n, 0x7fffffff9f70n]);
expect(rows.every((r) => r.address % BigInt(ROW_BYTES) === 0n)).toBe(true);
expect(rows[0]!.bytes).toHaveLength(ROW_BYTES);
expect(rows[1]!.bytes).toHaveLength(data.length - ROW_BYTES);
const text = rows.flatMap((r) => r.bytes).slice(9);
expect(text.map(hexByte).join(" ")).toBe("48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 0A 00");
expect(text.map(asciiChar).join("")).toBe("Hello, World!..");
});
it("shows unreadable bytes as ?? after the ones read", () => {
const rows = memoryRows(0x1000n, [0x41, 0x42], 18);
expect(rows).toHaveLength(2);
expect(rows[0]!.bytes.map(hexByte).slice(0, 3)).toEqual(["41", "42", "??"]);
expect(rows[1]!.bytes).toEqual([null, null, null, null]);
expect(rows[0]!.bytes.map(asciiChar).join("")).toBe(`AB${" ".repeat(14)}`);
});
it("widens the address column only for addresses past 32 bits", () => {
expect(addressWidth(memoryRows(0xffff_ff00n, Array<number>(PAGE_BYTES).fill(0), 0))).toBe(8);
expect(addressWidth(memoryRows(0xffff_ff10n, Array<number>(PAGE_BYTES).fill(0), 0))).toBe(16);
expect(formatAddress(0x9f60n, 8)).toBe("0x00009F60");
expect(formatAddress(0x7fffffff9f60n, 16)).toBe("0x00007FFFFFFF9F60");
});
it("prints only printable ASCII", () => {
expect([0x00, 0x1f, 0x20, 0x7e, 0x7f, 0xff].map(asciiChar).join("")).toBe(".. ~..");
});
});
+260
Переглянути файл
@@ -0,0 +1,260 @@
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(() => ({
debugReadMemory: vi.fn(),
debugEvaluateIn: vi.fn(),
debugScopes: vi.fn(),
debugVariables: vi.fn(),
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
return { ...real, commands: { ...real.commands, ...ipc } };
});
import type { DebugCapabilities, MemoryBlock, Variable } from "@/platform/ipc";
import { registerActions } from "@/platform/actions";
import { setLocale } from "@/platform/i18n";
import { hideContextMenu, useContextMenuStore } from "@/ui/Menu";
import { addWatch, removeAllWatches, useDebug, type DebugSession } from "../state";
import { DebugToolWindow } from "../ui/DebugToolWindow";
import { revealMemoryView, showMemoryAt, useMemoryView } from "../memoryView/memoryViewState";
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
const fail = (message: string) =>
Promise.resolve({ status: "error" as const, error: { kind: "invalidInput", message } });
// The reporter's `msg` (#5921) at the address GDB gave it, 9 bytes into its row.
const MSG = "Hello, World!\n\0";
const MSG_AT = 0x7fffffff9f69;
/** A process whose memory is `MSG` at `MSG_AT` and each other byte's low address byte; nothing below 0x1000 is mapped. */
function memoryAt(reference: string, offset: number, count: number): MemoryBlock {
const start = Number(BigInt(reference)) + offset;
const data = Array.from({ length: count }, (_, i) => {
const a = start + i;
return a >= MSG_AT && a < MSG_AT + MSG.length ? MSG.charCodeAt(a - MSG_AT) : a & 0xff;
});
return { address: `0x${start.toString(16)}`, data, unreadableBytes: 0 };
}
const caps = (readMemory: boolean) => ({ readMemory }) as DebugCapabilities;
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: [{ id: 7, name: "run", path: "/p/src/main.c", line: 13, column: 0, presentationHint: null }],
selectedFrame: 7,
hits: 1,
stops: 1,
exitCode: null,
caps: caps(true),
};
const variable = (p: Partial<Variable>): Variable => ({
name: "x",
value: "",
typeName: null,
variablesReference: 0,
evaluateName: null,
...p,
});
function readArgs() {
return ipc.debugReadMemory.mock.calls.map((c) => c.slice(1));
}
async function goTo(expression: string) {
const field = screen.getByRole("textbox", { name: "Address or expression" });
fireEvent.change(field, { target: { value: expression } });
fireEvent.submit(field.closest("form")!);
}
beforeEach(() => {
setLocale("en");
useMemoryView.setState({ bySession: {}, revealPending: false });
useDebug.setState({ sessions: { 1: session }, active: 1 });
ipc.debugReadMemory.mockImplementation((_s: number, reference: string, offset: number, count: number) =>
Number(BigInt(reference)) + offset < 0x1000
? fail(
`readMemory failed: Cannot access memory at address 0x${(Number(BigInt(reference)) + offset).toString(16)}`,
)
: ok(memoryAt(reference, offset, count)),
);
ipc.debugEvaluateIn.mockImplementation((_s: number, _f: number | null, expression: string) => {
if (expression === "&msg[0]")
return ok(
variable({ name: expression, value: `0x7fffffff9f69 "Hello, World!\\n"`, memoryReference: "0x7fffffff9f69" }),
);
if (expression === "0x2000") return ok(variable({ name: expression, value: "8192", typeName: "long" }));
if (expression === "total") return ok(variable({ name: expression, value: "{a = 1}", typeName: "struct t" }));
if (expression === "null_ptr") return ok(variable({ name: expression, value: "0x0", memoryReference: "0x0" }));
return fail(`No symbol "${expression}" in current context.`);
});
ipc.debugScopes.mockImplementation(() => ok([{ name: "Locals", variablesReference: 1, expensive: false }]));
ipc.debugVariables.mockImplementation(() =>
ok([
variable({
name: "items",
value: "0x7fffffff9f40",
typeName: "const char **",
evaluateName: "items",
memoryReference: "0x7fffffff9f40",
}),
variable({ name: "total", value: "6", typeName: "int", evaluateName: "total" }),
]),
);
});
afterEach(() => {
cleanup();
hideContextMenu();
vi.clearAllMocks();
});
describe("native Memory View", () => {
it("is a tab of sessions whose adapter reads memory, and only those", () => {
useDebug.setState({ sessions: { 1: { ...session, caps: caps(false) } } });
const { unmount } = render(<DebugToolWindow />);
expect(screen.queryByRole("tab", { name: "Memory View" })).toBeNull();
unmount();
useDebug.setState({ sessions: { 1: session } });
render(<DebugToolWindow />);
fireEvent.click(screen.getByRole("tab", { name: "Memory View" }));
expect(screen.getByText("Enter an address or an expression, or choose View Memory on a variable.")).toBeTruthy();
// A JVM session's own Memory tab is a different view.
expect(screen.queryByRole("tab", { name: "Memory" })).toBeNull();
});
it("shows the bytes at an address expression in aligned address, hex and ASCII columns", async () => {
render(<DebugToolWindow />);
fireEvent.click(screen.getByRole("tab", { name: "Memory View" }));
await goTo("&msg[0]");
await waitFor(() => expect(screen.getAllByRole("row")).toHaveLength(1 + 16));
expect(ipc.debugEvaluateIn).toHaveBeenCalledWith(1, 7, "&msg[0]", "watch");
// One read of a page, from the start of the row that holds the address.
expect(readArgs()).toEqual([["0x7fffffff9f69", -9, 256]]);
const [, first, second] = screen.getAllByRole("row");
expect(within(first!).getByRole("rowheader").textContent).toBe("0x00007FFFFFFF9F60");
expect(within(second!).getByRole("rowheader").textContent).toBe("0x00007FFFFFFF9F70");
const [hex, ascii] = within(first!).getAllByRole("gridcell");
expect(hex!.textContent).toBe("606162636465666768" + "48656C6C6F2C20");
expect(ascii!.textContent).toBe("`abcdefghHello, ");
expect(within(second!).getAllByRole("gridcell")[1]!.textContent!.slice(0, 8)).toBe("World!..");
// The byte at the address is marked, in both columns.
const marked = first!.querySelectorAll("[class*=target]");
expect([...marked].map((m) => m.textContent)).toEqual(["48", "H"]);
});
it("turns pages and reads the page again after each stop", async () => {
render(<DebugToolWindow />);
fireEvent.click(screen.getByRole("tab", { name: "Memory View" }));
await goTo("&msg[0]");
await waitFor(() => expect(readArgs()).toHaveLength(1));
fireEvent.click(await screen.findByRole("button", { name: "Next Page" }));
await waitFor(() => expect(readArgs().at(-1)).toEqual(["0x7fffffff9f69", 247, 256]));
fireEvent.click(await screen.findByRole("button", { name: "Previous Page" }));
await waitFor(() => expect(readArgs().at(-1)).toEqual(["0x7fffffff9f69", -9, 256]));
const before = readArgs().length;
// Running: nothing is read; the next stop reads the same page again.
act(() => useDebug.setState({ sessions: { 1: { ...session, status: "running" } } }));
expect(screen.getByText("Memory is read while the program is paused.")).toBeTruthy();
expect(readArgs()).toHaveLength(before);
act(() => useDebug.setState({ sessions: { 1: { ...session, stops: 2, stopReason: "step" } } }));
await waitFor(() => expect(readArgs()).toHaveLength(before + 1));
expect(readArgs().at(-1)).toEqual(["0x7fffffff9f69", -9, 256]);
expect(screen.getByRole("tab", { name: "Memory View" }).getAttribute("aria-selected")).toBe("true");
});
it("says why memory cannot be shown, and the session goes on", async () => {
render(<DebugToolWindow />);
fireEvent.click(screen.getByRole("tab", { name: "Memory View" }));
await goTo("null_ptr");
expect((await screen.findByRole("alert")).textContent).toBe(
"readMemory failed: Cannot access memory at address 0x0",
);
await goTo("total");
expect((await screen.findByRole("alert")).textContent).toBe(
"“total” is not an address. Enter a pointer or an address, such as &buffer[0].",
);
await goTo("nope");
expect((await screen.findByRole("alert")).textContent).toBe('No symbol "nope" in current context.');
// A number is an address: its value is read as one.
await goTo("0x2000");
await waitFor(() => expect(readArgs().at(-1)).toEqual(["0x2000", 0, 256]));
expect(screen.queryByRole("alert")).toBeNull();
expect(useDebug.getState().sessions[1]!.status).toBe("paused");
});
it("aligns pages of references that are not addresses after a first read", async () => {
ipc.debugReadMemory.mockImplementation((_s: number, _reference: string, offset: number, count: number) =>
ok(memoryAt(`${MSG_AT}`, offset, count)),
);
await act(() => showMemoryAt(1, "mem:frame/7", "buffer"));
expect(readArgs()).toEqual([
["mem:frame/7", 0, 256],
["mem:frame/7", -9, 256],
]);
expect(useMemoryView.getState().bySession[1]).toMatchObject({ start: -9, target: BigInt(MSG_AT) });
});
it("offers View Memory on variables and watches with a memory reference", async () => {
const viewMemory = vi.fn();
const unregister = registerActions([
{ id: "debug.viewMemory", title: "View Memory", run: ({ arg }) => viewMemory(arg) },
]);
render(<DebugToolWindow />);
fireEvent.click(screen.getByRole("tab", { name: "Threads & Variables" }));
const labels = async (name: string) => {
fireEvent.contextMenu((await screen.findByText(name)).closest("[role=treeitem]")!);
return (useContextMenuStore.getState().menu?.items ?? []).map((i) => ("label" in i ? i.label : "-"));
};
expect(await labels("total")).toContain("Copy Value");
expect(await labels("total")).not.toContain("View Memory");
hideContextMenu();
expect(await labels("items")).toContain("View Memory");
const view = useContextMenuStore.getState().menu!.items.find((i) => "label" in i && i.label === "View Memory");
act(() => (view as { run: () => void }).run());
await waitFor(() => expect(viewMemory).toHaveBeenCalledWith("0x7fffffff9f40"));
hideContextMenu();
// A watch carries its evaluation result's reference.
act(() => addWatch("&msg[0]"));
expect(await labels("&msg[0]")).toContain("View Memory");
const watch = useContextMenuStore.getState().menu!.items.find((i) => "label" in i && i.label === "View Memory");
act(() => (watch as { run: () => void }).run());
await waitFor(() => expect(viewMemory).toHaveBeenLastCalledWith("0x7fffffff9f69"));
hideContextMenu();
// Not where the adapter cannot read memory.
act(() => useDebug.setState({ sessions: { 1: { ...session, caps: caps(false) } } }));
expect(await labels("items")).not.toContain("View Memory");
hideContextMenu();
act(() => removeAllWatches());
unregister();
});
it("comes to the front when View Memory asks for it", () => {
render(<DebugToolWindow />);
fireEvent.click(screen.getByRole("tab", { name: "Console" }));
act(() => revealMemoryView());
expect(screen.getByRole("tab", { name: "Memory View" }).getAttribute("aria-selected")).toBe("true");
expect(useMemoryView.getState().revealPending).toBe(false);
});
it("opens on the Memory View when View Memory opened the tool window", () => {
act(() => revealMemoryView());
render(<DebugToolWindow />);
expect(screen.getByRole("tab", { name: "Memory View" }).getAttribute("aria-selected")).toBe("true");
});
});
+24
Переглянути файл
@@ -55,6 +55,7 @@ import { cancelHotSwapBuild, reloadChangedClasses } from "./hotswap";
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 { captureHeap } from "./heap/heapState";
import { stopRecording, traceStreamChain } from "./streams/streamState";
import { isTracing, useStreamTrace } from "./streams/streamStore";
@@ -185,6 +186,20 @@ function notSupported(what: string, s: DebugSession) {
});
}
/**
* View Memory: the Memory View, at `reference` (a variable's or watch's memory reference) when given.
* Adapters without `readMemory` (most besides the native ones) say so instead.
*/
function viewMemory(reference: unknown) {
const s = activeSession();
if (!s || !isLive(s)) return;
if (!sessionSupports("readMemory", s)) return notSupported("View Memory", s);
// The address field shows the address itself: entered again, it reads the same memory.
if (typeof reference === "string") void showMemoryAt(s.id, reference, reference);
revealMemoryView();
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.
@@ -1210,6 +1225,15 @@ export function registerDebugActions(): () => void {
removeSpecialIn(path);
},
},
{
// Variables and watches pass their memory reference; without one the Memory View opens on its address field.
id: "debug.viewMemory",
title: "View Memory",
category: "Debug",
keywords: ["memory", "hex", "bytes", "address", "pointer", "dump"],
when: "debugSessionActive",
run: ({ arg }) => viewMemory(arg),
},
{
id: "debug.evaluate",
title: "Evaluate Expression…",
+2
Переглянути файл
@@ -55,6 +55,7 @@ import { heapEditorKind } from "./heap/heapEditorKind";
import { streamTraceKind } from "./streams/streamTraceKind";
import { installHeapContext } from "./heap/heapDumpFiles";
import { forgetMemory } from "./memory/memoryState";
import { forgetMemoryView } from "./memoryView/memoryViewState";
import { closeStaleStreamChooser, forgetStreamTrace } from "./streams/streamState";
/** Whether a breakpoint popover, debugger dialog or chooser is open. */
@@ -175,6 +176,7 @@ export function activate(): () => void {
for (const id of Object.keys(prev.sessions)) {
if (id in s.sessions) continue;
forgetMemory(Number(id));
forgetMemoryView(Number(id));
forgetInstances(Number(id));
forgetHeapCapture(Number(id));
forgetStreamTrace(Number(id));
+109
Переглянути файл
@@ -0,0 +1,109 @@
.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);
}
.toolbar .address {
flex: 1;
min-width: 0;
max-width: 480px;
margin-right: var(--space-1);
}
.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 the hex and the ASCII of a row line up with the rows above. */
.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;
gap: 2ch;
padding: 0 12px;
width: max-content;
}
.head {
position: sticky;
top: -4px;
color: var(--fg-subtle);
background: var(--bg-app);
}
.row:not(.head):hover {
background: var(--bg-hover);
}
.row > .address {
color: var(--fg-subtle);
min-width: 18ch;
}
.hex {
display: flex;
gap: 1ch;
}
/* A wider gap halfway, like a hex editor's two groups of eight. */
.hex > .byte:nth-child(8) {
margin-right: 1ch;
}
/* Spaces and dots stand for bytes, so keep every one. */
.ascii {
white-space: pre;
}
.target {
color: var(--fg-strong);
background: var(--bg-selected);
border-radius: 2px;
}
.unreadable {
color: var(--fg-faint);
}
+171
Переглянути файл
@@ -0,0 +1,171 @@
/** Memory View tab of the Debug tool window: a native program's memory as address, hex and ASCII columns. */
import { useEffect, useMemo, useState } from "react";
import clsx from "clsx";
import { EmptyState, IconButton, Input, T } from "@/ui";
import { formatMessage, useTx } from "@/platform/i18n";
import type { DebugSession } from "../state";
import {
ROW_BYTES,
addressWidth,
asciiChar,
formatAddress,
hexByte,
memoryRows,
parseAddress,
type MemoryRow,
} from "./bytes";
import { goToExpression, readPage, turnPage, useMemoryView } from "./memoryViewState";
import styles from "./MemoryViewPane.module.css";
const COLUMN_OFFSETS = Array.from({ length: ROW_BYTES }, (_, i) => i.toString(16).toUpperCase().padStart(2, "0"));
function Row({ row, width, target }: { row: MemoryRow; width: number; target: bigint | null }) {
const marked = target !== null && target >= row.address && target < row.address + BigInt(ROW_BYTES);
const at = marked ? Number(target - row.address) : -1;
return (
<div className={styles.row} role="row">
<span role="rowheader" className={styles.address}>
{formatAddress(row.address, width)}
</span>
<span role="gridcell" className={styles.hex}>
{COLUMN_OFFSETS.map((_, i) => {
const byte = row.bytes[i];
return (
<span key={i} className={clsx(styles.byte, i === at && styles.target, byte === null && styles.unreadable)}>
{byte === undefined ? " " : hexByte(byte)}
</span>
);
})}
</span>
<span role="gridcell" className={styles.ascii}>
{row.bytes.map((byte, i) => (
<span key={i} className={clsx(i === at && styles.target, byte === null && styles.unreadable)}>
{asciiChar(byte)}
</span>
))}
</span>
</div>
);
}
export function MemoryViewPane({ session }: { session: DebugSession }) {
const tx = useTx();
const id = session.id;
const entry = useMemoryView((s) => s.bySession[id]);
const [text, setText] = useState(entry?.expression ?? "");
const committed = entry?.expression ?? "";
// View Memory on a variable fills the field with its expression.
const [shown, setShown] = useState(committed);
if (shown !== committed) {
setShown(committed);
setText(committed);
}
const paused = session.status === "paused";
// The memory may have changed at each stop: the page is read again (also when the tab comes back).
const stale = !!entry?.reference && paused && !entry.loading && entry.readAtStop !== session.stops;
useEffect(() => {
if (stale) void readPage(id);
}, [id, stale]);
const block = entry?.block ?? null;
const rows = useMemo(() => {
const start = block ? parseAddress(block.address) : null;
return block && start !== null ? memoryRows(start, block.data, block.unreadableBytes) : [];
}, [block]);
const width = addressWidth(rows);
const busy = !!entry?.loading;
const canPage = paused && !!entry?.reference && !busy;
return (
<div className={styles.root} aria-busy={busy || undefined}>
<form
className={styles.toolbar}
role="toolbar"
aria-label={tx("Memory View")}
onSubmit={(e) => {
e.preventDefault();
void goToExpression(id, text);
}}
>
<Input
mono
className={styles.address}
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Address or expression, such as &buffer[0]"
aria-label="Address or expression"
disabled={!paused}
/>
<IconButton
icon="arrow-right"
type="submit"
title="Go to Address"
size="small"
disabled={!paused || !text.trim()}
/>
<IconButton
icon="chevron-up"
title="Previous Page"
size="small"
disabled={!canPage}
onClick={() => void turnPage(id, -1)}
/>
<IconButton
icon="chevron-down"
title="Next Page"
size="small"
disabled={!canPage}
onClick={() => void turnPage(id, 1)}
/>
<IconButton icon="refresh" title="Refresh" size="small" disabled={!canPage} onClick={() => void readPage(id)} />
</form>
{!paused && (
<div className={styles.note} role="status">
<T>Memory is read while the program is paused.</T>
</div>
)}
{entry?.error && (
<div className={styles.error} role="alert">
{entry.error}
</div>
)}
{block && block.data.length === 0 && (
<div className={styles.error} role="alert">
{formatMessage(tx("The memory at {address} cannot be read."), { address: block.address })}
</div>
)}
{rows.length > 0 ? (
<div className={clsx(styles.grid, !paused && styles.dimmed)} role="grid" aria-label={tx("Memory")}>
<div className={clsx(styles.row, styles.head)} role="row">
<span role="columnheader" className={styles.address}>
{tx("Address")}
</span>
<span role="columnheader" className={styles.hex}>
{COLUMN_OFFSETS.map((o) => (
<span key={o} className={styles.byte}>
{o}
</span>
))}
</span>
<span role="columnheader" className={styles.ascii}>
{tx("ASCII")}
</span>
</div>
{rows.map((row) => (
<Row key={row.address.toString()} row={row} width={width} target={entry?.target ?? null} />
))}
</div>
) : (
!entry?.error &&
!busy && (
<div className={styles.empty}>
<EmptyState title="Memory View">
<T>Enter an address or an expression, or choose View Memory on a variable.</T>
</EmptyState>
</div>
)
)}
</div>
);
}
+64
Переглянути файл
@@ -0,0 +1,64 @@
/** Rows of the native Memory View: aligned address, hexadecimal bytes and their ASCII text. */
/** Bytes per row; rows start at addresses that are multiples of it. */
export const ROW_BYTES = 16;
/** Bytes one page of the view reads. */
export const PAGE_BYTES = 256;
export interface MemoryRow {
/** Address of the row's first byte. */
address: bigint;
/** `null`: a byte the debugger could not read. */
bytes: (number | null)[];
}
/**
* An address as DAP writes it (`readMemory`'s `address`: hexadecimal with `0x`, decimal otherwise),
* or the address at the start of a value (`0x7ffd5c4a "Hello"`, `140737488346985`). `null` when the
* text doesn't start with one.
*/
export function parseAddress(text: string): bigint | null {
const m = /^\s*(0[xX][0-9a-fA-F]+|\d+)(?![\w.])/.exec(text);
if (!m) return null;
try {
return BigInt(m[1]!);
} catch {
return null;
}
}
/** How many bytes `address` lies past the start of its row. */
export function rowOffset(address: bigint): number {
return Number(address % BigInt(ROW_BYTES));
}
/** The bytes of a read that starts at `address`, followed by `unreadable` bytes that could not be read. */
export function memoryRows(address: bigint, data: readonly number[], unreadable: number): MemoryRow[] {
const bytes: (number | null)[] = [...data, ...Array<null>(unreadable).fill(null)];
const rows: MemoryRow[] = [];
for (let i = 0; i < bytes.length; i += ROW_BYTES) {
rows.push({ address: address + BigInt(i), bytes: bytes.slice(i, i + ROW_BYTES) });
}
return rows;
}
/** Hex digits the address column shows: 8 for 32-bit addresses, 16 once one doesn't fit. */
export function addressWidth(rows: readonly MemoryRow[]): number {
const last = rows.at(-1);
return last && last.address + BigInt(ROW_BYTES - 1) > 0xffffffffn ? 16 : 8;
}
export function formatAddress(address: bigint, width: number): string {
return `0x${address.toString(16).toUpperCase().padStart(width, "0")}`;
}
/** `48`, or `??` for a byte that could not be read. */
export function hexByte(byte: number | null): string {
return byte === null ? "??" : byte.toString(16).toUpperCase().padStart(2, "0");
}
/** The byte as printable ASCII; `.` for any other byte, ` ` for one that could not be read. */
export function asciiChar(byte: number | null): string {
if (byte === null) return " ";
return byte >= 0x20 && byte < 0x7f ? String.fromCharCode(byte) : ".";
}
+162
Переглянути файл
@@ -0,0 +1,162 @@
/** Native Memory View (DAP `readMemory`): what each session's view shows, and reading it. */
import { create } from "zustand";
import { call, commands, type DebugSessionId, type MemoryBlock } from "@/platform/ipc";
import { formatMessage, tx } from "@/platform/i18n";
import { evaluate, useDebug } from "../state";
import { PAGE_BYTES, parseAddress, rowOffset } from "./bytes";
export interface MemoryViewEntry {
/** What the address field shows. */
expression: string;
/** The memory reference pages are read relative to: an evaluation result's or a variable's. */
reference: string | null;
/** Address of `reference` once known: the byte the view marks. */
target: bigint | null;
/** Offset from `reference` of the page shown; it starts a row. */
start: number;
block: MemoryBlock | null;
error: string | null;
loading: boolean;
/** The session's `stops` when `block` (or `error`) was read: a later stop reads the page again. */
readAtStop: number;
}
interface MemoryViewState {
bySession: Record<DebugSessionId, MemoryViewEntry>;
/** Set by View Memory until the Debug tool window has brought the Memory View to the front. */
revealPending: boolean;
}
export const useMemoryView = create<MemoryViewState>(() => ({ bySession: {}, revealPending: false }));
const emptyEntry = (): MemoryViewEntry => ({
expression: "",
reference: null,
target: null,
start: 0,
block: null,
error: null,
loading: false,
readAtStop: -1,
});
/** The read each session waits for; a newer one (or `forgetMemoryView`) makes an older reply stale. */
const inflight = new Map<DebugSessionId, symbol>();
function patchEntry(id: DebugSessionId, patch: Partial<MemoryViewEntry>) {
useMemoryView.setState((s) => ({
bySession: { ...s.bySession, [id]: { ...(s.bySession[id] ?? emptyEntry()), ...patch } },
}));
}
const message = (e: unknown) => (e instanceof Error ? e.message : String(e));
/**
* Reads the page at the entry's `start`. Before the reference's address is known (references
* are opaque in DAP), a first read at the reference itself tells it, and the page then moves back
* to the start of its row.
*/
export async function readPage(id: DebugSessionId): Promise<void> {
const entry = useMemoryView.getState().bySession[id];
const session = useDebug.getState().sessions[id];
if (!entry?.reference || !session || session.status !== "paused") return;
const reference = entry.reference;
const token = Symbol("memory view");
inflight.set(id, token);
const stop = session.stops;
patchEntry(id, { loading: true });
const read = (offset: number) => call(commands.debugReadMemory(id, reference, offset, PAGE_BYTES));
try {
let { target, start } = entry;
let block = await read(start);
if (target === null && inflight.get(id) === token) {
target = parseAddress(block.address);
const back = target === null ? 0 : rowOffset(target);
if (back) block = await read((start = -back));
}
if (inflight.get(id) !== token) return;
patchEntry(id, { target, start, block, error: null, readAtStop: stop });
} catch (e) {
if (inflight.get(id) !== token) return;
patchEntry(id, { block: null, error: message(e), readAtStop: stop });
} finally {
if (inflight.get(id) === token) {
inflight.delete(id);
patchEntry(id, { loading: false });
}
}
}
/** Shows the memory at `reference` (a variable's, or an evaluation result's); the address field shows `expression`. */
export function showMemoryAt(id: DebugSessionId, reference: string, expression: string): Promise<void> {
// Adapters that write references as addresses (lldb-dap, CodeLLDB, cppdbg, GDB) need no read to align the page.
const target = parseAddress(reference);
patchEntry(id, {
expression,
reference,
target,
start: target === null ? 0 : 0 - rowOffset(target),
block: null,
error: null,
});
return readPage(id);
}
/** Address field: evaluates `expression` (`&msg[0]`, `buffer`, `0x7ffd5c4a`) and shows the memory it points to. */
export async function goToExpression(id: DebugSessionId, expression: string): Promise<void> {
const text = expression.trim();
const session = useDebug.getState().sessions[id];
if (!text || !session) return;
patchEntry(id, { expression: text });
let reference: string | null;
try {
const value = await evaluate(text, "watch", session);
// A plain number (`0x601040`, an integer variable) has no reference: its value is the address.
const address = value.memoryReference ? null : parseAddress(value.value);
reference = value.memoryReference ?? (address === null ? null : `0x${address.toString(16)}`);
if (!reference) {
patchEntry(id, {
reference: null,
block: null,
error: formatMessage(
tx("“{expression}” is not an address. Enter a pointer or an address, such as &buffer[0]."),
{
expression: text,
},
),
});
return;
}
} catch (e) {
patchEntry(id, { reference: null, block: null, error: message(e) });
return;
}
if (useMemoryView.getState().bySession[id]?.expression !== text) return;
await showMemoryAt(id, reference, text);
}
/** Previous (-1) or next (1) page. */
export function turnPage(id: DebugSessionId, pages: number): Promise<void> {
const entry = useMemoryView.getState().bySession[id];
if (!entry?.reference) return Promise.resolve();
patchEntry(id, { start: entry.start + pages * PAGE_BYTES });
return readPage(id);
}
export function revealMemoryView(): void {
useMemoryView.setState({ revealPending: true });
}
/** The Debug tool window shows the Memory View: the request is done. */
export function memoryViewRevealed(): void {
useMemoryView.setState({ revealPending: false });
}
export function forgetMemoryView(id: DebugSessionId): void {
inflight.delete(id);
useMemoryView.setState((s) => {
if (!(id in s.bySession)) return s;
const { [id]: _gone, ...rest } = s.bySession;
return { bySession: rest };
});
}
+32 -5
Переглянути файл
@@ -59,6 +59,8 @@ import { NetworkView } from "../js/NetworkView";
import { liveWatchesApply, useLiveWatches } from "../js/liveWatches";
import { pageProfileItems, useJsProfile } from "../js/profile";
import { MemoryView } from "../memory/MemoryView";
import { MemoryViewPane } from "../memoryView/MemoryViewPane";
import { memoryViewRevealed, useMemoryView } from "../memoryView/memoryViewState";
import { DebugConsole } from "./DebugConsole";
import { VariablesView, type VarRoot } from "./VariablesView";
import { useExpressionCompletion } from "./ExpressionCompletion";
@@ -129,7 +131,7 @@ function MoreActions() {
);
}
type Tab = "variables" | "console" | "memory" | "network";
type Tab = "variables" | "console" | "memory" | "memoryView" | "network";
/** The view the user last picked; the tool window opens on it again (Console until one is picked). */
let chosenTab: Tab = "console";
@@ -225,19 +227,35 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod
session: number | undefined;
status: DebugSession["status"] | undefined;
tab: Tab;
}>({ session: undefined, status: undefined, tab: chosenTab });
}>(() => ({
session: undefined,
status: undefined,
tab: useMemoryView.getState().revealPending ? "memoryView" : chosenTab,
}));
// View Memory brings the Memory View to the front, also in the tool window it opens (above).
useEffect(() => {
const reveal = (pending: boolean, shown: boolean) => {
if (!pending) return;
memoryViewRevealed();
chosenTab = "memoryView";
if (!shown) setView((v) => (v.tab === "memoryView" ? v : { ...v, tab: "memoryView" }));
};
reveal(useMemoryView.getState().revealPending, true);
return useMemoryView.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 does Memory.
// stepping), and so do Memory and the Memory View.
tab:
active.status === "starting"
? "console"
: active.status === "paused" &&
view.tab !== "memory" &&
view.tab !== "memoryView" &&
active.stopReason !== "step" &&
workflowSettings().debugger.variablesOnBreakpoint
? "variables"
@@ -247,9 +265,15 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod
const memoryPending = !!active && !active.caps && JVM_ADAPTERS.has(rootOf(active).adapter);
const hasMemory = !!active && (sessionSupports("jvmMemory", active) || memoryPending);
const hasNetwork = !!active && sessionSupports("jsPage", active);
// The selected session may be one without the Memory or the Network tab.
// 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.
const tab: Tab =
(view.tab === "memory" && !hasMemory) || (view.tab === "network" && !hasNetwork) ? "variables" : view.tab;
(view.tab === "memory" && !hasMemory) ||
(view.tab === "memoryView" && !hasMemoryView) ||
(view.tab === "network" && !hasNetwork)
? "variables"
: view.tab;
if (!active) {
return (
@@ -307,6 +331,7 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod
["variables", "Threads & Variables"],
["console", "Console"],
...(hasMemory ? [["memory", "Memory"] as const] : []),
...(hasMemoryView ? [["memoryView", "Memory View"] as const] : []),
...(hasNetwork ? [["network", "Network"] as const] : []),
] as const
).map(([id, label]) => (
@@ -355,6 +380,8 @@ function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNod
) : (
<MemoryView key={active.id} session={active} />
)
) : tab === "memoryView" ? (
<MemoryViewPane key={active.id} session={active} />
) : tab === "network" ? (
<NetworkView key={active.id} session={active.id} />
) : (
+13
Переглянути файл
@@ -10,6 +10,7 @@ import { resolveMonoFont } from "@/platform/fonts";
import { useProject } from "@/platform/project";
import { activeEditor } from "@/editor/api";
import { notifications } from "@/workbench/contributions";
import { executeAction } from "@/platform/actions";
import { addFieldWatchpoint } from "../breakpoints/special";
import { methodAt } from "../breakpoints/symbols";
import {
@@ -52,6 +53,8 @@ interface VarNode {
container: number;
/** `value` is not computed yet; `reference` holds it as a single nameless variable. */
lazy: boolean;
/** Where the value points to or is stored, for View Memory. */
memoryReference?: string | null;
}
function fromRoot(r: VarRoot): VarNode {
@@ -85,6 +88,7 @@ function fromRoot(r: VarRoot): VarNode {
depth0: true,
container: 0,
lazy: !!r.variable?.lazy,
memoryReference: r.variable?.memoryReference,
};
}
}
@@ -102,6 +106,7 @@ function fromVariable(key: string, v: Variable, container: number, depth0 = fals
depth0,
container,
lazy: !!v.lazy,
memoryReference: v.memoryReference,
};
}
@@ -113,6 +118,7 @@ function toVariable(n: VarNode): Variable {
variablesReference: n.reference,
evaluateName: n.evaluateName,
lazy: n.lazy,
memoryReference: n.memoryReference,
};
}
@@ -422,6 +428,13 @@ export function VariablesView({
run: () => void addWatchpointFor(session!, node),
});
if (watchActions.length) items.push({ kind: "separator" }, ...watchActions);
const memoryReference = node.memoryReference;
if (memoryReference && sessionSupports("readMemory"))
items.push({
label: "View Memory",
icon: "file-binary",
run: () => void executeAction("debug.viewMemory", memoryReference),
});
items.push(
{ kind: "separator" },
+2
Переглянути файл
@@ -303,6 +303,8 @@ describe("catalogs", () => {
// The OpenPGP signing format, in Configure GPG Signature.
"OpenPGP",
"URL",
// The character set's name, as the Memory View's text column header.
"ASCII",
"ID:",
"Code Vision",
"JUnit",
+11 -1
Переглянути файл
@@ -4660,5 +4660,15 @@
"Re-run Failed Jobs": "Re-run Failed Jobs",
"Re-run All Jobs": "Re-run All Jobs",
"Re-run Job": "Re-run Job",
"Open Workflow Run in Browser": "Open Workflow Run in Browser"
"Open Workflow Run in Browser": "Open Workflow Run in Browser",
"Memory View": "Memory View",
"View Memory": "View Memory",
"Address or expression, such as &buffer[0]": "Address or expression, such as &buffer[0]",
"Address or expression": "Address or expression",
"Go to Address": "Go to Address",
"ASCII": "ASCII",
"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]."
}
+11 -1
Переглянути файл
@@ -11250,5 +11250,15 @@
"Resumed after backend upgrade": "后端升级后已恢复",
"Resumed after backend stop": "后端停止后已恢复",
"Resumed after unexpected exit": "异常退出后已恢复",
"Resumed after network drop": "网络恢复后已继续"
"Resumed after network drop": "网络恢复后已继续",
"Memory View": "内存视图",
"View Memory": "查看内存",
"Address or expression, such as &buffer[0]": "地址或表达式,例如 &buffer[0]",
"Address or expression": "地址或表达式",
"Go to Address": "转到地址",
"ASCII": "ASCII",
"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]。"
}