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
//! Panels about the code itself: disassembly, the explanation, breakpoints.

use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::Wrap;
use ratatui::Frame;

use crate::app::page::Page;
use crate::app::panel::Panel;
use crate::app::App;

/// Draws the disassembly panel.
pub fn draw_disassembly(frame: &mut Frame, app: &App, area: Rect, focused: bool) {
    let block = super::panel_block(&app.theme, Panel::Disassembly, focused);

    if app.disassembly.is_empty() {
        super::draw_placeholder(
            frame,
            area,
            &app.theme,
            block,
            "No disassembly yet.\n\nBuild the project (F6) to disassemble the executable, or \
             start a debug session (F12) to follow the program counter.",
        );
        return;
    }
    let inner = block.inner(area);
    frame.render_widget(block, area);
    if inner.width == 0 || inner.height == 0 {
        return;
    }

    let lines = disassembly_lines(app, usize::from(inner.width));
    super::draw_scrolled(frame, app, Panel::Disassembly, inner, lines, None);
}

/// Columns kept for the mnemonic and its operands, whatever else is dropped.
const INSTRUCTION_WIDTH: usize = 20;

/// How wide the address and byte columns should be for this listing.
fn column_widths(app: &App, width: usize) -> (usize, usize) {
    let widest_address = app
        .disassembly
        .iter()
        .map(|line| line.instruction.address)
        .max()
        .unwrap_or(0);
    let digits = (16 - widest_address.leading_zeros() as usize / 4).max(8);
    let address = digits.min(16);

    let bytes = app
        .disassembly
        .iter()
        .map(|line| line.instruction.bytes_text().chars().count())
        .max()
        .unwrap_or(0)
        .min(24);

    let fixed = 2 + address + 2;
    if fixed + bytes + 2 + INSTRUCTION_WIDTH > width {
        (address, 0)
    } else {
        (address, bytes)
    }
}

/// One line per decoded instruction, for a panel `width` columns wide.
pub fn disassembly_lines<'a>(app: &App, width: usize) -> Vec<Line<'a>> {
    let theme = &app.theme;
    let symbols = theme.symbols();
    let (address_width, byte_width) = column_widths(app, width);

    app.disassembly
        .iter()
        .map(|line| {
            let instruction = &line.instruction;
            let is_current = app.current_address == Some(instruction.address);

            let marker = if is_current {
                Span::styled(
                    format!("{} ", symbols.current_instruction),
                    theme.current_line(),
                )
            } else {
                Span::raw("  ".to_owned())
            };

            let text_style = if instruction.invalid {
                theme.error()
            } else if is_current {
                theme.current_line()
            } else {
                theme.base()
            };

            let mut spans = vec![
                marker,
                Span::styled(
                    format!("{:0address_width$x}  ", instruction.address),
                    theme.address(),
                ),
            ];
            if byte_width > 0 {
                spans.push(Span::styled(
                    format!("{:<byte_width$}  ", instruction.bytes_text()),
                    theme.bytes(),
                ));
            }
            spans.push(Span::styled(instruction.text(), text_style));

            if let Some(name) = instruction
                .branch_target
                .and_then(|target| target_name(app, target))
            {
                spans.push(Span::styled(
                    format!("  {} {name}", symbols.stack_pointer),
                    theme.dim(),
                ));
            }
            Line::from(spans)
        })
        .collect()
}

fn target_name(app: &App, target: u64) -> Option<String> {
    let line = app
        .disassembly
        .iter()
        .find(|line| line.instruction.address == target)?;
    let (name, offset) = line.symbol.as_ref()?;
    Some(if *offset == 0 {
        name.clone()
    } else {
        format!("{name}+{offset:#x}")
    })
}

/// Draws the instruction explanation panel.
pub fn draw_explanation(frame: &mut Frame, app: &App, area: Rect, focused: bool) {
    let block = super::panel_block(&app.theme, Panel::Explain, focused);

    if app.current_explanation().is_none() {
        let hint = match app.page {
            Page::Reference => "Type an instruction name in the search box to see what it does.",
            Page::Learn => "Type an instruction in the scratchpad to see what it does.",
            Page::Code | Page::Debug => "Put the cursor on an instruction to see what it does.",
        };
        super::draw_placeholder(frame, area, &app.theme, block, hint);
        return;
    }
    let inner = block.inner(area);
    frame.render_widget(block, area);
    if inner.width == 0 || inner.height == 0 {
        return;
    }

    let lines = explanation_lines(app);
    super::draw_scrolled(
        frame,
        app,
        Panel::Explain,
        inner,
        lines,
        Some(Wrap { trim: true }),
    );
}

/// The explanation of whichever instruction is under discussion.
pub fn explanation_lines<'a>(app: &App) -> Vec<Line<'a>> {
    let Some(explanation) = app.current_explanation() else {
        return Vec::new();
    };
    let theme = &app.theme;
    let mut lines: Vec<Line> = Vec::new();

    let mut heading = vec![Span::styled(
        explanation.mnemonic.to_uppercase(),
        theme.bright(),
    )];
    if let Some(prefix) = &explanation.prefix {
        heading.insert(
            0,
            Span::styled(format!("{} ", prefix.to_uppercase()), theme.accent()),
        );
    }
    heading.push(Span::styled(
        format!("  {}", explanation.summary),
        theme.dim(),
    ));
    lines.push(Line::from(heading));

    for (label, value) in explanation.lines() {
        lines.push(super::field_line(
            format!("{label:<16}"),
            value,
            theme.dim(),
            theme.base(),
        ));

        if label == "Effect" {
            if let Some(concrete) = &explanation.concrete {
                lines.push(super::field_line(
                    format!("{:<16}", "  with values"),
                    concrete.clone(),
                    theme.dim(),
                    theme.current_line(),
                ));
            }
        }
    }

    if explanation.approximate {
        lines.push(Line::from(Span::styled(
            "Vector instruction: named, but its per-lane effect is not modelled.",
            theme.warning(),
        )));
    }
    if let Some(notes) = &explanation.notes {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(notes.clone(), theme.dim())));
    }

    lines
}

/// Draws the call stack: the chain of calls, not the stack memory.
pub fn draw_call_stack(frame: &mut Frame, app: &App, area: Rect, focused: bool) {
    let block = super::panel_block(&app.theme, Panel::CallStack, focused);

    if app.frames.is_empty() {
        let message = if app.debugger.state().can_inspect() {
            "No frames reported.\n\nGDB could not walk the stack from here."
        } else {
            "No debug session.\n\nPress F12 to start one; the call stack shows how execution \
             reached the current instruction."
        };
        super::draw_placeholder(frame, area, &app.theme, block, message);
        return;
    }
    let inner = block.inner(area);
    frame.render_widget(block, area);
    if inner.width == 0 || inner.height == 0 {
        return;
    }

    let theme = &app.theme;
    let symbols = theme.symbols();

    let lines: Vec<Line> = app
        .frames
        .iter()
        .enumerate()
        .map(|(index, stack_frame)| {
            let selected = index == app.frame_selected && focused;
            let marker = if stack_frame.is_innermost() {
                symbols.current_instruction
            } else if selected {
                symbols.selection
            } else {
                " "
            };

            let style = if selected {
                theme.selection()
            } else if stack_frame.is_innermost() {
                theme.current_line()
            } else {
                theme.dim()
            };

            Line::from(vec![
                Span::styled(format!("{marker} "), theme.accent()),
                Span::styled(
                    super::truncate(
                        &stack_frame.describe(),
                        usize::from(inner.width).saturating_sub(2),
                        symbols.ellipsis,
                    ),
                    style,
                ),
            ])
        })
        .collect();

    super::draw_scrolled(frame, app, Panel::CallStack, inner, lines, None);
}

/// Draws the breakpoint list.
pub fn draw_breakpoints(frame: &mut Frame, app: &App, area: Rect, focused: bool) {
    let block = super::panel_block(&app.theme, Panel::Breakpoints, focused);

    if app.breakpoints.is_empty() {
        super::draw_placeholder(
            frame,
            area,
            &app.theme,
            block,
            "No breakpoints.\n\nPut the cursor on a line and press F9 to set one.",
        );
        return;
    }
    let inner = block.inner(area);
    frame.render_widget(block, area);
    if inner.width == 0 || inner.height == 0 {
        return;
    }

    let theme = &app.theme;
    let symbols = theme.symbols();

    let lines: Vec<Line> = app
        .breakpoints
        .all()
        .iter()
        .enumerate()
        .map(|(index, breakpoint)| {
            let glyph = if breakpoint.enabled {
                symbols.breakpoint
            } else {
                symbols.breakpoint_disabled
            };
            let style = if index == app.breakpoint_selected && focused {
                theme.selection()
            } else if breakpoint.enabled {
                theme.base()
            } else {
                theme.dim()
            };

            Line::from(vec![
                Span::styled(format!("{glyph} "), theme.breakpoint()),
                Span::styled(breakpoint.describe(), style),
            ])
        })
        .collect();

    super::draw_scrolled(frame, app, Panel::Breakpoints, inner, lines, None);
}

#[cfg(test)]
mod tests {
    use crate::app::App;
    use crate::config::Settings;
    use crate::project::Project;

    fn app() -> App {
        let project = Project::for_file(std::path::Path::new("/tmp/ratasm-test/main.asm"));
        App::new(project, Settings::default()).expect("databases load")
    }

    fn decoded(address: u64, bytes: Vec<u8>) -> crate::disassembler::DisassemblyLine {
        let mut decoded = crate::disassembler::decode(&bytes, address, Default::default());
        crate::disassembler::DisassemblyLine::bare(decoded.pop().expect("one instruction"))
    }

    #[test]
    fn a_branch_names_its_target_by_symbol() {
        let mut app = app();
        let mut jump = decoded(0x1000, vec![0xeb, 0x00]);
        assert_eq!(jump.instruction.text(), "jmp 0x1002");
        jump.symbol = Some(("start".into(), 0));
        let mut target = decoded(0x1002, vec![0x90]);
        target.symbol = Some(("start".into(), 2));
        app.disassembly = vec![jump, target];
        assert_eq!(
            super::target_name(&app, 0x1002).as_deref(),
            Some("start+0x2")
        );
        assert_eq!(super::target_name(&app, 0x9999), None);
    }

    #[test]
    fn a_low_address_does_not_pay_for_sixteen_hex_digits() {
        let mut app = app();
        app.disassembly = vec![decoded(0x40_00b0, vec![0x90])];

        let (address, _) = super::column_widths(&app, 120);
        assert_eq!(address, 8, "a user program sits well below 2^32");

        app.disassembly = vec![decoded(0x7fff_0000_1000, vec![0x90])];
        let (address, _) = super::column_widths(&app, 120);
        assert!(address > 8, "a high address still gets the digits it needs");
    }

    #[test]
    fn the_byte_column_fits_the_listing_and_goes_when_there_is_no_room() {
        let mut app = app();
        app.disassembly = vec![decoded(0x40_00b0, vec![0x90])];

        let (_, bytes) = super::column_widths(&app, 120);
        assert_eq!(bytes, 2, "one byte needs two columns, not twenty-four");

        let (_, bytes) = super::column_widths(&app, 24);
        assert_eq!(bytes, 0, "the mnemonic outranks the machine code");
    }

    #[test]
    fn an_empty_listing_still_produces_usable_widths() {
        let app = app();
        let (address, bytes) = super::column_widths(&app, 120);
        assert_eq!((address, bytes), (8, 0));
    }

    #[test]
    fn the_explanation_panel_has_content_for_a_real_instruction() {
        let mut app = app();
        app.workspace.active_mut().insert("    add rax, rbx\n");
        app.workspace.active_mut().move_cursor(
            crate::editor::Movement::To(crate::editor::Position::new(0, 6)),
            crate::editor::SelectionMode::Collapse,
        );

        let explanation = app.current_explanation().expect("an explanation");
        assert_eq!(explanation.effect, "RAX ← RAX + RBX");
        assert!(!explanation.lines().is_empty());
    }

    #[test]
    fn a_comment_line_yields_no_explanation_to_draw() {
        let mut app = app();
        app.workspace.active_mut().insert("; nothing here\n");
        assert!(app.current_explanation().is_none());
    }
}