v5gdb User Manual
Welcome to the v5gdb user manual! This guide will help you set up a debugger for your VEX V5 project.
Supported frameworks
Currently, v5gdb supports vexide (Rust) and PROS (C++) programs. The VEXcode framework is not supported at this time.
Getting Started
If you use the vexide framework (Rust), please read our installation and setup guide for Rust projects.
If you use the PROS framework (C++), please read our installation and setup guide for C++ (PROS) projects.
If you haven’t used a debugger before, follow Your first debugging session (C++) next. And once you’ve set up v5gdb in your project, you can optionally configure it to connect with VS Code.
If something isn’t working, see Troubleshooting.
Here are some common commands you may find helpful when using GDB in the terminal:
layout srcwill show you what code is currently running. After running the above command,focus cmdwill let you use the up and down arrow keys to quickly select a previous command.break opcontrolwill set a breakpoint on a function namedopcontrol, andbreak main.cpp:15will put a breakpoint on line 15 ofmain.cpp.deleteremoves all breakpoints.stepwill step execution forward by a single line of code.nextwill step execution forward by a single line of code, and “jump over” function calls.monitor helpwill show the special commands specific to the V5 debugger.contwill exit the debug console and continue execution as normal. The debug console session will resume if a breakpoint is hit.quitwill quit the debugger.info localswill show you the values of all the variables in the current function.info argswill show you the values of all the parameters passed to the current function.info frametells you what function is currently running and what file/line number you’re on.backtracetells you what function called the current function, and what function called that one, and so on.printcan be used to print out certain variables or call functions, like this:- Print a variable or expression:
print kp * error - Call a function (C++):
print calculate_number(30, 100, 4) - Call a function (Rust):
print my_crate::calculate_number(30, 100, 4)
- Print a variable or expression:
finishwill skip to the end of the current function.
Advanced topics
Reading these wiki pages is optional, and most users won’t need them.
- Command-line interface: all
v5gdbcommand-line flags and options. - Transports: how v5gdb talks to your computer, and how to use a different connection than USB.
Support
If you have questions about v5gdb, please don’t hesitate to let us know in our Discord server. We are happy to help with any issues!
Installation and setup (Rust)
This chapter discusses how to add v5gdb to your existing Rust project, assuming you use the vexide runtime.
Important
v5gdb is compatible with vexide v0.9.0-alpha.1 or later.
Project setup
Start by adding v5gdb to your project.
cargo add v5gdb
To enable debugging support, add the following line somewhere in your program, preferably near the beginning.
use v5gdb::prelude::*;
#[vexide::main]
async fn main(peripherals: Peripherals) {
v5gdb::install(V5Debugger::stdio());
// ...rest...
}
If you’ve enabled Link Time Optimization for the build profile you plan to debug in, you will need to disable it. v5gdb does not support debugging programs that have LTO enabled.
Debugger setup
Please install GDB using one of the following commands:
| Platform | Command |
|---|---|
| macOS | brew install gdb |
| Ubuntu | apt install gdb-multiarch |
| Fedora | dnf install gdb |
| Windows, via msys2 | pacman -S mingw-w64-ucrt-x86_64-gdb |
| Any OS (macOS/Linux/Windows) | Install the PROS Toolchain in VS Code |
| (Other) | Let us know what works for you |
You will also need to install the v5gdb command on your computer using one of the commands below. This is a support program that helps GDB running on your computer connect to your VEX V5 brain.
Shell script (macOS/Linux)
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/vexide/v5gdb/releases/download/v0.1.0-beta.2/v5gdb-cli-installer.sh | sh
PowerShell script (Windows)
powershell -ExecutionPolicy Bypass -c "irm https://github.com/vexide/v5gdb/releases/download/v0.1.0-beta.2/v5gdb-cli-installer.ps1 | iex"
Other
- Cargo:
cargo install [email protected] - Cargo Binstall:
cargo binstall [email protected] - View the Releases page for detailed install instructions and manual downloads.
Usage
Upload your program, then start it. Avoid using --release when debugging.
cargo v5 upload
At this point, you can now view the debug console by running the v5gdb command in your terminal.
You will need to specify the path name of the executable ELF file you are running on the V5. Generally, this path is of the form:
./target/armv7a-vex-v5/debug/[PROGRAM_NAME]
$ v5gdb ./target/armv7a-vex-v5/debug/my_program
GNU gdb (GDB) 16.3
Copyright (C) 2024 Free Software Foundation, Inc.
Reading symbols from ./target/armv7a-vex-v5/debug/my_program...
Remote debugging using :35537
0x0380b240 in basic::main::main::{async_fn#0} () at examples/basic.rs:26
26 v5gdb::breakpoint!();
(gdb)
Tip
Make sure to quit other commands like
pros,cargo v5, orvexcombefore startingv5gdb.
Considerations
If you try to debug a program that was built with the “release” profile, you might find it act more unpredictably because of the optimizations made by the compiler. Additionally, if you have LTO enabled, you may find that v5gdb has trouble hooking into certain events like program exits and prints. To avoid these issues, we recommend debugging programs built in the “dev” profile without optimizations turned on.
If your uploads are taking too long or failing intermittently, consider enabling optimizations for your dependencies to reduce the size of your executable:
[profile.dev.package."*"]
opt-level = "z"
Installation and setup (C++)
This chapter discusses how to add v5gdb to a C++ project using PROS.
Important
v5gdb is compatible with PROS v4.2.3 or later.
(At the time of writing, this is a very recent release, so actually check that you are using it!)
To check, run
pros c info-projectin your project folder and look for the version ofkernel. If it is older than 4.2.3, runpros c upgradeto update it.
Installing v5gdb
v5gdb has two parts: a library that runs on the brain as part of your program, and a v5gdb command that runs on your computer.
The library
Open the PROS Integrated Terminal (or any terminal in your project folder) and run these commands:
pros c add-depot v5gdb https://raw.githubusercontent.com/vexide/v5gdb/depot/preview.json
pros c apply v5gdb
The first command tells PROS where to download v5gdb from. You only need to run it once per computer. The second command adds the v5gdb library to the current project, so run it once in each project you want to debug.
The v5gdb command
Next, install the v5gdb command on your computer using one of the commands below. This is a support program that helps GDB running on your computer connect to your VEX V5 brain.
Shell script (macOS/Linux)
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/vexide/v5gdb/releases/download/v0.1.0-beta.2/v5gdb-cli-installer.sh | sh
PowerShell script (Windows)
powershell -ExecutionPolicy Bypass -c "irm https://github.com/vexide/v5gdb/releases/download/v0.1.0-beta.2/v5gdb-cli-installer.ps1 | iex"
Other installation methods
- Cargo:
cargo install [email protected] - Cargo Binstall:
cargo binstall [email protected] - View the Releases page for detailed install instructions and manual downloads.
After installing, close and reopen your terminal (or restart VS Code) so it can find the new command. Then check that it works:
v5gdb --help
If you installed PROS through the VS Code extension, you already have GDB and don’t need to install it separately.
Project setup
To enable debugging support, add the following line to your initialize function, preferably near the beginning.
#include "v5gdb/v5gdb.h"
void initialize() {
v5gdb::install({.stop_motors_on_break = true});
// ...rest...
}
stop_motors_on_break makes every motor stop whenever your program pauses in the debugger. Without it, motors keep running at whatever speed they were last set to while you look around. You can also toggle this while debugging with monitor autostop true or monitor autostop false.
Debugger setup
Build and upload your program, then start it:
pros mu
At this point, you can now view the debug console by running the v5gdb command in the PROS Integrated Terminal.
$ v5gdb
GNU gdb (GDB) 16.3
Copyright (C) 2024 Free Software Foundation, Inc.
Reading symbols from ./bin/hot.package.elf...
add symbol table from file "./bin/cold.package.elf"
Reading symbols from ./bin/cold.package.elf...
Remote debugging using :35537
initialize () at src/main.cpp:19
19 printf("Hello world\n");
(gdb)
You may now use GDB to debug your program: for instance, type continue to resume execution, or press Ctrl-C to pause the program.
Tip
Make sure to quit other commands like
pros,cargo v5, orvexcombefore startingv5gdb. Only one program can use the brain’s USB connection at a time.
Considerations
PROS compiles your program with optimizations turned on. This makes the debugger a little less predictable: some variables may show as <optimized out>, and stepping line by line may jump around or skip lines. This is normal. If it gets in the way, set a breakpoint on a later line instead of stepping, or print the value you care about at a point where it’s still in use.
Next steps
- New to debuggers? Follow Your first debugging session (C++).
- Prefer clicking to typing commands? Set up Debugging in VS Code.
- Something not working? See Troubleshooting.
Your first debugging session (C++)
This page walks through a short debugging session with a PROS program. It assumes you’ve finished Installation and setup (C++).
What a debugger does
A debugger lets you pause your program while it runs on the brain, look at the values of your variables, and then unpause it or run one line at a time. Instead of adding printf calls and re-uploading, you can pause at the line you care about and inspect everything.
Some common terms used with debuggers include:
- Breakpoint: a line or function where the debugger pauses the program.
- Step: run one line of code, then pause again.
- Continue: unpause the program, letting it run normally until it reaches the next breakpoint.
Example program
Suppose src/main.cpp has this driver control loop:
#include "main.h"
#include "v5gdb/v5gdb.h"
pros::Controller ctrl(pros::E_CONTROLLER_MASTER);
pros::MotorGroup left_mg({1, 2});
pros::MotorGroup right_mg({-3, -4});
void initialize() {
v5gdb::install({.stop_motors_on_break = true});
}
void opcontrol() {
while (true) {
int forward = ctrl.get_analog(ANALOG_LEFT_Y);
int turn = ctrl.get_analog(ANALOG_RIGHT_X);
int left = forward + turn;
int right = forward - turn;
left_mg.move(left);
right_mg.move(right);
pros::delay(20);
}
}
Upload it with pros mu, start it, then run v5gdb. The program will pause as soon as GDB connects, and you will see a (gdb) prompt.
1. Set a breakpoint
Tell GDB to pause on the line that computes left:
(gdb) break src/main.cpp:18
Breakpoint 1 at 0x...: file src/main.cpp, line 16.
You can also put a breakpoint on a whole function, e.g. break opcontrol.
2. Continue until the breakpoint
(gdb) continue
Continuing.
Thread 5 hit Breakpoint 1, opcontrol () at src/main.cpp:16
16 int left = forward + turn;
The program is now paused just before line 16 runs. Because of stop_motors_on_break, the drivetrain has stopped too.
3. Look at variables
You can view the values of each variable you have by running info locals, or do calculations with them by running print.
(gdb) info locals
forward = 127
turn = -40
left = <optimized out>
right = <optimized out>
(gdb) print forward + turn
$1 = 87
left and right haven’t been set yet because line 16 hasn’t run, so they might show as <optimized out> for you. This means the compiler didn’t keep track of them at this point. See Considerations for more information about that.
4. Step through the code
(gdb) next
17 int right = forward - turn;
(gdb) print left
$2 = 87
next runs one line of code. If the line calls a function, next runs the entire function. Use step instead to go inside the function, and finish to run until the current function returns.
To see how you got here, use backtrace, which lists the function that called this one, the function that called that one, and so on.
5. Test a competition mode
You can use v5gdb to test autonomous code without a field controller or competition switch:
(gdb) monitor comp auton
(gdb) continue
Use monitor comp real to go back to the real competition state. See Monitor Commands for more robot commands, such as monitor devices and monitor battery.
6. Finish up
- Pressing Ctrl-C pauses the program wherever it is, even inside long loops. This is very helpful if you forgot to set a breakpoint or if your code has gotten stuck!
deleteremoves all breakpoints.quitexits the debugger.
More commands
The Home page has a “cheat sheet” of commonly used GDB commands.
Debugging in VS Code
This chapter will provide an example configuration for debugging PROS programs from VS Code.
Start by installing the Microsoft C/C++ extension. Then add the following to .vscode/tasks.json in your project folder. Create the .vscode folder and that file if they don’t exist yet. If you already have a tasks.json, add the new task to it instead of replacing the file.
{
"version": "2.0.0",
"tasks": [
{
"label": "v5gdb server",
"type": "process",
"command": "v5gdb",
"args": ["--tcp=127.0.0.1:3333"],
"isBackground": true,
"presentation": {
"panel": "dedicated",
"clear": false
},
"problemMatcher": {
"owner": "v5gdb",
"pattern": { "regexp": "^\\b$" },
"background": {
"activeOnStart": true,
"beginsPattern": "^",
"endsPattern": "Listening on "
}
}
}
]
}
Create the following launch configuration in .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Attach to V5 (v5gdb)",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/bin/hot.package.elf",
"cwd": "${workspaceFolder}",
"MIMode": "gdb",
"miDebuggerServerAddress": "127.0.0.1:3333",
"stopAtConnect": true,
"preLaunchTask": "v5gdb server",
"setupCommands": [
{ "text": "-enable-pretty-printing", "ignoreFailures": true },
{ "text": "mem 0x100000 0x2c00000 ro cache" },
{ "text": "mem 0x2c00000 0x8000000 rw cache" },
{ "text": "set dcache line-size 1024" },
{ "text": "add-symbol-file ${workspaceFolder}/bin/cold.package.elf", "ignoreFailures": true }
]
}
]
}
The mem and set dcache commands make reading memory faster. See TCP Server mode for details.
Start the program as normal, then press F5 to start debugging it.
Troubleshooting
This page lists common problems and how to fix them. If yours isn’t here, ask in our Discord server.
v5gdb is not recognized / command not found
Your terminal can’t find the v5gdb command.
- Close and reopen the terminal, or restart VS Code. The installer should add
v5gdbto your shell PATH, but terminals that were already open might not see v5gdb until they’re re-opened. - Run
v5gdb --helpto check that it’s now working. If it still isn’t found, run the installer again and read its output for errors.
“No V5 device is connected”
v5gdb can’t communicate with your V5 brain. It might be turned off or unplugged.
- Check that the brain is on and plugged into your computer with a USB cable. A controller connected to the brain over USB may also work, but is not recommended.
- Try a different cable or USB port. Some cables are only for power.
“Address already in use”
A different program is using your V5 brain and preventing v5gdb from connecting to it.
- Close anything else that might be using the brain’s USB connection, such as another terminal running
pros terminal,cargo v5, orvexcom. Only one program can use the V5 at a time.
“Device disconnected” or “Device not configured”
The USB cable was disconnected during the session, or the V5 brain turned off. Reconnect the cable, then run v5gdb again. If the brain was turned off or the program was stopped, start the program again first.
v5gdb can’t find a debugger
v5gdb needs GDB to be installed. It looks for these, in order:
arm-none-eabi-gdb- GDB from the PROS toolchain named in the
PROS_TOOLCHAINenvironment variable - GDB from the PROS toolchain installed by the PROS VS Code extension
gdb-multiarchgdb
If you use PROS through VS Code, make sure the extension has finished installing its toolchain. Otherwise, see the GDB installation instructions in the Rust setup guide, or tell v5gdb which GDB program to use with --client.
GDB starts, but my program never stops at breakpoints
- GDB may have lost connection at some point; try quitting and re-running v5gdb.
- Make sure you rebuilt and uploaded after adding
v5gdb::install()(PROS:pros mu). - Make sure
v5gdb::install()is actually being run. In PROS it should be near the start ofinitialize(). - Make sure the program is running on the brain before you start
v5gdb. - Check that the breakpoint is on a line that is actually being run. For example, a breakpoint in
autonomous()won’t be run during driver control.
GDB shows the wrong code, or line numbers don’t match
- The program on the brain may be older than the code on your computer. Build and upload again, then restart
v5gdb. - v5gdb might not have found the robot code on your computer. Make sure you’re running v5gdb from inside your PROS project. For Rust, make sure you’ve specified the ELF file you’re debugging.
Variables are <optimized out>, or stepping skips lines
The compiler rearranged or removed some code to make your program faster. This is normal when optimizations are on. Try setting a breakpoint on a later line where the variable is used, instead of stepping. For Rust, debug without --release (see Considerations).
My printf output looks garbled
PROS encodes program output in a special format. v5gdb normally detects this in PROS projects, but if you run v5gdb from outside your project folder, it might not. Run it from your project folder, or pass --user-io pros. See --user-io.
The robot keeps moving while paused
Pausing the program doesn’t stop motors by default. Stop them with monitor stop, or turn on automatic stopping:
- From GDB:
monitor autostop true - In C++:
v5gdb::install({.stop_motors_on_break = true}); - In Rust:
v5gdb::install(V5Debugger::stdio().stop_motors_on_break(true));
Uploads fail while v5gdb is running
When v5gdb is running, other programs aren’t able to connect to the V5 brain.
Quit v5gdb (type quit) before uploading, and start it again after the upload.
Command-line interface
v5gdb has a command line interface that can debug your V5 brain over a USB connection. It’s intended for use with the StdioTransport; if you make a custom transport, you will have to make your own alternative.
Usage
The arguments to v5gdb are the ELF files that describe the program which is currently running on the brain. All frameworks for the VEX V5 output these files as part of their build process, but they are placed in varying locations.
For PROS programs, specifying ELF files is optional; v5gdb can usually automatically discover them.
Example usage:
# PROS
v5gdb
# PROS (with ELF files specified; optional)
v5gdb ./bin/hot.package.elf ./bin/cold.package.elf
# vexide
v5gdb ./target/armv7a-vex-v5/release/your_program_name
Command-line Options
-c <client>, --client <client> (Debugger Client)
environment variable: V5GDB_CLIENT
This flag allows you to specify the path or name of a custom GDB or LLDB program which v5gdb should use. This option is useful if your installation of GDB/LLDB has a non-standard name which v5gdb does not detect by default.
For example, to use Rust GDB instead of GDB:
v5gdb -c rust-gdb
Whatever you pass must accept GDB’s command-line arguments (or LLDB’s, if --lldb is specified or the client name contains lldb).
This option has no effect in TCP mode.
Automatic Discovery
If this option is not specified, v5gdb will check for the following programs and use the first one it finds:
arm-none-eabi-gdb- GDB from the PROS Toolchain in the
PROS_TOOLCHAINenv variable - GDB from the PROS Toolchain installed by the PROS VS Code extension (“OneClick”)
gdb-multiarchgdb
Or, if --lldb is specified, these programs will be checked:
lldb
-C=<arg>, --client-arg=<arg> (Debugger Client Arguments)
This flag passes an extra argument to the debugger client. It can be specified more than one time.
For example, to run GDB in “quiet” mode with its TUI interface enabled:
v5gdb -C=--quiet -C=--tui
--tcp <addr> (TCP Server mode)
By default, v5gdb CLI opens directly into the gdb command-line REPL interface. If you’d like to use a custom GDB frontend, you can disable this behavior by specifying the --tcp flag, which makes v5gdb CLI run headless (similarly to gdbserver).
v5gdb --tcp=localhost:35537
When the --tcp flag is specified, v5gdb will start a TCP server and wait for a connection on the specified address and port. You can connect to it from a GDB frontend like this:
$ gdb -ex "target remote :35537" bin/monolith.elf
Reading symbols from bin/monolith.elf...
Remote debugging using :35537
(gdb)
When v5gdb starts GDB itself, it runs a few setup commands before connecting that help improve the performance of memory reads. In TCP Server mode, we recommend running these commands yourself (before target remote):
mem 0x100000 0x2c00000 ro cache
mem 0x2c00000 0x8000000 rw cache
set dcache line-size 1024
For example:
gdb -ex "mem 0x100000 0x2c00000 ro cache" \
-ex "mem 0x2c00000 0x8000000 rw cache" \
-ex "set dcache line-size 1024" \
-ex "target remote :35537" \
bin/monolith.elf
The above example just uses GDB like normal, but TCP Server mode can be useful for integrating v5gdb with an IDE or code editor to set up graphical debugging.
In TCP Server mode, logs and other serial output from the program you are debugging will appear under the v5gdb command instead of being interleaved with your GDB session.
--lldb (Use LLDB)
While GDB is v5gdb’s best-supported debugger, you can also use it with LLDB instead by specifying this flag.
Tip
LLDB mode is turned on automatically if you choose a client whose name includes
lldb, such asv5gdb -c rust-lldb.
TCP Server mode and LLDB
In TCP Server mode, this flag isn’t supported; however, you can connect LLDB yourself with these commands:
$ lldb
(lldb) settings set target.process.memory-cache-line-size 1024
(lldb) target create bin/monolith.elf
(lldb) gdb-remote 35537
To debug more than one ELF file (e.g. PROS’s hot.package.elf and cold.package.elf), load each extra file after connecting:
(lldb) target modules add bin/cold.package.elf
(lldb) target modules load --file bin/cold.package.elf --slide 0
Compatibility
LLDB can’t call functions in expressions because it disables remote code execution on bare-metal targets. Reading variables and simple expressions like x * 2 work, though.
--no-discover-elf (ELF auto-discovery)
environment variable: V5GDB_NO_DISCOVER_ELF
By default, if no ELF files are specified on the command line, v5gdb will search common locations in PROS projects for debug info stored in ELF files, including bin/monolith.elf, bin/hot.package.elf, and bin/cold.package.elf.
You can disable this feature using the --no-discover-elf command-line flag. ELF auto-discovery is always disabled in TCP Server mode.
--user-io <mode> (User I/O packet format)
environment variable: V5GDB_USER_IO
PROS adds extra COBS encoding to all data written to stdout, which can make your prints look odd when v5gdb does not recognize that it needs to decode your program’s output. This flag customizes how v5gdb interprets your program’s output.
Supported modes:
--user-io auto(default): When v5gdb is running inside a PROS project, it will apply PROS-style program output decoding.--user-io pros: v5gdb will always apply PROS-style program output decoding.--user-io raw: v5gdb will not apply any additional processing to program output.
--debug-io
Enables TRACE-level logging for serial operations. All decoding errors and serial I/O will be logged.
This is the same as adding v5gdb::serial=trace to the V5GDB_LOG environment variable.
Logging
You can use the V5GDB_LOG environment variable to customize logging. Format details are available here.
Example:
$ V5GDB_LOG=debug v5gdb
Monitor commands
v5gdb includes some extensions to GDB that allow you to control some unique aspects of the V5 brain. These extensions are accessible as subcommands of the “monitor” command (which can be typed as “mon” for short). For example, to view all connected devices, you could run monitor devices.
Utility
monitor help
Lists all monitor commands that the active version of v5gdb supports.
monitor log [level]
View or set the current log level (one of off/trace/debug/info/warn/error).
Device Access
These commands allow you to interact with the devices connected to your V5 Brain.
monitor devices
(alias dev)
Lists all connected smart devices, including their port numbers and types.
monitor ctrl [partner]
Views the active inputs from the connected controller. If multiple controllers are connected, you can view the inputs from the partner controller by specifying partner.
monitor battery
(alias batt)
Views the status of the connected battery, including temperature, voltage, current, and percent charge.
monitor stop
Immediately stops all Smart Motors connected to the robot.
Competition Control
You can use v5gdb to inspect or override the robot’s competition state using the monitor comp command. This can be useful for testing how your robot would function in different modes outside of a real competition.
Competition state overrides do not have any effect on the restrictions imposed by VEXos when your robot is autonomous or disabled. For instance, if the competition state is actually “autonomous” but is overridden to “opcontrol”, your code will not receive new data from controllers. Alternatively, if a robot is actually in the “opcontrol” state but is overridden to “disabled,” it will still be able to move motors.
monitor comp
Running the command without any arguments will show you the current competition state and any overrides you have set.
monitor comp driver | auton | disabled
Override the current competition mode by specifying driver (or opcontrol), auton, or disabled.
monitor comp none | fc | switch
Override the current competition system by specifying none for disconnected, fc for field control, or switch for competition switch.
monitor comp real
Remove any overrides that you have set by specifying real.
Maintenance
These commands allow you to perform maintenance or debugging on v5gdb itself.
monitor dbg break
Shows the internal status of software breakpoint system.
monitor dbg hw
Shows the internal status of hardware breakpoint system, including the configuration of the processor’s debug subsystem.
System Access
v5gdb can interface with an RTOS to support thread-aware debugging. Depending on which RTOS is in use, different system-specific commands will be available as subcommands of monitor sys.
You can view all available system commands by running monitor sys help.
FreeRTOS
FreeRTOS is the operating system used by the PROS framework.
monitor sys tasks
(alias task, t)
Lists the details of all FreeRTOS tasks, including:
- Id: The task’s unique task ID number.
- Name: The task’s name, if configured.
- State: The scheduling state of the task (Blocked, Deleted, Ready, Running, Suspended, or Unknown).
- Priority: The scheduling priority of the task.
- Stack Remaining: The stack high-water mark, formatted as the number of words (i.e. 4-byte chunks) in the task’s stack which have never been used.
You can also view different information about the active tasks by using GDB’s builtin info threads command.
Transports
This chapter discusses the options you have for communicating with the debugger running on the brain.
When you use GDB to debug a V5 brain, it has to connect to the v5gdb debug server (that’s what this project is) to get info about what the brain is doing, command a single-step/resume, or manage breakpoints. The method that GDB uses to communicate with the debug server is called a transport. You have the option of either using one of v5gdb’s builtin transports or making your own.
Stdio Transport (USB Serial)
In the StdioTransport configuration, v5gdb will reconfigure the brain’s USB Serial connection so that both user serial writes (via printf or std::io::stdout) and debugger IO share the same communication stream. All data sent from the brain is given extra framing so that a tool running on the user’s PC can differentiate between user IO and debugger IO. This process is completely transparent to user code; no additional configuration is required for user serial writes to be formatted correctly.
This transport method encodes serial output using the following protocol:
- Data is organized into arbitrarily-sized packets that are COBS-encoded.
- The first byte of each packet is the channel identifier.
- The byte
'd'indicates that the packet contains debugger protocol data. - The byte
'l'indicates that the packet contains UTF-8 debugger logs. - The byte
'u'indicates that the packet contains user serial data.
- The byte
- The remaining bytes contain the packet body.
- Encoded packets are never larger than 2048 bytes.
- Invalid packets, or packets with an unknown channel ID, are treated as user serial data.
The user serial data in the body of a packet is left completely unprocessed by StdioTransport, so it might be doubly-COBS-encoded if the framework you are using is already COBS-encoding user serial data. The v5gdb command-line tool will automatically detect this and decode user serial data as needed (this behavior can be configured with the --user-io flag).
At this time, PC-to-brain data is not COBS-encoded. All data sent to the brain is assumed to be part of the debugger channel.
This repository contains the v5gdb command-line tool (in ./cli/) which implements this protocol.
Custom Transport
You can create and use a custom transport method by implementing the v5gdb::transport::Transport trait (Rust) or by sub-classing v5gdb::Transport (C++).
use v5gdb::transport::*;
pub struct SmartPortTransport {
serial: SerialPort,
}
impl Transport for SmartPortTransport {
fn write_all(&mut self, buf: &[u8]) -> Result<(), TransportError> {
self.serial.write_all(buf).map_err(|_| "i/o error".into())
}
// ...
}
#include "v5gdb.h"
#include "api.h"
#include "pros/serial.hpp"
#include <cstring>
class SmartPortTransport : public v5gdb::Transport {
public:
SmartPortTransport(pros::Serial&& serial) : serial(serial) {}
v5gdb::Result<void> write(std::span<uint8_t const> buffer) noexcept override;
// ...
private:
pros::Serial serial;
};
v5gdb::Result<void> SmartPortTransport::write(std::span<uint8_t const> buffer) noexcept {
int written = serial.write(const_cast<uint8_t *>(buffer.data()), buffer.size());
if (written == PROS_ERR) {
return std::unexpected(strerror(errno));
}
if (written != buffer.size()) {
return std::unexpected("not all bytes were written");
}
return {};
}
Then pass it to the debugger when setting it up.
#[vexide::main]
async fn main(p: Peripherals) {
let serial = SerialPort::open(p.port_1, 921600).await;
v5gdb::install(V5Debugger::new(SmartPortTransport { serial }));
}
void initialize() {
v5gdb::install({}, SmartPortTransport(pros::Serial(1, 921600)));
}
The debugger will now run your callbacks to send and receive data. Generally, breakpoints will not be enabled when user transports are called, but it’s probably a good idea to separate your transport code from the code you’re trying to debug.
Internals
This page is for people who want to understand how v5gdb works. You might be looking for the v5gdb user manual instead.
The vexide team has developed v5gdb, an on-device debugger for the VEX V5 platform to satisfy a long-term interest by the VEX community for better debugging tools. This chapter will attempt to give an overview of how v5gdb works and the problems we needed to solve to create it.
Previous Work
There has been some past work on implementing a similar project on previous VEX platforms. For instance, the ROBOTC language and framework (which targeted the VEX Cortex platform) included a feature-rich graphical debugger that took advantage of the language’s virtual machine environment. Additionally, the PROS project, also targeting the Cortex, initially included a prototype of a real-time, key/value dashboard called “JINX Debugger” (however, it never was expanded to include most of the traditional features of a debugger). Ultimately, neither ROBOTC nor JINX were ported to the more recent VEX V5.
Another more recent notable project is Interfiber’s v5dbg, a debugger for PROS programs that allows developers to define breakpoints at compile time using some C++ macro magic and function calls. It also allows users to manually expose variables so they can be viewed when their breakpoints are hit. Unfortunately, due to v5dbg’s architecture, users cannot step through lines of code or place arbitrary breakpoints at runtime. Additionally, developers must update their existing code to take advantage of the debugger’s features.
With v5gdb, our goal was to bring a “full” debugger on par with what ROBOTC had supported to the VEX V5 platform, so we decided to instead implement a GDB backend for VEX V5. By taking advantage of the Cortex A9’s advanced hardware debug functionality, we were able to implement the ability to place breakpoints in arbitrary locations and view variables without explicit code changes. While this debugger’s primary goal is to support vexide and PROS, we would like to bring support to the VEXcode framework in the future.
Debugger overview
This section gives a high-level overview of the architecture of this project.
Resources
Those interested in contributing are highly encouraged to download a copy of the ARMv7-A Reference Manual and optionally the Cortex-A9 Manual. These cover nearly all important details about debug events, debug registers, and the CPU’s exception model. Also, it might be helpful to look at the Zynq 7000 Reference for information about the device’s memory map and configuration registers.
While v5gdb interacts with VEXos fairly minimally, it may also be helpful to refer to some of the other resources on this website that cover how VEXos itself works.
ARMv7-A debugging model
The VEX V5 is built around the Zynq 7000 system-on-chip, running user code on one of its dual ARM Cortex-A9 processors. Since all user code is run in System mode (which is one of the privileged “kernel modes”), it is free to manage processor state such as the debug architecture. The debugger library uses this ability to configure the CPU just as a real operating system would.
The ARMv7-A debug architecture is controlled by various registers that the CPU checks to determine where, when, and how to cause breakpoints. These registers can be accessed through Coprocessor #14 (cp14), but require special assembly instructions for each one - for instance, accessing each numbered hardware breakpoint would have to be its own line of code. The alternative is the processor’s debug MMIO interface, which lets you access debug state just like any other global integer or array. For the most part, v5gdb uses MMIO to access hardware state because of its greater ease-of-use. To access it, the library reads and saves the address of the MMIO interface from cp14 when it initializes.
The debugging process itself is centered around debug events, which can occur whenever a hardware breakpoint, watchpoint, or bkpt assembly instruction are triggered. Depending on the CPU state, debug events will either be ignored (the default), cause the CPU to halt (for debugging with a probe device like J-Link), or induce a debug exception that can be handled by the operating system. The V5 only supports so many hardware breakpoints, so, for the most part, we just dynamically edit programs to replace certain instructions with bkpt. Whenever they’re hit, a debug event is triggered just as if a real breakpoint had been there. When we want to continue, we can replace the bkpt instruction with whatever was there before and return from the exception handler. This approach is called software breakpoints because it doesn’t require the use of the hardware’s dedicated breakpoint registers.
Hardware breakpoints do have their uses, though, because they can be configured to trigger when the processor isn’t executing a targeted instruction rather than just when it is doing so. For instance, if the debugger wanted to single-step past an instruction, it could place such a “mismatch” breakpoint on the current instruction and return from the debug handler. Then, just as that instruction finished, the program would pause again. Recreating this same behavior would be pretty difficult with the normal strategy of overwriting certain instructions with bkpt because programs don’t always advance linearly: they might call a function, for instance, or jump back to the beginning of a loop. Using a hardware breakpoint to avoid having to guess what the next instruction will be helps the debugger avoid implementing what’d essentially be an entire ARM emulator.
(See also chapters C1 and C3 of the ARMv7-A reference.)
Zynq 7000 configuration
Unfortunately, using hardware breakpoints at all requires some more setup because they only work if the Cortex-A9 processor’s DBGEN (Debug Enable) signal is set High. In comparison, the bkpt instruction always causes a debug event (and, in turn, bkpt debug events always cause exceptions the library is able to handle). Setting DBGEN requires the debugger to access the Device Configuration Interface, one of the peripherals on the Zynq itself. Without doing this, it would be unable to take advantage of the flexibility of hardware breakpoints.
By default, VEXos configures the Memory Management Unit (MMU) to protect that peripheral against accidental reads and writes by the user code CPU. Since the vexide debugger is accessing it legitimately, it temporarily disables MMU permission checks by switching to the Manager Domain when it needs to update the device configuration. Note that it is unlikely VEXos resets either the Zynq’s device configuration or CPU’s breakpoint configuration after each program, so it’s likely that breakpoints persist between different programs (but not between restarts). This is not a problem that has been investigated yet.
(DBGEN is discussed in chapter C2 of the ARMv7-A reference.)
CPU exceptions and the vector table
As mentioned previously in this document, the vexide debugger is able to capture the emitted debug events, execute some code in a debug monitor state, then continue execution where it left off. It uses the processor’s CPU exceptions feature to facilitate this. Exceptions are the system the CPU uses to handle anything that requires it to pause and switch context, from interrupts (common) to data/prefetch aborts (hopefully never). Whenever an exception occurs, the processor saves its current state and re-starts execution at one of several offsets inside the currently-configured exception vector table. Traditionally, this is a list of jump instructions to functions that know how to handle whatever the current “exceptional” process state is. For instance, after a prefetch abort, the processor jumps to vector_table + 0x0c. There, vexide’s vector table has a jump instruction to its code for showing an abort error screen.
The vexide debugger needs its own vector table to manage debug exceptions triggered by breakpoints. However, since a processor can only have one vector table active at a time, any vector table we install must also be able to handle the responsibilities of any exception handlers configured by the user’s framework (e.g., vexide or PROS). Instead of incorporating framework-specific logic in the vector table, we opted to have ours function as a flexible overlay. When the debugger is initialized, it stores the items in the original vector table, assuming that it contains an existing set of handlers that are already capable of handling the normal exceptions. It then re-configures the processor to use its own vector table, which captures anything debug-related but falls through for any exceptions out of its scope.
This architecture is useful because it makes fewer assumptions. For instance, if another error-handling library adds its own custom abort handlers to the exception vector table, the debugger will be completely compatible with it at runtime because its own overlay vector table will dynamically fall through to whatever else is currently in use.
Interrupt Handlers
When debugging a program with GDB, you can press Ctrl-C to send the device a packet asking to pause the program. In order to periodically check for these Ctrl-C packets, v5gdb runs some of its own code before each IRQ exception to poll serial input. Since IRQ exceptions happen fairly regularly (e.g. the CPU1 Timer triggers one every 1ms) and the serial input buffer is filled automatically in the background by CPU0, this approach allows the program to detect when GDB has asked it to pause even when the user’s code has otherwise frozen up.
In some cases, instead of just running some code before the user’s normal IRQ handler, v5gdb will completely take over servicing interrupts. Especially under FreeRTOS, the normal system interrupt handlers tend to edit state or switch CPU modes in a way that is incompatible with the debugger. This was the cause of some trouble in the past: at one point, if an interrupt was triggered while the debugger was arming a single step, that single step would fire inside the framework interrupt handler instead of in the user’s code. That would lead to the debug monitor starting recursively, which led to all sorts of other trouble.
Implementation
GDB protocol and transports
The gdb command line tool is able to connect to remote devices (such as the VEX V5) and issue them commands like “create a breakpoint at <ADDRESS>” or “send the values of all general-purpose registers.” From the user’s perspective, the experience is as seamless as on-device debugging, but it does require GDB to reliably and and receive packets and be able to recognize what data from the remote device is intended for it (versus what data is just noise). To facilitate the flexible streaming of this data between the computer running GDB and the robot hosting the debugger, vexide’s debugger allows developers to implement custom transport streams.
The simplest possible transport stream is just sending GDB’s packets as-is across the V5’s USB serial connection. This was the original communication method used by the debugger. With this approach, a user might connect to their brain by telling GDB to pipe its packets directly through cargo-v5’s terminal connection:
target extended-remote | cargo v5 terminal
While this approach is very convenient, it has the notable downside of preventing developers from using the V5’s serial stream for any other purpose such as logging or tracing. Thus, a more flexible approach is to add extra packet framing to all data leaving the device which allows data to be distinguished between coming from the user or coming from v5gdb. Then, a program running on the user’s computer decodes it. This is what v5gdb calls StdioTransport.
Cache coherency for self-modifying code
Software breakpoints are implemented by temporarily replacing certain instructions in a program with bkpt instructions. This is considered a type of self-modifying code similar to JIT compilers or vexide’s differential patcher, and as such, is subject to some of the same caching problems. Modern processors like the V5’s Cortex-A9 have both instruction caches and data caches to speed up program execution, but they work under the assumption that “instructions” and “mutable data” are separate. As such, after we insert or remove a breakpoint, we need to take care to correctly manage both of these caches to ensure the change actually takes effect.
When the breakpoint instruction is initially changed in memory, it likely isn’t actually written to RAM at first; instead, the change is kept track of by the processor’s internal data cache. As it turns out, the part of the processor responsible for managing memory is separate from the part that fetches instructions. For any new breakpoint to take effect, these caches must be synchronized to the Level of Unification, the point at which all parts of the processor see the same copy of the system memory. The debugger does this by first cleaning the 32-byte section of the data cache containing the modified memory (committing it to system memory), then invalidating the same part of the instruction cache (pulling the new changes from system memory). After this is completed, it’s also best practice to invalidate the processor’s branch prediction system to help prevent any slow state rollbacks in case of a misprediction.
(The cache operations required after self-modifying code operations are described in the ARMv7-A reference in section D7.5.2 “Instruction cache maintenance operations”.)
Debug register access
The Cortex-A9’s ARMv7-A architecture defines a plethora of debug registers that can be used to control the processor’s breakpoints and watchpoints, among other things. There are two methods for accessing them: either as registers in Coprocessor 14 (cp14) or as a struct at a special place in memory. The latter is preferable because it works better with Rust’s ownership model and is overall simpler to use. While each access to cp14 requires a specially encoded mcr or mrc assembly instruction, it’s trivial to index an array in memory. However, in order to take advantage of struct-like MMIO method, the debugger makes a few accesses to cp14 when it first initializes to determine the base address of those memory-mapped registers. This is done by accessing two registers:
DBGDRAR(Debug ROM Address Register) defines the address in memory of a ROM Table that encodes where to access the debug registers of each processor on the device. We don’t access this table whatsoever.DBGDSAR(Debug Self Address Offset Register) defines the offset of the current processor’s debug registers in memory from the start of the ROM Table.
Adding these two values together gives a pointer to the virtual struct containing debug registers.
(Chapter C6 of the ARMv7-A manual describes the cp14 interface and the memory-mapped struct interface. Chapter C11 has a summary of the various registers that the debugger uses.)
Exception handling
When breakpoints are hit, they generally turn into prefetch aborts. In the debugger’s handler for this kind of exception, it determines whether the abort is “real” or not by checking if the “cause” bits in the Instruction Fault Status Register indicate a debug event. If so, execution diverges to the debugger. Importantly, throughout this process, no general-purpose registers are clobbered.
Once the debugger knows it’s going to stop, it collects the current state of the processor for inspection and modification by the GDB client inside an instance of DebugEventContext. Then, when the debugger is ready to return, it restores the (possibly modified) general purpose registers and processor state before jumping back to user code.
Support for dedicated floating point registers isn’t implemented right now, which means it’s not possible to see some floating point values from GDB. The main work for this feature will be updating the exception handling code to store these in the context struct.
User setup and usage
Currently, users activate the debugger by passing a transport method to the install function. They then enter debug mode by explicitly calling the breakpoint function.
#[vexide::main(banner(enabled = false))]
async fn main(_peripherals: Peripherals) {
v5gdb::install(StdioTransport::new());
v5gdb::breakpoint();
let iters = black_box(80);
let n = fib(iters);
black_box(n);
}
This process may need to be refined before the debugger is finished.