use std::path::{Path, PathBuf};
use crate::debugger::mi::Value;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Location {
Line {
file: PathBuf,
line: usize,
},
Address(u64),
Symbol(String),
Watch(String),
}
impl Location {
pub fn to_gdb_location(&self) -> String {
match self {
Location::Line { file, line } => {
let name = file
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| file.display().to_string());
format!("{name}:{line}")
}
Location::Address(address) => format!("*0x{address:x}"),
Location::Symbol(name) | Location::Watch(name) => name.clone(),
}
}
pub fn display(&self) -> String {
match self {
Location::Line { file, line } => {
let name = file
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| file.display().to_string());
format!("{name}:{line}")
}
Location::Address(address) => format!("0x{address:x}"),
Location::Symbol(name) => name.clone(),
Location::Watch(expression) => format!("watch {expression}"),
}
}
pub fn source_line(&self) -> Option<(&Path, usize)> {
match self {
Location::Line { file, line } => Some((file.as_path(), *line)),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Breakpoint {
pub number: Option<u32>,
pub location: Location,
pub enabled: bool,
pub address: Option<u64>,
pub function: Option<String>,
pub hit_count: u32,
pub condition: Option<String>,
pub synced: Option<(bool, Option<String>)>,
}
impl Breakpoint {
pub fn pending(location: Location) -> Self {
Self {
number: None,
location,
enabled: true,
address: None,
function: None,
hit_count: 0,
condition: None,
synced: None,
}
}
pub fn is_active(&self) -> bool {
self.number.is_some()
}
pub fn describe(&self) -> String {
let mut text = match self.number {
Some(number) => format!("{number}: "),
None => "-: ".to_owned(),
};
text.push_str(&self.location.display());
if let Some(function) = &self.function {
text.push_str(&format!(" in {function}"));
}
if let Some(condition) = &self.condition {
text.push_str(&format!(" if {condition}"));
}
if !self.enabled {
text.push_str(" (disabled)");
}
if self.hit_count > 0 {
text.push_str(&format!(" hit {}", self.hit_count));
}
text
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BreakpointSet {
breakpoints: Vec<Breakpoint>,
removed: Vec<u32>,
}
impl BreakpointSet {
pub fn new() -> Self {
Self::default()
}
pub fn all(&self) -> &[Breakpoint] {
&self.breakpoints
}
pub fn len(&self) -> usize {
self.breakpoints.len()
}
pub fn is_empty(&self) -> bool {
self.breakpoints.is_empty()
}
pub fn at_line(&self, file: &Path, line: usize) -> Option<&Breakpoint> {
self.breakpoints.iter().find(|breakpoint| {
breakpoint
.location
.source_line()
.is_some_and(|(path, number)| same_file(path, file) && number == line)
})
}
pub fn is_set_at(&self, file: &Path, line: usize) -> bool {
self.at_line(file, line).is_some()
}
pub fn toggle_line(&mut self, file: &Path, line: usize) -> bool {
if let Some(index) = self.index_of_line(file, line) {
self.remove_index(index);
false
} else {
self.breakpoints.push(Breakpoint::pending(Location::Line {
file: file.to_path_buf(),
line,
}));
true
}
}
pub fn add_address(&mut self, address: u64) -> bool {
if self
.breakpoints
.iter()
.any(|breakpoint| breakpoint.location == Location::Address(address))
{
return false;
}
self.breakpoints
.push(Breakpoint::pending(Location::Address(address)));
true
}
pub fn add_watch(&mut self, expression: &str) -> bool {
let location = Location::Watch(expression.trim().to_owned());
if self
.breakpoints
.iter()
.any(|breakpoint| breakpoint.location == location)
{
return false;
}
self.breakpoints.push(Breakpoint::pending(location));
true
}
pub fn set_condition(&mut self, index: usize, condition: Option<String>) -> bool {
match self.breakpoints.get_mut(index) {
Some(breakpoint) => {
breakpoint.condition = condition.filter(|text| !text.trim().is_empty());
true
}
None => false,
}
}
pub fn restore(&mut self, location: Location, enabled: bool, condition: Option<String>) {
if self
.breakpoints
.iter()
.any(|breakpoint| breakpoint.location == location)
{
return;
}
let mut breakpoint = Breakpoint::pending(location);
breakpoint.enabled = enabled;
breakpoint.condition = condition;
self.breakpoints.push(breakpoint);
}
pub fn move_file(&mut self, from: &Path, to: Option<&Path>) {
let mut index = 0;
while index < self.breakpoints.len() {
let here = matches!(&self.breakpoints[index].location, Location::Line { file, .. } if same_file(file, from));
match (here, to) {
(true, None) => {
self.remove_index(index);
continue;
}
(true, Some(to)) => {
if let Location::Line { file, .. } = &mut self.breakpoints[index].location {
*file = to.to_path_buf();
}
}
_ => {}
}
index += 1;
}
}
pub fn take_removed(&mut self) -> Vec<u32> {
std::mem::take(&mut self.removed)
}
pub fn out_of_sync(&self) -> Vec<(u32, bool, Option<String>)> {
self.breakpoints
.iter()
.filter_map(|breakpoint| {
let number = breakpoint.number?;
let wanted = (breakpoint.enabled, breakpoint.condition.clone());
(breakpoint.synced.as_ref() != Some(&wanted))
.then_some((number, wanted.0, wanted.1))
})
.collect()
}
pub fn mark_synced(&mut self, number: u32, enabled: bool, condition: Option<String>) {
if let Some(breakpoint) = self
.breakpoints
.iter_mut()
.find(|breakpoint| breakpoint.number == Some(number))
{
breakpoint.synced = Some((enabled, condition));
}
}
pub fn add_symbol(&mut self, name: &str) -> bool {
let location = Location::Symbol(name.to_owned());
if self
.breakpoints
.iter()
.any(|breakpoint| breakpoint.location == location)
{
return false;
}
self.breakpoints.push(Breakpoint::pending(location));
true
}
pub fn remove_number(&mut self, number: u32) -> bool {
match self
.breakpoints
.iter()
.position(|breakpoint| breakpoint.number == Some(number))
{
Some(index) => self.remove_index(index).is_some(),
None => false,
}
}
pub fn remove_index(&mut self, index: usize) -> Option<Breakpoint> {
if index >= self.breakpoints.len() {
return None;
}
let breakpoint = self.breakpoints.remove(index);
self.removed.extend(breakpoint.number);
Some(breakpoint)
}
pub fn set_enabled(&mut self, index: usize, enabled: bool) -> bool {
match self.breakpoints.get_mut(index) {
Some(breakpoint) => {
breakpoint.enabled = enabled;
true
}
None => false,
}
}
pub fn clear(&mut self) {
self.removed.extend(
self.breakpoints
.drain(..)
.filter_map(|breakpoint| breakpoint.number),
);
}
pub fn detach(&mut self) {
for breakpoint in &mut self.breakpoints {
breakpoint.number = None;
breakpoint.address = None;
breakpoint.hit_count = 0;
breakpoint.synced = None;
}
self.removed.clear();
}
pub fn pending(&self) -> Vec<&Breakpoint> {
self.breakpoints
.iter()
.filter(|breakpoint| breakpoint.number.is_none())
.collect()
}
pub fn adopt(&mut self, location: &Location, record: &Value) -> bool {
let Some(index) = self
.breakpoints
.iter()
.position(|breakpoint| &breakpoint.location == location)
else {
return false;
};
let breakpoint = &mut self.breakpoints[index];
breakpoint.number = record.get_int("number").and_then(|n| u32::try_from(n).ok());
breakpoint.address = record.get_address("addr");
breakpoint.function = record.get_str("func").map(str::to_owned);
let enabled = record.get_str("enabled") != Some("n");
let condition = record.get_str("cond").map(str::to_owned);
breakpoint.synced = Some((enabled, condition));
true
}
pub fn record_hit(&mut self, number: u32) {
if let Some(breakpoint) = self
.breakpoints
.iter_mut()
.find(|breakpoint| breakpoint.number == Some(number))
{
breakpoint.hit_count = breakpoint.hit_count.saturating_add(1);
}
}
fn index_of_line(&self, file: &Path, line: usize) -> Option<usize> {
self.breakpoints.iter().position(|breakpoint| {
breakpoint
.location
.source_line()
.is_some_and(|(path, number)| same_file(path, file) && number == line)
})
}
}
fn same_file(left: &Path, right: &Path) -> bool {
if left == right {
return true;
}
match (left.file_name(), right.file_name()) {
(Some(left_name), Some(right_name)) => left_name == right_name,
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn main_asm() -> PathBuf {
PathBuf::from("/project/src/main.asm")
}
#[test]
fn a_new_set_is_empty() {
let set = BreakpointSet::new();
assert!(set.is_empty());
assert_eq!(set.len(), 0);
}
#[test]
fn toggling_adds_then_removes() {
let mut set = BreakpointSet::new();
assert!(set.toggle_line(&main_asm(), 12), "first toggle adds");
assert_eq!(set.len(), 1);
assert!(set.is_set_at(&main_asm(), 12));
assert!(!set.toggle_line(&main_asm(), 12), "second toggle removes");
assert!(set.is_empty());
assert!(!set.is_set_at(&main_asm(), 12));
}
#[test]
fn breakpoints_on_different_lines_coexist() {
let mut set = BreakpointSet::new();
set.toggle_line(&main_asm(), 5);
set.toggle_line(&main_asm(), 12);
assert_eq!(set.len(), 2);
assert!(set.is_set_at(&main_asm(), 5));
assert!(set.is_set_at(&main_asm(), 12));
assert!(!set.is_set_at(&main_asm(), 7));
}
#[test]
fn a_relative_path_matches_an_absolute_one() {
let mut set = BreakpointSet::new();
set.toggle_line(&main_asm(), 9);
assert!(set.is_set_at(Path::new("main.asm"), 9));
assert!(!set.is_set_at(Path::new("other.asm"), 9));
}
#[test]
fn a_new_breakpoint_starts_pending_and_enabled() {
let mut set = BreakpointSet::new();
set.toggle_line(&main_asm(), 3);
let breakpoint = &set.all()[0];
assert!(!breakpoint.is_active(), "no session has adopted it");
assert!(breakpoint.enabled);
assert_eq!(breakpoint.hit_count, 0);
assert_eq!(set.pending().len(), 1);
}
#[test]
fn adopting_records_the_details_gdb_resolved() {
let mut set = BreakpointSet::new();
let location = Location::Line {
file: main_asm(),
line: 9,
};
set.toggle_line(&main_asm(), 9);
let record = Value::Tuple(vec![
("number".to_owned(), Value::String("1".to_owned())),
("enabled".to_owned(), Value::String("y".to_owned())),
("addr".to_owned(), Value::String("0x004000b0".to_owned())),
("func".to_owned(), Value::String("_start".to_owned())),
]);
assert!(set.adopt(&location, &record));
let breakpoint = &set.all()[0];
assert_eq!(breakpoint.number, Some(1));
assert_eq!(breakpoint.address, Some(0x0040_00b0));
assert_eq!(breakpoint.function.as_deref(), Some("_start"));
assert!(breakpoint.is_active());
assert!(set.pending().is_empty());
}
#[test]
fn adopting_an_unknown_location_changes_nothing() {
let mut set = BreakpointSet::new();
set.toggle_line(&main_asm(), 9);
let elsewhere = Location::Line {
file: PathBuf::from("other.asm"),
line: 1,
};
assert!(!set.adopt(&elsewhere, &Value::Tuple(Vec::new())));
assert!(!set.all()[0].is_active());
}
#[test]
fn what_gdb_holds_is_compared_with_what_was_asked_for() {
let mut set = BreakpointSet::new();
let location = Location::Symbol("_start".to_owned());
set.add_symbol("_start");
let record = Value::Tuple(vec![
("number".to_owned(), Value::String("1".to_owned())),
("enabled".to_owned(), Value::String("n".to_owned())),
]);
set.adopt(&location, &record);
assert_eq!(set.out_of_sync(), vec![(1, true, None)]);
set.mark_synced(1, true, None);
assert!(set.out_of_sync().is_empty());
set.set_enabled(0, false);
set.set_condition(0, Some("$rax == 1".into()));
assert_eq!(
set.out_of_sync(),
vec![(1, false, Some("$rax == 1".into()))]
);
assert!(set.all()[0].describe().contains("disabled"));
assert!(set.all()[0].describe().contains("if $rax == 1"));
set.clear();
assert_eq!(set.take_removed(), vec![1]);
assert!(set.take_removed().is_empty());
}
#[test]
fn watchpoints_and_moved_files() {
let mut set = BreakpointSet::new();
assert!(set.add_watch(" $rax "));
assert!(!set.add_watch("$rax"));
assert_eq!(set.all()[0].location.display(), "watch $rax");
set.toggle_line(Path::new("/p/a.asm"), 3);
set.move_file(Path::new("/p/a.asm"), Some(Path::new("/p/b.asm")));
assert!(set.is_set_at(Path::new("/p/b.asm"), 3));
set.move_file(Path::new("/p/b.asm"), None);
assert_eq!(set.len(), 1);
}
#[test]
fn ending_a_session_returns_every_breakpoint_to_pending() {
let mut set = BreakpointSet::new();
set.toggle_line(&main_asm(), 9);
set.adopt(
&Location::Line {
file: main_asm(),
line: 9,
},
&Value::Tuple(vec![("number".to_owned(), Value::String("1".to_owned()))]),
);
set.record_hit(1);
assert_eq!(set.all()[0].hit_count, 1);
set.detach();
let breakpoint = &set.all()[0];
assert!(!breakpoint.is_active());
assert_eq!(breakpoint.hit_count, 0);
assert_eq!(breakpoint.address, None);
assert_eq!(set.pending().len(), 1, "it must be replayed next time");
}
#[test]
fn hits_are_counted_for_the_right_breakpoint() {
let mut set = BreakpointSet::new();
set.add_symbol("first");
set.add_symbol("second");
set.adopt(
&Location::Symbol("first".to_owned()),
&Value::Tuple(vec![("number".to_owned(), Value::String("1".to_owned()))]),
);
set.adopt(
&Location::Symbol("second".to_owned()),
&Value::Tuple(vec![("number".to_owned(), Value::String("2".to_owned()))]),
);
set.record_hit(2);
set.record_hit(2);
assert_eq!(set.all()[0].hit_count, 0);
assert_eq!(set.all()[1].hit_count, 2);
}
#[test]
fn recording_a_hit_on_an_unknown_number_is_ignored() {
let mut set = BreakpointSet::new();
set.add_symbol("_start");
set.record_hit(99);
assert_eq!(set.all()[0].hit_count, 0);
}
#[test]
fn address_and_symbol_breakpoints_are_not_duplicated() {
let mut set = BreakpointSet::new();
assert!(set.add_address(0x4000));
assert!(!set.add_address(0x4000), "the same address twice");
assert!(set.add_address(0x4008));
assert!(set.add_symbol("_start"));
assert!(!set.add_symbol("_start"));
assert_eq!(set.len(), 3);
}
#[test]
fn gdb_locations_use_the_expected_syntax() {
assert_eq!(
Location::Line {
file: main_asm(),
line: 12
}
.to_gdb_location(),
"main.asm:12"
);
assert_eq!(Location::Address(0x4000b0).to_gdb_location(), "*0x4000b0");
assert_eq!(
Location::Symbol("_start".into()).to_gdb_location(),
"_start"
);
}
#[test]
fn removing_by_number_and_index_both_work() {
let mut set = BreakpointSet::new();
set.add_symbol("a");
set.add_symbol("b");
set.adopt(
&Location::Symbol("a".to_owned()),
&Value::Tuple(vec![("number".to_owned(), Value::String("7".to_owned()))]),
);
assert!(set.remove_number(7));
assert_eq!(set.len(), 1);
assert!(!set.remove_number(7), "already gone");
assert!(set.remove_index(0).is_some());
assert!(set.is_empty());
assert!(set.remove_index(0).is_none());
}
#[test]
fn enabling_and_disabling_by_index_is_bounds_checked() {
let mut set = BreakpointSet::new();
set.add_symbol("_start");
assert!(set.set_enabled(0, false));
assert!(!set.all()[0].enabled);
assert!(!set.set_enabled(9, true), "out of range is refused");
}
#[test]
fn clearing_removes_everything() {
let mut set = BreakpointSet::new();
set.add_symbol("a");
set.toggle_line(&main_asm(), 1);
set.clear();
assert!(set.is_empty());
}
#[test]
fn descriptions_are_readable_in_every_state() {
let mut set = BreakpointSet::new();
set.toggle_line(&main_asm(), 9);
assert_eq!(set.all()[0].describe(), "-: main.asm:9");
set.adopt(
&Location::Line {
file: main_asm(),
line: 9,
},
&Value::Tuple(vec![
("number".to_owned(), Value::String("1".to_owned())),
("func".to_owned(), Value::String("_start".to_owned())),
]),
);
set.record_hit(1);
assert_eq!(set.all()[0].describe(), "1: main.asm:9 in _start hit 1");
}
}