commit 033eb22f5ecf639833ab644bf0ab6e57d1666481
parent fce2eac2ac0adcf5ad9cb2534a5ef531d9324374
Author: xplshn <anto@xplshn.com.ar>
Date: Tue, 24 Nov 2026 02:36:43 -0300
libdisk: gpt and mbr tables as a list of partitions, and a plan of what each holds. fdisk uses its gpt code
Diffstat:
10 files changed, 1491 insertions(+), 268 deletions(-)
diff --git a/cmd/extra/fdisk.c b/cmd/extra/fdisk.c
@@ -1,5 +1,6 @@
/* see LICENSE file for copyright and license details */
#include "diskutil.h"
+#include "libdisk/gpt.h"
#include "util.h"
#include <fcntl.h>
@@ -9,47 +10,6 @@
#include <strings.h>
#include <unistd.h>
-struct MbrPartition {
- uint8_t boot;
- uint8_t start_chs[3];
- uint8_t type;
- uint8_t end_chs[3];
- uint32_t start_lba;
- uint32_t size;
-} __attribute__((packed));
-
-struct MbrHeader {
- uint8_t code[446];
- struct MbrPartition parts[4];
- uint8_t sig[2];
-} __attribute__((packed));
-
-struct GptHeader {
- uint8_t sig[8];
- uint32_t rev;
- uint32_t size;
- uint32_t crc;
- uint32_t reserved;
- uint64_t current_lba;
- uint64_t backup_lba;
- uint64_t first_usable;
- uint64_t last_usable;
- uint8_t disk_guid[16];
- uint64_t partition_lba;
- uint32_t num_parts;
- uint32_t part_size;
- uint32_t parts_crc;
-} __attribute__((packed));
-
-struct GptPartition {
- uint8_t type_guid[16];
- uint8_t part_guid[16];
- uint64_t start_lba;
- uint64_t end_lba;
- uint64_t flags;
- uint16_t name[36];
-} __attribute__((packed));
-
struct BsdPartition {
uint32_t size;
uint32_t offset;
@@ -91,142 +51,6 @@ struct BsdDisklabel {
struct BsdPartition d_partitions[16];
} __attribute__((packed));
-static uint32_t crc32_table[256];
-static int crc32_table_initialized = 0;
-
-static void
-init_crc32_table(void)
-{
- uint32_t i, j, c;
- for (i = 0; i < 256; i++) {
- c = i;
- for (j = 0; j < 8; j++) {
- if (c & 1)
- c = 0xedb88320U ^ (c >> 1);
- else
- c = c >> 1;
- }
- crc32_table[i] = c;
- }
- crc32_table_initialized = 1;
-}
-
-static uint32_t
-crc32(uint32_t crc, const void *buf, size_t len)
-{
- const uint8_t *p = buf;
- if (!crc32_table_initialized)
- init_crc32_table();
- while (len--)
- crc = (crc >> 8) ^ crc32_table[(crc ^ *p++) & 0xFF];
- return crc;
-}
-
-/* short two-byte codes match gdisk/sgdisk's own convention, since
- * every caller already writing "-t ef00" etc against those tools
- * expects the same codes here */
-static const struct {
- const char *code;
- uint8_t guid[16];
-} gpt_type_table[] = {
- /* ef00: efi system partition */
- {"ef00",
- {0x28, 0x73, 0x2a, 0xc1, 0x1f, 0xf8, 0xd2, 0x11, 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9,
- 0x3b} },
- /* ef02: bios boot partition */
- {"ef02",
- {0x48, 0x61, 0x68, 0x21, 0x49, 0x64, 0x6f, 0x6e, 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46,
- 0x49} },
- /* 8200: linux swap */
- {"8200",
- {0x6d, 0xfd, 0x57, 0x06, 0xab, 0xa4, 0xc4, 0x43, 0x84, 0xe5, 0x09, 0x33, 0xc8, 0x4b, 0x4f,
- 0x4f} },
- /* 8300: linux filesystem data */
- {"8300",
- {0xaf, 0x3d, 0xc6, 0x0f, 0x83, 0x84, 0x72, 0x47, 0x8e, 0x79, 0x3d, 0x69, 0xd8, 0x47, 0x7d,
- 0xe4} },
-};
-#define GPT_TYPE_TABLE_LEN (int)(sizeof(gpt_type_table) / sizeof(gpt_type_table[0]))
-
-/* canonical XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX form: the first three
- * groups store little-endian, the last two store big-endian, the same
- * mixed layout every other GUID field in this file already uses */
-static int
-parse_guid_string(const char *s, uint8_t out[16])
-{
- static const int group_len[5] = {8, 4, 4, 4, 12};
- static const int group_le[5] = {1, 1, 1, 0, 0};
- int g, i, hi, lo, byte_idx = 0;
- const char *p = s;
-
- for (g = 0; g < 5; g++) {
- uint8_t bytes[6];
- int nbytes = group_len[g] / 2;
- for (i = 0; i < nbytes; i++) {
- hi = hexval(p[i * 2]);
- lo = hexval(p[i * 2 + 1]);
- if (hi < 0 || lo < 0)
- return -1;
- bytes[i] = (uint8_t)((hi << 4) | lo);
- }
- if (group_le[g]) {
- for (i = nbytes - 1; i >= 0; i--)
- out[byte_idx++] = bytes[i];
- } else {
- for (i = 0; i < nbytes; i++)
- out[byte_idx++] = bytes[i];
- }
- p += group_len[g];
- if (g < 4) {
- if (*p != '-')
- return -1;
- p++;
- }
- }
- return *p == '\0' ? 0 : -1;
-}
-
-/* opt_type is a short gdisk-style code (see gpt_type_table above), a
- * full canonical GUID string, or unset: unset (or unrecognized, with
- * a warning) keeps the long-standing default of "linux filesystem
- * data", matching what every caller got before -t existed */
-static void
-gpt_type_guid(const char *type, uint8_t out[16])
-{
- int i;
-
- if (type) {
- for (i = 0; i < GPT_TYPE_TABLE_LEN; i++) {
- if (strcasecmp(type, gpt_type_table[i].code) == 0) {
- memcpy(out, gpt_type_table[i].guid, 16);
- return;
- }
- }
- if (parse_guid_string(type, out) == 0)
- return;
- weprintf("unrecognized GPT type '%s', using linux filesystem data\n", type);
- }
- memcpy(out, gpt_type_table[GPT_TYPE_TABLE_LEN - 1].guid, 16);
-}
-
-/* a random GUID, version 4: the disk and each partition must have a
- * GUID of their own, and a loader such as limine ignores a partition
- * whose GUID is zero */
-static int
-gpt_random_guid(uint8_t out[16])
-{
- int fd = open(ARUU_PATH_DEVURANDOM, O_RDONLY);
- ssize_t n = fd < 0 ? -1 : read(fd, out, 16);
-
- if (fd >= 0)
- close(fd);
- if (n != 16)
- return -1;
- out[6] = (out[6] & 0x0f) | 0x40;
- out[8] = (out[8] & 0x3f) | 0x80;
- return 0;
-}
-
/* resolves -b for a GPT add: a plain sector number, or 0/unset for
* the first free sector right after every existing partition's own
* end_lba (gpt_hdr.first_usable if the table is still empty), the
@@ -270,21 +94,6 @@ gpt_resolve_end(struct GptHeader *hdr, size_t sec_size, uint64_t start, const ch
return (uint64_t)estrtoul(s, 10);
}
-/* GPT partition names are UTF-16LE, 36 code units, null-padded: every
- * caller so far only ever needs a plain ASCII label, so this widens
- * each byte rather than pulling in a real UTF-8 decoder for it */
-static void
-gpt_set_name(uint16_t name[36], const char *s)
-{
- size_t i;
-
- memset(name, 0, 36 * sizeof(uint16_t));
- if (!s)
- return;
- for (i = 0; i < 35 && s[i]; i++)
- name[i] = (uint16_t)(unsigned char)s[i];
-}
-
static int opt_list = 0;
static int opt_print = 0;
static int opt_init_gpt = 0;
@@ -377,79 +186,6 @@ gpt_print(struct GptHeader *hdr, struct GptPartition *parts, const char *path)
}
}
-static int
-gpt_read(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts)
-{
- unsigned char sector[512];
- size_t part_sectors;
-
- if (blockdev_read(dev, 1, sector, 1) < 0)
- return -1;
-
- memcpy(hdr, sector, sizeof(*hdr));
-
- if (memcmp(hdr->sig, "EFI PART", 8) != 0)
- return -1;
-
- part_sectors = (hdr->num_parts * hdr->part_size + dev->sec_size - 1) / dev->sec_size;
- if (blockdev_read(dev, hdr->partition_lba, parts, part_sectors) < 0)
- return -1;
-
- return 0;
-}
-
-static int
-gpt_write(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts)
-{
- unsigned char sector[512];
- struct MbrHeader pmbr;
- struct GptHeader backup_hdr;
- uint64_t limit;
- size_t part_sectors;
-
- part_sectors = (hdr->num_parts * hdr->part_size + dev->sec_size - 1) / dev->sec_size;
-
- hdr->parts_crc = crc32(~0U, parts, hdr->num_parts * hdr->part_size) ^ ~0U;
-
- hdr->crc = 0;
- hdr->crc = crc32(~0U, hdr, hdr->size) ^ ~0U;
-
- memset(&pmbr, 0, sizeof(pmbr));
- pmbr.parts[0].type = 0xEE;
- pmbr.parts[0].start_lba = 1;
- limit = dev->size / dev->sec_size - 1;
- pmbr.parts[0].size = limit > 0xFFFFFFFFU ? 0xFFFFFFFFU : (uint32_t)limit;
- pmbr.sig[0] = 0x55;
- pmbr.sig[1] = 0xAA;
- if (blockdev_write(dev, 0, &pmbr, 1) < 0)
- return -1;
-
- memset(sector, 0, sizeof(sector));
- memcpy(sector, hdr, sizeof(*hdr));
- if (blockdev_write(dev, 1, sector, 1) < 0)
- return -1;
- if (blockdev_write(dev, hdr->partition_lba, parts, part_sectors) < 0)
- return -1;
-
- backup_hdr = *hdr;
- backup_hdr.current_lba = hdr->backup_lba;
- backup_hdr.backup_lba = hdr->current_lba;
- backup_hdr.partition_lba = backup_hdr.current_lba - part_sectors;
-
- backup_hdr.crc = 0;
- backup_hdr.crc = crc32(~0U, &backup_hdr, backup_hdr.size) ^ ~0U;
-
- if (blockdev_write(dev, backup_hdr.partition_lba, parts, part_sectors) < 0)
- return -1;
-
- memset(sector, 0, sizeof(sector));
- memcpy(sector, &backup_hdr, sizeof(backup_hdr));
- if (blockdev_write(dev, backup_hdr.current_lba, sector, 1) < 0)
- return -1;
-
- return 0;
-}
-
static uint16_t
bsd_dkcksum(void *lp, size_t nparts)
{
diff --git a/ninqu.rules b/ninqu.rules
@@ -97,7 +97,21 @@
(feature core-lib)
(exec $(AR) $(ARFLAGS) $(OUT) $(IN)))
- (group lib LIBUTF LIBUTIL LIBREDLINE LIBBLAKE3)
+ (rule LIBDISK_OBJ
+ (glob "shared/libdisk/*.c")
+ (skip "label_test.c" "plan_test.c")
+ (dep $(MATCH) FEATURES_H)
+ (out "$(STEM).o")
+ (exec $(CC) $(CPPFLAGS) -Ishared -Ishared/libdisk $(CFLAGS) -c -o $(OUT) $(MATCH)))
+
+ (rule LIBDISK
+ (dep LIBDISK_OBJ)
+ (out "shared/libdisk/libdisk.a")
+ (description "partition tables: the GPT and MBR as a list of partitions, for fdisk and for a partitioner")
+ (feature core-lib)
+ (exec $(AR) $(ARFLAGS) $(OUT) $(IN)))
+
+ (group lib LIBUTF LIBUTIL LIBREDLINE LIBBLAKE3 LIBDISK)
; perfile: every *.c directly inside one of these dirs becomes its
; own binary of the same name, individually gated by
@@ -142,7 +156,7 @@
; compiled and linked in one step, so the header that every compile
; -includes is order-only: as a dep it would land in $(IN) and be
; passed to the linker. its path still makes a change rebuild
- (dep $(MATCH) LIBUTIL LIBUTF LIBBLAKE3)
+ (dep $(MATCH) LIBDISK LIBUTIL LIBUTF LIBBLAKE3)
(after "scripts/mk/features.h" $(EXTRA_AFTER))
(out $(STEM))
(description $(DESC))
@@ -827,7 +841,7 @@
; instead, same as LIBUTIL/LIBUTF/LIBREDLINE
;
(rule BOX
- (dep BOX_DISPATCH BOX_OBJ POSIX_BC_BOX POSIX_AWK_BOX POSIX_SH_BOX POSIX_MAKE_BOX EXTRA_YAP_BOX NINQU_BOX LIBUTIL LIBUTF LIBREDLINE LIBBLAKE3)
+ (dep BOX_DISPATCH BOX_OBJ POSIX_BC_BOX POSIX_AWK_BOX POSIX_SH_BOX POSIX_MAKE_BOX EXTRA_YAP_BOX NINQU_BOX LIBDISK LIBUTIL LIBUTF LIBREDLINE LIBBLAKE3)
(out "aruu-box")
(description "single multi-call binary, one dispatch table for every enabled tool")
(shell "$(CC) $(CPPFLAGS) $(CFLAGS) -o $(OUT) $(IN) $(LDFLAGS) $(LDLIBS) $(BOX_EXTRA_LIBS)")
diff --git a/shared/libdisk/gpt.c b/shared/libdisk/gpt.c
@@ -0,0 +1,243 @@
+/* see LICENSE file for copyright and license details */
+#include "gpt.h"
+#include "../util.h"
+
+#include <fcntl.h>
+#include <stdio.h>
+#include <string.h>
+#include <strings.h>
+#include <unistd.h>
+
+static uint32_t crc32_table[256];
+static int crc32_table_initialized = 0;
+
+static void
+init_crc32_table(void)
+{
+ uint32_t i, j, c;
+ for (i = 0; i < 256; i++) {
+ c = i;
+ for (j = 0; j < 8; j++) {
+ if (c & 1)
+ c = 0xedb88320U ^ (c >> 1);
+ else
+ c = c >> 1;
+ }
+ crc32_table[i] = c;
+ }
+ crc32_table_initialized = 1;
+}
+
+uint32_t
+disk_crc32(uint32_t crc, const void *buf, size_t len)
+{
+ const uint8_t *p = buf;
+ if (!crc32_table_initialized)
+ init_crc32_table();
+ while (len--)
+ crc = (crc >> 8) ^ crc32_table[(crc ^ *p++) & 0xFF];
+ return crc;
+}
+
+const struct GptType gpt_types[] = {
+ /* short two-byte codes match gdisk/sgdisk's own convention, since
+ * every caller already writing "-t ef00" etc against those tools
+ * expects the same codes here. the last is the default */
+ {"ef00", "EFI system", "c12a7328-f81f-11d2-ba4b-00a0c93ec93b", 0xef},
+ {"ef02", "BIOS boot", "21686148-6449-6e6f-744e-656564454649", 0x00},
+ {"8200", "Linux swap", "0657fd6d-a4ab-43c4-84e5-0933c84b4f4f", 0x82},
+ {"0700", "Basic data", "ebd0a0a2-b9e5-4433-87c0-68b6b72699c7", 0x07},
+ {"8e00", "Linux LVM", "e6d6d379-f507-44c2-a23c-238f2a3df928", 0x8e},
+ {"fd00", "Linux RAID", "a19d880f-05fc-4d3b-a006-743f0f84911e", 0xfd},
+ {"8302", "Linux home", "933ac7e1-2eb4-4f13-b844-0e14e2aef915", 0x83},
+ {"8300", "Linux filesystem", "0fc63daf-8483-4772-8e79-3d69d8477de4", 0x83},
+};
+const int gpt_ntypes = (int)(sizeof(gpt_types) / sizeof(gpt_types[0]));
+
+/* canonical XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX form: the first three
+ * groups store little-endian, the last two store big-endian, the same
+ * mixed layout every other GUID field in this file already uses */
+int
+parse_guid_string(const char *s, uint8_t out[16])
+{
+ static const int group_len[5] = {8, 4, 4, 4, 12};
+ static const int group_le[5] = {1, 1, 1, 0, 0};
+ int g, i, hi, lo, byte_idx = 0;
+ const char *p = s;
+
+ for (g = 0; g < 5; g++) {
+ uint8_t bytes[6];
+ int nbytes = group_len[g] / 2;
+ for (i = 0; i < nbytes; i++) {
+ hi = hexval(p[i * 2]);
+ lo = hexval(p[i * 2 + 1]);
+ if (hi < 0 || lo < 0)
+ return -1;
+ bytes[i] = (uint8_t)((hi << 4) | lo);
+ }
+ if (group_le[g]) {
+ for (i = nbytes - 1; i >= 0; i--)
+ out[byte_idx++] = bytes[i];
+ } else {
+ for (i = 0; i < nbytes; i++)
+ out[byte_idx++] = bytes[i];
+ }
+ p += group_len[g];
+ if (g < 4) {
+ if (*p != '-')
+ return -1;
+ p++;
+ }
+ }
+ return *p == '\0' ? 0 : -1;
+}
+
+/* a GUID as text, in the canonical form parse_guid_string reads */
+void
+format_guid(const uint8_t g[16], char out[37])
+{
+ snprintf(out, 37, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", g[3], g[2], g[1], g[0], g[5],
+ g[4], g[7], g[6], g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]);
+}
+
+const struct GptType *
+gpt_type_of(const uint8_t guid[16])
+{
+ uint8_t want[16];
+ int i;
+
+ for (i = 0; i < gpt_ntypes; i++)
+ if (parse_guid_string(gpt_types[i].guid, want) == 0 && memcmp(want, guid, 16) == 0)
+ return &gpt_types[i];
+ return NULL;
+}
+
+/* type is a short gdisk-style code (see gpt_types above), a full
+ * canonical GUID string, or unset: unset (or unrecognized, with a
+ * warning) keeps the long-standing default of "linux filesystem data",
+ * matching what every caller got before -t existed */
+void
+gpt_type_guid(const char *type, uint8_t out[16])
+{
+ int i;
+
+ if (type) {
+ for (i = 0; i < gpt_ntypes; i++) {
+ if (strcasecmp(type, gpt_types[i].code) == 0) {
+ parse_guid_string(gpt_types[i].guid, out);
+ return;
+ }
+ }
+ if (parse_guid_string(type, out) == 0)
+ return;
+ weprintf("unrecognized GPT type '%s', using linux filesystem data\n", type);
+ }
+ parse_guid_string(gpt_types[gpt_ntypes - 1].guid, out);
+}
+
+/* a random GUID, version 4: the disk and each partition must have a
+ * GUID of their own, and a loader such as limine ignores a partition
+ * whose GUID is zero */
+int
+gpt_random_guid(uint8_t out[16])
+{
+ int fd = open(ARUU_PATH_DEVURANDOM, O_RDONLY);
+ ssize_t n = fd < 0 ? -1 : read(fd, out, 16);
+
+ if (fd >= 0)
+ close(fd);
+ if (n != 16)
+ return -1;
+ out[6] = (out[6] & 0x0f) | 0x40;
+ out[8] = (out[8] & 0x3f) | 0x80;
+ return 0;
+}
+
+/* GPT partition names are UTF-16LE, 36 code units, null-padded: every
+ * caller so far only ever needs a plain ASCII label, so this widens
+ * each byte rather than pulling in a real UTF-8 decoder for it */
+void
+gpt_set_name(uint16_t name[36], const char *s)
+{
+ size_t i;
+
+ memset(name, 0, 36 * sizeof(uint16_t));
+ if (!s)
+ return;
+ for (i = 0; i < 35 && s[i]; i++)
+ name[i] = (uint16_t)(unsigned char)s[i];
+}
+
+int
+gpt_read(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts)
+{
+ unsigned char sector[512];
+ size_t part_sectors;
+
+ if (blockdev_read(dev, 1, sector, 1) < 0)
+ return -1;
+
+ memcpy(hdr, sector, sizeof(*hdr));
+
+ if (memcmp(hdr->sig, "EFI PART", 8) != 0)
+ return -1;
+
+ part_sectors = (hdr->num_parts * hdr->part_size + dev->sec_size - 1) / dev->sec_size;
+ if (blockdev_read(dev, hdr->partition_lba, parts, part_sectors) < 0)
+ return -1;
+
+ return 0;
+}
+
+int
+gpt_write(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts)
+{
+ unsigned char sector[512];
+ struct MbrHeader pmbr;
+ struct GptHeader backup_hdr;
+ uint64_t limit;
+ size_t part_sectors;
+
+ part_sectors = (hdr->num_parts * hdr->part_size + dev->sec_size - 1) / dev->sec_size;
+
+ hdr->parts_crc = disk_crc32(~0U, parts, hdr->num_parts * hdr->part_size) ^ ~0U;
+
+ hdr->crc = 0;
+ hdr->crc = disk_crc32(~0U, hdr, hdr->size) ^ ~0U;
+
+ memset(&pmbr, 0, sizeof(pmbr));
+ pmbr.parts[0].type = 0xEE;
+ pmbr.parts[0].start_lba = 1;
+ limit = dev->size / dev->sec_size - 1;
+ pmbr.parts[0].size = limit > 0xFFFFFFFFU ? 0xFFFFFFFFU : (uint32_t)limit;
+ pmbr.sig[0] = 0x55;
+ pmbr.sig[1] = 0xAA;
+ if (blockdev_write(dev, 0, &pmbr, 1) < 0)
+ return -1;
+
+ memset(sector, 0, sizeof(sector));
+ memcpy(sector, hdr, sizeof(*hdr));
+ if (blockdev_write(dev, 1, sector, 1) < 0)
+ return -1;
+ if (blockdev_write(dev, hdr->partition_lba, parts, part_sectors) < 0)
+ return -1;
+
+ backup_hdr = *hdr;
+ backup_hdr.current_lba = hdr->backup_lba;
+ backup_hdr.backup_lba = hdr->current_lba;
+ backup_hdr.partition_lba = backup_hdr.current_lba - part_sectors;
+
+ backup_hdr.crc = 0;
+ backup_hdr.crc = disk_crc32(~0U, &backup_hdr, backup_hdr.size) ^ ~0U;
+
+ if (blockdev_write(dev, backup_hdr.partition_lba, parts, part_sectors) < 0)
+ return -1;
+
+ memset(sector, 0, sizeof(sector));
+ memcpy(sector, &backup_hdr, sizeof(backup_hdr));
+ if (blockdev_write(dev, backup_hdr.current_lba, sector, 1) < 0)
+ return -1;
+
+ return 0;
+}
+
diff --git a/shared/libdisk/gpt.h b/shared/libdisk/gpt.h
@@ -0,0 +1,81 @@
+/* see LICENSE file for copyright and license details */
+#ifndef ARUU_LIBDISK_GPT_H
+#define ARUU_LIBDISK_GPT_H
+
+/* the tables as they are on a disk, and reading and writing the GPT
+ * itself. fdisk edits these directly; libdisk's label.c is the same
+ * tables as a list of partitions, for anything that is not a command
+ * line over them */
+
+#include "../diskutil.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+struct MbrPartition {
+ uint8_t boot;
+ uint8_t start_chs[3];
+ uint8_t type;
+ uint8_t end_chs[3];
+ uint32_t start_lba;
+ uint32_t size;
+} __attribute__((packed));
+
+struct MbrHeader {
+ uint8_t code[446];
+ struct MbrPartition parts[4];
+ uint8_t sig[2];
+} __attribute__((packed));
+
+struct GptHeader {
+ uint8_t sig[8];
+ uint32_t rev;
+ uint32_t size;
+ uint32_t crc;
+ uint32_t reserved;
+ uint64_t current_lba;
+ uint64_t backup_lba;
+ uint64_t first_usable;
+ uint64_t last_usable;
+ uint8_t disk_guid[16];
+ uint64_t partition_lba;
+ uint32_t num_parts;
+ uint32_t part_size;
+ uint32_t parts_crc;
+} __attribute__((packed));
+
+struct GptPartition {
+ uint8_t type_guid[16];
+ uint8_t part_guid[16];
+ uint64_t start_lba;
+ uint64_t end_lba;
+ uint64_t flags;
+ uint16_t name[36];
+} __attribute__((packed));
+
+#define GPT_ENTRIES 128
+#define GPT_ENTRY_SZ 128
+/* the table of known partition types, gdisk's four hex digit codes */
+struct GptType {
+ const char *code;
+ const char *name;
+ const char *guid; /* canonical form */
+ uint8_t mbr; /* the byte MBR uses for it, 0 for none */
+};
+extern const struct GptType gpt_types[];
+extern const int gpt_ntypes;
+
+uint32_t disk_crc32(uint32_t crc, const void *buf, size_t len);
+int parse_guid_string(const char *s, uint8_t out[16]);
+void format_guid(const uint8_t guid[16], char out[37]);
+/* the GUID of a type code or canonical GUID string; unknown ones give the
+ * linux filesystem type, with a warning */
+void gpt_type_guid(const char *type, uint8_t out[16]);
+/* the type of a GUID: its table entry, NULL when it is none of them */
+const struct GptType *gpt_type_of(const uint8_t guid[16]);
+int gpt_random_guid(uint8_t out[16]);
+void gpt_set_name(uint16_t name[36], const char *s);
+int gpt_read(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts);
+int gpt_write(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts);
+
+#endif
diff --git a/shared/libdisk/label.c b/shared/libdisk/label.c
@@ -0,0 +1,443 @@
+/* see LICENSE file for copyright and license details */
+#include "label.h"
+#include "gpt.h"
+#include "../util.h"
+
+#include <errno.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <strings.h>
+
+#define MBR_SLOTS 4
+
+static const struct label_type *types_cache;
+
+static void
+set_type(struct label_part *p, const char *code)
+{
+ const struct GptType *t = NULL;
+ int i;
+
+ for (i = 0; i < gpt_ntypes; i++)
+ if (strcasecmp(gpt_types[i].code, code) == 0)
+ t = &gpt_types[i];
+ memset(p->type, 0, sizeof p->type);
+ if (!t)
+ return;
+ snprintf(p->type, sizeof p->type, "%s", t->code);
+ parse_guid_string(t->guid, p->type_guid);
+ p->mbr_type = t->mbr;
+}
+
+const char *
+label_type_name(const struct label_part *p)
+{
+ int i;
+
+ for (i = 0; i < gpt_ntypes; i++)
+ if (p->type[0] && strcasecmp(gpt_types[i].code, p->type) == 0)
+ return gpt_types[i].name;
+ return "unknown";
+}
+
+int
+label_types(const struct label_type **out)
+{
+ static struct label_type table[16];
+ int i;
+
+ if (!types_cache) {
+ for (i = 0; i < gpt_ntypes && i < 16; i++) {
+ table[i].code = gpt_types[i].code;
+ table[i].name = gpt_types[i].name;
+ table[i].gpt_only = gpt_types[i].mbr == 0;
+ }
+ types_cache = table;
+ }
+ *out = types_cache;
+ return gpt_ntypes;
+}
+
+static uint64_t
+gpt_array_sectors(size_t sec_size)
+{
+ return (uint64_t)(GPT_ENTRIES * GPT_ENTRY_SZ + sec_size - 1) / sec_size;
+}
+
+int
+label_init(struct label *l, const struct BlockDev *dev, enum label_kind kind)
+{
+ memset(l, 0, sizeof *l);
+ l->kind = kind;
+ l->sec_size = dev->sec_size;
+ l->sectors = dev->size / dev->sec_size;
+ if (kind == LABEL_GPT) {
+ uint64_t arr = gpt_array_sectors(l->sec_size);
+
+ /* the primary header and array in front, the backup behind */
+ if (l->sectors < 2 + arr + 1 + arr + 1 + LABEL_ALIGN)
+ return -1;
+ l->first = 2 + arr;
+ l->last = l->sectors - 2 - arr;
+ l->slots = LABEL_SLOTS;
+ if (gpt_random_guid(l->disk_guid) < 0)
+ return -1;
+ } else if (kind == LABEL_MBR) {
+ if (l->sectors <= LABEL_ALIGN)
+ return -1;
+ l->first = LABEL_ALIGN;
+ l->last = l->sectors - 1;
+ l->slots = MBR_SLOTS;
+ {
+ uint8_t r[16];
+
+ if (gpt_random_guid(r) < 0)
+ return -1;
+ memcpy(&l->mbr_id, r, sizeof l->mbr_id);
+ }
+ }
+ return 0;
+}
+
+static int
+read_gpt(struct BlockDev *dev, struct label *l)
+{
+ struct GptHeader hdr;
+ struct GptPartition *parts;
+ uint32_t i;
+ int n = 0;
+
+ if (!(parts = calloc(GPT_ENTRIES, GPT_ENTRY_SZ)))
+ return -1;
+ if (gpt_read(dev, &hdr, parts) < 0 || hdr.part_size != GPT_ENTRY_SZ || hdr.num_parts > GPT_ENTRIES) {
+ free(parts);
+ return 0; /* no GPT */
+ }
+ l->kind = LABEL_GPT;
+ l->slots = LABEL_SLOTS;
+ l->first = hdr.first_usable;
+ l->last = hdr.last_usable;
+ memcpy(l->disk_guid, hdr.disk_guid, 16);
+ for (i = 0; i < hdr.num_parts; i++) {
+ struct label_part *p = &l->part[i];
+ const struct GptType *t;
+ int c;
+
+ if (parts[i].start_lba == 0 && parts[i].end_lba == 0)
+ continue;
+ p->used = 1;
+ p->start = parts[i].start_lba;
+ p->end = parts[i].end_lba;
+ memcpy(p->type_guid, parts[i].type_guid, 16);
+ memcpy(p->guid, parts[i].part_guid, 16);
+ if ((t = gpt_type_of(parts[i].type_guid))) {
+ snprintf(p->type, sizeof p->type, "%s", t->code);
+ p->mbr_type = t->mbr;
+ }
+ /* names are UTF-16, narrowed: what the installer writes is ASCII */
+ for (c = 0; c < 36 && c < (int)sizeof p->name - 1 && parts[i].name[c]; c++)
+ p->name[c] = parts[i].name[c] < 128 ? (char)parts[i].name[c] : '?';
+ n++;
+ }
+ free(parts);
+ return n >= 0 ? 1 : 0;
+}
+
+static int
+read_mbr(struct BlockDev *dev, struct label *l)
+{
+ struct MbrHeader mbr;
+ int i;
+
+ if (blockdev_read(dev, 0, &mbr, 1) < 0)
+ return -1;
+ if (mbr.sig[0] != 0x55 || mbr.sig[1] != 0xAA)
+ return 0;
+ /* a protective MBR over a GPT that did not read is no table of its own */
+ if (mbr.parts[0].type == 0xEE)
+ return 0;
+ l->kind = LABEL_MBR;
+ l->slots = MBR_SLOTS;
+ l->first = LABEL_ALIGN;
+ l->last = l->sectors - 1;
+ memcpy(l->mbr_code, mbr.code, sizeof l->mbr_code);
+ memcpy(&l->mbr_id, mbr.code + 440, 4);
+ for (i = 0; i < MBR_SLOTS; i++) {
+ struct label_part *p = &l->part[i];
+ int t;
+
+ if (mbr.parts[i].type == 0 || mbr.parts[i].size == 0)
+ continue;
+ p->used = 1;
+ p->start = mbr.parts[i].start_lba;
+ p->end = (uint64_t)mbr.parts[i].start_lba + mbr.parts[i].size - 1;
+ p->mbr_type = mbr.parts[i].type;
+ p->active = mbr.parts[i].boot == 0x80;
+ /* 0x83 stands for both Linux types: the plain one's code, not the home */
+ for (t = 0; t < gpt_ntypes; t++) {
+ if (gpt_types[t].mbr == p->mbr_type && strcmp(gpt_types[t].code, "8302") != 0) {
+ snprintf(p->type, sizeof p->type, "%s", gpt_types[t].code);
+ parse_guid_string(gpt_types[t].guid, p->type_guid);
+ break;
+ }
+ }
+ }
+ return 1;
+}
+
+int
+label_read(struct BlockDev *dev, struct label *l)
+{
+ int got;
+
+ memset(l, 0, sizeof *l);
+ l->sec_size = dev->sec_size;
+ l->sectors = dev->size / dev->sec_size;
+ if ((got = read_gpt(dev, l)) < 0)
+ return -1;
+ if (got > 0)
+ return 0;
+ if ((got = read_mbr(dev, l)) < 0)
+ return -1;
+ return 0;
+}
+
+static int
+overlaps(const struct label *l, uint64_t start, uint64_t end, int except)
+{
+ int i;
+
+ for (i = 0; i < l->slots; i++)
+ if (i != except && l->part[i].used && start <= l->part[i].end && end >= l->part[i].start)
+ return 1;
+ return 0;
+}
+
+static int
+by_start(const void *a, const void *b)
+{
+ const struct label_part *x = *(const struct label_part *const *)a, *y = *(const struct label_part *const *)b;
+
+ return x->start < y->start ? -1 : x->start > y->start;
+}
+
+int
+label_gaps(const struct label *l, struct label_gap *out, int max)
+{
+ const struct label_part *order[LABEL_SLOTS];
+ int i, n = 0, g = 0;
+ uint64_t from = l->first;
+
+ if (l->kind == LABEL_NONE)
+ return 0;
+ for (i = 0; i < l->slots; i++)
+ if (l->part[i].used)
+ order[n++] = &l->part[i];
+ qsort(order, (size_t)n, sizeof order[0], by_start);
+ for (i = 0; i <= n && g < max; i++) {
+ uint64_t to = i < n ? order[i]->start : l->last + 1;
+ uint64_t start = (from + LABEL_ALIGN - 1) / LABEL_ALIGN * LABEL_ALIGN;
+
+ /* the end is the sector before the next partition, rounded down so the next starts aligned */
+ if (to > start && to - start >= LABEL_ALIGN) {
+ out[g].start = start;
+ out[g].end = to - 1;
+ g++;
+ }
+ if (i < n && order[i]->end + 1 > from)
+ from = order[i]->end + 1;
+ }
+ return g;
+}
+
+int
+label_add(struct label *l, uint64_t start, uint64_t sectors, const char *type, const char *name)
+{
+ struct label_gap gaps[LABEL_SLOTS + 1];
+ struct label_part *p;
+ int n, i, slot = -1, pick = -1;
+ uint64_t end;
+
+ if (l->kind == LABEL_NONE)
+ return -EINVAL;
+ for (i = 0; i < l->slots && slot < 0; i++)
+ if (!l->part[i].used)
+ slot = i;
+ if (slot < 0)
+ return -EEXIST;
+ n = label_gaps(l, gaps, LABEL_SLOTS + 1);
+ if (start == 0) {
+ /* the first gap that holds it, or with no size the biggest */
+ for (i = 0; i < n; i++) {
+ uint64_t room = gaps[i].end - gaps[i].start + 1;
+
+ if (sectors && room >= sectors) {
+ pick = i;
+ break;
+ }
+ if (!sectors && (pick < 0 || room > gaps[pick].end - gaps[pick].start + 1))
+ pick = i;
+ }
+ if (pick < 0)
+ return -ENOSPC;
+ start = gaps[pick].start;
+ end = sectors ? start + sectors - 1 : gaps[pick].end;
+ } else if (sectors) {
+ end = start + sectors - 1;
+ } else {
+ /* to the end of the gap the start is in */
+ end = 0;
+ for (i = 0; i < n; i++)
+ if (start >= gaps[i].start && start <= gaps[i].end)
+ end = gaps[i].end;
+ if (!end)
+ return -EINVAL;
+ }
+ if (start < l->first || end > l->last || end < start || overlaps(l, start, end, -1))
+ return -EINVAL;
+ p = &l->part[slot];
+ memset(p, 0, sizeof *p);
+ p->used = 1;
+ p->start = start;
+ p->end = end;
+ set_type(p, type ? type : "8300");
+ if (!p->type[0])
+ set_type(p, "8300");
+ if (name)
+ snprintf(p->name, sizeof p->name, "%s", name);
+ if (l->kind == LABEL_GPT && gpt_random_guid(p->guid) < 0) {
+ memset(p, 0, sizeof *p);
+ return -EIO;
+ }
+ return slot;
+}
+
+int
+label_delete(struct label *l, int slot)
+{
+ if (slot < 0 || slot >= l->slots || !l->part[slot].used)
+ return -EINVAL;
+ memset(&l->part[slot], 0, sizeof l->part[slot]);
+ return 0;
+}
+
+int
+label_set_type(struct label *l, int slot, const char *type)
+{
+ if (slot < 0 || slot >= l->slots || !l->part[slot].used)
+ return -EINVAL;
+ set_type(&l->part[slot], type);
+ return l->part[slot].type[0] ? 0 : -EINVAL;
+}
+
+int
+label_set_name(struct label *l, int slot, const char *name)
+{
+ if (slot < 0 || slot >= l->slots || !l->part[slot].used)
+ return -EINVAL;
+ snprintf(l->part[slot].name, sizeof l->part[slot].name, "%s", name ? name : "");
+ return 0;
+}
+
+static int
+write_gpt(struct BlockDev *dev, const struct label *l)
+{
+ struct GptHeader hdr;
+ struct GptPartition *parts;
+ uint64_t arr = gpt_array_sectors(l->sec_size);
+ int i, c, rc;
+
+ if (!(parts = calloc(GPT_ENTRIES, GPT_ENTRY_SZ)))
+ return -1;
+ memset(&hdr, 0, sizeof hdr);
+ memcpy(hdr.sig, "EFI PART", 8);
+ hdr.rev = 0x00010000;
+ hdr.size = 92;
+ hdr.current_lba = 1;
+ hdr.backup_lba = l->sectors - 1;
+ hdr.first_usable = 2 + arr;
+ hdr.last_usable = l->sectors - 2 - arr;
+ memcpy(hdr.disk_guid, l->disk_guid, 16);
+ hdr.partition_lba = 2;
+ hdr.num_parts = GPT_ENTRIES;
+ hdr.part_size = GPT_ENTRY_SZ;
+ for (i = 0; i < LABEL_SLOTS; i++) {
+ const struct label_part *p = &l->part[i];
+
+ if (!p->used)
+ continue;
+ memcpy(parts[i].type_guid, p->type_guid, 16);
+ memcpy(parts[i].part_guid, p->guid, 16);
+ parts[i].start_lba = p->start;
+ parts[i].end_lba = p->end;
+ for (c = 0; c < 35 && p->name[c]; c++)
+ parts[i].name[c] = (uint16_t)(unsigned char)p->name[c];
+ }
+ rc = gpt_write(dev, &hdr, parts);
+ free(parts);
+ return rc;
+}
+
+/* the GPT headers of dev, primary and backup, zeroed when there are any */
+static void
+drop_gpt(struct BlockDev *dev)
+{
+ unsigned char sector[4096];
+ uint64_t at[2] = { 1, dev->size / dev->sec_size - 1 };
+ int i;
+
+ if (dev->sec_size > sizeof sector)
+ return;
+ for (i = 0; i < 2; i++) {
+ if (blockdev_read(dev, at[i], sector, 1) < 0 || memcmp(sector, "EFI PART", 8) != 0)
+ continue;
+ memset(sector, 0, sizeof sector);
+ blockdev_write(dev, at[i], sector, 1);
+ }
+}
+
+static int
+write_mbr(struct BlockDev *dev, const struct label *l)
+{
+ struct MbrHeader mbr;
+ int i;
+
+ memset(&mbr, 0, sizeof mbr);
+ memcpy(mbr.code, l->mbr_code, sizeof mbr.code);
+ memcpy(mbr.code + 440, &l->mbr_id, 4);
+ for (i = 0; i < MBR_SLOTS; i++) {
+ const struct label_part *p = &l->part[i];
+
+ if (!p->used)
+ continue;
+ mbr.parts[i].boot = p->active ? 0x80 : 0;
+ mbr.parts[i].type = p->mbr_type;
+ mbr.parts[i].start_lba = (uint32_t)p->start;
+ mbr.parts[i].size = (uint32_t)(p->end - p->start + 1);
+ /* CHS is not used: the largest value says "ask the LBA" */
+ memset(mbr.parts[i].start_chs, 0xff, 3);
+ memset(mbr.parts[i].end_chs, 0xff, 3);
+ }
+ mbr.sig[0] = 0x55;
+ mbr.sig[1] = 0xAA;
+ /* a GPT left behind would be read in preference to this table */
+ drop_gpt(dev);
+ return blockdev_write(dev, 0, &mbr, 1);
+}
+
+int
+label_write(struct BlockDev *dev, const struct label *l)
+{
+ int rc;
+
+ if (l->kind == LABEL_GPT)
+ rc = write_gpt(dev, l);
+ else if (l->kind == LABEL_MBR)
+ rc = write_mbr(dev, l);
+ else
+ return -1;
+ if (rc == 0)
+ dev->dirty = 1;
+ return rc;
+}
diff --git a/shared/libdisk/label.h b/shared/libdisk/label.h
@@ -0,0 +1,75 @@
+/* see LICENSE file for copyright and license details */
+#ifndef ARUU_LIBDISK_LABEL_H
+#define ARUU_LIBDISK_LABEL_H
+
+/* a disk's partition table as a list of partitions: read it, change it in
+ * memory, write it. nothing is written to the disk until label_write, so a
+ * program can offer to undo every change. GPT and MBR (four primary
+ * partitions); the byte layout of each is gpt.c's and mbr in label.c's.
+ * fdisk edits the tables directly, a graphical partitioner or an installer
+ * goes through this */
+
+#include "../diskutil.h"
+
+#include <stdint.h>
+
+#define LABEL_SLOTS 128
+#define LABEL_ALIGN 2048 /* sectors: partitions start on 1 MiB at 512 byte sectors */
+
+enum label_kind { LABEL_NONE, LABEL_GPT, LABEL_MBR };
+
+struct label_part {
+ int used;
+ uint64_t start, end; /* sectors, the last one included */
+ char type[8]; /* gdisk's four hex digits, "" when unknown */
+ uint8_t type_guid[16];
+ uint8_t guid[16]; /* the partition's own, GPT */
+ uint8_t mbr_type;
+ char name[40];
+ int active; /* MBR's boot flag */
+};
+
+struct label {
+ enum label_kind kind;
+ uint64_t sectors; /* the disk */
+ size_t sec_size;
+ uint64_t first, last; /* usable */
+ int slots; /* 128 for GPT, 4 for MBR */
+ struct label_part part[LABEL_SLOTS];
+ /* what a rewrite keeps of the table that was there */
+ uint8_t disk_guid[16];
+ uint8_t mbr_code[446];
+ uint32_t mbr_id;
+};
+
+/* the table on dev: kind LABEL_NONE when it has none. -1 when it cannot be read */
+int label_read(struct BlockDev *dev, struct label *l);
+/* an empty table of kind for a disk of dev's size, in memory only. -1 for a disk too small */
+int label_init(struct label *l, const struct BlockDev *dev, enum label_kind kind);
+/* a partition of sectors (0: all of the biggest gap) at start (0: the first gap it fits), of type
+ * (a code of label_types) and name. its slot, a negative errno: -ENOSPC no gap, -EINVAL a start
+ * that overlaps, -EEXIST all slots used */
+int label_add(struct label *l, uint64_t start, uint64_t sectors, const char *type, const char *name);
+int label_delete(struct label *l, int slot);
+int label_set_type(struct label *l, int slot, const char *type);
+int label_set_name(struct label *l, int slot, const char *name);
+
+/* the free stretches between partitions, aligned and at least LABEL_ALIGN
+ * sectors long: how many, at most max */
+struct label_gap {
+ uint64_t start, end;
+};
+int label_gaps(const struct label *l, struct label_gap *out, int max);
+
+/* the table written to dev, backup copy and protective MBR included. 0, or -1 */
+int label_write(struct BlockDev *dev, const struct label *l);
+
+/* the partition types, for a list to choose from and to name one */
+struct label_type {
+ const char *code, *name;
+ int gpt_only; /* MBR has no byte for it */
+};
+int label_types(const struct label_type **out);
+const char *label_type_name(const struct label_part *p);
+
+#endif
diff --git a/shared/libdisk/label_test.c b/shared/libdisk/label_test.c
@@ -0,0 +1,67 @@
+/* see LICENSE file for copyright and license details */
+/* a table made, written to an image, read back and changed:
+ * cc -Ishared shared/libdisk/label_test.c shared/libdisk/label.c shared/libdisk/gpt.c \
+ * shared/libutil/diskutil.c shared/libutil/libutil.a -o label_test && ./label_test */
+#include "label.h"
+
+#include <assert.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#define IMAGE_MIB 64
+
+static void
+roundtrip(const char *path, enum label_kind kind)
+{
+ struct BlockDev dev;
+ struct label a, b;
+ struct label_gap gaps[8];
+ int esp, root, n;
+
+ assert(blockdev_open(&dev, path, 1) == 0);
+ assert(label_init(&a, &dev, kind) == 0);
+ assert(label_gaps(&a, gaps, 8) == 1);
+ esp = label_add(&a, 0, 16 * 2048, "ef00", "ESP");
+ root = label_add(&a, 0, 0, "8300", "ROOT");
+ assert(esp == 0 && root == 1);
+ assert(a.part[esp].start % LABEL_ALIGN == 0 && a.part[root].start == a.part[esp].end + 1);
+ assert(label_gaps(&a, gaps, 8) == 0);
+ /* a gap again where one is deleted, and the next one fills it */
+ assert(label_delete(&a, esp) == 0);
+ n = label_gaps(&a, gaps, 8);
+ assert(n == 1 && gaps[0].start == a.first + (LABEL_ALIGN - a.first % LABEL_ALIGN) % LABEL_ALIGN);
+ assert(label_add(&a, 0, 8 * 2048, "8200", "SWAP") == 0);
+ assert(label_set_type(&a, root, "8302") == 0);
+ assert(label_write(&dev, &a) == 0);
+ blockdev_close(&dev);
+
+ assert(blockdev_open(&dev, path, 0) == 0);
+ assert(label_read(&dev, &b) == 0);
+ assert(b.kind == kind);
+ assert(b.part[0].used && b.part[1].used && !b.part[2].used);
+ assert(b.part[0].start == a.part[0].start && b.part[0].end == a.part[0].end);
+ assert(!strcmp(b.part[0].type, "8200") && !strcmp(b.part[1].type, kind == LABEL_GPT ? "8302" : "8300"));
+ if (kind == LABEL_GPT)
+ assert(!strcmp(b.part[0].name, "SWAP") && !strcmp(b.part[1].name, "ROOT"));
+ blockdev_close(&dev);
+}
+
+int
+main(void)
+{
+ char path[] = "/tmp/label_test.XXXXXX";
+ int fd = mkstemp(path);
+
+ assert(fd >= 0 && ftruncate(fd, (off_t)IMAGE_MIB << 20) == 0);
+ close(fd);
+ roundtrip(path, LABEL_GPT);
+ roundtrip(path, LABEL_MBR);
+ /* going back to GPT is read as GPT, the MBR one being gone with its table */
+ roundtrip(path, LABEL_GPT);
+ unlink(path);
+ puts("label_test: ok");
+ return 0;
+}
diff --git a/shared/libdisk/plan.c b/shared/libdisk/plan.c
@@ -0,0 +1,435 @@
+/* see LICENSE file for copyright and license details */
+#include "plan.h"
+#include "../util.h"
+
+#include <ctype.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+
+static const struct plan_fs filesystems[] = {
+ {"ext4", "ext4", "ext4", 1, 16},
+ {"f2fs", "f2fs", "f2fs", 1, 512},
+ {"vfat", "FAT32 (vfat)", "vfat", 0, 11},
+ {"swap", "swap", NULL, 0, 15},
+};
+#define NFS ((int)(sizeof filesystems / sizeof filesystems[0]))
+
+const struct plan_fs *
+plan_filesystems(int *n)
+{
+ *n = NFS;
+ return filesystems;
+}
+
+const struct plan_fs *
+plan_filesystem(const char *name)
+{
+ int i;
+
+ for (i = 0; i < NFS; i++)
+ if (name && strcmp(name, filesystems[i].name) == 0)
+ return &filesystems[i];
+ return NULL;
+}
+
+void
+plan_part_path(const char *disk, int slot, char *buf, size_t n)
+{
+ size_t len = strlen(disk);
+
+ /* a name that ends in a digit takes a p before the number: nvme0n1p1, mmcblk0p1 */
+ snprintf(buf, n, "%s%s%d", disk, len && isdigit((unsigned char)disk[len - 1]) ? "p" : "", slot + 1);
+}
+
+void
+plan_size(uint64_t bytes, char *buf, size_t n)
+{
+ static const char *units[] = {"B", "KiB", "MiB", "GiB", "TiB"};
+ double v = (double)bytes;
+ int u = 0;
+
+ while (v >= 1024 && u < 4) {
+ v /= 1024;
+ u++;
+ }
+ if (u == 0 || v >= 100)
+ snprintf(buf, n, "%.0f %s", v, units[u]);
+ else
+ snprintf(buf, n, "%.1f %s", v, units[u]);
+}
+
+int
+plan_read_disk(struct plan *p, const char *disk)
+{
+ struct BlockDev dev;
+ int i;
+
+ memset(p, 0, sizeof *p);
+ snprintf(p->disk, sizeof p->disk, "%s", disk);
+ if (blockdev_open(&dev, disk, 0) < 0)
+ return -1;
+ if (label_read(&dev, &p->label) < 0) {
+ blockdev_close(&dev);
+ return -1;
+ }
+ if (p->label.kind == LABEL_NONE)
+ label_init(&p->label, &dev, LABEL_NONE);
+ blockdev_close(&dev);
+ for (i = 0; i < p->label.slots; i++) {
+ struct BlockDev part;
+ char path[PLAN_PATH + 8], type[16] = "", label[64] = "", uuid[64] = "";
+
+ if (!p->label.part[i].used)
+ continue;
+ if (strcmp(p->label.part[i].type, "8200") == 0)
+ snprintf(p->attr[i].found, PLAN_FS, "swap");
+ plan_part_path(disk, i, path, sizeof path);
+ if (blockdev_open(&part, path, 0) < 0)
+ continue;
+ if (blockdev_detect_fs(&part, type, sizeof type, label, sizeof label, uuid, sizeof uuid) == 0) {
+ /* the detector calls ext2, 3 and 4 alike */
+ snprintf(p->attr[i].found, PLAN_FS, "%s", strcmp(type, "ext") == 0 ? "ext4" : type);
+ snprintf(p->attr[i].label, PLAN_LABEL, "%.*s", PLAN_LABEL - 1, label);
+ }
+ blockdev_close(&part);
+ }
+ return 0;
+}
+
+int
+plan_set(struct plan *p, int slot, const char *fs, const char *mount, const char *label, int format)
+{
+ struct plan_part *a;
+ const struct plan_fs *f;
+
+ if (slot < 0 || slot >= p->label.slots || !p->label.part[slot].used)
+ return -EINVAL;
+ f = fs && fs[0] ? plan_filesystem(fs) : NULL;
+ if (fs && fs[0] && !f)
+ return -EINVAL;
+ if (label && f && strlen(label) > (size_t)f->max_label)
+ return -EINVAL;
+ a = &p->attr[slot];
+ snprintf(a->fs, sizeof a->fs, "%s", fs ? fs : "");
+ snprintf(a->mount, sizeof a->mount, "%s", mount ? mount : "");
+ snprintf(a->label, sizeof a->label, "%s", label ? label : "");
+ a->format = f ? format : 0;
+ return 0;
+}
+
+int
+plan_add(struct plan *p, uint64_t start, uint64_t sectors, const char *type, const char *name, const char *fs,
+ const char *mount, const char *label)
+{
+ int slot = label_add(&p->label, start, sectors, type, name);
+
+ if (slot < 0)
+ return slot;
+ memset(&p->attr[slot], 0, sizeof p->attr[slot]);
+ /* a new partition's filesystem is made: nothing is on it */
+ if (plan_set(p, slot, fs, mount, label, 1) < 0) {
+ label_delete(&p->label, slot);
+ return -EINVAL;
+ }
+ return slot;
+}
+
+int
+plan_delete(struct plan *p, int slot)
+{
+ int rc = label_delete(&p->label, slot);
+
+ if (rc == 0)
+ memset(&p->attr[slot], 0, sizeof p->attr[slot]);
+ return rc;
+}
+
+static int
+fail(char *why, size_t n, const char *fmt, const char *a)
+{
+ snprintf(why, n, fmt, a ? a : "");
+ return -1;
+}
+
+int
+plan_check(const struct plan *p, unsigned need, char *why, size_t n)
+{
+ int i, j, root = 0, esp = 0, bios = 0;
+
+ for (i = 0; i < p->label.slots; i++) {
+ const struct plan_part *a = &p->attr[i];
+ const struct label_part *l = &p->label.part[i];
+ const struct plan_fs *f = plan_filesystem(a->fs);
+
+ if (!l->used)
+ continue;
+ if (a->mount[0] && a->mount[0] != '/')
+ return fail(why, n, "%s is not a place to mount: it starts with a /", a->mount);
+ if (a->mount[0] && !a->fs[0])
+ return fail(why, n, "%s needs a filesystem", a->mount);
+ if (a->mount[0] && f && !f->mount_as)
+ return fail(why, n, "%s cannot be mounted: it is swap", a->mount);
+ for (j = i + 1; j < p->label.slots; j++)
+ if (p->label.part[j].used && a->mount[0] && strcmp(a->mount, p->attr[j].mount) == 0)
+ return fail(why, n, "two partitions are mounted at %s", a->mount);
+ if (strcmp(a->mount, "/") == 0) {
+ if (!f || !f->bootable)
+ return fail(why, n, "%s", "the system cannot start from the filesystem at /");
+ root = 1;
+ }
+ if (strcmp(a->mount, "/boot/efi") == 0 && strcmp(l->type, "ef00") == 0 && strcmp(a->fs, "vfat") == 0)
+ esp = 1;
+ if (strcmp(l->type, "ef02") == 0)
+ bios = 1;
+ }
+ if ((need & PLAN_NEED_ROOT) && !root)
+ return fail(why, n, "%s", "no partition is mounted at /");
+ if ((need & PLAN_NEED_BOOT) && !esp && !bios)
+ return fail(why, n, "%s", "the machine needs a way to start: an EFI system partition mounted at /boot/efi, or a BIOS boot partition");
+ return 0;
+}
+
+int
+plan_changes(const struct plan *before, const struct plan *now, void (*fn)(const char *line, void *arg), void *arg)
+{
+ char line[256], dev[PLAN_PATH + 8], size[32];
+ int i, n = 0;
+
+ struct plan *none = NULL;
+
+ /* a table of another kind replaces the one there: all it held is gone, all the new one holds is made */
+ if (before->label.kind != now->label.kind) {
+ if (before->label.kind != LABEL_NONE) {
+ snprintf(line, sizeof line, "write a new %s partition table on %s, every partition on it is lost",
+ now->label.kind == LABEL_GPT ? "GPT" : "MBR", now->disk);
+ if (fn)
+ fn(line, arg);
+ n++;
+ }
+ if (!(none = calloc(1, sizeof *none)))
+ return n;
+ none->label.slots = now->label.slots;
+ before = none;
+ }
+ for (i = 0; i < now->label.slots; i++) {
+ const struct label_part *a = &before->label.part[i], *b = &now->label.part[i];
+ const struct plan_part *x = &before->attr[i], *y = &now->attr[i];
+ int same = a->used && b->used && a->start == b->start && a->end == b->end &&
+ strcmp(a->type, b->type) == 0;
+
+ plan_part_path(now->disk, i, dev, sizeof dev);
+ if (a->used && !same) {
+ snprintf(line, sizeof line, "delete %s (%s)", dev, label_type_name(a));
+ if (fn)
+ fn(line, arg);
+ n++;
+ }
+ if (b->used && !same) {
+ plan_size((b->end - b->start + 1) * now->label.sec_size, size, sizeof size);
+ snprintf(line, sizeof line, "create %s, %s", dev, size);
+ if (fn)
+ fn(line, arg);
+ n++;
+ }
+ if (b->used && y->format && y->fs[0]) {
+ snprintf(line, sizeof line, "format %s as %s%s%s", dev, y->fs, y->label[0] ? " labelled " : "", y->label);
+ if (fn)
+ fn(line, arg);
+ n++;
+ } else if (b->used && same && strcmp(x->mount, y->mount) != 0 && y->mount[0]) {
+ snprintf(line, sizeof line, "use %s at %s", dev, y->mount);
+ if (fn)
+ fn(line, arg);
+ n++;
+ }
+ }
+ free(none);
+ return n;
+}
+
+int
+plan_write_table(const struct plan *p)
+{
+ struct BlockDev dev;
+ int rc;
+
+ if (blockdev_open(&dev, p->disk, 1) < 0)
+ return -1;
+ rc = label_write(&dev, &p->label);
+ blockdev_close(&dev);
+ return rc;
+}
+
+/* the words of the command that makes a filesystem, each with its place in store */
+static int
+put(char **argv, int *n, int max, char *store, size_t store_n, size_t *used, const char *word)
+{
+ size_t len = strlen(word) + 1;
+
+ if (*n + 1 >= max || *used + len > store_n)
+ return -1;
+ memcpy(store + *used, word, len);
+ argv[(*n)++] = store + *used;
+ *used += len;
+ argv[*n] = NULL;
+ return 0;
+}
+
+int
+plan_mkfs_argv(const struct plan *p, int slot, char **argv, int max, char *store, size_t store_n)
+{
+ const struct plan_part *a = &p->attr[slot];
+ char dev[PLAN_PATH + 8];
+ size_t used = 0;
+ int n = 0, rc = 0;
+
+ if (slot < 0 || slot >= p->label.slots || !p->label.part[slot].used || !a->fs[0])
+ return -1;
+ plan_part_path(p->disk, slot, dev, sizeof dev);
+ if (max < 1)
+ return -1;
+ argv[0] = NULL;
+ if (strcmp(a->fs, "ext4") == 0) {
+ rc |= put(argv, &n, max, store, store_n, &used, "mkfs.ext4");
+ rc |= put(argv, &n, max, store, store_n, &used, "-F");
+ if (a->label[0]) {
+ rc |= put(argv, &n, max, store, store_n, &used, "-L");
+ rc |= put(argv, &n, max, store, store_n, &used, a->label);
+ }
+ } else if (strcmp(a->fs, "f2fs") == 0) {
+ rc |= put(argv, &n, max, store, store_n, &used, "mkfs.f2fs");
+ rc |= put(argv, &n, max, store, store_n, &used, "-f");
+ if (a->label[0]) {
+ rc |= put(argv, &n, max, store, store_n, &used, "-l");
+ rc |= put(argv, &n, max, store, store_n, &used, a->label);
+ }
+ } else if (strcmp(a->fs, "vfat") == 0) {
+ rc |= put(argv, &n, max, store, store_n, &used, "mkfs.fat");
+ rc |= put(argv, &n, max, store, store_n, &used, "-F");
+ rc |= put(argv, &n, max, store, store_n, &used, "32");
+ if (a->label[0]) {
+ rc |= put(argv, &n, max, store, store_n, &used, "-n");
+ rc |= put(argv, &n, max, store, store_n, &used, a->label);
+ }
+ } else if (strcmp(a->fs, "swap") == 0) {
+ rc |= put(argv, &n, max, store, store_n, &used, "mkswap");
+ if (a->label[0]) {
+ rc |= put(argv, &n, max, store, store_n, &used, "-L");
+ rc |= put(argv, &n, max, store, store_n, &used, a->label);
+ }
+ } else
+ return -1;
+ rc |= put(argv, &n, max, store, store_n, &used, dev);
+ return rc ? -1 : 0;
+}
+
+int
+plan_save(const struct plan *p, FILE *f)
+{
+ int i;
+
+ fprintf(f, "disk %s\nlabel %s\n", p->disk, p->label.kind == LABEL_GPT ? "gpt" : p->label.kind == LABEL_MBR ? "mbr" : "none");
+ for (i = 0; i < p->label.slots; i++) {
+ const struct label_part *l = &p->label.part[i];
+ const struct plan_part *a = &p->attr[i];
+
+ if (!l->used)
+ continue;
+ fprintf(f, "part %d start=%llu sectors=%llu type=%s", i + 1, (unsigned long long)l->start,
+ (unsigned long long)(l->end - l->start + 1), l->type[0] ? l->type : "8300");
+ if (l->name[0])
+ fprintf(f, " name=%s", l->name);
+ if (a->fs[0])
+ fprintf(f, " fs=%s", a->fs);
+ if (a->mount[0])
+ fprintf(f, " mount=%s", a->mount);
+ if (a->label[0])
+ fprintf(f, " label=%s", a->label);
+ if (a->format)
+ fprintf(f, " format=yes");
+ fputc('\n', f);
+ }
+ return ferror(f) ? -1 : 0;
+}
+
+static int
+bad(char *why, size_t n, const char *line)
+{
+ snprintf(why, n, "not a line of a plan: %.60s", line);
+ return -1;
+}
+
+int
+plan_load(struct plan *p, FILE *f, char *why, size_t n)
+{
+ char line[512];
+ struct BlockDev dev;
+
+ memset(p, 0, sizeof *p);
+ p->label.slots = 0;
+ while (fgets(line, sizeof line, f)) {
+ char *nl = strchr(line, '\n'), *word, *save = NULL;
+
+ if (nl)
+ *nl = '\0';
+ if (!line[0] || line[0] == '#')
+ continue;
+ if (strncmp(line, "disk ", 5) == 0) {
+ snprintf(p->disk, sizeof p->disk, "%s", line + 5);
+ } else if (strncmp(line, "label ", 6) == 0) {
+ enum label_kind kind = strcmp(line + 6, "gpt") == 0 ? LABEL_GPT : strcmp(line + 6, "mbr") == 0 ? LABEL_MBR : LABEL_NONE;
+
+ /* the table's geometry comes from the disk it is for */
+ if (kind == LABEL_NONE || !p->disk[0] || blockdev_open(&dev, p->disk, 0) < 0 || label_init(&p->label, &dev, kind) < 0)
+ return bad(why, n, line);
+ blockdev_close(&dev);
+ } else if (strncmp(line, "part ", 5) == 0) {
+ uint64_t start = 0, sectors = 0;
+ char type[8] = "8300", name[40] = "", fs[PLAN_FS] = "", mount[PLAN_MOUNT] = "", label[PLAN_LABEL] = "";
+ int format = 0, index = (int)strtol(line + 5, &word, 10);
+
+ if (p->label.kind == LABEL_NONE || index < 1 || index > p->label.slots)
+ return bad(why, n, line);
+ for (word = strtok_r(word, " ", &save); word; word = strtok_r(NULL, " ", &save)) {
+ if (strncmp(word, "start=", 6) == 0)
+ start = strtoull(word + 6, NULL, 10);
+ else if (strncmp(word, "sectors=", 8) == 0)
+ sectors = strtoull(word + 8, NULL, 10);
+ else if (strncmp(word, "type=", 5) == 0)
+ snprintf(type, sizeof type, "%s", word + 5);
+ else if (strncmp(word, "name=", 5) == 0)
+ snprintf(name, sizeof name, "%s", word + 5);
+ else if (strncmp(word, "fs=", 3) == 0)
+ snprintf(fs, sizeof fs, "%s", word + 3);
+ else if (strncmp(word, "mount=", 6) == 0)
+ snprintf(mount, sizeof mount, "%s", word + 6);
+ else if (strncmp(word, "label=", 6) == 0)
+ snprintf(label, sizeof label, "%s", word + 6);
+ else if (strcmp(word, "format=yes") == 0)
+ format = 1;
+ else
+ return bad(why, n, line);
+ }
+ /* a plan names the slots, so a partition goes where it says */
+ if (start == 0 || p->label.part[index - 1].used)
+ return bad(why, n, line);
+ {
+ int slot = label_add(&p->label, start, sectors, type, name);
+
+ if (slot < 0)
+ return bad(why, n, line);
+ if (slot != index - 1) {
+ p->label.part[index - 1] = p->label.part[slot];
+ memset(&p->label.part[slot], 0, sizeof p->label.part[slot]);
+ slot = index - 1;
+ }
+ if (plan_set(p, slot, fs, mount, label, format) < 0)
+ return bad(why, n, line);
+ }
+ } else
+ return bad(why, n, line);
+ }
+ return p->disk[0] ? 0 : (snprintf(why, n, "a plan names a disk"), -1);
+}
diff --git a/shared/libdisk/plan.h b/shared/libdisk/plan.h
@@ -0,0 +1,94 @@
+/* see LICENSE file for copyright and license details */
+#ifndef ARUU_LIBDISK_PLAN_H
+#define ARUU_LIBDISK_PLAN_H
+
+/* a disk as someone means it to be: its partition table, and for each
+ * partition the filesystem it is to hold, where that is mounted, its label
+ * and whether it is made fresh. what a partitioner edits, an installer is
+ * handed, and a file says (plan_save, plan_load), so each of them is the
+ * same thing in the same words.
+ *
+ * the file is text, a line each:
+ *
+ * disk /dev/vda
+ * label gpt
+ * part 1 start=2048 sectors=2048 type=ef02 name=BIOS
+ * part 2 start=4096 sectors=1048576 type=ef00 name=ESP fs=vfat mount=/boot/efi format=yes
+ * part 3 start=1052672 sectors=0 type=8300 name=ROOT fs=ext4 mount=/ format=yes
+ *
+ * sectors=0 is what is left of the disk. nothing here writes a disk but
+ * plan_write_table, and what it makes of the filesystems is the argv
+ * plan_mkfs_argv gives, for the caller to run */
+
+#include "label.h"
+
+#include <stdio.h>
+
+#define PLAN_PATH 128
+#define PLAN_FS 16
+#define PLAN_MOUNT 64
+#define PLAN_LABEL 32
+
+struct plan_part {
+ char fs[PLAN_FS]; /* what it is to hold: a name of plan_filesystems, "" for none */
+ char mount[PLAN_MOUNT]; /* where it is mounted in the installed system, "" for nowhere */
+ char label[PLAN_LABEL]; /* the filesystem's label */
+ int format; /* the filesystem is made, else what is there is kept */
+ char found[PLAN_FS]; /* what is on it now, "" when nothing is known */
+};
+
+struct plan {
+ char disk[PLAN_PATH];
+ struct label label;
+ struct plan_part attr[LABEL_SLOTS];
+};
+
+/* the filesystems a partition can hold */
+struct plan_fs {
+ const char *name;
+ const char *title; /* for a person */
+ const char *mount_as; /* the type the system mounts it as, NULL for none (swap) */
+ int bootable; /* a root filesystem the system can start from */
+ int max_label;
+};
+const struct plan_fs *plan_filesystems(int *n);
+const struct plan_fs *plan_filesystem(const char *name);
+
+/* the device of partition slot (0 based) of disk: /dev/vda1, /dev/nvme0n1p1 */
+void plan_part_path(const char *disk, int slot, char *buf, size_t n);
+
+/* disk read: its table, and what is on each partition. a disk with none is an
+ * empty plan of no table. -1 when it cannot be read */
+int plan_read_disk(struct plan *p, const char *disk);
+
+/* the partition's attributes set. false for a filesystem not known or a label too long */
+int plan_set(struct plan *p, int slot, const char *fs, const char *mount, const char *label, int format);
+/* label_add, with what it is to hold: the slot or a negative errno */
+int plan_add(struct plan *p, uint64_t start, uint64_t sectors, const char *type, const char *name, const char *fs,
+ const char *mount, const char *label);
+int plan_delete(struct plan *p, int slot);
+
+/* what the plan needs to be installed to: the checks asked for */
+#define PLAN_NEED_ROOT 1 /* a partition mounted at /, of a filesystem to start from */
+#define PLAN_NEED_BOOT 2 /* a way for the machine to start: an EFI system partition at /boot/efi or a BIOS boot one */
+/* 0 when the plan holds, else -1 and why, in words for a person */
+int plan_check(const struct plan *p, unsigned need, char *why, size_t n);
+
+/* what applying now would do over before, a line each (fn may be NULL to count), to read before it is done
+ * ("delete /dev/vda2", "create 512 MiB EFI system", "format /dev/vda3 as ext4"). how many */
+int plan_changes(const struct plan *before, const struct plan *now, void (*fn)(const char *line, void *arg), void *arg);
+
+/* the table written to the disk, the filesystems left for the caller */
+int plan_write_table(const struct plan *p);
+/* the command that makes the filesystem of slot: its argv into argv (at most max words,
+ * NULL ended) whose words are held in store. 0, -1 when the slot has no filesystem to make */
+int plan_mkfs_argv(const struct plan *p, int slot, char **argv, int max, char *store, size_t store_n);
+
+int plan_save(const struct plan *p, FILE *f);
+/* a plan read: -1 with why for a line that is not one */
+int plan_load(struct plan *p, FILE *f, char *why, size_t n);
+
+/* a size for a person, "512 MiB" */
+void plan_size(uint64_t bytes, char *buf, size_t n);
+
+#endif
diff --git a/shared/libdisk/plan_test.c b/shared/libdisk/plan_test.c
@@ -0,0 +1,35 @@
+/* see LICENSE file for copyright and license details */
+/* a plan made on an image, checked, written, saved and read again:
+ * cc -D_GNU_SOURCE -Ishared shared/libdisk/plan_test.c shared/libdisk/plan.c shared/libdisk/label.c \
+ * shared/libdisk/gpt.c shared/libutil/diskutil.c shared/libutil/hexval.c shared/libutil/eprintf.c \
+ * shared/libutil/ealloc.c shared/libutil/strlcpy.c -o plan_test && ./plan_test */
+#include "plan.h"
+#include <assert.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+static int nlines; static void line(const char *l, void *a){ (void)a; nlines++; puts(l); }
+int main(void){
+ char path[]="/tmp/plan_test.XXXXXX"; int fd=mkstemp(path); assert(fd>=0 && ftruncate(fd,(off_t)256<<20)==0); close(fd);
+ struct plan before, p; char why[200]; char *argv[16]; char store[256];
+ assert(plan_read_disk(&before,path)==0 && before.label.kind==LABEL_NONE);
+ p=before;
+ { struct BlockDev d; assert(blockdev_open(&d,path,0)==0); assert(label_init(&p.label,&d,LABEL_GPT)==0); blockdev_close(&d); }
+ assert(plan_check(&p,PLAN_NEED_ROOT,why,sizeof why)<0);
+ assert(plan_add(&p,0,2048,"ef02","BIOS","","","")==0);
+ assert(plan_add(&p,0,64*2048,"ef00","ESP","vfat","/boot/efi","ESP")==1);
+ assert(plan_add(&p,0,0,"8300","ROOT","ext4","/","")==2);
+ assert(plan_check(&p,PLAN_NEED_ROOT|PLAN_NEED_BOOT,why,sizeof why)==0);
+ assert(plan_changes(&before,&p,line,NULL)>=3);
+ assert(plan_mkfs_argv(&p,2,argv,16,store,sizeof store)==0 && !strcmp(argv[0],"mkfs.ext4") && !strcmp(argv[1],"-F"));
+ assert(argv[2] && argv[3] == NULL);
+ assert(plan_write_table(&p)==0);
+ FILE *f=tmpfile(); assert(plan_save(&p,f)==0); rewind(f);
+ struct plan q; assert(plan_load(&q,f,why,sizeof why)==0);
+ for(int i=0;i<3;i++){ assert(q.label.part[i].start==p.label.part[i].start && q.label.part[i].end==p.label.part[i].end); assert(!strcmp(q.attr[i].fs,p.attr[i].fs)&&!strcmp(q.attr[i].mount,p.attr[i].mount)); }
+ struct plan r; assert(plan_read_disk(&r,path)==0 && r.label.kind==LABEL_GPT && r.label.part[2].used);
+ p.attr[1].mount[0]='x'; assert(plan_check(&p,0,why,sizeof why)<0); puts(why);
+ plan_set(&p,1,"vfat","/",NULL,1); assert(plan_check(&p,0,why,sizeof why)<0); puts(why);
+ unlink(path); puts("plan_test: ok"); return 0; }