sys-rs 0.1.1

ptrace-based Linux system tool reimplementations: strace, gcov, addr2line, debugger
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
use libunwind_rs::{Accessors, AddressSpace, Byteorder, Cursor, PtraceState};
use nix::{errno::Errno, sys::ptrace};
use std::fs::read_to_string;

use crate::{
    diag::{Error, Result},
    hwaccess::Registers,
    param::{Join, Value},
    print::Layout,
    progress::{Execution, Mode, State},
};

/// Type of a command handler function.
///
/// A `CommandFn` is a function that receives the parsed argument list and
/// a mutable reference to the current `progress::State` and returns a
/// `Result` indicating success or failure.
pub type CommandFn = fn(&[Value], &mut State) -> Result<()>;

fn exit_with(args: &[Value], state: &mut State, f: CommandFn) -> Result<()> {
    f(args, state)?;
    state.set_execution(Execution::Exit);
    Ok(())
}

fn proceed_with(args: &[Value], state: &mut State, f: CommandFn) -> Result<()> {
    f(args, state)?;
    state.set_execution(Execution::Run);
    Ok(())
}

fn stall_with(args: &[Value], state: &mut State, f: CommandFn) -> Result<()> {
    f(args, state)?;
    state.set_execution(Execution::Skip);
    Ok(())
}

fn do_breakpoint_common(
    args: &[Value],
    state: &mut State,
    temporary: bool,
) -> Result<()> {
    let addr = match args {
        [Value::Address(addr)] => Ok(*addr),
        [] => state.prev_rip().ok_or_else(|| Error::from(Errno::ENODATA)),
        _ => Err(Error::from(Errno::EINVAL)),
    }?;

    if let Ok(id) = state
        .breakpoint_mgr()
        .set_breakpoint(addr, temporary, true, None)
    {
        let id = id.ok_or_else(|| Error::from(Errno::ENODATA))?;
        let bp_type = if temporary { "Temporary" } else { "Permanent" };
        println!("{bp_type} breakpoint #{id} set at address {addr:#x}");
    } else {
        eprintln!("Failed to set breakpoint at address {addr:#x}");
    }

    Ok(())
}

/// Handler for ambiguous commands (user input matches multiple commands).
///
/// Prints an error message indicating the command was ambiguous and does
/// not change execution state.
///
/// # Errors
///
/// Returns an error if the underlying printing operation fails (rare).
pub fn do_ambiguous(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |args, _| {
        eprintln!("{}: ambiguous command", args.join(" "));
        Ok(())
    })
}

/// Handler that prints a backtrace for the traced process.
///
/// Uses libunwind via ptrace to walk the tracee's stack and prints each
/// frame. When DWARF line information is available it will include file and
/// line information.
///
/// # Errors
///
/// Returns an error if libunwind/ptrace operations fail or if address
/// -> line resolution fails.
pub fn do_backtrace(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |_, state| {
        let pstate = PtraceState::new(u32::try_from(state.pid().as_raw())?)?;
        let mut aspace = AddressSpace::new(Accessors::ptrace(), Byteorder::Default)?;
        let mut cursor = Cursor::ptrace(&mut aspace, &pstate)?;

        let mut i = 0;
        loop {
            let ip = cursor.ip()?;
            let name = cursor
                .proc_name()
                .unwrap_or_else(|_| "<unknown>".to_string());

            let frame = format!("#{i} {ip:#018x} in {name} ()");
            match state.addr2line(u64::try_from(ip)?)? {
                Some(line) => println!("{frame} at {}:{}", line.path(), line.line()),
                None => println!("{frame}"),
            }

            if !cursor.step()? {
                break;
            }

            i += 1;
        }

        Ok(())
    })
}

/// Set a permanent breakpoint at the given address or the previous RIP.
///
/// # Errors
///
/// Returns an error if argument parsing fails or if setting the
/// breakpoint via the breakpoint manager fails.
pub fn do_breakpoint(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |args, state| {
        do_breakpoint_common(args, state, false)
    })
}

/// Continue execution of the traced process.
///
/// Transitions the tracer into `Continue` mode and resumes execution.
///
/// # Errors
///
/// Returns an error if state update fails (rare).
pub fn do_continue(args: &[Value], state: &mut State) -> Result<()> {
    proceed_with(args, state, |_, state| {
        state.set_mode(Mode::Continue);
        Ok(())
    })
}

/// Delete a breakpoint by id.
///
/// # Errors
///
/// Returns an error if arguments are invalid or deletion fails.
pub fn do_delete(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |args, state| match args {
        [Value::Id(id)] => {
            if state.breakpoint_mgr().delete_breakpoint(*id).is_err() {
                eprintln!("No breakpoint number {id}");
            }
            Ok(())
        }
        _ => Err(Error::from(Errno::EINVAL)),
    })
}

/// Examine memory at a given address and format the bytes.
///
/// # Errors
///
/// Returns an error if arguments are invalid, memory cannot be read, or formatting fails.
pub fn do_examine(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |args, state| match args {
        [Value::Format(format), Value::Size(size), Value::Address(addr)] => {
            let word_size = std::mem::size_of::<usize>();
            let mut buf = vec![0u8; usize::try_from(*size)?];
            let mut offset = 0;

            while offset < buf.len() {
                let read_addr = *addr + offset as u64;
                let word = if let Ok(val) =
                    ptrace::read(state.pid(), read_addr as ptrace::AddressType)
                {
                    #[allow(
                        clippy::cast_possible_truncation,
                        clippy::cast_sign_loss
                    )]
                    let ret = val as usize;
                    ret
                } else {
                    eprintln!("Failed to read memory at {read_addr:#x}");
                    break;
                };

                let bytes_to_write = word_size.min(buf.len() - offset);
                (0..bytes_to_write).try_for_each(|i| -> Result<()> {
                    buf[offset + i] = u8::try_from((word >> (i * 8)) & 0xff)?;
                    Ok(())
                })?;
                offset += bytes_to_write;
            }

            format.bytes(&buf, *addr)
        }
        _ => Err(Error::from(Errno::EINVAL)),
    })
}

/// Print help text for available commands.
///
/// Accepts a list of strings to print; used by the REPL to display help.
///
/// # Errors
///
/// Returns an error if printing fails.
pub fn do_help(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |args, _| {
        println!("{}", args.join("\n"));
        Ok(())
    })
}

/// Print information about currently set breakpoints.
///
/// # Errors
///
/// Returns an error if state access fails (rare).
pub fn do_info_breakpoints(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |_, state| {
        state.print_breakpoints();
        Ok(())
    })
}

/// Print the memory map (`/proc/PID/maps`) of the traced process.
///
/// # Errors
///
/// Returns an error if reading `/proc/PID/maps` fails.
pub fn do_info_memory(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |_, state| {
        print!("{}", read_to_string(format!("/proc/{}/maps", state.pid()))?);
        Ok(())
    })
}

/// Print the current register state of the traced process.
///
/// # Errors
///
/// Returns an error if reading registers via ptrace fails.
pub fn do_info_registers(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |_, state| {
        let regs = Registers::read(state.pid())?;
        println!("{regs}");
        Ok(())
    })
}

/// Handler for invalid argument errors.
///
/// Prints an error indicating the provided arguments were invalid.
///
/// # Errors
///
/// Returns an error if printing fails.
pub fn do_invalid_arguments(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |args, _| {
        eprintln!("{}: invalid arguments", args.join(" "));
        Ok(())
    })
}

/// Switch the display layout to assembly mode.
///
/// If already in assembly layout, prints a message and does nothing.
///
/// # Errors
///
/// Returns an error on I/O failure while printing (unlikely).
pub fn do_layout_asm(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |_, state| {
        if *state.layout() == Layout::Assembly {
            eprintln!("Already in assembly layout mode");
        } else {
            println!("Switching to assembly layout mode");
            state.set_requested_layout(Layout::Assembly);
        }
        Ok(())
    })
}

/// Switch the display layout to source mode (when available).
///
/// If no source layout is available or already in source mode, prints a
/// message accordingly.
///
/// # Errors
///
/// Returns an error if printing fails.
pub fn do_layout_src(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |_, state| {
        if state.initial_layout() == Layout::Assembly {
            eprintln!("No source layout available (DWARF symbols missing?)");
        } else if *state.layout() == Layout::Source {
            eprintln!("Already in source layout mode");
        } else {
            println!("Switching to source layout mode");
            state.set_requested_layout(Layout::Source);
        }
        Ok(())
    })
}

/// Re-print the last printed source or assembly chunk.
///
/// Useful after stepping when the REPL wants to show the previously
/// displayed context again.
///
/// # Errors
///
/// Returns an error if printing fails.
pub fn do_list(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |_, state| {
        if let Some(text) = state.printed() {
            println!("{text}");
        }
        Ok(())
    })
}

/// Step over the next instruction (implement stepping semantics).
///
/// Transitions the tracer into `StepOver` mode.
///
/// # Errors
///
/// Returns an error if state update fails.
pub fn do_next(args: &[Value], state: &mut State) -> Result<()> {
    proceed_with(args, state, |_, state| {
        state.set_mode(Mode::StepOver);
        Ok(())
    })
}

/// A no-op handler that does nothing and stalls execution.
///
/// # Errors
///
/// Never returns an error.
pub fn do_nothing(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |_, _| Ok(()))
}

/// Quit the debugger and exit the tracer loop.
///
/// Marks the execution state as Exit and prints a message.
///
/// # Errors
///
/// Returns an error if the underlying exit action fails (unlikely).
pub fn do_quit(args: &[Value], state: &mut State) -> Result<()> {
    exit_with(args, state, |_, _| {
        println!("Exiting...");
        Ok(())
    })
}

/// Step a single instruction (single-step execution).
///
/// # Errors
///
/// Returns an error if state update fails.
pub fn do_step(args: &[Value], state: &mut State) -> Result<()> {
    proceed_with(args, state, |_, _| Ok(()))
}

/// Set a temporary breakpoint at the given address or previous RIP.
///
/// Temporary breakpoints are removed after they are hit.
///
/// # Errors
///
/// Returns an error if argument parsing or breakpoint insertion fails.
pub fn do_tbreakpoint(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |args, state| {
        do_breakpoint_common(args, state, true)
    })
}

/// Handler for completely unknown commands.
///
/// Prints an error message indicating the command is unknown.
///
/// # Errors
///
/// Returns an error if printing fails.
pub fn do_unknown(args: &[Value], state: &mut State) -> Result<()> {
    stall_with(args, state, |args, _| {
        eprintln!("{}: unknown command", args.join(" "));
        Ok(())
    })
}

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

    use nix::unistd::Pid;

    use crate::{
        param::Value,
        print::Layout,
        progress::{Execution, State},
    };

    #[test]
    fn test_do_help_sets_skip() {
        let mut state = State::new(Pid::from_raw(1), None);
        let cmds: Vec<Value> = vec![Value::String("one"), Value::String("two")];
        let res = do_help(&cmds, &mut state);
        assert!(res.is_ok());
        assert!(matches!(state.execution(), Execution::Skip));
    }

    #[test]
    fn test_do_invalid_arguments_sets_skip() {
        let mut state = State::new(Pid::from_raw(1), None);
        let args: Vec<Value> = vec![Value::String("bad")];
        let res = do_invalid_arguments(&args, &mut state);
        assert!(res.is_ok());
        assert!(matches!(state.execution(), Execution::Skip));
    }

    #[test]
    fn test_do_nothing_sets_skip() {
        let mut state = State::new(Pid::from_raw(1), None);
        let res = do_nothing(&[], &mut state);
        assert!(res.is_ok());
        assert!(matches!(state.execution(), Execution::Skip));
    }

    #[test]
    fn test_do_layout_asm_switches_when_not_assembly() {
        let mut state = State::new(Pid::from_raw(1), None);
        state.set_layout(Layout::Source);
        let res = do_layout_asm(&[], &mut state);
        assert!(res.is_ok());
        assert!(matches!(state.execution(), Execution::Skip));
        let taken = state.take_requested_layout();
        assert!(taken.is_some());
        assert_eq!(taken.unwrap(), Layout::Assembly);
    }

    #[test]
    fn test_do_layout_src_no_source_available() {
        let mut state = State::new(Pid::from_raw(1), None);
        let res = do_layout_src(&[], &mut state);
        assert!(res.is_ok());
        assert!(matches!(state.execution(), Execution::Skip));
        assert!(state.take_requested_layout().is_none());
    }

    #[test]
    fn test_do_continue_next_step_quit() {
        let mut state = State::new(Pid::from_raw(1), None);

        let res = do_continue(&[], &mut state);
        assert!(res.is_ok());
        assert!(matches!(state.execution(), Execution::Run));
        assert!(matches!(state.mode(), crate::progress::Mode::Continue));

        let mut state2 = State::new(Pid::from_raw(1), None);
        let res = do_next(&[], &mut state2);
        assert!(res.is_ok());
        assert!(matches!(state2.execution(), Execution::Run));
        assert!(matches!(state2.mode(), crate::progress::Mode::StepOver));

        let mut state3 = State::new(Pid::from_raw(1), None);
        let res = do_step(&[], &mut state3);
        assert!(res.is_ok());
        assert!(matches!(state3.execution(), Execution::Run));

        let mut state4 = State::new(Pid::from_raw(1), None);
        let res = do_quit(&[], &mut state4);
        assert!(res.is_ok());
        assert!(matches!(state4.execution(), Execution::Exit));
    }

    #[test]
    fn test_do_list_printed() {
        let mut state = State::new(Pid::from_raw(1), None);
        state.set_printed(Some("hello".to_string()));
        let res = do_list(&[], &mut state);
        assert!(res.is_ok());
        assert!(matches!(state.execution(), Execution::Skip));
    }
}