Skip to content
systemcoding.dev
Debugging

The Complete Guide to Debugging With LLDB

A full guide to LLDB: its command grammar, breakpoints, stepping, variables, memory, watchpoints, core files, Python, remote debugging and macOS specifics.

25 min read
Summarize in AI
Flat illustration of a debugger stopped at a breakpoint beside the register values, with the LLVM, C and C++ logos.

LLDB is the debugger of the LLVM project, and for a large and growing share of programmers it is the only debugger they use. On macOS and iOS it is the debugger inside Xcode, and the one a terminal gets from the command line tools. On Linux and FreeBSD it is a first-class peer of GDB and the default on FreeBSD. It reads the same DWARF debug information, it stops programs with the same breakpoint instruction, and it shows the same stacks, so the ideas you may have learned from GDB transfer almost whole. What does not transfer is the spelling. LLDB's commands are organised as a grammar, its output is arranged differently, and some of its best features, its expression evaluator built on Clang, its Python API, its formatters, come from a different design. This guide takes you through all of it: the architecture that explains the design, the command grammar, a first session, breakpoints, stepping, variables and expressions, the stack and threads, memory and registers, watchpoints, crashes and core files, settings, scripting, formatters, macOS specifics, remote debugging and the editors that sit on top of it. LLDB 21 from LLVM 21 with Clang 21 on x86-64 Linux is the reference, and where macOS differs, the text says so. Each topic has a longer post in this series.

Where LLDB comes from

LLDB began around 2010 as part of the LLVM project, written to reuse the compiler's own libraries instead of reimplementing a parser. The expression evaluator is the clearest case: when you type p x + 1, LLDB gives the text to Clang, which parses it as C, C++, Objective-C or Swift against the program's own debug information, generates a small piece of machine code and has the debugger run it in the process. That is why LLDB understands templates, lambdas and overload resolution in expressions better than GDB's own parser, and why an expression can fail with a compiler diagnostic that reads like a compile error.

The second thing to know is that LLDB is a library first. The liblldb shared library holds the whole debugger, and the lldb command-line tool is a thin front end over it. Xcode, the Visual Studio Code extensions, CLion and the lldb-dap server link or load the same library. The scripting interface, the lldb Python module with its SB classes, is the stable programming interface of that library, and it is why tools built on LLDB are more common than tools built on GDB's text.

The third is the split between the debugger and the debug server. On macOS the process control is done by debugserver, a small program that Apple ships and signs, which talks to the debugger over a socket. On Linux it is lldb-server, a single binary that can run in several modes. The split lets the debugger and the process be on different machines, which is how remote debugging works, and it is why attaching on macOS involves entitlements and code signing.

LLDB supports x86-64, AArch64, 32-bit Arm, RISC-V and a few others, on macOS, Linux, FreeBSD, NetBSD and Windows, with the strongest support on macOS and Linux for the architectures Apple and the Linux distributions use. It is the debugger for Swift without competition, and the common debugger for Objective-C and Rust on macOS. For embedded targets reached through JTAG probes, GDB's remote protocol support is wider, and the comparison post covers the choice.

Building a program for LLDB

Compile with -g, and use -O0 while debugging.

Shell
clang -g -O0 -Wall -Wextra -o sum_g sum.c

The reasoning is the one from the GDB guide: -g writes DWARF, -O0 keeps source and machine code in step, and an optimised build moves, merges and removes code so that variables print as unavailable. -Og is a middle path in GCC and Clang. Clang adds two options that matter. -glldb tunes the debug information for LLDB, which on Linux makes little difference and on Apple platforms is the default. And -fstandalone-debug emits complete type information for every class in every file, where the default omits a class's definition from files that only use it, on the assumption that another file defines it. Without it, LLDB sometimes shows an incomplete type for a C++ class from a library built without debug info, and -fstandalone-debug is the fix when p obj reports incomplete type.

On macOS, Clang writes debug information into object files, and a linking step called dsymutil collects it into a .dSYM bundle next to the executable, which Xcode does for you. A command-line build can leave the information in the .o files, which works only while they stay in place; run dsymutil prog to make the bundle, and keep the .dSYM of every build you ship, since it is the only way to symbolicate a crash report later.

The command grammar

LLDB commands follow a pattern: a noun, then a verb, then options, then arguments. breakpoint set --name main. thread step-over. frame variable counts. process attach --pid 123. target create ./prog. The nouns are few: target, process, thread, frame, breakpoint, watchpoint, memory, register, type, settings, command, platform, image, source. Each noun has verbs, help breakpoint lists them, and the options have long names and one-letter forms, so breakpoint set --name main --condition 'x > 3' can be written br s -n main -c 'x > 3'.

Abbreviation is the reason this is usable. Any unique prefix of a command word is accepted, and LLDB ships a set of aliases for the commands programmers type most, many chosen to match GDB: b is breakpoint set, br is breakpoint, c is process continue, n and next are thread step-over, s and step are thread step-in, finish is thread step-out, bt is thread backtrace, p is expression, po is expression -O -- (print the object's description), up and down move between frames, r and run start the process, v is frame variable, and x is memory read. You can add your own with command alias.

The -- token ends options. expression -f x -- counts[0] formats in hex, and the -- tells LLDB that what follows is the expression, which matters when it starts with a dash. The help system is built in: help lists the nouns, help breakpoint set documents every option, and apropos watch finds commands whose help mentions a word. Tab completion works on commands, options, file names, function names and breakpoint numbers.

Because commands are text with options, a mistake is a message, not a surprise. error: invalid command 'break' happens in LLDB when a GDB habit slips out of an old alias, and the fix is usually breakpoint set or b. A table mapping GDB commands to LLDB's is the other half of this guide's support and has its own post.

A first session

The program for most examples is the same short one.

sum.cc
#include <stdio.h>

int sum(const int *v, int n)
{
    int total = 0;
    for (int i = 0; i < n; i++)
        total += v[i];
    return total;
}

int main(void)
{
    int data[] = {4, 8, 15, 16, 23, 42};
    int n = sizeof data / sizeof data[0];
    int result = sum(data, n);
    printf("sum = %d\n", result);
    return 0;
}

It prints sum = 108. Load it and run to the function.

Shell
lldb --no-lldbinit ./sum_g
Text
(lldb) target create "./sum_g"
Current executable set to '/home/dev/sum_g' (x86_64).
(lldb) breakpoint set --name sum
Breakpoint 1: where = sum_g`sum + 11 at sum.c:5:9, address = 0x0000000000001134
(lldb) run
Process 41990 launched: '/home/dev/sum_g' (x86_64)
Process 41990 stopped
* thread #1, name = 'sum_g', stop reason = breakpoint 1.1
    frame #0: 0x0000555555555134 sum_g`sum(v=0x00007fffffffe0e0, n=6) at sum.c:5:9
   2   	
   3   	int sum(const int *v, int n)
   4   	{
-> 5   	    int total = 0;
   6   	    for (int i = 0; i < n; i++)
   7   	        total += v[i];
   8   	    return total;

The model behind this output is the structure of everything in LLDB. A target is the program being debugged, loaded from a file; it exists before the process runs. A process is a running instance of it. A process has threads, each with a stack of frames, and the stop report names all four levels: the process id, the thread and its stop reason, the frame with its function, arguments and source location. The -> marks the line that will run next, not the one that just ran.

The stop reason is the first thing to read. breakpoint 1.1 means breakpoint 1, location 1. After a step it says step over, step in or step out; for a crash signal SIGSEGV; for a watch watchpoint 2. The post on starting a session walks the same flow with every line explained.

Breakpoints

LLDB offers more ways to say where than most people use. By function: breakpoint set --name sum. By file and line: breakpoint set --file sum.c --line 7, or b sum.c:7. By address, with --address. By regular expression over function names with --func-regex, and over source lines with --source-pattern-regexp, which stops at every line matching a pattern. For C++, --method takes a method name and Objective-C has --selector. A bare b 7 uses the file of the current frame. The command reports where the breakpoint landed, so read its reply: a line with no code moves to the next line that has some.

Management is plain: breakpoint list shows each breakpoint with its locations (1.1, 1.2), hit counts and whether each is resolved; breakpoint disable 2, enable 2 and delete 2 take numbers, locations or ranges; breakpoint delete with no arguments asks before removing all. A condition is --condition 'expr' at creation or breakpoint modify -c 'expr' N later. --ignore-count skips the first N hits and --one-shot true removes the breakpoint after the first stop. Commands attach with breakpoint command add N, which reads lines until DONE, and breakpoint modify --auto-continue true N makes the breakpoint a logger that never stops. Breakpoints can carry names, breakpoint name add -N parse 1 3, so a group is toggled with one command, and breakpoint write -f bps.json and breakpoint read -f bps.json save and restore a set across sessions, since LLDB does not keep them on its own.

The full details, including the interaction of conditions and commands, are in the breakpoints post. The cost model is the same as in any debugger: a conditional breakpoint stops the process on every hit and evaluates the condition in the debugger, so on a hot path it is slow, and the alternative is a Python callback or a different tool.

Stepping and control

thread step-over (next, n) runs a source line and treats calls as one step. thread step-in (step, s) enters a call that has line information. thread step-out (finish) runs until the current function returns and prints its value, in the form Return value: (int) $1 = 108. thread step-inst (si) and thread step-inst-over (ni) do the same by machine instruction. process continue (c) resumes. thread until runs to a line or address, thread jump moves the program counter, and thread return pops a frame and returns immediately, optionally with a value. Pressing Enter repeats the previous command.

LLDB avoids stepping into some functions by default, according to a pattern in target.process.thread.step-avoid-regexp, which covers trampolines and some runtime code. If step skips something you wanted to see, thread step-in -a true forces it, and settings set target.process.thread.step-avoid-libraries takes a list of libraries to treat the same way.

Variables and expressions

LLDB has two ways to look at a value, and the split is the idea to learn first. **frame variable** (v) reads variables from memory using the debug information and never runs code. **expression** (p) hands the text to Clang, compiles it and runs it in the process, so it can compute, call functions and assign.

Text
(lldb) frame variable
(const int *) v = 0x00007fffffffe0e0
(int) n = 6
(int) total = 0
(int) i = 21845
(lldb) frame variable v[1] total
(const int) v[1] = 8
(int) total = 0
(lldb) p total + n
(int) $0 = 6
(lldb) p v[0] + v[5]
(const int) $1 = 46

frame variable accepts variable paths: a.b, a->b, a[2], *p. It has flags worth learning: -L prints each variable's address, -T the types, -D 3 limits nesting depth, -f x formats in hex, -r REGEX selects names by pattern, and -Z N shows N elements behind a pointer. Results of expression go into $0, $1, and so on, and can be used in later expressions. For globals and statics outside the current frame, target variable NAME works. po ("print object") calls the object's description method, which is the daily command for Objective-C and Swift and a plain expression for C.

Expressions can have side effects: expression total = 99 assigns in the program, and expression f(3) calls a function in the stopped process. Both change the thing you are debugging, and a call can deadlock if the function takes a lock the stopped program already holds. Use them on purpose. frame variable is the right default, since it is cheaper, safer and works in core files where nothing runs; the dedicated post lists when each fails and the format letters.

For types, type lookup NAME prints a definition, and expression -T -- var shows a variable's type. image lookup --type NAME finds a type across modules.

The stack and threads

thread backtrace (bt) prints the current thread's stack. The selected frame carries a *. bt all prints every thread, which is the first command for a hang, and bt 3 limits the depth. frame select N (f N), up and down move between frames; like GDB, moving does not run anything, it changes the frame used to resolve names. frame info shows the details of the selected frame.

Text
(lldb) bt
* thread #1, name = 'sum_g', stop reason = breakpoint 1.1
  * frame #0: 0x0000555555555134 sum_g`sum(v=0x00007fffffffe0e0, n=6) at sum.c:5:9
    frame #1: 0x000055555555519b sum_g`main at sum.c:15:18
(lldb) up
frame #1: 0x000055555555519b sum_g`main at sum.c:15:18
   12  	{
   13  	    int data[] = {4, 8, 15, 16, 23, 42};
   14  	    int n = sizeof data / sizeof data[0];
-> 15  	    int result = sum(data, n);
   16  	    printf("sum = %d\n", result);
   17  	    return 0;
   18  	}
(lldb) frame variable data
(int[6]) data = ([0] = 4, [1] = 8, [2] = 15, [3] = 16, [4] = 23, [5] = 42)

For threads, thread list shows them all, thread select N switches, thread info gives details, and thread backtrace all is the survey. By default LLDB stops all threads at a stop and resumes all of them on continue, as GDB does. thread step-over can be told to run only the current thread with --run-mode this-thread, which is the equivalent of GDB's scheduler locking for stepping.

Memory, registers and disassembly

memory read shows raw memory, with the same format letters as GDB's x, which LLDB accepts as an alias.

Text
(lldb) memory read --size 4 --format x --count 6 v
0x7fffffffe0e0: 0x00000004 0x00000008 0x0000000f 0x00000010
0x7fffffffe0f0: 0x00000017 0x0000002a
(lldb) x/s 0x555555556004
0x555555556004: "sum = %d\n"

memory find searches a range for a byte pattern, memory write stores bytes, and memory region ADDR tells which mapping contains an address and its permissions, the equivalent of looking in /proc/PID/maps. register read prints the general-purpose registers, register read rip rsp selects some, and register write rax 1 changes one. disassemble shows the current function; --name sum another, --pc --count 5 a few instructions at the program counter, and --mixed interleaves source. The syntax defaults to AT&T on x86 and settings set target.x86-disassembly-flavor intel switches to Intel.

image list shows the loaded modules with their UUIDs, image lookup --address 0x... maps an address to a symbol and line, and image lookup --name NAME finds symbols by name, which is the family of commands that GDB spreads over info sharedlibrary, info symbol and info address.

Watchpoints

A watchpoint stops the program when memory changes, using the CPU's debug registers, four on x86-64. watchpoint set variable NAME follows a variable, and watchpoint set expression -s SIZE -- ADDRESS watches raw memory. -w write, read or read_write chooses the access. When it triggers, LLDB reports the old and new values and stops after the instruction that accessed it, which is often inside a library function, so the backtrace is what names the culprit.

Text
(lldb) watchpoint set variable current.level
Watchpoint created: Watchpoint 1: addr = 0x555555558018 size = 4 state = enabled type = w
(lldb) continue
Watchpoint 1 hit:
old value: 1
new value: 1869898098

LLDB has no software fallback, so a watch beyond the hardware limit fails at creation with an error and does not silently slow the program. The post on watchpoints works through the overflow example and the scope rules.

Crashes, core files and attaching

Run to a crash the same way as in GDB: no breakpoint, run, and the stop report names the signal and the frame. bt and frame variable do the investigation. process handle SIGPIPE --stop false --notify false --pass true changes how a signal is treated, and process signal SIGINT sends one.

For a core file, load it with the executable.

Shell
lldb --no-lldbinit -c core ./crash
Text
(lldb) target create "./crash" --core "core"
Core file '/home/dev/core' (x86_64) was loaded.
(lldb) bt
* thread #1, name = 'crash', stop reason = signal SIGSEGV
  * frame #0: 0x0000555555555145 crash`read_retries(cfg=0x0) at crash.c:9:12
    frame #1: 0x0000555555555170 crash`main at crash.c:15:5

Commands that read memory work, including frame variable, bt, memory read and register read, while expression cannot run code in a core. On macOS the core-file route is less common, since crash reports are the usual artefact, and the post on crashlog shows how LLDB symbolicates them.

To attach to a running process, lldb -p PID, or process attach --pid PID, or --name NAME, and process detach lets it go. On Linux the Yama ptrace_scope setting can refuse an attach to an unrelated process, as the earlier post describes. On macOS the target must permit it, which for a hardened-runtime binary means the get-task-allow entitlement, covered in its own post, and developer tools access must be enabled.

Settings and the init file

settings list shows the tree and settings show NAME reads one. Settings you will change: stop-line-count-before and stop-line-count-after for the context shown at a stop; target.run-args and target.env-vars for the program's command line and environment; target.x86-disassembly-flavor; frame-format and thread-format for the stop lines; target.max-children-count for how many array elements print; and target.input-path, output-path and error-path to redirect the program's streams.

Put your defaults in ~/.lldbinit.

~/.lldbinitText
settings set stop-line-count-before 5
settings set stop-line-count-after 5
settings set target.x86-disassembly-flavor intel
command alias bpl breakpoint list
command alias lo frame variable

LLDB also reads a .lldbinit in the current directory, but only if target.load-cwd-lldbinit is on, and by default it asks, since such a file runs arbitrary commands. lldb -x skips all init files for a clean run. For repeated work, command source file.lldb runs a command file, and lldb -b -o 'cmd' -o 'cmd' ./prog runs commands and exits, which is the form for scripts and CI.

Scripting and formatting

The script command runs Python inside LLDB, with lldb.debugger, lldb.target, lldb.process, lldb.thread and lldb.frame set to the current objects. The whole debugger is available as SB classes: SBTarget, SBProcess, SBThread, SBFrame and SBValue, where SBValue carries a value with its type and children. A custom command is a function def f(debugger, command, result, internal_dict) registered with command script add -f module.f name, and a breakpoint callback is def cb(frame, bp_loc, internal_dict) returning true to stop. The Python post builds both and lists the habits, such as checking IsValid() after every lookup, since the API returns invalid objects instead of raising.

Formatters change how a type prints. A summary sets the text after the =: type summary add --summary-string "head=${var.head}" ring, or a Python function. A synthetic child provider replaces the children, with a class that implements num_children, get_child_at_index and update, registered with type synthetic add --python-class module.Class ring. Together they let a ring buffer print as its live elements in order, instead of the raw array and two indexes. LLDB ships formatters for libc++ and for libstdc++ containers, so std::vector and std::map print as their contents when the matching standard library is in use. frame variable -R shows the raw value, which is the check when a formatter looks too tidy.

macOS specifics

On macOS, LLDB works with the rest of Apple's toolchain, and four things differ from Linux. Debug information lives in .dSYM bundles, matched to binaries by UUID, which dwarfdump --uuid shows and target symbols add attaches. Attaching to a process, other than ones LLDB launches itself, needs the target to carry the com.apple.security.get-task-allow entitlement if it uses the hardened runtime, and Xcode adds it to debug builds automatically, so a command-line build must be signed with codesign --force --sign - --entitlements debug.entitlements ./prog. System Integrity Protection blocks debugging of Apple's own binaries. And crash reports are .ips files that crashlog REPORT.ips loads and symbolicates through the dSYM. The macOS posts in this series cover signing and symbolication in detail.

Xcode's debugger is LLDB. Its variables view, its breakpoints, its console and its memory graph tools all go through the same library, and the Xcode console accepts every command in this guide. Formatters and commands from your ~/.lldbinit apply there too.

Remote debugging

A target with little memory or no room for symbols can be debugged from a workstation. On the target, lldb-server gdbserver '*:2345' -- ./prog runs one program under the server, or lldb-server platform --server --listen '*:2000' runs a platform that launches programs and transfers files. On the workstation, load the unstripped binary for symbols, then gdb-remote HOST:2345 connects to the first, and platform select remote-linux with platform connect connect://HOST:2000 connects to the second, after which platform put-file, platform shell and run work against the board. The protocol is unauthenticated, so tunnel it through SSH. Cross-built programs need a sysroot so LLDB can find symbols for the target's libraries: platform settings --sysroot. The remote post covers it from build to attach.

Editors and adapters

LLDB reaches editors through two routes. lldb-dap, shipped with LLVM, speaks the Debug Adapter Protocol and is the route for Visual Studio Code, Neovim and other editors that support DAP; it replaced the older lldb-vscode. CodeLLDB, an extension for Visual Studio Code, embeds LLDB itself, adds Rust support and pretty-printing and is the usual choice for Rust. CLion drives LLDB through its own front end. In all of them the commands of this guide are available in a debug console, and the breakpoints, stepping and variables views are thin layers over the same calls.

Rust, Swift and C++

For C++, LLDB's expression evaluator is its strength: templates, lambdas, overload resolution and auto in expressions work, because Clang parses them. The costs are speed on large programs and the need for -fstandalone-debug on types defined in other translation units. For Rust, use rust-lldb, the wrapper installed with the toolchain, which loads formatters for String, Vec, Option and the rest; expression support for Rust is limited, so read fields with frame variable. For Swift, LLDB is the only real debugger, with the Swift runtime and po descriptions built in. For Objective-C, po and message-send expressions are native.

When things go wrong

A short table of the failures you will meet.

Message or symptomLikely cause and fix
error: invalid command 'break'A GDB habit; use breakpoint set or b
Breakpoint says pending or unresolvedThe location is in a module not loaded yet; it resolves on load
Source lines missing at a stopNo -g, or the source path differs; check image list and settings set target.source-map
error: Couldn't lookup symbols in an expressionThe symbol is not in the debug info; rebuild with -g, or -fstandalone-debug for types
<variable not available>Optimised build; rebuild with -O0 or -Og
attach failed: Not allowed to attach to process (macOS)Missing get-task-allow, SIP or developer mode off; see the codesign post
Operation not permitted on attach (Linux)Yama ptrace_scope; run as root or start the program from LLDB
Process runs to the end without stoppingBreakpoint in code that does not run, or a typo in the name; check breakpoint list hit counts
A pretty-printed value looks wrongA formatter reads the wrong field; use frame variable -R

Source paths deserve a note. A program built on one machine and debugged on another has file names baked into its debug information, and LLDB looks for the source at those paths. settings set target.source-map /build/path /local/path rewrites the prefix, which is the standard answer for sources on a different machine or in a container.

From GDB to LLDB, and back

If you know GDB, you already know the ideas. Breakpoints, frames, watchpoints, core files and attaching are the same, and the short forms b, c, n, s, bt, p, r and up mean what you expect. What changes is the noun-verb spelling of the rest, the split of print into frame variable and expression, DONE where GDB writes end, and the absence of rr and dprintf. The command-map post has the full table, and the comparison post covers which debugger fits which job. A team that works on both Linux and macOS ends up using both daily, with a map of equivalent commands in a text file.

A method for a session

The commands matter less than the habit of using them in a sequence. Reproduce the failure and read the stop report before anything else. If it is a crash, bt, then up to the frame whose variable looks wrong, then frame variable. If it is a wrong value, set a breakpoint before it is produced and step, or use a watchpoint to find the first write. If it hangs, interrupt with Ctrl-C and bt all. Before you trust a value that looks too clean, check the raw form. And write down what you expect before you press next, since the surprise is the information.

A worked investigation

A guide to commands should show them used together, so here is a complete session on a program that fails.

orders.cc
#include <stdio.h>
#include <stdlib.h>

struct order {
    int id;
    int qty;
    double price;
};

static double line_total(const struct order *o)
{
    return o->qty * o->price;
}

static double grand_total(struct order **orders, int count)
{
    double total = 0.0;
    for (int i = 0; i < count; i++)
        total += line_total(orders[i]);
    return total;
}

int main(void)
{
    struct order *list[3];
    list[0] = malloc(sizeof **list);
    list[1] = NULL;
    list[2] = malloc(sizeof **list);
    *list[0] = (struct order){1, 2, 4.5};
    *list[2] = (struct order){3, 5, 1.2};
    printf("%.2f\n", grand_total(list, 3));
    free(list[0]);
    free(list[2]);
    return 0;
}

The second element is null, so the second iteration of the loop dereferences it. Run it with no breakpoints, which is the first move on a crash.

Text
(lldb) run
Process 77102 launched: '/home/dev/orders' (x86_64)
Process 77102 stopped
* thread #1, name = 'orders', stop reason = signal SIGSEGV: address not mapped to object (fault address: 0x4)
    frame #0: 0x0000555555555165 orders`line_total(o=0x0000000000000000) at orders.c:12:15
   9   	
   10  	static double line_total(const struct order *o)
   11  	{
-> 12  	    return o->qty * o->price;
   13  	}
   14  	
   15  	static double grand_total(struct order **orders, int count)

The stop reason names the signal and the fault address, 0x4, which is the offset of qty from a null pointer: a field access through a null o. The frame header shows o=0x0000000000000000. That much comes free. The question is which element of the array was null, so move up and look.

Text
(lldb) up
frame #1: 0x00005555555551d0 orders`grand_total(orders=0x00007fffffffe0d0, count=3) at orders.c:19:18
   16  	{
   17  	    double total = 0.0;
   18  	    for (int i = 0; i < count; i++)
-> 19  	        total += line_total(orders[i]);
   20  	    return total;
   21  	}
(lldb) frame variable i count
(int) i = 1
(int) count = 3
(lldb) expression -- orders[0] != 0 && orders[2] != 0
(bool) $0 = true
(lldb) frame variable -Z 3 orders
(struct order **) orders = 0x00007fffffffe0d0

i = 1, so element 1 was the null one. Checking the neighbours with expression shows elements 0 and 2 are valid, which fits a single missing element, not a corrupted array. The cause is in main, which never filled list[1], and a second up shows its locals. The whole investigation took four commands after the run, with no breakpoint, which is the usual shape of a crash: read the stop reason, climb to the frame where a variable is wrong, check the data around it.

For a bug that does not crash, the same program with list[1] set to a valid order but a wrong price would print a wrong total. There, the first move is a breakpoint on line_total with a condition, breakpoint set --name line_total --condition 'o->id == 2', followed by frame variable *o, which prints the struct with its fields and shows the bad price. And to find which line first sets a field wrongly, watchpoint set variable on list[1]->price after the allocation stops at the first write.

Launching: arguments, environment and standard streams

The way a program starts affects how it behaves, and LLDB lets you control it all. run ARGS launches with arguments and stores them; settings set target.run-args a b stores them without running; settings show target.run-args prints them. settings set target.env-vars KEY=value OTHER=1 sets environment variables for the next launch, and settings set target.inherit-env false stops the program inheriting LLDB's own environment, which helps when the program behaves differently in a clean environment. process launch --working-dir /tmp sets the working directory, and process launch --stop-at-entry stops before the first instruction, in the dynamic loader or the program's entry point, which is where you set breakpoints on code that runs before main, such as static constructors.

Standard streams default to LLDB's own terminal, which mixes the program's output with the debugger's. process launch -o out.txt -e err.txt -i input.txt redirects them to files for this launch, and the target.input-path, target.output-path and target.error-path settings do it persistently. The -t flag, --tty, launches the program in a new terminal window, which is the answer for a program that needs a real terminal, such as a curses application. ASLR is disabled by default in LLDB, and settings set target.disable-aslr false turns it back on, for the case where a bug depends on a randomised layout.

Debugging C++ in detail

Most of C++ debugging with LLDB is the same commands applied to richer types, and the differences come in four places.

Names. A C++ function has a mangled linker name, but LLDB works with source-level names. breakpoint set --name Stack::push finds the method. Overloads each get a location, and breakpoint set --name 'Stack::push(int)' picks one; quote the names with parentheses. breakpoint set --method push matches methods across classes, and image lookup --name push --verbose lists all matches with their addresses and files, which helps when a breakpoint has more locations than expected. Templates produce one function per instantiation, so a breakpoint on a template function reports one location for each concrete type the program uses.

Objects. In a method, this is a normal variable. frame variable this shows a pointer, and frame variable *this shows the object with its base classes as nested members. Virtual functions and the dynamic type are handled by settings set target.prefer-dynamic-value run-target, which makes frame variable show the dynamic type of a base-class pointer, and expression -d run-target -- ptr does so for one expression. type lookup Shape prints the class definition.

Standard library types. LLDB ships formatters for libc++ and libstdc++, and picks the right set when it recognises the library. A std::vector<int> prints as size=3 { [0] = 1 [1] = 2 [2] = 3 }, a std::string as its text, a std::map as its pairs and a std::unique_ptr as its pointer and pointee. When the formatters do not apply, usually because the program is built against a standard library LLDB does not know or lacks debug info for it, the raw members show, and -fstandalone-debug on the compile line often cures it. frame variable -R v shows the raw layout of a value regardless.

Expressions. Because Clang evaluates them, expression v.size() calls the method, expression std::min(a, b) works if the template is instantiated in the program, and lambdas and auto can appear in an expression. Calls can fail if the function was inlined and no out-of-line copy exists, with an error that the function cannot be called. expression -i false -- f() makes a call that stops at a breakpoint inside the function, which is how you debug a function by calling it from the debugger.

Exceptions. A thrown exception unwinds before you can look. breakpoint set --name __cxa_throw, or the friendlier breakpoint set -E c++, stops at the throw, with the stack intact, and -E c++ can narrow to -O for a type: breakpoint set -E c++ -O std::runtime_error. That is the C++ equivalent of running to a crash.

Checking your own setup

A short list of commands tells you what LLDB knows, and is the first thing to run when something does not work as expected. target list shows loaded targets and the selected one. image list shows the modules with UUIDs, load addresses and the symbol file for each; a module with no symbol file is why a breakpoint will not resolve. image dump line-table sum.c prints the line table for a file, which settles whether a line has code. settings show target.source-map shows how source paths are rewritten. log enable lldb breakpoints writes LLDB's own log of breakpoint decisions to the terminal, and log list shows the channels, which is the tool of last resort when a breakpoint behaves oddly. And version prints the LLDB build, which matters when you read a feature in the manual that your version lacks.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.