From dd405ea745e451fb0cf32e9dedd94d69850fe333 Mon Sep 17 00:00:00 2001
From: Toomas Losin <tlo@lenrek.net>
Date: Sun, 5 Mar 2023 15:57:55 -0800
Subject: [PATCH] libfdisk: Fix randomly generated GPT UUID's

Fdisk commands that create random GPT UUID's result in values that are
not UEFI-compliant being written to disk: The "g" command creates a
new GPT whose in-core DiskGUID value is entirely big-endian; the "n"
command creates a GPT partition whose in-core UniquePartitionGUID
value is entirely big-endian.  Those big-endian values are written to
disk by the "w" command rather than the mix of little- and big-endian
spec'd by UEFI.

This was caused by a libfdisk patch in 2017 that was addressing
warnings about "taking address of packed member".  Reading gpt.c finds
two instances of dead code which suggests that perhaps there was some
confusion between a struct and a pointer to a struct.  The intent must
have been to convert the randomly generated big-endian RFC 4122 UUID
values to UEFI's mixed-endian but the confusion(?) resulted in some
dead code and non-conversion of the UUID's.

This patch corrects the breakage while still avoiding "taking address
of packed member" warnings.  The "w" command will once again write
UEFI-compliant values to disk.

Fixes: 92e486f80ef8 ("libfdisk: fix guid usage of packed struct gpt_entry")
Signed-off-by: Toomas Losin <tlo@lenrek.net>
---
 libfdisk/src/gpt.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/libfdisk/src/gpt.c b/libfdisk/src/gpt.c
index d7b3e1c70..c3c0347cb 100644
--- a/libfdisk/src/gpt.c
+++ b/libfdisk/src/gpt.c
@@ -878,9 +878,9 @@ static int gpt_mknew_header(struct fdisk_context *cxt,
 	if (!has_id) {
 		struct gpt_guid guid;
 
-		uuid_generate_random((unsigned char *) &header->disk_guid);
-		guid = header->disk_guid;
+		uuid_generate_random((unsigned char *) &guid);
 		swap_efi_guid(&guid);
+		header->disk_guid = guid;
 	}
 	return 0;
 }
@@ -2621,9 +2621,9 @@ static int gpt_add_partition(
 		 */
 		struct gpt_guid guid;
 
-		uuid_generate_random((unsigned char *) &e->partition_guid);
-		guid = e->partition_guid;
+		uuid_generate_random((unsigned char *) &guid);
 		swap_efi_guid(&guid);
+		e->partition_guid = guid;
 	}
 
 	if (pa && pa->name && *pa->name)
-- 
2.27.0

