From 518070c5d7d10ab9b52806fba0bb738fa920fbd1 Mon Sep 17 00:00:00 2001 From: nicksinas Date: Thu, 26 Nov 2026 21:19:44 -0600 Subject: [PATCH 1/4] fix(runtime): remove dropped var_files from var-staging Var staging persists between builds and the var image is made from it. The var_files copies only added files, so a file removed from an extension's or the runtime's var_files stayed in var staging and reached the device on the next provision. - Move the extension var_files copy into ext_var_files_script - Record every path the var_files copies place, NUL-delimited, in .stamps/runtime//var-staging.files - Before anything writes to var staging, remove each recorded path that the current var_files no longer provide; remove a recorded directory only when it is empty, and never touch unrecorded paths or paths that leave var staging - Test the prune, copy and record steps with bash against a tempdir Refs: (bug)avocado-cli-S3-removed-var-files-stay-in-var-staging-and-the-var-image.md --- src/commands/runtime/build.rs | 423 ++++++++++++++++++++++++++++++---- 1 file changed, 377 insertions(+), 46 deletions(-) diff --git a/src/commands/runtime/build.rs b/src/commands/runtime/build.rs index b4f6e5b0..fcab6208 100644 --- a/src/commands/runtime/build.rs +++ b/src/commands/runtime/build.rs @@ -2395,57 +2395,31 @@ echo "Provisioned update authority: metadata/root.json""# // compression: btrfs property set // quotas: btrfs quota enable + btrfs qgroup limit - // Build var_files section: apply extension var_files to var staging in reverse order - // (last in extensions list applied first = lowest priority, first applied last = wins conflicts) - let var_files_section = { - let mut var_files_commands = Vec::new(); - - // Process in reverse order so first-listed extension wins conflicts - for ext_name in ext_list.iter().rev() { - let var_files = parsed + // Extension var_files in the order they are applied: last in the + // extensions list first (lowest priority), so the first-listed + // extension is applied last and wins conflicts. + let ext_var_files: Vec<(String, String)> = ext_list + .iter() + .rev() + .flat_map(|ext_name| { + parsed .get("extensions") .and_then(|e| e.get(*ext_name)) .map(crate::utils::config::get_ext_var_files) - .unwrap_or_default(); - - if !var_files.is_empty() { - for pattern in &var_files { - // Strip trailing glob suffixes and leading "var/" to get the dest path under $VAR_DIR - let clean_pattern = pattern.trim_end_matches("/**").trim_end_matches("/*"); - // The pattern is relative to the sysroot (e.g., "var/lib/docker") - // $VAR_DIR maps to /var on the target, so strip the leading "var/" for dest - let dest = clean_pattern.strip_prefix("var/").unwrap_or(clean_pattern); - var_files_commands.push(format!( - r#" -if [ -d "$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}" ]; then - echo " Applying var files from extension '{ext_name}': {clean_pattern}/" - mkdir -p "$VAR_DIR/{dest}" - cp -a "$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}/." "$VAR_DIR/{dest}/" -elif [ -f "$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}" ]; then - echo " Applying var file from extension '{ext_name}': {clean_pattern}" - mkdir -p "$(dirname "$VAR_DIR/{dest}")" - cp -f "$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}" "$VAR_DIR/{dest}" -fi"# - )); - } - } - } - - if var_files_commands.is_empty() { - "# No extension var_files to apply".to_string() - } else { - format!( - "echo \"Applying extension var files to var partition...\"\n{}", - var_files_commands.join("\n") - ) - } - }; + .unwrap_or_default() + .into_iter() + .map(|pattern| (ext_name.to_string(), pattern)) + }) + .collect(); + let var_files_section = ext_var_files_script(&ext_var_files); // Build runtime-level var_files section - let runtime_var_files_section = runtime_var_files_script( - &crate::utils::config::get_runtime_var_files(&merged_runtime), - "/opt/src", - ); + let runtime_var_files = crate::utils::config::get_runtime_var_files(&merged_runtime); + let runtime_var_files_section = runtime_var_files_script(&runtime_var_files, "/opt/src"); + + let var_files_copies = var_files_copies(&ext_var_files, &runtime_var_files, "/opt/src"); + let var_files_prune_section = var_files_prune_script(&var_files_copies); + let var_files_record_section = var_files_record_script(&var_files_copies); // Helper closure: given the rootfs/initramfs ImageConfig the runtime // resolves to, render the users/groups script that will edit the @@ -2600,6 +2574,7 @@ export RUNTIME_VERSION="{runtime_version}" {capability_check_section} VAR_DIR=$AVOCADO_PREFIX/runtimes/$RUNTIME_NAME/var-staging +{var_files_prune_section} mkdir -p "$VAR_DIR/lib/avocado/images" mkdir -p "$VAR_DIR/lib/avocado/runtimes" {subvol_mkdir_section} @@ -2667,6 +2642,7 @@ export AVOCADO_OS_VERSION_ID # Assemble var partition content and build var image {var_files_section} {runtime_var_files_section} +{var_files_record_section} {manifest_section} {update_authority_section} @@ -2693,6 +2669,8 @@ export AVOCADO_OS_VERSION_ID subvol_warnings_section = subvol_warnings_section, var_files_section = var_files_section, runtime_var_files_section = runtime_var_files_section, + var_files_prune_section = var_files_prune_section, + var_files_record_section = var_files_record_section, manifest_section = manifest_section, update_authority_section = update_authority_section, ota_tail_section = crate::commands::runtime::var_image::render_ota_tail( @@ -3512,6 +3490,174 @@ fi"#, ) } +/// The path an extension `var_files` pattern copies from (relative to the +/// extension sysroot), and the path under `$VAR_DIR` it copies to. +/// `var/lib/app/**` copies `var/lib/app` to `lib/app`, because `$VAR_DIR` +/// is `/var` on the target. +fn ext_var_files_paths(pattern: &str) -> (&str, &str) { + let clean_pattern = pattern.trim_end_matches("/**").trim_end_matches("/*"); + let dest = clean_pattern.strip_prefix("var/").unwrap_or(clean_pattern); + (clean_pattern, dest) +} + +/// Shell that copies extension `var_files` from the extension sysroots into +/// the var partition staging (`$VAR_DIR`). `ext_var_files` holds +/// `(extension, pattern)` pairs in the order they are applied, so a later +/// pair wins a conflict. +fn ext_var_files_script(ext_var_files: &[(String, String)]) -> String { + if ext_var_files.is_empty() { + return "# No extension var_files to apply".to_string(); + } + let commands: Vec = ext_var_files + .iter() + .map(|(ext_name, pattern)| { + let (clean_pattern, dest) = ext_var_files_paths(pattern); + format!( + r#" +if [ -d "$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}" ]; then + echo " Applying var files from extension '{ext_name}': {clean_pattern}/" + mkdir -p "$VAR_DIR/{dest}" + cp -a "$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}/." "$VAR_DIR/{dest}/" +elif [ -f "$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}" ]; then + echo " Applying var file from extension '{ext_name}': {clean_pattern}" + mkdir -p "$(dirname "$VAR_DIR/{dest}")" + cp -f "$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}" "$VAR_DIR/{dest}" +fi"# + ) + }) + .collect(); + format!( + "echo \"Applying extension var files to var partition...\"\n{}", + commands.join("\n") + ) +} + +/// One `var_files` copy into var staging. `placed` is the path under +/// `$VAR_DIR` that the copy creates or fills, and `source` is the shell path +/// (it may hold `$AVOCADO_EXT_SYSROOTS`) whose content ends up there. +#[derive(Debug)] +struct VarFilesCopy { + source: String, + placed: String, +} + +/// Every copy that `ext_var_files_script` and `runtime_var_files_script` +/// make, so the build can record what they placed and remove it again. +/// A runtime source with no last path part (such as `.`) is left out: what it +/// places cannot be known from the config, so it is never recorded or +/// removed. +fn var_files_copies( + ext_var_files: &[(String, String)], + runtime_var_files: &[crate::utils::config::VarFileMapping], + src_root: &str, +) -> Vec { + let ext = ext_var_files.iter().map(|(ext_name, pattern)| { + let (clean_pattern, dest) = ext_var_files_paths(pattern); + VarFilesCopy { + source: format!("$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}"), + placed: dest.trim_matches('/').to_string(), + } + }); + let runtime = runtime_var_files.iter().filter_map(|mapping| { + let base = std::path::Path::new(&mapping.source) + .file_name()? + .to_str()?; + let dest = mapping.dest.trim_matches('/'); + Some(VarFilesCopy { + source: format!("{src_root}/{}", mapping.source), + placed: if dest.is_empty() { + base.to_string() + } else { + format!("{dest}/{base}") + }, + }) + }); + ext.chain(runtime) + .filter(|copy| !copy.placed.is_empty()) + .collect() +} + +/// Shell that removes from var staging what earlier `var_files` copies +/// placed and the current ones no longer provide. It reads the list that +/// `var_files_record_script` wrote, in +/// `$AVOCADO_PREFIX/.stamps/runtime//var-staging.files`, next to the +/// runtime's stamps so `avocado runtime clean` removes it with var staging. +/// It runs before anything else writes to `$VAR_DIR`. +fn var_files_prune_script(copies: &[VarFilesCopy]) -> String { + let provides: String = copies + .iter() + .map(|VarFilesCopy { source, placed }| { + format!( + r#" + case "$1" in + "{placed}"|"{placed}"/*) + if [ -e "{source}${{1#"{placed}"}}" ] || [ -L "{source}${{1#"{placed}"}}" ]; then + return 0 + fi ;; + esac"# + ) + }) + .collect(); + format!( + r#" +# Remove what earlier var_files copies placed in var staging that the current +# var_files no longer provide. Var staging persists between builds and the var +# image is made from it, so a removed file would otherwise reach the device. +# Only listed paths are touched: files that packages, provisioning or the +# manifest steps put in var staging are never listed. A directory goes only +# when it is empty. +var_files_list="$AVOCADO_PREFIX/.stamps/runtime/$RUNTIME_NAME/var-staging.files" +var_files_provides() {{{provides} + return 1 +}} +if [ -f "$var_files_list" ]; then + # Reverse order puts a directory's content before the directory. + sort -rzu "$var_files_list" | while IFS= read -r -d '' relpath; do + [ -n "$relpath" ] || continue + # Never reach outside var staging, whatever the list holds. + case "$relpath" in /*|.|..|../*|*/../*|*/..) continue ;; esac + var_files_provides "$relpath" && continue + if [ -f "$VAR_DIR/$relpath" ] || [ -L "$VAR_DIR/$relpath" ]; then + rm -f "$VAR_DIR/$relpath" + echo "Removed /var/$relpath from var staging (no longer in var_files)" + elif [ -d "$VAR_DIR/$relpath" ] && rmdir "$VAR_DIR/$relpath" 2>/dev/null; then + echo "Removed empty directory /var/$relpath from var staging (no longer in var_files)" + fi + done +fi"# + ) +} + +/// Shell that records every path the `var_files` copies placed in var +/// staging, for `var_files_prune_script` in the next build. The list is +/// NUL-delimited so any path survives. Runs after the copies. +fn var_files_record_script(copies: &[VarFilesCopy]) -> String { + let entries: String = copies + .iter() + .map(|VarFilesCopy { source, placed }| { + format!( + r#" +if [ -d "{source}" ]; then + printf '%s\0' "{placed}" + (cd "{source}" && find . -mindepth 1 -print0) | while IFS= read -r -d '' path; do + printf '%s\0' "{placed}/${{path#./}}" + done +elif [ -e "{source}" ] || [ -L "{source}" ]; then + printf '%s\0' "{placed}" +fi >> "$var_files_list.tmp""# + ) + }) + .collect(); + format!( + r#" +# Record what the var_files copies placed, so the next build can remove what +# it no longer provides. +mkdir -p "$(dirname "$var_files_list")" +: > "$var_files_list.tmp"{entries} +mv "$var_files_list.tmp" "$var_files_list""# + ) +} + /// Shell that exports `AVOCADO_KERNEL_IMAGE` (and `AVOCADO_KERNEL_VERSION`) /// for the build hooks, from the kernels `rootfs install` staged at /// `$AVOCADO_PREFIX/kernel//Image`. @@ -3888,6 +4034,191 @@ extensions: assert!(!cp_log.exists(), "cp ran after mktemp failed"); } + #[test] + fn var_files_copies_match_where_the_copies_put_files() { + use crate::utils::config::VarFileMapping; + let copies = super::var_files_copies( + &[ + ("app".to_string(), "var/lib/app/**".to_string()), + ("app".to_string(), "var/lib/app.conf".to_string()), + ], + &[ + VarFileMapping { + source: "seed/conf/".to_string(), + dest: "/lib/".to_string(), + }, + VarFileMapping { + source: "top".to_string(), + dest: "".to_string(), + }, + VarFileMapping { + source: ".".to_string(), + dest: "lib".to_string(), + }, + ], + "/opt/src", + ); + let pairs: Vec<(&str, &str)> = copies + .iter() + .map(|c| (c.source.as_str(), c.placed.as_str())) + .collect(); + assert_eq!( + pairs, + [ + ("$AVOCADO_EXT_SYSROOTS/app/var/lib/app", "lib/app"), + ("$AVOCADO_EXT_SYSROOTS/app/var/lib/app.conf", "lib/app.conf"), + ("/opt/src/seed/conf/", "lib/conf"), + ("/opt/src/top", "top"), + ] + ); + } + + /// Runs the var_files part of the runtime build (prune, extension and + /// runtime copies, record) against `root`, the way the build script + /// orders it. `root` holds `sysroots/`, `src`, `var` (var staging) + /// and `prefix` (`$AVOCADO_PREFIX`). + #[cfg(unix)] + fn run_var_files_build( + root: &std::path::Path, + ext_var_files: &[(&str, &str)], + runtime_var_files: &[(&str, &str)], + ) -> String { + use crate::utils::config::VarFileMapping; + use std::os::unix::fs::PermissionsExt; + let ext: Vec<(String, String)> = ext_var_files + .iter() + .map(|(e, p)| (e.to_string(), p.to_string())) + .collect(); + let runtime: Vec = runtime_var_files + .iter() + .map(|(source, dest)| VarFileMapping { + source: source.to_string(), + dest: dest.to_string(), + }) + .collect(); + let src = root.join("src"); + let src = src.to_str().unwrap(); + let copies = super::var_files_copies(&ext, &runtime, src); + let script = format!( + "{}\n{}\n{}\n{}", + super::var_files_prune_script(&copies), + super::ext_var_files_script(&ext), + super::runtime_var_files_script(&runtime, src), + super::var_files_record_script(&copies), + ); + // The runtime copy makes its files root's; the test is not root. + let bin = root.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + std::fs::write(bin.join("chown"), "#!/bin/sh\nexit 0\n").unwrap(); + std::fs::set_permissions(bin.join("chown"), std::fs::Permissions::from_mode(0o755)) + .unwrap(); + let out = std::process::Command::new("bash") + .arg("-c") + .arg(&script) + .env("VAR_DIR", root.join("var")) + .env("AVOCADO_EXT_SYSROOTS", root.join("sysroots")) + .env("AVOCADO_PREFIX", root.join("prefix")) + .env("RUNTIME_NAME", "dev") + .env("TMPDIR", root) + .env( + "PATH", + format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()), + ) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout).to_string(); + assert!( + out.status.success(), + "{stdout}\n{}", + String::from_utf8_lossy(&out.stderr) + ); + stdout + } + + /// A file dropped from an extension's or the runtime's `var_files` + /// leaves var staging on the next build, and so stays out of the var + /// image. What var_files did not place there stays. + #[cfg(unix)] + #[test] + fn var_files_removed_between_builds_leave_var_staging() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let write = |rel: &str, body: &str| { + let p = root.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, body).unwrap(); + }; + let var = root.join("var"); + write("sysroots/app/var/lib/app/a.txt", "a"); + write("sysroots/app/var/lib/app/keep.txt", "k"); + write("sysroots/app/var/lib/app/sub dir/b.txt", "b"); + write("src/seed/conf/c.txt", "c"); + // In var staging before the first build: from an older CLI that kept + // no list, or from a package. Never listed, so never removed. + write("var/lib/app/old.txt", "o"); + let ext = [("app", "var/lib/app/**")]; + let runtime = [("seed/conf", "lib")]; + + run_var_files_build(root, &ext, &runtime); + for rel in ["a.txt", "keep.txt", "sub dir/b.txt", "old.txt"] { + assert!(var.join("lib/app").join(rel).exists(), "{rel}"); + } + assert!(var.join("lib/conf/c.txt").exists()); + + // Provisioning writes into a var_files directory between builds. + write("var/lib/app/primed", "p"); + // A list entry that points outside var staging is ignored. + write("victim", "v"); + let list = root.join("prefix/.stamps/runtime/dev/var-staging.files"); + let mut recorded = std::fs::read(&list).unwrap(); + recorded.extend_from_slice(b"../victim\0"); + recorded.extend_from_slice(root.join("victim").to_str().unwrap().as_bytes()); + recorded.push(0); + std::fs::write(&list, recorded).unwrap(); + + // Files leave the extension and the runtime entry is dropped. + std::fs::remove_file(root.join("sysroots/app/var/lib/app/a.txt")).unwrap(); + std::fs::remove_dir_all(root.join("sysroots/app/var/lib/app/sub dir")).unwrap(); + let out = run_var_files_build(root, &ext, &[]); + assert!(out.contains("Removed /var/lib/app/a.txt"), "{out}"); + assert!(!var.join("lib/app/a.txt").exists()); + assert!(!var.join("lib/app/sub dir").exists(), "empty dir removed"); + assert!(!var.join("lib/conf").exists(), "runtime entry removed"); + for rel in ["keep.txt", "old.txt", "primed"] { + assert!(var.join("lib/app").join(rel).exists(), "{rel}"); + } + assert!(root.join("victim").exists()); + + // The extension entry is dropped: its last file goes, and the + // directory stays because files var_files did not place are in it. + run_var_files_build(root, &[], &[]); + assert!(!var.join("lib/app/keep.txt").exists()); + assert!(var.join("lib/app/primed").exists()); + assert!(var.join("lib/app/old.txt").exists()); + assert_eq!(std::fs::read(&list).unwrap(), b""); + } + + #[test] + fn build_script_prunes_var_staging_first_and_records_after_the_copies() { + let tmp = TempDir::new().unwrap(); + let yaml = format!( + "{DEV_RUNTIME_HEAD} extensions: [app]\n var_files:\n - source: seed/conf\n dest: lib\nextensions:\n app:\n version: '1.0.0'\n var_files: ['var/lib/app/**']\n" + ); + let script = dev_build_script(&tmp, &yaml); + let at = |needle: &str| { + script + .find(needle) + .unwrap_or_else(|| panic!("missing {needle}")) + }; + let prune = at("var_files_provides \"$relpath\" && continue"); + assert!(at("VAR_DIR=$AVOCADO_PREFIX/runtimes/$RUNTIME_NAME/var-staging") < prune); + assert!(prune < at("mkdir -p \"$VAR_DIR/lib/avocado/images\"")); + let record = at("mv \"$var_files_list.tmp\" \"$var_files_list\""); + assert!(at("Applying var files from extension 'app'") < record); + assert!(at("Copied runtime var_files: seed/conf -> lib") < record); + assert!(record < at("$VAR_DIR/lib/avocado/active")); + } + #[test] fn fit_assembly_script_is_gated_and_handles_signing_both_ways() { let s = super::generate_fit_assembly_script(); From 5496406ff23f79e52e660d6666e95283f4857369 Mon Sep 17 00:00:00 2001 From: nicksinas Date: Fri, 27 Nov 2026 14:28:08 -0600 Subject: [PATCH 2/4] fix(runtime): match var_files records to the shell copy Changes from the QA review of the var-staging prune. - Record a runtime var_files source that ends in `/.` at its dest, where the shell copy puts its content - Sort the list with LC_ALL=C, as the other NUL-delimited sorts do - Warn when an extension var_files source is not in the sysroot - Tell users in the CHANGELOG that files from an earlier version stay until `avocado runtime clean ` Refs: (bug)avocado-cli-S3-removed-var-files-stay-in-var-staging-and-the-var-image.md --- CHANGELOG.md | 13 ++++++ src/commands/runtime/build.rs | 79 +++++++++++++++++++++++++++++------ 2 files changed, 79 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d3d9b672..d82815f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed +- **A file removed from `var_files` leaves var staging.** Var staging persists + between builds and the var image is made from it, so a file dropped from an + extension's or a runtime's `var_files` stayed and reached the device on the + next provision. `runtime build` now records what the `var_files` copies + place, in `.stamps/runtime//var-staging.files`, and on the next + build removes what the current `var_files` no longer provide. A directory + goes only when it is empty, and files that `var_files` did not place stay. + The first build with this version has no record, so it removes nothing: + files that an earlier version left stay. To remove them once, run + `avocado runtime clean `, then `avocado install` and + `avocado build`. + ## [1.2.0] - 2026-11-19 ### Added diff --git a/src/commands/runtime/build.rs b/src/commands/runtime/build.rs index fcab6208..a4c6b005 100644 --- a/src/commands/runtime/build.rs +++ b/src/commands/runtime/build.rs @@ -3522,6 +3522,8 @@ elif [ -f "$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}" ]; then echo " Applying var file from extension '{ext_name}': {clean_pattern}" mkdir -p "$(dirname "$VAR_DIR/{dest}")" cp -f "$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}" "$VAR_DIR/{dest}" +else + echo "WARNING: extension '{ext_name}' var_files source not found: {clean_pattern}" fi"# ) }) @@ -3541,11 +3543,26 @@ struct VarFilesCopy { placed: String, } +/// Where `runtime_var_files_script` puts a runtime `var_files` source, under +/// `$VAR_DIR`. The copy goes to `/`, so a source +/// that ends in `.` (such as `seed/conf/.`) puts its content straight into +/// `dest`. `None` when the copy target cannot be known or leaves `dest` +/// (an empty source, `/`, or one that ends in `..`). +fn runtime_var_files_placed(source: &str, dest: &str) -> Option { + let base = source.trim_end_matches('/').rsplit('/').next()?; + let dest = dest.trim_matches('/'); + match base { + "" | ".." => None, + "." => Some(dest.to_string()), + _ if dest.is_empty() => Some(base.to_string()), + _ => Some(format!("{dest}/{base}")), + } +} + /// Every copy that `ext_var_files_script` and `runtime_var_files_script` /// make, so the build can record what they placed and remove it again. -/// A runtime source with no last path part (such as `.`) is left out: what it -/// places cannot be known from the config, so it is never recorded or -/// removed. +/// A copy whose target is all of var staging, or cannot be known, is left +/// out, so it is never recorded or removed. fn var_files_copies( ext_var_files: &[(String, String)], runtime_var_files: &[crate::utils::config::VarFileMapping], @@ -3559,17 +3576,9 @@ fn var_files_copies( } }); let runtime = runtime_var_files.iter().filter_map(|mapping| { - let base = std::path::Path::new(&mapping.source) - .file_name()? - .to_str()?; - let dest = mapping.dest.trim_matches('/'); Some(VarFilesCopy { source: format!("{src_root}/{}", mapping.source), - placed: if dest.is_empty() { - base.to_string() - } else { - format!("{dest}/{base}") - }, + placed: runtime_var_files_placed(&mapping.source, &mapping.dest)?, }) }); ext.chain(runtime) @@ -3612,7 +3621,7 @@ var_files_provides() {{{provides} }} if [ -f "$var_files_list" ]; then # Reverse order puts a directory's content before the directory. - sort -rzu "$var_files_list" | while IFS= read -r -d '' relpath; do + LC_ALL=C sort -rzu "$var_files_list" | while IFS= read -r -d '' relpath; do [ -n "$relpath" ] || continue # Never reach outside var staging, whatever the list holds. case "$relpath" in /*|.|..|../*|*/../*|*/..) continue ;; esac @@ -4051,10 +4060,22 @@ extensions: source: "top".to_string(), dest: "".to_string(), }, + VarFileMapping { + source: "seed/conf/.".to_string(), + dest: "etc".to_string(), + }, VarFileMapping { source: ".".to_string(), dest: "lib".to_string(), }, + VarFileMapping { + source: ".".to_string(), + dest: "/".to_string(), + }, + VarFileMapping { + source: "seed/..".to_string(), + dest: "lib".to_string(), + }, ], "/opt/src", ); @@ -4069,6 +4090,8 @@ extensions: ("$AVOCADO_EXT_SYSROOTS/app/var/lib/app.conf", "lib/app.conf"), ("/opt/src/seed/conf/", "lib/conf"), ("/opt/src/top", "top"), + ("/opt/src/seed/conf/.", "etc"), + ("/opt/src/.", "lib"), ] ); } @@ -4198,6 +4221,36 @@ extensions: assert_eq!(std::fs::read(&list).unwrap(), b""); } + /// A runtime source that ends in `/.` copies its content straight into + /// `dest`; the record and the removal follow that. An extension pattern + /// with no source in the sysroot is reported. + #[cfg(unix)] + #[test] + fn var_files_dot_source_is_recorded_where_the_copy_puts_it() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + for rel in ["src/seed/conf/c.txt", "src/seed/conf/d.txt"] { + let p = root.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, rel).unwrap(); + } + let ext = [("app", "var/lib/missing/**")]; + let runtime = [("seed/conf/.", "etc")]; + + let out = run_var_files_build(root, &ext, &runtime); + assert!( + out.contains("WARNING: extension 'app' var_files source not found: var/lib/missing"), + "{out}" + ); + assert!(root.join("var/etc/c.txt").exists()); + assert!(!root.join("var/etc/conf").exists()); + + std::fs::remove_file(root.join("src/seed/conf/c.txt")).unwrap(); + run_var_files_build(root, &ext, &runtime); + assert!(!root.join("var/etc/c.txt").exists()); + assert!(root.join("var/etc/d.txt").exists()); + } + #[test] fn build_script_prunes_var_staging_first_and_records_after_the_copies() { let tmp = TempDir::new().unwrap(); From e4f85a192d5d2682b5a30e89afc2f990deba0b01 Mon Sep 17 00:00:00 2001 From: nicksinas Date: Sat, 28 Nov 2026 13:25:56 -0600 Subject: [PATCH 3/4] fix(runtime): record only what var_files copied and never prune through links Review of the var_files record found three gaps. A runtime source that is a symlink to a directory is copied as a link, but the record listed the files of its target, so dropping the entry removed them through the link. A dangling source link is not copied, but it was recorded, so dropping the entry could remove a file at its destination that var_files never placed. A copy into var staging itself (such as seed/conf/. to /) was not recorded at all, so its files stayed after they left var_files. - Record a runtime symlink source as one entry, and select sources with the same tests the copies use, so a dangling link is never recorded - Record and prune what a copy places in var staging itself, but never list var staging - Skip a listed path when a directory above it in var staging is a symlink, so an older list cannot lead removal through a link - Add tests for each case Refs: avocado-linux/avocado-cli#445 --- src/commands/runtime/build.rs | 197 ++++++++++++++++++++++++++++++---- 1 file changed, 177 insertions(+), 20 deletions(-) diff --git a/src/commands/runtime/build.rs b/src/commands/runtime/build.rs index a4c6b005..7bc1d299 100644 --- a/src/commands/runtime/build.rs +++ b/src/commands/runtime/build.rs @@ -3535,12 +3535,17 @@ fi"# } /// One `var_files` copy into var staging. `placed` is the path under -/// `$VAR_DIR` that the copy creates or fills, and `source` is the shell path -/// (it may hold `$AVOCADO_EXT_SYSROOTS`) whose content ends up there. +/// `$VAR_DIR` that the copy creates or fills (empty when the copy fills var +/// staging itself), and `source` is the shell path (it may hold +/// `$AVOCADO_EXT_SYSROOTS`) whose content ends up there. `runtime` is true +/// for a runtime copy: it copies any existing source with `cp -a`, which +/// keeps a symlink as a link. An extension copy takes a directory's content +/// or a regular file only. #[derive(Debug)] struct VarFilesCopy { source: String, placed: String, + runtime: bool, } /// Where `runtime_var_files_script` puts a runtime `var_files` source, under @@ -3561,8 +3566,8 @@ fn runtime_var_files_placed(source: &str, dest: &str) -> Option { /// Every copy that `ext_var_files_script` and `runtime_var_files_script` /// make, so the build can record what they placed and remove it again. -/// A copy whose target is all of var staging, or cannot be known, is left -/// out, so it is never recorded or removed. +/// A copy whose target cannot be known is left out, so it is never recorded +/// or removed. fn var_files_copies( ext_var_files: &[(String, String)], runtime_var_files: &[crate::utils::config::VarFileMapping], @@ -3573,17 +3578,17 @@ fn var_files_copies( VarFilesCopy { source: format!("$AVOCADO_EXT_SYSROOTS/{ext_name}/{clean_pattern}"), placed: dest.trim_matches('/').to_string(), + runtime: false, } }); let runtime = runtime_var_files.iter().filter_map(|mapping| { Some(VarFilesCopy { source: format!("{src_root}/{}", mapping.source), placed: runtime_var_files_placed(&mapping.source, &mapping.dest)?, + runtime: true, }) }); - ext.chain(runtime) - .filter(|copy| !copy.placed.is_empty()) - .collect() + ext.chain(runtime).collect() } /// Shell that removes from var staging what earlier `var_files` copies @@ -3595,12 +3600,21 @@ fn var_files_copies( fn var_files_prune_script(copies: &[VarFilesCopy]) -> String { let provides: String = copies .iter() - .map(|VarFilesCopy { source, placed }| { + .map(|VarFilesCopy { source, placed, .. }| { + // A copy into var staging itself provides any path its source has. + let (pattern, path) = if placed.is_empty() { + ("*".to_string(), format!("{source}/$1")) + } else { + ( + format!("\"{placed}\"|\"{placed}\"/*"), + format!("{source}${{1#\"{placed}\"}}"), + ) + }; format!( r#" case "$1" in - "{placed}"|"{placed}"/*) - if [ -e "{source}${{1#"{placed}"}}" ] || [ -L "{source}${{1#"{placed}"}}" ]; then + {pattern}) + if [ -e "{path}" ] || [ -L "{path}" ]; then return 0 fi ;; esac"# @@ -3619,6 +3633,17 @@ var_files_list="$AVOCADO_PREFIX/.stamps/runtime/$RUNTIME_NAME/var-staging.files" var_files_provides() {{{provides} return 1 }} +# True when a directory above the path in var staging is a symlink. Removal +# never goes through one, so it cannot reach files var_files did not place. +# The path itself may be a symlink: rm -f removes the link. +var_files_parent_is_link() {{ + parent="$1" + while case "$parent" in */*) true ;; *) false ;; esac; do + parent="${{parent%/*}}" + [ -L "$VAR_DIR/$parent" ] && return 0 + done + return 1 +}} if [ -f "$var_files_list" ]; then # Reverse order puts a directory's content before the directory. LC_ALL=C sort -rzu "$var_files_list" | while IFS= read -r -d '' relpath; do @@ -3626,6 +3651,7 @@ if [ -f "$var_files_list" ]; then # Never reach outside var staging, whatever the list holds. case "$relpath" in /*|.|..|../*|*/../*|*/..) continue ;; esac var_files_provides "$relpath" && continue + var_files_parent_is_link "$relpath" && continue if [ -f "$VAR_DIR/$relpath" ] || [ -L "$VAR_DIR/$relpath" ]; then rm -f "$VAR_DIR/$relpath" echo "Removed /var/$relpath from var staging (no longer in var_files)" @@ -3643,19 +3669,48 @@ fi"# fn var_files_record_script(copies: &[VarFilesCopy]) -> String { let entries: String = copies .iter() - .map(|VarFilesCopy { source, placed }| { - format!( - r#" -if [ -d "{source}" ]; then - printf '%s\0' "{placed}" + .map( + |VarFilesCopy { + source, + placed, + runtime, + }| { + // Record only what the copy made: the same tests the copy uses + // select the source, so a dangling link is never recorded. A + // runtime copy keeps a symlink source as a link, so the link is + // one entry and the files it points at are not listed. + let (copied, tree) = if *runtime { + ( + format!("[ -e \"{source}\" ]"), + format!("[ -d \"{source}\" ] && [ ! -L \"{source}\" ]"), + ) + } else { + ( + format!("[ -d \"{source}\" ] || [ -f \"{source}\" ]"), + format!("[ -d \"{source}\" ]"), + ) + }; + // Var staging itself is never listed, only what is copied into it. + let (top, prefix) = if placed.is_empty() { + (":".to_string(), String::new()) + } else { + (format!("printf '%s\\0' \"{placed}\""), format!("{placed}/")) + }; + format!( + r#" +if ! {{ {copied}; }}; then + : +elif {tree}; then + {top} (cd "{source}" && find . -mindepth 1 -print0) | while IFS= read -r -d '' path; do - printf '%s\0' "{placed}/${{path#./}}" + printf '%s\0' "{prefix}${{path#./}}" done -elif [ -e "{source}" ] || [ -L "{source}" ]; then - printf '%s\0' "{placed}" +else + {top} fi >> "$var_files_list.tmp""# - ) - }) + ) + }, + ) .collect(); format!( r#" @@ -4092,6 +4147,7 @@ extensions: ("/opt/src/top", "top"), ("/opt/src/seed/conf/.", "etc"), ("/opt/src/.", "lib"), + ("/opt/src/.", ""), ] ); } @@ -4251,6 +4307,107 @@ extensions: assert!(root.join("var/etc/d.txt").exists()); } + /// A runtime source that ends in `/.` with `dest: /` copies its content + /// into var staging itself. Its files are recorded and removed like any + /// others, and var staging itself is never listed. + #[cfg(unix)] + #[test] + fn var_files_copied_to_the_staging_root_are_recorded_and_removed() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + for rel in [ + "src/seed/conf/c.txt", + "src/seed/conf/sub/d.txt", + "var/pkg.txt", + ] { + let p = root.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, rel).unwrap(); + } + let runtime = [("seed/conf/.", "/")]; + + run_var_files_build(root, &[], &runtime); + assert!(root.join("var/c.txt").exists()); + assert!(root.join("var/sub/d.txt").exists()); + let list = root.join("prefix/.stamps/runtime/dev/var-staging.files"); + let recorded = std::fs::read(&list).unwrap(); + let mut entries: Vec<&[u8]> = recorded.split(|b| *b == 0).collect(); + entries.sort(); + assert_eq!( + entries, + [&b""[..], b"c.txt", b"sub", b"sub/d.txt"], + "only what the copy placed, never var staging itself" + ); + + std::fs::remove_file(root.join("src/seed/conf/c.txt")).unwrap(); + run_var_files_build(root, &[], &runtime); + assert!(!root.join("var/c.txt").exists()); + assert!(root.join("var/sub/d.txt").exists()); + + run_var_files_build(root, &[], &[]); + assert!(!root.join("var/sub").exists()); + assert!(root.join("var/pkg.txt").exists()); + } + + /// A runtime source that is a symlink to a directory is copied as a link, + /// so only the link is recorded. Removing it never goes through the link, + /// even when an older list holds paths below it. + #[cfg(unix)] + #[test] + fn var_files_never_remove_through_a_symlinked_directory() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let outside = root.join("outside"); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(outside.join("x.txt"), "x").unwrap(); + std::fs::create_dir_all(root.join("src")).unwrap(); + std::os::unix::fs::symlink(&outside, root.join("src/link")).unwrap(); + let runtime = [("link", "lib")]; + + run_var_files_build(root, &[], &runtime); + let staged = root.join("var/lib/link"); + assert!(staged.symlink_metadata().unwrap().file_type().is_symlink()); + let list = root.join("prefix/.stamps/runtime/dev/var-staging.files"); + assert_eq!(std::fs::read(&list).unwrap(), b"lib/link\0"); + + // A list from an older build that followed the link. + std::fs::write(&list, b"lib/link\0lib/link/x.txt\0").unwrap(); + run_var_files_build(root, &[], &[]); + assert!(staged.symlink_metadata().is_err(), "the link is removed"); + assert!(outside.join("x.txt").exists(), "its target is not touched"); + } + + /// A dangling source link is not copied, so it is not recorded, and a + /// file already at its destination stays when the entry is dropped. + #[cfg(unix)] + #[test] + fn var_files_do_not_record_a_dangling_source_link() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + for rel in [ + "var/lib/dangling", + "var/lib/app/gone", + "sysroots/app/var/lib/app/a", + ] { + let p = root.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, rel).unwrap(); + } + std::fs::create_dir_all(root.join("src")).unwrap(); + std::os::unix::fs::symlink("missing", root.join("src/dangling")).unwrap(); + std::os::unix::fs::symlink("missing", root.join("sysroots/app/var/lib/app/gone")).unwrap(); + let ext = [("app", "var/lib/app/gone")]; + let runtime = [("dangling", "lib")]; + + run_var_files_build(root, &ext, &runtime); + let list = root.join("prefix/.stamps/runtime/dev/var-staging.files"); + assert_eq!(std::fs::read(&list).unwrap(), b""); + + run_var_files_build(root, &[], &[]); + assert!(root.join("var/lib/dangling").exists()); + assert!(root.join("var/lib/app/gone").exists()); + } + #[test] fn build_script_prunes_var_staging_first_and_records_after_the_copies() { let tmp = TempDir::new().unwrap(); From f754b141f2ae75f6195dc97ed39462a7d9d1d9e1 Mon Sep 17 00:00:00 2001 From: nicksinas Date: Sat, 28 Nov 2026 14:29:16 -0600 Subject: [PATCH 4/4] fix(runtime): prune var_files copies the copy step no longer makes A top-level var_files source that became a dangling link still counted as provided in the prune, while the copy and the record skipped it. Its old copy then dropped off the list and stayed in var staging for good. A FIFO or other special file that cp -a copied inside a directory was recorded but never removed, because the prune removed only regular files and links. - Use the copy step's own test for the source in both the prune and the record, so a source the copy skips provides nothing - Remove any recorded entry that is not a directory, with the same guards against symlinked parents and paths that leave var staging - Add tests for a source that became a dangling link and for a FIFO that left the source directory Refs: avocado-linux/avocado-cli#445 --- src/commands/runtime/build.rs | 139 +++++++++++++++++++++++++--------- 1 file changed, 104 insertions(+), 35 deletions(-) diff --git a/src/commands/runtime/build.rs b/src/commands/runtime/build.rs index 7bc1d299..7fbdb3b1 100644 --- a/src/commands/runtime/build.rs +++ b/src/commands/runtime/build.rs @@ -3548,6 +3548,19 @@ struct VarFilesCopy { runtime: bool, } +impl VarFilesCopy { + /// Shell test that is true when the copy step copies `source`. It is + /// the same test the copy uses, so a dangling link is never copied. + fn copied_test(&self) -> String { + let source = &self.source; + if self.runtime { + format!("[ -e \"{source}\" ]") + } else { + format!("[ -d \"{source}\" ] || [ -f \"{source}\" ]") + } + } +} + /// Where `runtime_var_files_script` puts a runtime `var_files` source, under /// `$VAR_DIR`. The copy goes to `/`, so a source /// that ends in `.` (such as `seed/conf/.`) puts its content straight into @@ -3600,7 +3613,8 @@ fn var_files_copies( fn var_files_prune_script(copies: &[VarFilesCopy]) -> String { let provides: String = copies .iter() - .map(|VarFilesCopy { source, placed, .. }| { + .map(|copy| { + let VarFilesCopy { source, placed, .. } = copy; // A copy into var staging itself provides any path its source has. let (pattern, path) = if placed.is_empty() { ("*".to_string(), format!("{source}/$1")) @@ -3610,11 +3624,14 @@ fn var_files_prune_script(copies: &[VarFilesCopy]) -> String { format!("{source}${{1#\"{placed}\"}}"), ) }; + // The source must pass the copy step's test. Below it, a dangling + // link counts: cp -a copies links inside a directory as links. + let copied = copy.copied_test(); format!( r#" case "$1" in {pattern}) - if [ -e "{path}" ] || [ -L "{path}" ]; then + if {{ {copied}; }} && {{ [ -e "{path}" ] || [ -L "{path}" ]; }}; then return 0 fi ;; esac"# @@ -3652,7 +3669,7 @@ if [ -f "$var_files_list" ]; then case "$relpath" in /*|.|..|../*|*/../*|*/..) continue ;; esac var_files_provides "$relpath" && continue var_files_parent_is_link "$relpath" && continue - if [ -f "$VAR_DIR/$relpath" ] || [ -L "$VAR_DIR/$relpath" ]; then + if [ -L "$VAR_DIR/$relpath" ] || {{ [ -e "$VAR_DIR/$relpath" ] && [ ! -d "$VAR_DIR/$relpath" ]; }}; then rm -f "$VAR_DIR/$relpath" echo "Removed /var/$relpath from var staging (no longer in var_files)" elif [ -d "$VAR_DIR/$relpath" ] && rmdir "$VAR_DIR/$relpath" 2>/dev/null; then @@ -3669,35 +3686,30 @@ fi"# fn var_files_record_script(copies: &[VarFilesCopy]) -> String { let entries: String = copies .iter() - .map( - |VarFilesCopy { - source, - placed, - runtime, - }| { - // Record only what the copy made: the same tests the copy uses - // select the source, so a dangling link is never recorded. A - // runtime copy keeps a symlink source as a link, so the link is - // one entry and the files it points at are not listed. - let (copied, tree) = if *runtime { - ( - format!("[ -e \"{source}\" ]"), - format!("[ -d \"{source}\" ] && [ ! -L \"{source}\" ]"), - ) - } else { - ( - format!("[ -d \"{source}\" ] || [ -f \"{source}\" ]"), - format!("[ -d \"{source}\" ]"), - ) - }; - // Var staging itself is never listed, only what is copied into it. - let (top, prefix) = if placed.is_empty() { - (":".to_string(), String::new()) - } else { - (format!("printf '%s\\0' \"{placed}\""), format!("{placed}/")) - }; - format!( - r#" + .map(|copy| { + let VarFilesCopy { + source, + placed, + runtime, + } = copy; + // Record only what the copy made: the same tests the copy uses + // select the source, so a dangling link is never recorded. A + // runtime copy keeps a symlink source as a link, so the link is + // one entry and the files it points at are not listed. + let copied = copy.copied_test(); + let tree = if *runtime { + format!("[ -d \"{source}\" ] && [ ! -L \"{source}\" ]") + } else { + format!("[ -d \"{source}\" ]") + }; + // Var staging itself is never listed, only what is copied into it. + let (top, prefix) = if placed.is_empty() { + (":".to_string(), String::new()) + } else { + (format!("printf '%s\\0' \"{placed}\""), format!("{placed}/")) + }; + format!( + r#" if ! {{ {copied}; }}; then : elif {tree}; then @@ -3708,9 +3720,8 @@ elif {tree}; then else {top} fi >> "$var_files_list.tmp""# - ) - }, - ) + ) + }) .collect(); format!( r#" @@ -4408,6 +4419,64 @@ extensions: assert!(root.join("var/lib/app/gone").exists()); } + /// A source that the last build copied and that is now a dangling link + /// is not copied again, so its old copy leaves var staging. Otherwise it + /// would drop off the list and stay there for good. + #[cfg(unix)] + #[test] + fn var_files_remove_the_copy_of_a_source_that_became_a_dangling_link() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + for rel in ["src/app.conf", "sysroots/app/var/lib/app/x.conf"] { + let p = root.join(rel); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(p, rel).unwrap(); + } + let ext = [("app", "var/lib/app/x.conf")]; + let runtime = [("app.conf", "lib")]; + + run_var_files_build(root, &ext, &runtime); + assert!(root.join("var/lib/app.conf").exists()); + assert!(root.join("var/lib/app/x.conf").exists()); + + for rel in ["src/app.conf", "sysroots/app/var/lib/app/x.conf"] { + std::fs::remove_file(root.join(rel)).unwrap(); + std::os::unix::fs::symlink("missing", root.join(rel)).unwrap(); + } + let out = run_var_files_build(root, &ext, &runtime); + assert!(out.contains("Removed /var/lib/app.conf"), "{out}"); + assert!(root.join("var/lib/app.conf").symlink_metadata().is_err()); + assert!(root.join("var/lib/app/x.conf").symlink_metadata().is_err()); + } + + /// `cp -a` copies a FIFO inside a source directory as a FIFO. It is + /// recorded like a file and removed like one when it leaves the source. + #[cfg(unix)] + #[test] + fn var_files_remove_a_special_file_that_left_the_source() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let dir = root.join("sysroots/app/var/lib/app"); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("a.txt"), "a").unwrap(); + let status = std::process::Command::new("mkfifo") + .arg(dir.join("pipe")) + .status() + .unwrap(); + assert!(status.success()); + let ext = [("app", "var/lib/app/**")]; + + run_var_files_build(root, &ext, &[]); + let staged = root.join("var/lib/app/pipe"); + assert!(staged.symlink_metadata().is_ok()); + + std::fs::remove_file(dir.join("pipe")).unwrap(); + let out = run_var_files_build(root, &ext, &[]); + assert!(out.contains("Removed /var/lib/app/pipe"), "{out}"); + assert!(staged.symlink_metadata().is_err()); + assert!(root.join("var/lib/app/a.txt").exists()); + } + #[test] fn build_script_prunes_var_staging_first_and_records_after_the_copies() { let tmp = TempDir::new().unwrap();