Home | History | Annotate | Line # | Download | only in efi
gptsubr.c revision 1.1
      1 /* $NetBSD: gptsubr.c,v 1.1 2025/02/24 13:47:56 christos Exp $ */
      2 
      3 /*
      4  * Redistribution and use in source and binary forms, with or without
      5  * modification, are permitted provided that the following conditions
      6  * are met:
      7  * 1. Redistributions of source code must retain the above copyright
      8  *    notice, this list of conditions and the following disclaimer.
      9  * 2. Redistributions in binary form must reproduce the above copyright
     10  *    notice, this list of conditions and the following disclaimer in the
     11  *    documentation and/or other materials provided with the distribution.
     12  *
     13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
     14  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     15  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     16  * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
     19  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     23  * SUCH DAMAGE.
     24  */
     25 
     26 #include <sys/cdefs.h>
     27 #ifndef lint
     28 __RCSID("$NetBSD: gptsubr.c,v 1.1 2025/02/24 13:47:56 christos Exp $");
     29 #endif /* not lint */
     30 
     31 #include <sys/param.h>
     32 
     33 #include <sys/disk.h>
     34 #include <sys/disklabel.h>
     35 #include <sys/disklabel_gpt.h>
     36 #include <sys/dkio.h>
     37 #include <sys/ioctl.h>
     38 #include <sys/stat.h>
     39 #include <sys/statvfs.h>
     40 
     41 #include <err.h>
     42 #include <fcntl.h>
     43 #include <libgen.h>
     44 #include <paths.h>
     45 #include <stdbool.h>
     46 #include <stdio.h>
     47 #include <stdlib.h>
     48 #include <unistd.h>
     49 #include <uuid.h>
     50 
     51 #include "defs.h"
     52 #include "gpt.h"
     53 #include "gptsubr.h"
     54 #include "map.h"
     55 
     56 #define DEBUG
     57 
     58 #ifdef DEBUG
     59 #define DPRINTF(fmt, ...)	printf(fmt, __VA_ARGS__)
     60 #else
     61 #define DPRINTF(fmt, ...)	do { } while (/*CONSTCOND*/0)
     62 #endif
     63 
     64 static const char *
     65 map_type_name(int map_type)
     66 {
     67 	const char *xtbl[] = {
     68 		"UNUSED",	// 0
     69 		"MBR",		// 1
     70 		"MBR_PART",	// 2
     71 		"PRI_GPT_HDR",	// 3
     72 		"SEC_GPT_HDR",	// 4
     73 		"PRI_GPT_TBL",	// 5
     74 		"SEC_GPT_TBL",	// 6
     75 		"GPT_PART",	// 7
     76 		"PMBR",		// 8
     77 	};
     78 
     79 	if (map_type >= (int)__arraycount(xtbl))
     80 		return "UNKNOWN";
     81 
     82 	return xtbl[map_type];
     83 }
     84 
     85 #if 0
     86 struct map {
     87 	off_t	map_start;
     88 	off_t	map_size;
     89 	struct map *map_next;
     90 	struct map *map_prev;
     91 	int	map_type;
     92 #define	MAP_TYPE_UNUSED		0
     93 #define	MAP_TYPE_MBR		1
     94 #define	MAP_TYPE_MBR_PART	2
     95 #define	MAP_TYPE_PRI_GPT_HDR	3
     96 #define	MAP_TYPE_SEC_GPT_HDR	4
     97 #define	MAP_TYPE_PRI_GPT_TBL	5
     98 #define	MAP_TYPE_SEC_GPT_TBL	6
     99 #define	MAP_TYPE_GPT_PART	7
    100 #define	MAP_TYPE_PMBR		8
    101 	unsigned int map_index;
    102 	void 	*map_data;
    103 	int	map_alloc;
    104 };
    105 
    106 struct gpt_ent {
    107 	uint8_t		ent_type[16];	/* partition type GUID */
    108 	uint8_t		ent_guid[16];	/* unique partition GUID */
    109 	uint64_t	ent_lba_start;	/* start of partition */
    110 	uint64_t	ent_lba_end;	/* end of partition */
    111 	uint64_t	ent_attr;	/* partition attributes */
    112 	uint16_t	ent_name[36];	/* partition name in UCS-2 */
    113 };
    114 
    115 struct gpt_hdr {
    116 	int8_t		hdr_sig[8];	/* identifies GUID Partition Table */
    117 	uint32_t	hdr_revision;	/* GPT specification revision */
    118 	uint32_t	hdr_size;	/* size of GPT Header */
    119 	uint32_t	hdr_crc_self;	/* CRC32 of GPT Header */
    120 	uint32_t	hdr__rsvd0;	/* must be zero */
    121 	uint64_t	hdr_lba_self;	/* LBA that contains this Header */
    122 	uint64_t	hdr_lba_alt;	/* LBA of backup GPT Header */
    123 	uint64_t	hdr_lba_start;	/* first LBA usable for partitions */
    124 	uint64_t	hdr_lba_end;	/* last LBA usable for partitions */
    125 	uint8_t		hdr_guid[16];	/* GUID to identify the disk */
    126 	uint64_t	hdr_lba_table;	/* first LBA of GPE array */
    127 	uint32_t	hdr_entries;	/* number of entries in GPE array */
    128 	uint32_t	hdr_entsz;	/* size of each GPE */
    129 	uint32_t	hdr_crc_table;	/* CRC32 of GPE array */
    130 	/*
    131 	 * The remainder of the block that contains the GPT Header
    132 	 * is reserved by EFI for future GPT Header expansion, and
    133 	 * must be zero.
    134 	 */
    135 };
    136 #endif
    137 
    138 struct map_widths {
    139 	uint start;
    140 	uint size;
    141 	uint type_name;
    142 };
    143 
    144 static struct map_widths
    145 get_map_widths(gpt_t gpt)
    146 {
    147 	struct map_widths w;
    148 	off_t max_start = 0;
    149 	off_t max_size = 0;
    150 	map_t m;
    151 
    152 	w.type_name = 0;
    153 	for (m = map_first(gpt); m != NULL; m = m->map_next) {
    154 		uint n;
    155 
    156 		if (max_start < m->map_start)
    157 			max_start = m->map_start;
    158 		if (max_size < m->map_size)
    159 			max_size = m->map_size;
    160 		if (m->map_type == MAP_TYPE_GPT_PART) {
    161 			struct gpt_ent *ent = m->map_data;
    162 			gpt_uuid_t gpt_uuid;
    163 			char ent_type[128];
    164 
    165 			memcpy(&gpt_uuid, ent->ent_type, sizeof(gpt_uuid));
    166 			n = (uint)gpt_uuid_snprintf(ent_type, sizeof(ent_type), "%s", gpt_uuid);
    167 			if (w.type_name < n)
    168 				w.type_name = n;
    169 		}
    170 
    171 	}
    172 	w.start = (uint)snprintf(NULL, 0, "%zx", max_start);
    173 	w.size = (uint)snprintf(NULL, 0, "%zx", max_size);
    174 
    175 #define MIN_WIDTH_OF(s)	(sizeof(s) - 1)
    176 	if (w.type_name < MIN_WIDTH_OF("TYPE_NAME"))
    177 		w.type_name = MIN_WIDTH_OF("TYPE_NAME");
    178 	if (w.start < MIN_WIDTH_OF("START"))
    179 		w.start = MIN_WIDTH_OF("START");
    180 	if (w.size < MIN_WIDTH_OF("SIZE"))
    181 		w.size = MIN_WIDTH_OF("SIZE");
    182 #undef MIN_WIDTH_OF
    183 
    184 	return w;
    185 }
    186 
    187 static void
    188 show_map_banner(struct map_widths w)
    189 {
    190 
    191 	printf("IDX %*s %*s   ATTR            PARTITION_GUID"
    192 	    "                         TYPE_UUID       %*s "
    193 	    "TYPE_NAME ENTRY_NAME  DESCRIPTION\n",
    194 	    w.start, "START",
    195 	    w.size, "SIZE",
    196 	    w.type_name, "");
    197 }
    198 
    199 static void
    200 show_map(map_t m, struct map_widths w)
    201 {
    202 	struct gpt_ent *ent;
    203 	struct gpt_hdr *hdr;
    204 	gpt_uuid_t gpt_uuid;
    205 	uuid_t uuid;
    206 	uint32_t status;
    207 	char *type_uuid;
    208 	char *part_guid;
    209 	uint64_t ent_attr;
    210 	uint8_t  ent_desc[128];
    211 	char     ent_type[128];
    212 
    213 	ent_desc[0] = '\0';
    214 	ent_type[0] = '\0';
    215 	ent_attr = 0;
    216 
    217 	switch (m->map_type) {
    218 	case MAP_TYPE_PRI_GPT_HDR:
    219 	case MAP_TYPE_SEC_GPT_HDR:
    220 		hdr = m->map_data;
    221 		memcpy(&uuid, hdr->hdr_guid, sizeof(uuid));
    222 		uuid_to_string(&uuid, &part_guid, &status);
    223 		type_uuid = estrdup("");
    224 		break;
    225 
    226 	case MAP_TYPE_GPT_PART:
    227 		ent = m->map_data;
    228 
    229 		memcpy(&uuid, ent->ent_type, sizeof(uuid));
    230 		uuid_to_string(&uuid, &type_uuid, &status);
    231 
    232 		memcpy(&uuid, ent->ent_guid, sizeof(uuid));
    233 		uuid_to_string(&uuid, &part_guid, &status);
    234 
    235 		ent_attr = ent->ent_attr;
    236 
    237 		memcpy(&gpt_uuid, ent->ent_type, sizeof(uuid));
    238 		gpt_uuid_snprintf(ent_type, sizeof(ent_type), "%s", gpt_uuid);
    239 
    240 		/*
    241 		 * Use the gpt.c code here rather than our
    242 		 * ucs2_to_utf8() as we are in their world.
    243 		 */
    244 		utf16_to_utf8(ent->ent_name, sizeof(ent->ent_name),
    245 		    ent_desc, sizeof(ent_desc));
    246 
    247 		break;
    248 
    249 	case MAP_TYPE_MBR_PART:
    250 		part_guid = estrdup("");
    251 		type_uuid = estrdup("");
    252 		break;
    253 
    254 	case MAP_TYPE_MBR: {
    255 		struct mbr *mbr = m->map_data;
    256 
    257 		easprintf(&part_guid, "%02x%02x%02x%02x-0000-0000-0000-000000000000",
    258 		    mbr->mbr_code[440],
    259 		    mbr->mbr_code[441],
    260 		    mbr->mbr_code[442],
    261 		    mbr->mbr_code[443]);
    262 		uuid_to_string(&(uuid_t)GPT_ENT_TYPE_MBR, &type_uuid, &status);
    263 		break;
    264 	}
    265 	default:
    266 		part_guid = estrdup("");
    267 		type_uuid = estrdup("");
    268 		break;
    269 	}
    270 
    271 	printf("%2u: %*lx %*lx %08lx %36s %36s %*s %-11s %s\n",
    272 	    m->map_index,
    273 	    w.start,
    274 	    m->map_start,
    275 	    w.size,
    276 	    m->map_size,
    277 	    ent_attr,
    278 	    part_guid,
    279 	    type_uuid,
    280 	    w.type_name,
    281 	    ent_type,
    282 	    map_type_name(m->map_type),
    283 	    ent_desc);
    284 
    285 	free(part_guid);
    286 	free(type_uuid);
    287 }
    288 
    289 PUBLIC map_t
    290 find_gpt_map(const char *dev, uint idx)
    291 {
    292 	gpt_t gpt;
    293 	map_t m;
    294 
    295 	gpt = gpt_open(dev, GPT_READONLY, 0, 0, 0, 0);
    296 
    297 	if (gpt == NULL)
    298 		err(EXIT_FAILURE, "gpt_open");
    299 
    300 	if (map_find(gpt, MAP_TYPE_PRI_GPT_HDR) == NULL)
    301 		printf("GPT not found, displaying data from MBR.\n");
    302 
    303 	for (m = map_first(gpt); m != NULL; m = m->map_next) {
    304 		if (m->map_index == idx)
    305 			break;
    306 	}
    307 	gpt_close(gpt);
    308 	return m;
    309 }
    310 
    311 PUBLIC char *
    312 parent_of_fname(const char *fname)
    313 {
    314 	struct dkwedge_info dkinfo;
    315 	struct statvfs vfsb;
    316 	struct stat sb;
    317 	const char *d, *b;
    318 	char *p;
    319 	size_t n;
    320 	int fd, rv;
    321 
    322 	rv = stat(fname, &sb);
    323 	if (rv == -1)
    324 		err(EXIT_FAILURE, "stat: %s", fname);
    325 
    326 	if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode))
    327 		return estrdup(fname);
    328 
    329 	rv = statvfs(fname, &vfsb);
    330 	if (rv == -1)
    331 		err(EXIT_FAILURE, "statvfs: %s", fname);
    332 
    333 	b = basename(vfsb.f_mntfromname);
    334 	d = dirname(vfsb.f_mntfromname);
    335 	easprintf(&p, "%s/r%s", d, b);
    336 
    337 	fd = open(p, O_RDONLY);
    338 	if (fd == -1)
    339 		err(EXIT_FAILURE, "open");
    340 
    341 	rv = ioctl(fd, DIOCGWEDGEINFO, &dkinfo);
    342 	close(fd);
    343 
    344 	if (rv != -1) {
    345 		free(p);
    346 		return estrdup(dkinfo.dkw_parent);
    347 	}
    348 
    349 	warn("ioctl: DIOCGWEDGEINFO");
    350 
    351 	/*
    352 	 * Hum.  No wedges?  Assume we have the old disklabel
    353 	 * "/dev/rwd0x" syntax.  Convert it to "/dev/rwd0d".
    354 	 * XXX: this probably won't work.
    355 	 */
    356 	n = strlen(p);
    357 	p[n - 1] = 'd';
    358 
    359 	return p;
    360 }
    361 
    362 PUBLIC int
    363 mbr_sig_write(const char *fname, uint32_t new_sig, bool force, int verbose)
    364 {
    365 	gpt_t gpt;
    366 	map_t m;
    367 	struct mbr *mbr;
    368 	const char *dev;
    369 	uint32_t old_sig;
    370 
    371 	if (fname == NULL)
    372 		errx(EXIT_FAILURE, "please specify a device");
    373 
    374 	dev = parent_of_fname(fname);
    375 	if (dev == NULL) {
    376 		warnx("unable to find parent device of %s\n", fname);
    377 		return -1;
    378 	}
    379 
    380 	gpt = gpt_open(dev, GPT_MODIFIED, verbose, 0, 0, 0);
    381 
    382 	if (gpt == NULL)
    383 		err(EXIT_FAILURE, "gpt_open");
    384 
    385 	m = map_find(gpt, MAP_TYPE_MBR);
    386 	if (m == NULL)
    387 		printf("No MBR partition found!\n");
    388 	else {
    389 		mbr = m->map_data;
    390 
    391 		memcpy(&old_sig, &mbr->mbr_code[440], 4);
    392 
    393 		if (old_sig == 0)
    394 			force = true;
    395 
    396 		if (force) {
    397 			memcpy(&mbr->mbr_code[440], &new_sig, 4);
    398 			if (gpt_write(gpt, m) == -1)
    399 				warn("gpt_write");
    400 			else if (verbose)
    401 				printf("sig: 0x%08x -> 0x%08x\n",
    402 				    old_sig, new_sig);
    403 		}
    404 		else if (verbose)
    405 			printf("sig: 0x%08x (unchanged)\n", old_sig);
    406 	}
    407 
    408 	gpt_close(gpt);
    409 	return 0;
    410 }
    411 
    412 PUBLIC int
    413 show_gpt(const char *fname, int verbose)
    414 {
    415 	gpt_t gpt;
    416 	map_t m;
    417 	struct map_widths w;
    418 	const char *dev;
    419 
    420 	dev = parent_of_fname(fname);
    421 	if (dev == NULL)
    422 		return -1;
    423 
    424 	gpt = gpt_open(dev, GPT_READONLY, verbose, 0, 0, 0);
    425 
    426 	if (gpt == NULL)
    427 		err(EXIT_FAILURE, "gpt_open");
    428 
    429 	if (map_find(gpt, MAP_TYPE_PRI_GPT_HDR) == NULL)
    430 		warnx("GPT not found, displaying data from MBR.");
    431 
    432 	w = get_map_widths(gpt);
    433 	show_map_banner(w);
    434 
    435 	for (m = map_first(gpt); m != NULL; m = m->map_next)
    436 		show_map(m, w);
    437 
    438 	gpt_close(gpt);
    439 	return 0;
    440 }
    441 
    442 #if 0 /* UNUSED */
    443 
    444 PUBLIC char *
    445 wedge_of_fname(const char *fname)
    446 {
    447 	struct statvfs vfsbuf;
    448 	int rv;
    449 
    450 	rv = statvfs(fname, &vfsbuf);
    451 	if (rv) {
    452 		warn("statvfs: %s", fname);
    453 		return NULL;
    454 	}
    455 
    456 	return estrdup(vfsbuf.f_mntfromname);
    457 }
    458 
    459 PUBLIC int
    460 find_partition_idx(const char *fname, int verbose)
    461 {
    462 	struct dkwedge_info dkinfo;
    463 	struct stat sb;
    464 	struct statvfs vfsbuf;
    465 	gpt_t gpt;
    466 	map_t m;
    467 	off_t offset;
    468 	size_t size;
    469 	const char *parent;
    470 	char *b, *d;
    471 	int rv;
    472 
    473 	/* the following are for gpt_open() */
    474 	off_t mediasz = 0;
    475 	u_int secsz = 0;
    476 	time_t timestamp = 0;
    477 
    478 	rv = stat(fname, &sb);
    479 	if (rv == -1)
    480 		err(EXIT_FAILURE, "stat: %s", fname);
    481 
    482 	if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) {
    483 		parent = fname;
    484 		offset = 0;
    485 		size = 0;
    486 		goto doit;
    487 	}
    488 
    489 	rv = statvfs(fname, &vfsbuf);
    490 	if (rv == -1)
    491 		err(EXIT_FAILURE, "statvfs: %s", fname);
    492 
    493 	b = basename(vfsbuf.f_mntfromname);
    494 	d = dirname(vfsbuf.f_mntfromname);
    495 
    496 	{
    497 		char *p;
    498 
    499 		easprintf(&p, "%s/r%s", d, b);
    500 
    501 		int fd = open(p, O_RDONLY);
    502 		if (fd == -1)
    503 			err(EXIT_FAILURE, "open");
    504 
    505 		rv = ioctl(fd, DIOCGWEDGEINFO, &dkinfo);
    506 		if (rv != -1) {
    507 			parent = dkinfo.dkw_parent;
    508 			offset = dkinfo.dkw_offset;
    509 			size   = dkinfo.dkw_size;
    510 		}
    511 		else {
    512 			struct disklabel dl;
    513 
    514 			warn("ioctl: DIOCGWEDGEINFO");
    515 
    516 			rv = ioctl(fd, DIOCGDINFO, &dl);
    517 			if (rv == -1)
    518 				err(EXIT_FAILURE, "ioctl: DIOCGDINFO");
    519 
    520 			size_t n = strlen(p);
    521 
    522 			int pnum = p[n - 1] - 'a';
    523 			p[n - 1] = 'd';
    524 
    525 			printf("num_parts: %u\n", dl.d_npartitions);
    526 			printf("partition %d\n", pnum);
    527 			printf("  offset = %u (%#x)\n", dl.d_partitions[pnum].p_offset, dl.d_partitions[pnum].p_offset);
    528 			printf("  size = %u (%#x)\n",   dl.d_partitions[pnum].p_size,   dl.d_partitions[pnum].p_size);
    529 
    530 			parent = p;	// vfsbuf.f_mntfromname;
    531 			offset = dl.d_partitions[pnum].p_offset;
    532 			size   = dl.d_partitions[pnum].p_size;
    533 		}
    534 
    535 		close(fd);
    536 		free(p);
    537 	}
    538 
    539  doit:
    540 	DPRINTF("parent: %s\n", parent);
    541 	DPRINTF("offset: 0x%lx\n", offset);
    542 	DPRINTF("size: 0x%lx\n", size);
    543 
    544 	gpt = gpt_open(parent, GPT_READONLY,
    545 	    verbose, mediasz, secsz, timestamp);
    546 
    547 	if (gpt == NULL)
    548 		err(EXIT_FAILURE, "gpt_open");
    549 
    550 	if (map_find(gpt, MAP_TYPE_PRI_GPT_HDR) == NULL)
    551 		printf("GPT not found, displaying data from MBR.\n");
    552 
    553 	int index = -1;
    554 	struct map_widths w;
    555 	if (verbose) {
    556 		w = get_map_widths(gpt);
    557 		show_map_banner(w);
    558 	}
    559 	for (m = map_first(gpt); m != NULL; m = m->map_next) {
    560 		if (verbose)
    561 			show_map(m, w);
    562 
    563 		if (m->map_type != MAP_TYPE_GPT_PART || m->map_index < 1) {
    564 			continue;
    565 		}
    566 
    567 		if ((off_t)offset == m->map_start &&
    568 		    (off_t)size   == m->map_size) {
    569 			if (index != -1)
    570 				printf("match: %u\n", index);
    571 			index = (int)m->map_index;
    572 		}
    573 	}
    574 	return index;
    575 }
    576 
    577 PUBLIC char *
    578 find_partition_pathname(const char *fname)
    579 {
    580 	char *pname;	/* partition name */
    581 	char *rname;	/* real name */
    582 	struct statvfs vfsbuf;
    583 	int i, rv;
    584 
    585 	rname = realpath(fname, NULL);
    586 
    587 	DPRINTF("fname: %s\n", fname);
    588 	DPRINTF("rname: %s\n", rname);
    589 
    590 	rv = statvfs(rname, &vfsbuf);
    591 	if (rv) {
    592 		warn("statvfs: %s", rname);
    593 		free(rname);
    594 		return NULL;
    595 	}
    596 
    597 	DPRINTF("mount: %s\n", vfsbuf.f_mntonname);
    598 
    599 	i = 0;
    600 	while (vfsbuf.f_mntonname[i] == rname[i] && vfsbuf.f_mntonname[i] != '\0')
    601 		i++;
    602 
    603 	if (vfsbuf.f_mntonname[i] != '\0')
    604 		errx(EXIT_FAILURE, "mntonname mismatch: %s",
    605 		    vfsbuf.f_mntonname + i);
    606 
    607 	pname = estrdup(rname + i);
    608 	free(rname);
    609 
    610 	return pname;
    611 }
    612 
    613 #endif
    614