/*
 * DF-0134 readback — read the in-core disklabel64 via DIOCGDINFO64 and show
 * whether the out-of-slice partition was accepted by the read path.
 *
 * Build: cc -o readback readback.c
 * Run:   ./readback /dev/vnNs0
 */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/disklabel64.h>

int
main(int argc, char **argv)
{
	struct disklabel64 lp;
	int fd, i, leaked = 0;

	if (argc < 2) {
		fprintf(stderr, "usage: %s /dev/vnXs0\n", argv[0]);
		return 2;
	}
	fd = open(argv[1], O_RDONLY);
	if (fd < 0) { perror("open"); return 1; }
	if (ioctl(fd, DIOCGDINFO64, &lp) < 0) { perror("DIOCGDINFO64"); close(fd); return 1; }
	close(fd);

	printf("[*] in-core disklabel64: magic=0x%08x npart=%u "
	       "d_total_size=%llu d_pbase=%llu d_pstop=%llu\n",
	       lp.d_magic, lp.d_npartitions,
	       (unsigned long long)lp.d_total_size, (unsigned long long)lp.d_pbase,
	       (unsigned long long)lp.d_pstop);

	for (i = 0; i < (int)lp.d_npartitions && i < 16; i++) {
		unsigned long long off = lp.d_partitions[i].p_boffset;
		unsigned long long sz  = lp.d_partitions[i].p_bsize;
		unsigned long long end = off + sz;
		int oob = (sz && end > lp.d_total_size);
		leaked |= oob;
		printf("    part[%d]: p_boffset=%-10llu p_bsize=%-12llu end=%-12llu%s\n",
		       i, off, sz, end,
		       oob ? "   *** OUT-OF-SLICE (readdisklabel accepted it!) ***"
		           : "");
	}
	printf(leaked ? "\nRESULT: LEAK_CONFIRMED — in-core label contains a "
		"partition extending beyond d_total_size (readdisklabel has no "
		"structural validation)\n"
	              : "\nRESULT: NO_LEAK — partitions are bounded "
		"(validation present)\n");
	return leaked ? 0 : 1;
}
