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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
mod debugger;
mod debugger_script;

use std::str::FromStr;

use debugger::DebuggerType;
use proc_macro::TokenStream;
use quote::{format_ident, quote, ToTokens};
use syn::{parse::Parse, Token};

use crate::debugger_script::create_debugger_script;

struct DebuggerTest {
    debugger: String,
    commands: String,
    expected_statements: String,
}

impl Parse for DebuggerTest {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let debugger_meta = input.parse::<syn::MetaNameValue>()?;
        let debugger = if debugger_meta.path.is_ident("debugger") {
            match debugger_meta.lit {
                syn::Lit::Str(lit_str) => lit_str.value(),
                _ => {
                    return Err(input.error("Expected a literal string for the value of `debugger`"))
                }
            }
        } else {
            return Err(input.error("Expected value `debugger`"));
        };

        input.parse::<Token![,]>()?;

        let commands_meta = input.parse::<syn::MetaNameValue>()?;
        let commands = if commands_meta.path.is_ident("commands") {
            match commands_meta.lit {
                syn::Lit::Str(lit_str) => lit_str.value(),
                _ => {
                    return Err(input.error("Expected a literal string for the value of `commands`"))
                }
            }
        } else {
            return Err(input.error("Expected value `commands`"));
        };

        input.parse::<Token![,]>()?;

        let expected_statements_meta = input.parse::<syn::MetaNameValue>()?;
        let expected_statements = if expected_statements_meta
            .path
            .is_ident("expected_statements")
        {
            match expected_statements_meta.lit {
                syn::Lit::Str(lit_str) => lit_str.value(),
                _ => {
                    return Err(input
                        .error("Expected a literal string for the value of `expected_statements`"))
                }
            }
        } else {
            return Err(input.error("Expected value `expected_statements`"));
        };

        Ok(DebuggerTest {
            debugger,
            commands,
            expected_statements,
        })
    }
}

#[proc_macro_attribute]
pub fn debugger_test(attr: TokenStream, item: TokenStream) -> TokenStream {
    let invoc = match syn::parse::<DebuggerTest>(attr) {
        Ok(s) => s,
        Err(e) => return e.to_compile_error().into(),
    };

    let item = match syn::parse::<syn::Item>(item) {
        Ok(s) => s,
        Err(e) => return e.to_compile_error().into(),
    };

    let func = match item {
        syn::Item::Fn(ref f) => f,
        _ => panic!("must be attached to a function"),
    };

    let debugger_commands = &invoc
        .commands
        .trim()
        .lines()
        .into_iter()
        .map(|line| line.trim())
        .collect::<Vec<&str>>();

    let debugger_type = DebuggerType::from_str(invoc.debugger.as_str()).expect(
        format!(
            "debugger `{}` must be a valid debugger option.",
            invoc.debugger.as_str()
        )
        .as_str(),
    );
    let debugger_executable_path = debugger::get_debugger(&debugger_type);

    let fn_name = func.sig.ident.to_string();
    let fn_ident = format_ident!("{}", fn_name);
    let test_fn_name = format!("{}__{}", fn_name, debugger_type.to_string());
    let test_fn_ident = format_ident!("{}", test_fn_name);

    let debugger_script_contents = create_debugger_script(&fn_name, debugger_commands);

    // Trim all whitespace and remove any empty lines.
    let expected_statements = &invoc
        .expected_statements
        .trim()
        .lines()
        .collect::<Vec<&str>>();

    // Create the cli for the given debugger.
    let (debugger_command_line, cfg_attr) = match debugger_type {
        DebuggerType::Cdb => {
            let debugger_path = debugger_executable_path.to_string_lossy().to_string();
            let command_line = quote!(
                match std::process::Command::new(#debugger_path)
                    .stdout(std::process::Stdio::from(debugger_stdout_file))
                    .stderr(std::process::Stdio::from(debugger_stderr_file))
                    .arg("-pd")
                    .arg("-p")
                    .arg(pid.to_string())
                    .arg("-cf")
                    .arg(&debugger_script_path)
                    .spawn() {
                        Ok(child) => child,
                        Err(error) => {
                            return Err(std::boxed::Box::from(format!("Failed to launch CDB: {}\n", error.to_string())));
                        }
                }
            );

            // cdb is only supported on Windows.
            let cfg_attr = quote!(
                #[cfg_attr(not(target_os = "windows"), ignore = "test only runs on windows platforms.")]
            );

            (command_line, cfg_attr)
        }
    };

    // Create the test function that will launch the debugger and run debugger commands.
    let mut debugger_test_fn = proc_macro::TokenStream::from(quote!(
        #[test]
        #cfg_attr
        fn #test_fn_ident() -> std::result::Result<(), Box<dyn std::error::Error>> {
            use std::io::Read;
            use std::io::Write;

            let pid = std::process::id();
            let current_exe_filename = std::env::current_exe()?.file_stem().expect("must have a valid file name").to_string_lossy().to_string();

            // Create a temporary file to store the debugger script to run.
            let debugger_script_filename = format!("{}_{}.debugger_script", current_exe_filename, #test_fn_name);
            let debugger_script_path = std::env::temp_dir().join(debugger_script_filename);

            // Write the contents of the debugger script to a new file.
            let mut debugger_script = std::fs::File::create(&debugger_script_path)?;
            writeln!(debugger_script, #debugger_script_contents)?;

            // Create a temporary file to store the stdout and stderr from the debugger output.
            let debugger_stdout_path = debugger_script_path.with_extension("debugger_out");
            let debugger_stderr_path = debugger_script_path.with_extension("debugger_err");

            let debugger_stdout_file = std::fs::File::create(&debugger_stdout_path)?;
            let debugger_stderr_file = std::fs::File::create(&debugger_stderr_path)?;

            // Start the debugger and run the debugger commands.
            let mut child = #debugger_command_line;

            // Wait for the debugger to launch
            // On Windows, use the IsDebuggerPresent API to check if a debugger is present
            // for the current process. https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-isdebuggerpresent
            #[cfg(windows)]
            extern "stdcall" {
                fn IsDebuggerPresent() -> i32;
            };
            #[cfg(windows)]
            unsafe {
                while IsDebuggerPresent() == 0 {
                    std::thread::sleep(std::time::Duration::from_secs(1));
                }
            }

            // Wait 3 seconds to ensure the debugger is in control of the process.
            std::thread::sleep(std::time::Duration::from_secs(3));

            // Call the test function.
            #fn_ident();

            // Wait for the debugger to exit.
            std::thread::sleep(std::time::Duration::from_secs(3));

            // If debugger has not already quit, force quit the debugger.
            let mut debugger_stdout = String::new();
            match child.try_wait()? {
                Some(status) => {
                    // Bail early if the debugger process didn't execute successfully.
                    let mut debugger_stdout_file = std::fs::File::open(&debugger_stdout_path)?;
                    debugger_stdout_file.read_to_string(&mut debugger_stdout)?;

                    if !status.success() {
                        let mut debugger_stderr = String::new();
                        let mut debugger_stderr_file = std::fs::File::open(&debugger_stderr_path)?;
                        debugger_stderr_file.read_to_string(&mut debugger_stderr)?;
                        return Err(std::boxed::Box::from(format!("Debugger failed with {}.\n{}\n{}\n", status, debugger_stderr, debugger_stdout)));
                    }

                    println!("Debugger stdout:\n{}\n", &debugger_stdout);
                },
                None => {
                    // Force kill the debugger process if it has not exited yet.
                    println!("killing debugger process.");
                    child.kill().expect("debugger has been running for too long");

                    let mut debugger_stdout_file = std::fs::File::open(&debugger_stdout_path)?;
                    debugger_stdout_file.read_to_string(&mut debugger_stdout)?;
                    println!("Debugger stdout:\n{}\n", &debugger_stdout);
                }
            }

            // Verify the expected contents of the debugger output.
            let expected_statements = vec![#(#expected_statements),*];
            debugger_test_parser::parse(debugger_stdout, expected_statements)?;

            #[cfg(windows)]
            unsafe {
                while IsDebuggerPresent() == 1 {
                    std::thread::sleep(std::time::Duration::from_secs(1));
                }
            }

            #[cfg(not(windows))]
            std::thread::sleep(std::time::Duration::from_secs(3));

            Ok(())
        }
    ));

    debugger_test_fn.extend(proc_macro::TokenStream::from(item.to_token_stream()).into_iter());
    debugger_test_fn
}