• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# gdbstub
2
3[![](http://meritbadge.herokuapp.com/gdbstub)](https://crates.io/crates/gdbstub)
4[![](https://docs.rs/gdbstub/badge.svg)](https://docs.rs/gdbstub)
5
6An ergonomic and easy-to-integrate implementation of the [GDB Remote Serial Protocol](https://sourceware.org/gdb/onlinedocs/gdb/Remote-Protocol.html#Remote-Protocol) in Rust, with full `#![no_std]` support.
7
8Why `gdbstub`?
9
10-   **Excellent Ergonomics**
11    -   Unlike other GDB stub libraries, which simply expose the underlying GDB protocol "warts and all", `gdbstub` tries to abstract as much of the raw GDB protocol details from the user.
12        -   For example, instead of having to dig through some [obscure XML files deep the GDB codebase](https://github.com/bminor/binutils-gdb/tree/master/gdb/features) just to read/write from CPU registers, `gdbstub` comes with [built-in register definitions](https://docs.rs/gdbstub/*/gdbstub/arch/index.html) for most common architectures!
13    -   `gdbstub` makes _extensive_ use of Rust's powerful type system + generics to enforce protocol invariants at compile time, minimizing the number of tricky protocol details end users have to worry about.
14-   **Easy to Integrate**
15    -   `gdbstub`'s API is designed to be as unobtrusive as possible, and shouldn't require any large refactoring effort to integrate into an existing project. It doesn't require taking direct ownership of any key data structures, and aims to be a "drop in" solution when you need to add debugging to a project.
16-   **`#![no_std]` Ready & Size Optimized**
17    -   Can be configured to use fixed-size, pre-allocated buffers. **`gdbstub` does _not_ depend on `alloc`.**
18    -   `gdbstub` is transport-layer agnostic, and uses a basic [`Connection`](https://docs.rs/gdbstub/latest/gdbstub/trait.Connection.html) interface to communicate with the GDB server. As long as target has some method of performing in-order, serial, byte-wise I/O (e.g: putchar/getchar over UART), it's possible to run `gdbstub` on it.
19    -   "You don't pay for what you don't use": If you don't implement a particular protocol extension, the resulting binary won't include _any_ code related to parsing/handling that extension's packets! See the [Zero-overhead Protocol Extensions](#zero-overhead-protocol-extensions) section below for more details.
20    -   A lot of work has gone into reducing `gdbstub`'s binary and RAM footprints.
21        -   In release builds, using all the tricks outlined in [`min-sized-rust`](https://github.com/johnthagen/min-sized-rust), a baseline `gdbstub` implementation weighs in at roughly **_10kb of `.text` and negligible `.rodata`!_** \*
22        -   This is already pretty good, and I suspect that there are still lots of low-hanging optimizations which can reduce the size even further.
23
24\* Exact numbers vary by target platform, compiler version, and `gdbstub` revision. Data was collected using the included `example_no_std` project compiled on x86_64.
25
26`gdbstub` is particularly well suited for _emulation_, making it easy to add powerful, non-intrusive debugging support to an emulated system. Just provide an implementation of the [`Target`](https://docs.rs/gdbstub/latest/gdbstub/target/trait.Target.html) trait for your target platform, and you're ready to start debugging!
27
28-   [Documentation](https://docs.rs/gdbstub)
29
30### Can I Use `gdsbtub` in Production?
31
32**Yes, as long as you don't mind some API churn until `1.0.0` is released.**
33
34`gdbstub` has been integrated into [many projects](#real-world-examples) since its initial `0.1.0` release, and thusfar, no _major_ bugs have been reported. Reported issues have typically been the result of faulty `Target` implementations (e.g: forgetting to adjust the PC after a breakpoint is hit), or were related to certain unimplemented GDB protocol features.
35
36That being said, due to `gdbstub`'s heavy use of Rust's type system in enforcing GDB protocol invariants at compile time, it's often been the case that implementing new GDB protocol features has required making some breaking Trait/Type changes (e.g: adding the `RegId` associated type to `Arch` to support addressing individual registers). While these changes are typically quite minor, they are nonetheless breaking, and may require a code-change when moving between versions.
37
38See the [Future Plans + Roadmap to `1.0.0`](#future-plans--roadmap-to-100) for more information on what features `gdbstub` still needs to implement before committing to API stability with version `1.0.0`.
39
40## Debugging Features
41
42The GDB Remote Serial Protocol is surprisingly complex, supporting advanced features such as remote file I/O, spawning new processes, "rewinding" program execution, and much, _much_ more. Thankfully, most of these features are completely optional, and getting a basic debugging session up-and-running only requires implementing a few basic methods:
43
44-   Base GDB Protocol
45    -   Step + Continue
46    -   Read/Write memory
47    -   Read/Write registers
48    -   (optional) Multithreading support
49
50Of course, most use-cases will want to support additional debugging features as well. At the moment, `gdbstub` implements the following GDB protocol extensions:
51
52-   Automatic architecture + feature detection (automatically implemented)
53-   Breakpoints
54    -   Software Breakpoints
55    -   Hardware Breakpoints
56    -   Read/Write/Access Watchpoints (i.e: value breakpoints)
57-   Extended Mode
58    -   Run/Attach/Kill Processes
59    -   Pass environment variables / args to spawned processes
60    -   Change working directory
61-   Section offsets
62    -   Get section/segment relocation offsets from the target
63-   Custom `monitor` Commands
64    -   Extend the GDB protocol with custom debug commands using GDB's `monitor` command
65
66_Note:_ Which GDB features are implemented are decided on an as-needed basis by `gdbstub`'s contributors. If there's a missing GDB feature that you'd like `gdbstub` to implement, please file an issue / open a PR! Check out the [GDB Remote Configuration Docs](https://sourceware.org/gdb/onlinedocs/gdb/Remote-Configuration.html) for a table of GDB commands + their corresponding Remote Serial Protocol packets.
67
68### Zero-overhead Protocol Extensions
69
70Using a technique called **Inlineable Dyn Extension Traits** (IDETs), `gdbstub` is able to leverage the Rust compiler's powerful optimization passes to ensure any unused features are dead-code-eliminated in release builds _without_ having to rely on compile-time features flags!
71
72For example, if your target doesn't implement a custom GDB `monitor` command handler, the resulting binary won't include any code related to parsing / handling the underlying `qRcmd` packet!
73
74If you're interested in the low-level technical details of how IDETs work, I've included a brief writeup in the documentation [here](https://docs.rs/gdbstub/latest/gdbstub/target/ext/index.html#how-protocol-extensions-work---inlineable-dyn-extension-traits-idets).
75
76## Feature flags
77
78By default, the `std` and `alloc` features are enabled.
79
80When using `gdbstub` in `#![no_std]` contexts, make sure to set `default-features = false`.
81
82-   `alloc`
83    -   Implement `Connection` for `Box<dyn Connection>`.
84    -   Log outgoing packets via `log::trace!` (uses a heap-allocated output buffer).
85    -   Provide built-in implementations for certain protocol features:
86        -   Use a heap-allocated packet buffer in `GdbStub` (if none is provided via `GdbStubBuilder::with_packet_buffer`).
87        -   (Monitor Command) Use a heap-allocated output buffer in `ConsoleOutput`.
88        -   (Extended Mode) Automatically track Attached/Spawned PIDs without implementing `ExtendedMode::query_if_attached`.
89-   `std` (implies `alloc`)
90    -   Implement `Connection` for [`TcpStream`](https://doc.rust-lang.org/std/net/struct.TcpStream.html) and [`UnixStream`](https://doc.rust-lang.org/std/os/unix/net/struct.UnixStream.html).
91    -   Implement [`std::error::Error`](https://doc.rust-lang.org/std/error/trait.Error.html) for `gdbstub::Error`.
92    -   Add a `TargetError::Io` variant to simplify `std::io::Error` handling from Target methods.
93
94## Examples
95
96### Real-World Examples
97
98-   Virtual Machine Monitors (VMMs)
99    -   [crosvm](https://chromium.googlesource.com/chromiumos/platform/crosvm/+/refs/heads/main#gdb-support) - The Chrome OS Virtual Machine Monitor
100    -   [Firecracker](https://firecracker-microvm.github.io/) - A lightweight VMM developed by AWS - feature is in [PR](https://github.com/firecracker-microvm/firecracker/pull/2168)
101-   Emulators
102    -   [clicky](https://github.com/daniel5151/clicky/) - An emulator for classic clickwheel iPods (dual-core ARMv4T SoC)
103    -   [rustyboyadvance-ng](https://github.com/michelhe/rustboyadvance-ng/) - Nintendo GameBoy Advance emulator and debugger
104    -   [ts7200](https://github.com/daniel5151/ts7200/) - An emulator for the TS-7200, a somewhat bespoke embedded ARMv4t platform
105    -   [microcorruption-emu](https://github.com/sapir/microcorruption-emu) - msp430 emulator for the microcorruption.com ctf
106-   Other
107    -   [memflow](https://github.com/memflow/memflow) - A physical memory introspection framework (part of `memflow-cli`)
108
109While some of these projects may use older versions of `gdbstub`, they can nonetheless serve as useful examples of what a typical `gdbstub` integration might look like.
110
111If you end up using `gdbstub` in your project, consider opening a PR and add it to this list!
112
113### In-tree "Toy" Examples
114
115These examples are built as part of the CI, and are guaranteed to be kept up to date with the latest version of `gdbstub`'s API.
116
117- `armv4t` - `./examples/armv4t/`
118    - An incredibly simple ARMv4T-based system emulator with `gdbstub` support.
119    - Unlike all other examples, `armv4t` **implements (almost) all available `target::ext` features.**
120- `armv4t_multicore` - `./examples/armv4t_multicore/`
121    - A dual-core variation of the `armv4t` example.
122    - Implements the core of `gdbstub`'s multithread extensions API, but not much else.
123- `example_no_std` - `./example_no_std`
124    - An _extremely_ minimal example of how `gdbstub` can be used in a `#![no_std]` project.
125    - Unlike the `armv4t/armv4t_multicore` examples, this project does _not_ include a working emulator, and stubs-out all `gdbstub` functions.
126    - Tracks `gdbstub`'s approximate binary footprint (via the `check_size.sh` script)
127
128## Using `gdbstub` on bare-metal hardware
129
130Quite a bit of work has gone into making `gdbstub` optimized for `#![no_std]`, which means it should be entirely possible to implement a `Target` which uses low-level trap instructions + context switching to debug bare-metal code.
131
132If you happen to stumble across this crate and end up using it to debug some bare-metal code, please let me know! I'd love to link to your project, and/or create a simplified example based off your code!
133
134## `unsafe` in `gdbstub`
135
136`gdbstub` "core" only has 2 instances of unsafe code:
137
138-   A few trivially safe calls to `NonZeroUsize::new_unchecked()` when defining internal constants.
139-   A call to `str::from_utf8_unchecked()` when working with incoming GDB packets (the underlying `&[u8]` buffer is checked with `is_ascii()` prior to the call).
140
141With the `std` feature enabled, there is one additional instance of `unsafe` code:
142
143-   `gdbstub` includes an implementation of `UnixStream::peek` which uses `libc::recv`. This will be removed once [rust-lang/rust#73761](https://github.com/rust-lang/rust/pull/73761) is merged and stabilized.
144
145## Future Plans + Roadmap to `1.0.0`
146
147Before `gdbstub` can comfortably commit to a stable `1.0.0` API, there are several outstanding features that should be implemented and questions that need to be addressed. Due to `gdbstub`'s heavy reliance on the Rust type system to enforce GDB protocol invariants, it's likely that a certain subset of yet-unimplemented protocol features may require breaking API changes.
148
149Notably, the vast majority of GDB protocol features (e.g: remote filesystem support, tracepoint packets, most query packets, etc...) should _not_ require breaking API changes, and could most likely be implemented using the standard backwards-compatible protocol extension approach.
150
151The following features are most likely to require breaking API changes, and should therefore be implemented prior to `1.0.0`.
152
153-   [ ] Stabilize the `Arch` trait
154    -   [ ] Allow fine-grained control over target features ([\#12](https://github.com/daniel5151/gdbstub/issues/12))
155    -   [ ] Remove `RawRegId` ([\#29](https://github.com/daniel5151/gdbstub/issues/29))
156-   [ ] Implement GDB's various high-level operating modes:
157    -   [x] Single/Multi Thread debugging
158    -   [ ] Multiprocess Debugging
159        -   [ ] Add a third `base::multiprocess` API.
160        -   _Note:_ `gdbstub` already implements multiprocess extensions "under-the-hood", and just hard-codes a fake PID.
161    -   [x] [Extended Mode](https://sourceware.org/gdb/current/onlinedocs/gdb/Connecting.html) (`target extended-remote`)
162    -   [ ] [Non-Stop Mode](https://sourceware.org/gdb/onlinedocs/gdb/Remote-Non_002dStop.html#Remote-Non_002dStop)
163        -   This may require some breaking API changes and/or some internals rework -- more research is needed.
164-   [ ] Have a working example of `gdbstub` running in a "bare-metal" `#![no_std]` environment (e.g: debugging a hobby OS via serial).
165    -   While there's no reason it _wouldn't_ work, it would be good to validate that the API + implementation supports this use-case.
166
167Additionally, while not strict "blockers" to `1.0.0`, it would be good to explore these features as well:
168
169-   [ ] Commit to a MSRV
170-   [ ] Exposing an `async/await` interface
171    -   e.g: the current `check_gdb_interrupt` callback in `Target::resume()` could be modeled as a future.
172    -   Would require some tweaks to the Connection trait.
173-   [ ] Adding [LLDB extension](https://raw.githubusercontent.com/llvm-mirror/lldb/master/docs/lldb-gdb-remote.txt) support
174    -   Skimming through the list, it doesn't seem like these extensions would require breaking API changes -- more research is needed.
175