Skip to contentSkip to conversation

boot: revert boot related globalvars after booting

PATCH Applied Sascha Hauer 1 participant 11 messages Nov 13 – Nov 24 Documentation

lore
Share & tools
lore
#0 lore raw

v2 cover boot: revert boot related globalvars after booting

Boot entries configure booting through globalvars like global.bootm.*, global.linux.bootargs.* or global.of.overlay.*. So far only some of these were restored after a boot entry returned, by saving a fixed set of variables and by clearing the global.linux.bootargs.dyn.* namespace.

This series adds globalvar scopes, which snapshot all globalvars matching given patterns and restore them later, and uses them around each boot entry, bootm and bootchooser boot attempts. With that the .dyn infix is no longer needed, so it is dropped from the boot scripts of the default environment. blspec and extlinux keep using global.linux.bootargs.dyn.bootentries, so the position of their options in the Kernel command line doesn't change.

The series is based on the "boot: UAF and double free fixes" series.

To: open list:BAREBOX <[email protected]>

Assisted-by Claude:claude-opus-5-5

Changes in v2:
- globalvar scopes take fnmatch() patterns instead of name prefixes
- "boot: revert globalvar changes after each boot entry": use
global.bootm.earlycon instead of global.bootm.tee as example
- "test: py: add test for reverting globalvars after boot": fix line
break in commit message
- "of: add watchdog bootarg directly instead of via a globalvar": drop
the legacy bootargs fallback from the commit message, it is gone in
next
- Drop "boot: drop the dyn infix from the bootentries bootargs variable",
blspec and extlinux keep using global.linux.bootargs.dyn.bootentries
so their options don't move in the Kernel command line
- Migration guide: describe that global.linux.bootargs.dyn.* set before
calling boot is now kept, and that blspec and extlinux keep the .dyn
infix
- Link to v1: https://lore.barebox.org/[email protected]

---
Sascha Hauer (9):
globalvar: add scopes to snapshot and restore globalvars
bootm: revert globalvar changes in bootm_boot_cleanup()
boot: revert globalvar changes after each boot entry
bootchooser: use a globalvar scope for its bootargs
test: py: add test for reverting globalvars after boot
bootargs: remove unused linux_bootargs_overwrite()
of: add watchdog bootarg directly instead of via a globalvar
defaultenv: don't use global.linux.bootargs.dyn.* in boot entries
Documentation: migration-guides: describe reverting boot globalvars

 .../migration-master/boot-globalvar-scope.rst      |  19 +++
 Documentation/user/booting-linux.rst               |  27 ++--
 Documentation/user/devboot.rst                     |   4 +-
 common/Kconfig                                     |   6 +-
 common/boot.c                                      |  35 ++---
 common/bootargs.c                                  |  17 ---
 common/bootchooser.c                               |   6 +-
 common/bootm.c                                     |  27 +---
 common/globalvar.c                                 | 143 +++++++++++++++++++++
 common/oftree.c                                    |  41 +++---
 defaultenv/defaultenv-2-base/boot/net              |   5 +-
 defaultenv/defaultenv-2-base/data/boot-template    |   2 +-
 defaultenv/defaultenv-2-dfu/boot/dfu               |   4 +-
 include/boot.h                                     |  16 +++
 include/bootargs.h                                 |   5 -
 include/bootm.h                                    |   9 +-
 include/globalvar.h                                |  29 +++++
 test/py/test_boot_globalvar_scope.py               | 117 +++++++++++++++++
 18 files changed, 401 insertions(+), 111 deletions(-)

---
base-commit: db380db7a86026f0b19ea6841fa9b9f5326a4b0b
change-id: 20261030-boot-globalvar-stack-9c65609b5801

Best regards,

Signature · 1 line
Sascha Hauer <[email protected]>
#1 lore raw

PATCH v2 1/9 globalvar: add scopes to snapshot and restore globalvars

Code that runs foreign code, like boot scripts, often wants to revert whatever that code changed in the global namespace afterwards. So far this is done by hand for each use case: either by saving and restoring a fixed list of variables, or by putting variables into a dedicated namespace which is cleared afterwards.

Add globalvar_scope_push() and globalvar_scope_pop() to do this generically. A scope records the current values of all globalvars whose name matches one of the given fnmatch() patterns, as globalvar_remove() already takes them. Popping it restores changed values, removes variables created in the meantime and creates removed variables again. Variables are only removed or recreated if they were created with globalvar_add_simple(), which is what the shell's global command and most dynamically created variables use. For all other globalvars, which are backed by a C variable, only the value is restored, through the regular setter so the C variable follows.

Scopes can be nested as long as they are popped in reverse order.

---
 common/globalvar.c  | 143 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 include/globalvar.h |  29 +++++++++++
 2 files changed, 172 insertions(+)
common/globalvar.c +143 -0
index 876379b253..5ec40635dd 100644
@@ -456,6 +456,149 @@ void globalvar_set_match(const char *match, const char *val)
 	}
 }
 
+struct globalvar_scope_var {
+	struct list_head list;
+	char *name;
+	char *value;
+	bool unqualified;
+	bool seen;
+};
+
+struct globalvar_scope {
+	const char * const *patterns;
+	struct list_head vars;
+};
+
+static bool globalvar_scope_match(const struct globalvar_scope *scope,
+				  const char *name)
+{
+	const char * const *pattern;
+
+	for (pattern = scope->patterns; *pattern; pattern++)
+		if (!fnmatch(*pattern, name, 0))
+			return true;
+
+	return false;
+}
+
+static struct globalvar_scope_var *
+globalvar_scope_find(struct globalvar_scope *scope, const char *name)
+{
+	struct globalvar_scope_var *var;
+
+	list_for_each_entry(var, &scope->vars, list)
+		if (!strcmp(var->name, name))
+			return var;
+
+	return NULL;
+}
+
+/**
+ * __globalvar_scope_push - snapshot a set of globalvars
+ * @patterns: NULL terminated array of fnmatch() patterns of the names
+ *            to snapshot, which must stay valid until globalvar_scope_pop()
+ *
+ * Records the current value of all globalvars whose name matches one of
+ * @patterns, e.g. "bootm.*" for all variables in the bootm namespace. A
+ * later globalvar_scope_pop() reverts all changes done to these variables
+ * in the meantime, including adding and removing them. Scopes can be
+ * nested, but must be popped in reverse order.
+ *
+ * Return: the scope to be passed to globalvar_scope_pop()
+ */
+struct globalvar_scope *__globalvar_scope_push(const char * const *patterns)
+{
+	struct globalvar_scope *scope;
+	struct param_d *p;
+
+	scope = xzalloc(sizeof(*scope));
+	scope->patterns = patterns;
+	INIT_LIST_HEAD(&scope->vars);
+
+	dev_for_each_param(&global_device, p) {
+		struct globalvar_scope_var *var;
+
+		if (!globalvar_scope_match(scope, p->name))
+			continue;
+
+		var = xzalloc(sizeof(*var));
+		var->name = xstrdup(p->name);
+		var->value = xstrdup(p->get(p->bobj, p) ?: "");
+		var->unqualified = p->flags & PARAM_GLOBALVAR_UNQUALIFIED;
+		list_add_tail(&var->list, &scope->vars);
+	}
+
+	return scope;
+}
+
+/**
+ * globalvar_scope_pop - revert globalvars to a snapshot
+ * @scope: the scope returned by globalvar_scope_push()
+ *
+ * Restores all globalvars covered by @scope to the values they had when
+ * the scope was pushed: changed values are set back, variables created
+ * in the meantime are removed and removed variables are created again.
+ * Variables which were not created with globalvar_add_simple() are never
+ * removed or recreated, only their values are restored.
+ *
+ * @scope is freed afterwards.
+ */
+void globalvar_scope_pop(struct globalvar_scope *scope)
+{
+	struct globalvar_scope_var *var, *vtmp;
+	struct param_d *p, *tmp;
+	int ret;
+
+	if (!scope)
+		return;
+
+	dev_for_each_param_safe(&global_device, p, tmp) {
+		const char *cur;
+
+		if (!globalvar_scope_match(scope, p->name))
+			continue;
+
+		var = globalvar_scope_find(scope, p->name);
+		if (!var) {
+			if (!(p->flags & PARAM_GLOBALVAR_UNQUALIFIED))
+				continue;
+
+			pr_debug("scope: removing global.%s\n", p->name);
+			param_remove(p);
+			continue;
+		}
+
+		var->seen = true;
+
+		cur = p->get(p->bobj, p) ?: "";
+		if (!strcmp(cur, var->value))
+			continue;
+
+		pr_debug("scope: restoring global.%s: \"%s\" -> \"%s\"\n",
+			 p->name, cur, var->value);
+
+		ret = dev_set_param(&global_device, p->name, var->value);
+		if (ret)
+			pr_warn("Cannot restore global.%s=\"%s\": %pe\n",
+				p->name, var->value, ERR_PTR(ret));
+	}
+
+	list_for_each_entry_safe(var, vtmp, &scope->vars, list) {
+		if (!var->seen && var->unqualified) {
+			pr_debug("scope: recreating global.%s=\"%s\"\n",
+				 var->name, var->value);
+			globalvar_add_simple(var->name, var->value);
+		}
+
+		list_del(&var->list);
+		free(var->name);
+		free(var->value);
+		free(var);
+	}
+
+	free(scope);
+}
+
 void globalvar_set(const char *name, const char *val)
 {
 	dev_set_param(&global_device, name, val);
include/globalvar.h +29 -0
index e369616c63..5712bad7f9 100644
@@ -10,6 +10,24 @@
 
 extern struct device global_device;
 
+struct globalvar_scope;
+
+/**
+ * globalvar_scope_push - snapshot a set of globalvars
+ * @...: fnmatch() patterns of the globalvar names to snapshot
+ *
+ * See __globalvar_scope_push(). The scope borrows the patterns until
+ * globalvar_scope_pop(). Collecting them in a static array makes the
+ * compiler reject patterns that don't live that long, as only string
+ * literals and addresses of static objects are allowed as initializers.
+ *
+ * Return: the scope to be passed to globalvar_scope_pop()
+ */
+#define globalvar_scope_push(...) ({					\
+	static const char * const __patterns[] = { __VA_ARGS__, NULL };	\
+	__globalvar_scope_push(__patterns);				\
+})
+
 #ifdef CONFIG_GLOBALVAR
 
 static inline const char *globalvar_get(const char *name)
@@ -24,6 +42,9 @@ char *globalvar_get_match(const char *match, const char *separator);
 void globalvar_set_match(const char *match, const char *val);
 void globalvar_set(const char *name, const char *val);
 
+struct globalvar_scope *__globalvar_scope_push(const char * const *patterns);
+void globalvar_scope_pop(struct globalvar_scope *scope);
+
 int globalvar_add_simple_string(const char *name, char **value);
 int globalvar_add_simple_int(const char *name, int *value,
 			     const char *format);
@@ -126,6 +147,14 @@ static inline void globalvar_set_match(const char *match, const char *val) {}
 
 static inline void globalvar_set(const char *name, const char *val) {}
 
+static inline struct globalvar_scope *
+__globalvar_scope_push(const char * const *patterns)
+{
+	return NULL;
+}
+
+static inline void globalvar_scope_pop(struct globalvar_scope *scope) {}
+
 static inline int nvvar_load(void)
 {
 	return 0;
Signature · 1 line
2.47.3
#2 lore raw

PATCH v2 2/9 bootm: revert globalvar changes in bootm_boot_cleanup()

In reply to Sascha Hauer

bootm adds the Kernel command line options it generates itself as global.linux.bootargs.!bootm.* and global.linux.bootargs.~bootm.* variables and removes them again in bootm_boot_cleanup(). Anything else bootm or the image handlers change in the global namespace while booting stays, for example global.linux.bootargs.dyn.watchdog which is added by the devicetree fixups and only cleared again when booting through the boot command.

Add boot_globalvar_scope_push() which snapshots the globalvars that configure booting, take a snapshot in bootm_boot_prep() and restore it in bootm_boot_cleanup(). This covers the variables bootm removed so far, so drop the explicit removal.

Besides global.bootm.* and global.linux.bootargs.*, the scope covers the rest of global.linux.*, like global.linux.bootargs_append, which global.linux.bootargs.* doesn't match, or global.linux.rootwait, then global.of.*, which includes the global.of.overlay.* variables selecting the overlays applied to the Kernel device tree, and global.boot.watchdog_timeout.

It deliberately doesn't cover all globalvars: booting legitimately changes others, which must persist. For example DHCP sets global.net.server, global.net.gateway and global.hostname, and reverting them while the interface stays up would leave the network unusable, as a later ifup doesn't run DHCP again.

---
 common/bootm.c  |  6 ++++--
 include/boot.h  | 16 ++++++++++++++++
 include/bootm.h |  8 +++++++-
 3 files changed, 27 insertions(+), 3 deletions(-)
common/bootm.c +4 -2
index 26dba7244e..0798324b14 100644
@@ -2,6 +2,7 @@
 
 #include <common.h>
 #include <bootargs.h>
+#include <boot.h>
 #include <bootm.h>
 #include <fs.h>
 #include <fcntl.h>
@@ -542,6 +543,8 @@ struct image_data *bootm_boot_prep(const struct bootm_data *bootm_data)
 
 	data = xzalloc(sizeof(*data));
 
+	data->globalvar_scope = boot_globalvar_scope_push();
+
 	bootm_image_name_and_part(bootm_data->os_file, &data->os_file, &data->os_part);
 	bootm_image_name_and_part(bootm_data->oftree_file, &data->oftree_file, &data->oftree_part);
 	bootm_image_name_and_part(bootm_data->initrd_file, &data->initrd_file, &data->initrd_part);
@@ -801,8 +804,7 @@ void bootm_boot_cleanup(struct image_data *data)
 	if (data->of_root_node)
 		of_delete_node(data->of_root_node);
 
-	globalvar_remove(LINUX_BOOTARGS_BOOTM_EARLY "*");
-	globalvar_remove(LINUX_BOOTARGS_BOOTM_LATE  "*");
+	globalvar_scope_pop(data->globalvar_scope);
 	free(data->os_header);
 	free(data->os_file);
 	free(data->oftree_file);
include/boot.h +16 -0
index 57f9cb409b..1ae689732d 100644
@@ -7,6 +7,7 @@
 #include <environment.h>
 #include <bootm-overrides.h>
 #include <bootargs.h>
+#include <globalvar.h>
 
 struct bootentries {
 	struct list_head entries;
@@ -58,4 +59,19 @@ int boot_entry(struct bootentry *be, int verbose, int dryrun);
 struct bootm_data;
 int bootm_entry(struct bootentry *be, const struct bootm_data *data);
 
+/*
+ * Snapshot all globalvars that configure booting. Whatever a boot script,
+ * a boot entry or bootm itself changes there is reverted again by
+ * globalvar_scope_pop(), so it doesn't leak into the next boot attempt.
+ *
+ * This deliberately doesn't cover all globalvars: booting may change
+ * others that must persist, e.g. DHCP sets global.net.* and
+ * global.hostname while the interface stays up.
+ */
+static inline struct globalvar_scope *boot_globalvar_scope_push(void)
+{
+	return globalvar_scope_push("bootm.*", "linux.*", "of.*",
+				    "boot.watchdog_timeout");
+}
+
 #endif /* __BOOT_H */
include/bootm.h +7 -1
index 8e574040f4..bbdbb8e69d 100644
@@ -16,7 +16,8 @@
  *   !		0x21 is less than any non-space printable character
  *   ~		0x7e is greater than any printable character
  *
- * Users will never see those as bootm_boot_cleanup() will delete them again.
+ * Users will never see those as bootm_boot_cleanup() reverts the globalvars
+ * to the state before bootm_boot_prep().
  */
 #define LINUX_BOOTARGS_BOOTM_EARLY	"linux.bootargs.!bootm."
 #define LINUX_BOOTARGS_BOOTM_LATE	"linux.bootargs.~bootm."
@@ -80,7 +81,12 @@ int bootm_open_os_compressed(struct image_data *data);
 int bootm_boot_handler(struct image_data *data);
 void bootm_boot_cleanup(struct image_data *data);
 
+struct globalvar_scope;
+
 struct image_data {
+	/* globalvars to restore in bootm_boot_cleanup() */
+	struct globalvar_scope *globalvar_scope;
+
 	/* simplest case. barebox has already loaded the os here */
 	struct resource *os_res;
 
Signature · 1 line
2.47.3
#3 lore raw

PATCH v2 3/9 boot: revert globalvar changes after each boot entry

In reply to Sascha Hauer

Boot entries, especially boot scripts, configure the boot by setting global.bootm.* and global.linux.bootargs.* variables. To keep these from leaking into the boot entries tried afterwards, there are currently two mechanisms:

- bootscript_boot() saves the global.bootm.* variables that are part of struct bootm_data and restores them afterwards. Variables not part of this struct, like global.bootm.earlycon, are not restored, and empty load addresses come back as the hex values of UIMAGE_SOME_ADDRESS resp. UIMAGE_INVALID_ADDRESS.
- Kernel command line options have to be put into global.linux.bootargs.dyn.*, which boot_entry() clears after each boot entry. Options set by a boot entry in any other variable stay.

Replace both with a globalvar scope around the boot entry in boot_entry(). This reverts all changes to the globalvars covered by boot_globalvar_scope_push(), whatever the variable, and also restores values that were set before the boot entry instead of clearing them. This includes global.boot.watchdog_timeout, which boot_entry() reads before running the boot entry, so a value set by a boot entry so far only took effect for the following ones.

global.linux.bootargs.dyn.* still works as before for boot entries, but values set in this namespace before calling boot are now kept instead of being cleared once the first boot entry returns.

bootm_data_restore_defaults() has no users anymore, so remove it.

---
 Documentation/user/booting-linux.rst | 20 ++++++++++++++------
 Documentation/user/devboot.rst       |  4 ++--
 common/boot.c                        | 35 ++++++++---------------------------
 common/bootm.c                       | 21 ---------------------
 include/bootm.h                      |  1 -
 5 files changed, 24 insertions(+), 57 deletions(-)
Documentation/user/booting-linux.rst +14 -6
index afc705ac86..0fbdc52c68 100644
@@ -164,16 +164,24 @@ A simple boot entry in ``/env/boot/mmc`` could look like this:
   global.bootm.image=/mnt/mmc1/zImage
   global.bootm.oftree=/env/oftree
 
-  global linux.bootargs.dyn.root="root=PARTUUID=deadbeef:01"
+  global linux.bootargs.root="root=PARTUUID=deadbeef:01"
 
 This takes the kernel from ``/mnt/mmc1/zImage`` (which could be an
 :ref:`automount` path registered earlier). The devicetree will be used from
 ``/env/oftree``. The Kernel gets the command line
-``root=PARTUUID=deadbeef:01``. Note the ``.dyn`` in the bootargs variable name.
-boot entries should always add Kernel command line parameters to variables with
-``.dyn`` in it. These will be cleared before booting different boot entries.
-This is done so that following boot entries do not leak command line
-parameters from the previous boot entries.
+``root=PARTUUID=deadbeef:01``.
+
+All changes a boot entry makes to ``global.bootm.*``, ``global.linux.*``,
+``global.of.*`` and
+:ref:`global.boot.watchdog_timeout <magicvar_global_boot_watchdog_timeout>`
+are reverted when the boot entry returns:
+modified variables get their previous value back, variables created by
+the boot entry are removed and variables it removed are created again.
+This way a boot entry that fails to boot doesn't leak its settings into
+the following boot entries. Older boot entries put their Kernel command
+line parameters into ``global.linux.bootargs.dyn.*`` for this reason,
+which still works, but is no longer necessary. Settings meant for all
+boot entries belong into an init script or an nv variable instead.
 
 This entry can be booted with ``boot mmc``. It can also be made the default by
 setting the :ref:`global.boot.default <magicvar_global_boot_default>` variable
Documentation/user/devboot.rst +2 -2
index 78ee61d790..227048be97 100644
@@ -193,8 +193,8 @@ when ``CONFIG_BOOTM_OFTREE_FALLBACK`` is enabled), and appends the
 contains.
 
 Kernel command line fragments set by the script should use the
-``global.linux.bootargs.devboot.`` namespace. Unlike
-``global.linux.bootargs.dyn.``, which is cleared whenever a boot entry
+``global.linux.bootargs.devboot.`` namespace. Unlike variables set
+by the boot entries themselves, which are reverted whenever a boot entry
 returns, it survives falling through to the next boot target, e.g. for
 ``devboot system0 system1``. The ``devboot`` command removes the
 namespace after the boot command returns, so a subsequent plain
common/boot.c +8 -27
index 1d8768b864..eaeff7796e 100644
@@ -97,7 +97,7 @@ static int bootscript_boot(struct bootentry *entry, int verbose, int dryrun)
 	int bootm_nattempts;
 	int ret;
 
-	struct bootm_data backup = {}, data = {};
+	struct bootm_data data = {};
 
 	if (dryrun == 1) {
 		printf("Would run %s%s%s\n", bs->entry.path,
@@ -105,18 +105,6 @@ static int bootscript_boot(struct bootentry *entry, int verbose, int dryrun)
 		return 0;
 	}
 
-	bootm_data_init_defaults(&backup);
-
-	/*
-	 * The strings point to the globalvars' current values, which the
-	 * script frees when it assigns new ones. Keep our own copies.
-	 */
-	backup.os_file = xstrdup(backup.os_file);
-	backup.initrd_file = xstrdup(backup.initrd_file);
-	backup.oftree_file = xstrdup(backup.oftree_file);
-	backup.root_dev = xstrdup(backup.root_dev);
-	backup.root_param = xstrdup(backup.root_param);
-
 	globalvar_add_simple("linux.bootargs.dyn.ip", NULL);
 	globalvar_add_simple("linux.bootargs.dyn.root", NULL);
 
@@ -129,12 +117,12 @@ static int bootscript_boot(struct bootentry *entry, int verbose, int dryrun)
 	ret = execute_binfmt(bs->args ? 2 : 1, argv);
 	if (ret) {
 		pr_err("Running script '%s' failed: %s\n", bs->entry.path, strerror(-ret));
-		goto out;
+		return ret;
 	}
 
 	/* No point in repeating bootm if script already called it */
 	if (bootm_nattempts != bootm_command_attempts())
-		goto out;
+		return 0;
 
 	bootm_data_init_defaults(&data);
 
@@ -143,17 +131,7 @@ static int bootscript_boot(struct bootentry *entry, int verbose, int dryrun)
 	if (dryrun >= 2)
 		data.dryrun = dryrun - 1;
 
-	ret = bootm_entry(entry, &data);
-out:
-	bootm_data_restore_defaults(&backup);
-
-	free_const(backup.os_file);
-	free_const(backup.initrd_file);
-	free_const(backup.oftree_file);
-	free_const(backup.root_dev);
-	free_const(backup.root_param);
-
-	return ret;
+	return bootm_entry(entry, &data);
 }
 
 static unsigned int boot_watchdog_timeout;
@@ -210,6 +188,7 @@ BAREBOX_MAGICVAR(global.user,
 
 int boot_entry(struct bootentry *be, int verbose, int dryrun)
 {
+	struct globalvar_scope *scope;
 	int ret;
 
 	pr_info("Booting entry '%s'\n", be->title);
@@ -224,11 +203,13 @@ int boot_entry(struct bootentry *be, int verbose, int dryrun)
 		}
 	}
 
+	scope = boot_globalvar_scope_push();
+
 	ret = be->boot(be, verbose, dryrun);
 	if (ret && ret != -ENOMEDIUM)
 		pr_err("Booting entry '%s' failed: %pe\n", be->title, ERR_PTR(ret));
 
-	globalvar_set_match("linux.bootargs.dyn.", "");
+	globalvar_scope_pop(scope);
 
 	return ret;
 }
common/bootm.c +0 -21
index 0798324b14..4e0b688910 100644
@@ -101,27 +101,6 @@ void bootm_data_init_defaults(struct bootm_data *data)
 	data->efi_boot = bootm_efi_mode;
 }
 
-void bootm_data_restore_defaults(const struct bootm_data *data)
-{
-	globalvar_set("bootm.oftree", data->oftree_file);
-	globalvar_set("bootm.image", data->os_file);
-	pr_setenv("global.bootm.image.loadaddr", "0x%lx", data->os_address);
-	if (IS_ENABLED(CONFIG_BOOTM_INITRD)) {
-		pr_setenv("global.bootm.initrd.loadaddr", "0x%lx", data->initrd_address);
-		globalvar_set("bootm.initrd", data->initrd_file);
-	}
-	globalvar_set("bootm.root_dev", data->root_dev);
-	globalvar_set("bootm.root_param", data->root_param);
-	bootm_set_verify_mode(data->verify);
-	bootm_appendroot = data->appendroot;
-	bootm_provide_machine_id = data->provide_machine_id;
-	bootm_provide_hostname = data->provide_hostname;
-	bootm_provide_policy = data->provide_policy;
-	bootm_verbosity = data->verbose;
-	bootm_dryrun = data->dryrun;
-	bootm_efi_mode = data->efi_boot;
-}
-
 static enum bootm_verify bootm_verify_mode = BOOTM_VERIFY_AVAILABLE;
 
 enum bootm_verify bootm_get_verify_mode(void)
include/bootm.h +0 -1
index bbdbb8e69d..06eb90c5ed 100644
@@ -196,7 +196,6 @@ static inline int bootm_verbose(struct image_data *data)
 #endif
 
 void bootm_data_init_defaults(struct bootm_data *data);
-void bootm_data_restore_defaults(const struct bootm_data *data);
 
 const struct resource *
 bootm_load_os(struct image_data *data,
Signature · 1 line
2.47.3
#4 lore raw

PATCH v2 4/9 bootchooser: use a globalvar scope for its bootargs

In reply to Sascha Hauer

bootchooser passes the active target to the Kernel in global.linux.bootargs.bootchooser and sets it to an empty value again after booting failed. The variable is never removed though, so it stays around with an empty value after the first boot attempt.

Use a globalvar scope instead, which removes the variable again and also reverts any other boot related globalvars changed while booting the target.

---
 common/bootchooser.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
common/bootchooser.c +5 -1
index 2a75dfdcc8..2049425ab3 100644
@@ -6,6 +6,7 @@
 #define pr_fmt(fmt)	"bootchooser: " fmt
 
 #include <bootchooser.h>
+#include <boot.h>
 #include <environment.h>
 #include <globalvar.h>
 #include <magicvar.h>
@@ -846,6 +847,7 @@ static int bootchooser_boot_one(struct bootchooser *bc, int *tryagain,
 	struct bootentries *entries;
 	struct bootentry *entry;
 	struct bootchooser_target *target;
+	struct globalvar_scope *scope = NULL;
 	int ret = 0;
 
 	entries = bootentries_alloc();
@@ -857,6 +859,8 @@ static int bootchooser_boot_one(struct bootchooser *bc, int *tryagain,
 		goto out;
 	}
 
+	scope = boot_globalvar_scope_push();
+
 	system = basprintf("bootchooser.active=%s", target->name);
 	globalvar_add_simple("linux.bootargs.bootchooser", system);
 	free(system);
@@ -887,7 +891,7 @@ static int bootchooser_boot_one(struct bootchooser *bc, int *tryagain,
 
 	*tryagain = 1;
 out:
-	globalvar_set_match("linux.bootargs.bootchooser", NULL);
+	globalvar_scope_pop(scope);
 
 	bootentries_free(entries);
 
Signature · 1 line
2.47.3
#5 lore raw

PATCH v2 5/9 test: py: add test for reverting globalvars after boot

In reply to Sascha Hauer

Add tests for the globalvar scope around boot entries: a failing boot script that changes, creates and removes global.bootm.* and global.linux.bootargs.* variables and changes global.of.overlay.path and global.linux.bootargs_append, where the configuration has them, must leave them as they were before, while globalvars outside the scope keep their new values. A second test nests boot entries like devboot does and checks that the outer entry's variables are visible in the inner one and survive it.

---
 test/py/test_boot_globalvar_scope.py | 117 +++++++++++++++++++++++++++++++++++
 1 file changed, 117 insertions(+)
test/py/test_boot_globalvar_scope.py new file +117 -0
new file mode 100644
index 0000000000..041d38c814
@@ -0,0 +1,117 @@
+# SPDX-License-Identifier: GPL-2.0-or-later
+
+import pytest
+from .helper import devinfo, skip_disabled
+
+
+def write_bootscript(barebox, name, lines):
+    barebox.run_check(f"echo -o /env/boot/{name} '#!/bin/sh'")
+    for line in lines:
+        # Variable references must reach the script unexpanded. Neither
+        # quoting nor a backslash achieves that here, so splice in the
+        # dollar sign from a variable.
+        line = line.replace("$", "${dollar}")
+        barebox.run_check(f"dollar='$'; echo -a /env/boot/{name} \"{line}\"")
+
+
+def globals_now(barebox):
+    params = devinfo(barebox, "global")["Parameters"]
+    # devinfo prints "value (type: ...)", strip the annotation
+    return {k: v.split(" (type:")[0].strip('"') for k, v in params.items()}
+
+
[email protected](scope="function")
+def scope_globals(barebox, barebox_config):
+    skip_disabled(barebox_config, "CONFIG_CMD_BOOT", "CONFIG_CMD_GLOBAL",
+                  "CONFIG_CMD_ECHO")
+
+    barebox.run_check("global.bootm.image=/preset/image")
+    barebox.run_check("global linux.bootargs.preset=preset=1")
+    barebox.run_check("global linux.bootargs.removed=removed=1")
+    barebox.run_check("global.bootm.appendroot=0")
+    old_user = barebox.run_check("echo ${global.user}")[0]
+
+    yield old_user
+
+    barebox.run_check(f"global.user={old_user}")
+    barebox.run("global -r linux.bootargs.preset")
+    barebox.run("global -r linux.bootargs.removed")
+    barebox.run_check("global.bootm.image=")
+
+
+def test_boot_entry_reverts_globalvars(barebox, scope_globals):
+    old_user = scope_globals
+    before = globals_now(barebox)
+
+    # boot related globalvars outside of bootm.* and linux.bootargs.*,
+    # where the configuration has them
+    others = {var: val for var, val in (("of.overlay.path", "/does/not/exist"),
+                                        ("linux.bootargs_append", "1"))
+              if var in before}
+
+    write_bootscript(barebox, "scope", [
+        *(f"global.{var}={val}" for var, val in others.items()),
+        "global.bootm.image=/does/not/exist",
+        "global.bootm.oftree=/does/not/exist.dtb",
+        "global.bootm.appendroot=1",
+        "global.linux.bootargs.dyn.root=root=/dev/leak",
+        "global linux.bootargs.leak=leak=1",
+        "global.linux.bootargs.preset=preset=2",
+        "global -r linux.bootargs.removed",
+        "global.user=scope-test",
+    ])
+
+    # bootm fails on the nonexistent image, so boot returns
+    barebox.run("boot scope")
+
+    after = globals_now(barebox)
+
+    # values within the boot scope are restored...
+    assert after["bootm.image"] == "/preset/image"
+    assert after["bootm.oftree"] == before["bootm.oftree"]
+    assert after["bootm.appendroot"] == "0"
+    assert after["linux.bootargs.preset"] == "preset=1"
+    for var in others:
+        assert after[var] == before[var]
+
+    # ...vars created by the boot entry are gone...
+    assert "linux.bootargs.leak" not in after
+    assert "linux.bootargs.dyn.root" not in after
+    assert "linux.bootargs.dyn.ip" not in after
+
+    # ...vars removed by the boot entry are back...
+    assert after["linux.bootargs.removed"] == "removed=1"
+
+    # ...and the loadaddrs don't come back as 0xfffffffe after a failed boot
+    assert after["bootm.image.loadaddr"] == before["bootm.image.loadaddr"]
+
+    # globalvars outside the boot scope are left alone
+    assert after["user"] == "scope-test"
+    assert old_user != "scope-test"
+
+
[email protected]("scope_globals")
+def test_boot_entry_scope_nests(barebox):
+    # devboot-style: an outer entry sets up bootargs that must be visible
+    # in, and survive, the inner boot entry
+    write_bootscript(barebox, "scope-inner", [
+        "global.bootm.image=/does/not/exist",
+        "echo inner-sees ${global.linux.bootargs.outer}",
+        "global.linux.bootargs.outer=outer=clobbered",
+        "global linux.bootargs.inner=inner=1",
+    ])
+    write_bootscript(barebox, "scope-outer", [
+        "global linux.bootargs.outer=outer=1",
+        "boot scope-inner",
+        "echo outer-sees ${global.linux.bootargs.outer} "
+        "inner=${global.linux.bootargs.inner}",
+    ])
+
+    stdout, _, _ = barebox.run("boot scope-outer")
+    assert "inner-sees outer=1" in stdout
+    assert "outer-sees outer=1 inner=" in stdout
+
+    after = globals_now(barebox)
+    assert "linux.bootargs.outer" not in after
+    assert "linux.bootargs.inner" not in after
+    assert after["bootm.image"] == "/preset/image"
Signature · 1 line
2.47.3
#6 lore raw

PATCH v2 6/9 bootargs: remove unused linux_bootargs_overwrite()

In reply to Sascha Hauer

linux_bootargs_overwrite() lost its last user with commit fe1e02cc68cd ("bootm: add generic android image handler"), which replaced the old ARM32 specific Android image handler calling it. Remove it together with the linux_bootargs_overwritten state it maintained.

---
 common/bootargs.c  | 17 -----------------
 include/bootargs.h |  5 -----
 2 files changed, 22 deletions(-)
common/bootargs.c +0 -17
index 6373d9ccb1..06623bb60b 100644
@@ -12,7 +12,6 @@
 #include <environment.h>
 
 static char *linux_bootargs;
-static int linux_bootargs_overwritten;
 
 /*
  * This returns the Linux bootargs
@@ -28,9 +27,6 @@ const char *linux_bootargs_get(void)
 {
 	char *bootargs, *parts;
 
-	if (linux_bootargs_overwritten)
-		return linux_bootargs;
-
 	free(linux_bootargs);
 	linux_bootargs = NULL;
 
@@ -65,19 +61,6 @@ const char *linux_bootargs_get(void)
 	return linux_bootargs;
 }
 
-int linux_bootargs_overwrite(const char *bootargs)
-{
-	if (bootargs) {
-		free(linux_bootargs);
-		linux_bootargs = xstrdup(bootargs);
-		linux_bootargs_overwritten = 1;
-	} else {
-		linux_bootargs_overwritten = 0;
-	}
-
-	return 0;
-}
-
 char *linux_bootargs_append_rootwait(char *rootarg_old)
 {
 	char *rootarg = xasprintf("%s rootwait=%d",
include/bootargs.h +0 -5
index 4a51e81173..93ec621ad1 100644
@@ -8,7 +8,6 @@ extern int linux_rootwait_secs;
 
 #ifdef CONFIG_FLEXIBLE_BOOTARGS
 const char *linux_bootargs_get(void);
-int linux_bootargs_overwrite(const char *bootargs);
 char *linux_bootargs_append_rootwait(char *rootarg_old);
 #else
 static inline const char *linux_bootargs_get(void)
@@ -16,10 +15,6 @@ static inline const char *linux_bootargs_get(void)
 	return getenv("bootargs");
 }
 
-static inline int linux_bootargs_overwrite(const char *bootargs)
-{
-	return setenv("bootargs", bootargs);
-}
 static inline char *linux_bootargs_append_rootwait(char *rootarg)
 {
 	return rootarg;
Signature · 1 line
2.47.3
#7 lore raw

PATCH v2 7/9 of: add watchdog bootarg directly instead of via a globalvar

In reply to Sascha Hauer

With CONFIG_SYSTEMD_OF_WATCHDOG, the device tree bootargs fixup puts systemd.watchdog_device= into global.linux.bootargs.dyn.watchdog only to read it back right away via linux_bootargs_get(). As a side effect, the variable is created whenever the fixup runs, so also for of_dump -F, oftree -s or of_diff after a boot attempt has enabled the watchdog, and stays around afterwards.

Return the option from watchdog_build_bootargs() and append it to the bootargs in of_write_bootargs() instead. Note this moves the option to the end of the command line, while it was previously sorted among the global.linux.bootargs.* variables.

---
 Documentation/user/booting-linux.rst |  2 ++
 common/Kconfig                       |  6 +++---
 common/oftree.c                      | 41 ++++++++++++++++++++----------------
 3 files changed, 28 insertions(+), 21 deletions(-)
Documentation/user/booting-linux.rst +2 -0
index 0fbdc52c68..158aa8b313 100644
@@ -124,6 +124,8 @@ interleaved with externally provided command-line arguments:
   * ``systemd.machine_id=`` controlled by :ref:`global.bootm.provide_machine_id <magicvar_global_bootm_provide_machine_id>`
   * ``systemd.hostname=`` controlled by :ref:`global.bootm.provide_hostname <magicvar_global_bootm_provide_hostname>`
   * ``barebox.security.policy=`` controlled by :ref:`global.bootm.provide_policy <magicvar_global_bootm_provide_policy>`
+  * ``systemd.watchdog_device=`` controlled by ``CONFIG_SYSTEMD_OF_WATCHDOG``,
+    only when booting with a device tree
 
 Creating root= options for the Kernel
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
common/Kconfig +3 -3
index 9adecfd2e4..da4cc8a5c9 100644
@@ -1443,9 +1443,9 @@ config SYSTEMD_OF_WATCHDOG
 	bool "inform devicetree-enabled kernel of used watchdog"
 	depends on WATCHDOG && OFTREE && FLEXIBLE_BOOTARGS
 	help
-	  Sets the linux.bootargs.dyn.watchdog global variable with a value of
-	  systemd.watchdog_device=/dev/WDOG if barebox succeeded in enabling
-	  the watchdog WDOG prior to boot. WDOG is the alias of the watchdog
+	  Appends systemd.watchdog_device=/dev/WDOG to the Kernel command line
+	  in the device tree if barebox succeeded in enabling the watchdog
+	  WDOG prior to boot. WDOG is the alias of the watchdog
 	  in the kernel device tree. If the kernel is booted without a device
 	  tree or with one that lacks aliases, nothing is added.
 
common/oftree.c +23 -18

76 lines not on this page · raw message

Signature · 1 line
2.47.3
#8 lore raw

PATCH v2 8/9 defaultenv: don't use global.linux.bootargs.dyn.* in boot entries

In reply to Sascha Hauer

Boot entries no longer need to put their Kernel command line options into global.linux.bootargs.dyn.*, as boot_entry() reverts all changes to global.linux.bootargs.* when the boot entry returns. Use plain names in the net and dfu boot entries, the boot entry template and the matching example in the documentation.

Unlike the dyn.ip and dyn.root variables, which bootscript_boot() creates for compatibility with existing boot scripts, the new variables don't exist beforehand, so create them with the global command.

---
 Documentation/user/booting-linux.rst            | 5 +++--
 defaultenv/defaultenv-2-base/boot/net           | 5 +++--
 defaultenv/defaultenv-2-base/data/boot-template | 2 +-
 defaultenv/defaultenv-2-dfu/boot/dfu            | 4 ++--
 4 files changed, 9 insertions(+), 7 deletions(-)
Documentation/user/booting-linux.rst +3 -2
index 158aa8b313..85f7694fe8 100644
@@ -442,9 +442,10 @@ If the preconfigured paths or names are not suitable, they can be adjusted in
   fi
 
   nfsroot="/home/${global.user}/nfsroot/${global.hostname}"
-  ip_route_get -b ${global.net.server} global.linux.bootargs.dyn.ip
+  global linux.bootargs.ip
+  ip_route_get -b ${global.net.server} global.linux.bootargs.ip
 
-  global.linux.bootargs.dyn.root="root=/dev/nfs nfsroot=$nfsroot,v3,tcp"
+  global linux.bootargs.root="root=/dev/nfs nfsroot=$nfsroot,v3,tcp"
 
 ``boot net`` will then retrieve the kernel (and also the device tree and
 initramfs, if used) over TFTP and boot it.
defaultenv/defaultenv-2-base/boot/net +3 -2
index 8408ceaf39..f025bb4098 100644
@@ -23,6 +23,7 @@ if [ -f "${initramfs}" ]; then
 	global.bootm.initrd="$initramfs"
 else
 	nfsroot="${nfsserver}:/home/${global.user}/nfsroot/${global.hostname}"
-	ip_route_get -b ${global.net.server} global.linux.bootargs.dyn.ip
-	global.linux.bootargs.dyn.root="root=/dev/nfs nfsroot=$nfsroot,v3,tcp"
+	global linux.bootargs.ip
+	ip_route_get -b ${global.net.server} global.linux.bootargs.ip
+	global linux.bootargs.root="root=/dev/nfs nfsroot=$nfsroot,v3,tcp"
 fi
defaultenv/defaultenv-2-base/data/boot-template +1 -1
index 689d98e1e9..b63eb86d1a 100644
@@ -6,4 +6,4 @@ global.bootm.image=<path to image>
 
 #bootargs-ip
 
-global.linux.bootargs.dyn.root="root=<rootfs here>"
+global linux.bootargs.root="root=<rootfs here>"
defaultenv/defaultenv-2-dfu/boot/dfu +2 -2
index 682091141e..56a88ae0a3 100644
@@ -23,8 +23,8 @@ if [ ! -f "$kernel" ]; then
 fi
 
 if [ -f "$cmdline" ]; then
-	global linux.bootargs.dyn.dfu
-	readf $cmdline global.linux.bootargs.dyn.dfu
+	global linux.bootargs.dfu
+	readf $cmdline global.linux.bootargs.dfu
 fi
 
 if [ -f "$dtb" ]; then
Signature · 1 line
2.47.3
#9 lore raw

PATCH v2 9/9 Documentation: migration-guides: describe reverting boot globalvars

In reply to Sascha Hauer

Describe that the boot related globalvars are now reverted after booting, that the .dyn infix is no longer necessary, that values set in global.linux.bootargs.dyn.* before calling boot are now kept and that the order of the Kernel command line options generated by the default environment boot scripts may change.

---
 .../migration-master/boot-globalvar-scope.rst         | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
Documentation/migration-guides/migration-master/boot-globalvar-scope.rst new file +19 -0
new file mode 100644
index 0000000000..92428ae1e0
@@ -0,0 +1,19 @@
+Boot related globalvars are reverted after booting
+--------------------------------------------------
+
+``global.bootm.*``, ``global.linux.*``, ``global.of.*`` and
+``global.boot.watchdog_timeout`` are now snapshotted before each boot
+entry and each bootm and restored afterwards, so changes made while
+booting no longer leak into subsequent boot attempts.
+
+Boot entries therefore no longer need to put Kernel command line options
+into ``global.linux.bootargs.dyn.*``. The boot scripts shipped with the
+default environment have dropped the ``.dyn`` infix.
+
+``global.linux.bootargs.dyn.*`` variables are no longer cleared after a
+boot entry returns, but restored to their previous values. Values set
+in this namespace before calling ``boot`` are thus kept and passed to
+all boot entries instead of only the first one. Settings meant for all
+boot entries should be put into a different variable, e.g.
+``global.linux.bootargs.base``, as ``.dyn`` no longer has a special
+meaning.
Signature · 1 line
2.47.3
author Applied
#10 lore raw
In reply to Sascha Hauer
Quoted 13 lines · Sascha Hauer

Boot entries configure booting through globalvars like global.bootm.*, global.linux.bootargs.* or global.of.overlay.*. So far only some of these were restored after a boot entry returned, by saving a fixed set of variables and by clearing the global.linux.bootargs.dyn.* namespace.

This series adds globalvar scopes, which snapshot all globalvars matching given patterns and restore them later, and uses them around each boot entry, bootm and bootchooser boot attempts. With that the .dyn infix is no longer needed, so it is dropped from the boot scripts of the default environment. blspec and extlinux keep using global.linux.bootargs.dyn.bootentries, so the position of their options in the Kernel command line doesn't change.

Quoted 1 line

[...]

Applied, thanks!

[1/9] globalvar: add scopes to snapshot and restore globalvars
https://git.pengutronix.de/cgit/barebox/commit/?id=4b6cba03b9c1 (link may not be stable)
[2/9] bootm: revert globalvar changes in bootm_boot_cleanup()

      https://git.pengutronix.de/cgit/barebox/commit/?id=94074c039321 (link may not be stable)

[3/9] boot: revert globalvar changes after each boot entry
https://git.pengutronix.de/cgit/barebox/commit/?id=efb2a44be77c (link may not be stable)
[4/9] bootchooser: use a globalvar scope for its bootargs
https://git.pengutronix.de/cgit/barebox/commit/?id=1d5167e77f1f (link may not be stable)
[5/9] test: py: add test for reverting globalvars after boot
https://git.pengutronix.de/cgit/barebox/commit/?id=7e59add5e61e (link may not be stable)
[6/9] bootargs: remove unused linux_bootargs_overwrite()
https://git.pengutronix.de/cgit/barebox/commit/?id=697cf02c0d13 (link may not be stable)
[7/9] of: add watchdog bootarg directly instead of via a globalvar

      https://git.pengutronix.de/cgit/barebox/commit/?id=f59275942a82 (link may not be stable)

[8/9] defaultenv: don't use global.linux.bootargs.dyn.* in boot entries
https://git.pengutronix.de/cgit/barebox/commit/?id=e71011c84ad2 (link may not be stable)
[9/9] Documentation: migration-guides: describe reverting boot globalvars
https://git.pengutronix.de/cgit/barebox/commit/?id=99b7fad27f75 (link may not be stable)

Best regards,

Signature · 1 line
Sascha Hauer <[email protected]>