Skip to contentSkip to conversation

bootstd: rauc: Fixes, partition names and built-in boot command

PATCH In review Frieder Schrempf 3 participants 16 messages Nov 2 – Nov 12

lore
Share & tools
lore
#0 lore raw

v2 cover bootstd: rauc: Fixes, partition names and built-in boot command

This series fixes some issues in the RAUC bootmeth and adds two options to make it safer to use on real devices, together with tests.

Patches 1-4 fix bugs in bootmeth_rauc.c: an uninitialised pointer when a bootflow has no block device, a leak of the active slot name, a stack buffer overflow with long slot names in BOOT_ORDER, and a leak of the boot script when a boot attempt fails and is retried.

Patch 5 makes the RAUC test restore the bootdev order also if it fails. Before, a failing check left a static array in std->bootdev_order, which was then passed to free() and aborted sandbox. Patch 6 adds a test that boots the same RAUC bootflow twice.

Patch 7 makes the bootmeth set its BOOT_ORDER and BOOT_x_LEFT variables only for a device with a RAUC system, instead of for every MMC device it scans.

Patches 8 and 9 make the bootmeth safer to use on real devices, without changing anything for existing users:

- CONFIG_BOOTMETH_RAUC_PARTITIONS can give the partitions by their GPT names instead of their numbers. The bootmeth then only claims a device which has the partitions of all slots. With numbers, it claims any MMC device whose partitions happen to fit the configured layout, such as a standard distro installed to eMMC, and writes its variables to the environment. This allows to use BOOTMETH_RAUC safely alongside other bootmeths.

- The new option CONFIG_BOOTMETH_RAUC_BOOTCMD, empty by default, sets a command built into U-Boot that boots the slot instead of running boot.scr from the boot partition.
Nothing authenticates that partition, and signing the script is not a reliable fix, as the environment must stay writable for the RAUC variables and setting verify=no there skips all checks. With this option, U-Boot executes nothing from the boot partition.

The bootmeth keeps both options in its platform data, which is set from Kconfig when it is bound. The tests in patches 11 and 12 change them at runtime, so sandbox_defconfig keeps the default configuration and all tests run on it. As partition names need GPT, patch 10 adds GPT support to DiskHelper in fs_helper.py for a second RAUC test image.

---
Changes in v2:
- Patches 1, 5 and 10: Add Reviewed-by tag from Simon.
- Patch 2: Look up the slot in find_active_slot() and return it instead of a strdup() copy of its name (Simon). This also catches an unknown slot in BOOT_ORDER before its BOOT_x_LEFT counter is decremented.
- Patch 3: Print an error for a too long slot name in CONFIG_BOOTMETH_RAUC_BOOT_ORDER, document the 32-character limit and pass on the return value of boot_left_name() (Simon). Rebase on the changes in patch 2.
- Patch 4: Reset the bootflow state before loading the script again and move freeing the image list into bootflow_free_images() in bootflow.c, used by bootflow_free() as well (Simon).
- New patch 6: Test booting the same bootflow twice (Simon).
- New patch 7: Set BOOT_ORDER and BOOT_x_LEFT only for a device with a RAUC system (Simon).
- Patch 8: Give the partition names in CONFIG_BOOTMETH_RAUC_PARTITIONS instead of the new option CONFIG_BOOTMETH_RAUC_PART_NAMES (Bastien), and only use a device which has the partitions of all slots (Simon). Renamed from "Optionally check the partition names".
- Patches 8 and 9: Keep the options in the platform data of the bootmeth, set from Kconfig when it is bound, so that tests can change them at runtime. The boot script code is now always built (Simon).
- Patches 11 and 12: Set the options in the tests instead of sandbox_defconfig, so that the default configuration is still tested, and drop the #ifdefs. Keep the RAUC test image (mmc10) on MBR with a boot script and use a second GPT image (mmc13) for partition names. Also check matching names, a slot with missing partitions, that MBR is rejected and that no variables are set for an unused device (Simon). Patch 11 is renamed from "Test the RAUC partition name check".
- Link to v1: https://patch.msgid.link/[email protected]

---
Frieder Schrempf (12):
bootstd: rauc: Initialise desc in distro_rauc_scan_parts()
bootstd: rauc: Fix leak of the active slot name
bootstd: rauc: Fix overflow of the BOOT_x_LEFT name buffer
bootstd: rauc: Free the boot script of a failed boot attempt
test: boot: Restore the bootdev order if the RAUC test fails
test: boot: Test booting a RAUC bootflow twice
bootstd: rauc: Only set the RAUC variables for a RAUC device
bootstd: rauc: Optionally find the partitions by name
bootstd: rauc: Optionally boot with a built-in command
test: fs_helper: Support GPT in DiskHelper
test: boot: Test finding the RAUC partitions by name
test: boot: Test the RAUC built-in boot command

 MAINTAINERS                  |   1 +
 arch/sandbox/dts/test.dts    |   8 ++
 boot/Kconfig                 |  24 ++++
 boot/bootflow.c              |  13 +-
 boot/bootmeth_rauc.c         | 284 ++++++++++++++++++++++++++++++----------
 configs/sandbox_defconfig    |   1 +
 doc/develop/bootstd/rauc.rst |  15 +++
 include/bootflow.h           |  10 ++
 include/bootmeth_rauc.h      |  25 ++++
 test/boot/bootflow.c         | 301 +++++++++++++++++++++++++++++++++++++++++--
 test/py/tests/fs_helper.py   |  36 ++++--
 test/py/tests/test_ut.py     |  30 +++--
 12 files changed, 644 insertions(+), 104 deletions(-)

---
base-commit: ee9fc27f2a2a43f253a6fe18d7a6f7c4eb0cda3b
change-id: 20261029-main-c3a89be613d5

Best regards,

Signature · 1 line
Frieder Schrempf <[email protected]>
#1 lore raw

PATCH v2 1/12 bootstd: rauc: Initialise desc in distro_rauc_scan_parts()

From: Frieder Schrempf <[email protected]>

distro_rauc_scan_parts() only sets desc if the bootflow has a block device, but then checks desc before scanning the slots. Without a block device, that check reads an uninitialised pointer and may hand it to fs_set_blk_dev_with_part() and part_get_info().

Initialise desc to NULL, so that a bootflow without a block device finds no slot, as the check intends.

Fixes f271b0627001 ("bootstd: rauc: Only scan all partitions instead of boot files")

---
Changes in v2:
- Add Reviewed-by tag from Simon

---
 boot/bootmeth_rauc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
boot/bootmeth_rauc.c +1 -1
index 844df7576bb..4a3f05103eb 100644
@@ -95,7 +95,7 @@ static int distro_rauc_check(struct udevice *dev, struct bootflow_iter *iter)
 
 static int distro_rauc_scan_parts(struct bootflow *bflow)
 {
-	struct blk_desc *desc;
+	struct blk_desc *desc = NULL;
 	struct distro_rauc_priv *priv;
 	struct disk_partition fs_info;
 	char *boot_order;
Signature · 1 line
2.56.0
#2 lore raw

PATCH v2 2/12 bootstd: rauc: Fix leak of the active slot name

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

find_active_slot() returns a strdup() copy of the slot name, which distro_rauc_boot() never frees, so every boot attempt leaks it. The strdup() result is not checked either and if it fails, get_slot() passes NULL to strcmp().

The copy is only used to look up the slot. Pass the private data to find_active_slot() and look up the slot there, while the boot order list is still valid, and return the slot instead of its name. This drops the copy altogether. It also catches a BOOT_ORDER entry without a matching slot before its BOOT_x_LEFT counter is decremented.

Fixes 7e5c2c782fb9 ("bootstd: Add implementation for bootmeth rauc")
Assisted-by LLM

---
Changes in v2:
- Look up the slot in find_active_slot() and return it instead of a strdup() copy of its name (Simon)
- Update the commit message accordingly

---
 boot/bootmeth_rauc.c | 47 +++++++++++++++++++++++------------------------
 1 file changed, 23 insertions(+), 24 deletions(-)
boot/bootmeth_rauc.c +23 -24
index 4a3f05103eb..7273156c4dd 100644
@@ -19,6 +19,7 @@
 #include <mapmem.h>
 #include <part.h>
 #include <string.h>
+#include <linux/err.h>
 #include <linux/stringify.h>
 #include <asm/cache.h>
 
@@ -318,42 +319,46 @@ static int distro_rauc_load_boot_script(struct bootflow *bflow,
 	return 0;
 }
 
-static int find_active_slot(char **slot_name, ulong *slot_tries)
+static const struct distro_rauc_slot *find_active_slot(struct distro_rauc_priv *priv,
+						       ulong *slot_tries)
 {
 	ulong tries;
 	char boot_left[BOOT_LEFT_LEN];
 	char *boot_order;
+	const struct distro_rauc_slot *slot = NULL;
 	const char **boot_order_list;
-	bool slot_found = false;
 	int ret;
 	int i;
 
 	boot_order = env_get("BOOT_ORDER");
 	if (!boot_order)
-		return log_msg_ret("env", -ENOENT);
+		return ERR_PTR(log_msg_ret("env", -ENOENT));
 	boot_order_list = str_to_list(boot_order);
-	for (i = 0; boot_order_list[i] && !slot_found; i++) {
+	for (i = 0; boot_order_list[i] && !slot; i++) {
 		sprintf(boot_left, "BOOT_%s_LEFT", boot_order_list[i]);
 		tries = env_get_ulong(boot_left, 10, ULONG_MAX);
 		if (tries == ULONG_MAX) {
 			str_free_list(boot_order_list);
-			return log_msg_ret("env", -ENOENT);
+			return ERR_PTR(log_msg_ret("env", -ENOENT));
 		}
 
 		if (tries) {
+			slot = get_slot(priv, boot_order_list[i]);
+			if (!slot) {
+				str_free_list(boot_order_list);
+				return ERR_PTR(log_msg_ret("slot", -ENOENT));
+			}
 			ret = env_set_ulong(boot_left, tries - 1);
 			if (ret) {
 				str_free_list(boot_order_list);
-				return log_msg_ret("env", ret);
+				return ERR_PTR(log_msg_ret("env", ret));
 			}
-			*slot_name = strdup(boot_order_list[i]);
 			*slot_tries = tries;
-			slot_found = true;
 		}
 	}
 	str_free_list(boot_order_list);
 
-	if (!slot_found) {
+	if (!slot) {
 		if (IS_ENABLED(CONFIG_BOOTMETH_RAUC_RESET_ALL_ZERO_TRIES)) {
 			log_warning("WARNING: No valid slot found\n");
 			log_info("INFO: Resetting all slot tries to " __stringify(CONFIG_BOOTMETH_RAUC_DEFAULT_TRIES) "\n");
@@ -363,20 +368,20 @@ static int find_active_slot(char **slot_name, ulong *slot_tries)
 				ret = env_set_ulong(boot_left, CONFIG_BOOTMETH_RAUC_DEFAULT_TRIES);
 				if (ret) {
 					str_free_list(boot_order_list);
-					return log_msg_ret("env", ret);
+					return ERR_PTR(log_msg_ret("env", ret));
 				}
 			}
 			str_free_list(boot_order_list);
 			ret = env_save();
 			if (ret)
-				return log_msg_ret("env", ret);
+				return ERR_PTR(log_msg_ret("env", ret));
 			do_reset(NULL, 0, 0, NULL);
 		}
 		log_err("ERROR: No valid slot found\n");
-		return -EINVAL;
+		return ERR_PTR(-EINVAL);
 	}
 
-	return 0;
+	return slot;
 }
 
 static int distro_rauc_boot(struct udevice *dev, struct bootflow *bflow)
@@ -386,7 +391,6 @@ static int distro_rauc_boot(struct udevice *dev, struct bootflow *bflow)
 	const struct distro_rauc_slot *slot;
 	char *boot_order;
 	const char **boot_order_list;
-	char *active_slot;
 	ulong active_slot_tries;
 	char raucargs[64];
 	char boot_left[BOOT_LEFT_LEN];
@@ -411,20 +415,15 @@ static int distro_rauc_boot(struct udevice *dev, struct bootflow *bflow)
 		return log_msg_ret("env", ret);
 
 	/* Find active, valid slot */
-	ret = find_active_slot(&active_slot, &active_slot_tries);
-	if (ret)
-		return log_msg_ret("env", ret);
+	slot = find_active_slot(priv, &active_slot_tries);
+	if (IS_ERR(slot))
+		return log_msg_ret("env", PTR_ERR(slot));
 
 	/* Kernel command line arguments */
-	sprintf(raucargs, "rauc.slot=%s", active_slot);
+	sprintf(raucargs, "rauc.slot=%s", slot->name);
 	ret = env_set("raucargs", raucargs);
 	if (ret)
 		return log_msg_ret("env", ret);
-
-	/* Active slot info */
-	slot = get_slot(priv, active_slot);
-	if (!slot)
-		return log_msg_ret("env", -ENOENT);
 	ret = env_set_hex("distro_bootpart", slot->boot_part);
 	if (ret)
 		return log_msg_ret("env", ret);
@@ -441,7 +440,7 @@ static int distro_rauc_boot(struct udevice *dev, struct bootflow *bflow)
 		return log_msg_ret("load", ret);
 
 	log_info("INFO: Booting slot %s, %lu of %d tries left\n",
-		 active_slot, active_slot_tries, CONFIG_BOOTMETH_RAUC_DEFAULT_TRIES);
+		 slot->name, active_slot_tries, CONFIG_BOOTMETH_RAUC_DEFAULT_TRIES);
 
 	log_debug("devtype: %s\n", env_get("devtype"));
 	log_debug("devnum: %s\n", env_get("devnum"));
Signature · 1 line
2.56.0
#3 lore raw

PATCH v2 3/12 bootstd: rauc: Fix overflow of the BOOT_x_LEFT name buffer

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

The name of the BOOT_x_LEFT variable of a slot is written into a stack buffer of BOOT_LEFT_LEN bytes with sprintf(). BOOT_LEFT_LEN leaves room for a slot name of 32 characters, but not for the terminating NUL, and longer names are not limited at all.

When booting, the slot names come from BOOT_ORDER in the environment, which is only checked against the configured slots when the bootflow is read. Setting BOOT_ORDER to a long name between 'bootflow scan' and 'bootflow boot' therefore overflows the buffer in find_active_slot().

Make room for the NUL, and write the name with snprintf() in a helper that fails with -E2BIG if it does not fit.

A slot name in CONFIG_BOOTMETH_RAUC_BOOT_ORDER that is too long is a configuration error, which would otherwise only make the bootmeth fail silently. Print an error for it and document the limit in the help of the option.

Fixes 7e5c2c782fb9 ("bootstd: Add implementation for bootmeth rauc")
Assisted-by LLM

---
Changes in v2:
- Print an error for a too long slot name in CONFIG_BOOTMETH_RAUC_BOOT_ORDER (Simon)
- Document the 32-character limit in the Kconfig help (Simon)
- Pass on the return value of boot_left_name() (Simon)
- Rebase on the changes in patch 2

---
 boot/Kconfig         |  1 +
 boot/bootmeth_rauc.c | 37 ++++++++++++++++++++++++++++++-------
 2 files changed, 31 insertions(+), 7 deletions(-)
boot/Kconfig +1 -0
index 8fcdc36c931..d4d2a77f15a 100644
@@ -958,6 +958,7 @@ config BOOTMETH_RAUC_BOOT_ORDER
 	  Sets the default boot order. This must be list of space-separated
 	  strings naming the individual boot slots. Each entry in this string
 	  should correspond to an existing slot on the target's flash device.
+	  Slot names can be at most 32 characters long.
 
 config BOOTMETH_RAUC_PARTITIONS
 	string "RAUC boot and root partitions indexes"
boot/bootmeth_rauc.c +30 -7
index 7273156c4dd..32e1de886cc 100644
@@ -23,8 +23,8 @@
 #include <linux/stringify.h>
 #include <asm/cache.h>
 
-/* Length of env var "BOOT_*_LEFT" */
-#define BOOT_LEFT_LEN	(5 + 32 + 5)
+/* Length of env var "BOOT_*_LEFT", including the terminating NUL */
+#define BOOT_LEFT_LEN	(5 + 32 + 5 + 1)
 
 static const char * const script_names[] = { "boot.scr", "boot.scr.uimg", NULL };
 
@@ -67,6 +67,15 @@ static void distro_rauc_priv_free(struct distro_rauc_priv *priv)
 	free(priv);
 }
 
+static int boot_left_name(char *buf, const char *slot_name)
+{
+	if (snprintf(buf, BOOT_LEFT_LEN, "BOOT_%s_LEFT", slot_name) >=
+	    BOOT_LEFT_LEN)
+		return log_msg_ret("name", -E2BIG);
+
+	return 0;
+}
+
 static struct distro_rauc_slot *get_slot(struct distro_rauc_priv *priv,
 					 const char *slot_name)
 {
@@ -168,7 +177,13 @@ static int distro_rauc_read_bootflow(struct udevice *dev, struct bootflow *bflow
 	default_boot_order = CONFIG_BOOTMETH_RAUC_BOOT_ORDER;
 	default_boot_order_list = str_to_list(default_boot_order);
 	for (i = 0; default_boot_order_list[i]; i++) {
-		sprintf(boot_left, "BOOT_%s_LEFT", default_boot_order_list[i]);
+		ret = boot_left_name(boot_left, default_boot_order_list[i]);
+		if (ret) {
+			log_err("ERROR: Slot name %s is too long\n",
+				default_boot_order_list[i]);
+			str_free_list(default_boot_order_list);
+			return ret;
+		}
 		if (!env_get(boot_left)) {
 			log_debug("%s did not exist yet, setting default value\n",
 				  boot_left);
@@ -335,7 +350,11 @@ static const struct distro_rauc_slot *find_active_slot(struct distro_rauc_priv *
 		return ERR_PTR(log_msg_ret("env", -ENOENT));
 	boot_order_list = str_to_list(boot_order);
 	for (i = 0; boot_order_list[i] && !slot; i++) {
-		sprintf(boot_left, "BOOT_%s_LEFT", boot_order_list[i]);
+		ret = boot_left_name(boot_left, boot_order_list[i]);
+		if (ret) {
+			str_free_list(boot_order_list);
+			return ERR_PTR(ret);
+		}
 		tries = env_get_ulong(boot_left, 10, ULONG_MAX);
 		if (tries == ULONG_MAX) {
 			str_free_list(boot_order_list);
@@ -364,7 +383,11 @@ static const struct distro_rauc_slot *find_active_slot(struct distro_rauc_priv *
 			log_info("INFO: Resetting all slot tries to " __stringify(CONFIG_BOOTMETH_RAUC_DEFAULT_TRIES) "\n");
 			boot_order_list = str_to_list(CONFIG_BOOTMETH_RAUC_BOOT_ORDER);
 			for (i = 0; boot_order_list[i]; i++) {
-				sprintf(boot_left, "BOOT_%s_LEFT", boot_order_list[i]);
+				ret = boot_left_name(boot_left, boot_order_list[i]);
+				if (ret) {
+					str_free_list(boot_order_list);
+					return ERR_PTR(ret);
+				}
 				ret = env_set_ulong(boot_left, CONFIG_BOOTMETH_RAUC_DEFAULT_TRIES);
 				if (ret) {
 					str_free_list(boot_order_list);
@@ -453,8 +476,8 @@ static int distro_rauc_boot(struct udevice *dev, struct bootflow *bflow)
 	log_debug("BOOT_ORDER: %s\n", boot_order);
 	boot_order_list = str_to_list(boot_order);
 	for (i = 0; boot_order_list[i]; i++) {
-		sprintf(boot_left, "BOOT_%s_LEFT", boot_order_list[i]);
-		log_debug("%s: %s\n", boot_left, env_get(boot_left));
+		if (!boot_left_name(boot_left, boot_order_list[i]))
+			log_debug("%s: %s\n", boot_left, env_get(boot_left));
 	}
 	str_free_list(boot_order_list);
 
Signature · 1 line
2.56.0
#4 lore raw

PATCH v2 4/12 bootstd: rauc: Free the boot script of a failed boot attempt

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

The RAUC bootmeth loads the boot script when booting, not when reading the bootflow. If the boot fails, the bootflow keeps its private data and can be booted again, for example with another 'bootflow boot'. Each attempt then loads the script into a new buffer and adds another image to the bootflow, but the previous buffer, image list entry and subdir are never freed. 'bootstd images' lists one more copy of boot.scr after every attempt.

If the previous attempt found the script but failed to read it, the bootflow also stays in BOOTFLOWST_FILE. The next attempt then skips the search and reads the file name and size found on the previous slot from the partition of the new one.

Free what a previous attempt loaded and reset the state before loading the script again. Move the freeing of the image list from bootflow_free() into a new helper bootflow_free_images(), so that both can use it. Also check the strdup() of the subdir.

Fixes 7e5c2c782fb9 ("bootstd: Add implementation for bootmeth rauc")
Assisted-by LLM

---
Changes in v2:
- Reset the bootflow state before loading the script again (Simon)
- Move freeing the image list into bootflow_free_images() in bootflow.c, used by bootflow_free() as well (Simon)
- Update the commit message accordingly

---
 boot/bootflow.c      | 13 +++++++++----
 boot/bootmeth_rauc.c | 10 ++++++++++
 include/bootflow.h   | 10 ++++++++++
 3 files changed, 29 insertions(+), 4 deletions(-)
boot/bootflow.c +9 -4
index 7ee940460af..38747d35c29 100644
@@ -634,10 +634,17 @@ void bootflow_init(struct bootflow *bflow, struct udevice *bootdev,
 	alist_init_struct(&bflow->images, struct bootflow_img);
 }
 
-void bootflow_free(struct bootflow *bflow)
+void bootflow_free_images(struct bootflow *bflow)
 {
 	struct bootflow_img *img;
 
+	alist_for_each(img, &bflow->images)
+		free(img->fname);
+	alist_empty(&bflow->images);
+}
+
+void bootflow_free(struct bootflow *bflow)
+{
 	free(bflow->name);
 	free(bflow->subdir);
 	free(bflow->fname);
@@ -647,9 +654,7 @@ void bootflow_free(struct bootflow *bflow)
 	free(bflow->fdt_fname);
 	free(bflow->bootmeth_priv);
 
-	alist_for_each(img, &bflow->images)
-		free(img->fname);
-	alist_empty(&bflow->images);
+	bootflow_free_images(bflow);
 }
 
 void bootflow_remove(struct bootflow *bflow)
boot/bootmeth_rauc.c +10 -0
index 32e1de886cc..52d5be388cc 100644
@@ -309,6 +309,14 @@ static int distro_rauc_load_boot_script(struct bootflow *bflow,
 	if (!bflow->part)
 		return log_msg_ret("part", -ENOENT);
 
+	/* Drop the boot script of a previous, failed boot attempt */
+	free(bflow->buf);
+	bflow->buf = NULL;
+	free(bflow->subdir);
+	bflow->subdir = NULL;
+	bootflow_free_images(bflow);
+	bflow->state = BOOTFLOWST_READY;
+
 	ret = bootmeth_setup_fs(bflow, desc);
 	if (ret)
 		return log_msg_ret("set", ret);
@@ -320,6 +328,8 @@ static int distro_rauc_load_boot_script(struct bootflow *bflow,
 					  prefixes[i], script_names[j],
 					  bflow->dev->name, bflow->part);
 				bflow->subdir = strdup(prefixes[i]);
+				if (!bflow->subdir)
+					return log_msg_ret("buf", -ENOMEM);
 			}
 		}
 	}
include/bootflow.h +10 -0
index 1cfdda403ac..3df022f9aa3 100644
@@ -395,6 +395,16 @@ int bootflow_first_glob(struct bootflow **bflowp);
  */
 int bootflow_next_glob(struct bootflow **bflowp);
 
+/**
+ * bootflow_free_images() - Free the list of images of a bootflow
+ *
+ * This frees the file names of the images and empties the list. It does not
+ * free the image data itself.
+ *
+ * @bflow: Bootflow to update
+ */
+void bootflow_free_images(struct bootflow *bflow);
+
 /**
  * bootflow_free() - Free memory used by a bootflow
  *
Signature · 1 line
2.56.0
#5 lore raw

PATCH v2 5/12 test: boot: Restore the bootdev order if the RAUC test fails

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

bootflow_rauc() points std->bootdev_order at a static array and only restores the original order at its end. If an assertion fails, the test returns early with the static array still in place, and removing bootstd then hands it to free(). This trips the dlmalloc checks and aborts sandbox, so the failure of the flat-tree run is never reported and no further test runs.

Move the setup into bootflow_rauc_run(), which restores the order after running the checks, whether they pass or not.

Fixes 36add050eea4 ("test: boot: Add test for bootmeth_rauc")
Assisted-by LLM

---
Changes in v2:
- Add Reviewed-by tag from Simon

---
 test/boot/bootflow.c | 48 +++++++++++++++++++++++++++++++++++-------------
 1 file changed, 35 insertions(+), 13 deletions(-)
test/boot/bootflow.c +35 -13
index d478fd575be..d2d4edb0add 100644
@@ -1619,23 +1619,31 @@ static int bootflow_efi(struct unit_test_state *uts)
 }
 BOOTSTD_TEST(bootflow_efi, UTF_CONSOLE);
 
-/* Test RAUC bootmeth */
-static int bootflow_rauc(struct unit_test_state *uts)
+/**
+ * bootflow_rauc_run() - Run RAUC bootmeth checks on an mmc bootdev
+ *
+ * This binds @mmc_dev and the RAUC bootmeth and makes them the only bootdev
+ * and bootmeth used, then runs @check. The bootdev order is restored even if
+ * @check fails, since bootstd frees it when it is removed.
+ *
+ * @uts: Unit test state
+ * @mmc_dev: MMC device to use, e.g. "mmc10"
+ * @check: Checks to run with the RAUC bootmeth
+ * Returns 0 on success, -ve on failure
+ */
+static int bootflow_rauc_run(struct unit_test_state *uts, const char *mmc_dev,
+			     int (*check)(struct unit_test_state *uts))
 {
-	const char *mmc_dev = "mmc10";
+	static const char *order[] = {NULL, NULL};
 	struct bootstd_priv *std;
 	struct udevice *bootstd;
-	static const char *order[] = {NULL, NULL};
 	const char **old_order;
-	ulong mem_start;
 	ofnode root;
 	ofnode node;
+	int ret;
 
 	order[0] = mmc_dev;
 
-	if (!CONFIG_IS_ENABLED(BOOTMETH_RAUC))
-		return -EAGAIN;
-
 	/* Enable the requested mmc node since we need a different bootflow */
 	root = oftree_root(oftree_default());
 	node = ofnode_find_subnode(root, mmc_dev);
@@ -1646,13 +1654,21 @@ static int bootflow_rauc(struct unit_test_state *uts)
 	ut_assertok(uclass_first_device_err(UCLASS_BOOTSTD, &bootstd));
 	ut_assertok(device_bind(bootstd, DM_DRIVER_REF(bootmeth_rauc),
 				"rauc", 0, ofnode_null(), NULL));
+	ut_assertok(bootmeth_set_order("rauc"));
 
-	/* Change the device and bootmeth order */
+	/* Change the device order, and restore it also if a check fails */
 	std = dev_get_priv(bootstd);
 	old_order = std->bootdev_order;
 	std->bootdev_order = order;
+	ret = check(uts);
+	std->bootdev_order = old_order;
 
-	ut_assertok(bootmeth_set_order("rauc"));
+	return ret;
+}
+
+static int bootflow_rauc_check(struct unit_test_state *uts)
+{
+	ulong mem_start;
 
 	/* Run scan and list */
 	ut_assertok(run_command("bootflow scan", 0));
@@ -1705,11 +1721,17 @@ static int bootflow_rauc(struct unit_test_state *uts)
 
 	ut_assertok(env_set("BOOT_ORDER", "A B"));
 
-	/* Restore the order used by the device tree */
-	std->bootdev_order = old_order;
-
 	return 0;
 }
+
+/* Test RAUC bootmeth */
+static int bootflow_rauc(struct unit_test_state *uts)
+{
+	if (!CONFIG_IS_ENABLED(BOOTMETH_RAUC))
+		return -EAGAIN;
+
+	return bootflow_rauc_run(uts, "mmc10", bootflow_rauc_check);
+}
 BOOTSTD_TEST(bootflow_rauc, UTF_CONSOLE | UTF_DM | UTF_SCAN_FDT);
 
 /*
Signature · 1 line
2.56.0
#6 lore raw

PATCH v2 6/12 test: boot: Test booting a RAUC bootflow twice

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

Add a test that boots the same RAUC bootflow twice and checks that each attempt uses up a try and that the boot script is only listed once afterwards. Before the boot script of a failed attempt was freed, every attempt added another copy of it.

The boot script of the RAUC test image now runs a command set by the test, which lets it fail, as a successful boot script frees the private data of the bootflow, so it cannot be booted again.

Booting saves the environment, which sandbox keeps nowhere by default. Set CONFIG_ENV_FAT_DEVICE_AND_PART to the first partition of mmc10, which has a FAT filesystem, and select it during the test. No other test uses the FAT environment.

---
Changes in v2:
- New patch (Simon)

---
 configs/sandbox_defconfig |  1 +
 test/boot/bootflow.c      | 84 +++++++++++++++++++++++++++++++++++++++++++++++
 test/py/tests/test_ut.py  |  4 +--
 3 files changed, 87 insertions(+), 2 deletions(-)
configs/sandbox_defconfig +1 -0
index a3fa5246082..289fbcf2d34 100644
@@ -166,6 +166,7 @@ CONFIG_ENV_IS_IN_SPI_FLASH=y
 CONFIG_ENV_SECT_SIZE_AUTO=y
 CONFIG_ENV_REDUNDANT=y
 CONFIG_ENV_REDUNDANT_UPGRADE=y
+CONFIG_ENV_FAT_DEVICE_AND_PART="a:1"
 CONFIG_ENV_EXT4_INTERFACE="host"
 CONFIG_ENV_EXT4_DEVICE_AND_PART="0:0"
 CONFIG_ENV_IMPORT_FDT=y
test/boot/bootflow.c +84 -0

90 lines not on this page · raw message

test/py/tests/test_ut.py +2 -2
index a33f188d984..36d0f14973d 100644
@@ -590,8 +590,8 @@ def setup_rauc_image(ubman):
     boot = FsHelper(ubman.config, 'fat32', 8, 'rauc_boot')
     boot.setup()
 
-    # Generate boot script
-    script = '# dummy boot script'
+    # Generate boot script, which runs a command set by the test
+    script = 'run rauc_test_script'
     cmd_fname = os.path.join(boot.srcdir, 'boot.cmd')
     scr_fname = os.path.join(boot.srcdir, 'boot.scr')
     with open(cmd_fname, 'w', encoding='ascii') as outf:
Signature · 1 line
2.56.0
#7 lore raw

PATCH v2 7/12 bootstd: rauc: Only set the RAUC variables for a RAUC device

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

distro_rauc_read_bootflow() sets BOOT_ORDER and the BOOT_x_LEFT variables to their default values before it looks at the partitions of the device. Every MMC device that is scanned therefore adds them to the environment, also if it has no RAUC system on it, and the next saveenv stores them, for example when another bootmeth saves the environment.

Set the default values only once the partitions of the slots have been found on the device. Until then, use the default boot order if BOOT_ORDER is not set.

Assisted-by LLM

---
Changes in v2:
- New patch (Simon)

---
 boot/bootmeth_rauc.c | 57 +++++++++++++++++++++++++++++++++++-----------------
 1 file changed, 39 insertions(+), 18 deletions(-)
boot/bootmeth_rauc.c +39 -18
index 52d5be388cc..a32f19303a5 100644
@@ -121,7 +121,10 @@ static int distro_rauc_scan_parts(struct bootflow *bflow)
 	if (!priv || !priv->slots)
 		return log_msg_ret("priv", -EINVAL);
 
+	/* BOOT_ORDER is only set once a device has been found */
 	boot_order = env_get("BOOT_ORDER");
+	if (!boot_order)
+		boot_order = CONFIG_BOOTMETH_RAUC_BOOT_ORDER;
 	boot_order_list = str_to_list(boot_order);
 	for (i = 0; boot_order_list[i]; i++) {
 		const struct distro_rauc_slot *slot;
@@ -150,32 +153,27 @@ static int distro_rauc_scan_parts(struct bootflow *bflow)
 	return -1;
 }
 
-static int distro_rauc_read_bootflow(struct udevice *dev, struct bootflow *bflow)
+/**
+ * distro_rauc_set_defaults() - Set the RAUC variables that do not exist yet
+ *
+ * This sets BOOT_ORDER and the BOOT_x_LEFT variable of each slot to their
+ * default values, unless they exist already.
+ *
+ * Return: 0 if OK, -ve on error
+ */
+static int distro_rauc_set_defaults(void)
 {
-	struct distro_rauc_priv *priv = NULL;
-	int ret = 0;
-	char *slot;
-	int i;
-	char *partitions = NULL;
-	char *partitions_cursor;
-	char *boot_order = NULL;
-	const char *default_boot_order;
 	const char **default_boot_order_list;
-	char *boot_order_copy;
-	char *boot_order_cursor;
 	char boot_left[BOOT_LEFT_LEN];
-	char *parts;
+	int ret;
+	int i;
 
-	/* Get RAUC variables or set their default values */
-	boot_order = env_get("BOOT_ORDER");
-	if (!boot_order) {
+	if (!env_get("BOOT_ORDER")) {
 		log_debug("BOOT_ORDER did not exist yet, setting default value\n");
 		if (env_set("BOOT_ORDER", CONFIG_BOOTMETH_RAUC_BOOT_ORDER))
 			return log_msg_ret("env", -EPERM);
-		boot_order = CONFIG_BOOTMETH_RAUC_BOOT_ORDER;
 	}
-	default_boot_order = CONFIG_BOOTMETH_RAUC_BOOT_ORDER;
-	default_boot_order_list = str_to_list(default_boot_order);
+	default_boot_order_list = str_to_list(CONFIG_BOOTMETH_RAUC_BOOT_ORDER);
 	for (i = 0; default_boot_order_list[i]; i++) {
 		ret = boot_left_name(boot_left, default_boot_order_list[i]);
 		if (ret) {
@@ -195,6 +193,24 @@ static int distro_rauc_read_bootflow(struct udevice *dev, struct bootflow *bflow
 	}
 	str_free_list(default_boot_order_list);
 
+	return 0;
+}
+
+static int distro_rauc_read_bootflow(struct udevice *dev, struct bootflow *bflow)
+{
+	struct distro_rauc_priv *priv = NULL;
+	int ret = 0;
+	char *slot;
+	int i;
+	char *partitions = NULL;
+	char *partitions_cursor;
+	const char *default_boot_order;
+	char *boot_order_copy;
+	char *boot_order_cursor;
+	char *parts;
+
+	default_boot_order = CONFIG_BOOTMETH_RAUC_BOOT_ORDER;
+
 	priv = calloc(1, sizeof(struct distro_rauc_priv));
 	if (!priv)
 		return log_msg_ret("buf", -ENOMEM);
@@ -257,6 +273,11 @@ static int distro_rauc_read_bootflow(struct udevice *dev, struct bootflow *bflow
 	if (ret < 0)
 		goto rauc_read_bootflow_err;
 
+	/* Only touch the environment for a device with a RAUC system */
+	ret = distro_rauc_set_defaults();
+	if (ret)
+		goto rauc_read_bootflow_err;
+
 	bflow->state = BOOTFLOWST_READY;
 
 	free(boot_order_copy);
Signature · 1 line
2.56.0
#8 lore raw

PATCH v2 8/12 bootstd: rauc: Optionally find the partitions by name

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

The RAUC bootmeth uses any MMC device on which the boot partition of a slot holds a filesystem and the root partition exists. This also matches devices with a different layout, for example a single-system image or a standard distro installed to eMMC. The bootmeth then claims such a device and creates and saves its BOOT_ORDER and BOOT_x_LEFT variables in the environment, which makes it difficult to run BOOTMETH_RAUC alongside other bootmeths.

Allow to give the boot and root partitions in CONFIG_BOOTMETH_RAUC_PARTITIONS by their GPT names instead of their numbers, for example "boot_a,root_a boot_b,root_b". The bootmeth looks up the names on each device and only uses a device which has the partitions of all slots, so that it never boots a slot whose partitions are missing. As only GPT has partition names, this also rejects MBR devices. A value consisting only of digits is still taken as a partition number, which keeps the current behaviour.

The bootmeth keeps the partitions in its platform data, which is set from the option when the bootmeth is bound. This allows tests to check other layouts at runtime. Also report a slot without a boot or root partition in the option, instead of passing NULL to simple_strtoul().

Assisted-by LLM

---
Changes in v2:
- Give the partition names in CONFIG_BOOTMETH_RAUC_PARTITIONS instead of the new option CONFIG_BOOTMETH_RAUC_PART_NAMES (Bastien)
- Only use a device which has the partitions of all slots (Simon)
- Keep the partitions in the platform data of the bootmeth, so that tests can change them at runtime (Simon)
- Report a slot without a boot or root partition in the option
- Rename from "bootstd: rauc: Optionally check the partition names"

---
 MAINTAINERS                  |   1 +
 boot/Kconfig                 |   7 +++
 boot/bootmeth_rauc.c         | 108 +++++++++++++++++++++++++++++++++++++++----
 doc/develop/bootstd/rauc.rst |   7 +++
 include/bootmeth_rauc.h      |  22 +++++++++
 5 files changed, 136 insertions(+), 9 deletions(-)
MAINTAINERS +1 -0
index af3ca0f1bf2..63bed54e8bf 100644
@@ -846,6 +846,7 @@ F:	drivers/mmc/mmc_bootdev.c
 F:	include/bootdev.h
 F:	include/bootflow.h
 F:	include/bootmeth.h
+F:	include/bootmeth_rauc.h
 F:	include/bootstd.h
 F:	test/boot/
 
boot/Kconfig +7 -0
index d4d2a77f15a..072108db64a 100644
@@ -969,6 +969,13 @@ config BOOTMETH_RAUC_PARTITIONS
 	  The first value in pair is for the boot partition and second for the
 	  root partition.
 
+	  Instead of an index, a value can also be the name of a GPT partition,
+	  for example "boot_a,root_a boot_b,root_b". A device is then only used
+	  if it has partitions with these names for all slots, so the bootmeth
+	  does not claim devices with a different layout. As only GPT has
+	  partition names, this also rejects MBR devices. A value consisting
+	  only of digits is always taken as an index.
+
 config BOOTMETH_RAUC_DEFAULT_TRIES
 	int "RAUC slot default tries"
 	default 3
boot/bootmeth_rauc.c +99 -9

181 lines not on this page · raw message

doc/develop/bootstd/rauc.rst +7 -0
index 5afd705dcb1..eee8d103fb9 100644
@@ -14,6 +14,13 @@ filesystem each. The partition numbers must be specified with
 the following syntax: ``1,2 3,4``, where 1 and 3 are the slots' boot partition
 and 2 and 4 the slots' root partition.
 
+Instead of their numbers, the partitions can also be given by their GPT
+partition names, for example ``boot_a,root_a boot_b,root_b``. The bootmeth then
+only uses a device if it has partitions with these names for all slots. This
+prevents it from claiming devices with a different layout which happen to have
+a filesystem in the first partition. A value consisting only of digits is
+always taken as a partition number.
+
 Each pair of boot and rootfs partition form a "slot". The default order in which
 available slots are tried is set through ``CONFIG_BOOTMETH_RAUC_BOOT_ORDER``,
 with the left one tried first.
include/bootmeth_rauc.h new file +22 -0
new file mode 100644
index 00000000000..0faeab192d4
@@ -0,0 +1,22 @@
+/* SPDX-License-Identifier: GPL-2.0+ */
+/*
+ * Bootmethod for distro boot with RAUC
+ */
+
+#ifndef __BOOTMETH_RAUC_H
+#define __BOOTMETH_RAUC_H
+
+/**
+ * struct distro_rauc_plat - Platform data of the RAUC bootmeth
+ *
+ * This is set from Kconfig when the bootmeth is bound. Tests can change it
+ * afterwards to check other configurations.
+ *
+ * @partitions: Boot and root partitions of each slot, given by number or
+ *	by name, see CONFIG_BOOTMETH_RAUC_PARTITIONS
+ */
+struct distro_rauc_plat {
+	const char *partitions;
+};
+
+#endif
Signature · 1 line
2.56.0
#9 lore raw

PATCH v2 9/12 bootstd: rauc: Optionally boot with a built-in command

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

The RAUC bootmeth boots a slot by running boot.scr or boot.scr.uimg from its boot partition. Nothing authenticates this partition, so with verified boot, whoever can write it can run any U-Boot command, for example booting an unsigned kernel or changing the kernel command line. Signing the script does not close this reliably as source skips all checks if the environment sets verify=no, which RAUC systems must keep writable for BOOT_ORDER and BOOT_x_LEFT, and it accepts a FIT script without configurations, whose signature is then only checked against keys required for images, not configurations.

Add CONFIG_BOOTMETH_RAUC_BOOTCMD to set a command built into U-Boot that boots the slot instead. It sees the same environment variables as the boot script. The boot partition then contains nothing that U-Boot executes.

The option is empty by default, which keeps loading the boot script. As for the partitions, the bootmeth keeps the command in its platform data, so that tests can set it at runtime.

Assisted-by LLM

---
Changes in v2:
- Keep the command in the platform data of the bootmeth, so that tests can change it at runtime, and always build the boot script code (Simon)

---
 boot/Kconfig                 | 16 ++++++++++++++++
 boot/bootmeth_rauc.c         | 23 ++++++++++++++++-------
 doc/develop/bootstd/rauc.rst |  8 ++++++++
 include/bootmeth_rauc.h      |  3 +++
 4 files changed, 43 insertions(+), 7 deletions(-)
boot/Kconfig +16 -0
index 072108db64a..27640817068 100644
@@ -976,6 +976,22 @@ config BOOTMETH_RAUC_PARTITIONS
 	  partition names, this also rejects MBR devices. A value consisting
 	  only of digits is always taken as an index.
 
+config BOOTMETH_RAUC_BOOTCMD
+	string "RAUC built-in boot command"
+	default ""
+	help
+	  Sets a command to boot the selected slot, for example
+	  "run distro_boot_rauc". It is run instead of loading a boot script
+	  from the slot's boot partition, and can use the same environment
+	  variables as the boot script, such as distro_bootpart and raucargs.
+
+	  As the command is built into U-Boot, the boot partition does not
+	  need to contain anything U-Boot executes, which helps with verified
+	  boot. If the command runs an environment variable, that variable must
+	  not be writable at runtime then, see ENV_WRITEABLE_LIST.
+
+	  Leave this empty to load the boot script.
+
 config BOOTMETH_RAUC_DEFAULT_TRIES
 	int "RAUC slot default tries"
 	default 3
boot/bootmeth_rauc.c +16 -7
index acf9413591b..4f4927d5cd1 100644
@@ -527,6 +527,7 @@ static const struct distro_rauc_slot *find_active_slot(struct distro_rauc_priv *
 
 static int distro_rauc_boot(struct udevice *dev, struct bootflow *bflow)
 {
+	const struct distro_rauc_plat *rplat = dev_get_plat(dev);
 	struct blk_desc *desc;
 	struct distro_rauc_priv *priv;
 	const struct distro_rauc_slot *slot;
@@ -575,10 +576,12 @@ static int distro_rauc_boot(struct udevice *dev, struct bootflow *bflow)
 	if (ret)
 		return log_msg_ret("env", ret);
 
-	/* Load distro boot script */
-	ret = distro_rauc_load_boot_script(bflow, slot);
-	if (ret)
-		return log_msg_ret("load", ret);
+	/* Load distro boot script, unless a built-in command boots the slot */
+	if (!*rplat->bootcmd) {
+		ret = distro_rauc_load_boot_script(bflow, slot);
+		if (ret)
+			return log_msg_ret("load", ret);
+	}
 
 	log_info("INFO: Booting slot %s, %lu of %d tries left\n",
 		 slot->name, active_slot_tries, CONFIG_BOOTMETH_RAUC_DEFAULT_TRIES);
@@ -599,9 +602,14 @@ static int distro_rauc_boot(struct udevice *dev, struct bootflow *bflow)
 	}
 	str_free_list(boot_order_list);
 
-	/* Run distro boot script */
-	addr = map_to_sysmem(bflow->buf);
-	ret = cmd_source_script(addr, NULL, NULL);
+	if (*rplat->bootcmd) {
+		/* Run built-in boot command */
+		ret = run_command(rplat->bootcmd, 0);
+	} else {
+		/* Run distro boot script */
+		addr = map_to_sysmem(bflow->buf);
+		ret = cmd_source_script(addr, NULL, NULL);
+	}
 	if (ret)
 		return log_msg_ret("boot", ret);
 
@@ -619,6 +627,7 @@ static int distro_rauc_bootmeth_bind(struct udevice *dev)
 	plat->desc = "RAUC distro boot from MMC";
 	plat->flags = BOOTMETHF_ANY_PART;
 	rplat->partitions = CONFIG_BOOTMETH_RAUC_PARTITIONS;
+	rplat->bootcmd = CONFIG_BOOTMETH_RAUC_BOOTCMD;
 
 	return 0;
 }
doc/develop/bootstd/rauc.rst +8 -0
index eee8d103fb9..247ae474f0f 100644
@@ -44,6 +44,13 @@ The boot script must be located in each boot partition. The bootmeth searches
 for ``boot.scr`` first, then ``boot.scr.uimg`` if not found. It will search in
 all directories of the bootstd list of prefixes (``"/", "/boot"`` by default).
 
+Alternatively, ``CONFIG_BOOTMETH_RAUC_BOOTCMD`` sets a command built into
+U-Boot, for example ``run distro_boot_rauc``, which boots the slot instead of a
+boot script. The boot partitions then need no boot script, and the bootmeth
+executes nothing from them. For verified boot, the command must load only
+signed images, and any environment variable it runs must not be writable at
+runtime (see ``CONFIG_ENV_WRITEABLE_LIST``).
+
 When the bootflow is booted, the bootmeth sets these environment variables:
 
 devtype
@@ -63,6 +70,7 @@ raucargs
     kernel command line arguments needed for RAUC to detect the currently booted
     slot
 
+The boot script or the boot command can use these variables to boot the slot.
 The script file must be a FIT or a legacy uImage. It is loaded into memory and
 executed.
 
include/bootmeth_rauc.h +3 -0
index 0faeab192d4..88b17f10235 100644
@@ -14,9 +14,12 @@
  *
  * @partitions: Boot and root partitions of each slot, given by number or
  *	by name, see CONFIG_BOOTMETH_RAUC_PARTITIONS
+ * @bootcmd: Command to boot the selected slot, see
+ *	CONFIG_BOOTMETH_RAUC_BOOTCMD. Empty to run the boot script instead
  */
 struct distro_rauc_plat {
 	const char *partitions;
+	const char *bootcmd;
 };
 
 #endif
Signature · 1 line
2.56.0
#10 lore raw

PATCH v2 10/12 test: fs_helper: Support GPT in DiskHelper

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

DiskHelper can only create disk images with an MBR partition table, so tests that need partition names cannot use it.

Add a gpt option to create a GPT partition table instead, and a name argument to add_fs() to name a partition. With GPT, the 'bootable' flag is set as the LegacyBIOSBootable attribute, which U-Boot reads as bootable, and 1MB is reserved at the end of the disk for the backup GPT.

---
Changes in v2:
- Add Reviewed-by tag from Simon

---
 test/py/tests/fs_helper.py | 36 +++++++++++++++++++++++++++---------
 1 file changed, 27 insertions(+), 9 deletions(-)
test/py/tests/fs_helper.py +27 -9
index e3824b2c1fd..d6e0f5e65d7 100644
@@ -124,7 +124,13 @@ class DiskHelper:
     VFAT  = 0xc
     EXT4  = 0x83
 
-    def __init__(self, config, devnum, prefix, cur_dir=False):
+    # GPT partition-type GUIDs for the above codes
+    GPT_TYPES = {
+        VFAT: 'EBD0A0A2-B9E5-4433-87C0-68B6B72699C7',
+        EXT4: '0FC63DAF-8483-4772-8E79-3D69D8477DE4',
+    }
+
+    def __init__(self, config, devnum, prefix, cur_dir=False, gpt=False):
         """Set up a new disk image
 
         Args:
@@ -133,37 +139,49 @@ class DiskHelper:
             prefix (str): Prefix string of volume's file name
             cur_dir (bool): True to put the file in the current directory,
                 instead of the persistent-data directory
+            gpt (bool): True to use a GPT partition table, instead of MBR
         """
         self.fs_list = []
+        self.gpt = gpt
         self.fname = os.path.join('' if cur_dir else config.persistent_data_dir,
                                   f'{prefix}{devnum}.img')
 
-    def add_fs(self, fs_img, part_type, bootable=False):
+    def add_fs(self, fs_img, part_type, bootable=False, name=None):
         """Add a new filesystem
 
         Args:
             fs_img (FsHelper): Filesystem to add
             part_type (DiskHelper.FAT or DiskHelper.EXT4): Partition type
             bootable (bool): True to set the 'bootable' flat
+            name (str): Partition name, only supported with GPT
         """
-        self.fs_list.append([fs_img, part_type, bootable])
+        if name and not self.gpt:
+            raise ValueError('Partition names need a GPT partition table')
+        self.fs_list.append([fs_img, part_type, bootable, name])
 
     def create(self):
         """Create the disk image
 
         Create an image with a partition table and the filesystems
         """
-        spec = ''
+        spec = 'label: gpt' if self.gpt else ''
         pos = 1   # Reserve 1MB for the partition table itself
-        for fsi, part_type, bootable in self.fs_list:
+        for fsi, part_type, bootable, name in self.fs_list:
             if spec:
                 spec += '\n'
-            spec += f'type={part_type:x}, size={fsi.size_mb}M, start={pos}M'
+            if self.gpt:
+                spec += f'type={self.GPT_TYPES[part_type]}'
+            else:
+                spec += f'type={part_type:x}'
+            spec += f', size={fsi.size_mb}M, start={pos}M'
             if bootable:
-                spec += ', bootable'
+                spec += ', attrs=LegacyBIOSBootable' if self.gpt else ', bootable'
+            if name:
+                spec += f', name={name}'
             pos += fsi.size_mb
 
-        img_size = pos
+        # Reserve 1MB at the end for the backup GPT
+        img_size = pos + 1 if self.gpt else pos
         try:
             check_call(f'qemu-img create {self.fname} {img_size}M', shell=True)
             check_call(f'printf "{spec}" | sfdisk {self.fname}', shell=True)
@@ -172,7 +190,7 @@ class DiskHelper:
             raise
 
         pos = 1   # Reserve 1MB for the partition table itself
-        for fsi, part_type, bootable in self.fs_list:
+        for fsi, _, _, _ in self.fs_list:
             check_call(
                 f'dd if={fsi.fs_img} of={self.fname} bs=1M seek={pos} conv=notrunc',
                 shell=True)
Signature · 1 line
2.56.0
#11 lore raw

PATCH v2 11/12 test: boot: Test finding the RAUC partitions by name

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

Add a second RAUC test image (mmc13) with a GPT and named partitions, and tests that give the partitions by name in the platform data of the RAUC bootmeth. The bootmeth must find a bootflow on mmc13 if the partitions of all slots exist, and none if those of one or all slots are missing. On the RAUC test image mmc10, which stays on MBR and has no partition names, it must find a bootflow by the partition numbers, but none by the names. If it finds no bootflow, the RAUC variables must not be set in the environment.

The RAUC tests now reset the options of the bootmeth to their default values before each check, so that they don't depend on the Kconfig values of the build.

Assisted-by LLM

---
Changes in v2:
- Set the partitions in the platform data of the bootmeth instead of CONFIG_BOOTMETH_RAUC_PART_NAMES in sandbox_defconfig, and drop the #ifdef (Simon)
- Keep mmc10 on MBR and use mmc13 with GPT partition names
- Also check matching names, a slot with missing partitions and finding mmc10 by partition numbers (Simon)
- Check that the RAUC variables are not set for an unused device (Simon)
- Move the tests next to bootflow_rauc() (Simon)
- Rename from "test: boot: Test the RAUC partition name check"

---
 arch/sandbox/dts/test.dts |   8 ++++
 test/boot/bootflow.c      | 118 +++++++++++++++++++++++++++++++++++++++++++---
 test/py/tests/test_ut.py  |  26 ++++++----
 3 files changed, 137 insertions(+), 15 deletions(-)
arch/sandbox/dts/test.dts +8 -0
index 02a9ca29b79..895ecb97e87 100644
@@ -51,6 +51,7 @@
 		mmc10 = "/mmc10";
 		mmc11 = "/mmc11";
 		mmc12 = "/mmc12";
+		mmc13 = "/mmc13";
 		pci0 = &pci0;
 		pci1 = &pci1;
 		pci2 = &pci2;
@@ -1406,6 +1407,13 @@
 		filename = "mmc12.img";
 	};
 
+	/* This is used for RAUC boot tests with GPT partition names */
+	mmc13 {
+		status = "disabled";
+		compatible = "sandbox,mmc";
+		filename = "mmc13.img";
+	};
+
 	pch {
 		compatible = "sandbox,pch";
 	};
test/boot/bootflow.c +112 -6

175 lines not on this page · raw message

test/py/tests/test_ut.py +17 -9
index 36d0f14973d..51eca5cf98b 100644
@@ -583,10 +583,15 @@ def setup_efi_image(ubman):
     fsh.cleanup()
 
 
-def setup_rauc_image(ubman):
-    """Create a 40MB disk image with an A/B RAUC system on it"""
-    mmc_dev = 10
+def setup_rauc_image(ubman, mmc_dev, part_names=None):
+    """Create a disk image with an A/B RAUC system on it
 
+    Args:
+        ubman (ConsoleBase): Console to use
+        mmc_dev (int): MMC device number, e.g. 10
+        part_names (tuple of str): GPT names of the boot A, root A, boot B
+            and root B partitions, or None to use MBR
+    """
     boot = FsHelper(ubman.config, 'fat32', 8, 'rauc_boot')
     boot.setup()
 
@@ -606,11 +611,13 @@ def setup_rauc_image(ubman):
     root = FsHelper(ubman.config, 'ext4', 10, 'rauc_root')
     root.mk_fs()
 
-    img = DiskHelper(ubman.config, mmc_dev, 'mmc', True)
-    img.add_fs(boot, DiskHelper.VFAT, bootable=True)
-    img.add_fs(root, DiskHelper.EXT4)
-    img.add_fs(boot, DiskHelper.VFAT, bootable=True)
-    img.add_fs(root, DiskHelper.EXT4)
+    boot_a, root_a, boot_b, root_b = part_names or (None,) * 4
+    img = DiskHelper(ubman.config, mmc_dev, 'mmc', True,
+                     gpt=part_names is not None)
+    img.add_fs(boot, DiskHelper.VFAT, bootable=True, name=boot_a)
+    img.add_fs(root, DiskHelper.EXT4, name=root_a)
+    img.add_fs(boot, DiskHelper.VFAT, bootable=True, name=boot_b)
+    img.add_fs(root, DiskHelper.EXT4, name=root_b)
     img.create()
     boot.cleanup()
     root.cleanup()
@@ -626,7 +633,8 @@ def test_ut_dm_init_bootstd(ubman):
     setup_cros_image(ubman)
     setup_android_image(ubman)
     setup_efi_image(ubman)
-    setup_rauc_image(ubman)
+    setup_rauc_image(ubman, 10)
+    setup_rauc_image(ubman, 13, ('boot_a', 'root_a', 'boot_b', 'root_b'))
     setup_bls_prefix_image(ubman)
 
     # Restart so that the new mmc1.img is picked up
Signature · 1 line
2.56.0
#12 lore raw

PATCH v2 12/12 test: boot: Test the RAUC built-in boot command

In reply to Frieder Schrempf

From: Frieder Schrempf <[email protected]>

Add a test that sets a built-in boot command in the platform data of the RAUC bootmeth, which runs a test variable, and boots the RAUC bootflow on mmc10 with it. It checks that the command sees the slot's partitions and raucargs, that the boot script is not loaded, that slot B is booted once slot A has no tries left, and that a failing command uses up a try.

Assisted-by LLM

---
Changes in v2:
- Set the command in the platform data of the bootmeth instead of in sandbox_defconfig, and drop the #ifdef (Simon)
- Move CONFIG_ENV_FAT_DEVICE_AND_PART and the environment handling to patch 6
- Also check that the boot script is not loaded

---
 test/boot/bootflow.c | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 61 insertions(+)
test/boot/bootflow.c +61 -0
index 0c22ad58521..2278453ca4d 100644
@@ -1664,6 +1664,7 @@ static int bootflow_rauc_run(struct unit_test_state *uts, const char *mmc_dev,
 	ut_assertok(bootmeth_set_order("rauc"));
 	rplat = dev_get_plat(dev);
 	rplat->partitions = "1,2 3,4";
+	rplat->bootcmd = "";
 
 	/* Change the device order, and restore it also if a check fails */
 	std = dev_get_priv(bootstd);
@@ -1924,6 +1925,66 @@ static int bootflow_rauc_part_names_mbr(struct unit_test_state *uts)
 }
 BOOTSTD_TEST(bootflow_rauc_part_names_mbr, UTF_CONSOLE | UTF_DM | UTF_SCAN_FDT);
 
+/* Scan and boot the RAUC bootflow, as a successful boot command frees it */
+static int bootflow_rauc_scan_boot(struct unit_test_state *uts)
+{
+	ut_assertok(run_command("bootflow scan", 0));
+	ut_assertok(run_command("bootflow select 0", 0));
+
+	return bootflow_rauc_boot(uts);
+}
+
+static int bootflow_rauc_bootcmd_check(struct unit_test_state *uts,
+				       struct distro_rauc_plat *rplat)
+{
+	/* Start with the default tries, also when running a second time */
+	ut_assertok(env_set("BOOT_A_LEFT", NULL));
+	ut_assertok(env_set("BOOT_B_LEFT", NULL));
+	ut_assertok(env_set("rauc_test_boot",
+			    "echo rauc boot: ${raucargs} ${distro_bootpart} ${distro_rootpart}"));
+	rplat->bootcmd = "run rauc_test_boot";
+
+	/* The command returns instead of booting, so the boot fails */
+	ut_assertok(bootflow_rauc_scan_boot(uts));
+	ut_assert_skip_to_line("rauc boot: rauc.slot=A 1 2");
+	ut_assert_nextline("Boot failed (err=-14)");
+	ut_assert_console_end();
+	ut_asserteq_str("2", env_get("BOOT_A_LEFT"));
+
+	/* The boot script is not loaded */
+	ut_assertok(run_command("bootstd images", 0));
+	ut_assert_skip_to_line("(0 images)");
+	ut_assert_console_end();
+
+	/* Slot B is booted once slot A has no tries left */
+	ut_assertok(env_set("BOOT_A_LEFT", "0"));
+	ut_assertok(bootflow_rauc_scan_boot(uts));
+	ut_assert_skip_to_line("rauc boot: rauc.slot=B 3 4");
+	ut_assert_nextline("Boot failed (err=-14)");
+	ut_assert_console_end();
+	ut_asserteq_str("2", env_get("BOOT_B_LEFT"));
+
+	/* A failing command uses up a try as well */
+	ut_assertok(env_set("rauc_test_boot", "false"));
+	ut_assertok(bootflow_rauc_scan_boot(uts));
+	ut_assert_skip_to_line("Boot failed (err=1)");
+	ut_assert_console_end();
+	ut_asserteq_str("1", env_get("BOOT_B_LEFT"));
+
+	ut_assertok(env_set("BOOT_A_LEFT", NULL));
+	ut_assertok(env_set("BOOT_B_LEFT", NULL));
+	ut_assertok(env_set("rauc_test_boot", NULL));
+
+	return 0;
+}
+
+/* Test booting a slot with the built-in boot command of the RAUC bootmeth */
+static int bootflow_rauc_bootcmd(struct unit_test_state *uts)
+{
+	return bootflow_rauc_run_env_fat(uts, bootflow_rauc_bootcmd_check);
+}
+BOOTSTD_TEST(bootflow_rauc_bootcmd, UTF_CONSOLE | UTF_DM | UTF_SCAN_FDT);
+
 /*
  * Test the BLS bootmeth against entries that live below a '/boot/' prefix,
  * so that they are only found via the second bootstd prefix. The Fedora
Signature · 1 line
2.56.0
#13 lore raw
In reply to Frieder Schrempf

Hi Tom,

Quoted 76 lines · Frieder Schrempf

This series fixes some issues in the RAUC bootmeth and adds two options to make it safer to use on real devices, together with tests.

Patches 1-4 fix bugs in bootmeth_rauc.c: an uninitialised pointer when a bootflow has no block device, a leak of the active slot name, a stack buffer overflow with long slot names in BOOT_ORDER, and a leak of the boot script when a boot attempt fails and is retried.

Patch 5 makes the RAUC test restore the bootdev order also if it fails. Before, a failing check left a static array in std->bootdev_order, which was then passed to free() and aborted sandbox. Patch 6 adds a test that boots the same RAUC bootflow twice.

Patch 7 makes the bootmeth set its BOOT_ORDER and BOOT_x_LEFT variables only for a device with a RAUC system, instead of for every MMC device it scans.

Patches 8 and 9 make the bootmeth safer to use on real devices, without changing anything for existing users:

- CONFIG_BOOTMETH_RAUC_PARTITIONS can give the partitions by their GPT names instead of their numbers. The bootmeth then only claims a device which has the partitions of all slots. With numbers, it claims any MMC device whose partitions happen to fit the configured layout, such as a standard distro installed to eMMC, and writes its variables to the environment. This allows to use BOOTMETH_RAUC safely alongside other bootmeths.

- The new option CONFIG_BOOTMETH_RAUC_BOOTCMD, empty by default, sets a command built into U-Boot that boots the slot instead of running boot.scr from the boot partition.
Nothing authenticates that partition, and signing the script is not a reliable fix, as the environment must stay writable for the RAUC variables and setting verify=no there skips all checks. With this option, U-Boot executes nothing from the boot partition.

The bootmeth keeps both options in its platform data, which is set from Kconfig when it is bound. The tests in patches 11 and 12 change them at runtime, so sandbox_defconfig keeps the default configuration and all tests run on it. As partition names need GPT, patch 10 adds GPT support to DiskHelper in fs_helper.py for a second RAUC test image.

---
Changes in v2:
- Patches 1, 5 and 10: Add Reviewed-by tag from Simon.
- Patch 2: Look up the slot in find_active_slot() and return it instead of a strdup() copy of its name (Simon). This also catches an unknown slot in BOOT_ORDER before its BOOT_x_LEFT counter is decremented.
- Patch 3: Print an error for a too long slot name in CONFIG_BOOTMETH_RAUC_BOOT_ORDER, document the 32-character limit and pass on the return value of boot_left_name() (Simon). Rebase on the changes in patch 2.
- Patch 4: Reset the bootflow state before loading the script again and move freeing the image list into bootflow_free_images() in bootflow.c, used by bootflow_free() as well (Simon).
- New patch 6: Test booting the same bootflow twice (Simon).
- New patch 7: Set BOOT_ORDER and BOOT_x_LEFT only for a device with a RAUC system (Simon).
- Patch 8: Give the partition names in CONFIG_BOOTMETH_RAUC_PARTITIONS instead of the new option CONFIG_BOOTMETH_RAUC_PART_NAMES (Bastien), and only use a device which has the partitions of all slots (Simon). Renamed from "Optionally check the partition names".
- Patches 8 and 9: Keep the options in the platform data of the bootmeth, set from Kconfig when it is bound, so that tests can change them at runtime. The boot script code is now always built (Simon).
- Patches 11 and 12: Set the options in the tests instead of sandbox_defconfig, so that the default configuration is still tested, and drop the #ifdefs. Keep the RAUC test image (mmc10) on MBR with a boot script and use a second GPT image (mmc13) for partition names. Also check matching names, a slot with missing partitions, that MBR is rejected and that no variables are set for an unused device (Simon). Patch 11 is renamed from "Test the RAUC partition name check".
- Link to v1: https://patch.msgid.link/[email protected]

Quoted 14 lines

---
Frieder Schrempf (12):
bootstd: rauc: Initialise desc in distro_rauc_scan_parts()
bootstd: rauc: Fix leak of the active slot name
bootstd: rauc: Fix overflow of the BOOT_x_LEFT name buffer
bootstd: rauc: Free the boot script of a failed boot attempt
test: boot: Restore the bootdev order if the RAUC test fails
test: boot: Test booting a RAUC bootflow twice
bootstd: rauc: Only set the RAUC variables for a RAUC device
bootstd: rauc: Optionally find the partitions by name
bootstd: rauc: Optionally boot with a built-in command
test: fs_helper: Support GPT in DiskHelper
test: boot: Test finding the RAUC partitions by name
test: boot: Test the RAUC built-in boot command

With the bootstd subsystem being orphaned now, is there any chance to get at least the fixes (patch 1-5) upstream?

Thanks
Frieder

#14 lore raw
Quoted 94 lines · Frieder Schrempf

Hi Tom,

Quoted 76 lines · Frieder Schrempf

This series fixes some issues in the RAUC bootmeth and adds two options to make it safer to use on real devices, together with tests.

Patches 1-4 fix bugs in bootmeth_rauc.c: an uninitialised pointer when a bootflow has no block device, a leak of the active slot name, a stack buffer overflow with long slot names in BOOT_ORDER, and a leak of the boot script when a boot attempt fails and is retried.

Patch 5 makes the RAUC test restore the bootdev order also if it fails. Before, a failing check left a static array in std->bootdev_order, which was then passed to free() and aborted sandbox. Patch 6 adds a test that boots the same RAUC bootflow twice.

Patch 7 makes the bootmeth set its BOOT_ORDER and BOOT_x_LEFT variables only for a device with a RAUC system, instead of for every MMC device it scans.

Patches 8 and 9 make the bootmeth safer to use on real devices, without changing anything for existing users:

- CONFIG_BOOTMETH_RAUC_PARTITIONS can give the partitions by their GPT names instead of their numbers. The bootmeth then only claims a device which has the partitions of all slots. With numbers, it claims any MMC device whose partitions happen to fit the configured layout, such as a standard distro installed to eMMC, and writes its variables to the environment. This allows to use BOOTMETH_RAUC safely alongside other bootmeths.

- The new option CONFIG_BOOTMETH_RAUC_BOOTCMD, empty by default, sets a command built into U-Boot that boots the slot instead of running boot.scr from the boot partition.
Nothing authenticates that partition, and signing the script is not a reliable fix, as the environment must stay writable for the RAUC variables and setting verify=no there skips all checks. With this option, U-Boot executes nothing from the boot partition.

The bootmeth keeps both options in its platform data, which is set from Kconfig when it is bound. The tests in patches 11 and 12 change them at runtime, so sandbox_defconfig keeps the default configuration and all tests run on it. As partition names need GPT, patch 10 adds GPT support to DiskHelper in fs_helper.py for a second RAUC test image.

---
Changes in v2:
- Patches 1, 5 and 10: Add Reviewed-by tag from Simon.
- Patch 2: Look up the slot in find_active_slot() and return it instead of a strdup() copy of its name (Simon). This also catches an unknown slot in BOOT_ORDER before its BOOT_x_LEFT counter is decremented.
- Patch 3: Print an error for a too long slot name in CONFIG_BOOTMETH_RAUC_BOOT_ORDER, document the 32-character limit and pass on the return value of boot_left_name() (Simon). Rebase on the changes in patch 2.
- Patch 4: Reset the bootflow state before loading the script again and move freeing the image list into bootflow_free_images() in bootflow.c, used by bootflow_free() as well (Simon).
- New patch 6: Test booting the same bootflow twice (Simon).
- New patch 7: Set BOOT_ORDER and BOOT_x_LEFT only for a device with a RAUC system (Simon).
- Patch 8: Give the partition names in CONFIG_BOOTMETH_RAUC_PARTITIONS instead of the new option CONFIG_BOOTMETH_RAUC_PART_NAMES (Bastien), and only use a device which has the partitions of all slots (Simon). Renamed from "Optionally check the partition names".
- Patches 8 and 9: Keep the options in the platform data of the bootmeth, set from Kconfig when it is bound, so that tests can change them at runtime. The boot script code is now always built (Simon).
- Patches 11 and 12: Set the options in the tests instead of sandbox_defconfig, so that the default configuration is still tested, and drop the #ifdefs. Keep the RAUC test image (mmc10) on MBR with a boot script and use a second GPT image (mmc13) for partition names. Also check matching names, a slot with missing partitions, that MBR is rejected and that no variables are set for an unused device (Simon). Patch 11 is renamed from "Test the RAUC partition name check".
- Link to v1: https://patch.msgid.link/[email protected]

Quoted 14 lines

---
Frieder Schrempf (12):
bootstd: rauc: Initialise desc in distro_rauc_scan_parts()
bootstd: rauc: Fix leak of the active slot name
bootstd: rauc: Fix overflow of the BOOT_x_LEFT name buffer
bootstd: rauc: Free the boot script of a failed boot attempt
test: boot: Restore the bootdev order if the RAUC test fails
test: boot: Test booting a RAUC bootflow twice
bootstd: rauc: Only set the RAUC variables for a RAUC device
bootstd: rauc: Optionally find the partitions by name
bootstd: rauc: Optionally boot with a built-in command
test: fs_helper: Support GPT in DiskHelper
test: boot: Test finding the RAUC partitions by name
test: boot: Test the RAUC built-in boot command

Quoted 2 lines

With the bootstd subsystem being orphaned now, is there any chance to get at least the fixes (patch 1-5) upstream?

I'll pick this series up shortly. And figuring out what we're going to do with bootstd moving forward is on the list of things that need doing.

Signature · 1 line
Tom
#15 lore raw
In reply to Frieder Schrempf
Quoted 9 lines · Frieder Schrempf

This series fixes some issues in the RAUC bootmeth and adds two options to make it safer to use on real devices, together with tests.

Patches 1-4 fix bugs in bootmeth_rauc.c: an uninitialised pointer when a bootflow has no block device, a leak of the active slot name, a stack buffer overflow with long slot names in BOOT_ORDER, and a leak of the boot script when a boot attempt fails and is retried.

[...]

Applied to u-boot/main, thanks!

[01/12] bootstd: rauc: Initialise desc in distro_rauc_scan_parts()

        commit: ba04ce9bf8917fc445011af06bc52a19480f6ffe
[02/12] bootstd: rauc: Fix leak of the active slot name
        commit: c41bafb348c31025b13d545d9c8cb884565644ed
[03/12] bootstd: rauc: Fix overflow of the BOOT_x_LEFT name buffer
        commit: ffc23ed61795699070bdd5d0b401b1b390ae192d
[04/12] bootstd: rauc: Free the boot script of a failed boot attempt
        commit: 20b5083334c6e5c6c617cb4fce34c6c4e8e18ac4
[05/12] test: boot: Restore the bootdev order if the RAUC test fails
        commit: 046d25230db117bd037035aa4ec00c62ab8abdae
[06/12] test: boot: Test booting a RAUC bootflow twice
        commit: acf2c9b7952f4e93b585f2387672645c9fdaa51e
[07/12] bootstd: rauc: Only set the RAUC variables for a RAUC device
        commit: 48dd34a34ebf33a58bad7b51882a7e26c97ce719
[08/12] bootstd: rauc: Optionally find the partitions by name
        commit: 4ca14703dc38a33110619ff1b41671dde2714548
[09/12] bootstd: rauc: Optionally boot with a built-in command
        commit: 3cf09c8b5033c85310e4a8f77874731b19da0995
[10/12] test: fs_helper: Support GPT in DiskHelper
        commit: 17defa32cbe0afdd83178150a20cee24769e0fb0
[11/12] test: boot: Test finding the RAUC partitions by name
        commit: 7107800ed761a77e51f89f7217f62cf9f09e5fbf
[12/12] test: boot: Test the RAUC built-in boot command
        commit: a44a9004c1cd79ac638e6804258242be036c0d88
Signature · 1 line
Tom