1 //! An ergonomic and easy-to-integrate implementation of the 2 //! [GDB Remote Serial Protocol](https://sourceware.org/gdb/onlinedocs/gdb/Remote-Protocol.html#Remote-Protocol) 3 //! in Rust, with full `#![no_std]` support. 4 //! 5 //! ## Feature flags 6 //! 7 //! By default, both the `std` and `alloc` features are enabled. 8 //! 9 //! When using `gdbstub` in `#![no_std]` contexts, make sure to set 10 //! `default-features = false`. 11 //! 12 //! - `alloc` 13 //! - Implement `Connection` for `Box<dyn Connection>`. 14 //! - Log outgoing packets via `log::trace!` (uses a heap-allocated output 15 //! buffer). 16 //! - Provide built-in implementations for certain protocol features: 17 //! - Use a heap-allocated packet buffer in `GdbStub` (if none is 18 //! provided via `GdbStubBuilder::with_packet_buffer`). 19 //! - (Monitor Command) Use a heap-allocated output buffer in 20 //! `ConsoleOutput`. 21 //! - `std` (implies `alloc`) 22 //! - Implement `Connection` for [`TcpStream`](std::net::TcpStream) and 23 //! [`UnixStream`](std::os::unix::net::UnixStream). 24 //! - Implement [`std::error::Error`] for `gdbstub::Error`. 25 //! - Add a `TargetError::Io` variant to simplify `std::io::Error` handling 26 //! from Target methods. 27 //! - `paranoid_unsafe` 28 //! - Please refer to the [`unsafe` in `gdbstub`](https://github.com/daniel5151/gdbstub#unsafe-in-gdbstub) 29 //! section of the README.md for more details. 30 //! 31 //! ## Getting Started 32 //! 33 //! This section provides a brief overview of the key traits and types used in 34 //! `gdbstub`, and walks though the basic steps required to integrate `gdbstub` 35 //! into a project. 36 //! 37 //! At a high level, there are only three things that are required to get up and 38 //! running with `gdbstub`: a [`Connection`](#the-connection-trait), a 39 //! [`Target`](#the-target-trait), and a [event loop](#the-event-loop). 40 //! 41 //! > _Note:_ I _highly recommended_ referencing some of the 42 //! [examples](https://github.com/daniel5151/gdbstub#examples) listed in the 43 //! project README when integrating `gdbstub` into a project for the first time. 44 //! 45 //! > In particular, the in-tree 46 //! [`armv4t`](https://github.com/daniel5151/gdbstub/tree/master/examples/armv4t) 47 //! example contains basic implementations off almost all protocol extensions, 48 //! making it an incredibly valuable reference when implementing protocol 49 //! extensions. 50 //! 51 //! ### The `Connection` Trait 52 //! 53 //! First things first: `gdbstub` needs some way to communicate with a GDB 54 //! client. To facilitate this communication, `gdbstub` uses a custom 55 //! [`Connection`](conn::Connection) trait. 56 //! 57 //! `Connection` is automatically implemented for common `std` types such as 58 //! [`TcpStream`](std::net::TcpStream) and 59 //! [`UnixStream`](std::os::unix::net::UnixStream). 60 //! 61 //! If you're using `gdbstub` in a `#![no_std]` environment, `Connection` will 62 //! most likely need to be manually implemented on top of whatever in-order, 63 //! serial, byte-wise I/O your particular platform has available (e.g: 64 //! putchar/getchar over UART, using an embedded TCP stack, etc.). 65 //! 66 //! One common way to start a remote debugging session is to simply wait for a 67 //! GDB client to connect via TCP: 68 //! 69 //! ```rust 70 //! use std::io; 71 //! use std::net::{TcpListener, TcpStream}; 72 //! 73 //! fn wait_for_gdb_connection(port: u16) -> io::Result<TcpStream> { 74 //! let sockaddr = format!("localhost:{}", port); 75 //! eprintln!("Waiting for a GDB connection on {:?}...", sockaddr); 76 //! let sock = TcpListener::bind(sockaddr)?; 77 //! let (stream, addr) = sock.accept()?; 78 //! 79 //! // Blocks until a GDB client connects via TCP. 80 //! // i.e: Running `target remote localhost:<port>` from the GDB prompt. 81 //! 82 //! eprintln!("Debugger connected from {}", addr); 83 //! Ok(stream) // `TcpStream` implements `gdbstub::Connection` 84 //! } 85 //! ``` 86 //! 87 //! ### The `Target` Trait 88 //! 89 //! The [`Target`](target::Target) trait describes how to control and modify 90 //! a system's execution state during a GDB debugging session, and serves as the 91 //! primary bridge between `gdbstub`'s generic GDB protocol implementation and a 92 //! specific target's project/platform-specific code. 93 //! 94 //! At a high level, the `Target` trait is a collection of user-defined handler 95 //! methods that the GDB client can invoke via the GDB remote serial protocol. 96 //! For example, the `Target` trait includes methods to read/write 97 //! registers/memory, start/stop execution, etc... 98 //! 99 //! **`Target` is the most important trait in `gdbstub`, and must be implemented 100 //! by anyone integrating `gdbstub` into their project!** 101 //! 102 //! Please refer to the [`target` module documentation](target) for in-depth 103 //! instructions on how to implement [`Target`](target::Target) for a particular 104 //! platform. 105 //! 106 //! ## The Event Loop 107 //! 108 //! Once a [`Connection`](#the-connection-trait) has been established and the 109 //! [`Target`](#the-target-trait) has been initialized, all that's left is to 110 //! wire things up and decide what kind of event loop will be used to drive the 111 //! debugging session! 112 //! 113 //! First things first, let's get an instance of `GdbStub` ready to run: 114 //! 115 //! ```rust,ignore 116 //! // Set-up a valid `Target` 117 //! let mut target = MyTarget::new()?; // implements `Target` 118 //! 119 //! // Establish a `Connection` 120 //! let connection: TcpStream = wait_for_gdb_connection(9001); 121 //! 122 //! // Create a new `gdbstub::GdbStub` using the established `Connection`. 123 //! let mut debugger = gdbstub::GdbStub::new(connection); 124 //! ``` 125 //! 126 //! Cool, but how do you actually start the debugging session? 127 // use an explicit doc attribute to avoid automatic rustfmt wrapping 128 #![doc = "### `GdbStub::run_blocking`: The quick and easy way to get up and running with `gdbstub`"] 129 //! 130 //! If you've got an extra thread to spare, the quickest way to get up and 131 //! running with `gdbstub` is by using the 132 //! [`GdbStub::run_blocking`](stub::run_blocking) API alongside the 133 //! [`BlockingEventLoop`] trait. 134 //! 135 //! If you are on a more resource constrained platform, and/or don't wish to 136 //! dedicate an entire thread to `gdbstub`, feel free to skip ahead to the 137 //! [following 138 //! section](#gdbstubstatemachine-driving-gdbstub-in-an-async-event-loop--via-interrupt-handlers). 139 //! 140 //! A basic integration of `gdbstub` into a project using the 141 //! `GdbStub::run_blocking` API might look something like this: 142 //! 143 //! ```rust 144 //! # use gdbstub::target::ext::base::BaseOps; 145 //! # 146 //! # struct MyTarget; 147 //! # 148 //! # impl Target for MyTarget { 149 //! # type Error = &'static str; 150 //! # type Arch = gdbstub_arch::arm::Armv4t; // as an example 151 //! # fn base_ops(&mut self) -> BaseOps<Self::Arch, Self::Error> { todo!() } 152 //! # } 153 //! # 154 //! # impl MyTarget { 155 //! # fn run_and_check_for_incoming_data( 156 //! # &mut self, 157 //! # conn: &mut impl Connection 158 //! # ) -> MyTargetEvent { todo!() } 159 //! # 160 //! # fn stop_in_response_to_ctrl_c_interrupt( 161 //! # &mut self 162 //! # ) -> Result<(), &'static str> { todo!() } 163 //! # } 164 //! # 165 //! # enum MyTargetEvent { 166 //! # IncomingData, 167 //! # StopReason(SingleThreadStopReason<u32>), 168 //! # } 169 //! # 170 //! use gdbstub::common::Signal; 171 //! use gdbstub::conn::{Connection, ConnectionExt}; // note the use of `ConnectionExt` 172 //! use gdbstub::stub::{run_blocking, DisconnectReason, GdbStub, GdbStubError}; 173 //! use gdbstub::stub::SingleThreadStopReason; 174 //! use gdbstub::target::Target; 175 //! 176 //! enum MyGdbBlockingEventLoop {} 177 //! 178 //! // The `run_blocking::BlockingEventLoop` groups together various callbacks 179 //! // the `GdbStub::run_blocking` event loop requires you to implement. 180 //! impl run_blocking::BlockingEventLoop for MyGdbBlockingEventLoop { 181 //! type Target = MyTarget; 182 //! type Connection = Box<dyn ConnectionExt<Error = std::io::Error>>; 183 //! 184 //! // or MultiThreadStopReason on multi threaded targets 185 //! type StopReason = SingleThreadStopReason<u32>; 186 //! 187 //! // Invoked immediately after the target's `resume` method has been 188 //! // called. The implementation should block until either the target 189 //! // reports a stop reason, or if new data was sent over the connection. 190 //! fn wait_for_stop_reason( 191 //! target: &mut MyTarget, 192 //! conn: &mut Self::Connection, 193 //! ) -> Result< 194 //! run_blocking::Event<SingleThreadStopReason<u32>>, 195 //! run_blocking::WaitForStopReasonError< 196 //! <Self::Target as Target>::Error, 197 //! <Self::Connection as Connection>::Error, 198 //! >, 199 //! > { 200 //! // the specific mechanism to "select" between incoming data and target 201 //! // events will depend on your project's architecture. 202 //! // 203 //! // some examples of how you might implement this method include: `epoll`, 204 //! // `select!` across multiple event channels, periodic polling, etc... 205 //! // 206 //! // in this example, lets assume the target has a magic method that handles 207 //! // this for us. 208 //! let event = match target.run_and_check_for_incoming_data(conn) { 209 //! MyTargetEvent::IncomingData => { 210 //! let byte = conn 211 //! .read() // method provided by the `ConnectionExt` trait 212 //! .map_err(run_blocking::WaitForStopReasonError::Connection)?; 213 //! 214 //! run_blocking::Event::IncomingData(byte) 215 //! } 216 //! MyTargetEvent::StopReason(reason) => { 217 //! run_blocking::Event::TargetStopped(reason) 218 //! } 219 //! }; 220 //! 221 //! Ok(event) 222 //! } 223 //! 224 //! // Invoked when the GDB client sends a Ctrl-C interrupt. 225 //! fn on_interrupt( 226 //! target: &mut MyTarget, 227 //! ) -> Result<Option<SingleThreadStopReason<u32>>, <MyTarget as Target>::Error> { 228 //! // notify the target that a ctrl-c interrupt has occurred. 229 //! target.stop_in_response_to_ctrl_c_interrupt()?; 230 //! 231 //! // a pretty typical stop reason in response to a Ctrl-C interrupt is to 232 //! // report a "Signal::SIGINT". 233 //! Ok(Some(SingleThreadStopReason::Signal(Signal::SIGINT).into())) 234 //! } 235 //! } 236 //! 237 //! fn gdb_event_loop_thread( 238 //! debugger: GdbStub<MyTarget, Box<dyn ConnectionExt<Error = std::io::Error>>>, 239 //! mut target: MyTarget 240 //! ) { 241 //! match debugger.run_blocking::<MyGdbBlockingEventLoop>(&mut target) { 242 //! Ok(disconnect_reason) => match disconnect_reason { 243 //! DisconnectReason::Disconnect => { 244 //! println!("Client disconnected") 245 //! } 246 //! DisconnectReason::TargetExited(code) => { 247 //! println!("Target exited with code {}", code) 248 //! } 249 //! DisconnectReason::TargetTerminated(sig) => { 250 //! println!("Target terminated with signal {}", sig) 251 //! } 252 //! DisconnectReason::Kill => println!("GDB sent a kill command"), 253 //! }, 254 //! Err(GdbStubError::TargetError(e)) => { 255 //! println!("target encountered a fatal error: {}", e) 256 //! } 257 //! Err(e) => { 258 //! println!("gdbstub encountered a fatal error: {}", e) 259 //! } 260 //! } 261 //! } 262 //! ``` 263 // use an explicit doc attribute to avoid automatic rustfmt wrapping 264 #![doc = "### `GdbStubStateMachine`: Driving `gdbstub` in an async event loop / via interrupt handlers"] 265 //! 266 //! `GdbStub::run_blocking` requires that the target implement the 267 //! [`BlockingEventLoop`] trait, which as the name implies, uses _blocking_ IO 268 //! when handling certain events. Blocking the thread is a totally reasonable 269 //! approach in most implementations, as one can simply spin up a separate 270 //! thread to run the GDB stub (or in certain emulator implementations, run the 271 //! emulator as part of the `wait_for_stop_reason` method). 272 //! 273 //! Unfortunately, this blocking behavior can be a non-starter when integrating 274 //! `gdbstub` in projects that don't support / wish to avoid the traditional 275 //! thread-based execution model, such as projects using `async/await`, or 276 //! bare-metal `no_std` projects running on embedded hardware. 277 //! 278 //! In these cases, `gdbstub` provides access to the underlying 279 //! [`GdbStubStateMachine`] API, which gives implementations full control over 280 //! the GDB stub's "event loop". This API requires implementations to "push" 281 //! data to the `gdbstub` implementation whenever new data becomes available 282 //! (e.g: when a UART interrupt handler receives a byte, when the target hits a 283 //! breakpoint, etc...), as opposed to the `GdbStub::run_blocking` API, which 284 //! "pulls" these events in a blocking manner. 285 //! 286 //! See the [`GdbStubStateMachine`] docs for more details on how to use this 287 //! API. 288 //! 289 //! <br> 290 //! 291 //! * * * 292 //! 293 //! <br> 294 //! 295 //! And with that lengthy introduction, I wish you the best of luck in your 296 //! debugging adventures! 297 //! 298 //! If you have any suggestions, feature requests, or run into any problems, 299 //! please start a discussion / open an issue over on the 300 //! [`gdbstub` GitHub repo](https://github.com/daniel5151/gdbstub/). 301 //! 302 //! [`GdbStubStateMachine`]: stub::state_machine::GdbStubStateMachine 303 //! [`BlockingEventLoop`]: stub::run_blocking::BlockingEventLoop 304 305 #![cfg_attr(not(feature = "std"), no_std)] 306 #![cfg_attr(feature = "paranoid_unsafe", forbid(unsafe_code))] 307 308 #[cfg(feature = "alloc")] 309 extern crate alloc; 310 311 #[macro_use] 312 extern crate log; 313 314 mod protocol; 315 mod util; 316 317 #[doc(hidden)] 318 pub mod internal; 319 320 pub mod arch; 321 pub mod common; 322 pub mod conn; 323 pub mod stub; 324 pub mod target; 325 326 // https://users.rust-lang.org/t/compile-time-const-unwrapping/51619/7 327 // 328 // This works from Rust 1.46.0 onwards, which stabilized branching and looping 329 // in const contexts. 330 macro_rules! unwrap { 331 ($e:expr $(,)*) => { 332 match $e { 333 ::core::option::Option::Some(x) => x, 334 ::core::option::Option::None => { 335 ["tried to unwrap a None"][99]; 336 loop {} 337 } 338 } 339 }; 340 } 341 342 /// (Internal) The fake Tid that's used when running in single-threaded mode. 343 const SINGLE_THREAD_TID: common::Tid = unwrap!(common::Tid::new(1)); 344 /// (Internal) The fake Pid reported to GDB when running in multi-threaded mode. 345 const FAKE_PID: common::Pid = unwrap!(common::Pid::new(1)); 346 347 pub(crate) mod is_valid_tid { 348 pub trait IsValidTid {} 349 350 impl IsValidTid for () {} 351 impl IsValidTid for crate::common::Tid {} 352 } 353