From a0925d2532fbfe09801e26591a4dae1921910045 Mon Sep 17 00:00:00 2001 From: Phil Elwell Date: Wed, 18 Nov 2026 16:20:44 +0000 Subject: [PATCH 1/8] dtoverlay: Move the state directory to /run and check it The state directory, /tmp/.dtoverlays, has a fixed name in a world-writable directory. Any local user can create it first (running "dtoverlay -l" as an unprivileged user was enough), and root then replays the .dtbo files it contains into the kernel and writes files through any symlinks planted there. Move it to /run/dtoverlays, which only root can write to and which is cleared at boot (as the configfs state is). Only create it when running as root, and refuse to use it unless it is a real directory owned and only writable by root. If it doesn't exist, non-root users listing overlays just see that none are loaded. Co-Authored-By: Claude Opus 5.5 --- dtmerge/dtoverlay_main.c | 52 +++++++++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/dtmerge/dtoverlay_main.c b/dtmerge/dtoverlay_main.c index 081d6f4..0adb76e 100644 --- a/dtmerge/dtoverlay_main.c +++ b/dtmerge/dtoverlay_main.c @@ -43,7 +43,7 @@ modification, are permitted provided that the following conditions are met: #define CFG_DIR_1 "/sys/kernel/config" #define CFG_DIR_2 "/config" #define DT_SUBDIR "/device-tree" -#define WORK_DIR "/tmp/.dtoverlays" +#define WORK_DIR "/run/dtoverlays" #define OVERLAY_SRC_SUBDIR "overlays" #define README_FILE "README" #define DT_OVERLAYS_SUBDIR "overlays" @@ -88,6 +88,7 @@ static int dtoverlay_list(STATE_T *state); static int dtoverlay_list_all(STATE_T *state); static void usage(void); static void root_check(void); +static int check_work_dir(const char *dir, int create); static void overlay_help(const char *overlay, const char **params); @@ -120,6 +121,7 @@ int main(int argc, const char **argv) int ret = 0; STATE_T *state = NULL; const char *cfg_dir; + int have_work_dir = 1; cmd_name = argv[0]; if (strrchr(cmd_name, '/')) @@ -251,10 +253,11 @@ int main(int argc, const char **argv) goto orderly_exit; } - if (!dir_exists(work_dir)) + if (!dry_run) { - if (mkdir(work_dir, DIR_MODE) != 0) - fatal_error("Failed to create '%s' - %d", work_dir, errno); + /* Only root may create the state directory. Others can still list + the active overlays if it exists. */ + have_work_dir = check_work_dir(work_dir, getuid() == 0); } error_file = sprintf_dup("%s/%s", work_dir, "error.dtb"); @@ -290,7 +293,7 @@ int main(int argc, const char **argv) if (!dir_exists(dt_overlays_dir)) fatal_error("configfs overlays folder not found - incompatible kernel"); - state = read_state(work_dir); + state = read_state(have_work_dir ? work_dir : NULL); if (!state) fatal_error("Failed to read state"); } @@ -1128,6 +1131,32 @@ static void root_check(void) fatal_error("Must be run as root - try 'sudo %s ...'", cmd_name); } +/* Returns 1 if the directory exists (creating it if requested), 0 if it + doesn't. Exits if it exists but can't be trusted. */ +static int check_work_dir(const char *dir, int create) +{ + struct stat st; + + if (create && (mkdir(dir, DIR_MODE) != 0) && (errno != EEXIST)) + fatal_error("Failed to create '%s' - %s", dir, strerror(errno)); + + if (lstat(dir, &st) != 0) + { + if (errno == ENOENT) + return 0; + fatal_error("Failed to stat '%s' - %s", dir, strerror(errno)); + } + + /* The contents are replayed into the kernel, so they must only be + writable by root */ + if (!S_ISDIR(st.st_mode) || (st.st_uid != 0) || + (st.st_mode & (S_IWGRP | S_IWOTH))) + fatal_error("'%s' is not a directory owned and only writable by root", + dir); + + return 1; +} + static void overlay_help(const char *overlay, const char **params) { OVERLAY_HELP_STATE_T *state; @@ -1284,7 +1313,18 @@ static STATE_T *read_state(const char *dir) if (state) { - state->count = scandir(dir, &state->namelist, seq_filter, seq_compare); + state->count = 0; + state->namelist = NULL; + if (dir) + { + state->count = scandir(dir, &state->namelist, seq_filter, + seq_compare); + if (state->count < 0) + { + free(state); + return NULL; + } + } for (i = 0; i < state->count; i++) { From 9af0ccb4b92fcab5edfd57929e874d24a808a4d9 Mon Sep 17 00:00:00 2001 From: Phil Elwell Date: Wed, 18 Nov 2026 16:21:25 +0000 Subject: [PATCH 2/8] dtoverlay: Serialise instances with a lock on the state Nothing stops two instances of dtoverlay/dtparam from running at once, and the results can be bad: - Both read the same overlay count and give their overlays the same sequence number, breaking the numbering that removal relies on. - A removal deletes and replays the later overlays, and an add that runs during it corrupts the sequence. - Concurrent dtparam invocations share base.dtb, and can take a snapshot of /proc/device-tree while another overlay is being applied. - Listing can read a .dtbo that is still being written. Take an flock() on /run/dtoverlays/lock before reading the state and hold it until exit, exclusively for adds and removals, shared for listing. The kernel releases it however the process exits, including through fatal_error(). Rather than block forever, give up after 30s. The dtoverlay-pre/post hooks run with the lock held, so a hook that tried to add or remove an overlay would deadlock (or recurse). Mark the hooks' environment and make that an error; listing from a hook is still allowed, and skips the lock because the parent already holds it exclusively. Also check for root before touching the state when adding or removing, rather than after reading it. Co-Authored-By: Claude Opus 5.5 --- dtmerge/dtoverlay_main.c | 77 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/dtmerge/dtoverlay_main.c b/dtmerge/dtoverlay_main.c index 0adb76e..c5181b2 100644 --- a/dtmerge/dtoverlay_main.c +++ b/dtmerge/dtoverlay_main.c @@ -33,6 +33,8 @@ modification, are permitted provided that the following conditions are met: #include #include #include +#include +#include #include @@ -49,6 +51,11 @@ modification, are permitted provided that the following conditions are met: #define DT_OVERLAYS_SUBDIR "overlays" #define DTOVERLAY_PATH_MAX 128 #define DIR_MODE 0755 +#define LOCK_FILE "lock" +#define LOCK_POLL_MS 50 +#define LOCK_TIMEOUT_MS 30000 +/* Set in the environment of the dtoverlay-pre/post hooks */ +#define HOOK_ENV "DTOVERLAY_IN_HOOK" enum { @@ -89,6 +96,7 @@ static int dtoverlay_list_all(STATE_T *state); static void usage(void); static void root_check(void); static int check_work_dir(const char *dir, int create); +static void lock_state(int exclusive); static void overlay_help(const char *overlay, const char **params); @@ -107,6 +115,7 @@ const char *error_file = NULL; const char *platform_string; int platform_string_len; int dry_run = 0; +static int lock_fd = -1; char cell_source_loc[DTOVERLAY_MAX_PATH]; int cell_source_loc_len; @@ -122,6 +131,8 @@ int main(int argc, const char **argv) STATE_T *state = NULL; const char *cfg_dir; int have_work_dir = 1; + int modifying; + int in_hook; cmd_name = argv[0]; if (strrchr(cmd_name, '/')) @@ -221,6 +232,16 @@ int main(int argc, const char **argv) dtoverlay_enable_debug(opt_verbose); + modifying = !dry_run && ((opt == OPT_ADD) || (opt == OPT_REMOVE) || + (opt == OPT_REMOVE_FROM)); + in_hook = (getenv(HOOK_ENV) != NULL); + + /* The hooks run while the state is locked, so any attempt to change it + from a hook would deadlock (and risks infinite recursion) */ + if (modifying && in_hook) + fatal_error("%s can't add or remove overlays from a dtoverlay-pre or " + "dtoverlay-post hook", cmd_name); + if (!overlay_src_dir) { /* Find the overlays and README */ @@ -253,11 +274,20 @@ int main(int argc, const char **argv) goto orderly_exit; } + if (modifying) + root_check(); + if (!dry_run) { /* Only root may create the state directory. Others can still list the active overlays if it exists. */ have_work_dir = check_work_dir(work_dir, getuid() == 0); + + /* Serialise against other instances, holding the lock until exit. + A hook runs while its parent holds the lock exclusively, so the + state can't change under it and it must not wait for the lock. */ + if (have_work_dir && !in_hook) + lock_state(modifying); } error_file = sprintf_dup("%s/%s", work_dir, "error.dtb"); @@ -305,7 +335,7 @@ int main(int argc, const char **argv) case OPT_REMOVE_FROM: if (!dry_run) { - root_check(); + setenv(HOOK_ENV, "1", 1); run_cmd("which dtoverlay-pre >/dev/null 2>&1 && dtoverlay-pre"); } break; @@ -1157,6 +1187,51 @@ static int check_work_dir(const char *dir, int create) return 1; } +/* Take a shared or exclusive lock on the state. It is released when the + process exits, however that happens. */ +static void lock_state(int exclusive) +{ + int op = (exclusive ? LOCK_EX : LOCK_SH) | LOCK_NB; + int waited_ms = 0; + + if (lock_fd < 0) + { + const char *lock_path = sprintf_dup("%s/%s", work_dir, LOCK_FILE); + + if (getuid() == 0) + lock_fd = open(lock_path, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, + 0644); + else + lock_fd = open(lock_path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); + + if (lock_fd < 0) + { + /* Root has never modified the state, so there is nothing to + protect */ + if ((errno == ENOENT) && (getuid() != 0)) + return; + fatal_error("Failed to open '%s' - %s", lock_path, + strerror(errno)); + } + free_string(lock_path); + } + + while (flock(lock_fd, op) != 0) + { + if (errno == EINTR) + continue; + if (errno != EWOULDBLOCK) + fatal_error("Failed to lock '%s' - %s", work_dir, strerror(errno)); + if (waited_ms == 0) + dtoverlay_debug("waiting for another instance to finish"); + if (waited_ms >= LOCK_TIMEOUT_MS) + fatal_error("Timed out waiting for another dtoverlay or dtparam " + "to finish"); + usleep(LOCK_POLL_MS * 1000); + waited_ms += LOCK_POLL_MS; + } +} + static void overlay_help(const char *overlay, const char **params) { OVERLAY_HELP_STATE_T *state; From ec9ddd249bb949ff92cb1359198f12b2f5dc2c54 Mon Sep 17 00:00:00 2001 From: Phil Elwell Date: Wed, 18 Nov 2026 16:21:55 +0000 Subject: [PATCH 3/8] dtoverlay: Write the saved overlays atomically The .dtbo files in the state directory were written in place, so killing dtoverlay part-way through a write left a truncated file that a later removal would try to replay. Write to a temporary file and rename it into place. The temporary name starts with '.', so a leftover one isn't mistaken for an overlay. Also fail the add if the file can't be written, instead of applying whatever is there. dtoverlay_list passed the result of dtoverlay_load_dtb to dtoverlay_dtb_trailer without checking it for NULL, so an unreadable file crashed it; report the overlay as unreadable instead. In the library, dtoverlay_save_dtb leaked the FILE when a write failed, and ignored the result of fclose, which is where errors in buffered data are reported. dtoverlay_save_dtb is also used to write to configfs, so it still writes directly to the named file. Co-Authored-By: Claude Opus 5.5 --- dtmerge/dtoverlay.c | 18 +++++++++++------- dtmerge/dtoverlay_main.c | 32 +++++++++++++++++++++++++++++--- 2 files changed, 40 insertions(+), 10 deletions(-) diff --git a/dtmerge/dtoverlay.c b/dtmerge/dtoverlay.c index 1cbb5ab..7c7d147 100644 --- a/dtmerge/dtoverlay.c +++ b/dtmerge/dtoverlay.c @@ -2972,18 +2972,23 @@ int dtoverlay_save_dtb(const DTBLOB_T *dtb, const char *filename) { dtoverlay_error("fwrite failed"); err = -2; - goto error_exit; } - if (dtb->trailer_len && - (fwrite(dtb->trailer, dtb->trailer_len, 1, fp) != 1)) + else if (dtb->trailer_len && + (fwrite(dtb->trailer, dtb->trailer_len, 1, fp) != 1)) { dtoverlay_error("fwrite failed"); err = -2; - goto error_exit; } - dtoverlay_debug("wrote %ld bytes to '%s'", len, filename); - fclose(fp); + /* Buffered data is only written (and the error reported) here */ + if ((fclose(fp) != 0) && !err) + { + dtoverlay_error("failed to write '%s'", filename); + err = -2; + } + + if (!err) + dtoverlay_debug("wrote %d bytes to '%s'", len, filename); } else { @@ -2991,7 +2996,6 @@ int dtoverlay_save_dtb(const DTBLOB_T *dtb, const char *filename) err = -1; } - error_exit: return err; } diff --git a/dtmerge/dtoverlay_main.c b/dtmerge/dtoverlay_main.c index c5181b2..81792f9 100644 --- a/dtmerge/dtoverlay_main.c +++ b/dtmerge/dtoverlay_main.c @@ -101,6 +101,7 @@ static void lock_state(int exclusive); static void overlay_help(const char *overlay, const char **params); static int apply_overlay(const char *overlay_file, const char *overlay); +static int save_dtb_atomic(DTBLOB_T *dtb, const char *filename); static int overlay_applied(const char *overlay_dir); static STATE_T *read_state(const char *dir); @@ -791,8 +792,10 @@ static int dtoverlay_add(STATE_T *state, const char *overlay, /* then write the overlay to the file */ dtoverlay_pack_dtb(overlay_dtb); - dtoverlay_save_dtb(overlay_dtb, overlay_file); + err = save_dtb_atomic(overlay_dtb, overlay_file); dtoverlay_free_dtb(overlay_dtb); + if (err) + return error("Failed to write '%s'", overlay_file); if (!dry_run && !apply_overlay(overlay_file, overlay_name)) { @@ -1014,15 +1017,19 @@ static int dtoverlay_list(STATE_T *state) saved_overlay = sprintf_dup("%s/%s", work_dir, name); dtb = dtoverlay_load_dtb(saved_overlay, 0); + free_string(saved_overlay); - if (dtoverlay_dtb_trailer(dtb)) + if (!dtb) + printf("%d: %.*s \n", i, (int)(right - left), left); + else if (dtoverlay_dtb_trailer(dtb)) printf("%d: %.*s %.*s\n", i, (int)(right - left), left, dtoverlay_dtb_trailer_len(dtb), (char *)dtoverlay_dtb_trailer(dtb)); else printf("%d: %.*s\n", i, (int)(right - left), left); - dtoverlay_free_dtb(dtb); + if (dtb) + dtoverlay_free_dtb(dtb); } } @@ -1347,6 +1354,25 @@ static int apply_overlay(const char *overlay_file, const char *overlay) return ret; } +/* Write a DTB so that a reader never sees a partial file, even if this + process is killed. The state lives on a tmpfs that doesn't survive a + power cut, so there is no need to fsync. The file must be in work_dir; + the temporary name is hidden from seq_filter. */ +static int save_dtb_atomic(DTBLOB_T *dtb, const char *filename) +{ + const char *tmp_file = sprintf_dup("%s/.new.dtbo", work_dir); + int err; + + err = dtoverlay_save_dtb(dtb, tmp_file); + if (!err && (rename(tmp_file, filename) != 0)) + err = -1; + if (err) + unlink(tmp_file); + free_string(tmp_file); + + return err; +} + static int overlay_applied(const char *overlay_dir) { char status[7] = { '\0' }; From 0f018672419b6c246836fb31d3a2d69f9496a761 Mon Sep 17 00:00:00 2001 From: Phil Elwell Date: Wed, 18 Nov 2026 16:22:15 +0000 Subject: [PATCH 4/8] dtoverlay: Tidy up set-up races and error.dtb handling Two instances starting at once could both find /config missing, and the loser's mkdir failed with EEXIST, which was fatal; accept EEXIST. They could also both find configfs unmounted and mount it twice. The mount now happens under the exclusive lock; listing only takes a shared lock, so it upgrades the lock before mounting. When applying an overlay failed, dtoverlay_add moved it to error.dtb and freed error_file without clearing it. If a later step then succeeded, as can happen while replaying overlays during a removal, main() passed the freed string to unlink. Clear error_file, which also keeps the error.dtb that has just been written. Co-Authored-By: Claude Opus 5.5 --- dtmerge/dtoverlay_main.c | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/dtmerge/dtoverlay_main.c b/dtmerge/dtoverlay_main.c index 81792f9..9ffb28d 100644 --- a/dtmerge/dtoverlay_main.c +++ b/dtmerge/dtoverlay_main.c @@ -298,12 +298,14 @@ int main(int argc, const char **argv) { root_check(); + /* Only one instance may mount configfs. Listing only holds a shared + lock, so upgrade it (by now the root user has a lock file). */ + if (!modifying && !in_hook) + lock_state(1); + cfg_dir = CFG_DIR_2; - if (!dir_exists(cfg_dir)) - { - if (mkdir(cfg_dir, DIR_MODE) != 0) - fatal_error("Failed to create '%s' - %d", cfg_dir, errno); - } + if ((mkdir(cfg_dir, DIR_MODE) != 0) && (errno != EEXIST)) + fatal_error("Failed to create '%s' - %s", cfg_dir, strerror(errno)); cfg_dir = CFG_DIR_2 DT_SUBDIR; if (!dir_exists(cfg_dir) && @@ -801,8 +803,10 @@ static int dtoverlay_add(STATE_T *state, const char *overlay, { if (error_file) { + /* Keep the failed overlay, and don't delete it on exit */ rename(overlay_file, error_file); free_string(error_file); + error_file = NULL; } return 1; } From e3051986fa423c5a53ce569c81e0ea859fbe8d05 Mon Sep 17 00:00:00 2001 From: Phil Elwell Date: Wed, 18 Nov 2026 16:35:23 +0000 Subject: [PATCH 5/8] dtoverlay: Fix the fallback mounting of configfs If configfs wasn't at /sys/kernel/config, dtoverlay created /config and then tried to mount configfs on /config/device-tree, which can't exist until configfs is mounted at /config - so the mount always failed. It also ran mount via the shell and then reported errno, which said nothing about why mount had failed. Mount configfs on /run/dtoverlays/configfs instead, which is on a tmpfs and in a directory already checked to belong to root, using mount(2). Then check that it has a device-tree folder, unmounting it and failing if it doesn't. Co-Authored-By: Claude Opus 5.5 --- dtmerge/dtoverlay_main.c | 39 +++++++++++++++++++++++++++------------ 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/dtmerge/dtoverlay_main.c b/dtmerge/dtoverlay_main.c index 9ffb28d..f9672e7 100644 --- a/dtmerge/dtoverlay_main.c +++ b/dtmerge/dtoverlay_main.c @@ -35,15 +35,16 @@ modification, are permitted provided that the following conditions are met: #include #include #include +#include #include #include "dtoverlay.h" #include "utils.h" - -#define CFG_DIR_1 "/sys/kernel/config" -#define CFG_DIR_2 "/config" +#define CFG_DIR "/sys/kernel/config" +/* Where to mount configfs if it isn't at CFG_DIR (relative to WORK_DIR) */ +#define CFG_MOUNT_SUBDIR "configfs" #define DT_SUBDIR "/device-tree" #define WORK_DIR "/run/dtoverlays" #define OVERLAY_SRC_SUBDIR "overlays" @@ -293,9 +294,14 @@ int main(int argc, const char **argv) error_file = sprintf_dup("%s/%s", work_dir, "error.dtb"); - cfg_dir = CFG_DIR_1 DT_SUBDIR; + cfg_dir = CFG_DIR DT_SUBDIR; if (!dry_run && !dir_exists(cfg_dir)) { + /* configfs isn't mounted in the usual place, so mount it in the + state directory, which is on a tmpfs */ + const char *mount_dir = sprintf_dup("%s/%s", work_dir, + CFG_MOUNT_SUBDIR); + root_check(); /* Only one instance may mount configfs. Listing only holds a shared @@ -303,14 +309,23 @@ int main(int argc, const char **argv) if (!modifying && !in_hook) lock_state(1); - cfg_dir = CFG_DIR_2; - if ((mkdir(cfg_dir, DIR_MODE) != 0) && (errno != EEXIST)) - fatal_error("Failed to create '%s' - %s", cfg_dir, strerror(errno)); - - cfg_dir = CFG_DIR_2 DT_SUBDIR; - if (!dir_exists(cfg_dir) && - (run_cmd("mount -t configfs none '%s'", cfg_dir) != 0)) - fatal_error("Failed to mount configfs - %d", errno); + cfg_dir = sprintf_dup("%s%s", mount_dir, DT_SUBDIR); + if (!dir_exists(cfg_dir)) + { + if ((mkdir(mount_dir, DIR_MODE) != 0) && (errno != EEXIST)) + fatal_error("Failed to create '%s' - %s", mount_dir, + strerror(errno)); + if (mount("configfs", mount_dir, "configfs", + MS_NOSUID | MS_NODEV | MS_NOEXEC, NULL) != 0) + fatal_error("Failed to mount configfs on '%s' - %s", + mount_dir, strerror(errno)); + if (!dir_exists(cfg_dir)) + { + umount(mount_dir); + fatal_error("configfs has no '%s' folder - incompatible kernel", + DT_SUBDIR + 1); + } + } } if (!platform_string) From fecd3f8d244fd660ccba9119f76347e7da4c2551 Mon Sep 17 00:00:00 2001 From: Phil Elwell Date: Wed, 18 Nov 2026 16:37:58 +0000 Subject: [PATCH 6/8] dtoverlay: Defer termination signals while changing overlays Removing an overlay deletes the configfs directories of it and every later overlay, then renumbers and reapplies the survivors. Being interrupted part-way (Ctrl-C, kill, or the terminal hanging up) left configfs and the state directory out of step, with no way to recover short of a reboot. Block SIGHUP, SIGINT, SIGQUIT, SIGTERM and SIGPIPE while an overlay is being added or removed, and unblock them afterwards, at which point any that arrived are acted on (so the dtoverlay-post hook doesn't run). A signal handler couldn't clean up safely, and the only consistent state to clean up to is the finished one anyway. SIGKILL still can't be stopped. Co-Authored-By: Claude Opus 5.5 --- dtmerge/dtoverlay_main.c | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/dtmerge/dtoverlay_main.c b/dtmerge/dtoverlay_main.c index f9672e7..a27ad0a 100644 --- a/dtmerge/dtoverlay_main.c +++ b/dtmerge/dtoverlay_main.c @@ -33,6 +33,7 @@ modification, are permitted provided that the following conditions are met: #include #include #include +#include #include #include #include @@ -98,6 +99,7 @@ static void usage(void); static void root_check(void); static int check_work_dir(const char *dir, int create); static void lock_state(int exclusive); +static void defer_signals(int defer); static void overlay_help(const char *overlay, const char **params); @@ -361,6 +363,11 @@ int main(int argc, const char **argv) break; } + /* Don't let a signal leave configfs and the state directory out of + step - act on it once they agree again */ + if (modifying) + defer_signals(1); + switch (opt) { case OPT_ADD: @@ -383,6 +390,10 @@ int main(int argc, const char **argv) break; } + /* Any pending signal is delivered here, and the hook doesn't run */ + if (modifying) + defer_signals(0); + switch (opt) { case OPT_ADD: @@ -1258,6 +1269,31 @@ static void lock_state(int exclusive) } } +/* Block (or unblock) the signals that would normally terminate the process + when sent by a user or a terminal. Unblocking delivers any that arrived + in the meantime. SIGKILL can't be blocked. Child processes (dtc, when a + dtparam is regenerated) inherit the blocked set. */ +static void defer_signals(int defer) +{ + static sigset_t old_set; + sigset_t set; + + if (defer) + { + sigemptyset(&set); + sigaddset(&set, SIGHUP); + sigaddset(&set, SIGINT); + sigaddset(&set, SIGQUIT); + sigaddset(&set, SIGTERM); + sigaddset(&set, SIGPIPE); + sigprocmask(SIG_BLOCK, &set, &old_set); + } + else + { + sigprocmask(SIG_SETMASK, &old_set, NULL); + } +} + static void overlay_help(const char *overlay, const char **params) { OVERLAY_HELP_STATE_T *state; From 4eff640557a1cb650b0bfc7b7b8b45766aac9d30 Mon Sep 17 00:00:00 2001 From: Phil Elwell Date: Wed, 18 Nov 2026 16:39:52 +0000 Subject: [PATCH 7/8] dtoverlay: Keep the numbering intact when a reapply fails When removing an overlay, the later overlays are renumbered and reapplied. If one of them failed to apply, its renumbered .dtbo was left in the state directory without the count being advanced, so the next overlay was given the same number, or the next run believed the failed overlay was loaded. The same happened in dtoverlay_add when a failure had already used up error.dtb. Discard the file of an overlay that fails to apply: move the first one to error.dtb as before, and delete any others. It then drops out of the sequence and the numbering stays contiguous. Name the overlay in the error message (it always said "dtparam"), and exit with an error if any overlay was lost. Co-Authored-By: Claude Opus 5.5 --- dtmerge/dtoverlay_main.c | 45 +++++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/dtmerge/dtoverlay_main.c b/dtmerge/dtoverlay_main.c index a27ad0a..1cbad8f 100644 --- a/dtmerge/dtoverlay_main.c +++ b/dtmerge/dtoverlay_main.c @@ -105,6 +105,7 @@ static void overlay_help(const char *overlay, const char **params); static int apply_overlay(const char *overlay_file, const char *overlay); static int save_dtb_atomic(DTBLOB_T *dtb, const char *filename); +static void discard_overlay_file(const char *filename); static int overlay_applied(const char *overlay_dir); static STATE_T *read_state(const char *dir); @@ -827,13 +828,7 @@ static int dtoverlay_add(STATE_T *state, const char *overlay, if (!dry_run && !apply_overlay(overlay_file, overlay_name)) { - if (error_file) - { - /* Keep the failed overlay, and don't delete it on exit */ - rename(overlay_file, error_file); - free_string(error_file); - error_file = NULL; - } + discard_overlay_file(overlay_file); return 1; } @@ -847,6 +842,7 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) char *end; int overlay_len; int count = state->count; + int failed = 0; int rmpos; int i; @@ -960,6 +956,7 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) if (!dtb) { error("Failed to re-apply dtparam"); + failed++; continue; } @@ -968,6 +965,7 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) { error("Failed to re-apply dtparam"); dtoverlay_free_dtb(dtb); + failed++; continue; } @@ -988,6 +986,7 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) { error("out of memory re-applying dtparam"); dtoverlay_free_dtb(dtb); + failed++; continue; } @@ -998,7 +997,8 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) } paramv[j] = NULL; - /* Create the new overlay */ + /* Create the new overlay. If it can't be applied, the + file is discarded. */ ret = dtoverlay_add(state, "dtparam", paramc, paramv); free(paramv); dtoverlay_free_dtb(dtb); @@ -1007,10 +1007,18 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) { rename(filename, new_file); ret = !apply_overlay(new_file, new_name); + if (ret != 0) + discard_overlay_file(new_file); } + free_string(new_file); + free_string(new_name); if (ret != 0) { - error("Failed to re-apply dtparam"); + /* Its file has gone, so the next overlay takes its + number */ + error("Failed to re-apply '%.*s' - it is no longer loaded", + len, left); + failed++; continue; } state->count++; @@ -1018,7 +1026,7 @@ static int dtoverlay_remove(STATE_T *state, const char *overlay, int and_later) } } - return 0; + return failed ? 1 : 0; } static int dtoverlay_list(STATE_T *state) @@ -1428,6 +1436,23 @@ static int save_dtb_atomic(DTBLOB_T *dtb, const char *filename) return err; } +/* Remove the file of an overlay that failed to apply from the sequence. + The first failure is kept as error.dtb for diagnosis. */ +static void discard_overlay_file(const char *filename) +{ + if (error_file) + { + rename(filename, error_file); + free_string(error_file); + /* Don't delete it on exit */ + error_file = NULL; + } + else + { + unlink(filename); + } +} + static int overlay_applied(const char *overlay_dir) { char status[7] = { '\0' }; From 020b1fa191ff0d17cdfd5483b303fa4c822678c3 Mon Sep 17 00:00:00 2001 From: Phil Elwell Date: Thu, 19 Nov 2026 09:15:00 +0000 Subject: [PATCH 8/8] dtoverlay: Stop signals killing dtc while they are deferred Signals from a terminal or from timeout are sent to the whole process group. While dtoverlay was deferring them during a removal, the dtc that regenerates a dtparam still received them, and testing on a Pi 5 showed that a SIGINT or SIGTERM at the wrong moment killed it. The state stayed consistent, but the dtparam was dropped with "Failed to read active DTB". Run dtc with fork/exec rather than system(), and while the parent is deferring signals make the child ignore them, which survives exec. This also stops the filename being passed through a shell. Co-Authored-By: Claude Opus 5.5 --- dtmerge/dtoverlay_main.c | 70 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 63 insertions(+), 7 deletions(-) diff --git a/dtmerge/dtoverlay_main.c b/dtmerge/dtoverlay_main.c index 1cbad8f..6fd11aa 100644 --- a/dtmerge/dtoverlay_main.c +++ b/dtmerge/dtoverlay_main.c @@ -37,6 +37,7 @@ modification, are permitted provided that the following conditions are met: #include #include #include +#include #include @@ -100,6 +101,7 @@ static void root_check(void); static int check_work_dir(const char *dir, int create); static void lock_state(int exclusive); static void defer_signals(int defer); +static int read_live_dt(const char *dtb_file); static void overlay_help(const char *overlay, const char **params); @@ -679,8 +681,7 @@ static int dtoverlay_add(STATE_T *state, const char *overlay, { /* Convert /proc/device-tree to a .dtb and load it */ overlay_file = sprintf_dup("%s/%s", work_dir, "base.dtb"); - if (run_cmd("dtc -I fs -O dtb -o '%s' /proc/device-tree 1>/dev/null 2>&1", - overlay_file) != 0) + if (read_live_dt(overlay_file) != 0) return error("Failed to read active DTB"); } else if ((len > 0) && (strcmp(overlay + len, ".dtbo") == 0)) @@ -1281,19 +1282,25 @@ static void lock_state(int exclusive) when sent by a user or a terminal. Unblocking delivers any that arrived in the meantime. SIGKILL can't be blocked. Child processes (dtc, when a dtparam is regenerated) inherit the blocked set. */ +static const int deferred_signals[] = +{ + SIGHUP, SIGINT, SIGQUIT, SIGTERM, SIGPIPE +}; + +#define NUM_DEFERRED_SIGNALS \ + (int)(sizeof(deferred_signals) / sizeof(deferred_signals[0])) + static void defer_signals(int defer) { static sigset_t old_set; sigset_t set; + int i; if (defer) { sigemptyset(&set); - sigaddset(&set, SIGHUP); - sigaddset(&set, SIGINT); - sigaddset(&set, SIGQUIT); - sigaddset(&set, SIGTERM); - sigaddset(&set, SIGPIPE); + for (i = 0; i < NUM_DEFERRED_SIGNALS; i++) + sigaddset(&set, deferred_signals[i]); sigprocmask(SIG_BLOCK, &set, &old_set); } else @@ -1302,6 +1309,55 @@ static void defer_signals(int defer) } } +/* Snapshot the live device tree into a .dtb file using dtc. Signals sent + to the process group (Ctrl-C, timeout) would otherwise kill dtc even + while they are deferred here, losing a dtparam that is being regenerated, + so while they are deferred the child ignores them - an ignored signal + stays ignored across exec. Running dtc directly also avoids passing the + filename through a shell. */ +static int read_live_dt(const char *dtb_file) +{ + sigset_t blocked; + int status; + pid_t pid; + int i; + + dtoverlay_debug("dtc -I fs -O dtb -o %s /proc/device-tree", dtb_file); + + pid = fork(); + if (pid < 0) + return -1; + + if (pid == 0) + { + int fd = open("/dev/null", O_RDWR); + if (fd >= 0) + { + dup2(fd, STDOUT_FILENO); + dup2(fd, STDERR_FILENO); + } + + sigprocmask(SIG_BLOCK, NULL, &blocked); + for (i = 0; i < NUM_DEFERRED_SIGNALS; i++) + { + if (sigismember(&blocked, deferred_signals[i])) + signal(deferred_signals[i], SIG_IGN); + } + + execlp("dtc", "dtc", "-I", "fs", "-O", "dtb", "-o", dtb_file, + "/proc/device-tree", (char *)NULL); + _exit(127); + } + + while (waitpid(pid, &status, 0) < 0) + { + if (errno != EINTR) + return -1; + } + + return (WIFEXITED(status) && (WEXITSTATUS(status) == 0)) ? 0 : -1; +} + static void overlay_help(const char *overlay, const char **params) { OVERLAY_HELP_STATE_T *state;