文章

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.

Debugging Ruby with ruby/debug: rdbg, Breakpoints, Tracing, and Remote Sessions

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?

Concernbyebugruby/debug
OwnershipThird-party gemOfficial gem under the ruby GitHub org
MechanismTracePoint-based, older internalsPer-ISeq breakpoints + C extension
Remote debuggingNot built inUNIX domain socket, TCP/IP, DAP, CDP
Editor supportLegacy RDP adaptersVS Code (DAP) and Chrome DevTools (CDP)
Record/replayNoYes (record, step back)
Frame inspectionvar local, var instanceinfo locals, info ivars, outline, display
ConsoleBasicReline 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 wantUseEquivalent to
Inline breakpoint, no wrapperrequire 'debug' + binding.breakrdbg --nonstop --no-sigint-hook
Launch under debugger, stop at startrdbg target.rbrequire 'debug/start', ruby -r debug/start
Open a remote port, stop at startrdbg --open target.rbrequire 'debug/open'
Open a remote port, keep runningrdbg --open --nonstop target.rbrequire '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. Typing foo.bar evaluates 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 explicit p, pp, or eval commands.
  • Enter repeats the last command. Convenient for repeated step.
  • Ctrl-D equals quit.

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 startCommand-linerequireAPI
yesrdbg --openrequire "debug/open"DEBUGGER__.open
nordbg --open --nonstoprequire "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 10 tries 12345, 12346, … until a port is free.
  • --host chooses the listening interface (default 127.0.0.1).
  • --cookie and --session-name help distinguish or secure multiple sessions.
  • RUBY_DEBUG_SKIP_BP=1 skips 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-rdbg extension, toggle breakpoints in the editor, then press F5. The extension launches your program with rdbg -c and talks DAP. You can also attach to an already-running process with rdbg --open=vscode target.rb or the open vscode console command.
  • Chrome DevTools: rdbg --open=chrome target.rb prints a devtools://... 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 varConfig nameDefaultEffect
RUBY_DEBUG_LOG_LEVELlog_levelWARNDebugger’s own log level
RUBY_DEBUG_SHOW_SRC_LINESshow_src_lines10Source lines shown on a breakpoint
RUBY_DEBUG_SHOW_SRC_LINES_FRAMEshow_src_lines_frame1Source lines on frame operations
RUBY_DEBUG_SHOW_FRAMESshow_frames2Frames shown on a breakpoint
RUBY_DEBUG_USE_SHORT_PATHuse_short_pathfalsePrint $(Gem)/foo.rb style paths
RUBY_DEBUG_NO_COLORno_colorfalseDisable colors (also via NO_COLOR)
RUBY_DEBUG_NO_SIGINT_HOOKno_sigint_hookfalseDo not suspend on SIGINT
RUBY_DEBUG_NO_RELINEno_relinefalseDo not use Reline (useful for pipes)
RUBY_DEBUG_NO_HINTno_hintfalseHide the REPL hint
RUBY_DEBUG_NO_LINENOno_linenofalseHide line numbers
RUBY_DEBUG_NO_REPEATno_repeatfalseDo not repeat the last command on Enter
RUBY_DEBUG_IRB_CONSOLEirb_consolefalseUse IRB as the console

Control

Env varConfig nameEffect
RUBY_DEBUG_SKIP_PATHskip_pathSkip frames from matching paths
RUBY_DEBUG_SKIP_NOSRCskip_nosrcSkip frames without source
RUBY_DEBUG_POSTMORTEMpostmortemEnter a postmortem session on an uncaught exception
RUBY_DEBUG_FORK_MODEfork_modeWhich process keeps the debugger after fork (both/parent/child)
RUBY_DEBUG_KEEP_ALLOC_SITEkeep_alloc_siteShow allocation sites with p/pp
RUBY_DEBUG_SIGDUMP_SIGsigdump_sigSigdump signal

Boot

Env varConfig nameEffect
RUBY_DEBUG_NONSTOPnonstopDo not stop at load
RUBY_DEBUG_STOP_AT_LOADstop_at_loadStop as soon as the debugger is loaded
RUBY_DEBUG_INIT_SCRIPTinit_scriptDebug-command script to load at first stop
RUBY_DEBUG_COMMANDScommandsCommands run at first stop, separated by ;;
RUBY_DEBUG_NO_RCno_rcIgnore ~/.rdbgrc
RUBY_DEBUG_HISTORY_FILEhistory_fileHistory file location
RUBY_DEBUG_SAVE_HISTORYsave_historyHistory size (default 10000)

Remote

Env varConfig nameEffect
RUBY_DEBUG_OPENopenSame as rdbg --open
RUBY_DEBUG_PORTportTCP port
RUBY_DEBUG_PORT_RANGEport_rangeNumber of ports to try
RUBY_DEBUG_HOSThostBind host (default 127.0.0.1)
RUBY_DEBUG_SOCK_PATHsock_pathUNIX socket path
RUBY_DEBUG_SOCK_DIRsock_dirUNIX socket directory
RUBY_DEBUG_LOCAL_FS_MAPlocal_fs_mapMap remote paths to local ones
RUBY_DEBUG_SKIP_BPskip_bpSkip breakpoints when no client is attached
RUBY_DEBUG_COOKIEcookieNegotiation cookie
RUBY_DEBUG_SESSION_NAMEsession_nameDistinguish multiple sessions

Other environment variables:

  • RUBY_DEBUG_ENABLE=0 disables the debugger entirely (useful to neutralize an inherited RUBYOPT).
  • RUBY_DEBUG_ADDED_RUBYOPT removes the injected -r debug/... from RUBYOPT in child processes.
  • RUBY_DEBUG_EDITOR or EDITOR selects the editor used by the edit command.
  • RUBY_DEBUG_BB=1 defines Kernel#bb as an alias of debugger.

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

Taskbyebugruby/debug
Insert a breakpointbyebugbinding.break / binding.b
Step in / over / outstep / next / finishstep / next / finish
Continuecontinuecontinue
Backtracewhere / btbt
Local variablesvar localinfo locals
Instance variablesvar instanceinfo ivars
Evaluateeval / pp / pp / eval
Frame selectionframe nframe n, plus up / down
List sourcelistlist
Watch an expressiondisplaydisplay
Catch an exceptioncatch Exceptioncatch Exception
Threadsthread listinfo threads / thread
Quitquitquit / kill
Restartrestartno 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.

FileRole
exe/rdbgCLI 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.rbThe singleton DEBUGGER__::SESSION (~2,700 lines): command registry, prompt loop, SIGINT handling, fork/daemon interception, IRB integration, preset commands.
lib/debug/thread_client.rbPer-thread debugging state: stepping, frame handling, and the recorder used by record / step back.
lib/debug/breakpoint.rbBreakpoint subclasses: ISeqBreakpoint, LineBreakpoint, CatchBreakpoint, CheckBreakpoint, WatchIVarBreakpoint, MethodBreakpoint.
lib/debug/tracer.rbLineTracer, CallTracer, ExceptionTracer, ObjectTracer.
lib/debug/server.rb, server_dap.rb, server_cdp.rbProtocol adapters: the plain socket protocol, VS Code’s Debug Adapter Protocol, and Chrome’s DevTools Protocol.
lib/debug/config.rbThe CONFIG_SET table that gives every option both an env var and a config name.
ext/debug/debug.c, iseq_collector.cC 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/:return TracePoint scoped to the current thread (target_thread:) and disables it again at the next suspension.
  • b if: <expr> without a location creates a CheckBreakpoint: a process-wide :line TracePoint that evaluates the condition on every line. The README calls this “super slow” for a reason.
  • watch @ivar enables a process-wide :line/:return/:b_return TracePoint 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

本文由作者按照 CC BY 4.0 进行授权