aboutsummaryrefslogtreecommitdiff
path: root/test/tools.rs
blob: ed78a170617b4511fa5add254363ab574c128a86 (plain)
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// for masm testing:
// * `dumpbin` is a "bytes to masm-like text" function and,
// * `masm` is a "masm-like text to bytes" function.
pub use imp::{dumpbin, masm};

/// configure the various test tools for a desired bitness.
// some tools (dumpbin) do not require any particular configuration as they take their cues from
// object file headers. other tools (masm) not only need different source directives, but are
// entirely different executables for different modes.
#[derive(Copy, Clone, Debug)]
pub enum CodeModel {
    // nothing even tries to run masm in 16-bit mode (yet..?)
    #[allow(dead_code)]
    Bits16,
    Bits32,
    Bits64,
}

#[cfg(not(any(target_os="linux", target_os="windows")))]
mod imp {
    use super::CodeModel;

    // stub impls to at least run tests on other platforms, but some
    // test-specific features will of course fail at runtime..
    pub fn dumpbin(_bytes: &[u8], _codeness: CodeModel) -> Result<String, String> {
        panic!("no impl of dumpbin on this target");
    }

    pub fn masm(_text: &str, _codeness: CodeModel) -> Result<Vec<u8>, String> {
        panic!("no impl of masm on this target");
    }
}

#[cfg(target_os="linux")]
mod imp {
    use super::CodeModel;

    pub fn dumpbin(_bytes: &[u8], _codeness: CodeModel) -> Result<String, String> {
        // how very sad:
        // > wibo: call reached missing import GetModuleHandleExA from kernel32
        panic!("wibo can't run dumpbin right now");
    }

    pub fn masm(_text: &str, _codeness: CodeModel) -> Result<Vec<u8>, String> {
        panic!("have not implemented wibo/masm on linux yet");
    }
}

#[cfg(target_os="windows")]
mod imp {
    use super::CodeModel;

    use std::fmt::{Write as FmtWrite};
    use std::io::Write;
    use std::process::Command;
    use crate::tools::carve_dumpbin_stdout;

    use tempfile::NamedTempFile;

    pub fn dumpbin(bytes: &[u8], codeness: CodeModel) -> Result<String, String> {
        let mut source = String::new();

        match codeness {
            CodeModel::Bits16 => {
                source.push_str(".286\n");
            }
            CodeModel::Bits32 => {
                source.push_str(".386\n");
            }
            CodeModel::Bits64 => {
                // no special incantations to get 64-bit code out of masm
            }
        }
        source.push_str(".code\n");
        source.push_str("\n");
        source.push_str("start::\n");
        source.push_str("    db ");
        let mut printed = false;
        for byte in bytes {
            if printed {
                source.push_str(", ");
            }
            write!(source, "0{:02x}h", byte).expect("can write");
            printed = true;
        }
        source.push_str("\nEND\n");
        eprintln!("SOURCE FOLLOWS: {source}");

        let mut tempfile = NamedTempFile::new().unwrap();
        tempfile.write_all(source.as_bytes()).expect("can write source");
        let sourcepath = tempfile.into_temp_path();
        let mut objpath = sourcepath.to_path_buf();
        objpath.add_extension(".o");

        let exe = match codeness {
            CodeModel::Bits64 => "ml64.exe",
            _other => "ml.exe"
        };

        let out = Command::new(format!("..\\..\\tools\\{}", exe))
            .args(&["/c", "/Fo", &objpath.display().to_string(), &sourcepath.display().to_string()])
            .output()
            .expect("can run");
        if !out.status.success() {
            eprintln!("failed to assemble {bytes:x?}:");
            eprintln!("stdout: {}", std::str::from_utf8(out.stdout.as_slice()).expect("valid utf8"));
            eprintln!("stderr: {}", std::str::from_utf8(out.stderr.as_slice()).expect("valid utf8"));
            panic!("failed to {}", exe);
        }

        let out = Command::new("..\\..\\tools\\dumpbin.exe")
            .args(&["/disasm:wide", &objpath.display().to_string()])
            .output()
            .expect("can run");
        if !out.status.success() {
            eprintln!("failed to dumpbin {bytes:x?}:");
            eprintln!("stdout: {}", std::str::from_utf8(out.stdout.as_slice()).expect("valid utf8"));
            eprintln!("stderr: {}", std::str::from_utf8(out.stderr.as_slice()).expect("valid utf8"));
            panic!("failed to dumpbin.exe");
        }


        let dumpbin_out = std::str::from_utf8(out.stdout.as_slice()).expect("valid utf8");

        let dumpbin_interesting = carve_dumpbin_stdout(dumpbin_out).expect("works");
        let dumpbin_interesting = dumpbin_interesting[0];

        let end =   "  0000000000000000: 0F C7 0F                                     ".len();
        if dumpbin_interesting.len() <= end {
            return Err("no instruction".to_string());
        }

        let asm_line = dumpbin_interesting[end..].trim();
        let text = if let Some(idx) = asm_line.find("  ") {
            let opcode = &asm_line[..idx];
            let operands = &asm_line[idx..].trim();
            format!("{opcode} {operands}")
        } else {
            asm_line.to_string()
        };
        let text = text.replace(",", ", ")
            .replace("+", " + ")
            .replace("-", " - ")
            .replace("*", " * ")
            .replace(" + FFFFFFFFCCBBAA34h", " - 334455CCh") // with apologies to future-me, replace common negative displacements into more normal values...
            .replace("rn - sae", "rn-sae")
            .replace("rd - sae", "rd-sae")
            .replace("ru - sae", "ru-sae")
            .replace("rz - sae", "rz-sae")
            .replace(" oword ", " xmmword ");

        eprintln!("testcase bytes {:x?} -> dumpbin -> text {}", bytes, text);

        Ok(text)
    }

    pub fn masm(text: &str, codeness: CodeModel) -> Result<Vec<u8>, String> {
        let mut source = String::new();

        match codeness {
            CodeModel::Bits16 => {
                source.push_str(".286\n");
            }
            CodeModel::Bits32 => {
                source.push_str(".386\n");
            }
            CodeModel::Bits64 => {
                // no special incantations to get 64-bit code out of masm
            }
        }
        source.push_str(".code\n");
        source.push_str("\n");
        source.push_str("start::\n");
        writeln!(source, "    {text}").expect("ok");
        source.push_str("\nEND\n");
/*
        eprintln!("assembling SOURCE:");
        eprintln!("{source}");
        eprintln!("-----");
*/
        let mut tempfile = NamedTempFile::new().unwrap();
        tempfile.write_all(source.as_bytes()).expect("can write source");
        tempfile.as_file().sync_data().expect("can sync");
        let sourcepath = tempfile.into_temp_path();
        let mut objpath = sourcepath.to_path_buf();
        objpath.add_extension(".o");

        let exe = match codeness {
            CodeModel::Bits64 => "ml64.exe",
            _other => "ml.exe"
        };

        let out = Command::new(format!("..\\..\\tools\\{}", exe))
            .args(&["/c", "/Fo", &objpath.display().to_string(), &sourcepath.display().to_string()])
            .output()
            .expect("can run");
        if !out.status.success() {
            eprintln!("failed to assemble {text:x?}:");
            eprintln!("stdout: {}", std::str::from_utf8(out.stdout.as_slice()).expect("valid utf8"));
            eprintln!("stderr: {}", std::str::from_utf8(out.stderr.as_slice()).expect("valid utf8"));
            panic!("failed to {} as part of masm()", exe);
        }

        let out = Command::new("..\\..\\tools\\dumpbin.exe")
            .args(&["/disasm:wide", &objpath.display().to_string()])
            .output()
            .expect("can run");
        if !out.status.success() {
            eprintln!("failed to dumpbin {text:x?}:");
            eprintln!("stdout: {}", std::str::from_utf8(out.stdout.as_slice()).expect("valid utf8"));
            eprintln!("stderr: {}", std::str::from_utf8(out.stderr.as_slice()).expect("valid utf8"));
            panic!("failed to dumpbin.exe");
        }

        let dumpbin_out = std::str::from_utf8(out.stdout.as_slice()).expect("valid utf8");

        let dumpbin_interesting = carve_dumpbin_stdout(dumpbin_out).expect("works");

        let end =   "  0000000000000000: 0F C7 0F                                     ".len();
        let start = "  0000000000000000: ".len();
        let hex_text = dumpbin_interesting[0][start..end].trim();
        let mut bytes = Vec::new();
        for f in hex_text.split(" ") {
            let b = u8::from_str_radix(f, 16).expect("should be able to parse");
            bytes.push(b);
        }

        eprintln!("testcase \"{}\" -> masm -> dumpbin -> bytes {:x?}", text, bytes);

        Ok(bytes)
    }
}

#[allow(unused)]
fn carve_dumpbin_stdout(stdout: &str) -> Result<Vec<&str>, String> {
    let lines = stdout.split("\n").collect::<Vec<_>>();

    let mut disasm_start = match lines.iter().enumerate().find_map(|(idx, line)| {
        if line.starts_with("File Type: COFF OBJECT") {
            Some(idx)
        } else {
            None
        }
    }) {
        Some(start) => start,
        None => {
            eprintln!("failed to find COFF OBJECT line in dumpbin output:");
            eprintln!("{}", stdout);
            return Err("failed to find disassembly start in dumpbin output".to_string());
        }
    };

    let disasm_end = match lines.iter().enumerate().find_map(|(idx, line)| {
        if line.starts_with("  Summary") {
            Some(idx)
        } else {
            None
        }
    }) {
        Some(end) => end,
        None => {
            eprintln!("failed to find Summary line in dumpbin output:");
            eprintln!("{}", stdout);
            return Err("failed to find disassembly end in dumpbin output".to_string());
        }
    };

    if lines[disasm_start + 2].starts_with("$$00") {
        // the line is probably an invented label for rip-relative addressing.
        disasm_start += 1;
    }

    let disasm_lines = &lines[disasm_start + 2..disasm_end - 2 + 1];

    if disasm_lines.len() > 1 {
        eprintln!("disassembly is too complex");
        eprintln!("{}", stdout);
        return Err("got multiple lines of disassembly".to_string());
    }

    // eprintln!("dumpbin returns: {:?}", disasm_lines);

    Ok(disasm_lines.to_vec())
}