1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::{
    interpreter::Interpreter,
    loader::{Function, Loader},
};
use move_binary_format::file_format::Bytecode;
use move_vm_types::values::{self, Locals};
use std::{
    collections::BTreeSet,
    io::{self, Write},
    str::FromStr,
};

#[derive(Debug)]
enum DebugCommand {
    PrintStack,
    Step,
    Continue,
    Breakpoint(String),
    DeleteBreakpoint(String),
    PrintBreakpoints,
}

impl DebugCommand {
    pub fn debug_string(&self) -> &str {
        match self {
            Self::PrintStack => "stack",
            Self::Step => "step",
            Self::Continue => "continue",
            Self::Breakpoint(_) => "breakpoint ",
            Self::DeleteBreakpoint(_) => "delete ",
            Self::PrintBreakpoints => "breakpoints",
        }
    }

    pub fn commands() -> Vec<DebugCommand> {
        vec![
            Self::PrintStack,
            Self::Step,
            Self::Continue,
            Self::Breakpoint("".to_string()),
            Self::DeleteBreakpoint("".to_string()),
            Self::PrintBreakpoints,
        ]
    }
}

impl FromStr for DebugCommand {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use DebugCommand::*;
        let s = s.trim();
        if s.starts_with(PrintStack.debug_string()) {
            return Ok(PrintStack);
        }
        if s.starts_with(Step.debug_string()) {
            return Ok(Step);
        }
        if s.starts_with(Continue.debug_string()) {
            return Ok(Continue);
        }
        if let Some(breakpoint) = s.strip_prefix(Breakpoint("".to_owned()).debug_string()) {
            return Ok(Breakpoint(breakpoint.to_owned()));
        }
        if let Some(breakpoint) = s.strip_prefix(DeleteBreakpoint("".to_owned()).debug_string()) {
            return Ok(DeleteBreakpoint(breakpoint.to_owned()));
        }
        if s.starts_with(PrintBreakpoints.debug_string()) {
            return Ok(PrintBreakpoints);
        }
        Err(format!(
            "Unrecognized command: {}\nAvailable commands: {}",
            s,
            Self::commands()
                .iter()
                .map(|command| command.debug_string())
                .collect::<Vec<_>>()
                .join(", ")
        ))
    }
}

#[derive(Debug)]
pub(crate) struct DebugContext {
    breakpoints: BTreeSet<String>,
    should_take_input: bool,
}

impl DebugContext {
    pub(crate) fn new() -> Self {
        Self {
            breakpoints: BTreeSet::new(),
            should_take_input: true,
        }
    }

    pub(crate) fn debug_loop(
        &mut self,
        function_desc: &Function,
        locals: &Locals,
        pc: u16,
        instr: &Bytecode,
        resolver: &Loader,
        interp: &Interpreter,
    ) {
        let instr_string = format!("{:?}", instr);
        let function_string = function_desc.pretty_string();
        let breakpoint_hit = self.breakpoints.contains(&function_string)
            || self
                .breakpoints
                .iter()
                .any(|bp| instr_string[..].starts_with(bp.as_str()));

        if self.should_take_input || breakpoint_hit {
            self.should_take_input = true;
            if breakpoint_hit {
                let bp_match = self
                    .breakpoints
                    .iter()
                    .find(|bp| instr_string.starts_with(bp.as_str()))
                    .unwrap()
                    .clone();
                println!(
                    "Breakpoint {} hit with instruction {}",
                    bp_match, instr_string
                );
            }
            println!(
                "function >> {}\ninstruction >> {:?}\nprogram counter >> {}",
                function_string, instr, pc
            );
            loop {
                print!("> ");
                std::io::stdout().flush().unwrap();
                let mut input = String::new();
                match io::stdin().read_line(&mut input) {
                    Ok(_) => match input.parse::<DebugCommand>() {
                        Err(err) => println!("{}", err),
                        Ok(command) => match command {
                            DebugCommand::Step => {
                                self.should_take_input = true;
                                break;
                            }
                            DebugCommand::Continue => {
                                self.should_take_input = false;
                                break;
                            }
                            DebugCommand::Breakpoint(breakpoint) => {
                                self.breakpoints.insert(breakpoint.to_string());
                            }
                            DebugCommand::DeleteBreakpoint(breakpoint) => {
                                self.breakpoints.remove(&breakpoint);
                            }
                            DebugCommand::PrintBreakpoints => self
                                .breakpoints
                                .iter()
                                .enumerate()
                                .for_each(|(i, bp)| println!("[{}] {}", i, bp)),
                            DebugCommand::PrintStack => {
                                let mut s = String::new();
                                interp.debug_print_stack_trace(&mut s, resolver).unwrap();
                                println!("{}", s);
                                println!("Current frame: {}\n", function_string);
                                let code = function_desc.code();
                                println!("        Code:");
                                for (i, instr) in code.iter().enumerate() {
                                    if i as u16 == pc {
                                        println!("          > [{}] {:?}", pc, instr);
                                    } else {
                                        println!("            [{}] {:?}", i, instr);
                                    }
                                }
                                println!("        Locals:");
                                if function_desc.local_count() > 0 {
                                    let mut s = String::new();
                                    values::debug::print_locals(&mut s, locals).unwrap();
                                    println!("{}", s);
                                } else {
                                    println!("            (none)");
                                }
                            }
                        },
                    },
                    Err(err) => {
                        println!("Error reading input: {}", err);
                        break;
                    }
                }
            }
        }
    }
}