Module 6 · Lesson 7 of 108

The reproducible build loop and advanced debugging

Make a build reproducible and debug harder problems with core files, threads, and cross-architecture profiling.

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

Ubuntu 24.04 (WSL2, VM or container) with a cross toolchain or a Yocto SDK; a QEMU aarch64 target or a Raspberry Pi for the debug sections

Your place in the module
By the end you can 3 objectives
  • Design a one-command build, deploy and debug loop and diagnose its common failures
  • Make a build reproducible by fixing timestamps and path maps and by using a compiler cache
  • Analyze a crash from a core file and choose a profiling approach for an AArch64 target
Video coming soonThe reproducible build loop and advanced debugging
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Deploying and remote debugging
  • gdbserver runs on the target and host gdb does the symbol work; set sysroot so gdb reads the right libraries.
  • Ship a stripped binary and keep the debug file; the build-id links the two.
  • During development, rsync or an NFS root gets builds onto the board; production delivery is an OTA update, not a copy.
01

The one-command loop, reproducible builds and caches

4 min read

You can now deploy and debug, but the loop is still many manual steps and results can drift between machines. This lesson answers: how do you make the build reproducible and debug harder problems?

The edit, build, deploy, debug cycle repeats hundreds of times a day, so each manual step costs you. Collect them in one script, tools/dbg.sh:

bash
#!/usr/bin/env bash
set -euo pipefail

TARGET="${TARGET:-learner@board}"
PORT="${PORT:-2345}"
PRESET="${PRESET:-arm64-debug}"
REMOTE_DIR="${REMOTE_DIR:-/opt/sensornode}"
SYSROOT="${SYSROOT:-/home/learner/sysroots/board}"
BIN="sensornode"

cmake --preset "$PRESET"
cmake --build --preset "$PRESET"

BUILD="build/$PRESET"
rsync -az --partial "$BUILD/$BIN" "$TARGET:$REMOTE_DIR/"

exec gdb-multiarch -q "$BUILD/$BIN" \
  -ex "set sysroot $SYSROOT" \
  -ex "target remote | ssh $TARGET gdbserver - $REMOTE_DIR/$BIN" \
  -ex "break main" -ex "continue"

Each choice is deliberate. set -euo pipefail stops at the first failure, so a compile error never reaches the board. The pipe form of target remote starts gdbserver over SSH and needs no port or race between starting the server and connecting. Environment variables with defaults let a teammate or a CI job override the board address without editing the file. The same logic can be exposed as a CMake custom target named debug, but a script is easier to read, and a CMake target is better when the IDE should trigger it. Note the stripped-binary rule from before: the host copy in build/ has symbols, while the copy on the board may be stripped to match production, since gdb reads symbols from the host side.

Reproducible builds. A build is when nothing environmental leaks into the output. Three leaks are common. Timestamps: __DATE__, __TIME__ and archive members carry the build time. Set SOURCE_DATE_EPOCH to a fixed Unix time (many teams use the last commit time with git log -1 --format=%ct), and GCC substitutes it for the macros. Paths: GCC embeds the absolute build directory in debug info and in __FILE__, so two checkouts in different directories differ. Use -ffile-prefix-map=/home/learner/work/sensornode=. (GCC 8 and newer) to rewrite the prefix in both places. Ordering: parallel builds and filesystem iteration order can reorder inputs; modern linkers and archivers are deterministic for the same inputs. Tools such as diffoscope compare two outputs and show where they differ.

The benefit for the loop is practical: with path maps and a fixed epoch, a preprocessed translation unit does not change between checkouts, so the compiler cache hits. ccache keys on the preprocessed text and flags; setting hash_dir = false in its config stops the working directory from entering the hash when you use debug prefix maps, and base_dir rewrites absolute paths under it to relative ones. sccache is a similar wrapper that can store results on a shared server, such as an S3-compatible bucket, so a whole team shares hits. Both are enabled through CMAKE_<LANG>_COMPILER_LAUNCHER, and both can serve cross builds because the launcher sits in front of the cross compiler. Check effectiveness with ccache -s, and remember that a cache never replaces correct dependency tracking; it only skips work that was already done.

One-command debug loopConfigurecmake--presetBuildcmake--buildDeployrsync toboardStartgdbserverover sshpipeHalt in gdbbreak main↻ Repeat from step 1Configurecmake--presetBuildcmake--buildDeployrsync toboardStartgdbserverover sshpipeHalt in gdbbreak main↻ Repeat from step 1
The one-command loop from source change to a halted debugger
02

Cross-debugging cores, threads and profiling, and common mistakes

5 min read

Core files. A core file, a snapshot of a crashed process's memory and registers written by the kernel, is the field-debugging workhorse. On the board, enable it with ulimit -c unlimited for the process, and decide where it goes with /proc/sys/kernel/core_pattern, described in core(5). On a systemd system the pattern may pipe to systemd-coredump, and coredumpctl lists and extracts them. Cores can be large, so on a flash device write them to tmpfs or a dedicated partition and cap their size. On the host:

bash
gdb-multiarch build/arm64-debug/sensornode core
text
(gdb) set sysroot /home/learner/sysroots/board
(gdb) bt
(gdb) info sharedlibrary
(gdb) thread apply all bt

gdb needs the exact binary and libraries that were running. If you rebuilt since, the addresses no longer match and you see nonsense frames. info sharedlibrary shows whether each library was found with symbols. This is where the build-id archive from the previous section pays off: it is the only way to pair a field core with the right debug file.

Threads. gdbserver reports every thread of the debugged process, and info threads lists them, thread N switches, and thread apply all bt prints every stack, which is the first command to run on a deadlock. By default gdb lets other threads run while you step one; set scheduler-locking on freezes the others, which makes single-stepping predictable at the price of possible deadlock if the stepped thread waits on a frozen one. For threaded programs the host gdb must read libthread_db metadata, which another sysroot library provides, so a wrong or missing sysroot also shows up as missing thread names.

The eSDK and devtool. In the extensible SDK the devtool command gives an application developer an iterative path against the real image without leaving the SDK. devtool add sensornode /home/learner/src/sensornode creates a recipe from your source tree; devtool build sensornode builds it with the full build system; devtool deploy-target sensornode root@board copies the resulting files to the board over SSH; devtool undeploy-target removes them. devtool modify <recipe> extracts the source of an existing recipe into the workspace for patching, and devtool finish turns your changes into a patch in a layer. The eSDK gives you the exact same dependency resolution as the final image build, at the cost of a large installer and more disk space; the plain SDK with CMake is lighter and is the better choice when the application builds standalone.

Profiling across architectures. The rules are asymmetric. perf records on the target against the target's kernel, and the data can be copied to the host and reported with perf report --symfs=<sysroot>, which is usually workable for flat profiles; DWARF-based call-graph unwinding across architectures is the fragile part, so build with frame pointers (-fno-omit-frame-pointer) when you want reliable call graphs. valgrind supports AArch64 and 32-bit ARM Linux natively, but it must run on the target, takes a large amount of memory and time, and does not run under qemu-user; running an x86 valgrind on a foreign binary is not possible. strace and ltrace also run on the target. The AddressSanitizer from earlier lessons works natively on ARM with the cross compiler, and needs its runtime library present in the target's image.

Common mistakes. Four failures account for most lost afternoons in this loop. Each has a symptom, a cause, a diagnosis and a fix:

  • "cannot execute: required file not found" on the board. The binary was built against the host's dynamic loader or a different path than the image provides. Diagnose with file sensornode and readelf -l sensornode | grep interpreter, then compare to the board's loader. Fix: build with the SDK, not the host compiler.
  • "Exec format error" or "cannot execute binary file". The binary is for the wrong architecture, or an AArch64 binary reached a 32-bit userland. Diagnose with file. Fix: check CMAKE_SYSTEM_PROCESSOR and the compiler prefix.
  • Link succeeds with host libraries, program crashes on the board. The find-root modes were BOTH, or pkg-config read host files. Diagnose with cmake --build build --verbose and look for /usr/lib/x86_64-linux-gnu in link lines. Fix: the ONLY modes and PKG_CONFIG_LIBDIR.
  • Breakpoints never hit, or lines look wrong in gdb. The debug file or source does not match the binary on the board, or the optimiser reordered code. Diagnose by comparing build-ids with readelf -n on both copies. Fix: deploy exactly what you built, and use RelWithDebInfo or -Og for development.
Going deeperWhy a missing sysroot can send gdb to the wrong libc

When gdb loads a shared library for a remote target it asks the dynamic linker's link_map list for each library's path on the target, then rewrites that path under the sysroot. With sysroot target: the file is fetched from the board. With a host sysroot, gdb reads <sysroot>/lib/libc.so.6 or the multiarch equivalent. If you point at the host's root by mistake, gdb loads an x86 libc and warns about an architecture mismatch, or silently reads wrong symbols when the architectures are similar, such as 32-bit versus 64-bit ARM. The check is info sharedlibrary, which lists the resolved path for each library; every path should sit under the target sysroot.

Common failures and causesSymptomUsual causeFirst checkrequired filenot foundwrong ELFinterpreterhost gcc usedreadelf -lExec formaterrorwrongarchitecturewrongcompilerprefixfile appHost libs linkedfind modesBOTHpkg-configreads hostverbose linklineBreakpointsnever hitbinary andsymbolsdifferstale debugfilereadelf -nbuild-id
Common failure symptoms in the cross loop and where each one comes from
03

Try it

1 min read

Open the lab for this lesson. Install or unpack an SDK, write a small CMake application with a library target and one pkg-config dependency, and cross-build it with a preset, then confirm with file that the result is for the target. Deploy it to the QEMU target, start gdbserver, attach from the host with the sysroot set, hit a breakpoint and set a watchpoint. Finally write one script or custom target that does all of it in one command. The practice pack has the step-by-step tasks, and none of the answers are in this lesson.

Key takeaways

  • Reproducible builds need fixed timestamps and path maps, which also makes ccache hits more likely.
  • One script that builds, deploys and starts gdbserver turns a ten-step ritual into a habit.
  • A core file pairs with the exact binary and libraries that crashed, matched by build-id, so the debug archive must be kept.
  • perf records on the target and reports on the host; valgrind runs on the target only, never under qemu-user.
Reflect
  1. Explain to a colleague, in two sentences: design a one-command build, deploy and debug loop and diagnose its common failures
  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

Official documentation first. Links checked when the lesson was published.

Find your next step

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