ratasm 0.3.0

A terminal IDE and debugger for x86_64 assembly
Documentation
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//! Building GDB/MI commands.
//!
//! Commands are constructed as a name plus a list of arguments and rendered
//! once, at the point of sending. Arguments that need quoting are quoted and
//! escaped here, so a path containing a space — or a source file whose name
//! contains a quote — cannot break the protocol framing.
//!
//! Every command carries a numeric token. GDB echoes it on the matching result
//! record, which is what lets a reply be identified when asynchronous events
//! are interleaved with it.

use std::fmt;
use std::path::Path;

/// A GDB/MI command awaiting a token.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Command {
    name: String,
    args: Vec<String>,
}

impl Command {
    /// Creates a command with the given MI operation name.
    ///
    /// The leading `-` is added if it is not already present.
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();
        let name = if name.starts_with('-') || name.is_empty() {
            name
        } else {
            format!("-{name}")
        };
        Self {
            name,
            args: Vec::new(),
        }
    }

    /// Appends one argument.
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.args.push(arg.into());
        self
    }

    /// Appends several arguments.
    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.args.extend(args.into_iter().map(Into::into));
        self
    }

    /// The operation name.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The arguments, unquoted.
    pub fn arguments(&self) -> &[String] {
        &self.args
    }

    /// Renders the command with `token`, without a trailing newline.
    pub fn render(&self, token: u32) -> String {
        let mut out = format!("{token}{}", self.name);
        for arg in &self.args {
            out.push(' ');
            out.push_str(&quote(arg));
        }
        out
    }
}

impl fmt::Display for Command {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.name)?;
        for arg in &self.args {
            write!(f, " {}", quote(arg))?;
        }
        Ok(())
    }
}

/// Quotes an argument if the MI grammar requires it.
///
/// Arguments that are plain words are passed through unquoted, which keeps
/// commands readable in the protocol log. Anything containing whitespace, a
/// quote, a backslash or a control character is wrapped in a C-string.
pub fn quote(arg: &str) -> String {
    let needs_quoting = arg.is_empty()
        || arg
            .chars()
            .any(|ch| ch.is_whitespace() || ch == '"' || ch == '\\' || ch.is_control());

    if !needs_quoting {
        return arg.to_owned();
    }

    let mut out = String::with_capacity(arg.len() + 2);
    out.push('"');
    for ch in arg.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            other => out.push(other),
        }
    }
    out.push('"');
    out
}

/// Loads an executable and its symbols.
pub fn file_exec_and_symbols(path: &Path) -> Command {
    Command::new("-file-exec-and-symbols").arg(path.display().to_string())
}

/// Sets the arguments the program will be started with.
pub fn exec_arguments<I, S>(args: I) -> Command
where
    I: IntoIterator<Item = S>,
    S: Into<String>,
{
    Command::new("-exec-arguments").args(args)
}

/// Sets the working directory for the program.
pub fn environment_cd(path: &Path) -> Command {
    Command::new("-environment-cd").arg(path.display().to_string())
}

/// Connects the inferior's standard streams to a pseudo-terminal.
pub fn inferior_tty_set(path: &Path) -> Command {
    Command::new("-inferior-tty-set").arg(path.display().to_string())
}

/// Starts the program, stopping at its entry point.
///
/// `--start` is used rather than plain run so the debugger always gets an
/// initial stop, giving the user a chance to inspect the program before any of
/// it executes.
pub fn exec_run_to_start() -> Command {
    Command::new("-exec-run").arg("--start")
}

/// Starts the program without stopping at the entry point.
pub fn exec_run() -> Command {
    Command::new("-exec-run")
}

/// Resumes execution.
pub fn exec_continue() -> Command {
    Command::new("-exec-continue")
}

/// Interrupts a running program.
pub fn exec_interrupt() -> Command {
    Command::new("-exec-interrupt").arg("--all")
}

/// Executes one machine instruction, entering calls.
pub fn exec_step_instruction() -> Command {
    Command::new("-exec-step-instruction")
}

/// Executes one machine instruction, stepping over calls.
pub fn exec_next_instruction() -> Command {
    Command::new("-exec-next-instruction")
}

/// Executes one source line, entering calls.
pub fn exec_step() -> Command {
    Command::new("-exec-step")
}

/// Executes one source line, stepping over calls.
pub fn exec_next() -> Command {
    Command::new("-exec-next")
}

/// Executes one machine instruction backwards.
pub fn exec_step_instruction_reverse() -> Command {
    Command::new("-exec-step-instruction").arg("--reverse")
}

/// Executes one machine instruction backwards, over calls.
pub fn exec_next_instruction_reverse() -> Command {
    Command::new("-exec-next-instruction").arg("--reverse")
}

/// Executes one source line backwards.
pub fn exec_step_reverse() -> Command {
    Command::new("-exec-step").arg("--reverse")
}

/// Runs backwards until the previous breakpoint or the start of the recording.
pub fn exec_continue_reverse() -> Command {
    Command::new("-exec-continue").arg("--reverse")
}

/// Runs an ordinary GDB console command.
///
/// The escape hatch for the handful of things the machine interface has no
/// command of its own for. Used sparingly: the reply comes back as console
/// text rather than structured data, so anything with a real MI command uses
/// that instead.
pub fn console(command: &str) -> Command {
    Command::new("-interpreter-exec")
        .arg("console")
        .arg(command)
}

/// Starts recording execution so it can be replayed backwards.
///
/// There is no MI command for this, so it goes through the console. Recording
/// makes every instruction cost more, which is invisible for the small
/// programs ratasm targets and would not be for a large one — hence the
/// setting that turns it off.
pub fn record_full() -> Command {
    console("record full")
}

/// Stops recording, so the program can run past an exit.
pub fn record_stop() -> Command {
    console("record stop")
}

/// Runs until the current function returns.
pub fn exec_finish() -> Command {
    Command::new("-exec-finish")
}

/// Sets a breakpoint at a source location or symbol.
pub fn break_insert(location: &str) -> Command {
    Command::new("-break-insert").arg(location)
}

/// Sets a breakpoint that may start disabled or carry a condition.
pub fn break_insert_with(location: &str, enabled: bool, condition: Option<&str>) -> Command {
    let mut command = Command::new("-break-insert");
    if !enabled {
        command = command.arg("-d");
    }
    if let Some(condition) = condition {
        command = command.arg("-c").arg(condition);
    }
    command.arg(location)
}

/// Sets a watchpoint that stops when `expression` changes.
pub fn break_watch(expression: &str) -> Command {
    Command::new("-break-watch").arg(expression)
}

/// Sets or, with `None`, clears a breakpoint's condition.
pub fn break_condition(number: u32, condition: Option<&str>) -> Command {
    let command = Command::new("-break-condition").arg(number.to_string());
    match condition {
        Some(condition) => command.arg(condition),
        None => command,
    }
}

/// Sets a breakpoint at a file and line.
pub fn break_insert_at_line(file: &str, line: usize) -> Command {
    Command::new("-break-insert").arg(format!("{file}:{line}"))
}

/// Sets a breakpoint at a raw address.
///
/// The `*` prefix is MI's syntax for "this is an address, not a symbol".
pub fn break_insert_at_address(address: u64) -> Command {
    Command::new("-break-insert").arg(format!("*0x{address:x}"))
}

/// Sets a breakpoint that deletes itself the first time it is hit.
///
/// Used to stop at the entry point when a session starts.
pub fn break_insert_temporary(location: &str) -> Command {
    Command::new("-break-insert").arg("-t").arg(location)
}

/// Sets a self-deleting breakpoint at a raw address.
pub fn break_insert_temporary_at_address(address: u64) -> Command {
    Command::new("-break-insert")
        .arg("-t")
        .arg(format!("*0x{address:x}"))
}

/// Removes a breakpoint by number.
pub fn break_delete(number: u32) -> Command {
    Command::new("-break-delete").arg(number.to_string())
}

/// Enables a breakpoint.
pub fn break_enable(number: u32) -> Command {
    Command::new("-break-enable").arg(number.to_string())
}

/// Disables a breakpoint without removing it.
pub fn break_disable(number: u32) -> Command {
    Command::new("-break-disable").arg(number.to_string())
}

/// Lists all breakpoints.
pub fn break_list() -> Command {
    Command::new("-break-list")
}

/// Lists the names of every register, in GDB's numbering order.
pub fn data_list_register_names() -> Command {
    Command::new("-data-list-register-names")
}

/// Reads every register as a hexadecimal value.
pub fn data_list_register_values() -> Command {
    Command::new("-data-list-register-values").arg("x")
}

/// Reads the registers that changed since the previous stop.
pub fn data_list_changed_registers() -> Command {
    Command::new("-data-list-changed-registers")
}

/// Reads `count` bytes of memory starting at `address`.
pub fn data_read_memory_bytes(address: u64, count: usize) -> Command {
    Command::new("-data-read-memory-bytes")
        .arg(format!("0x{address:x}"))
        .arg(count.to_string())
}

/// Writes a value into memory.
pub fn data_write_memory_bytes(address: u64, contents: &str) -> Command {
    Command::new("-data-write-memory-bytes")
        .arg(format!("0x{address:x}"))
        .arg(contents)
}

/// Disassembles the address range `[start, end)`.
///
/// Mode 4 asks for source lines and opcode bytes alongside the instructions,
/// which is what the side-by-side disassembly view needs. GDB falls back to
/// instructions alone when the program has no debug information.
pub fn data_disassemble_range(start: u64, end: u64) -> Command {
    Command::new("-data-disassemble")
        .arg("-s")
        .arg(format!("0x{start:x}"))
        .arg("-e")
        .arg(format!("0x{end:x}"))
        .arg("--")
        .arg("4")
}

/// Disassembles the range with instructions and opcodes but no source.
pub fn data_disassemble_range_plain(start: u64, end: u64) -> Command {
    Command::new("-data-disassemble")
        .arg("-s")
        .arg(format!("0x{start:x}"))
        .arg("-e")
        .arg(format!("0x{end:x}"))
        .arg("--")
        .arg("2")
}

/// Evaluates an expression in the current frame.
pub fn data_evaluate_expression(expression: &str) -> Command {
    Command::new("-data-evaluate-expression").arg(expression)
}

/// Lists the frames of the call stack.
pub fn stack_list_frames() -> Command {
    Command::new("-stack-list-frames")
}

/// Selects a stack frame by level.
pub fn stack_select_frame(level: u32) -> Command {
    Command::new("-stack-select-frame").arg(level.to_string())
}

/// Lists information about the current threads.
pub fn thread_info() -> Command {
    Command::new("-thread-info")
}

/// Ends the debugging session.
pub fn gdb_exit() -> Command {
    Command::new("-gdb-exit")
}

/// Sets a GDB parameter, such as `disassembly-flavor`.
pub fn gdb_set(name: &str, value: &str) -> Command {
    Command::new("-gdb-set").arg(name).arg(value)
}

/// Selects the disassembly flavour.
///
/// Intel syntax is the default because the editor targets NASM, where reading
/// disassembly in AT&T order would mean mentally reversing every operand.
pub fn set_disassembly_flavor(intel: bool) -> Command {
    gdb_set("disassembly-flavor", if intel { "intel" } else { "att" })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_command_renders_with_its_token() {
        assert_eq!(Command::new("-exec-run").render(7), "7-exec-run");
    }

    #[test]
    fn a_missing_leading_dash_is_added() {
        assert_eq!(Command::new("exec-run").name(), "-exec-run");
        assert_eq!(Command::new("-exec-run").name(), "-exec-run");
    }

    #[test]
    fn plain_arguments_are_not_quoted() {
        // Readability in the protocol log matters when debugging the debugger.
        let command = Command::new("-break-insert").arg("_start");
        assert_eq!(command.render(1), "1-break-insert _start");
    }

    #[test]
    fn arguments_with_spaces_are_quoted() {
        let command = Command::new("-file-exec-and-symbols").arg("/tmp/my project/main");
        assert_eq!(
            command.render(2),
            "2-file-exec-and-symbols \"/tmp/my project/main\""
        );
    }

    #[test]
    fn quotes_and_backslashes_are_escaped() {
        // The property that keeps a hostile path from breaking framing.
        assert_eq!(quote(r#"a"b"#), r#""a\"b""#);
        assert_eq!(quote(r"a\b"), r#""a\\b""#);
        assert_eq!(quote("a\nb"), r#""a\nb""#);
        assert_eq!(quote("a\tb"), r#""a\tb""#);
    }

    #[test]
    fn an_empty_argument_is_quoted_so_it_is_not_lost() {
        assert_eq!(quote(""), r#""""#);
        assert_eq!(Command::new("-x").arg("").render(1), r#"1-x """#);
    }

    #[test]
    fn a_path_that_would_break_framing_is_neutralised() {
        let hostile = Path::new("/tmp/evil\" -exec-run \"/x");
        let rendered = file_exec_and_symbols(hostile).render(3);
        // The injected command text must be inside one quoted argument.
        assert_eq!(
            rendered,
            r#"3-file-exec-and-symbols "/tmp/evil\" -exec-run \"/x""#
        );
        assert_eq!(rendered.matches("-exec-run").count(), 1);
    }

    #[test]
    fn an_inferior_terminal_path_is_a_single_mi_argument() {
        assert_eq!(
            inferior_tty_set(Path::new("/dev/pts/12")).render(4),
            "4-inferior-tty-set /dev/pts/12"
        );
    }

    #[test]
    fn breakpoint_commands_render_correctly() {
        assert_eq!(break_insert("_start").render(1), "1-break-insert _start");
        assert_eq!(
            break_insert_at_line("main.asm", 12).render(2),
            "2-break-insert main.asm:12"
        );
        assert_eq!(break_delete(3).render(4), "4-break-delete 3");
        assert_eq!(break_enable(1).render(5), "5-break-enable 1");
        assert_eq!(break_disable(1).render(6), "6-break-disable 1");
        assert_eq!(break_list().render(7), "7-break-list");
    }

    #[test]
    fn a_temporary_breakpoint_carries_the_delete_flag() {
        // How a session stops at the entry point: -exec-run --start looks for
        // `main` and runs a _start-only program to completion instead.
        assert_eq!(
            break_insert_temporary("_start").render(1),
            "1-break-insert -t _start"
        );
        assert_eq!(
            break_insert_temporary_at_address(0x401000).render(2),
            "2-break-insert -t *0x401000"
        );
    }

    #[test]
    fn an_address_breakpoint_uses_the_star_prefix() {
        // Without the star GDB reads the text as a symbol name.
        assert_eq!(
            break_insert_at_address(0x40_00b0).render(1),
            "1-break-insert *0x4000b0"
        );
    }

    #[test]
    fn a_file_with_a_space_is_quoted_in_a_line_breakpoint() {
        let command = break_insert_at_line("my source.asm", 5);
        assert_eq!(command.render(1), "1-break-insert \"my source.asm:5\"");
    }

    #[test]
    fn memory_commands_use_hexadecimal_addresses() {
        assert_eq!(
            data_read_memory_bytes(0x7fff_ffff_e000, 64).render(1),
            "1-data-read-memory-bytes 0x7fffffffe000 64"
        );
    }

    #[test]
    fn disassembly_requests_the_documented_mode() {
        assert_eq!(
            data_disassemble_range(0x4000, 0x4010).render(1),
            "1-data-disassemble -s 0x4000 -e 0x4010 -- 4"
        );
        assert_eq!(
            data_disassemble_range_plain(0x4000, 0x4010).render(2),
            "2-data-disassemble -s 0x4000 -e 0x4010 -- 2"
        );
    }

    #[test]
    fn execution_commands_render_correctly() {
        assert_eq!(exec_run_to_start().render(1), "1-exec-run --start");
        assert_eq!(exec_continue().render(2), "2-exec-continue");
        assert_eq!(exec_step_instruction().render(3), "3-exec-step-instruction");
        assert_eq!(exec_next_instruction().render(4), "4-exec-next-instruction");
        assert_eq!(exec_step().render(5), "5-exec-step");
        assert_eq!(exec_next().render(6), "6-exec-next");
        assert_eq!(exec_finish().render(7), "7-exec-finish");
        assert_eq!(exec_interrupt().render(8), "8-exec-interrupt --all");
    }

    #[test]
    fn reverse_execution_commands_carry_the_reverse_flag() {
        assert_eq!(
            exec_step_instruction_reverse().render(1),
            "1-exec-step-instruction --reverse"
        );
        assert_eq!(
            exec_next_instruction_reverse().render(2),
            "2-exec-next-instruction --reverse"
        );
        assert_eq!(exec_step_reverse().render(3), "3-exec-step --reverse");
        assert_eq!(
            exec_continue_reverse().render(4),
            "4-exec-continue --reverse"
        );
    }

    #[test]
    fn recording_goes_through_the_console_because_mi_has_no_command_for_it() {
        assert_eq!(
            record_full().render(1),
            "1-interpreter-exec console \"record full\""
        );
    }

    #[test]
    fn a_console_command_with_spaces_is_quoted_as_one_argument() {
        // Otherwise GDB would read the words as separate arguments.
        let rendered = console("set confirm off").render(1);
        assert_eq!(rendered, "1-interpreter-exec console \"set confirm off\"");
    }

    #[test]
    fn register_commands_request_hexadecimal_values() {
        assert_eq!(
            data_list_register_values().render(1),
            "1-data-list-register-values x"
        );
        assert_eq!(
            data_list_register_names().render(2),
            "2-data-list-register-names"
        );
        assert_eq!(
            data_list_changed_registers().render(3),
            "3-data-list-changed-registers"
        );
    }

    #[test]
    fn the_disassembly_flavour_defaults_to_intel() {
        assert_eq!(
            set_disassembly_flavor(true).render(1),
            "1-gdb-set disassembly-flavor intel"
        );
        assert_eq!(
            set_disassembly_flavor(false).render(2),
            "2-gdb-set disassembly-flavor att"
        );
    }

    #[test]
    fn program_arguments_are_quoted_individually() {
        let command = exec_arguments(["--flag", "a value", "plain"]);
        assert_eq!(
            command.render(1),
            "1-exec-arguments --flag \"a value\" plain"
        );
    }

    #[test]
    fn display_omits_the_token() {
        // Used in the protocol log, where the token is shown separately.
        assert_eq!(break_insert("_start").to_string(), "-break-insert _start");
    }

    #[test]
    fn a_rendered_command_never_contains_a_newline() {
        // A newline inside a command would be read as a second command.
        let command = Command::new("-break-insert").arg("evil\n-gdb-exit");
        let rendered = command.render(1);
        assert!(!rendered.contains('\n'), "rendered: {rendered}");
        assert!(rendered.contains("\\n"));
    }

    #[test]
    fn arguments_are_preserved_unquoted_for_inspection() {
        let command = Command::new("-x").arg("a b").arg("c");
        assert_eq!(command.arguments(), ["a b", "c"]);
    }
}