Module 4 · Lesson 127 of 156

The debugging workflow and gdbserver

Reproduce and isolate a user-space crash, capture a backtrace with gdbserver, and analyse a core dump with an architecture-aware GDB.

  • Beginner to advanced
  • 8 min read
  • 28 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with the AArch64 GCC cross toolchain, its static C library, and gdb-multiarch. A Raspberry Pi 4 or 5 running 64-bit Ubuntu 24.04 with gdbserver and SSH access is needed for the live and core exercises.

Your place in the module
By the end you can 4 objectives
  • Record a repeatable failure and a working control under the same conditions.
  • Connect a host debugger to gdbserver, stop at a breakpoint, and capture a crash backtrace.
  • Enable core dumps for a shell-launched process and open a saved core with the matching executable.
  • Verify a proposed fix using the original failing input and a working control.
Video coming soonThe debugging workflow and gdbserver
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from U-Boot Falcon mode
  • Falcon mode runs U-Boot SPL and skips U-Boot proper on the direct Linux path.
  • A legacy raw-MMC Falcon setup stores a kernel image and a prepared device tree at locations SPL knows.
  • Linux can mount a partition as its root filesystem even when SPL reads the boot payload from raw blocks.
01

Reproduce, isolate, hypothesise, verify

4 min read

Boot optimisation assumed a working system; when it breaks you need a debugging method. This lesson answers the reproduce, isolate, hypothesise and verify workflow, gdbserver with a cross gdb, and analysing core dumps.

A program on a board can terminate while the serial console and the rest of Linux are still responsive. Linux defines signals whose default action terminates the receiving process and requests a core dump. For example, abort() raises SIGABRT. If you know that the program received this signal, you still need to identify the application call that led to it and the condition that caused that call. That distinction is documented in signal(7) and abort(3) and is the problem this lesson works through.

A repeatable debugging workflowReproduceRecordinput andfailureIsolateChange oneconditionHypothesisePredict anobservationVerifyRetestfailure andcontrol↻ Repeat from step 1ReproduceRecordinput andfailureIsolateChange oneconditionHypothesisePredict anobservationVerifyRetestfailure andcontrol↻ Repeat from step 1
Each test either supports your prediction or sends you back to refine it
Step by stepA repeatable debugging workflow
  1. Reproduce. Write down the exact command, input, working directory, and deployed build. Record the expected result and the observed failure. Run the same case again. If the failure is intermittent, record how often it occurs under the same conditions.

  2. Isolate. Keep the build and environment fixed. Compare a failing input with a successful one and vary one input at a time. If a smaller input still fails, save it for subsequent runs. Keep the successful case as a control.

  3. Hypothesise. Write a cause that predicts an observation. If an empty argument causes the program to call abort(), a breakpoint at the input-handling function should show an empty string before the signal. A nonempty argument should reach the same function and finish successfully.

  4. Verify. Test the prediction on the original build, then make the smallest change that addresses the cause. Rerun the original failing command and the successful control on the new build. Check the intended behaviour and exit status in both cases. Repeat the test under the original launch conditions if you simplified them during isolation.

A backtrace shows the active function calls when the program stopped. Frame 0 is the innermost frame. Higher-numbered frames are callers. Start with the first frame that belongs to your application and check what arguments or local values it contains. A library function may be doing exactly what your application asked it to do. In this lesson the program calls abort() directly. In a real crash, the value that caused the failure may have been set earlier by a function that has already returned.

Use this small program to make the failure repeatable. Save it as crash-demo.c. Its intended behaviour is to accept one nonempty name and report invalid input as a normal command-line error. The empty-input path deliberately violates that requirement.

c
#include <stdio.h>
#include <stdlib.h>

static void validate_name(const char *name)
{
    if (name[0] == '\0') {
        abort();
    }
}

int main(int argc, char **argv)
{
    if (argc != 2) {
        fputs("usage: crash-demo NAME\n", stderr);
        return EXIT_FAILURE;
    }

    validate_name(argv[1]);
    return EXIT_SUCCESS;
}

On an Ubuntu host, build it for a Raspberry Pi running 64-bit Ubuntu. -g includes debug information, -O0 keeps this example easy to step through, and -static avoids needing a copy of the target's shared libraries on the host for this example.

bash
aarch64-linux-gnu-gcc -Wall -Wextra -std=c17 -g -O0 -static \
    -o crash-demo crash-demo.c
scp ./crash-demo "$TARGET:~/crash-demo"

Install the tools first: sudo apt install gcc-aarch64-linux-gnu gdb-multiarch on the Ubuntu host and sudo apt install gdbserver on the board. Set TARGET on the host to the board's SSH destination in user@hostname form before copying. Keep the host executable and source from this build. On the board, run the following from your home directory.

bash
./crash-demo sensor
./crash-demo ''

The quotes pass one empty argument. On the Ubuntu 24.04 host the same source compiled natively with gcc -Wall -Wextra -std=c17 -g -O0 exits with status 0 for sensor, with 134 (128 plus SIGABRT, signal 6) for the empty argument, and with 1 and the usage line when no argument is given. Running without any argument instead exercises the argc check, so it cannot reproduce this abort. The successful control uses the same argument count and varies only the string. This gives you a specific prediction to check when the debugger stops.

02

Stop the program with gdbserver

3 min read

gdbserver runs on the board and controls the target process. On the Ubuntu host, gdb-multiarch acts as the cross debugger for the AArch64 executable. It reads the host copy of the executable and uses the debug information to resolve addresses to functions and source lines. Keep that executable from the exact build deployed to the board. A later rebuild can change the addresses even when the function names stay the same.

A remote debugging sessionHost GDBBoard gdbserverTarget processConnectSet breakpointResume processStopsReport stop1. Host GDB → Board gdbserverConnect2. Host GDB → Board gdbserverSet breakpoint3. Board gdbserver → TargetprocessResume process4. Target process → BoardgdbserverStops5. Board gdbserver → Host GDBReport stop
Host GDB reads local symbols and controls the target process through gdbserver

For this lab, connect over SSH with local port forwarding. Run the first command on the host and the second command in the board shell it opens. Use a private lab board for the session because the gdbserver TCP endpoint has no authentication.

bash
ssh -L 127.0.0.1:2345:127.0.0.1:2345 "$TARGET"
bash
gdbserver --once :2345 ~/crash-demo ''

The board's gdbserver starts the program stopped and waits for a debugger. Keep that SSH session open. In a second host terminal, change to the directory containing the executable and source, then start GDB.

bash
gdb-multiarch ./crash-demo

Enter these commands at the GDB prompt. In this connection mode, the program and its arguments are supplied to gdbserver, and continue resumes the process it has already started.

text
target remote 127.0.0.1:2345
break validate_name
continue
print *name
continue
bt

The first continue should stop at validate_name. print *name examines the first character. For the empty input that character is the null terminator. The second continue should stop on SIGABRT with the default GDB handling for that signal. Run bt while the process is stopped. Save the backtrace and the signal reported by GDB before resuming or closing the session.

Look for validate_name and main in the backtrace. Select the application frame with frame N, replacing N with the frame number GDB shows, and use info args to inspect its arguments. bt full also asks for local variables. If a crash occurs in a multithreaded program, thread apply all bt shows the call stacks of all threads, including threads that were waiting when the failure occurred.

If a breakpoint cannot be resolved, check that you loaded the unstripped host executable and spelled the function name correctly. If application frames resolve but frames in shared libraries are missing or misleading in a real, dynamically linked program, use set sysroot /path/to/target-rootfs in GDB with a host copy of the matching target libraries and supply their debug symbols as needed. The static lab executable keeps that setup out of this session.

03

Inspect a crash after the process exits

3 min read

A contains register state and selected memory. It is useful when the program fails outside a live debug session. You can inspect frames and available variables after the event. To test a new hypothesis about an earlier step in execution, start another run with a breakpoint at that step.

Analysing a saved coreFatalsignalCore dumpRegistersandselectedmemoryOpen in GDBUsematchingexecutableReadbacktraceFatalsignalCore dumpRegistersandselectedmemoryOpen in GDBUsematchingexecutableReadbacktrace
The target generates a dump and the host debugger opens it with the original executable

Run the crashing command directly on the board for this capture. In Bash on the target, raise the soft core limit in the same shell that launches the program. The process inherits that limit. If the hard limit prevents an unlimited soft limit, use a sufficient value within the hard limit or arrange for the program's launcher to set it.

bash
ulimit -S -c unlimited
ulimit -S -c
cat /proc/sys/kernel/core_pattern

Read core_pattern before generating the crash. A filename pattern such as core.%p writes a file in the crashing process's working directory, with %p replaced by its process ID. An absolute pattern names a location directly. A pattern beginning with | sends the dump to a handler. On Ubuntu, the active handler depends on how the system is configured. Use its export mechanism if it retains a core. For a system using systemd-coredump with a retained dump, coredumpctl dump PID --output=crash-demo.core exports it when you replace PID with the crashed process ID.

For a predictable file capture on a dedicated lab board, you can temporarily set a relative filename pattern. The setting applies to the whole running system, so save the original first and restore it after the run. Begin in a writable directory with space for the dump, such as your home directory.

bash
old_pattern=$(cat /proc/sys/kernel/core_pattern)
sudo sysctl -w 'kernel.core_pattern=core.%p'
./crash-demo ''
sudo sysctl -w "kernel.core_pattern=$old_pattern"

Identify the newly written core.<pid> file. If the file is missing, check that the pattern change succeeded, that the program ran from a writable directory, that free space is available, and that the shell accepted the core limit. Linux can also suppress dumps for some processes, including certain privileged executables. A crash and a saved dump are two observations to record separately.

Copy the core to the host as crash-demo.core, then open it with the executable from the crash build.

bash
gdb-multiarch ./crash-demo ./crash-demo.core

Use bt, select the relevant application frame with frame N, and inspect it with info args. Compare the signal and application call sequence with the live capture. Process addresses may differ between runs. Save the matching executable before building the fix so you can still open the original core later. Core files can contain data from process memory, so handle them with the same care as the input and credentials the process used.

The next lesson, strace and perf, answers what to examine when a program stays alive but makes unexpected Linux requests or spends too much time doing work.

Key takeaways

  • A backtrace shows the active calls at the point of failure. The originating defect can occur earlier.
  • gdbserver controls the process on the target while GDB on the host uses the matching executable and debug symbols.
  • ulimit changes the shell's core size limit for future child processes. The target's core pattern determines how dumps are routed.
  • A core records process state for inspection after the process exits.
Reflect
  1. Explain to a colleague, in two sentences: record a repeatable failure and a working control under the same conditions.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close