Debugging Ruby with ruby/debug: rdbg, Breakpoints, Tracing, and Remote Sessions
A complete guide to the official ruby/debug gem (debug.rb): the four ways to start it, the full console command set, conditional and method breakpoints, tracing, record/replay, remote debugging over UDS and TCP, configuration, and how it is built internally.
debug is the official debugger for MRI (CRuby) 2.7 and later. It replaces the ancient lib/debug.rb standard library, which was implemented with set_trace_func — a global hook that slows the whole program down. The new debug.rb takes a different approach (breakpoints are attached to specific instruction sequences via TracePoint), is remote-capable, and is extensible enough to drive VS Code and Chrome DevTools.
This post is a practical walkthrough of the gem, based on the repository at https://github.com/ruby/debug (master was at v1.11.1 when this was written) plus sessions I ran locally on Ruby 3.3.8 with debug 1.11.1. Terminal output shown below is real output, with color stripped.
Why not just keep using byebug?
| Concern | byebug | ruby/debug |
|---|---|---|
| Ownership | Third-party gem | Official gem under the ruby GitHub org |
| Mechanism | TracePoint-based, older internals | Per-ISeq breakpoints + C extension |
| Remote debugging | Not built in | UNIX domain socket, TCP/IP, DAP, CDP |
| Editor support | Legacy RDP adapters | VS Code (DAP) and Chrome DevTools (CDP) |
| Record/replay | No | Yes (record, step back) |
| Frame inspection | var local, var instance | info locals, info ivars, outline, display |
| Console | Basic | Reline line editing, optional full IRB console |
If you are migrating an existing byebug workflow, the mapping near the end of this post lists the command equivalents.
Installation
1
$ gem install debug
With Bundler, add it to the Gemfile:
1
gem "debug", ">= 1.0.0"
The version constraint matters: debug below 1.0.0 is a completely different, abandoned gem.
debug has been a bundled gem since Ruby 3.1, so it may already be installed with your Ruby. Bundler-managed projects still need the Gemfile entry, otherwise bundle exec will hide it.
The four ways to start a session
1. binding.break — the binding.pry replacement
Add require "debug" at the top of the program and drop binding.break where you want to stop. It has two aliases that do the same thing: binding.b and debugger.
1
2
3
4
5
6
7
8
require 'debug'
def greet(name)
binding.break
"hi #{name}"
end
puts greet("sky")
Run it normally — no wrapper command needed:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ ruby bb.rb
[1, 8] in bb.rb
1| require 'debug'
2|
3| def greet(name)
=> 4| binding.break
5| "hi #{name}"
6| end
7|
8| puts greet("sky")
=>#0 Object#greet(name="sky") at bb.rb:4
#1 <main> at bb.rb:8
(rdbg) p name
=> "sky"
(rdbg) next
[1, 8] in bb.rb
1| require 'debug'
...
=> 5| "hi #{name}"
=>#0 Object#greet(name="sky") at bb.rb:5
(rdbg) continue
hi sky
Note the current frame line: Object#greet(name="sky") — parameters are shown in the frame header, which is one of the small quality-of-life wins over the old debugger.
binding.break accepts two keywords that turn it into a non-interactive hook:
1
2
3
4
5
6
7
8
9
def initialize
@a = 1
binding.b do: 'info ;; watch @a' # run the commands, then continue automatically
end
def foo
binding.b pre: 'p bar()' # run the commands, then stay suspended
...
end
do: is “stop, execute, continue”. pre: is “execute, then stop”. Multiple commands are separated by ;;.
If you want a shorter alias everywhere without typing binding.b, set RUBY_DEBUG_BB=1 to define Kernel#bb.
2. rdbg script.rb — launch the program from the debugger
If you cannot modify the source, run it under rdbg, which behaves like ruby script.rb:
1
2
$ rdbg target.rb
$ bundle exec rdbg target.rb # Bundler projects
The program suspends at the first line, and you set breakpoints yourself:
1
2
3
4
5
(rdbg) break 12
#0 BP - Line /app/app.rb:12 (return)
(rdbg) break
#0 BP - Line /app/app.rb:12 (return)
(rdbg) continue
You can also suspend a running rdbg process at any time with Ctrl-C (SIGINT) and inspect what it is doing. Set RUBY_DEBUG_NO_SIGINT_HOOK=1 to disable that.
3. rdbg -c -- <command> — debug any Ruby executable
-c (command mode) means “the first argument is an executable in PATH”, so it works for rails, rake, bundle, rspec, sidekiq, and friends:
1
2
3
4
$ rdbg -c -- rails server
$ rdbg -c -- bundle exec rspec spec/models/cart_spec.rb:12
$ rdbg -c -- bundle exec rake test
$ rdbg -c -- ruby target.rb # equivalent to: rdbg target.rb
The -- separator is required so that rdbg stops parsing options. rdbg -c rake -T is parsed as rdbg -c -T -- rake and is wrong; write rdbg -c -- rake -T.
4. Remote sessions with --open
When there is no TTY (Docker, daemons, piped stdio) or you want to attach later, start the program as a remote debuggee and attach from another terminal:
1
2
3
4
5
6
7
8
9
# terminal 1: run the program and wait for a debugger to attach
$ rdbg --open target.rb
DEBUGGER: Session start (pid: 7773)
DEBUGGER: Debugger can attach via UNIX domain socket (/home/ko1/.ruby-debug-sock/ruby-debug-ko1-7773)
DEBUGGER: wait for debugger connection...
# terminal 2: attach
$ rdbg -A
(rdbg:remote)
--open has a short form -O, and --attach has -A. Details are in the remote section below.
Choosing the right entry point
| You want | Use | Equivalent to |
|---|---|---|
| Inline breakpoint, no wrapper | require 'debug' + binding.break | rdbg --nonstop --no-sigint-hook |
| Launch under debugger, stop at start | rdbg target.rb | require 'debug/start', ruby -r debug/start |
| Open a remote port, stop at start | rdbg --open target.rb | require 'debug/open' |
| Open a remote port, keep running | rdbg --open --nonstop target.rb | require 'debug/open_nonstop' |
The require forms are useful when the debug configuration must be set from inside the program:
1
2
3
4
5
require 'debug/session'
DEBUGGER__.start(no_color: true, log_level: 'INFO')
# or: DEBUGGER__.open / DEBUGGER__.open_unix / DEBUGGER__.open_tcp
The debug console
The prompt is (rdbg), or (rdbg:remote) for an attached remote console.
Three behaviors make the console pleasant to use:
- A bare expression is
pp. Typingfoo.barevaluates it and pretty-prints the result. The downside: single-letter commands (i,b,n,c) shadow local variables of the same name, so prefer the explicitp,pp, orevalcommands. Enterrepeats the last command. Convenient for repeatedstep.Ctrl-Dequalsquit.
If you want autocompletion, multi-line input, and show_source/show_doc, switch to the full IRB console with the irb command (available since v1.9):
1
2
(rdbg) irb
irb:rdbg(main):001>
Make it the default for every session with RUBY_DEBUG_IRB_CONSOLE=true or by adding config set irb_console 1 to ~/.rdbgrc.
Breakpoints
Line breakpoints
1
2
3
4
5
6
7
8
9
10
b[reak] show all breakpoints
b[reak] <line> current file
b[reak] <file>:<line> explicit file
b[reak] <class>#<name> method
b[reak] <expr>.<name> method on an object
b[reak] ... if: <expr> break only when the condition is true
b[reak] ... pre: <command> run a command before stopping
b[reak] ... do: <command> run a command, then continue
b[reak] ... path: <path> only in matching paths (string or /regexp/)
del[ete] [<bpnum>] delete one or all
Conditional breakpoints are the cure for “this loop runs 10,000 times”:
1
2
(rdbg) b 12 if: price > 250
(rdbg) b Cart#total if: @items.size > 2
path: is handy to stop only in your own code and not in gems:
1
(rdbg) b 12 path: /app/
Method breakpoints
Registering a method breakpoint before the class is defined is fine — it becomes a pending breakpoint and resolves when the constant appears. This is a real session:
1
2
3
4
5
6
7
8
9
10
11
(rdbg) break Cart#total
#0 BP - Method (pending) Cart#total
(rdbg) continue
[7, 16] in app.rb
7| def total
=> 8| @items.each do |price|
...
=>#0 Cart#total at app.rb:8
#1 <main> at app.rb:16
Stop by #0 BP - Method Cart#total at app.rb:7
Without the Class#method form, break some_method fails for top-level methods because they live on Object:
1
2
3
(rdbg) break a
Unknown breakpoint format: a
(rdbg) break Object#a
Exception breakpoints: catch
catch <Error> stops when that exception is raised, anywhere:
1
2
3
4
5
6
7
8
9
10
11
(rdbg) catch RuntimeError
#0 BP - Catch "RuntimeError"
(rdbg) continue
9| def c
=> 10| raise "boom"
...
=>#0 Object#c at nested.rb:10
#1 Object#b at nested.rb:6
# and 2 frames (use `bt' command for all frames)
Stop by #0 BP - Catch "RuntimeError"
catch also accepts if:, pre:, do:, and path:, just like line breakpoints:
1
(rdbg) catch StandardError path: /app/models/
Unlike byebug, you do not need to enable “catch mode” first; catch registers a normal breakpoint that can be listed and deleted like any other.
Watchpoints
watch @ivar stops whenever the instance variable changes value:
1
2
(rdbg) watch @total
#1 BP - Watch #<Cart:0x00007ff47cc51d90> @total = 600
Watchpoints are implemented with a slow check on every suspension, so use them on a narrow scope.
Stepping and control flow
1
2
3
4
5
6
7
8
9
s[tep] [n] step into (n breakable points)
n[ext] [n] step over
fin[ish] [n] run until the current (or n-th) frame returns
u[ntil] ... run until a line, or until a method is called
c / cont / continue
q[uit] leave the debugger (the program keeps running in remote mode)
q[uit]! quit without confirmation
kill terminate the debuggee with exit!
sigint run the debuggee's own SIGINT handler (right after Ctrl-C)
until is the underrated one. It is gdb’s advance: run until a specific location, or until a named method is entered.
1
2
3
4
(rdbg) until 42 # run to line 42
(rdbg) until lib/cart.rb:42
(rdbg) until total # run until a method called `total` is invoked
(rdbg) until /total/ # regexp works too
Note the difference between quit and kill in a remote session: quit only disconnects the console, so you can attach again later; kill terminates the debuggee.
Inspecting state
1
2
3
4
5
6
7
8
9
10
11
bt [n] [/regexp/] backtrace, optionally limited or filtered
l[ist] source around the current line; list - goes backwards
l[ist] 10-25 explicit range
whereami current frame plus source
edit [file] open in $EDITOR
i[nfo] ... see below
o[utline] [expr] available methods/constants/locals (alias: ls)
display <expr> evaluate automatically at every stop
undisplay [n]
f[rame] [n] show or select a frame
up / down move through the frame stack
info subcommands
1
2
3
4
5
6
7
i[nfo] locals (l) local variables, %self, and _return
i[nfo] ivars (i) instance variables; info ivars <expr> for another object
i[nfo] consts (c) accessible constants; info consts <expr> for a class
i[nfo] globals (g) global variables
i[nfo] threads (th) all threads
i[nfo] breakpoints (b) breakpoints and watchpoints
i[nfo] ... /regexp/ filter the output
Subcommands can be abbreviated as long as they are unambiguous (info l, info i, …). Real output:
1
2
3
4
5
6
(rdbg) outline
Cart#methods: total
instance variables: @items @total
(rdbg) info ivars
@items = [100, 200, 300]
@total = 0
outline (ls) is the “what can I do here?” command: it lists the methods, constants, locals and ivars in scope, or the API of an object if you pass one (ls @items).
_return in info locals shows the return value of the frame you just stepped out of, and the frame header appends #=> 600 when a value is about to be returned — very useful when stepping through a chain of methods.
Tracing
Tracing is for when you do not want to single-step, but want a stream of events:
1
2
3
4
5
6
7
8
trace list tracers
trace line line events
trace call call/return events
trace exception raised exceptions
trace object <expr> events where the object is a parameter or receiver
trace ... /regexp/ filter by name
trace ... into: <file> write to a file instead of the console
trace off [num|type] disable tracers
Real output from trace call /greet/:
1
2
3
4
5
6
(rdbg) trace call /greet/
Enable CallTracer (enabled) with pattern /greet/
(rdbg) continue
DEBUGGER (trace/call) #th:1 #depth:2 > Object#greet at tr.rb:1
DEBUGGER (trace/call) #th:1 #depth:2 < Object#greet #=> "hi sky" at tr.rb:3
hi sky
The > line is the call (with the receiver and arguments) and the < line is the return, including the return value. trace object @cart answers the question “who touches this object?”.
Record and replay
This is the feature with no byebug equivalent. Turn recording on, execute, then step backwards:
1
2
3
4
5
6
7
8
9
10
(rdbg) record on
Recorder for #<Thread:0x00007fb7cbbca978 run>: on (0 records)
(rdbg) step
=> 2| 3.times do |i|
(rdbg) step
=> 3| x += i
(rdbg) step back
[replay] => 2| 3.times do |i|
(rdbg) p x
[replay] => 0
While replaying, the prompt is prefixed with [replay] and the source lines are printed with [replay] markers. step moves forward through the recorded log and step back moves backward. step reset leaves replay mode.
record (without arguments) shows the recorder status. Recording has a cost, so enable it only around the region you care about.
Remote debugging
Remote debugging covers three very common situations:
- the process has no TTY (containers, daemons, services),
- stdio is a pipe,
- you want to inspect a running process without stopping it at startup.
Starting a debuggee
| Stop at start | Command-line | require | API |
|---|---|---|---|
| yes | rdbg --open | require "debug/open" | DEBUGGER__.open |
| no | rdbg --open --nonstop | require "debug/open_nonstop" | DEBUGGER__.open(nonstop: true) |
By default --open uses a UNIX domain socket in a per-user directory and prints its path. debug/open_nonstop is effectively a debug backdoor — treat it as a vulnerability and never enable it in production.
UNIX domain socket
1
2
3
4
5
6
$ rdbg --open target.rb
DEBUGGER: Debugger can attach via UNIX domain socket (/tmp/ruby-debug-sock-1000/ruby-debug-ko1-27706)
DEBUGGER: wait for debugger connection...
$ rdbg -A # auto-detect the socket
$ rdbg -A /path/to/socket # explicit
A real attach session (server and client on the same machine):
1
2
3
4
5
6
7
8
9
10
11
12
$ rdbg -A /tmp/rdbg-demo/test.sock
DEBUGGER (client): Connected. PID:1454726, $0:app.rb
[1, 10] in app.rb
=> 1| class Cart
...
=>#0 <main> at app.rb:1
(rdbg:remote) info
%self = main
cart = nil
(rdbg:remote) bt 2
=>#0 <main> at app.rb:1
TCP/IP
For containers you typically need TCP, because a UNIX socket cannot cross the container boundary:
1
2
3
4
5
# debuggee (inside the container)
$ rdbg --open --host 0.0.0.0 --port 12345 target.rb
# debugger (on the host)
$ rdbg -A localhost 12345
Useful options:
--port 12345 --port-range 10tries 12345, 12346, … until a port is free.--hostchooses the listening interface (default127.0.0.1).--cookieand--session-namehelp distinguish or secure multiple sessions.RUBY_DEBUG_SKIP_BP=1skips breakpoints while no client is attached, so an unattended debuggee does not block on a breakpoint nobody is watching.
Security note: messages between the debugger and the debuggee are not encrypted. Do not expose the debug port to an untrusted network.
Editor integration
- VS Code: install the
vscode-rdbgextension, toggle breakpoints in the editor, then press F5. The extension launches your program withrdbg -cand talks DAP. You can also attach to an already-running process withrdbg --open=vscode target.rbor theopen vscodeconsole command. - Chrome DevTools:
rdbg --open=chrome target.rbprints adevtools://...URL; open it in Chrome to use the Sources panel against Ruby code through CDP.
Both frontends are served by protocol adapters over the same core session, so the command set and semantics are identical.
Configuration
Every option has an environment variable and a matching config name. The command form:
1
2
3
4
5
(rdbg) config # list everything with descriptions
(rdbg) config set no_color true
(rdbg) config no_color = true # equivalent
(rdbg) config append skip_path /gems/
(rdbg) config unset no_color
The most useful options, grouped as the source groups them:
UI
| Env var | Config name | Default | Effect |
|---|---|---|---|
RUBY_DEBUG_LOG_LEVEL | log_level | WARN | Debugger’s own log level |
RUBY_DEBUG_SHOW_SRC_LINES | show_src_lines | 10 | Source lines shown on a breakpoint |
RUBY_DEBUG_SHOW_SRC_LINES_FRAME | show_src_lines_frame | 1 | Source lines on frame operations |
RUBY_DEBUG_SHOW_FRAMES | show_frames | 2 | Frames shown on a breakpoint |
RUBY_DEBUG_USE_SHORT_PATH | use_short_path | false | Print $(Gem)/foo.rb style paths |
RUBY_DEBUG_NO_COLOR | no_color | false | Disable colors (also via NO_COLOR) |
RUBY_DEBUG_NO_SIGINT_HOOK | no_sigint_hook | false | Do not suspend on SIGINT |
RUBY_DEBUG_NO_RELINE | no_reline | false | Do not use Reline (useful for pipes) |
RUBY_DEBUG_NO_HINT | no_hint | false | Hide the REPL hint |
RUBY_DEBUG_NO_LINENO | no_lineno | false | Hide line numbers |
RUBY_DEBUG_NO_REPEAT | no_repeat | false | Do not repeat the last command on Enter |
RUBY_DEBUG_IRB_CONSOLE | irb_console | false | Use IRB as the console |
Control
| Env var | Config name | Effect |
|---|---|---|
RUBY_DEBUG_SKIP_PATH | skip_path | Skip frames from matching paths |
RUBY_DEBUG_SKIP_NOSRC | skip_nosrc | Skip frames without source |
RUBY_DEBUG_POSTMORTEM | postmortem | Enter a postmortem session on an uncaught exception |
RUBY_DEBUG_FORK_MODE | fork_mode | Which process keeps the debugger after fork (both/parent/child) |
RUBY_DEBUG_KEEP_ALLOC_SITE | keep_alloc_site | Show allocation sites with p/pp |
RUBY_DEBUG_SIGDUMP_SIG | sigdump_sig | Sigdump signal |
Boot
| Env var | Config name | Effect |
|---|---|---|
RUBY_DEBUG_NONSTOP | nonstop | Do not stop at load |
RUBY_DEBUG_STOP_AT_LOAD | stop_at_load | Stop as soon as the debugger is loaded |
RUBY_DEBUG_INIT_SCRIPT | init_script | Debug-command script to load at first stop |
RUBY_DEBUG_COMMANDS | commands | Commands run at first stop, separated by ;; |
RUBY_DEBUG_NO_RC | no_rc | Ignore ~/.rdbgrc |
RUBY_DEBUG_HISTORY_FILE | history_file | History file location |
RUBY_DEBUG_SAVE_HISTORY | save_history | History size (default 10000) |
Remote
| Env var | Config name | Effect |
|---|---|---|
RUBY_DEBUG_OPEN | open | Same as rdbg --open |
RUBY_DEBUG_PORT | port | TCP port |
RUBY_DEBUG_PORT_RANGE | port_range | Number of ports to try |
RUBY_DEBUG_HOST | host | Bind host (default 127.0.0.1) |
RUBY_DEBUG_SOCK_PATH | sock_path | UNIX socket path |
RUBY_DEBUG_SOCK_DIR | sock_dir | UNIX socket directory |
RUBY_DEBUG_LOCAL_FS_MAP | local_fs_map | Map remote paths to local ones |
RUBY_DEBUG_SKIP_BP | skip_bp | Skip breakpoints when no client is attached |
RUBY_DEBUG_COOKIE | cookie | Negotiation cookie |
RUBY_DEBUG_SESSION_NAME | session_name | Distinguish multiple sessions |
Other environment variables:
RUBY_DEBUG_ENABLE=0disables the debugger entirely (useful to neutralize an inheritedRUBYOPT).RUBY_DEBUG_ADDED_RUBYOPTremoves the injected-r debug/...fromRUBYOPTin child processes.RUBY_DEBUG_EDITORorEDITORselects the editor used by theeditcommand.RUBY_DEBUG_BB=1definesKernel#bbas an alias ofdebugger.
Initial scripts
~/.rdbgrc is loaded at session start and contains debug commands; ~/.rdbgrc.rb is loaded as Ruby. Use them for personal defaults:
1
2
3
4
5
# ~/.rdbgrc
config set show_src_lines 15
config set use_short_path true
config set skip_path /gems/
config set no_sigint_hook true
rdbg -x file loads a specific script, and --no-rc ignores the rc files. RUBY_DEBUG_INIT_SCRIPT and RUBY_DEBUG_COMMANDS cover the same ground for non-interactive runs.
Practical recipes
Rails server
1
$ rdbg -c -- bin/rails server
Then set a breakpoint on a controller method from the console:
1
2
(rdbg) break OrdersController#create
(rdbg) continue
Rails 7 generated apps already include gem "debug" in the :development, :test group. To pause in a specific request without a debugger running, drop binding.break in the action and restart the server.
RSpec
1
$ rdbg -c -- bundle exec rspec spec/models/cart_spec.rb:12
This stops at the beginning of the run. Use b <file>:<line> to put a breakpoint inside a spec, or binding.break in the spec body. RUBY_DEBUG_SKIP_PATH keeps you out of RSpec internals:
1
$ RUBY_DEBUG_SKIP_PATH="$PWD:$(bundle show rspec-core)" rdbg -c -- bundle exec rspec
Rake tasks and background jobs
1
2
$ rdbg -c -- bundle exec rake db:migrate
$ rdbg -c -- bundle exec sidekiq
For a forking job runner, fork_mode decides who keeps the debugger:
1
$ RUBY_DEBUG_FORK_MODE=child rdbg -c -- bundle exec sidekiq
Docker
A container usually has no TTY and its UNIX socket is not reachable from the host, so use TCP:
1
2
3
4
5
# inside the container
$ rdbg --open --host 0.0.0.0 --port 12345 --nonstop -c -- bin/rails server
# from the host, with 12345 published
$ rdbg -A localhost 12345
RUBY_DEBUG_LOCAL_FS_MAP is useful when the container paths differ from the host paths, so source files resolve correctly in an IDE.
Postmortem debugging
With postmortem enabled, an uncaught exception makes the process enter a postmortem session instead of just dying, so you can inspect the frames that led to the crash:
1
$ RUBY_DEBUG_POSTMORTEM=1 rdbg --nonstop app.rb
The prompt becomes (rdbg:postmortem). Stepping commands are rejected in this mode — it is for inspection only.
A quick comparison with byebug
| Task | byebug | ruby/debug |
|---|---|---|
| Insert a breakpoint | byebug | binding.break / binding.b |
| Step in / over / out | step / next / finish | step / next / finish |
| Continue | continue | continue |
| Backtrace | where / bt | bt |
| Local variables | var local | info locals |
| Instance variables | var instance | info ivars |
| Evaluate | eval / p | p / pp / eval |
| Frame selection | frame n | frame n, plus up / down |
| List source | list | list |
| Watch an expression | display | display |
| Catch an exception | catch Exception | catch Exception |
| Threads | thread list | info threads / thread |
| Quit | quit | quit / kill |
| Restart | restart | no equivalent; use record / step back or rerun |
Stan Lo’s From byebug to ruby/debug covers the migration in more depth, and there is also a cheatsheet.
How it is built
Reading the source explains why debug is fast and how the frontends stay in sync. The repository is small and approachable — about 9,800 lines of Ruby plus a 350-line C extension.
| File | Role |
|---|---|
exe/rdbg | CLI front door. Parses options, then re-execs the target with RUBYOPT="-r .../lib/debug/start" and exports the configuration as RUBY_DEBUG_* environment variables. Attach mode boots lib/debug/client.rb. |
lib/debug/session.rb | The singleton DEBUGGER__::SESSION (~2,700 lines): command registry, prompt loop, SIGINT handling, fork/daemon interception, IRB integration, preset commands. |
lib/debug/thread_client.rb | Per-thread debugging state: stepping, frame handling, and the recorder used by record / step back. |
lib/debug/breakpoint.rb | Breakpoint subclasses: ISeqBreakpoint, LineBreakpoint, CatchBreakpoint, CheckBreakpoint, WatchIVarBreakpoint, MethodBreakpoint. |
lib/debug/tracer.rb | LineTracer, CallTracer, ExceptionTracer, ObjectTracer. |
lib/debug/server.rb, server_dap.rb, server_cdp.rb | Protocol adapters: the plain socket protocol, VS Code’s Debug Adapter Protocol, and Chrome’s DevTools Protocol. |
lib/debug/config.rb | The CONFIG_SET table that gives every option both an env var and a config name. |
ext/debug/debug.c, iseq_collector.c | C extension exposing DEBUGGER__.capture_frames (built on rb_debug_inspector) and ISeq helpers such as first_line, last_line, and parameters_symbols. |
The key design decision is in breakpoint.rb: breakpoints do not install a global trace hook. Instead each breakpoint creates a TracePoint and enables it only for the target instruction sequence:
1
2
3
4
5
6
7
8
9
10
11
12
class ISeqBreakpoint < Breakpoint
def setup
@tp = TracePoint.new(*@events) do |tp|
delete if @oneshot
suspend
end
end
def enable
@tp.enable(target: @iseq)
end
end
Because the hook is scoped to the ISeq, code that never reaches a breakpoint pays essentially nothing. The old set_trace_func-based lib/debug.rb enabled a process-wide hook, which is why it was unusable in production-like code paths.
The other mechanisms are intentionally more expensive, and are only active while they are needed:
- Stepping installs a temporary
:line/:returnTracePoint scoped to the current thread (target_thread:) and disables it again at the next suspension. b if: <expr>without a location creates aCheckBreakpoint: a process-wide:lineTracePoint that evaluates the condition on every line. The README calls this “super slow” for a reason.watch @ivarenables a process-wide:line/:return/:b_returnTracePoint that compares the instance variable on every event, which is why watchpoints should stay narrow.
So the fast path is a located breakpoint, and everything that must reason about every event is opt-in and explicitly documented as slow.
On top of that core, the three UI modules (UI_Base, UI_DAP, UI_CDP) share the same session and command layer, which is why setting a breakpoint from the console, from VS Code, or from Chrome all behave the same. rdbg itself is thin: it converts CLI flags into environment variables and lets Ruby do the rest.
Cheatsheet
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
# start
rdbg app.rb launch under the debugger
rdbg -c -- bin/rails server debug an executable
rdbg --open --nonstop app.rb remote debuggee, keep running
rdbg -A [socket|port] attach
RUBY_DEBUG_POSTMORTEM=1 ... inspect after a crash
# breakpoints
b 42 line
b app.rb:42
b Cart#total method
b 42 if: x > 3 conditional
b 42 do: 'info' run then continue
b 42 pre: 'p x' run then stop
b 42 path: /app/ path filter
catch RuntimeError exception
watch @total ivar watch
del 1 delete
# step
s / n / fin / until / c step/next/finish/until/continue
q / kill quit / terminate debuggee
# inspect
bt / l / whereami / edit
info locals | ivars | consts | threads | breakpoints
outline [expr] available API
display x / undisplay
f n / up / down frames
p / pp / eval evaluate
# trace and replay
trace call /trace line / trace exception / trace object x
trace ... into: file
trace off
record on / step back / step reset
# config
config set no_color true
config set skip_path /gems/
config set show_src_lines 15
References
- Source and full documentation: https://github.com/ruby/debug
rdbg --help,rdbg --version- Jekyll-style note: everything above was exercised with debug 1.11.1 on Ruby 3.3.8
- Migration guide: https://st0012.dev/from-byebug-to-ruby-debug
- Cheatsheet: https://st0012.dev/ruby-debug-cheatsheet