Skip to content

Visual Studio Code, rebuilt in Rust

Rust
11.4 KB
Raw Blame
//! debugMemory.ts `DebugMemoryFileSystemProvider` over debugModel.ts `MemoryRegion`, which the extension host's
//! `workspace.fs` reaches through `main_thread_files.rs`, and variablesView.ts VIEW_MEMORY_ID, which opens a
//! variable's memory in the hex editor.

use std::sync::LazyLock;

use base64::Engine;
use exthost::main_thread_files::DEBUG_MEMORY_SCHEME;
use futures::channel::oneshot;
use gpui::{Context, Window};
use regex::Regex;
use serde_json::{Value, json};

use super::Workbench;
use super::debug_service::{answer, on_workbench};
use crate::commands::Outcome;
use crate::debug::session::State;

pub(super) const VIEW_MEMORY_ID: &str = "workbench.debug.viewlet.action.viewMemory";
const HEX_EDITOR_EXTENSION_ID: &str = "ms-vscode.hexeditor";
const HEX_EDITOR_EDITOR_ID: &str = "hexEditor.hexedit";

/// The most bytes one read or write moves: the hex editor asks for 4 KB pages, a larger range comes from no adapter.
const MAX_RANGE: u64 = 1 << 24;
/// `Number.MAX_SAFE_INTEGER`: the DAP offset is a JavaScript number.
const MAX_OFFSET: u64 = (1 << 53) - 1;

static RANGE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"range=([0-9]+):([0-9]+)").unwrap());

/// A `vscode-debug-memory` resource: its session, memory reference and `range=from:to` query.
#[derive(Debug, PartialEq)]
struct MemoryResource {
    session_id: String,
    memory_reference: String,
    range: Option<(u64, u64)>,
}

/// debugModel.ts `getUriForDebugMemory` without a range.
pub(super) fn memory_uri(session_id: &str, memory_reference: &str) -> Value {
    let path = format!("/{}/memory.bin", super::content_hover::encode_uri_component(memory_reference));
    json!({ "$mid": 1, "scheme": DEBUG_MEMORY_SCHEME, "authority": session_id, "path": path, "query": "" })
}

/// debugMemory.ts `parseUri`. The range comes from an extension: it must be in order, a JavaScript integer, and at most
/// `MAX_RANGE` long.
fn parse_memory_uri(uri: &Value) -> Result<MemoryResource, Value> {
    let scheme = uri["scheme"].as_str().unwrap_or_default();
    if scheme != DEBUG_MEMORY_SCHEME {
        return Err(provider_error(files::FILE_NOT_FOUND, format!("Cannot open file with scheme {scheme}")));
    }
    let memory_reference = uri["path"].as_str().unwrap_or_default().split('/').nth(1).map(crate::uri::percent_decode).unwrap_or_default();
    if memory_reference.is_empty() {
        return Err(provider_error(files::FILE_NOT_FOUND, "Memory reference not found"));
    }
    let range = match RANGE.captures(uri["query"].as_str().unwrap_or_default()) {
        None => None,
        Some(captures) => {
            let (from, to) = (captures[1].parse::<u64>(), captures[2].parse::<u64>());
            match (from, to) {
                (Ok(from), Ok(to)) if from <= to && to <= MAX_OFFSET && to - from <= MAX_RANGE => Some((from, to)),
                _ => return Err(provider_error(files::FILE_NOT_FOUND, format!("Invalid memory range {}", &captures[0]))),
            }
        }
    };
    Ok(MemoryResource { session_id: uri["authority"].as_str().unwrap_or_default().to_owned(), memory_reference, range })
}

fn provider_error(code: &str, message: impl Into<String>) -> Value {
    let error = files::provider_error(code, message);
    json!({ "name": error.name, "message": error.message })
}

/// `readFile` over `MemoryRegion.read`: the file service reads the provider with `read` (it has no `FileReadWrite`),
/// which stops at the first unreadable byte. The readable part is the adapter's data, zero padded or cut to length.
fn memory_bytes(body: &Value, length: usize) -> Result<Vec<u8>, String> {
    let data = body["data"].as_str().unwrap_or_default();
    if data.is_empty() {
        return Ok(Vec::new());
    }
    let mut bytes = base64::engine::general_purpose::STANDARD.decode(data).map_err(|_| "Invalid base64 data from debug adapter".to_owned())?;
    let unreadable = usize::try_from(body["unreadableBytes"].as_u64().unwrap_or_default()).unwrap_or(usize::MAX);
    bytes.resize(length.saturating_sub(unreadable), 0);
    Ok(bytes)
}

impl Workbench {
    pub(super) fn register_debug_memory_commands(&mut self) {
        self.commands.register(VIEW_MEMORY_ID, |workbench, args, window, cx| workbench.view_memory(args.first().unwrap_or(&Value::Null), window, cx));
    }

    /// VIEW_MEMORY_ID on a Variables or hover row's `IVariablesContext`, or a Watch row's expression: the memory in the
    /// hex editor beside the active group, once the extension is installed.
    fn view_memory(&mut self, arg: &Value, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let target = match arg["sessionId"].as_str() {
            Some(session_id) => arg["variable"]["memoryReference"].as_str().map(|reference| (session_id.to_owned(), reference.to_owned())),
            None => {
                let reference = match arg["watchExpressionId"].as_str() {
                    Some(id) => self.debug.watch_values.get(id).and_then(|value| value.memory_reference.clone()),
                    None => arg["memoryReference"].as_str().map(str::to_owned),
                };
                reference.zip(self.debug.focus.session.clone()).map(|(reference, session_id)| (session_id, reference))
            }
        };
        let Some((session_id, memory_reference)) = target.filter(|(session_id, reference)| !session_id.is_empty() && !reference.is_empty()) else { return Outcome::done() };
        let resource = memory_uri(&session_id, &memory_reference);
        if self.extensions.iter().any(|extension| extension.id.eq_ignore_ascii_case(HEX_EDITOR_EXTENSION_ID)) {
            return self.open_memory(resource, window, cx);
        }
        // `tryInstallHexEditor`: the install shows its own errors, a refused prompt opens nothing.
        let justification = json!("Inspecting binary data requires this extension.");
        let Outcome::Pending(installed) = self.install_with_justification(HEX_EDITOR_EXTENSION_ID.to_owned(), None, !crate::product::is_stable(), justification, window, cx) else { return Outcome::done() };
        cx.spawn_in(window, async move |this, cx| {
            if matches!(installed.await, Ok(Ok(_))) {
                let _ = on_workbench(&this, cx, |workbench, window, cx| drop(workbench.open_memory(resource, window, cx)));
            }
        })
        .detach();
        Outcome::done()
    }

    fn open_memory(&mut self, resource: Value, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        if !self.debug.memory_resources.contains(&resource) {
            self.debug.memory_resources.push(resource.clone());
        }
        self.activate_column(&json!(super::webview_panels::SIDE_GROUP), None);
        self.open_with_resolver(&resource, Some(HEX_EDITOR_EDITOR_ID), json!({ "revealIfOpened": true }), window, cx)
    }

    /// A DebugMemoryFileSystemProvider `stat`, `readFile` or `writeFile` the extension host forwards.
    pub(crate) fn debug_memory_request(&mut self, args: &[Value], cx: &mut Context<Self>) -> Outcome {
        let memory = match args.get(1).map(parse_memory_uri) {
            Some(Ok(memory)) => memory,
            Some(Err(error)) => return Outcome::Ready(Err(error)),
            None => return Outcome::Ready(Err(provider_error(files::FILE_NOT_FOUND, "Missing resource"))),
        };
        let Some(session) = self.debug.session(&memory.session_id) else { return Outcome::Ready(Err(provider_error(files::FILE_NOT_FOUND, "Debug session not found"))) };
        let (can_read, can_write) = (session.capabilities["supportsReadMemoryRequest"] == true, session.capabilities["supportsWriteMemoryRequest"] == true);
        let operation = args[0].as_str().unwrap_or_default();
        if operation == "stat" {
            return Outcome::Ready(Ok(json!({ "readonly": !can_write })));
        }
        let Some((from, to)) = memory.range else { return Outcome::Ready(Err(provider_error(files::FILE_NOT_FOUND, "Range must be present to read a file"))) };
        let reply = match operation {
            // rawDebugSession.ts `readMemory` answers nothing without the capability: the memory is unreadable.
            "readFile" if !can_read => return Outcome::Ready(Ok(json!([]))),
            "readFile" => {
                let length = (to - from) as usize;
                let request = self.dap_request(&memory.session_id, "readMemory", json!({ "memoryReference": memory.memory_reference, "offset": from, "count": length }));
                spawn_answer(cx, async move {
                    let body = answer(request).await.map_err(|error| provider_error(files::UNKNOWN, error))?;
                    memory_bytes(&body, length).map(|bytes| json!(bytes)).map_err(|error| provider_error(files::UNKNOWN, error))
                })
            }
            "writeFile" => {
                let data = match serde_json::from_value::<Vec<u8>>(args.get(2).cloned().unwrap_or_default()) {
                    Ok(data) if data.len() as u64 <= MAX_RANGE => data,
                    _ => return Outcome::Ready(Err(provider_error(files::UNKNOWN, "Invalid memory contents"))),
                };
                if !can_write {
                    return Outcome::Ready(Err(provider_error(files::NO_PERMISSIONS, "Not allowed")));
                }
                let data = base64::engine::general_purpose::STANDARD.encode(data);
                let request = self.dap_request(&memory.session_id, "writeMemory", json!({ "memoryReference": memory.memory_reference, "offset": from, "data": data, "allowPartial": true }));
                spawn_answer(cx, async move { answer(request).await.map(|_| Value::Null).map_err(|error| provider_error(files::UNKNOWN, error)) })
            }
            _ => return Outcome::Ready(Err(provider_error(files::NO_PERMISSIONS, "Not allowed"))),
        };
        Outcome::Pending(reply)
    }

    /// debugMemory.ts `watch`: the session's memory resources are deleted once it runs or ends (the hex editor closes
    /// them), and changed when a `memory` event invalidates their reference.
    pub(super) fn debug_memory_session_changed(&mut self, session_id: &str, invalidated_reference: Option<&str>) {
        let focused_thread = self.debug.focus.thread.filter(|_| self.debug.focus.session.as_deref() == Some(session_id));
        let state = self.debug.session(session_id).map_or(State::Inactive, |session| session.state(focused_thread));
        let ran = matches!(state, State::Running | State::Inactive) && invalidated_reference.is_none();
        let mut touched = Vec::new();
        for resource in &self.debug.memory_resources {
            let Ok(memory) = parse_memory_uri(resource) else { continue };
            if memory.session_id == session_id && (ran || invalidated_reference == Some(memory.memory_reference.as_str())) {
                touched.push(resource.clone());
            }
        }
        if touched.is_empty() {
            return;
        }
        let event = match ran {
            true => {
                self.debug.memory_resources.retain(|resource| !touched.contains(resource));
                json!({ "created": [], "changed": [], "deleted": touched })
            }
            false => json!({ "created": [], "changed": touched, "deleted": [] }),
        };
        drop(self.host.call("ExtHostFileSystemEventService", "$onFileEvent", vec![event]));
    }
}

fn spawn_answer(cx: &mut Context<Workbench>, answer: impl Future<Output = Result<Value, Value>> + 'static) -> oneshot::Receiver<Result<Value, Value>> {
    let (sender, receiver) = oneshot::channel();
    cx.spawn(async move |_, _| drop(sender.send(answer.await))).detach();
    receiver
}

#[cfg(test)]
mod tests;