Skip to content

Visual Studio Code, rebuilt in Rust

Rust
9.0 KB
Raw Blame
//! The instruction list of disassemblyView.ts `DisassemblyView`: the DAP `disassemble` answers merged by address,
//! the address of each instruction reference, and which rows show their source location.

use std::collections::HashMap;

use serde_json::Value;

/// `DisassemblyView.NUM_INSTRUCTIONS_TO_LOAD`.
pub const INSTRUCTIONS_TO_LOAD: i64 = 50;

/// `IDisassembledInstructionEntry`, its breakpoint state left to the model.
#[derive(Clone, Debug, PartialEq)]
pub struct Entry {
    pub instruction_reference: String,
    /// The `offset` the request asked for, the basis of `instruction_offset`.
    pub reference_offset: i64,
    /// How many instructions from the reference and its offset this one is.
    pub instruction_offset: i64,
    /// The DAP `DisassembledInstruction`, its location filled forward.
    pub instruction: Value,
    pub address: u64,
    /// The first instruction of its source line.
    pub show_source_location: bool,
}

#[derive(Clone, Debug, Default)]
pub struct Disassembly {
    pub entries: Vec<Entry>,
    reference_addresses: HashMap<String, u64>,
}

impl Disassembly {
    /// `clear`: an empty list draws "Disassembly not available.".
    pub fn clear(&mut self) {
        self.entries.clear();
        self.reference_addresses.clear();
    }

    /// `getReferenceAddress`.
    pub fn reference_address(&self, instruction_reference: &str) -> Option<u64> {
        self.reference_addresses.get(instruction_reference).copied()
    }

    /// `getIndexFromAddress`.
    pub fn index_of_address(&self, address: u64) -> Option<usize> {
        self.entries.binary_search_by_key(&address, |entry| entry.address).ok()
    }

    /// `getAddressAndOffset`: the reference, the entry's distance from its address, and the address.
    pub fn address_and_offset(&self, entry: &Entry) -> (String, i64, u64) {
        let base = self.reference_address(&entry.instruction_reference).unwrap_or(entry.address);
        (entry.instruction_reference.clone(), entry.address.wrapping_sub(base) as i64, entry.address)
    }

    /// The body of `loadDisassembledInstructions` after the request: the instructions replace the ones in their
    /// address range; the range replaced and the count put in its place.
    pub fn merge(&mut self, instruction_reference: &str, offset: i64, instruction_offset: i64, instructions: &[Value]) -> (std::ops::Range<usize>, usize) {
        let mut new_entries = Vec::new();
        let mut last_location = Value::Null;
        let mut last_line = None;
        for (index, instruction) in instructions.iter().enumerate() {
            let mut instruction = instruction.clone();
            let this_offset = instruction_offset + index as i64;
            // The DAP spec fills a missing location forward; only the first instruction of a range keeps it.
            if !instruction["location"].is_null() {
                last_location = instruction["location"].clone();
                last_line = None;
            }
            if let Some(line) = instruction["line"].as_u64() {
                let number = |key: &str, default: u64| instruction[key].as_u64().unwrap_or(default);
                let range = Some((line, number("column", 0), number("endLine", line), number("endColumn", 0)));
                if range != last_line {
                    last_line = range;
                    instruction["location"] = last_location.clone();
                }
            }
            // An address that does not parse, or the adapter's -1, is no instruction.
            let Some(address) = instruction["address"].as_str().and_then(parse_address) else { continue };
            if offset == 0 && this_offset == 0 {
                self.reference_addresses.insert(instruction_reference.to_owned(), address);
            }
            new_entries.push(Entry { instruction_reference: instruction_reference.to_owned(), reference_offset: offset, instruction_offset: this_offset, instruction, address, show_source_location: false });
        }
        let (Some(first), Some(last)) = (new_entries.first(), new_entries.last()) else { return (0..0, 0) };
        let start = match self.entries.binary_search_by_key(&first.address, |entry| entry.address) {
            Ok(index) | Err(index) => index,
        };
        let end = match self.entries.binary_search_by_key(&last.address, |entry| entry.address) {
            Ok(index) => index + 1,
            Err(index) => index,
        };
        let end = end.max(start);
        // Rows group by source line: a location shows when it differs from the last one shown before it.
        let mut last_located = self.entries[..start].iter().rev().map(|entry| &entry.instruction).find(|instruction| !instruction["location"].is_null() && !instruction["line"].is_null()).cloned();
        for entry in &mut new_entries {
            let instruction = &entry.instruction;
            let shows = !instruction["line"].is_null()
                && !instruction["location"].is_null()
                && last_located.as_ref().is_none_or(|last| !sources_equal(&instruction["location"], &last["location"]) || instruction["line"] != last["line"]);
            if shows {
                entry.show_source_location = true;
                last_located = Some(instruction.clone());
            }
        }
        let inserted = new_entries.len();
        self.entries.splice(start..end, new_entries);
        (start..end, inserted)
    }
}

/// `BigInt(address)`: hex with `0x`, else decimal; a negative address is none.
fn parse_address(address: &str) -> Option<u64> {
    match address.strip_prefix("0x").or_else(|| address.strip_prefix("0X")) {
        Some(hex) => u64::from_str_radix(hex, 16).ok(),
        None => address.parse().ok(),
    }
}

/// debugUtils.ts `sourcesEqual`.
fn sources_equal(first: &Value, second: &Value) -> bool {
    first["name"] == second["name"] && first["path"] == second["path"] && first["sourceReference"] == second["sourceReference"]
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    fn instructions(addresses: std::ops::Range<u64>) -> Vec<Value> {
        addresses.map(|address| json!({ "address": format!("0x{address:x}"), "instruction": format!("nop {address}") })).collect()
    }

    /// `loadDisassembledInstructions`' answer: the rows added.
    fn load(disassembly: &mut Disassembly, offset: i64, instruction_offset: i64, answer: &[Value]) -> i64 {
        let (replaced, inserted) = disassembly.merge("ref", offset, instruction_offset, answer);
        inserted as i64 - replaced.len() as i64
    }

    fn addresses(disassembly: &Disassembly) -> Vec<u64> {
        disassembly.entries.iter().map(|entry| entry.address).collect()
    }

    #[test]
    fn the_first_instruction_at_offset_zero_gives_the_reference_its_address() {
        let mut disassembly = Disassembly::default();
        assert_eq!(load(&mut disassembly, 0, -2, &instructions(0x10..0x15)), 5);
        assert_eq!(disassembly.reference_address("ref"), Some(0x12));
        let entry = disassembly.entries[4].clone();
        assert_eq!(disassembly.address_and_offset(&entry), ("ref".to_owned(), 2, 0x14));
    }

    #[test]
    fn loads_above_and_below_join_by_address_and_replace_the_overlap() {
        let mut disassembly = Disassembly::default();
        disassembly.merge("ref", 0, 0, &instructions(0x20..0x30));
        assert_eq!(load(&mut disassembly, 0, -8, &instructions(0x18..0x22)), 8);
        assert_eq!(load(&mut disassembly, 0, 16, &instructions(0x30..0x34)), 4);
        assert_eq!(addresses(&disassembly), (0x18..0x34).collect::<Vec<_>>());
        assert_eq!(disassembly.index_of_address(0x20), Some(8));
    }

    #[test]
    fn the_adapters_invalid_addresses_are_skipped() {
        let mut disassembly = Disassembly::default();
        let answer = [json!({ "address": "-1", "instruction": "?" }), json!({ "address": "junk", "instruction": "?" }), json!({ "address": "4096", "instruction": "ret" })];
        assert_eq!(load(&mut disassembly, 0, -2, &answer), 1);
        assert_eq!(addresses(&disassembly), [4096]);
    }

    #[test]
    fn the_location_fills_forward_and_shows_once_per_line() {
        let mut disassembly = Disassembly::default();
        let source = json!({ "name": "a.c", "path": "/w/a.c" });
        let answer = [
            json!({ "address": "0x1", "instruction": "a", "location": source, "line": 3 }),
            json!({ "address": "0x2", "instruction": "b", "line": 3 }),
            json!({ "address": "0x3", "instruction": "c", "line": 4 }),
            json!({ "address": "0x4", "instruction": "d" }),
        ];
        disassembly.merge("ref", 0, 0, &answer);
        let shown: Vec<bool> = disassembly.entries.iter().map(|entry| entry.show_source_location).collect();
        assert_eq!(shown, [true, false, true, false]);
        assert_eq!(disassembly.entries[2].instruction["location"], source);
        // A later load below the line already shown does not show it again.
        disassembly.merge("ref", 0, 4, &[json!({ "address": "0x5", "instruction": "e", "location": source, "line": 4 })]);
        assert!(!disassembly.entries[4].show_source_location);
    }
}