Programming Search⌘K

Conceptcore

Interactive debugging

Also called debugger, breakpoint, watchpoint, stepping, backtrace, gdb, lldb, pdb, Delve, jdb.

A debugger stops a running program at a breakpoint, runs it one step at a time, and shows its stack and variables. It controls the process through the operating system and reads debug information.

Applies to
core-languages

Idea

A program gives a wrong result, and the code looks correct. The developer must see what the program does, not what the code seems to say. A debugger runs the program under its control. It stops the program at a chosen place, shows the values of the variables and the chain of calls, and lets the program continue one step at a time.

The DWARF introduction lists the common operations. The programmer sets a breakpoint at a line or a function. When the program reaches the breakpoint, the programmer displays variables and the call stack, which shows how the program arrived there. Then the programmer continues the program, or steps through it line by line, into called functions or over them.8

Interactive debugging has a cost: a person must be at the terminal. A breakpoint in a server stops all requests, and a session leaves no record. The other tools of this area answer different questions. Structured logging records what happened in a run that nobody watched. CPU profiling measures where the time goes. Delta debugging reduces a failing input before anybody opens a debugger. A debugger is for the moment when the developer has a failing case and needs to see the state at one point in it.

How it works

Breakpoints

A breakpoint is a place in the program where the user wants to regain control. GDB names two ways to make one.5

  • A hardware breakpoint uses a dedicated register of the processor. The debugger stores the address in the register. When the program counter matches it, the processor raises an exception. The registers are few, so GDB uses software breakpoints when the user asks for more.5
  • A software breakpoint changes the program. GDB replaces an instruction with a trap or another instruction that causes an exception. When the program reaches it, GDB takes the exception and stops the program. To continue, GDB puts back the original instruction, executes one instruction, puts the trap in again and continues.5

A software breakpoint writes into the code, so the code must be in writable memory. The technique does not work for a program in ROM.5 The trap instruction must also be short. A long trap could cover the start of the next instruction, and a jump to that instruction would land in the middle of the trap.5

A conditional breakpoint stops only when an expression is true. In GDB, break … if cond evaluates the condition each time the program reaches the breakpoint and stops if the value is nonzero.1 The program still stops at the trap each time. The debugger evaluates the condition and continues the program when the condition is false.

Stepping

A stop at a breakpoint is the start. From there, the user moves through the code in steps of different sizes. GDB has these commands:2

Command What it runs before it stops
step (s) until control reaches a different source line, also inside a called function
next (n) to the next line in the current frame; calls on the line run without a stop
finish until the function of the selected frame returns; prints the returned value
until like next, but at a jump it continues until it passes the jump, so it runs a loop to its end
stepi (si) one machine instruction

A step at the level of a source line is many machine instructions. The debugger needs a map from addresses to lines to know where a line ends. That map is the line number table of the debug information (see below).

Watchpoints

A watchpoint stops the program when a value changes, wherever the change happens. It answers the question "who wrote this variable?" GDB makes a software watchpoint when it has no other choice. It single-steps the program and tests the value after each step, which is hundreds of times slower than normal execution. Most x86 and PowerPC targets have hardware watchpoints, which do not slow down the program.3 rwatch stops when the program reads a value, and awatch stops on a read or a write. They need hardware support.3

Inspecting the stack

A backtrace is a summary of how the program got where it is. It shows one line for each frame. Frame zero is the frame that runs now, frame one is its caller, and so on up the stack.4 The user selects a frame with up and down and prints the local variables of that frame.15 In the pdb example, up moves from total to checkout, and p cart[1]["name"] reads a variable that only checkout has.

A session

The commands are similar across debuggers. This table lists the forms that the manuals give.

Action gdb lldb pdb Delve node inspect
set a breakpoint break total 1 b main 10 break total 11 break main.total 15 sb('main.js', 16) 22
with a condition break 30 if price > 100 1 breakpoint set --name foo --condition '…' 10 break 30, price > 100 11 break 30 if price > 100 15
step into step s step step step
step over next n next next next
step out finish finish return stepout out
show the stack backtrace bt where stack backtrace
stop on a write watch total 3 watchpoint set variable total 10 watch -w total 15

The manuals of pdb and of the Node debugger list no watchpoint command. pdb's display prints an expression each time the program stops in the frame and the value has changed.11 The Node debugger evaluates its watch expressions at each breakpoint and shows them.22

How a debugger works

Control of the process: ptrace

A debugger is a separate process. It needs a way to stop another process, read its memory and registers, and change them. On Unix, the system call for this is ptrace. The Linux manual says that ptrace lets the tracer observe and control the execution of the tracee, and examine and change the tracee's memory and registers. It is primarily used to implement breakpoint debugging and system call tracing.6

The steps are these:6

  1. The debugger forks. The child calls PTRACE_TRACEME and then execve with the program. Or the debugger attaches to a running process with PTRACE_ATTACH or PTRACE_SEIZE.
  2. The tracee stops each time a signal is delivered. The tracer learns this from its next call to waitpid.
  3. While the tracee is stopped, the tracer reads and writes its memory with PTRACE_PEEKTEXT and PTRACE_POKETEXT, and reads its registers with PTRACE_GETREGS.
  4. The tracer restarts the tracee with PTRACE_CONT, or with PTRACE_SINGLESTEP for one instruction. After the single step, the tracee appears stopped by SIGTRAP.

A software breakpoint is step 3 and step 4 together. PTRACE_POKETEXT writes the trap. The trap raises a signal, and the signal stops the tracee. Attachment is per thread on Linux. In a process with many threads, each thread is attached on its own.6

The design is old. The ptrace page of the Sixth Edition of Unix gives the same model: a parent process controls a child, examines and changes its core image, and its primary use is breakpoint debugging. The traced child stops at a signal, and the parent learns of it through wait. That version had nine requests and no single step. Its BUGS section asks for a way to stop the child at each system call.7

Meaning of the bytes: debug information

ptrace gives addresses and bytes. The user thinks in files, lines, functions and variables. The compiler writes debug information that maps one to the other, and DWARF is a common format for it. The DWARF introduction says that the debugger must reverse much of the transformation that the compiler made.8 Three parts of DWARF do most of the work:8

  • Debugging information entries (DIEs) describe the program. Each DIE has a tag, such as a subprogram or a variable, and attributes such as the name, the type and the location. A location expression gives the place of a variable. A stack machine evaluates it, so a variable can be in a register, or at an offset from the frame base.
  • The line number table maps each address of code to a file, a line and a column. To set a breakpoint at a line, the debugger looks up the address in the table and stores the breakpoint instruction there. After a fault, the debugger looks up the address of the fault to find the line.
  • Call frame information (CFI) tells the debugger how each function was called. With it, the debugger finds the frame of the caller and the arguments. The debugger uses it to unwind the stack and print the backtrace.

A program compiled without debug information has none of this. GDB can still stop the process, but it cannot map an address to a line, and step goes on until it reaches a function that has debug information.2 Compilers write the information with -g.9 In Rust, -g is the same as -C debuginfo=2, and without a flag rustc writes no debug information.26 The Go linker writes DWARF by default, and the flag -ldflags=-w leaves it out.14

Debuggers of a virtual machine

A program on the JVM, in Python or in V8 is not a process that the debugger reads byte by byte. The virtual machine has a debugging interface of its own. The Java Platform Debugger Architecture has three layers. JVM TI defines the debugging services of the VM. JDWP defines the protocol between the debuggee and the debugger processes. JDI is a Java interface for the authors of debuggers.19 A debugger can connect at any layer.19 jdb, the command-line debugger of the JDK, demonstrates this architecture.18 pdb runs inside the Python process that it debugs. Node starts the V8 inspector, and a client connects to it on port 9229 of 127.0.0.1.22

In languages

LanguageVerdictNote
PythonStandard library
C++Library
JavaStandard library
CLibrary
C#Library
JavaScriptNative
TypeScriptNative
GoLibrary
RustLibrary
KotlinStandard libraryKotlin on the JVM runs under the same debuggers as Java, through the Java Platform Debugger Architecture of the JDK; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query has no call stack to step through; the database server explains the plan of a query instead.
BashIdiomSet -x prints each command and its arguments as the shell runs it, which traces a script without a debugger; the page has no example of it.
PowerShellStandard libraryThe Set-PSBreakpoint cmdlet sets line, command and variable breakpoints, and the prompt changes to DBG at a breakpoint; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup does not run code; the debugger of a browser stops in the scripts of a page, not in the markup.
CSSDoes not applyA style sheet does not run code to stop at.
Regular expressionsDoes not applyA pattern has no statements to stop at.
Language Verdict Form
Python stdlib pdb, breakpoint() and sys.breakpointhook; faulthandler and traceback print the stack
Java stdlib jdb and JPDA in the JDK; StackWalker in the code
Kotlin stdlib the JVM debuggers, as in Java
JavaScript native the debugger statement; node inspect and the V8 inspector
TypeScript native the debugger statement of JavaScript
Go library Delve outside the toolchain; runtime.Breakpoint, runtime.CallersFrames and runtime/debug.Stack in the code
C library gdb or lldb; __func__ and __LINE__ for manual traces
C++ library gdb or lldb; std::source_location
Rust library gdb or lldb; std::backtrace
C# library an external debugger; System.Diagnostics.Debugger and StackTrace in the code
PowerShell stdlib Set-PSBreakpoint
Bash idiom set -x traces each command
SQL, Regex, HTML, CSS n/a no statements to stop at

The examples on this page cannot type commands into a debugger. Each example shows instead the hook that a debugger uses, or the part of the work that a program can do itself: print its own stack.

Python

pdb supports conditional breakpoints, single steps at the level of source lines, inspection of stack frames and post-mortem debugging.11 python -m pdb script.py runs a script under the debugger. When the script exits with an error, pdb enters post-mortem debugging.11 breakpoint() in the code calls sys.breakpointhook. By default, the hook calls pdb.set_trace(). If the environment variable PYTHONBREAKPOINT is 0, the hook returns at once. Another value names a function to call instead.12 The Python example replaces the hook with a function that prints the stack and the local variables and returns.

pdb reads its commands from any file object. The example gives it the commands in a string and records a full session. A command name that is also a variable name is a trap: n is next, not the variable n. The ! prefix runs a line as a Python statement, and it is necessary when the first word resembles a command.11

faulthandler dumps the Python stack on a fault, after a timeout, on a user signal, or on request. It is written in C and uses only signal-safe functions, so it works after a crash or in a deadlock. It prints only the file, the function and the line, and at most 100 frames.13

Java and Kotlin

A JVM starts with the JDWP agent, for example java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n MyClass. Then jdb -attach 8000 connects to it. stop at MyClass:22 and stop in java.lang.String.length set breakpoints. step goes to the next line, also in a called method, and next stays in the current frame.18 A debugger, such as the one in an IDE, can hook into JPDA at any of the three layers.19 In the code, StackWalker walks the frames of the current thread. By default, a frame has the names but not the Class object, and getDeclaringClass throws UnsupportedOperationException.20

JavaScript and TypeScript

JavaScript has a statement for this. The specification says that evaluating debugger may cause a breakpoint when the program runs under a debugger, and that it has no observable effect when no debugger is present or active.23 node inspect script.js starts the command-line client of Node. node --inspect-brk stops before the first line and waits for a client such as Chrome DevTools.22 TypeScript has the same statement, and the TypeScript example runs under Node with it. In V8, error.stack holds the topmost 10 frames by default. Error.stackTraceLimit changes the number, and Infinity collects all frames.24

Go

The Go documentation calls Delve a better alternative to GDB for programs that the standard toolchain builds. GDB does not understand Go programs well. The stack management, the threads and the runtime of Go differ from the model that GDB expects.14 Delve has commands for goroutines, conditional breakpoints, watchpoints and reverse execution with rev.15 The compiler inlines functions and keeps variables in registers. go build -gcflags=all="-N -l" turns these optimizations off for a debugging session.14 In the code, runtime.Breakpoint executes a breakpoint trap, runtime.CallersFrames reads the stack with inlined calls, and debug.Stack formats the stack of the calling goroutine.1617

C, C++ and Rust

These languages compile to machine code, and gdb and lldb debug them through ptrace and DWARF as described above. The lldb project keeps a map of each gdb command to its lldb form.10 The standard libraries of C and C++ do not walk the stack. A macro with __func__ and __LINE__ records where it was used. In C++, std::source_location::current() as a default argument gives the place of the call.29 Rust has std::backtrace. Backtrace::capture records a trace only when RUST_BACKTRACE or RUST_LIB_BACKTRACE is set. Backtrace::force_capture records one in all cases.25

C#

The .NET debugger is outside the program. Debugger.IsAttached tells if a debugger is attached to the process.28 Debugger.Break signals a breakpoint to an attached debugger. If no debugger is attached, the user is asked to attach one. The documentation also says that the runtime reports an error to Windows Error Reporting, and that its settings change what happens.27 The example checks IsAttached before it calls Break.

IDE debuggers

An IDE shows breakpoints, values and the stack in the editor. Without a common protocol, each development tool must build this interface again for each debugger.21 The Debug Adapter Protocol defines one protocol between a development tool and a debugger. A debug adapter translates between the protocol and the API of a debugger or runtime.21 The JVM gives IDEs the layers of JPDA.19

PythonGitHub
def double(x):
    breakpoint()  # pdb stops here and waits for commands
    return x * 2


print(double(21))

The program above stops at breakpoint() and waits for a person to type commands. A page cannot record that session. The next program gives the same commands to pdb from a string. The subclass of pdb.Pdb echoes each command, so the output reads like a session at a terminal.

import io
import os
import pdb
import sys


class Script(pdb.Pdb):
    """A Pdb that reads its commands from a string and echoes each one."""

    def __init__(self, commands):
        super().__init__(stdin=io.StringIO(commands), stdout=ShortPaths(), nosigint=True, readrc=False)
        self.use_rawinput = False

    def precmd(self, line):
        if not line.startswith("_"):  # skip the internal commands of pdb
            self.stdout.write(line + "\n")
        return super().precmd(line)


class ShortPaths(io.TextIOBase):
    """Writes to standard output and removes the directory from file paths."""

    def write(self, text):
        return sys.stdout.write(text.replace(os.path.dirname(os.path.abspath(__file__)) + os.sep, ""))


def total(prices):
    result = 0
    for price in prices:
        result += price
    return result


def checkout(cart):
    prices = [item["price"] for item in cart]
    return total(prices)


commands = """\
break total
continue
p prices
next
display result
next
next
break 30, price > 100
continue
p price, result
up
p cart[1]["name"]
continue
"""
cart = [{"name": "apple", "price": 30}, {"name": "bread", "price": 250}]
print("total:", Script(commands).runcall(checkout, cart))
Output
> main.py(35)checkout()
-> prices = [item["price"] for item in cart]
(Pdb) break total
Breakpoint 1 at main.py:28
(Pdb) continue
> main.py(28)total()
-> result = 0
(Pdb) p prices
[30, 250]
(Pdb) next
> main.py(29)total()
-> for price in prices:
(Pdb) display result
display result: 0
(Pdb) next
> main.py(30)total()
-> result += price
(Pdb) next
> main.py(29)total()
-> for price in prices:
display result: 30  [old: 0]
(Pdb) break 30, price > 100
Breakpoint 2 at main.py:30
(Pdb) continue
> main.py(30)total()
-> result += price
(Pdb) p price, result
(250, 30)
(Pdb) up
> main.py(36)checkout()
-> return total(prices)
(Pdb) p cart[1]["name"]
'bread'
(Pdb) continue
total: 280

break total stops at the first line of total. next runs one line and stays in the function. display result prints result again each time the value changes. break 30, price > 100 stops on line 30 only when the condition is true. up moves to the frame of the caller, where cart is visible.

Commands of pdb have short names. A variable with the same name as a command does not print. pdb runs the command.

This code runs but gives a wrong answer on purpose.

import io
import os
import pdb
import sys


class Script(pdb.Pdb):
    """A Pdb that reads its commands from a string and echoes each one."""

    def __init__(self, commands):
        super().__init__(stdin=io.StringIO(commands), stdout=ShortPaths(), nosigint=True, readrc=False)
        self.use_rawinput = False

    def precmd(self, line):
        if not line.startswith("_"):  # skip the internal commands of pdb
            self.stdout.write(line + "\n")
        return super().precmd(line)


class ShortPaths(io.TextIOBase):
    """Writes to standard output and removes the directory from file paths."""

    def write(self, text):
        return sys.stdout.write(text.replace(os.path.dirname(os.path.abspath(__file__)) + os.sep, ""))


def average(values):
    n = len(values)
    s = sum(values)
    return s / n


# The person wants to see the variables n and s. But n is the command next,
# and s is the command step: pdb runs them and prints no value.
commands = """\
next
next
n
s
p n, s
continue
"""
print("average:", Script(commands).runcall(average, [3, 4, 8]))
Output
> main.py(28)average()
-> n = len(values)
(Pdb) next
> main.py(29)average()
-> s = sum(values)
(Pdb) next
> main.py(30)average()
-> return s / n
(Pdb) n
--Return--
> main.py(30)average()->5.0
-> return s / n
(Pdb) s
average: 5.0

n ran one more line and s stepped out of the function, so the program ended before p n, s. The fix is p n, or !n, which runs the text as a Python statement.

breakpoint() calls sys.breakpointhook. A program can put its own function in that hook. The next hook prints the stack and the local variables and then returns, so the program continues.

import sys
import traceback


def show_frame(*args, **kwargs):
    """A breakpoint hook that prints the stack and the locals, then returns."""
    caller = sys._getframe(1)
    for frame in traceback.extract_stack(caller):
        print(f"  {frame.name} line {frame.lineno}: {frame.line}")
    print("  locals:", caller.f_locals)


def total(prices):
    result = 0
    for price in prices:
        result += price
        if price > 100:
            breakpoint()  # calls sys.breakpointhook
    return result


sys.breakpointhook = show_frame
print("total:", total([30, 250]))
Output
  <module> line 23: print("total:", total([30, 250]))
  total line 18: breakpoint()  # calls sys.breakpointhook
  locals: {'prices': [30, 250], 'result': 280, 'price': 250}
total: 280

faulthandler prints the stack of Python frames with code in C. It works after a crash, when Python code can no longer run. dump_traceback prints the same stack on request.

import faulthandler
import os

# faulthandler writes to a file descriptor without Python's I/O, so that it
# still works after a crash or in a deadlock. Here it writes to a pipe, and the
# program removes the directory from the file names before it prints them.


def dump():
    read_end, write_end = os.pipe()
    with os.fdopen(write_end, "w") as out:
        faulthandler.dump_traceback(file=out, all_threads=False)
    with os.fdopen(read_end) as pipe:
        text = pipe.read()
    print(text.replace(os.path.dirname(os.path.abspath(__file__)) + os.sep, ""), end="")


def load(path):
    dump()


def main():
    load("orders.csv")


main()
Output
Stack (most recent call first):
  File "main.py", line 12 in dump
  File "main.py", line 19 in load
  File "main.py", line 23 in main
  File "main.py", line 26 in <module>
  • Verdict: stdlib. pdb is a module of the standard library. python -m pdb script.py runs a script under it, and breakpoint() starts it from the code.
  • PYTHONBREAKPOINT=0 turns every breakpoint() call into a call that does nothing. Another dotted name selects another debugger.
  • python -X faulthandler or PYTHONFAULTHANDLER turns on faulthandler for a crash: the program prints the stack on SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL.
  • traceback.extract_stack gives the same frames as Python objects. traceback.print_stack prints them.
#include <print>
#include <source_location>
#include <string_view>

// A default argument of type std::source_location is evaluated at the call
// site, so trace() reports the line and the function of its caller.
void trace(std::string_view note, std::source_location here = std::source_location::current()) {
    std::println("  line {} in {}: {}", here.line(), here.function_name(), note);
}

int price(std::string_view item) {
    if (item == "bread") {
        trace("found bread");
        return 250;
    }
    return 30;
}

int main() {
    int sum = price("apple") + price("bread");
    trace("done");
    std::println("total: {}", sum);
}
Output
  line 13 in int price(std::string_view): found bread
  line 21 in int main(): done
total: 280
  • Verdict: library. As in C, the program runs under gdb or lldb. The standard library gives std::source_location to record a place in the source.
  • The text of function_name() depends on the compiler. The example prints the signature, but another compiler may print only the name.
  • std::source_location::current() in a default argument gives the place of the call, not the place of the declaration.
JavaGitHub
import java.lang.management.ManagementFactory;
import java.util.List;

public class Main {
    // The frames of this class on the stack, innermost first: method and line.
    static List<String> whereAmI() {
        return StackWalker.getInstance().walk(frames -> frames
            .skip(1) // skip whereAmI itself
            .filter(f -> f.getClassName().equals("Main"))
            .map(f -> f.getMethodName() + " line " + f.getLineNumber())
            .toList());
    }

    static int price(String item) {
        if (item.equals("bread")) {
            System.out.println("  " + String.join(" <- ", whereAmI()));
            return 250;
        }
        return 30;
    }

    static int total(List<String> cart) {
        int sum = 0;
        for (String item : cart) {
            sum += price(item);
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println("total: " + total(List.of("apple", "bread")));

        // A debugger connects through the JDWP agent, which the JVM loads
        // with an option such as -agentlib:jdwp=transport=dt_socket,server=y
        boolean agent = ManagementFactory.getRuntimeMXBean().getInputArguments().stream()
            .anyMatch(arg -> arg.startsWith("-agentlib:jdwp"));
        System.out.println("JDWP agent loaded: " + agent);
    }
}
Output
  price line 16 <- total line 25 <- main line 31
total: 280
JDWP agent loaded: false

A StackWalker made without options does not keep the Class object of each frame. It keeps only the names.

This code raises UnsupportedOperationException, on purpose.

public class Main {
    public static void main(String[] args) {
        // Without the option RETAIN_CLASS_REFERENCE, a StackFrame does not
        // keep the Class object, and getDeclaringClass throws.
        StackWalker walker = StackWalker.getInstance();
        walker.forEach(frame -> System.out.println(frame.getDeclaringClass().getName()));
    }
}

The fix is StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE), or getClassName() when the name is enough.

  • Verdict: stdlib. The JDK ships jdb, a command-line debugger, and the Java Platform Debugger Architecture that IDE debuggers use.
  • java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n Main starts a program that a debugger can attach to. jdb -attach 8000 attaches to the port.
#include <stdio.h>
#include <string.h>

// C has no way to walk the stack in its standard library. A macro can record
// where it was used: the compiler fills in __func__ and __LINE__ at each use.
#define TRACE(fmt, ...) fprintf(stdout, "  %s line %d: " fmt "\n", __func__, __LINE__, __VA_ARGS__)

static int price(const char *item) {
    if (strcmp(item, "bread") == 0) {
        TRACE("item=%s", item);
        return 250;
    }
    return 30;
}

static int total(const char *cart[], int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += price(cart[i]);
        TRACE("i=%d sum=%d", i, sum);
    }
    return sum;
}

int main(void) {
    const char *cart[] = {"apple", "bread"};
    printf("total: %d\n", total(cart, 2));
}
Output
  total line 20: i=0 sum=30
  price line 10: item=bread
  total line 20: i=1 sum=280
total: 280
  • Verdict: library. The C standard library has no debugger and no way to walk the stack. A native debugger such as gdb or lldb runs the program, and the compiler writes the debug information with -g.
  • __func__ is the name of the enclosing function. __LINE__ is the current line of the source. Both are standard.
  • The trace of price comes before the second trace of total, because price runs inside the expression on line 19.
using System.Diagnostics;

Console.WriteLine($"total: {Shop.Total(["apple", "bread"])}");

// Debugger.Break() would stop here under a debugger. Without one, the program
// checks first, because Break can start a dialog or a crash report.
Console.WriteLine($"debugger attached: {Debugger.IsAttached}");
if (Debugger.IsAttached)
{
    Debugger.Break();
}

static class Shop
{
    public static int Total(string[] cart) => cart.Sum(Price);

    public static int Price(string item)
    {
        if (item == "bread")
        {
            Console.WriteLine("  " + string.Join(" <- ", WhereAmI()));
            return 250;
        }
        return 30;
    }

    // The frames of this class on the stack, innermost first.
    static IEnumerable<string> WhereAmI() =>
        new StackTrace(1) // skip WhereAmI itself
            .GetFrames()
            .Select(DiagnosticMethodInfo.Create)
            .Where(method => method?.DeclaringTypeName == "Shop")
            .Select(method => method!.Name);
}
Output
  Price <- Total
total: 280
debugger attached: False
  • Verdict: library. The debugger of .NET is a tool outside the program, such as the debugger of an IDE. System.Diagnostics.Debugger lets the code talk to it.
  • Debugger.Break signals a breakpoint to an attached debugger. When no debugger is attached, it can ask the user to attach one, so the example checks Debugger.IsAttached first.
  • StackTrace gives the frames of the current thread. DiagnosticMethodInfo gives the name of the method of a frame for logs.
JavaScriptGitHub
const inspector = require("node:inspector");

// The frames of this file on the stack, innermost first, without the paths.
// A line of a V8 stack trace reads "at name (file:line:column)".
function whereAmI() {
  const lines = new Error().stack.split("\n").slice(2); // skip the message and whereAmI
  return lines
    .map((line) => line.match(/at (\S+) \((.*):(\d+):\d+\)$/))
    .filter((match) => match !== null && match[2] === __filename)
    .map(([, name, , line]) => `${name} line ${line}`);
}

function price(item) {
  if (item === "bread") {
    debugger; // stops here under a debugger; does nothing without one
    console.log("  " + whereAmI().join(" <- "));
    return 250;
  }
  return 30;
}

function total(cart) {
  return cart.reduce((sum, item) => sum + price(item), 0);
}

console.log("total:", total(["apple", "bread"]));
// inspector.url() returns undefined when no inspector is listening.
console.log("inspector url:", inspector.url());
Output
  price line 16 <- total line 23 <- Object.<anonymous> line 26
total: 280
inspector url: undefined

V8 keeps a fixed number of frames in the stack of an error. A deep chain of calls loses its start.

This code runs but gives a wrong answer on purpose.

// A recursive parser fails deep in the input. V8 keeps only the top 10
// frames of a stack trace by default, so the start of the chain is lost.
function parse(depth) {
  if (depth === 0) {
    throw new Error("unexpected end of input");
  }
  return parse(depth - 1);
}

try {
  parse(15);
} catch (err) {
  const frames = err.stack.split("\n").slice(1);
  console.log("frames in the trace:", frames.length);
  console.log("frames of parse:", frames.filter((f) => f.includes("at parse")).length);
}
Output
frames in the trace: 10
frames of parse: 10

The call chain had 16 frames of parse and one more for the top level, but the trace kept 10. The fix is Error.stackTraceLimit = Infinity before the error is made, or the --stack-trace-limit option of V8.

  • Verdict: native. The debugger statement is part of the language. It stops the program when a debugger is active and has no effect otherwise.
  • node inspect script.js starts the command-line debugger of Node. node --inspect-brk script.js stops at the first line and waits for a client such as Chrome DevTools.
  • The node:inspector module opens and closes the inspector from the code. inspector.url() returns undefined when it is closed.
TypeScriptGitHub
// The frames of this file on the stack, innermost first. Node removes the
// types and keeps each line where it was, so the line numbers in a stack
// trace are the line numbers of this TypeScript file.
interface Frame {
  name: string;
  line: number;
}

function whereAmI(): Frame[] {
  const lines: string[] = (new Error().stack ?? "").split("\n").slice(2);
  const frames: Frame[] = [];
  for (const text of lines) {
    const match = text.match(/at (\S+) \((.*):(\d+):\d+\)$/);
    if (match !== null && match[2] === import.meta.url) {
      frames.push({ name: match[1], line: Number(match[3]) });
    }
  }
  return frames;
}

type Item = "apple" | "bread";

function price(item: Item): number {
  if (item === "bread") {
    debugger; // a breakpoint under a debugger; no effect without one
    for (const frame of whereAmI()) {
      console.log(`  ${frame.name} line ${frame.line}`);
    }
    return 250;
  }
  return 30;
}

function total(cart: Item[]): number {
  let sum = 0;
  for (const item of cart) {
    sum += price(item);
  }
  return sum;
}

console.log("total:", total(["apple", "bread"]));
Output
  price line 26
  total line 37
total: 280
  • Verdict: native. TypeScript has the debugger statement of JavaScript, and the program runs under the debugger of its JavaScript engine.
  • Node runs this file after it removes the types. The line numbers in the trace match the TypeScript source, so no source map is needed.
  • The module is an ES module, so a stack frame names the file with a file: URL. The example compares it with import.meta.url.
package main

import (
	"bytes"
	"fmt"
	"runtime"
	"runtime/debug"
	"strings"
)

// where returns the calls that led to its caller, one per line, without the
// file paths and addresses that change from one machine to another.
func where() []string {
	pcs := make([]uintptr, 16)
	n := runtime.Callers(2, pcs) // skip runtime.Callers and where
	frames := runtime.CallersFrames(pcs[:n])
	var lines []string
	for {
		frame, more := frames.Next()
		if strings.HasPrefix(frame.Function, "main.") {
			lines = append(lines, fmt.Sprintf("%s line %d", frame.Function, frame.Line))
		}
		if !more {
			return lines
		}
	}
}

func price(item string) int {
	if item == "bread" {
		for _, line := range where() {
			fmt.Println("  " + line)
		}
		return 250
	}
	return 30
}

func total(cart []string) int {
	sum := 0
	for _, item := range cart {
		sum += price(item)
	}
	return sum
}

func main() {
	fmt.Println("total:", total([]string{"apple", "bread"}))

	// debug.Stack formats the stack as a panic does: a goroutine header,
	// then a function and a file:line for each frame.
	stack := debug.Stack()
	header, _, _ := bytes.Cut(stack, []byte("\n"))
	fmt.Println(string(header))
	fmt.Println("mentions main.main:", bytes.Contains(stack, []byte("main.main()")))
}
Output
  main.price line 31
  main.total line 42
  main.main line 48
total: 280
goroutine 1 [running]:
mentions main.main: true

runtime.CallersFrames turns program counters into frames. It also gives a frame for each call that the compiler inlined. runtime.FuncForPC looks at one program counter and cannot do this.

package main

import (
	"fmt"
	"runtime"
	"strings"
)

// names looks up each program counter with FuncForPC. The documentation of
// runtime.Callers advises against this: FuncForPC cannot see inlined calls.
func names() []string {
	pcs := make([]uintptr, 16)
	n := runtime.Callers(2, pcs)
	var out []string
	for _, pc := range pcs[:n] {
		name := runtime.FuncForPC(pc).Name()
		if strings.HasPrefix(name, "main.") {
			out = append(out, name)
		}
	}
	return out
}

func lookup(item string) []string { return names() } // small: the compiler inlines it

func checkout() []string { return lookup("bread") }

func main() {
	fmt.Println(strings.Join(checkout(), " <- "))
}

The compiler inlines lookup and checkout into main. For the program counter of an inlined call, the name that FuncForPC gives depends on the compiler and on the architecture. With one Go release, this program can print the right chain on one machine and a chain with a missing or repeated function on another. So the output is not shown here. The fix is runtime.CallersFrames, as in the first example.

  • Verdict: library. Delve (dlv) is the debugger for Go, and it is not part of the Go distribution. The Go documentation says that GDB does not understand Go programs well.
  • runtime.Breakpoint() executes a breakpoint trap. Under a debugger, the program stops there.
  • debug.Stack returns the stack of the current goroutine as text. debug.PrintStack writes it to standard error.
  • go build -gcflags=all="-N -l" turns off optimizations and inlining, so the debugger sees each variable and each call.
RustGitHub
use std::backtrace::{Backtrace, BacktraceStatus};

/// Returns the names of the functions of this program on the stack,
/// innermost first, without addresses and file paths.
fn where_am_i() -> Vec<String> {
    let trace = Backtrace::force_capture(); // ignores RUST_BACKTRACE
    trace
        .to_string()
        .lines()
        .filter_map(|line| line.trim().split_once(": ").map(|(_, name)| name.to_string()))
        .filter(|name| name.starts_with("main::"))
        .collect()
}

#[inline(never)]
fn price(item: &str) -> u32 {
    if item == "bread" {
        println!("  {}", where_am_i().join(" <- "));
        return 250;
    }
    30
}

#[inline(never)]
fn total(cart: &[&str]) -> u32 {
    cart.iter().map(|item| price(item)).sum()
}

fn main() {
    println!("total: {}", total(&["apple", "bread"]));
    let status = Backtrace::force_capture().status();
    println!("captured: {}", status == BacktraceStatus::Captured);
}
Output
  main::where_am_i <- main::price <- main::total::{closure#0} <- main::total <- main::main
total: 280
captured: true

Backtrace::capture reads the environment first. When RUST_BACKTRACE and RUST_LIB_BACKTRACE are not set, it records nothing.

This code runs but gives a wrong answer on purpose.

use std::backtrace::Backtrace;

fn price(item: &str) -> u32 {
    if item == "bread" {
        // capture() reads RUST_BACKTRACE and RUST_LIB_BACKTRACE. When neither
        // is set, it captures nothing, and the trace is empty.
        let trace = Backtrace::capture();
        println!("status: {:?}", trace.status());
        println!("trace: {trace}");
        return 250;
    }
    30
}

fn main() {
    let total: u32 = ["apple", "bread"].iter().map(|item| price(item)).sum();
    println!("total: {total}");
}
Output
status: Disabled
trace: disabled backtrace
total: 280

The program asked for a trace and printed an empty one. Use Backtrace::force_capture when the trace must be there, or set RUST_BACKTRACE=1.

  • Verdict: library. The Rust standard library has no debugger. A native debugger such as gdb or lldb runs the program, and std::backtrace prints the stack from the code.
  • rustc -g is the same as -C debuginfo=2: full debug information for the debugger. Without a flag, rustc writes no debug information.
  • The names in a trace depend on the optimization level. The closure in total has a frame of its own only when the compiler does not inline it.

Post-mortem debugging

A debugger can also examine a program that has already failed. python -m pdb enters post-mortem debugging when the program exits with an error, and the user inspects the frames of the exception.11 GDB can also inspect a core dump of a program that crashed.14

Printing the stack from the code

A program can print its own stack without a debugger: traceback in Python, debug.Stack in Go, StackWalker in Java, StackTrace in .NET, std::backtrace in Rust, Error().stack in JavaScript. The examples show each one. A printed stack is a record of one moment, so it fits in a log. See Structured logging and Exception.

Reverse execution

Delve's rev runs next, step, step-instruction and stepout backward, and rewind runs backward until a breakpoint or the start of the recorded history.15 The user goes to the failure and then back to the cause.

Pitfalls

Optimized code

The optimizer rearranges the code, and the debugger shows what is really there. The execution path may not match the source. A variable that the program defines but never uses does not exist in the compiled code.9 GDB suggests a build with -g alone when a problem with -g -O is in doubt.9 Go gives the flags -N -l for the same reason.14 The Rust example shows the effect on a backtrace: the closure in total has its own frame only when the compiler did not inline it.

Inlined calls in a stack walk

The Go documentation advises against a loop over the program counters that runtime.Callers returns, and against FuncForPC on them. Such code cannot account for inlining. For an inlined call, FuncForPC returns the innermost function but with the entry of the outermost function.16 The Go wrong example loses main.lookup from the chain. runtime.CallersFrames gives the correct frames.

A command that has the name of a variable

pdb runs a line as a command if the first word is a command. n, s, c, p and others are commands.11 The Python wrong example types n and s to see two variables. pdb runs next and step instead, and the program ends. p n or !n prints the variable.

A stack trace that is too short

V8 keeps 10 frames by default.24 In a deep recursion, the trace loses the frames where the chain started. The JavaScript wrong example has 16 frames of parse and the trace keeps 10. See Recursion.

A trace that was never captured

Backtrace::capture in Rust does nothing when the environment variables are not set.25 The Rust wrong example prints a disabled trace. The code looks correct, and the problem shows only when somebody needs the trace.

A breakpoint call in production code

A breakpoint() call or a debugger; statement left in the code stops the program under a debugger, or calls whatever function PYTHONBREAKPOINT names.12 Debugger.Break in .NET without an attached debugger asks the user to attach one.27 Guard such calls, or remove them before a release.

A watchpoint in software

A software watchpoint makes the program hundreds of times slower.3 In a program with many threads, a software watchpoint watches the expression in one thread only. GDB may not notice when another thread changes the value. A hardware watchpoint watches all threads.3 See Thread and Data race.

Cost

Until the program reaches a breakpoint, the breakpoint costs nothing: the trap or the register waits for the program counter.5 Hardware watchpoints do not slow down the program.3 Each stop at a software breakpoint costs a signal, a switch to the debugger and back, and a single step to pass the original instruction.56 A conditional breakpoint pays this cost at each pass, also when the condition is false. A software watchpoint single-steps the whole program.3

In Rust, the levels range from none to line tables only to full information.26 Go puts DWARF in its binaries unless the linker gets -w.14 Some things do not work as well with -g -O as with -g alone, and GDB suggests a build without optimization when in doubt.9 That build is a different program from the one that runs in production, and a bug that depends on the optimizer may not appear in it.

A captured stack costs time too. The Rust documentation warns that a capture can be expensive on some platforms.25 V8 keeps 10 frames by default so that the collection has no noticeable cost.24

History

The ptrace system call is in the Sixth Edition of the Unix Programmer's Manual. The page names breakpoint debugging as its primary use and lists the command cdb under SEE ALSO.7 The model of the call, with a parent that controls a stopped child, is still the model of Linux.6

Brian Russell developed DWARF at Bell Labs in 1988 for the C compiler and the sdb debugger of Unix System V Release 4. The Programming Languages Special Interest Group of Unix International documented it as DWARF Version 1 in 1992.8 Richard Stallman was the original author of GDB.30

References

  1. Debugging with GDB, Setting Breakpoints, section 5.1.1 (break, break … if cond)
  2. Debugging with GDB, Continuing and Stepping, section 5.2 (step, next, finish, until, stepi)
  3. Debugging with GDB, Setting Watchpoints, section 5.1.2 (software and hardware watchpoints, rwatch, awatch)
  4. Debugging with GDB, Backtraces, section 8.2 (the first paragraph)
  5. GDB wiki, Internals, Breakpoint Handling, the first section (hardware and software breakpoints)
  6. Linux manual page, ptrace(2), DESCRIPTION; PTRACE_TRACEME; PTRACE_PEEKTEXT; PTRACE_POKETEXT; PTRACE_GETREGS; PTRACE_SINGLESTEP
  7. Unix Programmer's Manual, Sixth Edition, ptrace(II), DESCRIPTION; requests 0 to 8; SEE ALSO; BUGS
  8. Michael J. Eager, Introduction to the DWARF Debugging Format, April 2012, Using a Debugger; DWARF 1, Unix SVR4 sdb and PLSIG; Debugging Information Entry; Location Expressions; Line Number Table; Call Frame Information
  9. Debugging with GDB, Debugging Optimized Code, section 11 (the first paragraphs)
  10. LLDB, GDB to LLDB command map, Breakpoint Commands; Watchpoint Commands; Execution Commands; Examining Variables; Examining Thread State
  11. Python documentation, pdb, The Python Debugger, the introduction; Command-line interface; Debugger commands (break, step, next, return, until, display, up, where, !)
  12. Python documentation, sys, System-specific parameters and functions, sys.breakpointhook
  13. Python documentation, faulthandler, Dump the Python traceback, the introduction; Dumping the traceback; Fault handler state
  14. Go documentation, Debugging Go Code with GDB, the note at the top; Introduction
  15. Delve documentation, Commands, break; condition; step; next; stepout; stack; goroutines; watch; rev
  16. Go standard library, package runtime, Breakpoint; Callers; CallersFrames; FuncForPC
  17. Go standard library, package runtime/debug, Stack; PrintStack
  18. Java SE 25 tool specifications, The jdb Command, Description; Start a JDB Session; Breakpoints; Stepping
  19. Java SE 25, Java Platform Debugger Architecture, Structure Overview, the diagram and the list of the three layers
  20. Java SE 25 API, java.lang.StackWalker, the class description; StackWalker.StackFrame.getDeclaringClass
  21. Debug Adapter Protocol, Overview, What is the Debug Adapter Protocol?
  22. Node.js documentation, Debugger, Interactive mode; Watchers; Command reference; V8 inspector integration for Node.js
  23. ECMAScript Language Specification, The debugger Statement, section 14.16.1, Runtime Semantics, Evaluation
  24. V8 documentation, Stack trace API, Basic stack traces; Error.stackTraceLimit
  25. Rust standard library, std::backtrace::Backtrace, capture; force_capture; disabled
  26. The rustc book, Codegen Options, debuginfo
  27. .NET API reference, Debugger.Break Method, the summary and the Remarks
  28. .NET API reference, Debugger.IsAttached Property, the summary
  29. cppreference, std::source_location::current, Notes (the call in a default argument)
  30. Debugging with GDB, Contributors to GDB, the first paragraph

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/KVZR9T/text.yaml