dpkg State Databases, Signed APT Repositories & Sysroot pkg-config Isolation

Deleting /var/lib/dpkg/lock-frontend corrupts package transaction journals, unsigned third-party mirrors risk toolchain supply-chain compromise, and unguarded pkg-config leaks host /usr/include x86_64 paths straight into ARMv7-A cross-builds.

20 minfree previewLinux 6.12C11glibc 2.39→ module 3 lab
What you'll learn
  • Trace package ownership and state transitions using dpkg -L, dpkg -S, /var/lib/dpkg/status, and signed APT DEB822 repositories.
  • Diagnose /var/lib/dpkg/lock-frontend flock contention via fuser/lsof and recover interrupted unpacks with dpkg --configure -a.
  • Isolate ARMv7-A cross-compilation from host x86_64 headers and libraries using PKG_CONFIG_LIBDIR and PKG_CONFIG_SYSROOT_DIR.

How Host Package Managers Help—and Quietly Sabotage—Cross-Compilation

Setting up a fresh Ubuntu 22.04/24.04 LTS or Debian 12 workstation for Linux kernel and U-Boot development starts with installing host build tools (bc, bison, flex, libssl-dev, device-tree-compiler, u-boot-tools). Under the hood, two distinct tools cooperate: apt fetches repository metadata listed in /etc/apt/sources.list.d/ubuntu.sources, verifies GPG signatures (signed-by /usr/share/keyrings/*.gpg), solves the dependency graph, and hands downloaded .deb archives (ar containers holding control.tar.zst and data.tar.zst) to dpkg, which unpacks files and updates /var/lib/dpkg/status.

Two traps hit embedded engineers immediately. First, right after a VM boots, background unattended-upgrades holds an exclusive flock(2) on /var/lib/dpkg/lock-frontend; following bad forum advice to run sudo rm /var/lib/dpkg/lock* does not stop the running dpkg process and risks corrupting /var/lib/dpkg/status mid-write! Second, once you install host -dev libraries (zlib1g-dev, libasound2-dev), running a cross-compiled Makefile that invokes pkg-config --cflags --libs alsa silently returns host -I/usr/include and -L/usr/lib/x86_64-linux-gnu, causing arm-linux-gnueabihf-ld to abort with skipping incompatible /usr/lib/x86_64-linux-gnu/libasound.so!

fig_m03_l01_a.svg — PKG_CONFIG_LIBDIR replaces the default x86_64 search…

Figure 3.1a. PKG_CONFIG_LIBDIR replaces the default x86_64 search path (unlike PKG_CONFIG_PATH, which only prepends!), while PKG_CONFIG_SYSROOT_DIR prefixes -I and -L.

mental model: Think of dpkg as a warehouse inventory clerk who bolts crates onto shelves and writes every bolt's shelf coordinate into /var/lib/dpkg/status, while apt is the procurement planner who checks supplier wax seals (GPG -> SHA-256) and orders every prerequisite bracket first. Ripping the Occupied sign off the warehouse door (rm lock-frontend) while a clerk is still inside causes two clerks to overwrite the same ledger page! And setting PKG_CONFIG_PATH instead of PKG_CONFIG_LIBDIR tells the clerk *'check the ARM shelf first, and if a part is missing, silently grab an x86 truck bolt off the host shelf!'*

Where it stops working: flock(2) locks the kernel open file description (struct file / inode), not the directory pathname: unlinking /var/lib/dpkg/lock-frontend allows a second apt process to create a brand-new inode and acquire a second flock concurrently with the first!

definition (Advisory Inode Lock (flock) and PKG_CONFIG_LIBDIR vs PKG_CONFIG_PATH): When apt starts, it opens /var/lib/dpkg/lock-frontend and issues flock(fd, LOCK_EX | LOCK_NB). If the process crashes (SIGKILL or power loss), the Linux kernel closes fd automatically and releases the lock—leaving the zero-byte file on disk harmlessly! Only package state iU (unpacked, unconfigured) remains, which sudo dpkg --configure -a completes. In pkg-config, PKG_CONFIG_PATH prepends to /usr/lib/x86_64-linux-gnu/pkgconfig, whereas PKG_CONFIG_LIBDIR replaces the compiled-in host search list completely.

ast_m03_l01.svg — Never rm dpkg locks; use fuser + dpkg --configure -a…step 1/4
  1. Step 1. Use dpkg -S to identify which package owns a header or binary and dpkg -L to inspect installed utilities like mkimage.
  2. Step 2. Inspect live lock holders via fuser -v instead of unlinking lock files, then replay unfinished postinst scripts if idle.
  3. Step 3. Pin every repository in /etc/apt/sources.list.d/*.sources to a dedicated keyring file via Signed-By.
  4. Step 4. Export PKG_CONFIG_DIR, PKG_CONFIG_LIBDIR, and PKG_CONFIG_SYSROOT_DIR inside cross-build scripts and verify emitted flags.

Figure 3.1b. Never rm dpkg locks; use fuser + dpkg --configure -a and PKG_CONFIG_LIBDIR.

Inside .deb Archives, flock() Lifetimes & Cross-Sysroot Flag Rewriting

A .deb package is a standard Unix ar archive (ar t foo.deb) containing three members in fixed order: debian-binary (2.0\n), control.tar.zst (control metadata, md5sums, preinst/postinst scripts), and data.tar.zst (the FHS payload tree). During installation, dpkg transitions the package status in /var/lib/dpkg/status from not-installed -> unpacked (iU) -> installed (ii), syncing journal updates under /var/lib/dpkg/updates/.

Now trace what happens when cross-compiling an ALSA or DRM application for ARMv7-A against a staged sysroot at /opt/sysroots/armhf. Inside the sysroot, alsa.pc states prefix=/usr and includedir=${prefix}/include, so raw pkg-config --cflags alsa would print -I/usr/include! Setting PKG_CONFIG_SYSROOT_DIR=/opt/sysroots/armhf instructs pkg-config to rewrite every -I/usr/... and -L/usr/... token into -I/opt/sysroots/armhf/usr/include and -L/opt/sysroots/armhf/usr/lib/arm-linux-gnueabihf, while PKG_CONFIG_LIBDIR guarantees that missing target .pc files fail loudly instead of falling back to host x86_64 .pc files.

fig_m03_l01_b.svg — Combining PKG_CONFIG_LIBDIR (search isolation) with…

Figure 3.1b. Combining PKG_CONFIG_LIBDIR (search isolation) with PKG_CONFIG_SYSROOT_DIR (prefix rewriting) guarantees 100% EM_ARM header/library purity.

Environment / CommandBehavior on Missing Target .pcEmitted -I / -L FlagsCross-Build Safety
Unconfigured pkg-configReads host x86_64 .pc silently!-I/usr/include -L/usr/lib/x86_64-linux-gnuBroken: mixes x86 headers & fails ARM link
PKG_CONFIG_PATH=$SYS/... onlyFalls back to host x86_64 .pc!Bare -I/usr/include (no $SYS prefix!)Broken: silent fallback + unprefixed -I
PKG_CONFIG_LIBDIR=$SYS/... onlyFails cleanly (Package not found)Bare -I/usr/include (prefix=/usr unrewritten)Incomplete: still points -I at host /usr
PKG_CONFIG_DIR='' + LIBDIR + SYSROOT_DIRFails cleanly (Package not found)-I$SYS/usr/include -L$SYS/usr/lib/...Production safe: isolated search + prefixed paths
learner@ksa: ~/gl-e00/m03-l01
learner@ksa:~/gl-e00/m03-l01$ bat -H 6 -H 9 arm-pkg-config File: arm-pkg-config    #!/usr/bin/env bash    set -euo pipefail        : "${KSA_ARM_SYSROOT:?Set KSA_ARM_SYSROOT to your staged ARMv7 rootfs path}"      unset PKG_CONFIG_PATH    export PKG_CONFIG_DIR=""    export PKG_CONFIG_LIBDIR="${KSA_ARM_SYSROOT}/usr/lib/arm-linux-gnueabihf/pkgconfig:${KSA_ARM_SYSROOT}/usr/lib/pkgconfig:${KSA_ARM_SYSROOT}/usr/share/pkgconfig"  export PKG_CONFIG_SYSROOT_DIR="${KSA_ARM_SYSROOT}"        exec pkg-config "$@"
  1. Unsetting PKG_CONFIG_PATH and replacing PKG_CONFIG_LIBDIR cuts off /usr/lib/x86_64-linux-gnu completely.
  2. PKG_CONFIG_SYSROOT_DIR rewrites prefix=/usr inside target .pc files to ${KSA_ARM_SYSROOT}/usr.
dpkg(1) at a glance — GL-E00
dpkg(1)                     GL-E00 Quick Reference                     dpkg(1) NAME       dpkg, apt-get, pkg-config - Debian package ledger, signed repo solver,       and sysroot flags SYNOPSIS       dpkg -L <pkg> # List all files installed by <pkg> dpkg -S       /usr/bin/mkimage # Find which installed package owns a file sudo fuser       -v /var/lib/dpkg/lock-frontend sudo dpkg --configure -a # Finish       interrupted iU package configuration        CROSS-COMPILATION ENVIRONMENT PKG_CONFIG_DIR=""       PKG_CONFIG_LIBDIR="$SYSROOT/usr/lib/arm-linux-gnueabihf/pkgconfig:$SYSROOT/usr/share/pkgconfig"       PKG_CONFIG_SYSROOT_DIR="$SYSROOT" Kernel Systems Academy                   Lesson 3.1                    dpkg(1) GL-E00 quick reference · full manual page: man 1 dpkg 

Testing Kernel flock() Contention and Sysroot Flag Isolation in C11

In verify.c, we exercise real Linux kernel flock() advisory locking on two independent open file descriptions (open() called twice on the same lock path, mirroring two concurrent apt processes) and confirm that the second flock(fd2, LOCK_EX | LOCK_NB) fails immediately with EWOULDBLOCK—and succeeds the instant close(fd1) releases the kernel lock without deleting the lock file!

Next, rewrite_and_audit_cflags() models PKG_CONFIG_SYSROOT_DIR rewriting and inspects compiler/linker token streams to block bare -I/usr/include or -L/usr/lib/x86_64-linux-gnu host-poisoning flags.

learner@ksa: ~/gl-e00/m03-l01
learner@ksa:~/gl-e00/m03-l01$ bat -H 41 -H 47 verify.c File: verify.c    #define _DEFAULT_SOURCE    #include <errno.h>    #include <fcntl.h>    #include <stdio.h>    #include <stdlib.h>    #include <string.h>    #include <sys/file.h>    #include <unistd.h>        static int audit_cross_flags(const char *flags) {        char buf[320];        snprintf(buf, sizeof(buf), "%s", flags);        char *save = NULL;        for (char *t = strtok_r(buf, " ", &save); t; t = strtok_r(NULL, " ", &save)) {            if (strncmp(t, "-I/usr/", 7) == 0 || strcmp(t, "-I/usr") == 0) {                return -1; /* Unprefixed host /usr header leak */            }            if (strncmp(t, "-L/usr/", 7) == 0 || strstr(t, "x86_64-linux-gnu") != NULL) {                return -2; /* Host x86_64 library directory leak */            }        }        return 0;    }        static void apply_sysroot_prefix(const char *sysroot, const char *raw_flag,                                     char *out, size_t cap) {        if ((strncmp(raw_flag, "-I/", 3) == 0 || strncmp(raw_flag, "-L/", 3) == 0) &&            strncmp(raw_flag + 2, sysroot, strlen(sysroot)) != 0) {            snprintf(out, cap, "%.2s%s%s", raw_flag, sysroot, raw_flag + 2);        } else {            snprintf(out, cap, "%s", raw_flag);        }    }        int main(void) {        char lpath[] = "/tmp/ksa_dpkg_lock_XXXXXX";        int fd1 = mkstemp(lpath);        if (fd1 < 0) return 1;        int fd2 = open(lpath, O_RDWR);        if (fd2 < 0) return 1;          int r1 = flock(fd1, LOCK_EX | LOCK_NB);        errno = 0;        int r2_contend = flock(fd2, LOCK_EX | LOCK_NB);        int contend_eagain = (r2_contend == -1 && errno == EWOULDBLOCK);          /* Closing fd1 (as when apt exits or crashes) releases flock without unlink! */        close(fd1);        int r2_after = flock(fd2, LOCK_EX | LOCK_NB);        close(fd2);        unlink(lpath);            const char *leaked = "-I/usr/include/alsa -L/usr/lib/x86_64-linux-gnu -lasound";        char fixed_i[128], fixed_l[128], combined[320];        apply_sysroot_prefix("/opt/sysroots/armhf", "-I/usr/include/alsa", fixed_i, sizeof(fixed_i));        apply_sysroot_prefix("/opt/sysroots/armhf", "-L/usr/lib/arm-linux-gnueabihf", fixed_l, sizeof(fixed_l));        snprintf(combined, sizeof(combined), "%s %s -lasound", fixed_i, fixed_l);            int rc_bad = audit_cross_flags(leaked);        int rc_good = audit_cross_flags(combined);            printf("dpkg_flock: acquire1=%d contend_eblock=%d acquire_after_close=%d\n",               r1, contend_eagain, r2_after);        printf("pkgconfig_audit: host_leak_rc=%d sysroot_clean_rc=%d\n", rc_bad, rc_good);        printf("rewritten_flags: %s\n", combined);            return (r1 == 0 && contend_eagain == 1 && r2_after == 0 &&                rc_bad == -1 && rc_good == 0) ? 0 : 1;    }
  1. Second open() creates an independent struct file, so flock(LOCK_EX|LOCK_NB) returns -1 (EWOULDBLOCK).
  2. Closing fd1 immediately releases the kernel inode lock without unlinking the lock file.

Observing flock(LOCK_EX|LOCK_NB) = -1 EAGAIN in strace

Look right inside the strace capture: flock(3, LOCK_EX|LOCK_NB) = 0, followed by flock(4, LOCK_EX|LOCK_NB) = -1 EAGAIN (Resource temporarily unavailable), close(3) = 0, and flock(4, LOCK_EX|LOCK_NB) = 0! That single four-syscall sequence proves why an idle /var/lib/dpkg/lock-frontend file on disk never blocks apt once the owning process exits, and why rm /var/lib/dpkg/lock* is always wrong.

learner@ksa: ~/gl-e00/m03-l01
learner@ksa:~/gl-e00/m03-l01gcc -std=c11 -Wall -Wextra -Werror verify.c -o verifylearner@ksa:~/gl-e00/m03-l01./verifydpkg_flock: acquire1=0 contend_eblock=1 acquire_after_close=0pkgconfig_audit: host_leak_rc=-1 sysroot_clean_rc=0rewritten_flags: -I/opt/sysroots/armhf/usr/include/alsa -L/opt/sysroots/armhf/usr/lib/arm-linux-gnueabihf -lasoundlearner@ksa:~/gl-e00/m03-l01
strace — learner@ksa: ~/gl-e00/m03-l01
learner@ksa:~/gl-e00/m03-l01strace -e \trace=openat,flock,close,unlinkat,write ./verifyopenat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3close(3)                                = 0openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3close(3)                                = 0openat(AT_FDCWD, "/tmp/ksa_dpkg_lock_UA12qG", O_RDWR|O_CREAT|O_EXCL, 0600) = 3openat(AT_FDCWD, "/tmp/ksa_dpkg_lock_UA12qG", O_RDWR) = 4flock(3, LOCK_EX|LOCK_NB)               = 0flock(4, LOCK_EX|LOCK_NB)               = -1 EAGAIN (Resource temporarily unavailable)close(3)                                = 0flock(4, LOCK_EX|LOCK_NB)               = 0close(4)                                = 0write(1, "dpkg_flock: acquire1=0 contend_e"..., 229) = 229+++ exited with 0 +++

Multiarch Conflicts and Deprecated apt-key Anti-Patterns

Keeping host package management clean and cross-build pkg-config strictly fenced inside $SYSROOT prevents subtle ABI mismatches before they turn into mysterious target SIGSEGV crashes.

Using [trusted=yes] or Legacy apt-key add for Third-Party Toolchains:

  • Symptom: apt update prints Key is stored in legacy trusted.gpg keyring or accepts unsigned Packages files over plain HTTP.
  • Root Cause: [trusted=yes] disables GPG verification completely, while /etc/apt/trusted.gpg trusts a third-party vendor's key to sign packages for every repository on the system (including linux-image-generic!).
  • Fix: Place the dearmored .gpg key in /etc/apt/keyrings/<vendor>.gpg (0644) and scope it strictly inside that single .sources entry using Signed-By: /etc/apt/keyrings/<vendor>.gpg.

Autotools ./configure Runs Host pkg-config Instead of Cross Wrapper:

  • Symptom: You pass --host=arm-linux-gnueabihf to ./configure, yet the build still pulls /usr/include from the x86_64 host.
  • Root Cause: Autotools looks for arm-linux-gnueabihf-pkg-config first; if no prefixed wrapper exists on PATH, it falls back to bare host pkg-config with default host PKG_CONFIG_LIBDIR!
  • Fix: Either save our arm-pkg-config wrapper onto PATH named arm-linux-gnueabihf-pkg-config (chmod 0755), or export PKG_CONFIG=/path/to/arm-pkg-config explicitly.

Guided Practice

Modify verify.c to open lpath a third time (fd3) after unlinking lpath while fd2 still holds LOCK_EX (unlink(lpath) -> fd3 = open(lpath, O_CREAT|O_RDWR, 0600) -> flock(fd3, LOCK_EX|LOCK_NB)). Observe that flock(fd3) returns 0—proving in C11 how rm /var/lib/dpkg/lock-frontend lets two dpkg processes corrupt /var/lib/dpkg/status simultaneously!

Independent Practice

Write a C11 parser for /var/lib/dpkg/status stanzas (Package:, Status:, Architecture:) that flags any package not in install ok installed (ii) state so CI container health checks detect interrupted iU transactions.

Verification Checks

quiz · 1 of 3

Why does running sudo rm /var/lib/dpkg/lock-frontend when apt says Could not get lock risk corrupting /var/lib/dpkg/status?

quiz · 2 of 3

When cross-compiling an ARMv7-A user-space daemon against $SYSROOT, why must you set PKG_CONFIG_LIBDIR instead of only PKG_CONFIG_PATH?

quiz · 3 of 3

Which command identifies the exact installed Debian/Ubuntu package that placed /usr/bin/mkimage onto your workstation?

Key takeaways

  • Debian and Ubuntu split package management into dpkg (/var/lib/dpkg/status local archive installer and file-ownership ledger) and apt (cryptographically signed InRelease dependency solver).
  • APT verifies a three-link trust chain—GPG signed-by keyring on InRelease, SHA-256 of Packages.xz, and SHA-256 of each .deb—while serializing mutations via kernel flock() on /var/lib/dpkg/lock-frontend.
  • Cross-compiling against an ARMv7 target sysroot requires setting PKG_CONFIG_DIR='', PKG_CONFIG_LIBDIR to the sysroot pkgconfig directories, and PKG_CONFIG_SYSROOT_DIR so host /usr/include paths never leak.
  • When an interrupted dpkg run leaves half-configured packages (state iU) and zero live apt/dpkg processes hold the flock, dpkg --configure -a replays idempotent postinst scripts safely without deleting lock files.
Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure