+static grub_err_t ventoy_cmd_img_check_range(grub_extcmd_context_t ctxt, int argc, char **args)
+{
+ int i;
+ int ret = 1;
+ grub_file_t file;
+ grub_uint64_t FileSectors = 0;
+ ventoy_gpt_info *gpt = NULL;
+ ventoy_part_table *pt = NULL;
+ grub_uint8_t zeroguid[16] = {0};
+
+ (void)ctxt;
+ (void)argc;
+
+ file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]);
+ if (!file)
+ {
+ debug("failed to open file %s\n", args[0]);
+ return 1;
+ }
+
+ if (file->size % 512)
+ {
+ debug("unaligned file size: %llu\n", (ulonglong)file->size);
+ goto out;
+ }
+
+ gpt = grub_zalloc(sizeof(ventoy_gpt_info));
+ if (!gpt)
+ {
+ goto out;
+ }
+
+ FileSectors = file->size / 512;
+
+ grub_file_read(file, gpt, sizeof(ventoy_gpt_info));
+ if (grub_strncmp(gpt->Head.Signature, "EFI PART", 8) == 0)
+ {
+ debug("This is EFI partition table\n");
+
+ for (i = 0; i < 128; i++)
+ {
+ if (grub_memcmp(gpt->PartTbl[i].PartGuid, zeroguid, 16))
+ {
+ if (FileSectors < gpt->PartTbl[i].LastLBA)
+ {
+ debug("out of range: part[%d] LastLBA:%llu FileSectors:%llu\n", i,
+ (ulonglong)gpt->PartTbl[i].LastLBA, (ulonglong)FileSectors);
+ goto out;
+ }
+ }
+ }
+ }
+ else
+ {
+ debug("This is MBR partition table\n");
+
+ for (i = 0; i < 4; i++)
+ {
+ pt = gpt->MBR.PartTbl + i;
+ if (FileSectors < pt->StartSectorId + pt->SectorCount)
+ {
+ debug("out of range: part[%d] LastLBA:%llu FileSectors:%llu\n", i,
+ (ulonglong)(pt->StartSectorId + pt->SectorCount),
+ (ulonglong)FileSectors);
+ goto out;
+ }
+ }
+ }
+
+ ret = 0;
+
+out:
+ grub_file_close(file);
+ grub_check_free(gpt);
+ grub_errno = GRUB_ERR_NONE;
+ return ret;
+}
+