skip to content

rust-gdb

The gdb wrapper shipped with Rust that loads pretty-printers so Vec, String and enums display as Rust values rather than raw memory structs. Interviewers ask when Rust debugging comes up, since knowing the wrapper exists is the difference between readable and unreadable output.

on this pageshow

explore

questions

6

Why does plain `gdb` show a Rust `Vec<Order>` as raw `buf` and `len` fields, while `rust-gdb` lists its elements?

level: juniorimportance: should knowfreq 34%

answer

  1. the debugger sees structs, not lists
  2. Python scripts beside rustc
  3. lib/rustlib/etc on the search paths
  4. providers matched by std type name

basics

~20 s

To GDB a Vec is just a struct: a buffer holding a heap pointer and capacity, plus a length. rust-gdb starts GDB with the toolchain's Python pretty-printers loadable, and they follow that pointer to print Vec(size=2) and each element.

solid answer

~40 s

GDB prints what the debug info describes, and rustc describes a `Vec<Order>` as a struct: a `buf` whose `inner` holds the heap pointer and capacity, and a `len`. Plain `gdb` prints those fields. `rust-gdb` is the shell script rustup ships beside `rustc`. It starts GDB with the toolchain's `lib/rustlib/etc` directory on GDB's source search path, its auto-load safe path and `PYTHONPATH`, so the `gdb_load_rust_pretty_printers.py` file named in a Linux binary can load. Its providers recognise std types by name: `Vec(size=2)` with `[0]` and `[1]`, a `String` as text, a `HashMap` as entries. Enums such as `Option<Customer>` are decoded by GDB's own Rust support, not by a provider.

code

rust · 21 lines
rust
struct Order {
    id: u32,
    sku: String,
}

struct Customer {
    name: String,
}

fn main() {
    let orders: Vec<Order> = vec![
        Order { id: 1, sku: String::from("A-100") },
        Order { id: 2, sku: String::from("B-200") },
    ];
    let customer: Option<Customer> = Some(Customer { name: String::from("Ada") });
    // break here and print `orders` and `customer`
    let count = orders.len();
    if let Some(c) = &customer {
        println!("{} has {count} orders, first {} {}", c.name, orders[0].id, orders[0].sku);
    }
}

go deeper

for a junior

Know that rust-gdb is a wrapper rustup installs beside rustc, that it makes Vec, String and HashMap readable, and that it needs a debug build and GDB installed.

for a middle

Explain that the wrapper puts the toolchain's lib/rustlib/etc on GDB's paths so the loader the binary names can run, and that GDB itself decodes enums.

for a senior

Diagnose raw output: plain gdb, a GDB without Python, a toolchain mismatch with the binary, or a type no provider matches, such as PathBuf or another crate's collection.

for a principal

Weigh standardising one debugging entry point across a team, such as rust-gdb in scripts and editor launch settings, against developers' own GDB setups that silently lose std's printers.

## What GDB sees in a Rust value GDB knows a program's types only through its **debug information** (DWARF on Linux), which records each type's fields exactly as the compiler laid them out. In that record a `Vec<T>` is not a list. It is a struct. In Rust 1.99 its fields are `buf`, a raw-vector struct whose `inner` holds the heap pointer and the capacity, and `len`. A `String` wraps a `Vec<u8>` in a field named `vec`. A `&str` is a fat pointer with two fields, `data_ptr` and `length`. Without help GDB prints those fields faithfully. You get an address and a count, not the two orders you are chasing in a Linux service that is misbehaving. ## What rust-gdb adds `rust-gdb` is a short POSIX shell script that rustup installs in each toolchain's `bin` directory, next to `rustc`. It does not patch or replace GDB. Before it runs `gdb` (or the command in `RUST_GDB`), it: 1. asks `rustc --print=sysroot` where the toolchain lives; 2. puts that toolchain's `lib/rustlib/etc` directory on GDB's source search path (`--directory`) and on GDB's auto-load safe path, and appends it to `PYTHONPATH`; 3. maps the source paths std was compiled under (`/rustc/<commit-hash>`) to the installed rust-src copy with `set substitute-path`. The etc directory holds four Python files for GDB: `gdb_load_rust_pretty_printers.py`, `gdb_lookup.py`, `gdb_providers.py` and `rust_types.py`. A Linux binary built with debug info carries a `.debug_gdb_scripts` section whose entry names `gdb_load_rust_pretty_printers.py`. GDB searches for that file in the current directory and then along the source search path. Step 2 is what makes the search succeed and what makes GDB willing to run the file. The loader then registers one **pretty-printer** that classifies each value by its type name and hands std types to a **provider** class. ## What the providers print | Std type | What the provider shows | |---|---| | `Vec<T>`, `VecDeque<T>` | `Vec(size=N)` or `VecDeque(size=N)`, then each element | | `String`, `&str`, `OsString`, `Box<str>` | the text itself | | `HashMap`, `HashSet`, `BTreeMap`, `BTreeSet` | `HashMap(size=N)` and so on, then the entries | | `Rc`, `Arc` | `Rc(strong=N, weak=M)` or the `Arc` form, then the value | | `Cell`, `RefCell`, `Ref`, `RefMut` | the value; `RefCell` adds its borrow count | | `NonZero<T>` | the inner number | The `Vec` provider reads `len`, follows the pointer in `buf.inner.ptr`, casts it to a pointer to the element type and yields `[0]`, `[1]` and so on. That is the whole trick: the scripts know std's private layout, so you do not have to walk it by hand. The summaries carry information you would otherwise dig for. An `Rc` shows its strong and weak counts, which helps when a value refuses to drop. A `RefCell` shows `RefCell(borrow=N)` while shared borrows are live and `RefCell(borrow_mut=N)` while it is mutably borrowed. Seeing that at the breakpoint before a `BorrowMutError` panic tells you which borrow is still alive. ## What GDB prints on its own Not every value needs a provider. GDB has built-in **Rust language support**: - It prints structs field by field, so your own `Order` shows `id`, `sku` and `qty`. Only the `String` inside benefits from a provider. - It decodes **enums** from the debug info, so `Option<Customer>` shows its variant even under plain `gdb`. The loader registers an enum provider only when GDB is older than 7.12. - Types that no provider matches stay as raw structs. `PathBuf` is one: `rust_types.py` defines a pattern for it, but the GDB lookup never registers a provider. A collection from another crate is another, because the patterns only match std's own paths. ## Practical habits - Start the service with `rust-gdb ./target/debug/service`. Arguments after the wrapper's own flags pass straight through to GDB. - GDB must be installed separately. The wrapper only finds the scripts and runs `gdb`. - Raw fields mean the printers did not load, not that debug info is missing. A binary with no debug info shows no locals at all, raw or pretty. - If you have to start plain `gdb`, `source` the loader file from the toolchain's etc directory. Its own comment notes that sourcing it after GDB has started works, because it falls back to registering on the program space. - The printers come from the toolchain the wrapper runs, so use the same toolchain that built the binary. Std's internal layout changes between releases, and the providers carry compatibility branches only for layouts they already know.

  • Can you get the same output from plain `gdb` without the wrapper?
    Yes. `source` the toolchain's `lib/rustlib/etc/gdb_load_rust_pretty_printers.py` once GDB has started. The loader appends its own directory to Python's `sys.path` and registers the printers on the current object file, or on the program space when there is none. What you lose is the rest of the wrapper's setup: the auto-load path and the mapping of std's `/rustc/<hash>` source paths to rust-src.
  • Why does `Option<Customer>` print correctly even when `Vec<Order>` does not?
    Enums are decoded by GDB's built-in Rust support, which reads the variants straight from the debug info. The Rust scripts add an enum provider only for GDB older than 7.12. A `Vec` has no such built-in knowledge, because its elements sit behind a raw pointer that only a std-aware provider knows how to follow.

A Vec without printers is like a warehouse receipt: an aisle address, the shelf size and an item count. rust-gdb hands GDB the clerk who walks to that aisle and reads the items out.

  • rust-gdb is a separate debugger written in Rust that replaces GDB
  • The pretty-printers are compiled into every Rust binary, so plain gdb should show them
  • Raw buf and len fields mean the binary was built without debug info
  • Option needs its own pretty-printer, so a missing printer also hides enum variants
  • Plain gdb cannot debug Rust binaries at all
open as a page

Under rust-gdb, a Linux service built with `cargo build --release` shows no locals or source lines; why, and what must the binary carry?

level: middleimportance: should knowfreq 30%

basics

~20 s

Cargo's release profile emits no debug info by default, so GDB has only symbols. Full debug info (rustc's -C debuginfo=2, Cargo's debug = true) is what shows variables and feeds the printers; line-tables-only gives file and line, no locals.

open as a page

Under rust-gdb, how do you stop a Rust service at the moment it panics and find the line that caused the panic?

level: middleimportance: should knowfreq 28%

basics

~20 s

Break on std's rust_panic, the function std's source marks for panic breakpoints, then run bt and select the first frame in your crate. The hook has already printed the message by then; core::panicking::panic_fmt stops earlier for formatted panics.

open as a page

How does `#![debugger_visualizer(gdb_script_file = "...")]` let a Rust crate ship GDB pretty-printers for its own types, and why might they not load?

level: seniorimportance: nice to knowfreq 9%

basics

~20 s

Since Rust 1.71, the attribute embeds a Python pretty-printer script into a Linux binary's .debug_gdb_scripts section at compile time. GDB runs embedded scripts only when the binary's path is in its auto-load safe path, which rust-gdb does not add.

open as a page

Under rust-gdb, why can `print` show `customer` or read `order.qty`, yet reject a `match` expression or a generic call like `largest(&orders)`?

level: seniorimportance: nice to knowfreq 16%

basics

~20 s

GDB parses Rust syntax itself and evaluates paths, fields, literals and calls to compiled functions. Its manual lists no if or match, closures or tuples, and no inference for generics, so a generic call needs explicit parameters such as largest::<u32>.

open as a page

When `rust-gdb` still prints a Rust `Vec<Order>` as raw fields and std frames without source, which steps of its setup do you check?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

Check each link: the toolchain whose sysroot the script asks rustc for, the lib/rustlib/etc directory it adds to GDB's source and auto-load safe paths, the binary's .debug_gdb_scripts entry naming the loader, the providers' type-name patterns and std's /rustc/<hash> mapping to rust-src.

open as a page