| id
				 int64 4 16.3M | file_name
				 stringlengths 3 68 | file_path
				 stringlengths 14 181 | content
				 stringlengths 39 9.06M | size
				 int64 39 9.06M | language
				 stringclasses 1
				value | extension
				 stringclasses 2
				values | total_lines
				 int64 1 711k | avg_line_length
				 float64 3.18 138 | max_line_length
				 int64 10 140 | alphanum_fraction
				 float64 0.02 0.93 | repo_name
				 stringlengths 7 69 | repo_stars
				 int64 2 61.6k | repo_forks
				 int64 12 7.81k | repo_open_issues
				 int64 0 1.13k | repo_license
				 stringclasses 10
				values | repo_extraction_date
				 stringclasses 657
				values | exact_duplicates_stackv2
				 bool 1
				class | exact_duplicates_stackv1
				 bool 1
				class | exact_duplicates_redpajama
				 bool 1
				class | exact_duplicates_githubcode
				 bool 2
				classes | near_duplicates_stackv2
				 bool 1
				class | near_duplicates_stackv1
				 bool 1
				class | near_duplicates_redpajama
				 bool 1
				class | near_duplicates_githubcode
				 bool 2
				classes | 
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 4 | 
	freebsd.c | 
	ventoy_Ventoy/VBLADE/vblade-master/freebsd.c | 
	/*
 * Copyright (c) 2005, Stacey Son <sson (at) verio (dot) net>
 * All rights reserved.
 */
// freebsd.c: low level access routines for FreeBSD
#include "config.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <net/ethernet.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_dl.h>
#include <net/route.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <net/if.h>
#include <sys/stat.h>
#include <sys/disk.h>
#include <sys/select.h>
#include <sys/sysctl.h>
#include <fcntl.h>
#include <errno.h>
#include "dat.h"
#include "fns.h"
#define BPF_DEV "/dev/bpf0"
/* Packet buffer for getpkt() */
static uchar *pktbuf = NULL;
static int pktbufsz = 0;
int
dial(char *eth, int bufcnt)
{
	char m;
	int fd = -1;
	struct bpf_version bv;
	u_int v;
	unsigned bufsize, linktype;
	char device[sizeof BPF_DEV];
	struct ifreq ifr;
	struct bpf_program *bpf_program = create_bpf_program(shelf, slot);
	
	strncpy(device, BPF_DEV, sizeof BPF_DEV);
	/* find a bpf device we can use, check /dev/bpf[0-9] */
	for (m = '0'; m <= '9'; m++) {
		device[sizeof(BPF_DEV)-2] = m;
		if ((fd = open(device, O_RDWR)) > 0)
			break;
	}
	if (fd < 0) {
		perror("open");
		return -1;
	}
	if (ioctl(fd, BIOCVERSION, &bv) < 0) {
		perror("BIOCVERSION");
		goto bad;
	}
	if (bv.bv_major != BPF_MAJOR_VERSION ||
	    bv.bv_minor < BPF_MINOR_VERSION) {
		fprintf(stderr,
			"kernel bpf filter out of date\n");
		goto bad;
	}
	/*
	 * Try finding a good size for the buffer; 65536 may be too
	 * big, so keep cutting it in half until we find a size
	 * that works, or run out of sizes to try.
	 *
	 */
	for (v = 65536; v != 0; v >>= 1) {
		(void) ioctl(fd, BIOCSBLEN, (caddr_t)&v);
		(void)strncpy(ifr.ifr_name, eth,
			sizeof(ifr.ifr_name));
		if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
			break;  /* that size worked; we're done */
		if (errno != ENOBUFS) {
			fprintf(stderr, "BIOCSETIF: %s: %s\n",
					eth, strerror(errno));
			goto bad;
		}
	}
	if (v == 0) {
		fprintf(stderr, 
			"BIOCSBLEN: %s: No buffer size worked\n", eth);
		goto bad;
	}
	/* Allocate memory for the packet buffer */
	pktbufsz = v;
	if ((pktbuf = malloc(pktbufsz)) == NULL) {
		perror("malloc");
		goto bad;
	}
	/* Don't wait for buffer to be full or timeout */
	v = 1;
	if (ioctl(fd, BIOCIMMEDIATE, &v) < 0) {
		perror("BIOCIMMEDIATE");
		goto bad;
	}
	/* Only read incoming packets */
	v = 0;
	if (ioctl(fd, BIOCSSEESENT, &v) < 0) {
		perror("BIOCSSEESENT");
		goto bad;
	}
	/* Don't complete ethernet hdr */
	v = 1;
	if (ioctl(fd, BIOCSHDRCMPLT, &v) < 0) {
		perror("BIOCSHDRCMPLT");
		goto bad;
	}
	/* Get the data link layer type. */
	if (ioctl(fd, BIOCGDLT, (caddr_t)&v) < 0) {
		perror("BIOCGDLT");
		goto bad;
	}
	linktype = v;
	/* Get the filter buf size */
	if (ioctl(fd, BIOCGBLEN, (caddr_t)&v) < 0) {
		perror("BIOCGBLEN");
		goto bad;
	}
	bufsize = v;
	if (ioctl(fd, BIOCSETF, (caddr_t)bpf_program) < 0) {
		perror("BIOSETF");
		goto bad;
	} 
	free_bpf_program(bpf_program);
	return(fd);
bad:
	free_bpf_program(bpf_program);
	close(fd);
	return(-1);
}
int
getea(int s, char *eth, uchar *ea)
{
	int mib[6];
	size_t len;
	char *buf, *next, *end;
	struct if_msghdr *ifm;
	struct sockaddr_dl *sdl;
	
	mib[0] = CTL_NET; 	mib[1] = AF_ROUTE;
	mib[2] = 0; 		mib[3] = AF_LINK;
	mib[4] = NET_RT_IFLIST;	mib[5] = 0;
	if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
		return (-1);
	}
	if (!(buf = (char *) malloc(len))) {
		return (-1);
	}
	
	if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
		free(buf);
		return (-1);
	}
	end = buf + len;
	for (next = buf; next < end; next += ifm->ifm_msglen) {
		ifm = (struct if_msghdr *)next;
		if (ifm->ifm_type == RTM_IFINFO) {
			sdl = (struct sockaddr_dl *)(ifm + 1);
			if (strncmp(&sdl->sdl_data[0], eth, 
					sdl->sdl_nlen) == 0) {
				memcpy(ea, LLADDR(sdl), ETHER_ADDR_LEN);
				break;
			}
		}
	}
	free(buf);
	return(0);
}
#if 0
int
getsec(int fd, uchar *place, vlong lba, int nsec)
{
	return pread(fd, place, nsec * 512, lba * 512);
}
int
putsec(int fd, uchar *place, vlong lba, int nsec)
{
	return pwrite(fd, place, nsec * 512, lba * 512);
}
#endif
static int pktn = 0;
static uchar *pktbp = NULL;
int
getpkt(int fd, uchar *buf, int sz)
{
	register struct bpf_hdr *bh;
	register int pktlen, retlen;
	
	if (pktn <= 0) { 
		if ((pktn = read(fd, pktbuf, pktbufsz)) < 0) {
			perror("read");
			exit(1);
		}
		pktbp = pktbuf;
	}
	bh = (struct bpf_hdr *) pktbp;
	retlen = (int) bh->bh_caplen;
	/* This memcpy() is currently needed */ 
	memcpy(buf, (void *)(pktbp + bh->bh_hdrlen),
		retlen > sz ? sz : retlen);
	pktlen = bh->bh_hdrlen + bh->bh_caplen; 
	
	pktbp = pktbp + BPF_WORDALIGN(pktlen);
	pktn  -= (int) BPF_WORDALIGN(pktlen);
	return retlen; 
}
int
putpkt(int fd, uchar *buf, int sz)
{
	return write(fd, buf, sz);
}
int
getmtu(int fd, char *name)
{
	struct ifreq xx;
	int s, n, p;
	s = socket(AF_INET, SOCK_RAW, 0);
	if (s == -1) {
		perror("Can't get mtu");
		return 1500;
	}
	xx.ifr_addr.sa_family = AF_INET;
	snprintf(xx.ifr_name, sizeof xx.ifr_name, "%s", name);
	n = ioctl(s, SIOCGIFMTU, &xx);
	if (n == -1) {
		perror("Can't get mtu");
		return 1500;
	}
	close(s);
	// FreeBSD bpf writes are capped at one PAGESIZE'd mbuf. As such we must
	// limit our sector count. See FreeBSD PR 205164, OpenAoE/vblade #7.
	p = getpagesize();
	if (xx.ifr_mtu > p) {
		return p;
	}
	return xx.ifr_mtu;
}
vlong
getsize(int fd)
{
	off_t media_size;
	vlong size;
	struct stat s;
	int n;
	// Try getting disklabel from block dev
	if ((n = ioctl(fd, DIOCGMEDIASIZE, &media_size)) != -1) {
		size = media_size;
	} else {
		// must not be a block special dev
		if (fstat(fd, &s) == -1) {
			perror("getsize");
			exit(1);
		}
		size = s.st_size;
	}
	printf("ioctl returned %d\n", n);
	printf("%lld bytes\n", size);
	return size;
}
 | 5,924 | 
	C | 
	.c | 262 | 20.248092 | 73 | 0.637888 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 5 | 
	ata.c | 
	ventoy_Ventoy/VBLADE/vblade-master/ata.c | 
	// ata.c:  ATA simulator for vblade
#include "config.h"
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include "dat.h"
#include "fns.h"
enum {
	// err bits
	UNC =	1<<6,
	MC =	1<<5,
	IDNF =	1<<4,
	MCR =	1<<3,
	ABRT = 	1<<2,
	NM =	1<<1,
	// status bits
	BSY =	1<<7,
	DRDY =	1<<6,
	DF =	1<<5,
	DRQ =	1<<3,
	ERR =	1<<0,
};
static ushort ident[256];
static void
setfld(ushort *a, int idx, int len, char *str)	// set field in ident
{
	uchar *p;
	p = (uchar *)(a+idx);
	while (len > 0) {
		if (*str == 0)
			p[1] = ' ';
		else
			p[1] = *str++;
		if (*str == 0)
			p[0] = ' ';
		else
			p[0] = *str++;
		p += 2;
		len -= 2;
	}
}
static void
setlba28(ushort *ident, vlong lba)
{
	uchar *cp;
	cp = (uchar *) &ident[60];
	*cp++ = lba;
	*cp++ = lba >>= 8;
	*cp++ = lba >>= 8;
	*cp++ = (lba >>= 8) & 0xf;
}
static void
setlba48(ushort *ident, vlong lba)
{
	uchar *cp;
	cp = (uchar *) &ident[100];
	*cp++ = lba;
	*cp++ = lba >>= 8;
	*cp++ = lba >>= 8;
	*cp++ = lba >>= 8;
	*cp++ = lba >>= 8;
	*cp++ = lba >>= 8;
}
static void
setushort(ushort *a, int i, ushort n)
{
	uchar *p;
	p = (uchar *)(a+i);
	*p++ = n & 0xff;
	*p++ = n >> 8;
}
void
atainit(void)
{
	char buf[64];
	setushort(ident, 47, 0x8000);
	setushort(ident, 49, 0x0200);
	setushort(ident, 50, 0x4000);
	setushort(ident, 83, 0x5400);
	setushort(ident, 84, 0x4000);
	setushort(ident, 86, 0x1400);
	setushort(ident, 87, 0x4000);
	setushort(ident, 93, 0x400b);
	setfld(ident, 27, 40, "Coraid EtherDrive vblade");
	sprintf(buf, "V%d", VBLADE_VERSION);
	setfld(ident, 23, 8, buf);
	setfld(ident, 10, 20, serial);
}
/* The ATA spec is weird in that you specify the device size as number
 * of sectors and then address the sectors with an offset.  That means
 * with LBA 28 you shouldn't see an LBA of all ones.  Still, we don't
 * check for that.
 */
int
atacmd(Ataregs *p, uchar *dp, int ndp, int payload) // do the ata cmd
{
	vlong lba;
	ushort *ip;
	int n;
	enum { MAXLBA28SIZE = 0x0fffffff };
	extern int maxscnt;
	p->status = 0;
	switch (p->cmd) {
	default:
		p->status = DRDY | ERR;
		p->err = ABRT;
		return 0;
	case 0xe7:		// flush cache
		return 0;
	case 0xec:		// identify device
		if (p->sectors != 1 || ndp < 512)
			return -1;
		memmove(dp, ident, 512);
		ip = (ushort *)dp;
		if (size & ~MAXLBA28SIZE)
			setlba28(ip, MAXLBA28SIZE);
		else
			setlba28(ip, size);
		setlba48(ip, size);
		p->err = 0;
		p->status = DRDY;
		p->sectors = 0;
		return 0;
	case 0xe5:		// check power mode
		p->err = 0;
		p->sectors = 0xff; // the device is active or idle
		p->status = DRDY;
		return 0;
	case 0x20:		// read sectors
	case 0x30:		// write sectors
		lba = p->lba & MAXLBA28SIZE;
		break;
	case 0x24:		// read sectors ext
	case 0x34:		// write sectors ext
		lba = p->lba & 0x0000ffffffffffffLL;	// full 48
		break;
	}
	// we ought not be here unless we are a read/write
	if (p->sectors > maxscnt || p->sectors*512 > ndp)
		return -1;
	if (lba + p->sectors > size) {
		p->err = IDNF;
		p->status = DRDY | ERR;
		p->lba = lba;
		return 0;
	}
	if (p->cmd == 0x20 || p->cmd == 0x24)
		n = getsec(bfd, dp, lba+offset, p->sectors);
	else {
		// packet should be big enough to contain the data
		if (payload < 512 * p->sectors)
			return -1;
		n = putsec(bfd, dp, lba+offset, p->sectors);
	}
	n /= 512;
	if (n != p->sectors) {
		p->err = ABRT;
		p->status = ERR;
	} else
		p->err = 0;
	p->status |= DRDY;
	p->lba += n;
	p->sectors -= n;
	return 0;
}
 | 3,425 | 
	C | 
	.c | 165 | 18.509091 | 70 | 0.608333 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 6 | 
	aoe.c | 
	ventoy_Ventoy/VBLADE/vblade-master/aoe.c | 
	// aoe.c: the ATA over Ethernet virtual EtherDrive (R) blade
#define _GNU_SOURCE
#include "config.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <netinet/in.h>
#include "dat.h"
#include "fns.h"
enum {
	Nmasks= 32,
	Nsrr= 256,
	Alen= 6,
};
uchar masks[Nmasks*Alen];
int nmasks;
uchar srr[Nsrr*Alen];
int nsrr;
char config[Nconfig];
int nconfig = 0;
int maxscnt = 2;
char *ifname;
int bufcnt = Bufcount;
#ifndef O_BINARY
#define O_BINARY 0
#endif
typedef unsigned long long u64_t;
typedef unsigned int    u32_t;
#pragma pack(4)
typedef struct ventoy_img_chunk
{
    u32_t img_start_sector; // sector size: 2KB
    u32_t img_end_sector;   // included
    u64_t disk_start_sector; // in disk_sector_size
    u64_t disk_end_sector;   // included
}ventoy_img_chunk;
typedef struct ventoy_disk_map
{
    u64_t img_start_sector;
    u64_t img_end_sector;
    u64_t disk_start_sector;
    u64_t disk_end_sector;
}ventoy_disk_map;
#pragma pack()
static int verbose = 0;
static u64_t g_iso_file_size = 0;
static int g_img_map_num = 0;
static ventoy_disk_map *g_img_map = NULL;
static ventoy_disk_map * vtoydm_get_img_map_data(const char *img_map_file, int *plen)
{
    int i;
    int len;
    int rc = 1;
    u64_t sector_num;
    FILE *fp = NULL;
    ventoy_img_chunk *chunk = NULL;
    ventoy_disk_map *map = NULL;
    
    fp = fopen(img_map_file, "rb");
    if (NULL == fp)
    {
        fprintf(stderr, "Failed to open file %s\n", img_map_file);
        return NULL;
    }
    fseek(fp, 0, SEEK_END);
    len = (int)ftell(fp);
    fseek(fp, 0, SEEK_SET);
    chunk = (ventoy_img_chunk *)malloc(len);
    if (NULL == chunk)
    {
        fprintf(stderr, "Failed to malloc memory len:%d\n", len);
        goto end;
    }
    if (fread(chunk, 1, len, fp) != len)
    {
        fprintf(stderr, "Failed to read file\n");
        goto end;
    }
    if (len % sizeof(ventoy_img_chunk))
    {
        fprintf(stderr, "image map file size %d is not aligned with %d\n", 
                len, (int)sizeof(ventoy_img_chunk));
        goto end;
    }
    map = (ventoy_disk_map *)malloc((len / sizeof(ventoy_img_chunk)) * sizeof(ventoy_disk_map));
    if (NULL == map)
    {
        fprintf(stderr, "Failed to malloc memory\n");
        goto end;
    }
    
    for (i = 0; i < len / sizeof(ventoy_img_chunk); i++)
    {
        sector_num = chunk[i].img_end_sector - chunk[i].img_start_sector + 1;
        g_iso_file_size += sector_num * 2048;
        
        map[i].img_start_sector = chunk[i].img_start_sector << 2;
        map[i].img_end_sector = (chunk[i].img_end_sector << 2) + 3;
        map[i].disk_start_sector = chunk[i].disk_start_sector;
        map[i].disk_end_sector = chunk[i].disk_end_sector;
    }
    rc = 0;
end:
    fclose(fp);
    if (chunk)
    {
        free(chunk);
        chunk = NULL;
    }
    *plen = len;
    return map;
}
static void parse_img_chunk(const char *img_map_file)
{
    int len;
    g_img_map = vtoydm_get_img_map_data(img_map_file, &len);
    if (g_img_map)
    {
        g_img_map_num = len / sizeof(ventoy_img_chunk);
    }
}
static u64_t get_disk_sector(u64_t lba)
{
    int i;
    ventoy_disk_map *cur = g_img_map;
    
    for (i = 0; i < g_img_map_num; i++, cur++)
    {
        if (lba >= cur->img_start_sector && lba <= cur->img_end_sector)
        {
            return (lba - cur->img_start_sector) + cur->disk_start_sector;
        }
    }
    return 0;
}
int getsec(int fd, uchar *place, vlong lba, int nsec)
{
    int i;
    int count = 0;
    u64_t last_sector;
    u64_t sector;
    count = 1;
    last_sector = get_disk_sector((u64_t)lba);
    
    for (i = 1; i < nsec; i++)
    {
        sector = get_disk_sector((u64_t)(lba + i));
        if (sector == (last_sector + count))
        {
            count++;
        }
        else
        {
            lseek(fd, last_sector * 512, SEEK_SET);
            read(fd, place, count * 512);
            last_sector = sector;
            count = 1;
        }
    }
    lseek(fd, last_sector * 512, SEEK_SET);
    read(fd, place, count * 512);
	return nsec * 512;
}
// read only
int putsec(int fd, uchar *place, vlong lba, int nsec)
{
    return nsec * 512;
}
void
aoead(int fd)	// advertise the virtual blade
{
	uchar buf[2000];
	Conf *p;
	int i;
	p = (Conf *)buf;
	memset(p, 0, sizeof *p);
	memset(p->h.dst, 0xff, 6);
	memmove(p->h.src, mac, 6);
	p->h.type = htons(0x88a2);
	p->h.flags = Resp;
	p->h.maj = htons(shelf);
	p->h.min = slot;
	p->h.cmd = Config;
	p->bufcnt = htons(bufcnt);
	p->scnt = maxscnt = (getmtu(sfd, ifname) - sizeof (Ata)) / 512;
	p->firmware = htons(FWV);
	p->vercmd = 0x10 | Qread;
	memcpy(p->data, config, nconfig);
	p->len = htons(nconfig);
	if (nmasks == 0)
	if (putpkt(fd, buf, sizeof *p - sizeof p->data + nconfig) == -1) {
		perror("putpkt aoe id");
		return;
	}
	for (i=0; i<nmasks; i++) {
		memcpy(p->h.dst, &masks[i*Alen], Alen);
		if (putpkt(fd, buf, sizeof *p - sizeof p->data + nconfig) == -1)
			perror("putpkt aoe id");
	}
}
int
isbcast(uchar *ea)
{
	uchar *b = (uchar *)"\377\377\377\377\377\377";
	return memcmp(ea, b, 6) == 0;
}
long long
getlba(uchar *p)
{
	vlong v;
	int i;
	v = 0;
	for (i = 0; i < 6; i++)
		v |= (vlong)(*p++) << i * 8;
	return v;
}
int
aoeata(Ata *p, int pktlen)	// do ATA reqeust
{
	Ataregs r;
	int len = 60;
	int n;
	r.lba = getlba(p->lba);
	r.sectors = p->sectors;
	r.feature = p->err;
	r.cmd = p->cmd;
	if (r.cmd != 0xec)
	if (!rrok(p->h.src)) {
		p->h.flags |= Error;
		p->h.error = Res;
		return len;
	}
	if (atacmd(&r, (uchar *)(p+1), maxscnt*512, pktlen - sizeof(*p)) < 0) {
		p->h.flags |= Error;
		p->h.error = BadArg;
		return len;
	}
	if (!(p->aflag & Write))
	if ((n = p->sectors)) {
		n -= r.sectors;
		len = sizeof (Ata) + (n*512);
	}
	p->sectors = r.sectors;
	p->err = r.err;
	p->cmd = r.status;
	return len;
}
#define QCMD(x) ((x)->vercmd & 0xf)
// yes, this makes unnecessary copies.
int
confcmd(Conf *p, int payload)	// process conf request
{
	int len;
	len = ntohs(p->len);
	if (QCMD(p) != Qread)
	if (len > Nconfig || len > payload)
		return 0;	// if you can't play nice ...
	switch (QCMD(p)) {
	case Qtest:
		if (len != nconfig)
			return 0;
		// fall thru
	case Qprefix:
		if (len > nconfig)
			return 0;
		if (memcmp(config, p->data, len))
			return 0;
		// fall thru
	case Qread:
		break;
	case Qset:
		if (nconfig)
		if (nconfig != len || memcmp(config, p->data, len)) {
			p->h.flags |= Error;
			p->h.error = ConfigErr;
			break;
		}
		// fall thru
	case Qfset:
		nconfig = len;
		memcpy(config, p->data, nconfig);
		break;
	default:
		p->h.flags |= Error;
		p->h.error = BadArg;
	}
	memmove(p->data, config, nconfig);
	p->len = htons(nconfig);
	p->bufcnt = htons(bufcnt);
	p->scnt = maxscnt = (getmtu(sfd, ifname) - sizeof (Ata)) / 512;
	p->firmware = htons(FWV);
	p->vercmd = 0x10 | QCMD(p);	// aoe v.1
	return nconfig + sizeof *p - sizeof p->data;
}
static int
aoesrr(Aoesrr *sh, int len)
{
	uchar *m, *e;
	int n;
	e = (uchar *) sh + len;
	m = (uchar *) sh + Nsrrhdr;
	switch (sh->rcmd) {
	default:
e:		sh->h.error = BadArg;
		sh->h.flags |= Error;
		break;
	case 1:	// set
		if (!rrok(sh->h.src)) {
			sh->h.error = Res;
			sh->h.flags |= Error;
			break;
		}
	case 2:	// force set
		n = sh->nmacs * 6;
		if (e < m + n)
			goto e;
		nsrr = sh->nmacs;
		memmove(srr, m, n);
	case 0:	// read
		break;
	}
	sh->nmacs = nsrr;
	n = nsrr * 6;
	memmove(m, srr, n);
	return Nsrrhdr + n;
}
static int
addmask(uchar *ea)
{
	uchar *p, *e;
	p = masks;
	e = p + nmasks;
	for (; p<e; p += 6)
		if (!memcmp(p, ea, 6))
			return 2;
	if (nmasks >= Nmasks)
		return 0;
	memmove(p, ea, 6);
	nmasks++;
	return 1;
}
static void
rmmask(uchar *ea)
{
	uchar *p, *e;
	p = masks;
	e = p + nmasks;
	for (; p<e; p+=6)
		if (!memcmp(p, ea, 6)) {
			memmove(p, p+6, e-p-6);
			nmasks--;
			return;
		}
}
static int
aoemask(Aoemask *mh, int len)
{
	Mdir *md, *mdi, *mde;
	int i, n;
	n = 0;
	md = mdi = (Mdir *) ((uchar *)mh + Nmaskhdr);
	switch (mh->cmd) {
	case Medit:
		mde = md + mh->nmacs;
		for (; md<mde; md++) {
			switch (md->cmd) {
			case MDdel:
				rmmask(md->mac);
				continue;
			case MDadd:
				if (addmask(md->mac))
					continue;
				mh->merror = MEfull;
				mh->nmacs = md - mdi;
				goto e;
			case MDnop:
				continue;
			default:
				mh->merror = MEbaddir;
				mh->nmacs = md - mdi;
				goto e;
			}
		}
		// success.  fall thru to return list
	case Mread:
		md = mdi;
		for (i=0; i<nmasks; i++) {
			md->res = md->cmd = 0;
			memmove(md->mac, &masks[i*6], 6);
			md++;
		}
		mh->merror = 0;
		mh->nmacs = nmasks;
		n = sizeof *md * nmasks;
		break;
	default:
		mh->h.flags |= Error;
		mh->h.error = BadArg;
	}
e:	return n + Nmaskhdr;
}
void
doaoe(Aoehdr *p, int n)
{
	int len;
	switch (p->cmd) {
	case ATAcmd:
		if (n < Natahdr)
			return;
		len = aoeata((Ata*)p, n);
		break;
	case Config:
		if (n < Ncfghdr)
			return;
		len = confcmd((Conf *)p, n);
		break;
	case Mask:
		if (n < Nmaskhdr)
			return;
		len = aoemask((Aoemask *)p, n);
		break;
	case Resrel:
		if (n < Nsrrhdr)
			return;
		len = aoesrr((Aoesrr *)p, n);
		break;
	default:
		p->error = BadCmd;
		p->flags |= Error;
		len = n;
		break;
	}
	if (len <= 0)
		return;
	memmove(p->dst, p->src, 6);
	memmove(p->src, mac, 6);
	p->maj = htons(shelf);
	p->min = slot;
	p->flags |= Resp;
	if (putpkt(sfd, (uchar *) p, len) == -1) {
		perror("write to network");
		exit(1);
	}
}
void
aoe(void)
{
	Aoehdr *p;
	uchar *buf;
	int n, sh;
	long pagesz;
	enum { bufsz = 1<<16, };
	if ((pagesz = sysconf(_SC_PAGESIZE)) < 0) {
		perror("sysconf");
		exit(1);
	}        
	if ((buf = malloc(bufsz + pagesz)) == NULL) {
		perror("malloc");
		exit(1);
	}
	n = (size_t) buf + sizeof(Ata);
	if (n & (pagesz - 1))
		buf += pagesz - (n & (pagesz - 1));
	aoead(sfd);
	for (;;) {
		n = getpkt(sfd, buf, bufsz);
		if (n < 0) {
			perror("read network");
			exit(1);
		}
		if (n < sizeof(Aoehdr))
			continue;
		p = (Aoehdr *) buf;
		if (ntohs(p->type) != 0x88a2)
			continue;
		if (p->flags & Resp)
			continue;
		sh = ntohs(p->maj);
		if (sh != shelf && sh != (ushort)~0)
			continue;
		if (p->min != slot && p->min != (uchar)~0)
			continue;
		if (nmasks && !maskok(p->src))
			continue;
		doaoe(p, n);
	}
}
void
usage(void)
{
	fprintf(stderr, "usage: %s [-b bufcnt] [-o offset] [-l length] [-d ] [-s] [-r] [ -m mac[,mac...] ] shelf slot netif filename\n", 
		progname);
	exit(1);
}
/* parseether from plan 9 */
int
parseether(uchar *to, char *from)
{
	char nip[4];
	char *p;
	int i;
	p = from;
	for(i = 0; i < 6; i++){
		if(*p == 0)
			return -1;
		nip[0] = *p++;
		if(*p == 0)
			return -1;
		nip[1] = *p++;
		nip[2] = 0;
		to[i] = strtoul(nip, 0, 16);
		if(*p == ':')
			p++;
	}
	return 0;
}
void
setmask(char *ml)
{
	char *p;
	int n;
	for (; ml; ml=p) {
		p = strchr(ml, ',');
		if (p)
			*p++ = '\0';
		n = parseether(&masks[nmasks*Alen], ml);
		if (n < 0)
			fprintf(stderr, "ignoring mask %s, parseether failure\n", ml);
		else
			nmasks++;
	}
}
int
maskok(uchar *ea)
{
	int i, ok = 0;
	for (i=0; !ok && i<nmasks; i++)
		ok = memcmp(ea, &masks[i*Alen], Alen) == 0;
	return ok;
}
int
rrok(uchar *ea)
{
	int i, ok = 0;
	if (nsrr == 0)
		return 1;
	for (i=0; !ok && i<nsrr; i++)
		ok = memcmp(ea, &srr[i*Alen], Alen) == 0;
	return ok;
}
void
setserial(int sh, int sl)
{
	char h[32];
	h[0] = 0;
	gethostname(h, sizeof h);
	snprintf(serial, Nserial, "%d.%d:%.*s", sh, sl, (int) sizeof h, h);
}
int
main(int argc, char **argv)
{
	int ch, omode = 0, readonly = 0;
	vlong length = 0;
	char *end;
    char filepath[300] = {0};
    /* Avoid to be killed by systemd */
    if (access("/etc/initrd-release", F_OK) >= 0)
	{		
		argv[0][0] = '@';
	}
	bufcnt = Bufcount;
	offset = 0;
	setbuf(stdin, NULL);
	progname = *argv;
	while ((ch = getopt(argc, argv, "b:dsrm:f:tv::o:l:")) != -1) {
		switch (ch) {
		case 'b':
			bufcnt = atoi(optarg);
			break;
		case 'd':
#ifdef O_DIRECT
			omode |= O_DIRECT;
#endif
			break;
		case 's':
			omode |= O_SYNC;
			break;
		case 'r':
			readonly = 1;
			break;
		case 'm':
			setmask(optarg);
			break;
        case 't':
            return 0;
        case 'v':
            verbose = 1;
            break;
        case 'f':
            strncpy(filepath, optarg, sizeof(filepath) - 1);
            break;
		case 'o':
			offset = strtoll(optarg, &end, 0);
			if (end == optarg || offset < 0)
				usage();
			break;
		case 'l':
			length = strtoll(optarg, &end, 0);
			if (end == optarg || length < 1)
				usage();
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;
	if (argc != 4 || bufcnt <= 0)
		usage();
	omode |= readonly ? O_RDONLY : O_RDWR;
    parse_img_chunk(filepath);
	bfd = open(argv[3], omode);
	if (bfd == -1) {
		perror("open");
		exit(1);
	}
	shelf = atoi(argv[0]);
	slot = atoi(argv[1]);
	setserial(shelf, slot);
	size = g_iso_file_size; //getsize(bfd);
	size /= 512;
	if (size <= offset) {
                if (offset)
                        fprintf(stderr,
                                "Offset %lld too large for %lld-sector export\n",
                                offset,
                                size);
                else
                        fputs("0-sector file size is too small\n", stderr);
		exit(1);
	}
	size -= offset;
	if (length) {
		if (length > size) {
			fprintf(stderr, "Length %llu too big - exceeds size of file!\n", offset);
			exit(1);
		}
		size = length;
	}
	ifname = argv[2];
	sfd = dial(ifname, bufcnt);
	if (sfd < 0)
		return 1;
	getea(sfd, ifname, mac);
    if (verbose) {
        printf("pid %ld: e%d.%d, %lld sectors %s\n",
		    (long) getpid(), shelf, slot, size,
		    readonly ? "O_RDONLY" : "O_RDWR");
    }
    
	fflush(stdout);
	atainit();
	aoe();
	return 0;
}
 | 13,783 | 
	C | 
	.c | 664 | 17.192771 | 130 | 0.573569 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 7 | 
	bpf.c | 
	ventoy_Ventoy/VBLADE/vblade-master/bpf.c | 
	// bpf.c: bpf packet filter for linux/freebsd
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "dat.h"
#include "fns.h"
struct bpf_insn {
	ushort code;
	uchar jt;
	uchar jf;
	u_int32_t k;
};
struct bpf_program {
	uint bf_len;
	struct bpf_insn *bf_insns;
};
/* instruction classes */
#define		BPF_CLASS(code) ((code) & 0x07)
#define		BPF_LD		0x00
#define		BPF_LDX		0x01
#define		BPF_ST		0x02
#define		BPF_STX		0x03
#define		BPF_ALU		0x04
#define		BPF_JMP		0x05
#define		BPF_RET		0x06
#define		BPF_MISC	0x07
/* ld/ldx fields */
#define		BPF_SIZE(code)	((code) & 0x18)
#define		BPF_W		0x00
#define		BPF_H		0x08
#define		BPF_B		0x10
#define		BPF_MODE(code)	((code) & 0xe0)
#define		BPF_IMM 	0x00
#define		BPF_ABS		0x20
#define		BPF_IND		0x40
#define		BPF_MEM		0x60
#define		BPF_LEN		0x80
#define		BPF_MSH		0xa0
/* alu/jmp fields */
#define		BPF_OP(code)	((code) & 0xf0)
#define		BPF_ADD		0x00
#define		BPF_SUB		0x10
#define		BPF_MUL		0x20
#define		BPF_DIV		0x30
#define		BPF_OR		0x40
#define		BPF_AND		0x50
#define		BPF_LSH		0x60
#define		BPF_RSH		0x70
#define		BPF_NEG		0x80
#define		BPF_JA		0x00
#define		BPF_JEQ		0x10
#define		BPF_JGT		0x20
#define		BPF_JGE		0x30
#define		BPF_JSET	0x40
#define		BPF_SRC(code)	((code) & 0x08)
#define		BPF_K		0x00
#define		BPF_X		0x08
/* ret - BPF_K and BPF_X also apply */
#define		BPF_RVAL(code)	((code) & 0x18)
#define		BPF_A		0x10
/* misc */
#define		BPF_MISCOP(code) ((code) & 0xf8)
#define		BPF_TAX		0x00
#define		BPF_TXA		0x80
/* macros for insn array initializers */
#define BPF_STMT(code, k) { (ushort)(code), 0, 0, k }
#define BPF_JUMP(code, k, jt, jf) { (ushort)(code), jt, jf, k }
void *
create_bpf_program(int shelf, int slot)
{
	struct bpf_program *bpf_program;
	struct bpf_insn insns[] = {
		/* CHECKTYPE: Load the type into register */
		BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 12),
		/* Does it match AoE Type (0x88a2)? No, goto INVALID */
		BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0x88a2, 0, 10),
		/* Load the flags into register */
		BPF_STMT(BPF_LD+BPF_B+BPF_ABS, 14),
		/* Check to see if the Resp flag is set */
		BPF_STMT(BPF_ALU+BPF_AND+BPF_K, Resp),
		/* Yes, goto INVALID */
		BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0, 0, 7),
		/* CHECKSHELF: Load the shelf number into register */
		BPF_STMT(BPF_LD+BPF_H+BPF_ABS, 16),
		/* Does it match shelf number? Yes, goto CHECKSLOT */
		BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, shelf, 1, 0),
		/* Does it match broadcast? No, goto INVALID */
		BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xffff, 0, 4),
		/* CHECKSLOT: Load the slot number into register */
		BPF_STMT(BPF_LD+BPF_B+BPF_ABS, 18),
		/* Does it match shelf number? Yes, goto VALID */
		BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, slot, 1, 0),
		/* Does it match broadcast? No, goto INVALID */
		BPF_JUMP(BPF_JMP+BPF_JEQ+BPF_K, 0xff, 0, 1),
		/* VALID: return -1 (allow the packet to be read) */
		BPF_STMT(BPF_RET+BPF_K, -1),
		/* INVALID: return 0 (ignore the packet) */
		BPF_STMT(BPF_RET+BPF_K, 0),
	};
	if ((bpf_program = malloc(sizeof(struct bpf_program))) == NULL
	    || (bpf_program->bf_insns = malloc(sizeof(insns))) == NULL) {
		perror("malloc");
		exit(1);
	}
	bpf_program->bf_len = sizeof(insns)/sizeof(struct bpf_insn);
	memcpy(bpf_program->bf_insns, insns, sizeof(insns));
	return (void *)bpf_program;
}
void
free_bpf_program(void *bpf_program)
{
	free(((struct bpf_program *) bpf_program)->bf_insns);
	free(bpf_program);
}
 | 3,417 | 
	C | 
	.c | 116 | 27.698276 | 66 | 0.679331 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 8 | 
	linux.c | 
	ventoy_Ventoy/VBLADE/vblade-master/linux.c | 
	// linux.c: low level access routines for Linux
#define _GNU_SOURCE
#include "config.h"
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <features.h>    /* for the glibc version number */
#if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1
#include <netpacket/packet.h>
#include <net/ethernet.h>     /* the L2 protocols */
#else
#include <asm/types.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>   /* The L2 protocols */
#endif
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <net/if.h>
#include <netinet/in.h>
#include <linux/fs.h>
#include <sys/stat.h>
#include "dat.h"
#include "fns.h"
int	getindx(int, char *);
int	getea(int, char *, uchar *);
int
dial(char *eth, int bufcnt)		// get us a raw connection to an interface
{
	int i, n, s;
	struct sockaddr_ll sa;
	enum { aoe_type = 0x88a2 };
	memset(&sa, 0, sizeof sa);
	s = socket(PF_PACKET, SOCK_RAW, htons(aoe_type));
	if (s == -1) {
		perror("got bad socket");
		return -1;
	}
	i = getindx(s, eth);
	if (i < 0) {
		perror(eth);
		return -1;
	}
	sa.sll_family = AF_PACKET;
	sa.sll_protocol = htons(0x88a2);
	sa.sll_ifindex = i;
	n = bind(s, (struct sockaddr *)&sa, sizeof sa);
	if (n == -1) {
		perror("bind funky");
		return -1;
	}
	struct bpf_program {
		ulong bf_len;
		void *bf_insns;
	} *bpf_program = create_bpf_program(shelf, slot);
	setsockopt(s, SOL_SOCKET, SO_ATTACH_FILTER, bpf_program, sizeof(*bpf_program));
	free_bpf_program(bpf_program);
	n = bufcnt * getmtu(s, eth);
	if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &n, sizeof(n)) < 0)
		perror("setsockopt SOL_SOCKET, SO_SNDBUF");
	if (setsockopt(s, SOL_SOCKET, SO_RCVBUF, &n, sizeof(n)) < 0)
		perror("setsockopt SOL_SOCKET, SO_RCVBUF");
	return s;
}
int
getindx(int s, char *name)	// return the index of device 'name'
{
	struct ifreq xx;
	int n;
	snprintf(xx.ifr_name, sizeof xx.ifr_name, "%s", name);
	n = ioctl(s, SIOCGIFINDEX, &xx);
	if (n == -1)
		return -1;
	return xx.ifr_ifindex;
}
int
getea(int s, char *name, uchar *ea)
{
	struct ifreq xx;
	int n;
        snprintf(xx.ifr_name, sizeof xx.ifr_name, "%s", name);
	n = ioctl(s, SIOCGIFHWADDR, &xx);
	if (n == -1) {
		perror("Can't get hw addr");
		return 0;
	}
	memmove(ea, xx.ifr_hwaddr.sa_data, 6);
	return 1;
}
int
getmtu(int s, char *name)
{
	struct ifreq xx;
	int n;
	snprintf(xx.ifr_name, sizeof xx.ifr_name, "%s", name);
	n = ioctl(s, SIOCGIFMTU, &xx);
	if (n == -1) {
		perror("Can't get mtu");
		return 1500;
	}
	return xx.ifr_mtu;
}
#if 0
int
getsec(int fd, uchar *place, vlong lba, int nsec)
{
	return pread(fd, place, nsec * 512, lba * 512);
}
int
putsec(int fd, uchar *place, vlong lba, int nsec)
{
	return pwrite(fd, place, nsec * 512, lba * 512);
}
#endif
int
getpkt(int fd, uchar *buf, int sz)
{
	return read(fd, buf, sz);
}
int
putpkt(int fd, uchar *buf, int sz)
{
	return write(fd, buf, sz);
}
vlong
getsize(int fd)
{
	vlong size;
	struct stat s;
	int n;
	n = ioctl(fd, BLKGETSIZE64, &size);
	if (n == -1) {	// must not be a block special
		n = fstat(fd, &s);
		if (n == -1) {
			perror("getsize");
			exit(1);
		}
		size = s.st_size;
	}
	return size;
}
 | 3,179 | 
	C | 
	.c | 144 | 20.180556 | 80 | 0.661467 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 12 | 
	u64.c | 
	ventoy_Ventoy/VBLADE/vblade-master/config/u64.c | 
	#include <stdio.h>
int main(void)
{
	u64 n;
	printf("%d\n", (int) n+2);
	return 0;
}
 | 86 | 
	C | 
	.c | 7 | 10.714286 | 27 | 0.615385 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 16 | 
	VDiskRawData.c | 
	ventoy_Ventoy/EDK2/edk2_mod/edk2-edk2-stable201911/MdeModulePkg/Application/VDiskChain/VDiskRawData.c | 
	#include <Uefi.h>
int vdisk_get_vdisk_raw(UINT8 **buf, UINT32 *size) { *buf = NULL; *size = 0; return 0; } | 106 | 
	C | 
	.c | 2 | 52.5 | 88 | 0.647619 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 170 | 
	vtoy_fuse_iso.c | 
	ventoy_Ventoy/FUSEISO/vtoy_fuse_iso.c | 
	/******************************************************************************
 * vtoy_fuse_iso.c
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#define FUSE_USE_VERSION 26
#include <fuse.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
typedef unsigned int uint32_t;
typedef struct dmtable_entry
{
    uint32_t isoSector;
    uint32_t sectorNum;
    unsigned long long diskSector;
}dmtable_entry;
#define MAX_ENTRY_NUM  (1024 * 1024 / sizeof(dmtable_entry))
static int verbose = 0;
#define debug(fmt, ...) if(verbose) printf(fmt, ##__VA_ARGS__)
static int g_disk_fd = -1;
static uint64_t g_iso_file_size;
static char g_mnt_point[512];
static char g_iso_file_name[512];
static dmtable_entry *g_disk_entry_list = NULL;
static int g_disk_entry_num = 0;
static int ventoy_iso_getattr(const char *path, struct stat *statinfo)
{
    int ret = -ENOENT;
    if (path && statinfo)
    {
        memset(statinfo, 0, sizeof(struct stat));
        if (path[0] == '/' && path[1] == 0)
        {
            statinfo->st_mode  = S_IFDIR | 0755;
            statinfo->st_nlink = 2;
            ret = 0;
        }
        else if (strcmp(path, g_iso_file_name) == 0)
        {
            statinfo->st_mode  = S_IFREG | 0444;
            statinfo->st_nlink = 1;
            statinfo->st_size  = g_iso_file_size;
            ret = 0;
        }
    }
    
    return ret;
}
static int ventoy_iso_readdir
(
    const char *path, 
    void *buf, 
    fuse_fill_dir_t filler,
    off_t offset, 
    struct fuse_file_info *file
)
{
    (void)offset;
    (void)file;
    if (path[0] != '/' || path[1] != 0)
    {
        return -ENOENT;
    }
    filler(buf, ".", NULL, 0);
    filler(buf, "..", NULL, 0);
    filler(buf, g_iso_file_name + 1, NULL, 0);
    return 0;
}
static int ventoy_iso_open(const char *path, struct fuse_file_info *file)
{
    if (strcmp(path, g_iso_file_name) != 0)
    {
        return -ENOENT;
    }
    if ((file->flags & 3) != O_RDONLY)
    {
        return -EACCES;
    }
    return 0;
}
static int ventoy_read_iso_sector(uint32_t sector, uint32_t num, char *buf)
{
    uint32_t i = 0;
    uint32_t leftSec = 0;
    uint32_t readSec = 0;
    off_t offset = 0;
    dmtable_entry *entry = NULL;
    
    for (i = 0; i < g_disk_entry_num && num > 0; i++)
    {
        entry = g_disk_entry_list + i;
        if (sector >= entry->isoSector && sector < entry->isoSector + entry->sectorNum)
        {
            offset = (entry->diskSector + (sector - entry->isoSector)) * 512;
            leftSec = entry->sectorNum - (sector - entry->isoSector);
            readSec = (leftSec > num) ? num : leftSec;
            pread(g_disk_fd, buf, readSec * 512, offset);
            sector += readSec;
            buf += readSec * 512;
            num -= readSec;
        }
    }
    return 0;
}
static int ventoy_iso_read
(
    const char *path, char *buf, 
    size_t size, off_t offset,
    struct fuse_file_info *file
)
{
    uint32_t mod = 0;
    uint32_t align = 0;
    uint32_t sector = 0;
    uint32_t number = 0;
    size_t leftsize = 0;
    char secbuf[512];
    
    (void)file;
    
    if(strcmp(path, g_iso_file_name) != 0)
    {
        return -ENOENT;        
    }
    if (offset >= g_iso_file_size)
    {
        return 0;
    }
    if (offset + size > g_iso_file_size)
    {
        size = g_iso_file_size - offset;
    }
    
    leftsize = size;
    sector = offset / 512;
    mod = offset % 512;
    if (mod > 0)
    {
        align = 512 - mod;
        ventoy_read_iso_sector(sector, 1, secbuf);
        if (leftsize > align)
        {
            memcpy(buf, secbuf + mod, align);
            buf += align;
            offset += align;
            sector++;
            leftsize -= align;
        }
        else
        {
            memcpy(buf, secbuf + mod, leftsize);
            return size;
        }
    }
    number = leftsize / 512;
    ventoy_read_iso_sector(sector, number, buf);
    buf += number * 512;
    mod = leftsize % 512;
    if (mod > 0)
    {
        ventoy_read_iso_sector(sector + number, 1, secbuf);
        memcpy(buf, secbuf, mod);
    }
    return size;
}
static struct fuse_operations ventoy_op = 
{
    .getattr    = ventoy_iso_getattr,
    .readdir    = ventoy_iso_readdir,
    .open       = ventoy_iso_open,
    .read       = ventoy_iso_read,
};
static int ventoy_parse_dmtable(const char *filename)
{
    FILE *fp = NULL;
    char diskname[128] = {0};
    char line[256] = {0};
    dmtable_entry *entry= g_disk_entry_list;
    fp = fopen(filename, "r");
    if (NULL == fp)
    {
        printf("Failed to open file %s\n", filename);
        return 1;
    }
    /* read untill the last line */
    while (fgets(line, sizeof(line), fp) && g_disk_entry_num < MAX_ENTRY_NUM)
    {
        sscanf(line, "%u %u linear %s %llu", 
               &entry->isoSector, &entry->sectorNum, 
               diskname, &entry->diskSector);
        g_iso_file_size += (uint64_t)entry->sectorNum * 512ULL;
        g_disk_entry_num++;
        entry++;
    }
    fclose(fp);
    if (g_disk_entry_num >= MAX_ENTRY_NUM)
    {
        fprintf(stderr, "ISO file has too many fragments ( more than %u )\n", MAX_ENTRY_NUM);
        return 1;
    }
    debug("iso file size: %llu disk name %s\n", g_iso_file_size, diskname);
    g_disk_fd = open(diskname, O_RDONLY);
    if (g_disk_fd < 0)
    {
        debug("Failed to open %s\n", diskname);
        return 1;
    }
    return 0;
}
int main(int argc, char **argv)
{
    int rc;
    int ch;
    char filename[512] = {0};
    /* Avoid to be killed by systemd */
    if (access("/etc/initrd-release", F_OK) >= 0)
    {		
        argv[0][0] = '@';
    }
    g_iso_file_name[0] = '/';
    
    while ((ch = getopt(argc, argv, "f:s:m:v::t::")) != -1)
    {
        if (ch == 'f')
        {
            strncpy(filename, optarg, sizeof(filename) - 1);
        }
        else if (ch == 'm')
        {
            strncpy(g_mnt_point, optarg, sizeof(g_mnt_point) - 1);
        }
        else if (ch == 's')
        {
            strncpy(g_iso_file_name + 1, optarg, sizeof(g_iso_file_name) - 2);
        }
        else if (ch == 'v')
        {
            verbose = 1;
        }
        else if (ch == 't') // for test
        {
            return 0;
        }
    }
    if (filename[0] == 0)
    {
        fprintf(stderr, "Must input dmsetup table file with -f\n");
        return 1;
    }
    if (g_mnt_point[0] == 0)
    {
        fprintf(stderr, "Must input mount point with -m\n");
        return 1;
    }
    if (g_iso_file_name[1] == 0)
    {
        strncpy(g_iso_file_name + 1, "ventoy.iso", sizeof(g_iso_file_name) - 2);
    }
    debug("ventoy fuse iso: %s %s %s\n", filename, g_iso_file_name, g_mnt_point);
    g_disk_entry_list = malloc(MAX_ENTRY_NUM * sizeof(dmtable_entry));
    if (NULL == g_disk_entry_list)
    {
        return 1;
    }
    rc = ventoy_parse_dmtable(filename);
    if (rc)
    {
        free(g_disk_entry_list);
        return rc;
    }
    argv[1] = g_mnt_point;
    argv[2] = NULL;
    rc = fuse_main(2, argv, &ventoy_op, NULL);
    close(g_disk_fd);
    free(g_disk_entry_list);
    return rc;
}
 | 7,887 | 
	C | 
	.c | 289 | 21.176471 | 93 | 0.555955 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 175 | 
	process_fragments.h | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/process_fragments.h | 
	#ifndef PROCESS_FRAGMENTS_H
#define PROCESS_FRAGMENTS_H
/*
 * Create a squashfs filesystem.  This is a highly compressed read only
 * filesystem.
 *
 * Copyright (c) 2014
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * process_fragments.h
 */
#define DUP_HASH(a) (a & 0xffff)
extern void *frag_thrd(void *);
#endif
 | 1,016 | 
	C | 
	.c | 28 | 34.428571 | 71 | 0.758621 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 176 | 
	zstd_wrapper.c | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/zstd_wrapper.c | 
	/*
 * Copyright (c) 2017
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * zstd_wrapper.c
 *
 * Support for ZSTD compression http://zstd.net
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <zstd.h>
#include <zstd_errors.h>
#include "squashfs_fs.h"
#include "zstd_wrapper.h"
#include "compressor.h"
static int compression_level = ZSTD_DEFAULT_COMPRESSION_LEVEL;
/*
 * This function is called by the options parsing code in mksquashfs.c
 * to parse any -X compressor option.
 *
 * This function returns:
 *	>=0 (number of additional args parsed) on success
 *	-1 if the option was unrecognised, or
 *	-2 if the option was recognised, but otherwise bad in
 *	   some way (e.g. invalid parameter)
 *
 * Note: this function sets internal compressor state, but does not
 * pass back the results of the parsing other than success/failure.
 * The zstd_dump_options() function is called later to get the options in
 * a format suitable for writing to the filesystem.
 */
static int zstd_options(char *argv[], int argc)
{
	return 1;
}
/*
 * This function is called by mksquashfs to dump the parsed
 * compressor options in a format suitable for writing to the
 * compressor options field in the filesystem (stored immediately
 * after the superblock).
 *
 * This function returns a pointer to the compression options structure
 * to be stored (and the size), or NULL if there are no compression
 * options.
 */
static void *zstd_dump_options(int block_size, int *size)
{
	return NULL;
}
/*
 * This function is a helper specifically for the append mode of
 * mksquashfs.  Its purpose is to set the internal compressor state
 * to the stored compressor options in the passed compressor options
 * structure.
 *
 * In effect this function sets up the compressor options
 * to the same state they were when the filesystem was originally
 * generated, this is to ensure on appending, the compressor uses
 * the same compression options that were used to generate the
 * original filesystem.
 *
 * Note, even if there are no compressor options, this function is still
 * called with an empty compressor structure (size == 0), to explicitly
 * set the default options, this is to ensure any user supplied
 * -X options on the appending mksquashfs command line are over-ridden.
 *
 * This function returns 0 on sucessful extraction of options, and -1 on error.
 */
static int zstd_extract_options(int block_size, void *buffer, int size)
{
	struct zstd_comp_opts *comp_opts = buffer;
	if (size == 0) {
		/* Set default values */
		compression_level = ZSTD_DEFAULT_COMPRESSION_LEVEL;
		return 0;
	}
	/* we expect a comp_opts structure of sufficient size to be present */
	if (size < sizeof(*comp_opts))
		goto failed;
	SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
	if (comp_opts->compression_level < 1) {
		fprintf(stderr, "zstd: bad compression level in compression "
			"options structure\n");
		goto failed;
	}
	compression_level = comp_opts->compression_level;
	return 0;
failed:
	fprintf(stderr, "zstd: error reading stored compressor options from "
		"filesystem!\n");
	return -1;
}
static void zstd_display_options(void *buffer, int size)
{
	struct zstd_comp_opts *comp_opts = buffer;
	/* we expect a comp_opts structure of sufficient size to be present */
	if (size < sizeof(*comp_opts))
		goto failed;
	SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
	if (comp_opts->compression_level < 1) {
		fprintf(stderr, "zstd: bad compression level in compression "
			"options structure\n");
		goto failed;
	}
	printf("\tcompression-level %d\n", comp_opts->compression_level);
	return;
failed:
	fprintf(stderr, "zstd: error reading stored compressor options from "
		"filesystem!\n");
}
/*
 * This function is called by mksquashfs to initialise the
 * compressor, before compress() is called.
 *
 * This function returns 0 on success, and -1 on error.
 */
static int zstd_init(void **strm, int block_size, int datablock)
{
	return 0;
}
static int zstd_compress(void *strm, void *dest, void *src, int size,
			 int block_size, int *error)
{
    (void)strm;
    (void)dest;
    (void)src;
    (void)size;
    (void)block_size;
    (void)error;
	return 0;
}
static int zstd_uncompress(void *dest, void *src, int size, int outsize,
			   int *error)
{
	const size_t res = ZSTD_decompress(dest, outsize, src, size);
	if (ZSTD_isError(res)) {
		fprintf(stderr, "\t%d %d\n", outsize, size);
		*error = (int)ZSTD_getErrorCode(res);
		return -1;
	}
	return (int)res;
}
static void zstd_usage(void)
{
	fprintf(stderr, "\t  -Xcompression-level <compression-level>\n");
}
struct compressor zstd_comp_ops = {
	.init = zstd_init,
	.compress = zstd_compress,
	.uncompress = zstd_uncompress,
	.options = zstd_options,
	.dump_options = zstd_dump_options,
	.extract_options = zstd_extract_options,
	.display_options = zstd_display_options,
	.usage = zstd_usage,
	.id = ZSTD_COMPRESSION,
	.name = "zstd",
	.supported = 1
};
 | 5,411 | 
	C | 
	.c | 170 | 29.647059 | 79 | 0.741174 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 183 | 
	unsquash-123.c | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/unsquash-123.c | 
	/*
 * Unsquash a squashfs filesystem.  This is a highly compressed read only
 * filesystem.
 *
 * Copyright (c) 2019
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * unsquash-123.c
 *
 * Helper functions used by unsquash-1, unsquash-2 and unsquash-3.
 */
#include "unsquashfs.h"
#include "squashfs_compat.h"
int read_ids(int ids, long long start, long long end, unsigned int **id_table)
{
	/* Note on overflow limits:
	 * Size of ids is 2^8
	 * Max length is 2^8*4 or 1024
	 */
	int res;
	int length = ids * sizeof(unsigned int);
	/*
	 * The size of the index table (length bytes) should match the
	 * table start and end points
	 */
	if(length != (end - start)) {
		ERROR("read_ids: Bad inode count in super block\n");
		return FALSE;
	}
	TRACE("read_ids: no_ids %d\n", ids);
	*id_table = malloc(length);
	if(*id_table == NULL) {
		ERROR("read_ids: failed to allocate uid/gid table\n");
		return FALSE;
	}
	if(swap) {
		unsigned int *sid_table = malloc(length);
		if(sid_table == NULL) {
			ERROR("read_ids: failed to allocate uid/gid table\n");
			return FALSE;
		}
		res = read_fs_bytes(fd, start, length, sid_table);
		if(res == FALSE) {
			ERROR("read_ids: failed to read uid/gid table"
				"\n");
			free(sid_table);
			return FALSE;
		}
		SQUASHFS_SWAP_INTS_3((*id_table), sid_table, ids);
		free(sid_table);
	} else {
		res = read_fs_bytes(fd, start, length, *id_table);
		if(res == FALSE) {
			ERROR("read_ids: failed to read uid/gid table"
				"\n");
			return FALSE;
		}
	}
	return TRUE;
}
 | 2,208 | 
	C | 
	.c | 74 | 27.243243 | 78 | 0.698824 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 184 | 
	lzma_wrapper.c | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/lzma_wrapper.c | 
	/*
 * Copyright (c) 2009, 2010, 2013
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * lzma_wrapper.c
 *
 * Support for LZMA1 compression using LZMA SDK (4.65 used in
 * development, other versions may work) http://www.7-zip.org/sdk.html
 */
#include <LzmaLib.h>
#include "squashfs_fs.h"
#include "compressor.h"
#define LZMA_HEADER_SIZE	(LZMA_PROPS_SIZE + 8)
static int lzma_compress(void *strm, void *dest, void *src, int size, int block_size,
		int *error)
{
	return 0;
}
static int lzma_uncompress(void *dest, void *src, int size, int outsize,
	int *error)
{
	unsigned char *s = src;
	size_t outlen, inlen = size - LZMA_HEADER_SIZE;
	int res;
	outlen = s[LZMA_PROPS_SIZE] |
		(s[LZMA_PROPS_SIZE + 1] << 8) |
		(s[LZMA_PROPS_SIZE + 2] << 16) |
		(s[LZMA_PROPS_SIZE + 3] << 24);
	if(outlen > outsize) {
		*error = 0;
		return -1;
	}
	res = LzmaUncompress(dest, &outlen, src + LZMA_HEADER_SIZE, &inlen, src,
		LZMA_PROPS_SIZE);
	
	if(res == SZ_OK)
		return outlen;
	else {
		*error = res;
		return -1;
	}
}
struct compressor lzma_comp_ops = {
	.init = NULL,
	.compress = lzma_compress,
	.uncompress = lzma_uncompress,
	.options = NULL,
	.usage = NULL,
	.id = LZMA_COMPRESSION,
	.name = "lzma",
	.supported = 1
};
 | 1,922 | 
	C | 
	.c | 65 | 27.4 | 85 | 0.710255 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 185 | 
	fnmatch_compat.h | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/fnmatch_compat.h | 
	#ifndef FNMATCH_COMPAT
#define FNMATCH_COMPAT
/*
 * Squashfs
 *
 * Copyright (c) 2015
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * fnmatch_compat.h
 */
#include <fnmatch.h>
#ifndef FNM_EXTMATCH
#define FNM_EXTMATCH	0
#endif
#endif
 | 936 | 
	C | 
	.c | 29 | 30.448276 | 71 | 0.764381 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 188 | 
	gzip_wrapper.c | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/gzip_wrapper.c | 
	/*
 * Copyright (c) 2009, 2010, 2013, 2014
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * gzip_wrapper.c
 *
 * Support for ZLIB compression http://www.zlib.net
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <zlib.h>
#include "squashfs_fs.h"
#include "gzip_wrapper.h"
#include "compressor.h"
static struct strategy strategy[] = {
	{ "default", Z_DEFAULT_STRATEGY, 0 },
	{ "filtered", Z_FILTERED, 0 },
	{ "huffman_only", Z_HUFFMAN_ONLY, 0 },
	{ "run_length_encoded", Z_RLE, 0 },
	{ "fixed", Z_FIXED, 0 },
	{ NULL, 0, 0 }
};
static int strategy_count = 0;
/* default compression level */
static int compression_level = GZIP_DEFAULT_COMPRESSION_LEVEL;
/* default window size */
static int window_size = GZIP_DEFAULT_WINDOW_SIZE;
/*
 * This function is called by the options parsing code in mksquashfs.c
 * to parse any -X compressor option.
 *
 * This function returns:
 *	>=0 (number of additional args parsed) on success
 *	-1 if the option was unrecognised, or
 *	-2 if the option was recognised, but otherwise bad in
 *	   some way (e.g. invalid parameter)
 *
 * Note: this function sets internal compressor state, but does not
 * pass back the results of the parsing other than success/failure.
 * The gzip_dump_options() function is called later to get the options in
 * a format suitable for writing to the filesystem.
 */
static int gzip_options(char *argv[], int argc)
{
	if(strcmp(argv[0], "-Xcompression-level") == 0) {
		if(argc < 2) {
			fprintf(stderr, "gzip: -Xcompression-level missing "
				"compression level\n");
			fprintf(stderr, "gzip: -Xcompression-level it "
				"should be 1 >= n <= 9\n");
			goto failed;
		}
		compression_level = atoi(argv[1]);
		if(compression_level < 1 || compression_level > 9) {
			fprintf(stderr, "gzip: -Xcompression-level invalid, it "
				"should be 1 >= n <= 9\n");
			goto failed;
		}
		return 1;
	} else if(strcmp(argv[0], "-Xwindow-size") == 0) {
		if(argc < 2) {
			fprintf(stderr, "gzip: -Xwindow-size missing window "
				"	size\n");
			fprintf(stderr, "gzip: -Xwindow-size <window-size>\n");
			goto failed;
		}
		window_size = atoi(argv[1]);
		if(window_size < 8 || window_size > 15) {
			fprintf(stderr, "gzip: -Xwindow-size invalid, it "
				"should be 8 >= n <= 15\n");
			goto failed;
		}
		return 1;
	} else if(strcmp(argv[0], "-Xstrategy") == 0) {
		char *name;
		int i;
		if(argc < 2) {
			fprintf(stderr, "gzip: -Xstrategy missing "
							"strategies\n");
			goto failed;
		}
		name = argv[1];
		while(name[0] != '\0') {
			for(i = 0; strategy[i].name; i++) {
				int n = strlen(strategy[i].name);
				if((strncmp(name, strategy[i].name, n) == 0) &&
						(name[n] == '\0' ||
						 name[n] == ',')) {
					if(strategy[i].selected == 0) {
				 		strategy[i].selected = 1;
						strategy_count++;
					}
					name += name[n] == ',' ? n + 1 : n;
					break;
				}
			}
			if(strategy[i].name == NULL) {
				fprintf(stderr, "gzip: -Xstrategy unrecognised "
					"strategy\n");
				goto failed;
			}
		}
	
		return 1;
	}
	return -1;
failed:
	return -2;
}
/*
 * This function is called after all options have been parsed.
 * It is used to do post-processing on the compressor options using
 * values that were not expected to be known at option parse time.
 *
 * This function returns 0 on successful post processing, or
 *			-1 on error
 */
static int gzip_options_post(int block_size)
{
	if(strategy_count == 1 && strategy[0].selected) {
		strategy_count = 0;
		strategy[0].selected = 0;
	}
	return 0;
}
/*
 * This function is called by mksquashfs to dump the parsed
 * compressor options in a format suitable for writing to the
 * compressor options field in the filesystem (stored immediately
 * after the superblock).
 *
 * This function returns a pointer to the compression options structure
 * to be stored (and the size), or NULL if there are no compression
 * options
 *
 */
static void *gzip_dump_options(int block_size, int *size)
{
	static struct gzip_comp_opts comp_opts;
	int i, strategies = 0;
	/*
	 * If default compression options of:
	 * compression-level: 8 and
	 * window-size: 15 and
	 * strategy_count == 0 then
	 * don't store a compression options structure (this is compatible
	 * with the legacy implementation of GZIP for Squashfs)
	 */
	if(compression_level == GZIP_DEFAULT_COMPRESSION_LEVEL &&
				window_size == GZIP_DEFAULT_WINDOW_SIZE &&
				strategy_count == 0)
		return NULL;
	for(i = 0; strategy[i].name; i++)
		strategies |= strategy[i].selected << i;
	comp_opts.compression_level = compression_level;
	comp_opts.window_size = window_size;
	comp_opts.strategy = strategies;
	SQUASHFS_INSWAP_COMP_OPTS(&comp_opts);
	*size = sizeof(comp_opts);
	return &comp_opts;
}
/*
 * This function is a helper specifically for the append mode of
 * mksquashfs.  Its purpose is to set the internal compressor state
 * to the stored compressor options in the passed compressor options
 * structure.
 *
 * In effect this function sets up the compressor options
 * to the same state they were when the filesystem was originally
 * generated, this is to ensure on appending, the compressor uses
 * the same compression options that were used to generate the
 * original filesystem.
 *
 * Note, even if there are no compressor options, this function is still
 * called with an empty compressor structure (size == 0), to explicitly
 * set the default options, this is to ensure any user supplied
 * -X options on the appending mksquashfs command line are over-ridden
 *
 * This function returns 0 on sucessful extraction of options, and
 *			-1 on error
 */
static int gzip_extract_options(int block_size, void *buffer, int size)
{
	struct gzip_comp_opts *comp_opts = buffer;
	int i;
	if(size == 0) {
		/* Set default values */
		compression_level = GZIP_DEFAULT_COMPRESSION_LEVEL;
		window_size = GZIP_DEFAULT_WINDOW_SIZE;
		strategy_count = 0;
		return 0;
	}
	/* we expect a comp_opts structure of sufficient size to be present */
	if(size < sizeof(*comp_opts))
		goto failed;
	SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
	/* Check comp_opts structure for correctness */
	if(comp_opts->compression_level < 1 ||
			comp_opts->compression_level > 9) {
		fprintf(stderr, "gzip: bad compression level in "
			"compression options structure\n");
		goto failed;
	}
	compression_level = comp_opts->compression_level;
	if(comp_opts->window_size < 8 ||
			comp_opts->window_size > 15) {
		fprintf(stderr, "gzip: bad window size in "
			"compression options structure\n");
		goto failed;
	}
	window_size = comp_opts->window_size;
	strategy_count = 0;
	for(i = 0; strategy[i].name; i++) {
		if((comp_opts->strategy >> i) & 1) {
			strategy[i].selected = 1;
			strategy_count ++;
		} else
			strategy[i].selected = 0;
	}
	
	return 0;
failed:
	fprintf(stderr, "gzip: error reading stored compressor options from "
		"filesystem!\n");
	return -1;
}
static void gzip_display_options(void *buffer, int size)
{
	struct gzip_comp_opts *comp_opts = buffer;
	int i, printed;
	/* we expect a comp_opts structure of sufficient size to be present */
	if(size < sizeof(*comp_opts))
		goto failed;
	SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
	/* Check comp_opts structure for correctness */
	if(comp_opts->compression_level < 1 ||
			comp_opts->compression_level > 9) {
		fprintf(stderr, "gzip: bad compression level in "
			"compression options structure\n");
		goto failed;
	}
	printf("\tcompression-level %d\n", comp_opts->compression_level);
	if(comp_opts->window_size < 8 ||
			comp_opts->window_size > 15) {
		fprintf(stderr, "gzip: bad window size in "
			"compression options structure\n");
		goto failed;
	}
	printf("\twindow-size %d\n", comp_opts->window_size);
	for(i = 0, printed = 0; strategy[i].name; i++) {
		if((comp_opts->strategy >> i) & 1) {
			if(printed)
				printf(", ");
			else
				printf("\tStrategies selected: ");
			printf("%s", strategy[i].name);
			printed = 1;
		}
	}
	if(!printed)
		printf("\tStrategies selected: default\n");
	else
		printf("\n");
	return;
failed:
	fprintf(stderr, "gzip: error reading stored compressor options from "
		"filesystem!\n");
}	
/*
 * This function is called by mksquashfs to initialise the
 * compressor, before compress() is called.
 *
 * This function returns 0 on success, and
 *			-1 on error
 */
static int gzip_init(void **strm, int block_size, int datablock)
{
	int i, j, res;
	struct gzip_stream *stream;
	if(!datablock || !strategy_count) {
		stream = malloc(sizeof(*stream) + sizeof(struct gzip_strategy));
		if(stream == NULL)
			goto failed;
		stream->strategies = 1;
		stream->strategy[0].strategy = Z_DEFAULT_STRATEGY;
	} else {
		stream = malloc(sizeof(*stream) +
			sizeof(struct gzip_strategy) * strategy_count);
		if(stream == NULL)
			goto failed;
		memset(stream->strategy, 0, sizeof(struct gzip_strategy) *
			strategy_count);
		stream->strategies = strategy_count;
		for(i = 0, j = 0; strategy[i].name; i++) {
			if(!strategy[i].selected)
				continue;
			stream->strategy[j].strategy = strategy[i].strategy;
			if(j) {
				stream->strategy[j].buffer = malloc(block_size);
				if(stream->strategy[j].buffer == NULL)
					goto failed2;
			}
			j++;
		}
	}
		
	stream->stream.zalloc = Z_NULL;
	stream->stream.zfree = Z_NULL;
	stream->stream.opaque = 0;
	res = deflateInit2(&stream->stream, compression_level, Z_DEFLATED,
		window_size, 8, stream->strategy[0].strategy);
	if(res != Z_OK)
		goto failed2;
	*strm = stream;
	return 0;
failed2:
	for(i = 1; i < stream->strategies; i++)
		free(stream->strategy[i].buffer);
	free(stream);
failed:
	return -1;
}
static int gzip_compress(void *strm, void *d, void *s, int size, int block_size,
		int *error)
{
	int i, res;
	struct gzip_stream *stream = strm;
	struct gzip_strategy *selected = NULL;
	stream->strategy[0].buffer = d;
	for(i = 0; i < stream->strategies; i++) {
		struct gzip_strategy *strategy = &stream->strategy[i];
		res = deflateReset(&stream->stream);
		if(res != Z_OK)
			goto failed;
		stream->stream.next_in = s;
		stream->stream.avail_in = size;
		stream->stream.next_out = strategy->buffer;
		stream->stream.avail_out = block_size;
		if(stream->strategies > 1) {
			res = deflateParams(&stream->stream,
				compression_level, strategy->strategy);
			if(res != Z_OK)
				goto failed;
		}
		res = deflate(&stream->stream, Z_FINISH);
		strategy->length = stream->stream.total_out;
		if(res == Z_STREAM_END) {
			if(!selected || selected->length > strategy->length)
				selected = strategy;
		} else if(res != Z_OK)
			goto failed;
	}
	if(!selected)
		/*
		 * Output buffer overflow.  Return out of buffer space
		 */
		return 0;
	if(selected->buffer != d)
		memcpy(d, selected->buffer, selected->length);
	return (int) selected->length;
failed:
	/*
	 * All other errors return failure, with the compressor
	 * specific error code in *error
	 */
	*error = res;
	return -1;
}
static int gzip_uncompress(void *d, void *s, int size, int outsize, int *error)
{
	int res;
	unsigned long bytes = outsize;
	res = uncompress(d, &bytes, s, size);
	if(res == Z_OK)
		return (int) bytes;
	else {
		*error = res;
		return -1;
	}
}
static void gzip_usage()
{
	fprintf(stderr, "\t  -Xcompression-level <compression-level>\n");
	fprintf(stderr, "\t\t<compression-level> should be 1 .. 9 (default "
		"%d)\n", GZIP_DEFAULT_COMPRESSION_LEVEL);
	fprintf(stderr, "\t  -Xwindow-size <window-size>\n");
	fprintf(stderr, "\t\t<window-size> should be 8 .. 15 (default "
		"%d)\n", GZIP_DEFAULT_WINDOW_SIZE);
	fprintf(stderr, "\t  -Xstrategy strategy1,strategy2,...,strategyN\n");
	fprintf(stderr, "\t\tCompress using strategy1,strategy2,...,strategyN"
		" in turn\n");
	fprintf(stderr, "\t\tand choose the best compression.\n");
	fprintf(stderr, "\t\tAvailable strategies: default, filtered, "
		"huffman_only,\n\t\trun_length_encoded and fixed\n");
}
struct compressor gzip_comp_ops = {
	.init = gzip_init,
	.compress = gzip_compress,
	.uncompress = gzip_uncompress,
	.options = gzip_options,
	.options_post = gzip_options_post,
	.dump_options = gzip_dump_options,
	.extract_options = gzip_extract_options,
	.display_options = gzip_display_options,
	.usage = gzip_usage,
	.id = ZLIB_COMPRESSION,
	.name = "gzip",
	.supported = 1
};
 | 12,898 | 
	C | 
	.c | 421 | 27.855107 | 80 | 0.69461 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 189 | 
	read_xattrs.c | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/read_xattrs.c | 
	/*
 * Read a squashfs filesystem.  This is a highly compressed read only
 * filesystem.
 *
 * Copyright (c) 2010, 2012, 2013, 2019
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * read_xattrs.c
 */
/*
 * Common xattr read code shared between mksquashfs and unsquashfs
 */
#define TRUE 1
#define FALSE 0
#include <stdio.h>
#include <string.h>
#ifndef linux
#define __BYTE_ORDER BYTE_ORDER
#define __BIG_ENDIAN BIG_ENDIAN
#define __LITTLE_ENDIAN LITTLE_ENDIAN
#else
#include <endian.h>
#endif
#include "squashfs_fs.h"
#include "squashfs_swap.h"
#include "xattr.h"
#include "error.h"
#include <stdlib.h>
extern int read_fs_bytes(int, long long, int, void *);
extern int read_block(int, long long, long long *, int, void *);
static struct hash_entry {
	long long		start;
	unsigned int		offset;
	struct hash_entry	*next;
} *hash_table[65536];
static struct squashfs_xattr_id *xattr_ids;
static void *xattrs = NULL;
static long long xattr_table_start;
/*
 * Prefix lookup table, storing mapping to/from prefix string and prefix id
 */
struct prefix prefix_table[] = {
	{ "user.", SQUASHFS_XATTR_USER },
	{ "trusted.", SQUASHFS_XATTR_TRUSTED },
	{ "security.", SQUASHFS_XATTR_SECURITY },
	{ "", -1 }
};
/*
 * store mapping from location of compressed block in fs ->
 * location of uncompressed block in memory
 */
static void save_xattr_block(long long start, int offset)
{
	struct hash_entry *hash_entry = malloc(sizeof(*hash_entry));
	int hash = start & 0xffff;
	TRACE("save_xattr_block: start %lld, offset %d\n", start, offset);
	if(hash_entry == NULL)
		MEM_ERROR();
	hash_entry->start = start;
	hash_entry->offset = offset;
	hash_entry->next = hash_table[hash];
	hash_table[hash] = hash_entry;
}
/*
 * map from location of compressed block in fs ->
 * location of uncompressed block in memory
 */
static int get_xattr_block(long long start)
{
	int hash = start & 0xffff;
	struct hash_entry *hash_entry = hash_table[hash];
	for(; hash_entry; hash_entry = hash_entry->next)
		if(hash_entry->start == start)
			break;
	TRACE("get_xattr_block: start %lld, offset %d\n", start,
		hash_entry ? hash_entry->offset : -1);
	return hash_entry ? hash_entry->offset : -1;
}
/*
 * construct the xattr_list entry from the fs xattr, including
 * mapping name and prefix into a full name
 */
static int read_xattr_entry(struct xattr_list *xattr,
	struct squashfs_xattr_entry *entry, void *name)
{
	int i, len, type = entry->type & XATTR_PREFIX_MASK;
	for(i = 0; prefix_table[i].type != -1; i++)
		if(prefix_table[i].type == type)
			break;
	if(prefix_table[i].type == -1) {
		ERROR("read_xattr_entry: Unrecognised xattr type %d\n", type);
		return 0;
	}
	len = strlen(prefix_table[i].prefix);
	xattr->full_name = malloc(len + entry->size + 1);
	if(xattr->full_name == NULL)
		MEM_ERROR();
	memcpy(xattr->full_name, prefix_table[i].prefix, len);
	memcpy(xattr->full_name + len, name, entry->size);
	xattr->full_name[len + entry->size] = '\0';
	xattr->name = xattr->full_name + len;
	xattr->size = entry->size;
	xattr->type = type;
	return 1;
}
/*
 * Read and decompress the xattr id table and the xattr metadata.
 * This is cached in memory for later use by get_xattr()
 */
int read_xattrs_from_disk(int fd, struct squashfs_super_block *sBlk, int flag, long long *table_start)
{
	/*
	 * Note on overflow limits:
	 * Size of ids (id_table.xattr_ids) is 2^32 (unsigned int)
	 * Max size of bytes is 2^32*16 or 2^36
	 * Max indexes is (2^32*16)/8K or 2^23
	 * Max index_bytes is ((2^32*16)/8K)*8 or 2^26 or 64M
	 */
	int res, i, indexes, index_bytes;
	unsigned int ids;
	long long bytes;
	long long *index, start, end;
	struct squashfs_xattr_table id_table;
	TRACE("read_xattrs_from_disk\n");
	if(sBlk->xattr_id_table_start == SQUASHFS_INVALID_BLK)
		return SQUASHFS_INVALID_BLK;
	/*
	 * Read xattr id table, containing start of xattr metadata and the
	 * number of xattrs in the file system
	 */
	res = read_fs_bytes(fd, sBlk->xattr_id_table_start, sizeof(id_table),
		&id_table);
	if(res == 0)
		return 0;
	SQUASHFS_INSWAP_XATTR_TABLE(&id_table);
	/*
	 * Compute index table values
	 */
	ids = id_table.xattr_ids;
	xattr_table_start = id_table.xattr_table_start;
	index_bytes = SQUASHFS_XATTR_BLOCK_BYTES((long long) ids);
	indexes = SQUASHFS_XATTR_BLOCKS((long long) ids);
	/*
	 * The size of the index table (index_bytes) should match the
	 * table start and end points
	 */
	if(index_bytes != (sBlk->bytes_used - (sBlk->xattr_id_table_start + sizeof(id_table)))) {
		ERROR("read_xattrs_from_disk: Bad xattr_ids count in super block\n");
		return 0;
	}
	/*
	 * id_table.xattr_table_start stores the start of the compressed xattr
	 * metadata blocks.  This by definition is also the end of the previous
	 * filesystem table - the id lookup table.
	 */
	if(table_start != NULL)
		*table_start = id_table.xattr_table_start;
	/*
	 * If flag is set then return once we've read the above
	 * table_start.  That value is necessary for sanity checking,
	 * but we don't actually want to extract the xattrs, and so
	 * stop here.
	 */
	if(flag)
		return id_table.xattr_ids;
	/*
	 * Allocate and read the index to the xattr id table metadata
	 * blocks
	 */
	index = malloc(index_bytes);
	if(index == NULL)
		MEM_ERROR();
	res = read_fs_bytes(fd, sBlk->xattr_id_table_start + sizeof(id_table),
		index_bytes, index);
	if(res ==0)
		goto failed1;
	SQUASHFS_INSWAP_LONG_LONGS(index, indexes);
	/*
	 * Allocate enough space for the uncompressed xattr id table, and
	 * read and decompress it
	 */
	bytes = SQUASHFS_XATTR_BYTES((long long) ids);
	xattr_ids = malloc(bytes);
	if(xattr_ids == NULL)
		MEM_ERROR();
	for(i = 0; i < indexes; i++) {
		int expected = (i + 1) != indexes ? SQUASHFS_METADATA_SIZE :
					bytes & (SQUASHFS_METADATA_SIZE - 1);
		int length = read_block(fd, index[i], NULL, expected,
			((unsigned char *) xattr_ids) +
			((long long) i * SQUASHFS_METADATA_SIZE));
		TRACE("Read xattr id table block %d, from 0x%llx, length "
			"%d\n", i, index[i], length);
		if(length == 0) {
			ERROR("Failed to read xattr id table block %d, "
				"from 0x%llx, length %d\n", i, index[i],
				length);
			goto failed2;
		}
	}
	/*
	 * Read and decompress the xattr metadata
	 *
	 * Note the first xattr id table metadata block is immediately after
	 * the last xattr metadata block, so we can use index[0] to work out
	 * the end of the xattr metadata
	 */
	start = xattr_table_start;
	end = index[0];
	for(i = 0; start < end; i++) {
		int length;
		xattrs = realloc(xattrs, (i + 1) * SQUASHFS_METADATA_SIZE);
		if(xattrs == NULL)
			MEM_ERROR();
		/* store mapping from location of compressed block in fs ->
		 * location of uncompressed block in memory */
		save_xattr_block(start, i * SQUASHFS_METADATA_SIZE);
		length = read_block(fd, start, &start, 0,
			((unsigned char *) xattrs) +
			(i * SQUASHFS_METADATA_SIZE));
		TRACE("Read xattr block %d, length %d\n", i, length);
		if(length == 0) {
			ERROR("Failed to read xattr block %d\n", i);
			goto failed3;
		}
		/*
		 * If this is not the last metadata block in the xattr metadata
		 * then it should be SQUASHFS_METADATA_SIZE in size.
		 * Note, we can't use expected in read_block() above for this
		 * because we don't know if this is the last block until
		 * after reading.
		 */
		if(start != end && length != SQUASHFS_METADATA_SIZE) {
			ERROR("Xattr block %d should be %d bytes in length, "
				"it is %d bytes\n", i, SQUASHFS_METADATA_SIZE,
				length);
			goto failed3;
		}
	}
	/* swap if necessary the xattr id entries */
	for(i = 0; i < ids; i++)
		SQUASHFS_INSWAP_XATTR_ID(&xattr_ids[i]);
	free(index);
	return ids;
failed3:
	free(xattrs);
failed2:
	free(xattr_ids);
failed1:
	free(index);
	return 0;
}
void free_xattr(struct xattr_list *xattr_list, int count)
{
	int i;
	for(i = 0; i < count; i++)
		free(xattr_list[i].full_name);
	free(xattr_list);
}
/*
 * Construct and return the list of xattr name:value pairs for the passed xattr
 * id
 *
 * There are two users for get_xattr(), Mksquashfs uses it to read the
 * xattrs from the filesystem on appending, and Unsquashfs uses it
 * to retrieve the xattrs for writing to disk.
 *
 * Unfortunately, the two users disagree on what to do with unknown
 * xattr prefixes, Mksquashfs wants to treat this as fatal otherwise
 * this will cause xattrs to be be lost on appending.  Unsquashfs
 * on the otherhand wants to retrieve the xattrs which are known and
 * to ignore the rest, this allows Unsquashfs to cope more gracefully
 * with future versions which may have unknown xattrs, as long as the
 * general xattr structure is adhered to, Unsquashfs should be able
 * to safely ignore unknown xattrs, and to write the ones it knows about,
 * this is better than completely refusing to retrieve all the xattrs.
 *
 * So return an error flag if any unrecognised types were found.
 */
struct xattr_list *get_xattr(int i, unsigned int *count, int *failed)
{
	long long start;
	struct xattr_list *xattr_list = NULL;
	unsigned int offset;
	void *xptr;
	int j, n, res = 1;
	TRACE("get_xattr\n");
	if(xattr_ids[i].count == 0) {
		ERROR("get_xattr: xattr count unexpectedly 0 - corrupt fs?\n");
		*failed = TRUE;
		*count = 0;
		return NULL;
	} else
		*failed = FALSE;
	start = SQUASHFS_XATTR_BLK(xattr_ids[i].xattr) + xattr_table_start;
	offset = SQUASHFS_XATTR_OFFSET(xattr_ids[i].xattr);
	xptr = xattrs + get_xattr_block(start) + offset;
	TRACE("get_xattr: xattr_id %d, count %d, start %lld, offset %d\n", i,
			xattr_ids[i].count, start, offset);
	for(j = 0, n = 0; n < xattr_ids[i].count; n++) {
		struct squashfs_xattr_entry entry;
		struct squashfs_xattr_val val;
		if(res != 0) {
			xattr_list = realloc(xattr_list, (j + 1) *
						sizeof(struct xattr_list));
			if(xattr_list == NULL)
				MEM_ERROR();
		}
			
		SQUASHFS_SWAP_XATTR_ENTRY(xptr, &entry);
		xptr += sizeof(entry);
		res = read_xattr_entry(&xattr_list[j], &entry, xptr);
		if(res == 0) {
			/* unknown type, skip, and set error flag */
			xptr += entry.size;
			SQUASHFS_SWAP_XATTR_VAL(xptr, &val);
			xptr += sizeof(val) + val.vsize;
			*failed = TRUE;
			continue;
		}
		xptr += entry.size;
			
		TRACE("get_xattr: xattr %d, type %d, size %d, name %s\n", j,
			entry.type, entry.size, xattr_list[j].full_name); 
		if(entry.type & SQUASHFS_XATTR_VALUE_OOL) {
			long long xattr;
			void *ool_xptr;
			xptr += sizeof(val);
			SQUASHFS_SWAP_LONG_LONGS(xptr, &xattr, 1);
			xptr += sizeof(xattr);	
			start = SQUASHFS_XATTR_BLK(xattr) + xattr_table_start;
			offset = SQUASHFS_XATTR_OFFSET(xattr);
			ool_xptr = xattrs + get_xattr_block(start) + offset;
			SQUASHFS_SWAP_XATTR_VAL(ool_xptr, &val);
			xattr_list[j].value = ool_xptr + sizeof(val);
		} else {
			SQUASHFS_SWAP_XATTR_VAL(xptr, &val);
			xattr_list[j].value = xptr + sizeof(val);
			xptr += sizeof(val) + val.vsize;
		}
		TRACE("get_xattr: xattr %d, vsize %d\n", j, val.vsize);
		xattr_list[j++].vsize = val.vsize;
	}
	*count = j;
	return xattr_list;
}
 | 11,638 | 
	C | 
	.c | 358 | 29.868715 | 102 | 0.697162 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 194 | 
	lzo_wrapper.c | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/lzo_wrapper.c | 
	/*
 * Copyright (c) 2013, 2014
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * lzo_wrapper.c
 *
 * Support for LZO compression http://www.oberhumer.com/opensource/lzo
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <lzo/lzoconf.h>
#include <lzo/lzo1x.h>
#include "squashfs_fs.h"
#include "lzo_wrapper.h"
#include "compressor.h"
static struct lzo_algorithm lzo[] = {
	{ "lzo1x_1", LZO1X_1_MEM_COMPRESS, lzo1x_1_compress },
	{ "lzo1x_1_11", LZO1X_1_11_MEM_COMPRESS, lzo1x_1_11_compress },
	{ "lzo1x_1_12", LZO1X_1_12_MEM_COMPRESS, lzo1x_1_12_compress },
	{ "lzo1x_1_15", LZO1X_1_15_MEM_COMPRESS, lzo1x_1_15_compress },
	{ "lzo1x_999", LZO1X_999_MEM_COMPRESS, lzo1x_999_wrapper },
	{ NULL, 0, NULL } 
};
/* default LZO compression algorithm and compression level */
static int algorithm = SQUASHFS_LZO1X_999;
static int compression_level = SQUASHFS_LZO1X_999_COMP_DEFAULT;
/* user specified compression level */
static int user_comp_level = -1;
/*
 * This function is called by the options parsing code in mksquashfs.c
 * to parse any -X compressor option.
 *
 * This function returns:
 *	>=0 (number of additional args parsed) on success
 *	-1 if the option was unrecognised, or
 *	-2 if the option was recognised, but otherwise bad in
 *	   some way (e.g. invalid parameter)
 *
 * Note: this function sets internal compressor state, but does not
 * pass back the results of the parsing other than success/failure.
 * The lzo_dump_options() function is called later to get the options in
 * a format suitable for writing to the filesystem.
 */
static int lzo_options(char *argv[], int argc)
{
    (void)argv;
    (void)argc;
	return 1;
}
/*
 * This function is called after all options have been parsed.
 * It is used to do post-processing on the compressor options using
 * values that were not expected to be known at option parse time.
 *
 * In this case the LZO algorithm may not be known until after the
 * compression level has been set (-Xalgorithm used after -Xcompression-level)
 *
 * This function returns 0 on successful post processing, or
 *			-1 on error
 */
static int lzo_options_post(int block_size)
{
	/*
	 * Use of compression level only makes sense for
	 * LZO1X_999 algorithm
	 */
	if(user_comp_level != -1) {
		if(algorithm != SQUASHFS_LZO1X_999) {
			fprintf(stderr, "lzo: -Xcompression-level not "
				"supported by selected %s algorithm\n",
				lzo[algorithm].name);
			fprintf(stderr, "lzo: -Xcompression-level is only "
				"applicable for the lzo1x_999 algorithm\n");
			goto failed;
		}
		compression_level = user_comp_level;
	}
	return 0;
failed:
	return -1;
}
/*
 * This function is called by mksquashfs to dump the parsed
 * compressor options in a format suitable for writing to the
 * compressor options field in the filesystem (stored immediately
 * after the superblock).
 *
 * This function returns a pointer to the compression options structure
 * to be stored (and the size), or NULL if there are no compression
 * options
 *
 */
static void *lzo_dump_options(int block_size, int *size)
{
	static struct lzo_comp_opts comp_opts;
	/*
	 * If default compression options of SQUASHFS_LZO1X_999 and
	 * compression level of SQUASHFS_LZO1X_999_COMP_DEFAULT then
	 * don't store a compression options structure (this is compatible
	 * with the legacy implementation of LZO for Squashfs)
	 */
	if(algorithm == SQUASHFS_LZO1X_999 &&
			compression_level == SQUASHFS_LZO1X_999_COMP_DEFAULT)
		return NULL;
	comp_opts.algorithm = algorithm;
	comp_opts.compression_level = algorithm == SQUASHFS_LZO1X_999 ?
		compression_level : 0;
	SQUASHFS_INSWAP_COMP_OPTS(&comp_opts);
	*size = sizeof(comp_opts);
	return &comp_opts;
}
/*
 * This function is a helper specifically for the append mode of
 * mksquashfs.  Its purpose is to set the internal compressor state
 * to the stored compressor options in the passed compressor options
 * structure.
 *
 * In effect this function sets up the compressor options
 * to the same state they were when the filesystem was originally
 * generated, this is to ensure on appending, the compressor uses
 * the same compression options that were used to generate the
 * original filesystem.
 *
 * Note, even if there are no compressor options, this function is still
 * called with an empty compressor structure (size == 0), to explicitly
 * set the default options, this is to ensure any user supplied
 * -X options on the appending mksquashfs command line are over-ridden
 *
 * This function returns 0 on sucessful extraction of options, and
 *			-1 on error
 */
static int lzo_extract_options(int block_size, void *buffer, int size)
{
	struct lzo_comp_opts *comp_opts = buffer;
	if(size == 0) {
		/* Set default values */
		algorithm = SQUASHFS_LZO1X_999;
		compression_level = SQUASHFS_LZO1X_999_COMP_DEFAULT;
		return 0;
	}
	/* we expect a comp_opts structure of sufficient size to be present */
	if(size < sizeof(*comp_opts))
		goto failed;
	SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
	/* Check comp_opts structure for correctness */
	switch(comp_opts->algorithm) {
	case SQUASHFS_LZO1X_1:
	case SQUASHFS_LZO1X_1_11:
	case SQUASHFS_LZO1X_1_12:
	case SQUASHFS_LZO1X_1_15:
		if(comp_opts->compression_level != 0) {
			fprintf(stderr, "lzo: bad compression level in "
				"compression options structure\n");
			goto failed;
		}
		break;
	case SQUASHFS_LZO1X_999:
		if(comp_opts->compression_level < 1 ||
				comp_opts->compression_level > 9) {
			fprintf(stderr, "lzo: bad compression level in "
				"compression options structure\n");
			goto failed;
		}
		compression_level = comp_opts->compression_level;
		break;
	default:
		fprintf(stderr, "lzo: bad algorithm in compression options "
				"structure\n");
			goto failed;
	}
	algorithm = comp_opts->algorithm;
	return 0;
failed:
	fprintf(stderr, "lzo: error reading stored compressor options from "
		"filesystem!\n");
	return -1;
}
static void lzo_display_options(void *buffer, int size)
{
	struct lzo_comp_opts *comp_opts = buffer;
	/* we expect a comp_opts structure of sufficient size to be present */
	if(size < sizeof(*comp_opts))
		goto failed;
	SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
	/* Check comp_opts structure for correctness */
	switch(comp_opts->algorithm) {
	case SQUASHFS_LZO1X_1:
	case SQUASHFS_LZO1X_1_11:
	case SQUASHFS_LZO1X_1_12:
	case SQUASHFS_LZO1X_1_15:
		printf("\talgorithm %s\n", lzo[comp_opts->algorithm].name);
		break;
	case SQUASHFS_LZO1X_999:
		if(comp_opts->compression_level < 1 ||
				comp_opts->compression_level > 9) {
			fprintf(stderr, "lzo: bad compression level in "
				"compression options structure\n");
			goto failed;
		}
		printf("\talgorithm %s\n", lzo[comp_opts->algorithm].name);
		printf("\tcompression level %d\n",
						comp_opts->compression_level);
		break;
	default:
		fprintf(stderr, "lzo: bad algorithm in compression options "
				"structure\n");
			goto failed;
	}
	return;
failed:
	fprintf(stderr, "lzo: error reading stored compressor options from "
		"filesystem!\n");
}	
/*
 * This function is called by mksquashfs to initialise the
 * compressor, before compress() is called.
 *
 * This function returns 0 on success, and
 *			-1 on error
 */
static int squashfs_lzo_init(void **strm, int block_size, int datablock)
{
	struct lzo_stream *stream;
	stream = *strm = malloc(sizeof(struct lzo_stream));
	if(stream == NULL)
		goto failed;
	stream->workspace = malloc(lzo[algorithm].size);
	if(stream->workspace == NULL)
		goto failed2;
	stream->buffer = malloc(LZO_MAX_EXPANSION(block_size));
	if(stream->buffer != NULL)
		return 0;
	free(stream->workspace);
failed2:
	free(stream);
failed:
	return -1;
}
static int lzo_compress(void *strm, void *dest, void *src,  int size,
	int block_size, int *error)
{
    
	return 0;
}
static int lzo_uncompress(void *dest, void *src, int size, int outsize,
	int *error)
{
	int res;
	lzo_uint outlen = outsize;
	res = lzo1x_decompress_safe(src, size, dest, &outlen, NULL);
	if(res != LZO_E_OK) {
		*error = res;
		return -1;
	}
	return outlen;
}
static void lzo_usage()
{
	int i;
	fprintf(stderr, "\t  -Xalgorithm <algorithm>\n");
	fprintf(stderr, "\t\tWhere <algorithm> is one of:\n");
	for(i = 0; lzo[i].name; i++)
		fprintf(stderr, "\t\t\t%s%s\n", lzo[i].name,
				i == SQUASHFS_LZO1X_999 ? " (default)" : "");
	fprintf(stderr, "\t  -Xcompression-level <compression-level>\n");
	fprintf(stderr, "\t\t<compression-level> should be 1 .. 9 (default "
		"%d)\n", SQUASHFS_LZO1X_999_COMP_DEFAULT);
	fprintf(stderr, "\t\tOnly applies to lzo1x_999 algorithm\n");
}
/*
 * Helper function for lzo1x_999 compression algorithm.
 * All other lzo1x_xxx compressors do not take a compression level,
 * so we need to wrap lzo1x_999 to pass the compression level which
 * is applicable to it
 */
int lzo1x_999_wrapper(const lzo_bytep src, lzo_uint src_len, lzo_bytep dst,
	lzo_uintp compsize, lzo_voidp workspace)
{
	return lzo1x_999_compress_level(src, src_len, dst, compsize,
		workspace, NULL, 0, 0, compression_level);
}
struct compressor lzo_comp_ops = {
	.init = squashfs_lzo_init,
	.compress = lzo_compress,
	.uncompress = lzo_uncompress,
	.options = lzo_options,
	.options_post = lzo_options_post,
	.dump_options = lzo_dump_options,
	.extract_options = lzo_extract_options,
	.display_options = lzo_display_options,
	.usage = lzo_usage,
	.id = LZO_COMPRESSION,
	.name = "lzo",
	.supported = 1
};
 | 10,072 | 
	C | 
	.c | 309 | 30.220065 | 78 | 0.732763 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 197 | 
	lz4_wrapper.c | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/lz4_wrapper.c | 
	/*
 * Copyright (c) 2013, 2019
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * lz4_wrapper.c
 *
 * Support for LZ4 compression http://fastcompression.blogspot.com/p/lz4.html
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <lz4.h>
#include <lz4hc.h>
#include "squashfs_fs.h"
#include "lz4_wrapper.h"
#include "compressor.h"
/* LZ4 1.7.0 introduced new functions, and since r131,
 * the older functions produce deprecated warnings.
 *
 * There are still too many distros using older versions
 * to switch to the newer functions, but, the deprecated
 * functions may completely disappear.  This is a mess.
 *
 * Support both by checking the library version and
 * using shadow definitions
 */
/* Earlier (but > 1.7.0) versions don't define this */
#ifndef LZ4HC_CLEVEL_MAX
#define LZ4HC_CLEVEL_MAX 12
#endif
#if LZ4_VERSION_NUMBER >= 10700
#define COMPRESS(src, dest, size, max)		 LZ4_compress_default(src, dest, size, max)
#define COMPRESS_HC(src, dest, size, max)	 LZ4_compress_HC(src, dest, size, max, LZ4HC_CLEVEL_MAX)
#else
#define COMPRESS(src, dest, size, max)		 LZ4_compress_limitedOutput(src, dest, size, max)
#define COMPRESS_HC(src, dest, size, max)	 LZ4_compressHC_limitedOutput(src, dest, size, max)
#endif
static int hc = 0;
/*
 * This function is called by the options parsing code in mksquashfs.c
 * to parse any -X compressor option.
 *
 * This function returns:
 *	>=0 (number of additional args parsed) on success
 *	-1 if the option was unrecognised, or
 *	-2 if the option was recognised, but otherwise bad in
 *	   some way (e.g. invalid parameter)
 *
 * Note: this function sets internal compressor state, but does not
 * pass back the results of the parsing other than success/failure.
 * The lz4_dump_options() function is called later to get the options in
 * a format suitable for writing to the filesystem.
 */
static int lz4_options(char *argv[], int argc)
{
	if(strcmp(argv[0], "-Xhc") == 0) {
		hc = 1;
		return 0;
	}
	return -1;
}
/*
 * This function is called by mksquashfs to dump the parsed
 * compressor options in a format suitable for writing to the
 * compressor options field in the filesystem (stored immediately
 * after the superblock).
 *
 * This function returns a pointer to the compression options structure
 * to be stored (and the size), or NULL if there are no compression
 * options
 *
 * Currently LZ4 always returns a comp_opts structure, with
 * the version indicating LZ4_LEGACY stream fomat.  This is to
 * easily accomodate changes in the kernel code to different
 * stream formats 
 */
static void *lz4_dump_options(int block_size, int *size)
{
	static struct lz4_comp_opts comp_opts;
	comp_opts.version = LZ4_LEGACY;
	comp_opts.flags = hc ? LZ4_HC : 0;
	SQUASHFS_INSWAP_COMP_OPTS(&comp_opts);
	*size = sizeof(comp_opts);
	return &comp_opts;
}
/*
 * This function is a helper specifically for the append mode of
 * mksquashfs.  Its purpose is to set the internal compressor state
 * to the stored compressor options in the passed compressor options
 * structure.
 *
 * In effect this function sets up the compressor options
 * to the same state they were when the filesystem was originally
 * generated, this is to ensure on appending, the compressor uses
 * the same compression options that were used to generate the
 * original filesystem.
 *
 * Note, even if there are no compressor options, this function is still
 * called with an empty compressor structure (size == 0), to explicitly
 * set the default options, this is to ensure any user supplied
 * -X options on the appending mksquashfs command line are over-ridden
 *
 * This function returns 0 on sucessful extraction of options, and
 *			-1 on error
 */
static int lz4_extract_options(int block_size, void *buffer, int size)
{
	struct lz4_comp_opts *comp_opts = buffer;
	/* we expect a comp_opts structure to be present */
	if(size < sizeof(*comp_opts))
		goto failed;
	SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
	/* we expect the stream format to be LZ4_LEGACY */
	if(comp_opts->version != LZ4_LEGACY) {
		fprintf(stderr, "lz4: unknown LZ4 version\n");
		goto failed;
	}
	/*
	 * Check compression flags, currently only LZ4_HC ("high compression")
	 * can be set.
	 */
	if(comp_opts->flags == LZ4_HC)
		hc = 1;
	else if(comp_opts->flags != 0) {
		fprintf(stderr, "lz4: unknown LZ4 flags\n");
		goto failed;
	}
	return 0;
failed:
	fprintf(stderr, "lz4: error reading stored compressor options from "
		"filesystem!\n");
	return -1;
}
/*
 * This function is a helper specifically for unsquashfs.
 * Its purpose is to check that the compression options are
 * understood by this version of LZ4.
 *
 * This is important for LZ4 because the format understood by the
 * Linux kernel may change from the already obsolete legacy format
 * currently supported.
 *
 * If this does happen, then this version of LZ4 will not be able to decode
 * the newer format.  So we need to check for this.
 *
 * This function returns 0 on sucessful checking of options, and
 *			-1 on error
 */
static int lz4_check_options(int block_size, void *buffer, int size)
{
	struct lz4_comp_opts *comp_opts = buffer;
	/* we expect a comp_opts structure to be present */
	if(size < sizeof(*comp_opts))
		goto failed;
	SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
	/* we expect the stream format to be LZ4_LEGACY */
	if(comp_opts->version != LZ4_LEGACY) {
		fprintf(stderr, "lz4: unknown LZ4 version\n");
		goto failed;
	}
	return 0;
failed:
	fprintf(stderr, "lz4: error reading stored compressor options from "
		"filesystem!\n");
	return -1;
}
static void lz4_display_options(void *buffer, int size)
{
	struct lz4_comp_opts *comp_opts = buffer;
	/* check passed comp opts struct is of the correct length */
	if(size < sizeof(*comp_opts))
		goto failed;
	SQUASHFS_INSWAP_COMP_OPTS(comp_opts);
	/* we expect the stream format to be LZ4_LEGACY */
	if(comp_opts->version != LZ4_LEGACY) {
		fprintf(stderr, "lz4: unknown LZ4 version\n");
		goto failed;
	}
	/*
	 * Check compression flags, currently only LZ4_HC ("high compression")
	 * can be set.
	 */
	if(comp_opts->flags & ~LZ4_FLAGS_MASK) {
		fprintf(stderr, "lz4: unknown LZ4 flags\n");
		goto failed;
	}
	if(comp_opts->flags & LZ4_HC)
		printf("\tHigh Compression option specified (-Xhc)\n");
	return;
failed:
	fprintf(stderr, "lz4: error reading stored compressor options from "
		"filesystem!\n");
}	
static int lz4_compress(void *strm, void *dest, void *src,  int size,
	int block_size, int *error)
{
	return 0;
}
static int lz4_uncompress(void *dest, void *src, int size, int outsize,
	int *error)
{
	int res = LZ4_decompress_safe(src, dest, size, outsize);
	if(res < 0) {
		*error = res;
		return -1;
	}
	return res;
}
static void lz4_usage()
{
	fprintf(stderr, "\t  -Xhc\n");
	fprintf(stderr, "\t\tCompress using LZ4 High Compression\n");
}
struct compressor lz4_comp_ops = {
	.compress = lz4_compress,
	.uncompress = lz4_uncompress,
	.options = lz4_options,
	.dump_options = lz4_dump_options,
	.extract_options = lz4_extract_options,
	.check_options = lz4_check_options,
	.display_options = lz4_display_options,
	.usage = lz4_usage,
	.id = LZ4_COMPRESSION,
	.name = "lz4",
	.supported = 1
};
 | 7,894 | 
	C | 
	.c | 240 | 30.804167 | 98 | 0.737119 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 201 | 
	unsquash-34.c | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/unsquash-34.c | 
	/*
 * Unsquash a squashfs filesystem.  This is a highly compressed read only
 * filesystem.
 *
 * Copyright (c) 2019
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * unsquash-34.c
 *
 * Helper functions used by unsquash-3 and unsquash-4.
 */
#include "unsquashfs.h"
long long *alloc_index_table(int indexes)
{
	static long long *alloc_table = NULL;
	static int alloc_size = 0;
	int length = indexes * sizeof(long long);
	if(alloc_size < length || length == 0) {
		long long *table = realloc(alloc_table, length);
		if(table == NULL && length !=0)
			EXIT_UNSQUASH("alloc_index_table: failed to allocate "
				"index table\n");
		alloc_table = table;
		alloc_size = length;
	}
	return alloc_table;
}
 | 1,403 | 
	C | 
	.c | 41 | 31.97561 | 73 | 0.735988 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 208 | 
	read_file.c | 
	ventoy_Ventoy/SQUASHFS/squashfs-tools-4.4/squashfs-tools/read_file.c | 
	/*
 * Create a squashfs filesystem.  This is a highly compressed read only
 * filesystem.
 *
 * Copyright (c) 2012
 * Phillip Lougher <phillip@squashfs.org.uk>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2,
 * or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 * read_file.c
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include "error.h"
#define TRUE 1
#define FALSE 0
#define MAX_LINE 16384
/*
 * Read file, passing each line to parse_line() for
 * parsing.
 *
 * Lines can be split across multiple lines using "\".
 * 
 * Blank lines and comment lines indicated by # are supported.
 */
int read_file(char *filename, char *type, int (parse_line)(char *))
{
	FILE *fd;
	char *def, *err, *line = NULL;
	int res, size = 0;
	fd = fopen(filename, "r");
	if(fd == NULL) {
		ERROR("Could not open %s device file \"%s\" because %s\n",
			type, filename, strerror(errno));
		return FALSE;
	}
	while(1) {
		int total = 0;
		while(1) {
			int len;
			if(total + (MAX_LINE + 1) > size) {
				line = realloc(line, size += (MAX_LINE + 1));
				if(line == NULL)
					MEM_ERROR();
			}
			err = fgets(line + total, MAX_LINE + 1, fd);
			if(err == NULL)
				break;
			len = strlen(line + total);
			total += len;
			if(len == MAX_LINE && line[total - 1] != '\n') {
				/* line too large */
				ERROR("Line too long when reading "
					"%s file \"%s\", larger than "
					"%d bytes\n", type, filename, MAX_LINE);
				goto failed;
			}
			/*
			 * Remove '\n' terminator if it exists (the last line
			 * in the file may not be '\n' terminated)
			 */
			if(len && line[total - 1] == '\n') {
				line[-- total] = '\0';
				len --;
			}
			/*
			 * If no line continuation then jump out to
			 * process line.  Note, we have to be careful to
			 * check for "\\" (backslashed backslash) and to
			 * ensure we don't look at the previous line
			 */
			if(len == 0 || line[total - 1] != '\\' || (len >= 2 &&
					strcmp(line + total - 2, "\\\\") == 0))
				break;
			else
				total --;
		}	
		if(err == NULL) {
			if(ferror(fd)) {
                		ERROR("Reading %s file \"%s\" failed "
					"because %s\n", type, filename,
					strerror(errno));
				goto failed;
			}
			/*
			 * At EOF, normally we'll be finished, but, have to
			 * check for special case where we had "\" line
			 * continuation and then hit EOF immediately afterwards
			 */
			if(total == 0)
				break;
			else
				line[total] = '\0';
		}
		/* Skip any leading whitespace */
		for(def = line; isspace(*def); def ++);
		/* if line is now empty after skipping characters, skip it */
		if(*def == '\0')
			continue;
		/* if comment line, skip */
		if(*def == '#')
			continue;
		res = parse_line(def);
		if(res == FALSE)
			goto failed;
	}
	fclose(fd);
	free(line);
	return TRUE;
failed:
	fclose(fd);
	free(line);
	return FALSE;
}
 | 3,459 | 
	C | 
	.c | 129 | 23.364341 | 71 | 0.631006 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 256 | 
	huffman.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/huffman.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Huffman alphabets
 *
 */
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "wimboot.h"
#include "huffman.h"
/**
 * Transcribe binary value (for debugging)
 *
 * @v value		Value
 * @v bits		Length of value (in bits)
 * @ret string		Transcribed value
 */
static const char * huffman_bin ( unsigned long value, unsigned int bits ) {
	static char buf[ ( 8 * sizeof ( value ) ) + 1 /* NUL */ ];
	char *out = buf;
	/* Sanity check */
	assert ( bits < sizeof ( buf ) );
	/* Transcribe value */
	while ( bits-- )
		*(out++) = ( ( value & ( 1 << bits ) ) ? '1' : '0' );
	*out = '\0';
	return buf;
}
/**
 * Dump Huffman alphabet (for debugging)
 *
 * @v alphabet		Huffman alphabet
 */
static void __attribute__ (( unused ))
huffman_dump_alphabet ( struct huffman_alphabet *alphabet ) {
	struct huffman_symbols *sym;
	unsigned int bits;
	unsigned int huf;
	unsigned int i;
	/* Dump symbol table for each utilised length */
	for ( bits = 1 ; bits <= ( sizeof ( alphabet->huf ) /
				   sizeof ( alphabet->huf[0] ) ) ; bits++ ) {
		sym = &alphabet->huf[ bits - 1 ];
		if ( sym->freq == 0 )
			continue;
		huf = ( sym->start >> sym->shift );
		DBG ( "Huffman length %d start \"%s\" freq %d:", bits,
		      huffman_bin ( huf, sym->bits ), sym->freq );
		for ( i = 0 ; i < sym->freq ; i++ ) {
			DBG ( " %03x", sym->raw[ huf + i ] );
		}
		DBG ( "\n" );
	}
	/* Dump quick lookup table */
	DBG ( "Huffman quick lookup:" );
	for ( i = 0 ; i < ( sizeof ( alphabet->lookup ) /
			    sizeof ( alphabet->lookup[0] ) ) ; i++ ) {
		DBG ( " %d", ( alphabet->lookup[i] + 1 ) );
	}
	DBG ( "\n" );
}
/**
 * Construct Huffman alphabet
 *
 * @v alphabet		Huffman alphabet
 * @v lengths		Symbol length table
 * @v count		Number of symbols
 * @ret rc		Return status code
 */
int huffman_alphabet ( struct huffman_alphabet *alphabet,
		       uint8_t *lengths, unsigned int count ) {
	struct huffman_symbols *sym;
	unsigned int huf;
	unsigned int cum_freq;
	unsigned int bits;
	unsigned int raw;
	unsigned int adjustment;
	unsigned int prefix;
	int empty;
	int complete;
	/* Clear symbol table */
	memset ( alphabet->huf, 0, sizeof ( alphabet->huf ) );
	/* Count number of symbols with each Huffman-coded length */
	empty = 1;
	for ( raw = 0 ; raw < count ; raw++ ) {
		bits = lengths[raw];
		if ( bits ) {
			alphabet->huf[ bits - 1 ].freq++;
			empty = 0;
		}
	}
	/* In the degenerate case of having no symbols (i.e. an unused
	 * alphabet), generate a trivial alphabet with exactly two
	 * single-bit codes.  This allows callers to avoid having to
	 * check for this special case.
	 */
	if ( empty )
		alphabet->huf[0].freq = 2;
	/* Populate Huffman-coded symbol table */
	huf = 0;
	cum_freq = 0;
	for ( bits = 1 ; bits <= ( sizeof ( alphabet->huf ) /
				   sizeof ( alphabet->huf[0] ) ) ; bits++ ) {
		sym = &alphabet->huf[ bits - 1 ];
		sym->bits = bits;
		sym->shift = ( HUFFMAN_BITS - bits );
		sym->start = ( huf << sym->shift );
		sym->raw = &alphabet->raw[cum_freq];
		huf += sym->freq;
		if ( huf > ( 1U << bits ) ) {
			DBG ( "Huffman alphabet has too many symbols with "
			      "lengths <=%d\n", bits );
			return -1;
		}
		huf <<= 1;
		cum_freq += sym->freq;
	}
	complete = ( huf == ( 1U << bits ) );
	/* Populate raw symbol table */
	for ( raw = 0 ; raw < count ; raw++ ) {
		bits = lengths[raw];
		if ( bits ) {
			sym = &alphabet->huf[ bits - 1 ];
			*(sym->raw++) = raw;
		}
	}
	/* Adjust Huffman-coded symbol table raw pointers and populate
	 * quick lookup table.
	 */
	for ( bits = 1 ; bits <= ( sizeof ( alphabet->huf ) /
				   sizeof ( alphabet->huf[0] ) ) ; bits++ ) {
		sym = &alphabet->huf[ bits - 1 ];
		/* Adjust raw pointer */
		sym->raw -= sym->freq; /* Reset to first symbol */
		adjustment = ( sym->start >> sym->shift );
		sym->raw -= adjustment; /* Adjust for quick indexing */
		/* Populate quick lookup table */
		for ( prefix = ( sym->start >> HUFFMAN_QL_SHIFT ) ;
		      prefix < ( 1 << HUFFMAN_QL_BITS ) ; prefix++ ) {
			alphabet->lookup[prefix] = ( bits - 1 );
		}
	}
	/* Check that there are no invalid codes */
	if ( ! complete ) {
		DBG ( "Huffman alphabet is incomplete\n" );
		return -1;
	}
	return 0;
}
/**
 * Get Huffman symbol set
 *
 * @v alphabet		Huffman alphabet
 * @v huf		Raw input value (normalised to HUFFMAN_BITS bits)
 * @ret sym		Huffman symbol set
 */
struct huffman_symbols * huffman_sym ( struct huffman_alphabet *alphabet,
				       unsigned int huf ) {
	struct huffman_symbols *sym;
	unsigned int lookup_index;
	/* Find symbol set for this length */
	lookup_index = ( huf >> HUFFMAN_QL_SHIFT );
	sym = &alphabet->huf[ alphabet->lookup[ lookup_index ] ];
	while ( huf < sym->start )
		sym--;
	return sym;
}
 | 5,519 | 
	C | 
	.c | 187 | 26.839572 | 76 | 0.63484 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 258 | 
	pause.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/pause.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Diagnostic pause
 *
 */
#include <stdio.h>
#include "wimboot.h"
#include "cmdline.h"
#include "pause.h"
/**
 * Pause before booting
 *
 */
void pause ( void ) {
	/* Wait for keypress, prompting unless inhibited */
	if ( cmdline_pause_quiet ) {
		getchar();
	} else {
		printf ( "Press any key to continue booting..." );
		getchar();
		printf ( "\n" );
	}
}
 | 1,174 | 
	C | 
	.c | 42 | 25.97619 | 70 | 0.719858 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 259 | 
	peloader.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/peloader.c | 
	/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * PE image loader
 *
 */
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include "wimboot.h"
#include "peloader.h"
/**
 * Load PE image into memory
 *
 * @v data		PE image
 * @v len		Length of PE image
 * @v pe		Loaded PE structure to fill in
 * @ret rc		Return status code
 */
int load_pe ( const void *data, size_t len, struct loaded_pe *pe ) {
	const struct mz_header *mzhdr;
	size_t pehdr_offset;
	const struct pe_header *pehdr;
	size_t opthdr_offset;
	const struct pe_optional_header *opthdr;
	size_t section_offset;
	const struct coff_section *section;
	char name[ sizeof ( section->name ) + 1 /* NUL */ ];
	unsigned int i;
	void *section_base;
	size_t filesz;
	size_t memsz;
	void *end;
	void *raw_base;
	DBG2 ( "Loading PE executable...\n" );
	/* Parse PE header */
	mzhdr = data;
	if ( mzhdr->magic != MZ_HEADER_MAGIC ) {
		DBG ( "Bad MZ magic %04x\n", mzhdr->magic );
		return -1;
	}
	pehdr_offset = mzhdr->lfanew;
	if ( pehdr_offset > len ) {
		DBG ( "PE header outside file\n" );
		return -1;
	}
	pehdr = ( data + pehdr_offset );
	if ( pehdr->magic != PE_HEADER_MAGIC ) {
		DBG ( "Bad PE magic %08x\n", pehdr->magic );
		return -1;
	}
	opthdr_offset = ( pehdr_offset + sizeof ( *pehdr ) );
	opthdr = ( data + opthdr_offset );
	pe->base = ( ( void * ) ( intptr_t ) ( opthdr->base ) );
	section_offset = ( opthdr_offset + pehdr->coff.opthdr_len );
	section = ( data + section_offset );
	/* Load header into memory */
	DBG2 ( "...headers to %p+%#x\n", pe->base, opthdr->header_len );
	memcpy ( pe->base, data, opthdr->header_len );
	end = ( pe->base + opthdr->header_len );
	/* Load each section into memory */
	for ( i = 0 ; i < pehdr->coff.num_sections ; i++, section++ ) {
		memset ( name, 0, sizeof ( name ) );
		memcpy ( name, section->name, sizeof ( section->name ) );
		section_base = ( pe->base + section->virtual );
		filesz = section->raw_len;
		memsz = section->misc.virtual_len;
		DBG2 ( "...from %#05x to %p+%#zx/%#zx (%s)\n",
		       section->raw, section_base, filesz, memsz, name );
		memset ( section_base, 0, memsz );
		memcpy ( section_base, ( data + section->raw ), filesz );
		if ( end < ( section_base + memsz ) )
			end = ( section_base + memsz );
	}
	pe->len = ( ( ( end - pe->base ) + opthdr->section_align - 1 )
		    & ~( opthdr->section_align - 1 ) );
	/* Load copy of raw image into memory immediately after loaded
	 * sections.  This seems to be used for verification of X.509
	 * signatures.
	 */
	raw_base = ( pe->base + pe->len );
	memcpy ( raw_base, data, len );
	pe->len += len;
	DBG2 ( "...raw copy to %p+%#zx\n", raw_base, len );
	/* Extract entry point */
	pe->entry = ( pe->base + opthdr->entry );
	DBG2 ( "...entry point %p\n", pe->entry );
	return 0;
}
 | 3,557 | 
	C | 
	.c | 108 | 30.638889 | 70 | 0.657459 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 261 | 
	xca.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/xca.c | 
	/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Xpress Compression Algorithm (MS-XCA) decompression
 *
 */
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include "wimboot.h"
#include "huffman.h"
#include "xca.h"
/**
 * Decompress XCA-compressed data
 *
 * @v data		Compressed data
 * @v len		Length of compressed data
 * @v buf		Decompression buffer, or NULL
 * @ret out_len		Length of decompressed data, or negative error
 */
ssize_t xca_decompress ( const void *data, size_t len, void *buf ) {
	const void *src = data;
	const void *end = ( uint8_t * ) src + len;
	uint8_t *out = buf;
	size_t out_len = 0;
	size_t out_len_threshold = 0;
	const struct xca_huf_len *lengths;
	struct xca xca;
	uint32_t accum = 0;
	int extra_bits = 0;
	unsigned int huf;
	struct huffman_symbols *sym;
	unsigned int raw;
	unsigned int match_len;
	unsigned int match_offset_bits;
	unsigned int match_offset;
	const uint8_t *copy;
	int rc;
	/* Process data stream */
	while ( src < end ) {
		/* (Re)initialise decompressor if applicable */
		if ( out_len >= out_len_threshold ) {
			/* Construct symbol lengths */
			lengths = src;
			src = ( uint8_t * ) src + sizeof ( *lengths );
			if ( src > end ) {
				DBG ( "XCA too short to hold Huffman lengths table.\n");
				return -1;
			}
			for ( raw = 0 ; raw < XCA_CODES ; raw++ )
				xca.lengths[raw] = xca_huf_len ( lengths, raw );
			/* Construct Huffman alphabet */
			if ( ( rc = huffman_alphabet ( &xca.alphabet,
						       xca.lengths,
						       XCA_CODES ) ) != 0 )
				return rc;
			/* Initialise state */
			accum = XCA_GET16 ( src );
			accum <<= 16;
			accum |= XCA_GET16 ( src );
			extra_bits = 16;
			/* Determine next threshold */
			out_len_threshold = ( out_len + XCA_BLOCK_SIZE );
		}
		/* Determine symbol */
		huf = ( accum >> ( 32 - HUFFMAN_BITS ) );
		sym = huffman_sym ( &xca.alphabet, huf );
		raw = huffman_raw ( sym, huf );
		accum <<= huffman_len ( sym );
		extra_bits -= huffman_len ( sym );
		if ( extra_bits < 0 ) {
			accum |= ( XCA_GET16 ( src ) << ( -extra_bits ) );
			extra_bits += 16;
		}
		/* Process symbol */
		if ( raw < XCA_END_MARKER ) {
			/* Literal symbol - add to output stream */
			if ( buf )
				*(out++) = raw;
			out_len++;
		} else if ( ( raw == XCA_END_MARKER ) &&
			    ( (uint8_t *) src >= ( ( uint8_t * ) end - 1 ) ) ) {
			/* End marker symbol */
			return out_len;
		} else {
			/* LZ77 match symbol */
			raw -= XCA_END_MARKER;
			match_offset_bits = ( raw >> 4 );
			match_len = ( raw & 0x0f );
			if ( match_len == 0x0f ) {
				match_len = XCA_GET8 ( src );
				if ( match_len == 0xff ) {
					match_len = XCA_GET16 ( src );
				} else {
					match_len += 0x0f;
				}
			}
			match_len += 3;
			if ( match_offset_bits ) {
				match_offset =
					( ( accum >> ( 32 - match_offset_bits ))
					  + ( 1 << match_offset_bits ) );
			} else {
				match_offset = 1;
			}
			accum <<= match_offset_bits;
			extra_bits -= match_offset_bits;
			if ( extra_bits < 0 ) {
				accum |= ( XCA_GET16 ( src ) << (-extra_bits) );
				extra_bits += 16;
			}
			/* Copy data */
			out_len += match_len;
			if ( buf ) {
				copy = ( out - match_offset );
				while ( match_len-- )
					*(out++) = *(copy++);
			}
		}
	}
	return out_len;
}
 | 4,030 | 
	C | 
	.c | 141 | 25.170213 | 70 | 0.618187 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 262 | 
	wchar.h | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/wchar.h | 
	#ifndef _WCHAR_H
#define _WCHAR_H
/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Wide characters
 *
 */
#include <stdint.h>
typedef void mbstate_t;
/**
 * Convert wide character to multibyte sequence
 *
 * @v buf		Buffer
 * @v wc		Wide character
 * @v ps		Shift state
 * @ret len		Number of characters written
 *
 * This is a stub implementation, sufficient to handle basic ASCII
 * characters.
 */
static inline size_t wcrtomb ( char *buf, wchar_t wc,
			       mbstate_t *ps __attribute__ (( unused )) ) {
	*buf = wc;
	return 1;
}
extern int wcscasecmp ( const wchar_t *str1, const wchar_t *str2 );
extern size_t wcslen ( const wchar_t *str );
extern wchar_t * wcschr ( const wchar_t *str, wchar_t c );
extern char *strchr(const char *str, char c);
#endif /* _WCHAR_H */
 | 1,546 | 
	C | 
	.c | 49 | 29.510204 | 70 | 0.721477 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 264 | 
	efipath.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/efipath.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * EFI device paths
 *
 */
#include "wimboot.h"
#include "efi.h"
#include "efipath.h"
/**
 * Find end of device path
 *
 * @v path		Path to device
 * @ret path_end	End of device path
 */
EFI_DEVICE_PATH_PROTOCOL * efi_devpath_end ( EFI_DEVICE_PATH_PROTOCOL *path ) {
	while ( path->Type != END_DEVICE_PATH_TYPE ) {
		path = ( ( ( void * ) path ) +
			 /* There's this amazing new-fangled thing known as
			  * a UINT16, but who wants to use one of those? */
			 ( ( path->Length[1] << 8 ) | path->Length[0] ) );
	}
	return path;
}
 | 1,345 | 
	C | 
	.c | 42 | 29.857143 | 79 | 0.704388 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 265 | 
	wim.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/wim.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * WIM images
 *
 */
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <wchar.h>
#include <assert.h>
#include "wimboot.h"
#include "vdisk.h"
#include "lzx.h"
#include "xca.h"
#include "wim.h"
/** WIM chunk buffer */
static struct wim_chunk_buffer wim_chunk_buffer;
/**
 * Get WIM header
 *
 * @v file		Virtual file
 * @v header		WIM header to fill in
 * @ret rc		Return status code
 */
int wim_header ( struct vdisk_file *file, struct wim_header *header ) {
	/* Sanity check */
	if ( sizeof ( *header ) > file->len ) {
		DBG ( "WIM file too short (%#zx bytes)\n", file->len );
		return -1;
	}
	/* Read WIM header */
	file->read ( file, header, 0, sizeof ( *header ) );
	return 0;
}
/**
 * Get compressed chunk offset
 *
 * @v file		Virtual file
 * @v resource		Resource
 * @v chunk		Chunk number
 * @v offset		Offset to fill in
 * @ret rc		Return status code
 */
static int wim_chunk_offset ( struct vdisk_file *file,
			      struct wim_resource_header *resource,
			      unsigned int chunk, size_t *offset ) {
	size_t zlen = ( resource->zlen__flags & WIM_RESHDR_ZLEN_MASK );
	unsigned int chunks;
	size_t offset_offset;
	size_t offset_len;
	size_t chunks_len;
	union {
		uint32_t offset_32;
		uint64_t offset_64;
	} u;
	/* Special case: zero-length files have no chunks */
	if ( ! resource->len ) {
		*offset = 0;
		return 0;
	}
	/* Calculate chunk parameters */
	chunks = ( ( resource->len + WIM_CHUNK_LEN - 1 ) / WIM_CHUNK_LEN );
	offset_len = ( ( resource->len > 0xffffffffULL ) ?
		       sizeof ( u.offset_64 ) : sizeof ( u.offset_32 ) );
	chunks_len = ( ( chunks - 1 ) * offset_len );
	/* Sanity check */
	if ( chunks_len > zlen ) {
		DBG ( "Resource too short for %d chunks\n", chunks );
		return -1;
	}
	/* Special case: chunk 0 has no offset field */
	if ( ! chunk ) {
		*offset = chunks_len;
		return 0;
	}
	/* Treat out-of-range chunks as being at the end of the
	 * resource, to allow for length calculation on the final
	 * chunk.
	 */
	if ( chunk >= chunks ) {
		*offset = zlen;
		return 0;
	}
	/* Otherwise, read the chunk offset */
	offset_offset = ( ( chunk - 1 ) * offset_len );
	file->read ( file, &u, ( resource->offset + offset_offset ),
		     offset_len );
	*offset = ( chunks_len + ( ( offset_len == sizeof ( u.offset_64 ) ) ?
				   u.offset_64 : u.offset_32 ) );
	if ( *offset > zlen ) {
		DBG ( "Chunk %d offset lies outside resource\n", chunk );
		return -1;
	}
	return 0;
}
/**
 * Read chunk from a compressed resource
 *
 * @v file		Virtual file
 * @v header		WIM header
 * @v resource		Resource
 * @v chunk		Chunk number
 * @v buf		Chunk buffer
 * @ret rc		Return status code
 */
static int wim_chunk ( struct vdisk_file *file, struct wim_header *header,
		       struct wim_resource_header *resource,
		       unsigned int chunk, struct wim_chunk_buffer *buf ) {
	ssize_t ( * decompress ) ( const void *data, size_t len, void *buf );
	unsigned int chunks;
	size_t offset;
	size_t next_offset;
	size_t len;
	size_t expected_out_len;
	ssize_t out_len;
	int rc;
	/* Get chunk compressed data offset and length */
	if ( ( rc = wim_chunk_offset ( file, resource, chunk,
				       &offset ) ) != 0 )
		return rc;
	if ( ( rc = wim_chunk_offset ( file, resource, ( chunk + 1 ),
				       &next_offset ) ) != 0 )
		return rc;
	len = ( next_offset - offset );
	/* Calculate uncompressed length */
	assert ( resource->len > 0 );
	chunks = ( ( resource->len + WIM_CHUNK_LEN - 1 ) / WIM_CHUNK_LEN );
	expected_out_len = WIM_CHUNK_LEN;
	if ( chunk >= ( chunks - 1 ) )
		expected_out_len -= ( -resource->len & ( WIM_CHUNK_LEN - 1 ) );
	/* Read possibly-compressed data */
	if ( len == expected_out_len ) {
		/* Chunk did not compress; read raw data */
		file->read ( file, buf->data, ( resource->offset + offset ),
			     len );
	} else {
		uint8_t zbuf[len];
		/* Read compressed data into a temporary buffer */
		file->read ( file, zbuf, ( resource->offset + offset ), len );
		/* Identify decompressor */
		if ( header->flags & WIM_HDR_LZX ) {
			decompress = lzx_decompress;
        } else if (header->flags & WIM_HDR_XPRESS) {
            decompress = xca_decompress;
		} else {
			DBG ( "Can't handle unknown compression scheme %#08x "
			      "for %#llx chunk %d at [%#llx+%#llx)\n",
			      header->flags, resource->offset,
			      chunk, ( resource->offset + offset ),
			      ( resource->offset + offset + len ) );
			return -1;
		}
		/* Decompress data */
		out_len = decompress ( zbuf, len, NULL );
		if ( out_len < 0 )
			return out_len;
		if ( ( ( size_t ) out_len ) != expected_out_len ) {
			DBG ( "Unexpected output length %#lx (expected %#zx)\n",
			      out_len, expected_out_len );
			return -1;
		}
		decompress ( zbuf, len, buf->data );
	}
	return 0;
}
/**
 * Read from a (possibly compressed) resource
 *
 * @v file		Virtual file
 * @v header		WIM header
 * @v resource		Resource
 * @v data		Data buffer
 * @v offset		Starting offset
 * @v len		Length
 * @ret rc		Return status code
 */
int wim_read ( struct vdisk_file *file, struct wim_header *header,
	       struct wim_resource_header *resource, void *data,
	       size_t offset, size_t len ) {
	static struct vdisk_file *cached_file;
	static size_t cached_resource_offset;
	static unsigned int cached_chunk;
	size_t zlen = ( resource->zlen__flags & WIM_RESHDR_ZLEN_MASK );
	unsigned int chunk;
	size_t skip_len;
	size_t frag_len;
	int rc;
	/* Sanity checks */
	if ( ( offset + len ) > resource->len ) {
		DBG ( "Resource too short (%#llx bytes)\n", resource->len );
		return -1;
	}
	if ( ( resource->offset + zlen ) > file->len ) {
		DBG ( "Resource exceeds length of file\n" );
		return -1;
	}
	/* If resource is uncompressed, just read the raw data */
	if ( ! ( resource->zlen__flags & ( WIM_RESHDR_COMPRESSED |
					   WIM_RESHDR_PACKED_STREAMS ) ) ) {
		file->read ( file, data, ( resource->offset + offset ), len );
		return 0;
	}
	/* Read from each chunk overlapping the target region */
	while ( len ) {
		/* Calculate chunk number */
		chunk = ( offset / WIM_CHUNK_LEN );
		/* Read chunk, if not already cached */
		if ( ( file != cached_file ) ||
		     ( resource->offset != cached_resource_offset ) ||
		     ( chunk != cached_chunk ) ) {
			/* Read chunk */
			if ( ( rc = wim_chunk ( file, header, resource, chunk,
						&wim_chunk_buffer ) ) != 0 )
				return rc;
			/* Update cache */
			cached_file = file;
			cached_resource_offset = resource->offset;
			cached_chunk = chunk;
		}
		/* Copy fragment from this chunk */
		skip_len = ( offset % WIM_CHUNK_LEN );
		frag_len = ( WIM_CHUNK_LEN - skip_len );
		if ( frag_len > len )
			frag_len = len;
		memcpy ( data, ( wim_chunk_buffer.data + skip_len ), frag_len );
		/* Move to next chunk */
		data += frag_len;
		offset += frag_len;
		len -= frag_len;
	}
	return 0;
}
/**
 * Get number of images
 *
 * @v file		Virtual file
 * @v header		WIM header
 * @v count		Count of images to fill in
 * @ret rc		Return status code
 */
int wim_count ( struct vdisk_file *file, struct wim_header *header,
		unsigned int *count ) {
	struct wim_lookup_entry entry;
	size_t offset;
	int rc;
	/* Count metadata entries */
	for ( offset = 0 ; ( offset + sizeof ( entry ) ) <= header->lookup.len ;
	      offset += sizeof ( entry ) ) {
		/* Read entry */
		if ( ( rc = wim_read ( file, header, &header->lookup, &entry,
				       offset, sizeof ( entry ) ) ) != 0 )
			return rc;
		/* Check for metadata entries */
		if ( entry.resource.zlen__flags & WIM_RESHDR_METADATA ) {
			(*count)++;
			DBG2 ( "...found image %d metadata at +%#zx\n",
			       *count, offset );
		}
	}
	return 0;
}
/**
 * Get WIM image metadata
 *
 * @v file		Virtual file
 * @v header		WIM header
 * @v index		Image index, or 0 to use boot image
 * @v meta		Metadata to fill in
 * @ret rc		Return status code
 */
int wim_metadata ( struct vdisk_file *file, struct wim_header *header,
		   unsigned int index, struct wim_resource_header *meta ) {
	struct wim_lookup_entry entry;
	size_t offset;
	unsigned int found = 0;
	int rc;
	/* If no image index is specified, just use the boot metadata */
	if ( index == 0 ) {
		memcpy ( meta, &header->boot, sizeof ( *meta ) );
		return 0;
	}
	/* Look for metadata entry */
	for ( offset = 0 ; ( offset + sizeof ( entry ) ) <= header->lookup.len ;
	      offset += sizeof ( entry ) ) {
		/* Read entry */
		if ( ( rc = wim_read ( file, header, &header->lookup, &entry,
				       offset, sizeof ( entry ) ) ) != 0 )
			return rc;
		/* Look for our target entry */
		if ( entry.resource.zlen__flags & WIM_RESHDR_METADATA ) {
			found++;
			DBG2 ( "...found image %d metadata at +%#zx\n",
			       found, offset );
			if ( found == index ) {
				memcpy ( meta, &entry.resource,
					 sizeof ( *meta ) );
				return 0;
			}
		}
	}
	/* Fail if index was not found */
	DBG ( "Cannot find WIM image index %d in %s\n", index, file->name );
	return -1;
}
/**
 * Get directory entry
 *
 * @v file		Virtual file
 * @v header		WIM header
 * @v meta		Metadata
 * @v name		Name
 * @v offset		Directory offset (will be updated)
 * @v direntry		Directory entry to fill in
 * @ret rc		Return status code
 */
static int wim_direntry ( struct vdisk_file *file, struct wim_header *header,
			  struct wim_resource_header *meta,
			  const wchar_t *name, size_t *offset,
			  struct wim_directory_entry *direntry ) {
	wchar_t name_buf[ wcslen ( name ) + 1 /* NUL */ ];
	int rc;
	/* Search directory */
	for ( ; ; *offset += direntry->len ) {
		/* Read length field */
		if ( ( rc = wim_read ( file, header, meta, direntry, *offset,
				       sizeof ( direntry->len ) ) ) != 0 )
			return rc;
		/* Check for end of this directory */
		if ( ! direntry->len ) {
			DBG ( "...directory entry \"%ls\" not found\n", name );
			return -1;
		}
		/* Read fixed-length portion of directory entry */
		if ( ( rc = wim_read ( file, header, meta, direntry, *offset,
				       sizeof ( *direntry ) ) ) != 0 )
			return rc;
		/* Check name length */
		if ( direntry->name_len > sizeof ( name_buf ) )
			continue;
		/* Read name */
		if ( ( rc = wim_read ( file, header, meta, &name_buf,
				       ( *offset + sizeof ( *direntry ) ),
				       sizeof ( name_buf ) ) ) != 0 )
			return rc;
		/* Check name */
		if ( wcscasecmp ( name, name_buf ) != 0 )
			continue;
		DBG2 ( "...found entry \"%ls\"\n", name );
		return 0;
	}
}
/**
 * Get directory entry for a path
 *
 * @v file		Virtual file
 * @v header		WIM header
 * @v meta		Metadata
 * @v path		Path to file/directory
 * @v offset		Directory entry offset to fill in
 * @v direntry		Directory entry to fill in
 * @ret rc		Return status code
 */
int wim_path ( struct vdisk_file *file, struct wim_header *header,
	       struct wim_resource_header *meta, const wchar_t *path,
	       size_t *offset, struct wim_directory_entry *direntry ) {
	wchar_t path_copy[ wcslen ( path ) + 1 /* WNUL */ ];
	struct wim_security_header security;
	wchar_t *name;
	wchar_t *next;
	int rc;
	/* Read security data header */
	if ( ( rc = wim_read ( file, header, meta, &security, 0,
			       sizeof ( security ) ) ) != 0 )
		return rc;
	/* Get root directory offset */
    if (security.len > 0)
    	direntry->subdir = ( ( security.len + sizeof ( uint64_t ) - 1 ) & ~( sizeof ( uint64_t ) - 1 ) );
    else
        direntry->subdir = security.len + 8;
	/* Find directory entry */
	name = memcpy ( path_copy, path, sizeof ( path_copy ) );
	do {
		next = wcschr ( name, L'\\' );
		if ( next )
			*next = L'\0';
		*offset = direntry->subdir;
		if ( ( rc = wim_direntry ( file, header, meta, name, offset,
					   direntry ) ) != 0 )
			return rc;
		name = ( next + 1 );
	} while ( next );
	return 0;
}
/**
 * Get file resource
 *
 * @v file		Virtual file
 * @v header		WIM header
 * @v meta		Metadata
 * @v path		Path to file
 * @v resource		File resource to fill in
 * @ret rc		Return status code
 */
int wim_file ( struct vdisk_file *file, struct wim_header *header,
	       struct wim_resource_header *meta, const wchar_t *path,
	       struct wim_resource_header *resource ) {
	struct wim_directory_entry direntry;
	struct wim_lookup_entry entry;
	size_t offset;
	int rc;
	/* Find directory entry */
	if ( ( rc = wim_path ( file, header, meta, path, &offset,
			       &direntry ) ) != 0 )
		return rc;
	/* File matching file entry */
	for ( offset = 0 ; ( offset + sizeof ( entry ) ) <= header->lookup.len ;
	      offset += sizeof ( entry ) ) {
		/* Read entry */
		if ( ( rc = wim_read ( file, header, &header->lookup, &entry,
				       offset, sizeof ( entry ) ) ) != 0 )
			return rc;
		/* Look for our target entry */
		if ( memcmp ( &entry.hash, &direntry.hash,
			      sizeof ( entry.hash ) ) == 0 ) {
			DBG ( "...found file \"%ls\"\n", path );
			memcpy ( resource, &entry.resource,
				 sizeof ( *resource ) );
			return 0;
		}
	}
	DBG ( "Cannot find file %ls\n", path );
	return -1;
}
/**
 * Get length of a directory
 *
 * @v file		Virtual file
 * @v header		WIM header
 * @v meta		Metadata
 * @v offset		Directory offset
 * @v len		Directory length to fill in (excluding terminator)
 * @ret rc		Return status code
 */
int wim_dir_len ( struct vdisk_file *file, struct wim_header *header,
		  struct wim_resource_header *meta, size_t offset,
		  size_t *len ) {
	struct wim_directory_entry direntry;
	int rc;
	/* Search directory */
	for ( *len = 0 ; ; *len += direntry.len ) {
		/* Read length field */
		if ( ( rc = wim_read ( file, header, meta, &direntry,
				       ( offset + *len ),
				       sizeof ( direntry.len ) ) ) != 0 )
			return rc;
		/* Check for end of this directory */
		if ( ! direntry.len )
			return 0;
	}
}
 | 14,420 | 
	C | 
	.c | 479 | 26.818372 | 102 | 0.627929 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 267 | 
	die.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/die.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Fatal errors
 *
 */
#include <stdarg.h>
#include <stdio.h>
#include "wimboot.h"
#include "efi.h"
/**
 * Handle fatal errors
 *
 * @v fmt	Error message format string
 * @v ...	Arguments
 */
void die ( const char *fmt, ... ) {
	EFI_BOOT_SERVICES *bs;
	EFI_RUNTIME_SERVICES *rs;
	va_list args;
	/* Print message */
	va_start ( args, fmt );
	vprintf ( fmt, args );
	va_end ( args );
	/* Reboot or exit as applicable */
	if ( efi_systab ) {
		/* Exit */
		bs = efi_systab->BootServices;
		bs->Exit ( efi_image_handle, EFI_LOAD_ERROR, 0, NULL );
		printf ( "Failed to exit\n" );
		rs = efi_systab->RuntimeServices;
		rs->ResetSystem ( EfiResetWarm, 0, 0, NULL );
		printf ( "Failed to reboot\n" );
	} else {
		/* Wait for keypress */
		printf ( "Press a key to reboot..." );
		getchar();
		printf ( "\n" );
		/* Reboot system */
		reboot();
	}
	/* Should be impossible to reach this */
	__builtin_unreachable();
}
 | 1,731 | 
	C | 
	.c | 62 | 25.693548 | 70 | 0.689572 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 268 | 
	cookie.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/cookie.c | 
	/*
 * Copyright (C) 2021 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Stack cookie
 *
 */
#include "wimboot.h"
/** Stack cookie */
unsigned long __stack_chk_guard;
/**
 * Construct stack cookie value
 *
 */
static __attribute__ (( noinline )) unsigned long make_cookie ( void ) {
	union {
		struct {
			uint32_t eax;
			uint32_t edx;
		} __attribute__ (( packed ));
		unsigned long tsc;
	} u;
	unsigned long cookie;
	/* We have no viable source of entropy.  Use the CPU timestamp
	 * counter, which will have at least some minimal randomness
	 * in the low bits by the time we are invoked.
	 */
	__asm__ ( "rdtsc" : "=a" ( u.eax ), "=d" ( u.edx ) );
	cookie = u.tsc;
	/* Ensure that the value contains a NUL byte, to act as a
	 * runaway string terminator.  Construct the NUL using a shift
	 * rather than a mask, to avoid losing valuable entropy in the
	 * lower-order bits.
	 */
	cookie <<= 8;
	return cookie;
}
/**
 * Initialise stack cookie
 *
 * This function must not itself use stack guard
 */
void init_cookie ( void ) {
	/* Set stack cookie value
	 *
	 * This function must not itself use stack protection, since
	 * the change in the stack guard value would trigger a false
	 * positive.
	 *
	 * There is unfortunately no way to annotate a function to
	 * exclude the use of stack protection.  We must therefore
	 * rely on correctly anticipating the compiler's decision on
	 * the use of stack protection.
	 */
	__stack_chk_guard = make_cookie();
}
/**
 * Abort on stack check failure
 *
 */
void __stack_chk_fail ( void ) {
	/* Abort program */
	die ( "Stack check failed\n" );
}
 | 2,346 | 
	C | 
	.c | 81 | 26.703704 | 72 | 0.708962 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 271 | 
	cpio.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/cpio.c | 
	/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * CPIO archives
 *
 */
#include <stdint.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wimboot.h"
#include "cpio.h"
/**
 * Align CPIO length to nearest dword
 *
 * @v len		Length
 * @ret len		Aligned length
 */
static size_t cpio_align ( size_t len ) {
	return ( ( len + 0x03 ) & ~0x03 );
}
/**
 * Parse CPIO field value
 *
 * @v field		ASCII field
 * @ret value		Field value
 */
static unsigned long cpio_value ( const char *field ) {
	char buf[9];
	memcpy ( buf, field, ( sizeof ( buf ) - 1 ) );
	buf[ sizeof ( buf ) - 1 ] = '\0';
	return strtoul ( buf, NULL, 16 );
}
/**
 * Extract files from CPIO archive
 *
 * @v data		CPIO archive
 * @v len		Maximum length of CPIO archive
 * @v file		File handler
 * @ret rc		Return status code
 */
int cpio_extract ( void *data, size_t len,
		   int ( * file ) ( const char *name, void *data,
				    size_t len ) ) {
	const struct cpio_header *cpio;
	const uint32_t *pad;
	const char *file_name;
	void *file_data;
	size_t file_name_len;
	size_t file_len;
	size_t cpio_len;
	int rc;
	while ( 1 ) {
		/* Skip over any padding */
		while ( len >= sizeof ( *pad ) ) {
			pad = data;
			if ( *pad )
				break;
			data += sizeof ( *pad );
			len -= sizeof ( *pad );
		}
		/* Stop if we have reached the end of the archive */
		if ( ! len )
			return 0;
		/* Sanity check */
		if ( len < sizeof ( *cpio ) ) {
			DBG ( "Truncated CPIO header\n" );
			return -1;
		}
		cpio = data;
		/* Check magic */
		if ( memcmp ( cpio->c_magic, CPIO_MAGIC,
			      sizeof ( cpio->c_magic ) ) != 0 ) {
			DBG ( "Bad CPIO magic\n" );
			return -1;
		}
		/* Extract file parameters */
		file_name = ( ( void * ) ( cpio + 1 ) );
		file_name_len = cpio_value ( cpio->c_namesize );
		file_data = ( data + cpio_align ( sizeof ( *cpio ) +
						  file_name_len ) );
		file_len = cpio_value ( cpio->c_filesize );
		cpio_len = ( file_data + file_len - data );
		if ( cpio_len < len )
			cpio_len = cpio_align ( cpio_len );
		if ( cpio_len > len ) {
			DBG ( "Truncated CPIO file\n" );
			return -1;
		}
		/* If we reach the trailer, we're done */
		if ( strcmp ( file_name, CPIO_TRAILER ) == 0 )
			return 0;
		/* Process file */
		if ( ( rc = file ( file_name, file_data, file_len ) ) != 0 )
			return rc;
		/* Move to next file */
		data += cpio_len;
		len -= cpio_len;
	}
}
 | 3,160 | 
	C | 
	.c | 119 | 23.865546 | 70 | 0.634501 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 272 | 
	wimpatch.h | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/wimpatch.h | 
	#ifndef _WIMPATCH_H
#define _WIMPATCH_H
/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * WIM dynamic patching
 *
 */
#include <stdint.h>
struct vdisk_file;
extern void patch_wim ( struct vdisk_file *file, void *data, size_t offset,
			size_t len );
#endif /* _WIMPATCH_H */
 | 1,044 | 
	C | 
	.c | 31 | 31.677419 | 75 | 0.7428 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 274 | 
	efiblock.h | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/efiblock.h | 
	#ifndef _EFIBLOCK_H
#define _EFIBLOCK_H
/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * EFI block device
 *
 */
#include "efi.h"
#include "efi/Protocol/BlockIo.h"
#include "efi/Protocol/DevicePath.h"
extern void efi_install ( EFI_HANDLE *vdisk, EFI_HANDLE *vpartition );
extern EFI_DEVICE_PATH_PROTOCOL *bootmgfw_path;
#endif /* _EFIBLOCK_H */
 | 1,115 | 
	C | 
	.c | 32 | 32.96875 | 70 | 0.751161 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 276 | 
	vsprintf.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/vsprintf.c | 
	/*
 * Quick and dirty wrapper around iPXE's unmodified vsprintf.c
 *
 */
#include <stdint.h>
#include <string.h>
#include "wimboot.h"
#define FILE_LICENCE(x)
#include "ipxe/vsprintf.c"
 | 188 | 
	C | 
	.c | 9 | 19.222222 | 62 | 0.744318 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 277 | 
	coverity-model.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/coverity-model.c | 
	/*
 * Coverity modelling file
 *
 */
typedef unsigned short wchar_t;
typedef void mbstate_t;
/* Inhibit use of built-in models for functions where Coverity's
 * assumptions about the modelled function are incorrect for wimboot.
 */
int getchar ( void ) {
}
size_t wcrtomb ( char *buf, wchar_t wc, mbstate_t *ps ) {
}
 | 319 | 
	C | 
	.c | 13 | 23 | 69 | 0.740132 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 278 | 
	int13.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/int13.c | 
	/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * INT 13 emulation
 *
 */
#include <string.h>
#include <stdio.h>
#include "wimboot.h"
#include "int13.h"
#include "vdisk.h"
/** Emulated drive number */
static int vdisk_drive;
/**
 * Initialise emulation
 *
 * @ret drive		Emulated drive number
 */
int initialise_int13 ( void ) {
	/* Determine drive number */
	vdisk_drive = ( 0x80 | INT13_DRIVE_COUNT++ );
	DBG ( "Emulating drive %#02x\n", vdisk_drive );
	return vdisk_drive;
}
/**
 * INT 13, 08 - Get drive parameters
 *
 * @ret ch		Low bits of maximum cylinder number
 * @ret cl (bits 7:6)	High bits of maximum cylinder number
 * @ret cl (bits 5:0)	Maximum sector number
 * @ret dh		Maximum head number
 * @ret dl		Number of drives
 * @ret ah		Status code
 */
static void int13_get_parameters ( struct bootapp_callback_params *params ) {
	unsigned int max_cylinder = ( VDISK_CYLINDERS - 1 );
	unsigned int max_head = ( VDISK_HEADS - 1 );
	unsigned int max_sector = ( VDISK_SECTORS_PER_TRACK - 0 /* sic */ );
	unsigned int num_drives;
	unsigned int min_num_drives;
	/* Calculate number of drives to report */
	num_drives = INT13_DRIVE_COUNT;
	min_num_drives = ( ( vdisk_drive & 0x7f ) + 1 );
	if ( num_drives < min_num_drives )
		num_drives = min_num_drives;
	/* Fill in drive parameters */
	params->ch = ( max_cylinder & 0xff );
	params->cl = ( ( ( max_cylinder >> 8 ) << 6 ) | max_sector );
	params->dh = max_head;
	params->dl = num_drives;
	DBG2 ( "Get parameters: C/H/S = %d/%d/%d, drives = %d\n",
	       ( max_cylinder + 1 ), ( max_head + 1 ), max_sector, num_drives );
	/* Success */
	params->ah = 0;
}
/**
 * INT 13, 15 - Get disk type
 *
 * @ret cx:dx		Sector count
 * @ret ah		Type code
 */
static void int13_get_disk_type ( struct bootapp_callback_params *params ) {
	uint32_t sector_count = VDISK_COUNT;
	uint8_t drive_type = INT13_DISK_TYPE_HDD;
	/* Fill in disk type */
	params->cx = ( sector_count >> 16 );
	params->dx = ( sector_count & 0xffff );
	params->ah = drive_type;
	DBG2 ( "Get disk type: sectors = %#08x, type = %d\n",
	       sector_count, drive_type );
}
/**
 * INT 13, 41 - Extensions installation check
 *
 * @v bx		0x55aa
 * @ret bx		0xaa55
 * @ret cx		Extensions API support bitmap
 * @ret ah		API version
 */
static void int13_extension_check ( struct bootapp_callback_params *params ) {
	/* Fill in extension information */
	params->bx = 0xaa55;
	params->cx = INT13_EXTENSION_LINEAR;
	params->ah = INT13_EXTENSION_VER_1_X;
	DBG2 ( "Extensions installation check\n" );
}
/**
 * INT 13, 48 - Get extended parameters
 *
 * @v ds:si		Drive parameter table
 * @ret ah		Status code
 */
static void
int13_get_extended_parameters ( struct bootapp_callback_params *params ) {
	struct int13_disk_parameters *disk_params;
	/* Fill in extended parameters */
	disk_params = REAL_PTR ( params->ds, params->si );
	memset ( disk_params, 0, sizeof ( *disk_params ) );
	disk_params->bufsize = sizeof ( *disk_params );
	disk_params->flags = INT13_FL_DMA_TRANSPARENT;
	disk_params->cylinders = VDISK_CYLINDERS;
	disk_params->heads = VDISK_HEADS;
	disk_params->sectors_per_track = VDISK_SECTORS_PER_TRACK;
	disk_params->sectors = VDISK_COUNT;
	disk_params->sector_size = VDISK_SECTOR_SIZE;
	DBG2 ( "Get extended parameters: C/H/S = %d/%d/%d, sectors = %#08llx "
	       "(%d bytes)\n", disk_params->cylinders, disk_params->heads,
	       disk_params->sectors_per_track, disk_params->sectors,
	       disk_params->sector_size );
	/* Success */
	params->ah = 0;
}
/**
 * INT 13, 42 - Extended read
 *
 * @v ds:si		Disk address packet
 * @ret ah		Status code
 */
static void int13_extended_read ( struct bootapp_callback_params *params ) {
	struct int13_disk_address *disk_address;
	void *data;
	/* Read from emulated disk */
	disk_address = REAL_PTR ( params->ds, params->si );
	data = REAL_PTR ( disk_address->buffer.segment,
			  disk_address->buffer.offset );
	vdisk_read ( disk_address->lba, disk_address->count, data );
	/* Success */
	params->ah = 0;
}
/**
 * Emulate INT 13 drive
 *
 * @v params		Parameters
 */
void emulate_int13 ( struct bootapp_callback_params *params ) {
	int command = params->ah;
	int drive = params->dl;
	int min_num_drives;
	unsigned long eflags;
	if ( drive == vdisk_drive ) {
		/* Emulated drive - handle internally */
		/* Populate eflags with a sensible starting value */
		__asm__ ( "pushf\n\t"
			  "pop %0\n\t"
			  : "=r" ( eflags ) );
		params->eflags = ( eflags & ~CF );
		/* Handle command */
		switch ( command ) {
		case INT13_GET_PARAMETERS:
			int13_get_parameters ( params );
			break;
		case INT13_GET_DISK_TYPE:
			int13_get_disk_type ( params );
			break;
		case INT13_EXTENSION_CHECK:
			int13_extension_check ( params );
			break;
		case INT13_GET_EXTENDED_PARAMETERS:
			int13_get_extended_parameters ( params );
			break;
		case INT13_EXTENDED_READ:
			int13_extended_read ( params );
			break;
		default:
			DBG ( "Unrecognised INT 13,%02x\n", command );
			params->eflags |= CF;
			break;
		}
	} else {
		/* Pass through command to underlying INT 13 */
		call_interrupt ( params );
		/* Modify drive count, if applicable */
		if ( command == INT13_GET_PARAMETERS ) {
			min_num_drives = ( ( vdisk_drive & 0x7f ) + 1 );
			if ( params->dl < min_num_drives )
				params->dl = min_num_drives;
		}
	}
}
 | 6,058 | 
	C | 
	.c | 197 | 28.263959 | 78 | 0.681639 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 280 | 
	efiguid.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/efiguid.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * EFI GUIDs
 *
 */
#include "wimboot.h"
#include "efi.h"
#include "efi/Protocol/BlockIo.h"
#include "efi/Protocol/DevicePath.h"
#include "efi/Protocol/GraphicsOutput.h"
#include "efi/Protocol/LoadedImage.h"
#include "efi/Protocol/SimpleFileSystem.h"
/** Block I/O protocol GUID */
EFI_GUID efi_block_io_protocol_guid
	= EFI_BLOCK_IO_PROTOCOL_GUID;
/** Device path protocol GUID */
EFI_GUID efi_device_path_protocol_guid
	= EFI_DEVICE_PATH_PROTOCOL_GUID;
/** Graphics output protocol GUID */
EFI_GUID efi_graphics_output_protocol_guid
	= EFI_GRAPHICS_OUTPUT_PROTOCOL_GUID;
/** Loaded image protocol GUID */
EFI_GUID efi_loaded_image_protocol_guid
	= EFI_LOADED_IMAGE_PROTOCOL_GUID;
/** Simple file system protocol GUID */
EFI_GUID efi_simple_file_system_protocol_guid
	= EFI_SIMPLE_FILE_SYSTEM_PROTOCOL_GUID;
 | 1,626 | 
	C | 
	.c | 46 | 33.608696 | 70 | 0.762238 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 281 | 
	lzx.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/lzx.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * LZX decompression
 *
 * This algorithm is derived jointly from the document "[MS-PATCH]:
 * LZX DELTA Compression and Decompression", available from
 *
 *     http://msdn.microsoft.com/en-us/library/cc483133.aspx
 *
 * and from the file lzx-decompress.c in the wimlib source code.
 *
 */
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#include "wimboot.h"
#include "huffman.h"
#include "lzx.h"
/** Base positions, indexed by position slot */
static unsigned int lzx_position_base[LZX_POSITION_SLOTS];
/**
 * Attempt to accumulate bits from LZX bitstream
 *
 * @v lzx		Decompressor
 * @v bits		Number of bits to accumulate
 * @v norm_value	Accumulated value (normalised to 16 bits)
 *
 * Note that there may not be sufficient accumulated bits in the
 * bitstream; callers must check that sufficient bits are available
 * before using the value.
 */
static int lzx_accumulate ( struct lzx *lzx, unsigned int bits ) {
	const uint16_t *src16;
	/* Accumulate more bits if required */
	if ( ( lzx->bits < bits ) &&
	     ( lzx->input.offset < lzx->input.len ) ) {
		src16 = ( ( void * ) lzx->input.data + lzx->input.offset );
		lzx->input.offset += sizeof ( *src16 );
		lzx->accumulator |= ( *src16 << ( 16 - lzx->bits ) );
		lzx->bits += 16;
	}
	return ( lzx->accumulator >> 16 );
}
/**
 * Consume accumulated bits from LZX bitstream
 *
 * @v lzx		Decompressor
 * @v bits		Number of bits to consume
 * @ret rc		Return status code
 */
static int lzx_consume ( struct lzx *lzx, unsigned int bits ) {
	/* Fail if insufficient bits are available */
	if ( lzx->bits < bits ) {
		DBG ( "LZX input overrun in %#zx/%#zx out %#zx)\n",
		      lzx->input.offset, lzx->input.len, lzx->output.offset );
		return -1;
	}
	/* Consume bits */
	lzx->accumulator <<= bits;
	lzx->bits -= bits;
	return 0;
}
/**
 * Get bits from LZX bitstream
 *
 * @v lzx		Decompressor
 * @v bits		Number of bits to fetch
 * @ret value		Value, or negative error
 */
static int lzx_getbits ( struct lzx *lzx, unsigned int bits ) {
	int norm_value;
	int rc;
	/* Accumulate more bits if required */
	norm_value = lzx_accumulate ( lzx, bits );
	/* Consume bits */
	if ( ( rc = lzx_consume ( lzx, bits ) ) != 0 )
		return rc;
	return ( norm_value >> ( 16 - bits ) );
}
/**
 * Align LZX bitstream for byte access
 *
 * @v lzx		Decompressor
 * @v bits		Minimum number of padding bits
 * @ret rc		Return status code
 */
static int lzx_align ( struct lzx *lzx, unsigned int bits ) {
	int pad;
	/* Get padding bits */
	pad = lzx_getbits ( lzx, bits );
	if ( pad < 0 )
		return pad;
	/* Consume all accumulated bits */
	lzx_consume ( lzx, lzx->bits );
	return 0;
}
/**
 * Get bytes from LZX bitstream
 *
 * @v lzx		Decompressor
 * @v data		Data buffer, or NULL
 * @v len		Length of data buffer
 * @ret rc		Return status code
 */
static int lzx_getbytes ( struct lzx *lzx, void *data, size_t len ) {
	/* Sanity check */
	if ( ( lzx->input.offset + len ) > lzx->input.len ) {
		DBG ( "LZX input overrun in %#zx/%#zx out %#zx)\n",
		      lzx->input.offset, lzx->input.len, lzx->output.offset );
		return -1;
	}
	/* Copy data */
	if ( data )
		memcpy ( data, ( lzx->input.data + lzx->input.offset ), len );
	lzx->input.offset += len;
	return 0;
}
/**
 * Decode LZX Huffman-coded symbol
 *
 * @v lzx		Decompressor
 * @v alphabet		Huffman alphabet
 * @ret raw		Raw symbol, or negative error
 */
static int lzx_decode ( struct lzx *lzx, struct huffman_alphabet *alphabet ) {
	struct huffman_symbols *sym;
	int huf;
	int rc;
	/* Accumulate sufficient bits */
	huf = lzx_accumulate ( lzx, HUFFMAN_BITS );
	if ( huf < 0 )
		return huf;
	/* Decode symbol */
	sym = huffman_sym ( alphabet, huf );
	/* Consume bits */
	if ( ( rc = lzx_consume ( lzx, huffman_len ( sym ) ) ) != 0 )
		return rc;
	return huffman_raw ( sym, huf );
}
/**
 * Generate Huffman alphabet from raw length table
 *
 * @v lzx		Decompressor
 * @v count		Number of symbols
 * @v bits		Length of each length (in bits)
 * @v lengths		Lengths table to fill in
 * @v alphabet		Huffman alphabet to fill in
 * @ret rc		Return status code
 */
static int lzx_raw_alphabet ( struct lzx *lzx, unsigned int count,
			      unsigned int bits, uint8_t *lengths,
			      struct huffman_alphabet *alphabet ) {
	unsigned int i;
	int len;
	int rc;
	/* Read lengths */
	for ( i = 0 ; i < count ; i++ ) {
		len = lzx_getbits ( lzx, bits );
		if ( len < 0 )
			return len;
		lengths[i] = len;
	}
	/* Generate Huffman alphabet */
	if ( ( rc = huffman_alphabet ( alphabet, lengths, count ) ) != 0 )
		return rc;
	return 0;
}
/**
 * Generate pretree
 *
 * @v lzx		Decompressor
 * @v count		Number of symbols
 * @v lengths		Lengths table to fill in
 * @ret rc		Return status code
 */
static int lzx_pretree ( struct lzx *lzx, unsigned int count,
			 uint8_t *lengths ) {
	unsigned int i;
	unsigned int length;
	int dup = 0;
	int code;
	int rc;
	/* Generate pretree alphabet */
	if ( ( rc =  lzx_raw_alphabet ( lzx, LZX_PRETREE_CODES,
					LZX_PRETREE_BITS, lzx->pretree_lengths,
					&lzx->pretree ) ) != 0 )
		return rc;
	/* Read lengths */
	for ( i = 0 ; i < count ; i++ ) {
		if ( dup ) {
			/* Duplicate previous length */
			lengths[i] = lengths[ i - 1 ];
			dup--;
		} else {
			/* Get next code */
			code = lzx_decode ( lzx, &lzx->pretree );
			if ( code < 0 )
				return code;
			/* Interpret code */
			if ( code <= 16 ) {
				length = ( ( lengths[i] - code + 17 ) % 17 );
			} else if ( code == 17 ) {
				length = 0;
				dup = lzx_getbits ( lzx, 4 );
				if ( dup < 0 )
					return dup;
				dup += 3;
			} else if ( code == 18 ) {
				length = 0;
				dup = lzx_getbits ( lzx, 5 );
				if ( dup < 0 )
					return dup;
				dup += 19;
			} else if ( code == 19 ) {
				length = 0;
				dup = lzx_getbits ( lzx, 1 );
				if ( dup < 0 )
					return dup;
				dup += 3;
				code = lzx_decode ( lzx, &lzx->pretree );
				if ( code < 0 )
					return code;
				length = ( ( lengths[i] - code + 17 ) % 17 );
			} else {
				DBG ( "Unrecognised pretree code %d\n", code );
				return -1;
			}
			lengths[i] = length;
		}
	}
	/* Sanity check */
	if ( dup ) {
		DBG ( "Pretree duplicate overrun\n" );
		return -1;
	}
	return 0;
}
/**
 * Generate aligned offset Huffman alphabet
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 */
static int lzx_alignoffset_alphabet ( struct lzx *lzx ) {
	int rc;
	/* Generate aligned offset alphabet */
	if ( ( rc = lzx_raw_alphabet ( lzx, LZX_ALIGNOFFSET_CODES,
				       LZX_ALIGNOFFSET_BITS,
				       lzx->alignoffset_lengths,
				       &lzx->alignoffset ) ) != 0 )
		return rc;
	return 0;
}
/**
 * Generate main Huffman alphabet
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 */
static int lzx_main_alphabet ( struct lzx *lzx ) {
	int rc;
	/* Generate literal symbols pretree */
	if ( ( rc = lzx_pretree ( lzx, LZX_MAIN_LIT_CODES,
				  lzx->main_lengths.literals ) ) != 0 ) {
		DBG ( "Could not construct main literal pretree\n" );
		return rc;
	}
	/* Generate remaining symbols pretree */
	if ( ( rc = lzx_pretree ( lzx, ( LZX_MAIN_CODES - LZX_MAIN_LIT_CODES ),
				  lzx->main_lengths.remainder ) ) != 0 ) {
		DBG ( "Could not construct main remainder pretree\n" );
		return rc;
	}
	/* Generate Huffman alphabet */
	if ( ( rc = huffman_alphabet ( &lzx->main, lzx->main_lengths.literals,
				       LZX_MAIN_CODES ) ) != 0 ) {
		DBG ( "Could not generate main alphabet\n" );
		return rc;
	}
	return 0;
}
/**
 * Generate length Huffman alphabet
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 */
static int lzx_length_alphabet ( struct lzx *lzx ) {
	int rc;
	/* Generate pretree */
	if ( ( rc = lzx_pretree ( lzx, LZX_LENGTH_CODES,
				  lzx->length_lengths ) ) != 0 ) {
		DBG ( "Could not generate length pretree\n" );
		return rc;
	}
	/* Generate Huffman alphabet */
	if ( ( rc = huffman_alphabet ( &lzx->length, lzx->length_lengths,
				       LZX_LENGTH_CODES ) ) != 0 ) {
		DBG ( "Could not generate length alphabet\n" );
		return rc;
	}
	return 0;
}
/**
 * Process LZX block header
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 */
static int lzx_block_header ( struct lzx *lzx ) {
	size_t block_len;
	int block_type;
	int default_len;
	int len_high;
	int len_low;
	int rc;
	/* Get block type */
	block_type = lzx_getbits ( lzx, LZX_BLOCK_TYPE_BITS );
	if ( block_type < 0 )
		return block_type;
	lzx->block_type = block_type;
	/* Check block length */
	default_len = lzx_getbits ( lzx, 1 );
	if ( default_len < 0 )
		return default_len;
	if ( default_len ) {
		block_len = LZX_DEFAULT_BLOCK_LEN;
	} else {
		len_high = lzx_getbits ( lzx, 8 );
		if ( len_high < 0 )
			return len_high;
		len_low = lzx_getbits ( lzx, 8 );
		if ( len_low < 0 )
			return len_low;
		block_len = ( ( len_high << 8 ) | len_low );
	}
	lzx->output.threshold = ( lzx->output.offset + block_len );
	/* Handle block type */
	switch ( block_type ) {
	case LZX_BLOCK_ALIGNOFFSET :
		/* Generated aligned offset alphabet */
		if ( ( rc = lzx_alignoffset_alphabet ( lzx ) ) != 0 )
			return rc;
		/* Fall through */
	case LZX_BLOCK_VERBATIM :
		/* Generate main alphabet */
		if ( ( rc = lzx_main_alphabet ( lzx ) ) != 0 )
			return rc;
		/* Generate lengths alphabet */
		if ( ( rc = lzx_length_alphabet ( lzx ) ) != 0 )
			return rc;
		break;
	case LZX_BLOCK_UNCOMPRESSED :
		/* Align input stream */
		if ( ( rc = lzx_align ( lzx, 1 ) ) != 0 )
			return rc;
		/* Read new repeated offsets */
		if ( ( rc = lzx_getbytes ( lzx, &lzx->repeated_offset,
					   sizeof ( lzx->repeated_offset )))!=0)
			return rc;
		break;
	default:
		DBG ( "Unrecognised block type %d\n", block_type );
		return -1;
	}
	return 0;
}
/**
 * Process uncompressed data
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 */
static int lzx_uncompressed ( struct lzx *lzx ) {
	void *data;
	size_t len;
	int rc;
	/* Copy bytes */
	data = ( lzx->output.data ?
		 ( lzx->output.data + lzx->output.offset ) : NULL );
	len = ( lzx->output.threshold - lzx->output.offset );
	if ( ( rc = lzx_getbytes ( lzx, data, len ) ) != 0 )
		return rc;
	/* Align input stream */
	if ( len % 2 )
		lzx->input.offset++;
	return 0;
}
/**
 * Process an LZX token
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 *
 * Variable names are chosen to match the LZX specification
 * pseudo-code.
 */
static int lzx_token ( struct lzx *lzx ) {
	unsigned int length_header;
	unsigned int position_slot;
	unsigned int offset_bits;
	unsigned int i;
	size_t match_offset;
	size_t match_length;
	int verbatim_bits;
	int aligned_bits;
	int main;
	int length;
	uint8_t *copy;
	/* Get main symelse*/
	main = lzx_decode ( lzx, &lzx->main );
	if ( main < 0 )
		return main;
	/* Check for literals */
	if ( main < LZX_MAIN_LIT_CODES ) {
		if ( lzx->output.data )
			lzx->output.data[lzx->output.offset] = main;
		lzx->output.offset++;
		return 0;
	}
	main -= LZX_MAIN_LIT_CODES;
	/* Calculate the match length */
	length_header = ( main & 7 );
	if ( length_header == 7 ) {
		length = lzx_decode ( lzx, &lzx->length );
		if ( length < 0 )
			return length;
	} else {
		length = 0;
	}
	match_length = ( length_header + 2 + length );
	/* Calculate the position slot */
	position_slot = ( main >> 3 );
	if ( position_slot < LZX_REPEATED_OFFSETS ) {
		/* Repeated offset */
		match_offset = lzx->repeated_offset[position_slot];
		lzx->repeated_offset[position_slot] = lzx->repeated_offset[0];
		lzx->repeated_offset[0] = match_offset;
	} else {
		/* Non-repeated offset */
		offset_bits = lzx_footer_bits ( position_slot );
		if ( ( lzx->block_type == LZX_BLOCK_ALIGNOFFSET ) &&
		     ( offset_bits >= 3 ) ) {
			verbatim_bits = lzx_getbits ( lzx, ( offset_bits - 3 ));
			if ( verbatim_bits < 0 )
				return verbatim_bits;
			verbatim_bits <<= 3;
			aligned_bits = lzx_decode ( lzx, &lzx->alignoffset );
			if ( aligned_bits < 0 )
				return aligned_bits;
		} else {
			verbatim_bits = lzx_getbits ( lzx, offset_bits );
			if ( verbatim_bits < 0 )
				return verbatim_bits;
			aligned_bits = 0;
		}
		match_offset = ( lzx_position_base[position_slot] +
				 verbatim_bits + aligned_bits - 2 );
		/* Update repeated offset list */
		for ( i = ( LZX_REPEATED_OFFSETS - 1 ) ; i > 0 ; i-- )
			lzx->repeated_offset[i] = lzx->repeated_offset[ i - 1 ];
		lzx->repeated_offset[0] = match_offset;
	}
	/* Copy data */
	if ( match_offset > lzx->output.offset ) {
		DBG ( "LZX match underrun out %#zx offset %#zx len %#zx\n",
		      lzx->output.offset, match_offset, match_length );
		return -1;
	}
	if ( lzx->output.data ) {
		copy = &lzx->output.data[lzx->output.offset];
		for ( i = 0 ; i < match_length ; i++ )
			copy[i] = copy[ i - match_offset ];
	}
	lzx->output.offset += match_length;
	return 0;
}
/**
 * Translate E8 jump addresses
 *
 * @v lzx		Decompressor
 */
static void lzx_translate_jumps ( struct lzx *lzx ) {
	size_t offset;
	int32_t *target;
	/* Sanity check */
	if ( lzx->output.offset < 10 )
		return;
	/* Scan for jump instructions */
	for ( offset = 0 ; offset < ( lzx->output.offset - 10 ) ; offset++ ) {
		/* Check for jump instruction */
		if ( lzx->output.data[offset] != 0xe8 )
			continue;
		/* Translate jump target */
		target = ( ( int32_t * ) &lzx->output.data[ offset + 1 ] );
		if ( *target >= 0 ) {
			if ( *target < LZX_WIM_MAGIC_FILESIZE )
				*target -= offset;
		} else {
			if ( *target >= -( ( int32_t ) offset ) )
				*target += LZX_WIM_MAGIC_FILESIZE;
		}
		offset += sizeof ( *target );
	}
}
/**
 * Decompress LZX-compressed data
 *
 * @v data		Compressed data
 * @v len		Length of compressed data
 * @v buf		Decompression buffer, or NULL
 * @ret out_len		Length of decompressed data, or negative error
 */
ssize_t lzx_decompress ( const void *data, size_t len, void *buf ) {
	struct lzx lzx;
	unsigned int i;
	int rc;
	/* Sanity check */
	if ( len % 2 ) {
		DBG ( "LZX cannot handle odd-length input data\n" );
		return -1;
	}
	/* Initialise global state, if required */
	if ( ! lzx_position_base[ LZX_POSITION_SLOTS - 1 ] ) {
		for ( i = 1 ; i < LZX_POSITION_SLOTS ; i++ ) {
			lzx_position_base[i] =
				( lzx_position_base[i-1] +
				  ( 1 << lzx_footer_bits ( i - 1 ) ) );
		}
	}
	/* Initialise decompressor */
	memset ( &lzx, 0, sizeof ( lzx ) );
	lzx.input.data = data;
	lzx.input.len = len;
	lzx.output.data = buf;
	for ( i = 0 ; i < LZX_REPEATED_OFFSETS ; i++ )
		lzx.repeated_offset[i] = 1;
	/* Process blocks */
	while ( lzx.input.offset < lzx.input.len ) {
		/* Process block header */
		if ( ( rc = lzx_block_header ( &lzx ) ) != 0 )
			return rc;
		/* Process block contents */
		if ( lzx.block_type == LZX_BLOCK_UNCOMPRESSED ) {
			/* Copy uncompressed data */
			if ( ( rc = lzx_uncompressed ( &lzx ) ) != 0 )
				return rc;
		} else {
			/* Process token stream */
			while ( lzx.output.offset < lzx.output.threshold ) {
				if ( ( rc = lzx_token ( &lzx ) ) != 0 )
					return rc;
			}
		}
	}
	/* Postprocess to undo E8 jump compression */
	if ( lzx.output.data )
		lzx_translate_jumps ( &lzx );
	return lzx.output.offset;
}
 | 15,806 | 
	C | 
	.c | 580 | 24.448276 | 78 | 0.638346 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 282 | 
	xca.h | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/xca.h | 
	#ifndef _XCA_H
#define _XCA_H
/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Xpress Compression Algorithm (MS-XCA) decompression
 *
 */
#include <stdint.h>
#include "huffman.h"
/** Number of XCA codes */
#define XCA_CODES 512
/** XCA decompressor */
struct xca {
	/** Huffman alphabet */
	struct huffman_alphabet alphabet;
	/** Raw symbols
	 *
	 * Must immediately follow the Huffman alphabet.
	 */
	huffman_raw_symbol_t raw[XCA_CODES];
	/** Code lengths */
	uint8_t lengths[XCA_CODES];
};
/** XCA symbol Huffman lengths table */
struct xca_huf_len {
	/** Lengths of each symbol */
	uint8_t nibbles[ XCA_CODES / 2 ];
} __attribute__ (( packed ));
/**
 * Extract Huffman-coded length of a raw symbol
 *
 * @v lengths		Huffman lengths table
 * @v symbol		Raw symbol
 * @ret len		Huffman-coded length
 */
static inline unsigned int xca_huf_len ( const struct xca_huf_len *lengths,
					 unsigned int symbol ) {
	return ( ( ( lengths->nibbles[ symbol / 2 ] ) >>
		   ( 4 * ( symbol % 2 ) ) ) & 0x0f );
}
/** Get word from source data stream */
#define XCA_GET16( src ) ( {			\
	const uint16_t *src16 = src;		\
	src += sizeof ( *src16 );		\
	*src16; } )
/** Get byte from source data stream */
#define XCA_GET8( src ) ( {			\
	const uint8_t *src8 = src;		\
	src += sizeof ( *src8 );		\
	*src8; } )
/** XCA source data stream end marker */
#define XCA_END_MARKER 256
/** XCA block size */
#define XCA_BLOCK_SIZE ( 64 * 1024 )
extern ssize_t xca_decompress ( const void *data, size_t len, void *buf );
#endif /* _XCA_H */
 | 2,294 | 
	C | 
	.c | 75 | 28.613333 | 75 | 0.689937 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 283 | 
	wctype.h | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/wctype.h | 
	#ifndef _WCTYPE_H
#define _WCTYPE_H
/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Wide character types
 *
 * We don't actually care about wide characters.  Internationalisation
 * is a user interface concern, and has absolutely no place in the
 * boot process.  However, UEFI uses wide characters and so we have to
 * at least be able to handle the ASCII subset of UCS-2.
 *
 */
#include <ctype.h>
static inline int iswlower ( wint_t c ) {
	return islower ( c );
}
static inline int iswupper ( wint_t c ) {
	return isupper ( c );
}
static inline int towupper ( wint_t c ) {
	return toupper ( c );
}
static inline int iswspace ( wint_t c ) {
	return isspace ( c );
}
#endif /* _WCTYPE_H */
 | 1,464 | 
	C | 
	.c | 45 | 30.666667 | 70 | 0.734231 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 284 | 
	cmdline.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/cmdline.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Command line
 *
 */
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "wimboot.h"
#include "cmdline.h"
/** Use raw (unpatched) BCD files */
int cmdline_rawbcd;
/** Use raw (unpatched) WIM files */
int cmdline_rawwim;
/** Inhibit debugging output */
int cmdline_quiet;
/** Allow graphical output from bootmgr/bootmgfw */
int cmdline_gui;
/** Pause before booting OS */
int cmdline_pause;
/** Pause without displaying any prompt */
int cmdline_pause_quiet;
/** Use linear (unpaged) memory model */
int cmdline_linear;
/** WIM boot index */
unsigned int cmdline_index;
int cmdline_vf_num;
char cmdline_vf_path[MAX_VF][64];
file_size_pf pfventoy_file_size;
file_read_pf pfventoy_file_read;
/**
 * Process command line
 *
 * @v cmdline		Command line
 */
void process_cmdline ( char *cmdline ) {
	char *tmp = cmdline;
	char *key;
	char *value;
	char *endp;
	/* Do nothing if we have no command line */
	if ( ( cmdline == NULL ) || ( cmdline[0] == '\0' ) )
		return;
	/* Parse command line */
	while ( *tmp ) {
		/* Skip whitespace */
		while ( isspace ( *tmp ) )
			tmp++;
		/* Find value (if any) and end of this argument */
		key = tmp;
		value = NULL;
		while ( *tmp ) {
			if ( isspace ( *tmp ) ) {
				*(tmp++) = '\0';
				break;
			} else if ( *tmp == '=' ) {
				*(tmp++) = '\0';
				value = tmp;
			} else {
				tmp++;
			}
		}
		/* Process this argument */
		if ( strcmp ( key, "rawbcd" ) == 0 ) {
			cmdline_rawbcd = 1;
		} else if ( strcmp ( key, "rawwim" ) == 0 ) {
			cmdline_rawwim = 1;
		} else if ( strcmp ( key, "gui" ) == 0 ) {
			cmdline_gui = 1;
		}
        else if ((key[0] == 'v') && (key[1] == 'f') ) {
            if (cmdline_vf_num >= MAX_VF)
                die("Too many vf\n");
            snprintf(cmdline_vf_path[cmdline_vf_num], 64, "%s", value);
            cmdline_vf_num++;
		}else if ( strcmp ( key, "pfsize" ) == 0 ) {    
            pfventoy_file_size = (file_size_pf)strtoul(value, &endp, 0);
		} else if ( strcmp ( key, "pfread" ) == 0 ) {
            pfventoy_file_read = (file_read_pf)strtoul(value, &endp, 0 );
		}
        else if ( strcmp ( key, "linear" ) == 0 ) {
			cmdline_linear = 1;
		} else if ( strcmp ( key, "quiet" ) == 0 ) {
			cmdline_quiet = 1;
		} else if ( strcmp ( key, "pause" ) == 0 ) {
			cmdline_pause = 1;
			if ( value && ( strcmp ( value, "quiet" ) == 0 ) )
				cmdline_pause_quiet = 1;
		} else if ( strcmp ( key, "index" ) == 0 ) {
			if ( ( ! value ) || ( ! value[0] ) )
				die ( "Argument \"index\" needs a value\n" );
			cmdline_index = strtoul ( value, &endp, 0 );
			if ( *endp )
				die ( "Invalid index \"%s\"\n", value );
		} else if ( strcmp ( key, "initrdfile" ) == 0 ) {
			/* Ignore this keyword to allow for use with syslinux */
		} else if ( key == cmdline ) {
			/* Ignore unknown initial arguments, which may
			 * be the program name.
			 */
		} else {
			die ( "Unrecognised argument \"%s%s%s\"\n", key,
			      ( value ? "=" : "" ), ( value ? value : "" ) );
		}
	}
	/* Show command line (after parsing "quiet" option) */
	DBG ( "Command line: \"%s\" vf=%d pfsize=%p pfread=%p\n", 
	    cmdline, cmdline_vf_num, pfventoy_file_size, pfventoy_file_read);
}
 | 4,030 | 
	C | 
	.c | 130 | 27.623077 | 73 | 0.610724 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 286 | 
	stdio.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/stdio.c | 
	/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Standard Input/Output
 *
 */
#include <stdio.h>
#include <string.h>
#include "bootapp.h"
#include "wimboot.h"
#include "efi.h"
/**
 * Print character to console
 *
 * @v character		Character to print
 */
int putchar ( int character ) {
	EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *conout;
	struct bootapp_callback_params params;
	wchar_t wbuf[2];
	/* Convert LF to CR,LF */
	if ( character == '\n' )
		putchar ( '\r' );
	/* Print character to bochs debug port */
	__asm__ __volatile__ ( "outb %b0, $0xe9"
			       : : "a" ( character ) );
	/* Print character to EFI/BIOS console as applicable */
	if ( efi_systab ) {
		conout = efi_systab->ConOut;
		wbuf[0] = character;
		wbuf[1] = 0;
		conout->OutputString ( conout, wbuf );
	} else {
		memset ( ¶ms, 0, sizeof ( params ) );
		params.vector.interrupt = 0x10;
		params.eax = ( 0x0e00 | character );
		params.ebx = 0x0007;
		call_interrupt ( ¶ms );
	}
	return 0;
}
/**
 * Get character from console
 *
 * @ret character	Character
 */
int getchar ( void ) {
	EFI_BOOT_SERVICES *bs;
	EFI_SIMPLE_TEXT_INPUT_PROTOCOL *conin;
	EFI_INPUT_KEY key;
	UINTN index;
	struct bootapp_callback_params params;
	int character;
	/* Get character */
	if ( efi_systab ) {
		bs = efi_systab->BootServices;
		conin = efi_systab->ConIn;
		bs->WaitForEvent ( 1, &conin->WaitForKey, &index );
		conin->ReadKeyStroke ( conin, &key );
		character = key.UnicodeChar;
	} else {
		memset ( ¶ms, 0, sizeof ( params ) );
		params.vector.interrupt = 0x16;
		call_interrupt ( ¶ms );
		character = params.al;
	}
	return character;
}
 | 2,378 | 
	C | 
	.c | 86 | 25.360465 | 70 | 0.69851 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 287 | 
	wimfile.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/wimfile.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * WIM virtual files
 *
 */
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <wchar.h>
#include "wimboot.h"
#include "vdisk.h"
#include "wim.h"
#include "wimfile.h"
/** A WIM virtual file */
struct wim_file {
	/** Underlying virtual file */
	struct vdisk_file *file;
	/** WIM header */
	struct wim_header header;
	/** Resource */
	struct wim_resource_header resource;
};
/** Maximum number of WIM virtual files */
#define WIM_MAX_FILES 8
/** WIM virtual files */
static struct wim_file wim_files[WIM_MAX_FILES];
/**
 * Read from WIM virtual file
 *
 * @v file		Virtual file
 * @v data		Data buffer
 * @v offset		Offset
 * @v len		Length
 */
static void wim_read_file ( struct vdisk_file *file, void *data,
			    size_t offset, size_t len ) {
	struct wim_file *wfile = file->opaque;
	int rc;
	/* Read from resource */
	if ( ( rc = wim_read ( wfile->file, &wfile->header, &wfile->resource,
			       data, offset, len ) ) != 0 ) {
		die ( "Could not read from WIM virtual file\n" );
	}
}
/**
 * Add WIM virtual file
 *
 * @v file		Underlying virtual file
 * @v index		Image index, or 0 to use boot image
 * @v path		Path to file within WIM
 * @v wname		New virtual file name
 * @ret file		Virtual file, or NULL if not found
 */
struct vdisk_file * wim_add_file ( struct vdisk_file *file, unsigned int index,
				   const wchar_t *path, const wchar_t *wname ) {
	static unsigned int wim_file_idx = 0;
	struct wim_resource_header meta;
	struct wim_file *wfile;
	char name[ VDISK_NAME_LEN + 1 /* NUL */ ];
	unsigned int i;
	int rc;
	/* Sanity check */
	if ( wim_file_idx >= WIM_MAX_FILES )
		die ( "Too many WIM files\n" );
	wfile = &wim_files[wim_file_idx];
	/* Construct ASCII file name */
	snprintf ( name, sizeof ( name ), "%ls", wname );
	/* Skip files already added explicitly */
	for ( i = 0 ; i < VDISK_MAX_FILES ; i++ ) {
		if ( strcasecmp ( name, vdisk_files[i].name ) == 0 )
			return NULL;
	}
	/* Get WIM header */
	if ( ( rc = wim_header ( file, &wfile->header ) ) != 0 )
		return NULL;
	/* Get image metadata */
	if ( ( rc = wim_metadata ( file, &wfile->header, index, &meta ) ) != 0 )
		return NULL;
	/* Get file resource */
	if ( ( rc = wim_file ( file, &wfile->header, &meta, path,
			       &wfile->resource ) ) != 0 )
		return NULL;
	/* Add virtual file */
	wim_file_idx++;
	wfile->file = file;
	return vdisk_add_file ( name, wfile, wfile->resource.len,
				wim_read_file );
}
/**
 * Add WIM virtual files
 *
 * @v file		Underlying virtual file
 * @v index		Image index, or 0 to use boot image
 * @v paths		List of paths to files within WIM
 */
void wim_add_files ( struct vdisk_file *file, unsigned int index,
		     const wchar_t **paths ) {
	const wchar_t **path;
	const wchar_t *wname;
	const wchar_t *tmp;
	/* Add any existent files within the list */
	for ( path = paths ; *path ; path++ ) {
		/* Construct file name */
		wname = *path;
		for ( tmp = wname ; *tmp ; tmp++ ) {
			if ( *tmp == L'\\' )
				wname = ( tmp + 1 );
		}
		/* Add virtual file, if existent */
		wim_add_file ( file, index, *path, wname );
	}
}
 | 3,908 | 
	C | 
	.c | 132 | 27.227273 | 79 | 0.665425 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 288 | 
	efi.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/efi.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * EFI interface
 *
 */
#include "wimboot.h"
#include "efi.h"
/** EFI system table */
EFI_SYSTEM_TABLE *efi_systab;
/** EFI image handle */
EFI_HANDLE efi_image_handle;
 | 983 | 
	C | 
	.c | 30 | 30.9 | 70 | 0.742887 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 290 | 
	string.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/string.c | 
	/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * String functions
 *
 */
#include <stddef.h>
#include <stdint.h>
#include <string.h>
#include "ctype.h"
#include "wctype.h"
/**
 * Copy memory area
 *
 * @v dest		Destination address
 * @v src		Source address
 * @v len		Length
 * @ret dest		Destination address
 */
void * memcpy ( void *dest, const void *src, size_t len ) {
	void *edi = dest;
	const void *esi = src;
	int discard_ecx;
	/* Perform dword-based copy for bulk, then byte-based for remainder */
	__asm__ __volatile__ ( "rep movsl"
			       : "=&D" ( edi ), "=&S" ( esi ),
				 "=&c" ( discard_ecx )
			       : "0" ( edi ), "1" ( esi ), "2" ( len >> 2 )
			       : "memory" );
	__asm__ __volatile__ ( "rep movsb"
			       : "=&D" ( edi ), "=&S" ( esi ),
				 "=&c" ( discard_ecx )
			       : "0" ( edi ), "1" ( esi ), "2" ( len & 3 )
			       : "memory" );
	return dest;
}
/**
 * Copy memory area backwards
 *
 * @v dest		Destination address
 * @v src		Source address
 * @v len		Length
 * @ret dest		Destination address
 */
static void * memcpy_reverse ( void *dest, const void *src, size_t len ) {
	void *edi = ( dest + len - 1 );
	const void *esi = ( src + len - 1 );
	int discard_ecx;
	/* Assume memmove() is not performance-critical, and perform a
	 * bytewise copy for simplicity.
	 *
	 * Disable interrupts to avoid known problems on platforms
	 * that assume the direction flag always remains cleared.
	 */
	__asm__ __volatile__ ( "pushf\n\t"
			       "cli\n\t"
			       "std\n\t"
			       "rep movsb\n\t"
			       "popf\n\t"
			       : "=&D" ( edi ), "=&S" ( esi ),
				 "=&c" ( discard_ecx )
			       : "0" ( edi ), "1" ( esi ),
				 "2" ( len )
			       : "memory" );
	return dest;
}
/**
 * Copy (possibly overlapping) memory area
 *
 * @v dest		Destination address
 * @v src		Source address
 * @v len		Length
 * @ret dest		Destination address
 */
void * memmove ( void *dest, const void *src, size_t len ) {
	if ( dest <= src ) {
		return memcpy ( dest, src, len );
	} else {
		return memcpy_reverse ( dest, src, len );
	}
}
/**
 * Set memory area
 *
 * @v dest		Destination address
 * @v src		Source address
 * @v len		Length
 * @ret dest		Destination address
 */
void * memset ( void *dest, int c, size_t len ) {
	void *edi = dest;
	int eax = c;
	int discard_ecx;
	/* Expand byte to whole dword */
	eax |= ( eax << 8 );
	eax |= ( eax << 16 );
	/* Perform dword-based set for bulk, then byte-based for remainder */
	__asm__ __volatile__ ( "rep stosl"
			       : "=&D" ( edi ), "=&a" ( eax ),
				 "=&c" ( discard_ecx )
			       : "0" ( edi ), "1" ( eax ), "2" ( len >> 2 )
			       : "memory" );
	__asm__ __volatile__ ( "rep stosb"
			       : "=&D" ( edi ), "=&a" ( eax ),
				 "=&c" ( discard_ecx )
			       : "0" ( edi ), "1" ( eax ), "2" ( len & 3 )
			       : "memory" );
	return dest;
}
/**
 * Compare memory areas
 *
 * @v src1		First source area
 * @v src2		Second source area
 * @v len		Length
 * @ret diff		Difference
 */
int memcmp ( const void *src1, const void *src2, size_t len ) {
	const uint8_t *bytes1 = src1;
	const uint8_t *bytes2 = src2;
	int diff;
	while ( len-- ) {
		if ( ( diff = ( *(bytes1++) - *(bytes2++) ) ) )
			return diff;
	}
	return 0;
}
/**
 * Compare two strings
 *
 * @v str1		First string
 * @v str2		Second string
 * @ret diff		Difference
 */
int strcmp ( const char *str1, const char *str2 ) {
	int c1;
	int c2;
	do {
		c1 = *(str1++);
		c2 = *(str2++);
	} while ( ( c1 != '\0' ) && ( c1 == c2 ) );
	return ( c1 - c2 );
}
/**
 * Compare two strings, case-insensitively
 *
 * @v str1		First string
 * @v str2		Second string
 * @ret diff		Difference
 */
int strcasecmp ( const char *str1, const char *str2 ) {
	int c1;
	int c2;
	do {
		c1 = toupper ( *(str1++) );
		c2 = toupper ( *(str2++) );
	} while ( ( c1 != '\0' ) && ( c1 == c2 ) );
	return ( c1 - c2 );
}
/**
 * Compare two wide-character strings, case-insensitively
 *
 * @v str1		First string
 * @v str2		Second string
 * @ret diff		Difference
 */
int wcscasecmp ( const wchar_t *str1, const wchar_t *str2 ) {
	int c1;
	int c2;
	do {
		c1 = towupper ( *(str1++) );
		c2 = towupper ( *(str2++) );
	} while ( ( c1 != L'\0' ) && ( c1 == c2 ) );
	return ( c1 - c2 );
}
/**
 * Get length of string
 *
 * @v str		String
 * @ret len		Length
 */
size_t strlen ( const char *str ) {
	size_t len = 0;
	while ( *(str++) )
		len++;
	return len;
}
/**
 * Get length of wide-character string
 *
 * @v str		String
 * @ret len		Length (in characters)
 */
size_t wcslen ( const wchar_t *str ) {
	size_t len = 0;
	while ( *(str++) )
		len++;
	return len;
}
/**
 * Find character in wide-character string
 *
 * @v str		String
 * @v c			Wide character
 * @ret first		First occurrence of wide character in string, or NULL
 */
wchar_t * wcschr ( const wchar_t *str, wchar_t c ) {
	for ( ; *str ; str++ ) {
		if ( *str == c )
			return ( ( wchar_t * )str );
	}
	return NULL;
}
char *strchr(const char *str, char c) {
    for ( ; *str ; str++ ) {
		if ( *str == c )
			return ( ( char * )str );
	}
	return NULL;
}
/**
 * Check to see if character is a space
 *
 * @v c                 Character
 * @ret isspace         Character is a space
 */
int isspace ( int c ) {
        switch ( c ) {
        case ' ' :
        case '\f' :
        case '\n' :
        case '\r' :
        case '\t' :
        case '\v' :
                return 1;
        default:
                return 0;
        }
}
/**
 * Convert a string to an unsigned integer
 *
 * @v nptr		String
 * @v endptr		End pointer to fill in (or NULL)
 * @v base		Numeric base
 * @ret val		Value
 */
unsigned long strtoul ( const char *nptr, char **endptr, int base ) {
	unsigned long val = 0;
	int negate = 0;
	unsigned int digit;
	/* Skip any leading whitespace */
	while ( isspace ( *nptr ) )
		nptr++;
	/* Parse sign, if present */
	if ( *nptr == '+' ) {
		nptr++;
	} else if ( *nptr == '-' ) {
		nptr++;
		negate = 1;
	}
	/* Parse base */
	if ( base == 0 ) {
		/* Default to decimal */
		base = 10;
		/* Check for octal or hexadecimal markers */
		if ( *nptr == '0' ) {
			nptr++;
			base = 8;
			if ( ( *nptr | 0x20 ) == 'x' ) {
				nptr++;
				base = 16;
			}
		}
	}
	/* Parse digits */
	for ( ; ; nptr++ ) {
		digit = *nptr;
		if ( digit >= 'a' ) {
			digit = ( digit - 'a' + 10 );
		} else if ( digit >= 'A' ) {
			digit = ( digit - 'A' + 10 );
		} else if ( digit <= '9' ) {
			digit = ( digit - '0' );
		}
		if ( digit >= ( unsigned int ) base )
			break;
		val = ( ( val * base ) + digit );
	}
	/* Record end marker, if applicable */
	if ( endptr )
		*endptr = ( ( char * ) nptr );
	/* Return value */
	return ( negate ? -val : val );
}
 | 7,418 | 
	C | 
	.c | 313 | 20.597444 | 74 | 0.567223 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 291 | 
	main.c | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/main.c | 
	/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Main entry point
 *
 */
#include <stdint.h>
#include <stddef.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include "wimboot.h"
#include "peloader.h"
#include "int13.h"
#include "vdisk.h"
#include "cpio.h"
#include "lznt1.h"
#include "xca.h"
#include "cmdline.h"
#include "wimpatch.h"
#include "wimfile.h"
#include "pause.h"
#include "paging.h"
#include "memmap.h"
/** Start of our image (defined by linker) */
extern char _start[];
/** End of our image (defined by linker) */
extern char _end[];
/** Command line */
char *cmdline;
/** initrd */
void *initrd;
/** Length of initrd */
size_t initrd_len;
/** bootmgr.exe path within WIM */
static const wchar_t bootmgr_path[] = L"\\Windows\\Boot\\PXE\\bootmgr.exe";
/** Other paths within WIM */
static const wchar_t *wim_paths[] = {
	L"\\Windows\\Boot\\DVD\\PCAT\\boot.sdi",
	L"\\Windows\\Boot\\DVD\\PCAT\\BCD",
	L"\\Windows\\Boot\\Fonts\\segmono_boot.ttf",
	L"\\Windows\\Boot\\Fonts\\segoen_slboot.ttf",
	L"\\Windows\\Boot\\Fonts\\segoe_slboot.ttf",
	L"\\Windows\\Boot\\Fonts\\wgl4_boot.ttf",
	L"\\sms\\boot\\boot.sdi",
	NULL
};
/** bootmgr.exe file */
static struct vdisk_file *bootmgr;
/** WIM image file */
static struct vdisk_file *bootwim;
/** Minimal length of embedded bootmgr.exe */
#define BOOTMGR_MIN_LEN 16384
/** 1MB memory threshold */
#define ADDR_1MB 0x00100000
/** 2GB memory threshold */
#define ADDR_2GB 0x80000000
/** Memory regions */
enum {
	WIMBOOT_REGION = 0,
	PE_REGION,
	INITRD_REGION,
	NUM_REGIONS
};
/**
 * Wrap interrupt callback
 *
 * @v params		Parameters
 */
static void call_interrupt_wrapper ( struct bootapp_callback_params *params ) {
	struct paging_state state;
	uint16_t *attributes;
	/* Handle/modify/pass-through interrupt as required */
	if ( params->vector.interrupt == 0x13 ) {
		/* Enable paging */
		enable_paging ( &state );
		/* Intercept INT 13 calls for the emulated drive */
		emulate_int13 ( params );
		/* Disable paging */
		disable_paging ( &state );
	} else if ( ( params->vector.interrupt == 0x10 ) &&
		    ( params->ax == 0x4f01 ) &&
		    ( ! cmdline_gui ) ) {
		/* Mark all VESA video modes as unsupported */
		attributes = REAL_PTR ( params->es, params->di );
		call_interrupt ( params );
		*attributes &= ~0x0001;
	} else {
		/* Pass through interrupt */
		call_interrupt ( params );
	}
}
/** Real-mode callback functions */
static struct bootapp_callback_functions callback_fns = {
	.call_interrupt = call_interrupt_wrapper,
	.call_real = call_real,
};
/** Real-mode callbacks */
static struct bootapp_callback callback = {
	.fns = &callback_fns,
};
/** Boot application descriptor set */
static struct {
	/** Boot application descriptor */
	struct bootapp_descriptor bootapp;
	/** Boot application memory descriptor */
	struct bootapp_memory_descriptor memory;
	/** Boot application memory descriptor regions */
	struct bootapp_memory_region regions[NUM_REGIONS];
	/** Boot application entry descriptor */
	struct bootapp_entry_descriptor entry;
	struct bootapp_entry_wtf1_descriptor wtf1;
	struct bootapp_entry_wtf2_descriptor wtf2;
	struct bootapp_entry_wtf3_descriptor wtf3;
	struct bootapp_entry_wtf3_descriptor wtf3_copy;
	/** Boot application callback descriptor */
	struct bootapp_callback_descriptor callback;
	/** Boot application pointless descriptor */
	struct bootapp_pointless_descriptor pointless;
} __attribute__ (( packed )) bootapps = {
	.bootapp = {
		.signature = BOOTAPP_SIGNATURE,
		.version = BOOTAPP_VERSION,
		.len = sizeof ( bootapps ),
		.arch = BOOTAPP_ARCH_I386,
		.memory = offsetof ( typeof ( bootapps ), memory ),
		.entry = offsetof ( typeof ( bootapps ), entry ),
		.xxx = offsetof ( typeof ( bootapps ), wtf3_copy ),
		.callback = offsetof ( typeof ( bootapps ), callback ),
		.pointless = offsetof ( typeof ( bootapps ), pointless ),
	},
	.memory = {
		.version = BOOTAPP_MEMORY_VERSION,
		.len = sizeof ( bootapps.memory ),
		.num_regions = NUM_REGIONS,
		.region_len = sizeof ( bootapps.regions[0] ),
		.reserved_len = sizeof ( bootapps.regions[0].reserved ),
	},
	.entry = {
		.signature = BOOTAPP_ENTRY_SIGNATURE,
		.flags = BOOTAPP_ENTRY_FLAGS,
	},
	.wtf1 = {
		.flags = 0x11000001,
		.len = sizeof ( bootapps.wtf1 ),
		.extra_len = ( sizeof ( bootapps.wtf2 ) +
			       sizeof ( bootapps.wtf3 ) ),
	},
	.wtf3 = {
		.flags = 0x00000006,
		.len = sizeof ( bootapps.wtf3 ),
		.boot_partition_offset = ( VDISK_VBR_LBA * VDISK_SECTOR_SIZE ),
		.xxx = 0x01,
		.mbr_signature = VDISK_MBR_SIGNATURE,
	},
	.wtf3_copy = {
		.flags = 0x00000006,
		.len = sizeof ( bootapps.wtf3 ),
		.boot_partition_offset = ( VDISK_VBR_LBA * VDISK_SECTOR_SIZE ),
		.xxx = 0x01,
		.mbr_signature = VDISK_MBR_SIGNATURE,
	},
	.callback = {
		.callback = &callback,
	},
	.pointless = {
		.version = BOOTAPP_POINTLESS_VERSION,
	},
};
/**
 * Test if a paragraph is empty
 *
 * @v pgh		Paragraph
 * @ret is_empty	Paragraph is empty (all zeroes)
 */
static int is_empty_pgh ( const void *pgh ) {
	const uint32_t *dwords = pgh;
	return ( ( dwords[0] | dwords[1] | dwords[2] | dwords[3] ) == 0 );
}
/**
 * Read from file
 *
 * @v file		Virtual file
 * @v data		Data buffer
 * @v offset		Offset
 * @v len		Length
 */
static void read_file ( struct vdisk_file *file, void *data, size_t offset,
			size_t len ) {
	memcpy ( data, ( file->opaque + offset ), len );
}
/**
 * Add embedded bootmgr.exe extracted from bootmgr
 *
 * @v data		File data
 * @v len		Length
 * @ret file		Virtual file, or NULL
 *
 * bootmgr.exe is awkward to obtain, since it is not available as a
 * standalone file on the installation media, or on an installed
 * system, or in a Windows PE image as created by WAIK or WADK.  It
 * can be extracted from a typical boot.wim image using ImageX, but
 * this requires installation of the WAIK/WADK/wimlib.
 *
 * A compressed version of bootmgr.exe is contained within bootmgr,
 * which is trivial to obtain.
 */
static struct vdisk_file * add_bootmgr ( const void *data, size_t len ) {
	const uint8_t *compressed;
	size_t offset;
	size_t compressed_len;
	ssize_t ( * decompress ) ( const void *data, size_t len, void *buf );
	ssize_t decompressed_len;
	size_t padded_len;
	/* Look for an embedded compressed bootmgr.exe on an
	 * eight-byte boundary.
	 */
	for ( offset = BOOTMGR_MIN_LEN ; offset < ( len - BOOTMGR_MIN_LEN ) ;
	      offset += 0x08 ) {
		/* Initialise checks */
		decompress = NULL;
		compressed = ( data + offset );
		compressed_len = ( len - offset );
		/* Check for an embedded LZNT1-compressed bootmgr.exe.
		 * Since there is no way for LZNT1 to compress the
		 * initial "MZ" bytes of bootmgr.exe, we look for this
		 * signature starting three bytes after a paragraph
		 * boundary, with a preceding tag byte indicating that
		 * these two bytes would indeed be uncompressed.
		 */
		if ( ( ( offset & 0x0f ) == 0x00 ) &&
		     ( ( compressed[0x02] & 0x03 ) == 0x00 ) &&
		     ( compressed[0x03] == 'M' ) &&
		     ( compressed[0x04] == 'Z' ) ) {
			DBG ( "...checking for LZNT1-compressed bootmgr.exe at "
			      "+%#zx\n", offset );
			decompress = lznt1_decompress;
		}
		/* Check for an embedded XCA-compressed bootmgr.exe.
		 * The bytes 0x00, 'M', and 'Z' will always be
		 * present, and so the corresponding symbols must have
		 * a non-zero Huffman length.  The embedded image
		 * tends to have a large block of zeroes immediately
		 * beforehand, which we check for.  It's implausible
		 * that the compressed data could contain substantial
		 * runs of zeroes, so we check for that too, in order
		 * to eliminate some common false positive matches.
		 */
		if ( ( ( compressed[0x00] & 0x0f ) != 0x00 ) &&
		     ( ( compressed[0x26] & 0xf0 ) != 0x00 ) &&
		     ( ( compressed[0x2d] & 0x0f ) != 0x00 ) &&
		     ( is_empty_pgh ( compressed - 0x10 ) ) &&
		     ( ! is_empty_pgh ( ( compressed + 0x400 ) ) ) &&
		     ( ! is_empty_pgh ( ( compressed + 0x800 ) ) ) &&
		     ( ! is_empty_pgh ( ( compressed + 0xc00 ) ) ) ) {
			DBG ( "...checking for XCA-compressed bootmgr.exe at "
			      "+%#zx\n", offset );
			decompress = xca_decompress;
		}
		/* If we have not found a possible bootmgr.exe, skip
		 * to the next offset.
		 */
		if ( ! decompress )
			continue;
		/* Find length of decompressed image */
		decompressed_len = decompress ( compressed, compressed_len,
						NULL );
		if ( decompressed_len < 0 ) {
			/* May be a false positive signature match */
			continue;
		}
		/* Prepend decompressed image to initrd */
		DBG ( "...extracting embedded bootmgr.exe\n" );
		padded_len = ( ( decompressed_len + PAGE_SIZE - 1 ) &
			       ~( PAGE_SIZE - 1 ) );
		initrd -= padded_len;
		initrd_len += padded_len;
		decompress ( compressed, compressed_len, initrd );
		/* Add decompressed image */
		return vdisk_add_file ( "bootmgr.exe", initrd,
					decompressed_len, read_file );
	}
	DBG ( "...no embedded bootmgr.exe found\n" );
	return NULL;
}
/**
 * File handler
 *
 * @v name		File name
 * @v data		File data
 * @v len		Length
 * @ret rc		Return status code
 */
static int add_file ( const char *name, void *data, size_t len ) {
	struct vdisk_file *file;
	/* Store file */
	file = vdisk_add_file ( name, data, len, read_file );
	/* Check for special-case files */
	if ( strcasecmp ( name, "bootmgr.exe" ) == 0 ) {
		DBG ( "...found bootmgr.exe\n" );
		bootmgr = file;
	} else if ( strcasecmp ( name, "bootmgr" ) == 0 ) {
		DBG ( "...found bootmgr\n" );
		if ( ( ! bootmgr ) &&
		     ( bootmgr = add_bootmgr ( data, len ) ) ) {
			DBG ( "...extracted bootmgr.exe\n" );
		}
	} else if ( strcasecmp ( ( name + strlen ( name ) - 4 ),
				 ".wim" ) == 0 ) {
		DBG ( "...found WIM file %s\n", name );
		bootwim = file;
	}
	return 0;
}
/**
 * Relocate data between 1MB and 2GB if possible
 *
 * @v data		Start of data
 * @v len		Length of data
 * @ret start		Start address
 */
static void * relocate_memory_low ( void *data, size_t len ) {
	struct e820_entry *e820 = NULL;
	uint64_t end;
	intptr_t start;
	/* Read system memory map */
	while ( ( e820 = memmap_next ( e820 ) ) != NULL ) {
		/* Find highest compatible placement within this region */
		end = ( e820->start + e820->len );
		start = ( ( end > ADDR_2GB ) ? ADDR_2GB : end );
		if ( start < len )
			continue;
		start -= len;
		start &= ~( PAGE_SIZE - 1 );
		if ( start < e820->start )
			continue;
		if ( start < ADDR_1MB )
			continue;
		/* Relocate to this region */
		memmove ( ( void * ) start, data, len );
		return ( ( void * ) start );
	}
	/* Leave at original location */
	return data;
}
/**
 * Main entry point
 *
 */
int main ( void ) {
	size_t padded_len;
	void *raw_pe;
	struct loaded_pe pe;
	struct paging_state state;
	uint64_t initrd_phys;
	/* Initialise stack cookie */
	init_cookie();
	/* Print welcome banner */
    printf ( "\n\nBooting wim file...... (This may take a few minutes, please wait)\n\n");
	//printf ( "\n\nwimboot " VERSION " -- Windows Imaging Format "
	//	 "bootloader -- https://ipxe.org/wimboot\n\n" );
	/* Process command line */
	process_cmdline ( cmdline );
	/* Initialise paging */
	init_paging();
	/* Enable paging */
	enable_paging ( &state );
	/* Relocate initrd below 2GB if possible, to avoid collisions */
	DBG ( "Found initrd at [%p,%p)\n", initrd, ( initrd + initrd_len ) );
	initrd = relocate_memory_low ( initrd, initrd_len );
	DBG ( "Placing initrd at [%p,%p)\n", initrd, ( initrd + initrd_len ) );
	/* Extract files from initrd */
	if ( cpio_extract ( initrd, initrd_len, add_file ) != 0 )
		die ( "FATAL: could not extract initrd files\n" );
	/* Process WIM image */
	if ( bootwim ) {
		vdisk_patch_file ( bootwim, patch_wim );
		if ( ( ! bootmgr ) &&
		     ( bootmgr = wim_add_file ( bootwim, cmdline_index,
						bootmgr_path,
						L"bootmgr.exe" ) ) ) {
			DBG ( "...extracted bootmgr.exe\n" );
		}
		wim_add_files ( bootwim, cmdline_index, wim_paths );
	}
	/* Add INT 13 drive */
	callback.drive = initialise_int13();
	/* Read bootmgr.exe into memory */
	if ( ! bootmgr )
		die ( "FATAL: no bootmgr.exe\n" );
	if ( bootmgr->read == read_file ) {
		raw_pe = bootmgr->opaque;
	} else {
		padded_len = ( ( bootmgr->len + PAGE_SIZE - 1 ) &
			       ~( PAGE_SIZE -1 ) );
		raw_pe = ( initrd - padded_len );
		bootmgr->read ( bootmgr, raw_pe, 0, bootmgr->len );
	}
	/* Load bootmgr.exe into memory */
	if ( load_pe ( raw_pe, bootmgr->len, &pe ) != 0 )
		die ( "FATAL: Could not load bootmgr.exe\n" );
	/* Relocate initrd above 4GB if possible, to free up 32-bit memory */
	initrd_phys = relocate_memory_high ( initrd, initrd_len );
	DBG ( "Placing initrd at physical [%#llx,%#llx)\n",
	      initrd_phys, ( initrd_phys + initrd_len ) );
	/* Complete boot application descriptor set */
	bootapps.bootapp.pe_base = pe.base;
	bootapps.bootapp.pe_len = pe.len;
	bootapps.regions[WIMBOOT_REGION].start_page = page_start ( _start );
	bootapps.regions[WIMBOOT_REGION].num_pages = page_len ( _start, _end );
	bootapps.regions[PE_REGION].start_page = page_start ( pe.base );
	bootapps.regions[PE_REGION].num_pages =
		page_len ( pe.base, ( pe.base + pe.len ) );
	bootapps.regions[INITRD_REGION].start_page =
		( initrd_phys / PAGE_SIZE );
	bootapps.regions[INITRD_REGION].num_pages =
		page_len ( initrd, initrd + initrd_len );
	/* Omit initrd region descriptor if located above 4GB */
	if ( initrd_phys >= ADDR_4GB )
		bootapps.memory.num_regions--;
	/* Disable paging */
	disable_paging ( &state );
	/* Jump to PE image */
	DBG ( "Entering bootmgr.exe with parameters at %p\n", &bootapps );
	if ( cmdline_pause )
		pause();
	pe.entry ( &bootapps.bootapp );
	die ( "FATAL: bootmgr.exe returned\n" );
}
 | 14,409 | 
	C | 
	.c | 448 | 29.477679 | 90 | 0.665611 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 294 | 
	ProcessorBind.h | 
	ventoy_Ventoy/wimboot/wimboot-2.7.3/src/efi/ProcessorBind.h | 
	#ifndef _WIMBOOT_EFI_PROCESSOR_BIND_H
#define _WIMBOOT_EFI_PROCESSOR_BIND_H
/*
 * EFI header files rely on having the CPU architecture directory
 * present in the search path in order to pick up ProcessorBind.h.  We
 * use this header file as a quick indirection layer.
 *
 */
#if __i386__
#include <efi/Ia32/ProcessorBind.h>
#endif
#if __x86_64__
#include <efi/X64/ProcessorBind.h>
#endif
#endif /* _WIMBOOT_EFI_PROCESSOR_BIND_H */
 | 437 | 
	C | 
	.c | 15 | 27.533333 | 70 | 0.751196 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | true | false | false | false | true | 
| 303 | 
	vtoygpt.c | 
	ventoy_Ventoy/vtoycli/vtoygpt.c | 
	/******************************************************************************
 * vtoygpt.c  ---- ventoy gpt util
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include "vtoycli.h"
void DumpGuid(const char *prefix, GUID *guid)
{
    printf("%s: %08x-%04x-%04x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x\n",
        prefix,
        guid->data1, guid->data2, guid->data3,
        guid->data4[0], guid->data4[1], guid->data4[2], guid->data4[3],
        guid->data4[4], guid->data4[5], guid->data4[6], guid->data4[7]
        );
}
void DumpHead(VTOY_GPT_HDR *pHead)
{
    UINT32 CrcRead;
    UINT32 CrcCalc;
    
    printf("Signature:<%s>\n", pHead->Signature);
    printf("Version:<%02x %02x %02x %02x>\n", pHead->Version[0], pHead->Version[1], pHead->Version[2], pHead->Version[3]);
    printf("Length:%u\n", pHead->Length);
    printf("Crc:0x%08x\n", pHead->Crc);
    printf("EfiStartLBA:%lu\n", pHead->EfiStartLBA);
    printf("EfiBackupLBA:%lu\n", pHead->EfiBackupLBA);
    printf("PartAreaStartLBA:%lu\n", pHead->PartAreaStartLBA);
    printf("PartAreaEndLBA:%lu\n", pHead->PartAreaEndLBA);
    DumpGuid("DiskGuid", &pHead->DiskGuid);
    
    printf("PartTblStartLBA:%lu\n", pHead->PartTblStartLBA);
    printf("PartTblTotNum:%u\n", pHead->PartTblTotNum);
    printf("PartTblEntryLen:%u\n", pHead->PartTblEntryLen);
    printf("PartTblCrc:0x%08x\n", pHead->PartTblCrc);
    CrcRead = pHead->Crc;
    pHead->Crc = 0;
    CrcCalc = VtoyCrc32(pHead, pHead->Length);
    if (CrcCalc != CrcRead)
    {
        printf("Head CRC Check Failed\n");
    }
    else
    {
        printf("Head CRC Check SUCCESS [%x] [%x]\n", CrcCalc, CrcRead);
    }
    CrcRead = pHead->PartTblCrc;
    CrcCalc = VtoyCrc32(pHead + 1, pHead->PartTblEntryLen * pHead->PartTblTotNum);
    if (CrcCalc != CrcRead)
    {
        printf("Part Table CRC Check Failed\n");
    }
    else
    {
        printf("Part Table CRC Check SUCCESS [%x] [%x]\n", CrcCalc, CrcRead);
    }
}
void DumpPartTable(VTOY_GPT_PART_TBL *Tbl)
{
    int i;
    
    DumpGuid("PartType", &Tbl->PartType);
    DumpGuid("PartGuid", &Tbl->PartGuid);
    printf("StartLBA:%lu\n", Tbl->StartLBA);
    printf("LastLBA:%lu\n", Tbl->LastLBA);
    printf("Attr:0x%lx\n", Tbl->Attr);
    printf("Name:");
    for (i = 0; i < 36 && Tbl->Name[i]; i++)
    {
        printf("%c", (CHAR)(Tbl->Name[i]));
    }
    printf("\n");    
}
void DumpMBR(MBR_HEAD *pMBR)
{
    int i;
    
    for (i = 0; i < 4; i++)
    {
        printf("=========== Partition Table %d ============\n", i + 1);
        printf("PartTbl.Active = 0x%x\n", pMBR->PartTbl[i].Active);
        printf("PartTbl.FsFlag = 0x%x\n", pMBR->PartTbl[i].FsFlag);
        printf("PartTbl.StartSectorId = %u\n", pMBR->PartTbl[i].StartSectorId);
        printf("PartTbl.SectorCount = %u\n", pMBR->PartTbl[i].SectorCount);
        printf("PartTbl.StartHead = %u\n", pMBR->PartTbl[i].StartHead);
        printf("PartTbl.StartSector = %u\n", pMBR->PartTbl[i].StartSector);
        printf("PartTbl.StartCylinder = %u\n", pMBR->PartTbl[i].StartCylinder);
        printf("PartTbl.EndHead = %u\n", pMBR->PartTbl[i].EndHead);
        printf("PartTbl.EndSector = %u\n", pMBR->PartTbl[i].EndSector);
        printf("PartTbl.EndCylinder = %u\n", pMBR->PartTbl[i].EndCylinder);
    }
}
int DumpGptInfo(VTOY_GPT_INFO *pGptInfo)
{
    int i;
    DumpMBR(&pGptInfo->MBR);
    DumpHead(&pGptInfo->Head);
    for (i = 0; i < 128; i++)
    {
        if (pGptInfo->PartTbl[i].StartLBA == 0)
        {
            break;
        }
    
        printf("=====Part %d=====\n", i);
        DumpPartTable(pGptInfo->PartTbl + i);
    }
    return 0;
}
int vtoygpt_main(int argc, char **argv)
{
    int i;
    int fd;
    UINT64 DiskSize;
    CHAR16 *Name = NULL;
    VTOY_GPT_INFO *pMainGptInfo = NULL;
    VTOY_BK_GPT_INFO *pBackGptInfo = NULL;
    if (argc != 3)
    {
        printf("usage: vtoygpt -f /dev/sdb\n");
        return 1;
    }
    fd = open(argv[2], O_RDWR);
    if (fd < 0)
    {
        printf("Failed to open %s\n", argv[2]);
        return 1;
    }
    pMainGptInfo = malloc(sizeof(VTOY_GPT_INFO));
    pBackGptInfo = malloc(sizeof(VTOY_BK_GPT_INFO));
    if (NULL == pMainGptInfo || NULL == pBackGptInfo)
    {
        close(fd);
        return 1;
    }
    read(fd, pMainGptInfo, sizeof(VTOY_GPT_INFO));
    
    if (argv[1][0] == '-' && argv[1][1] == 'd')
    {
        DumpGptInfo(pMainGptInfo);
    }
    else
    {
        DiskSize = lseek(fd, 0, SEEK_END);
        lseek(fd, DiskSize - 33 * 512, SEEK_SET);
        read(fd, pBackGptInfo, sizeof(VTOY_BK_GPT_INFO));
        Name = pMainGptInfo->PartTbl[1].Name;
        if (Name[0] == 'V' && Name[1] == 'T' && Name[2] == 'O' && Name[3] == 'Y')
        {
            pMainGptInfo->PartTbl[1].Attr = VENTOY_EFI_PART_ATTR;
            pMainGptInfo->Head.PartTblCrc = VtoyCrc32(pMainGptInfo->PartTbl, sizeof(pMainGptInfo->PartTbl));
            pMainGptInfo->Head.Crc = 0;
            pMainGptInfo->Head.Crc = VtoyCrc32(&pMainGptInfo->Head, pMainGptInfo->Head.Length);
            pBackGptInfo->PartTbl[1].Attr = VENTOY_EFI_PART_ATTR;
            pBackGptInfo->Head.PartTblCrc = VtoyCrc32(pBackGptInfo->PartTbl, sizeof(pBackGptInfo->PartTbl));
            pBackGptInfo->Head.Crc = 0;
            pBackGptInfo->Head.Crc = VtoyCrc32(&pBackGptInfo->Head, pBackGptInfo->Head.Length);
            lseek(fd, 512, SEEK_SET);
            write(fd, (UINT8 *)pMainGptInfo + 512, sizeof(VTOY_GPT_INFO) - 512);
            lseek(fd, DiskSize - 33 * 512, SEEK_SET);
            write(fd, pBackGptInfo, sizeof(VTOY_BK_GPT_INFO));
            fsync(fd);
        }
    }
    free(pMainGptInfo);
    free(pBackGptInfo);
    close(fd);
    return 0;
}
 | 6,627 | 
	C | 
	.c | 189 | 29.285714 | 122 | 0.607551 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 304 | 
	vtoycli.c | 
	ventoy_Ventoy/vtoycli/vtoycli.c | 
	/******************************************************************************
 * vtoycli.c
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include "vtoycli.h"
void ventoy_gen_preudo_uuid(void *uuid)
{
    int i;
    int fd;
    fd = open("/dev/urandom", O_RDONLY);
    if (fd < 0)
    {
        srand(time(NULL));
        for (i = 0; i < 8; i++)
        {
            *((uint16_t *)uuid + i) = (uint16_t)(rand() & 0xFFFF);
        }
    }
    else
    {
        read(fd, uuid, 16);
        close(fd);
    }
}
UINT64 get_disk_size_in_byte(const char *disk)
{
    int fd;
    int rc;
    const char *pos = disk;
    unsigned long long size = 0;
    char diskpath[256] = {0};
    char sizebuf[64] = {0};
    if (strncmp(disk, "/dev/", 5) == 0)
    {
        pos = disk + 5;
    }
    // Try 1: get size from sysfs
    snprintf(diskpath, sizeof(diskpath) - 1, "/sys/block/%s/size", pos);
    if (access(diskpath, F_OK) >= 0)
    {
        fd = open(diskpath, O_RDONLY);
        if (fd >= 0)
        {
            read(fd, sizebuf, sizeof(sizebuf));
            size = strtoull(sizebuf, NULL, 10);
            close(fd);
            return (size * 512);
        }
    }
    else
    {
        printf("%s not exist \n", diskpath);
    }
    printf("disk %s size %llu bytes\n", disk, (unsigned long long)size);
    return size;
}
int main(int argc, char **argv)
{
    if (argc < 2)
    {
        return 1;
    }
    else if (strcmp(argv[1], "fat") == 0)
    {
        return vtoyfat_main(argc - 1, argv + 1);
    }
    else if (strcmp(argv[1], "gpt") == 0)
    {
        return vtoygpt_main(argc - 1, argv + 1);
    }
    else if (strcmp(argv[1], "partresize") == 0)
    {
        return partresize_main(argc - 1, argv + 1);
    }
    else
    {
        return 1;
    }
}
 | 2,750 | 
	C | 
	.c | 109 | 20.568807 | 79 | 0.573764 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 306 | 
	partresize.c | 
	ventoy_Ventoy/vtoycli/partresize.c | 
	/******************************************************************************
 * partresize.c  ---- ventoy part resize util
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <fat_filelib.h>
#include "vtoycli.h"
static int g_disk_fd = 0;
static UINT64 g_disk_offset = 0;
static GUID g_ZeroGuid = {0};
static GUID g_WindowsDataPartGuid = { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
static int vtoy_disk_read(uint32 sector, uint8 *buffer, uint32 sector_count)
{
    UINT64 offset = sector * 512ULL;
    
    lseek(g_disk_fd, g_disk_offset + offset, SEEK_SET);
    read(g_disk_fd, buffer, sector_count * 512);
    
    return 1;
}
static int vtoy_disk_write(uint32 sector, uint8 *buffer, uint32 sector_count)
{
    UINT64 offset = sector * 512ULL;
    
    lseek(g_disk_fd, g_disk_offset + offset, SEEK_SET);
    write(g_disk_fd, buffer, sector_count * 512);
    
    return 1;
}
static int gpt_check(const char *disk)
{
    int fd = -1;
    int rc = 1;
    VTOY_GPT_INFO *pGPT = NULL;
    fd = open(disk, O_RDONLY);
    if (fd < 0)
    {
        printf("Failed to open %s\n", disk);
        goto out;
    }
    pGPT = malloc(sizeof(VTOY_GPT_INFO));
    if (NULL == pGPT)
    {
        goto out;
    }
    memset(pGPT, 0, sizeof(VTOY_GPT_INFO));
    
    read(fd, pGPT, sizeof(VTOY_GPT_INFO));
    if (pGPT->MBR.PartTbl[0].FsFlag == 0xEE && memcmp(pGPT->Head.Signature, "EFI PART", 8) == 0)
	{
        rc = 0;
	}
out:
    check_close(fd);        
    check_free(pGPT);
    return rc;
}
static int part_check(const char *disk)
{
    int i;
    int fd = -1;
    int rc = 0;
    int Index = 0;
    int Count = 0;
    int PartStyle = 0;
    UINT64 Part1Start;
    UINT64 Part1End;
    UINT64 NextPartStart;
    UINT64 DiskSizeInBytes;
    VTOY_GPT_INFO *pGPT = NULL;
    DiskSizeInBytes = get_disk_size_in_byte(disk);
    if (DiskSizeInBytes == 0)
    {
        printf("Failed to get disk size of %s\n", disk);
        goto out;
    }
    
    fd = open(disk, O_RDONLY);
    if (fd < 0)
    {
        printf("Failed to open %s\n", disk);
        goto out;
    }
    pGPT = malloc(sizeof(VTOY_GPT_INFO));
    if (NULL == pGPT)
    {
        goto out;
    }
    memset(pGPT, 0, sizeof(VTOY_GPT_INFO));
    
    read(fd, pGPT, sizeof(VTOY_GPT_INFO));
    if (pGPT->MBR.PartTbl[0].FsFlag == 0xEE && memcmp(pGPT->Head.Signature, "EFI PART", 8) == 0)
	{
        PartStyle = 1;
	}
	else
	{
        PartStyle = 0;
	}
    if (PartStyle == 0)
    {
		PART_TABLE *PartTbl = pGPT->MBR.PartTbl;
        for (Count = 0, i = 0; i < 4; i++)
        {
            if (PartTbl[i].SectorCount > 0)
            {
				printf("MBR Part%d SectorStart:%u SectorCount:%u\n", i + 1, PartTbl[i].StartSectorId, PartTbl[i].SectorCount);
                Count++;
            }
        }
		//We must have a free partition table for VTOYEFI partition
		if (Count >= 4)
		{
			printf("###[FAIL] 4 MBR partition tables are all used.\n");
			goto out;
		}
		if (PartTbl[0].SectorCount > 0)
		{
			Part1Start = PartTbl[0].StartSectorId;
			Part1End = PartTbl[0].SectorCount + Part1Start;
		}
		else
		{
			printf("###[FAIL] MBR Partition 1 is invalid\n");
			goto out;
		}
		Index = -1;
		NextPartStart = DiskSizeInBytes / 512ULL;
		for (i = 1; i < 4; i++)
		{
			if (PartTbl[i].SectorCount > 0 && NextPartStart > PartTbl[i].StartSectorId)
			{
				Index = i;
				NextPartStart = PartTbl[i].StartSectorId;
			}
		}
        NextPartStart *= 512ULL;
		printf("DiskSize:%llu NextPartStart:%llu(LBA:%llu) Index:%d\n", 
            DiskSizeInBytes, NextPartStart, NextPartStart / 512ULL, Index);
    }
    else
    {
		VTOY_GPT_PART_TBL *PartTbl = pGPT->PartTbl;
        for (Count = 0, i = 0; i < 128; i++)
        {
            if (memcmp(&(PartTbl[i].PartGuid), &g_ZeroGuid, sizeof(GUID)))
            {
				printf("GPT Part%d StartLBA:%llu LastLBA:%llu\n", i + 1, PartTbl[i].StartLBA, PartTbl[i].LastLBA);
                Count++;
            }
        }
		if (Count >= 128)
		{
			printf("###[FAIL] 128 GPT partition tables are all used.\n");
			goto out;
		}
		if (memcmp(&(PartTbl[0].PartGuid), &g_ZeroGuid, sizeof(GUID)))
		{
			Part1Start = PartTbl[0].StartLBA;
			Part1End = PartTbl[0].LastLBA + 1;
		}
		else
		{
			printf("###[FAIL] GPT Partition 1 is invalid\n");
			goto out;
		}
		Index = -1;
		NextPartStart = (pGPT->Head.PartAreaEndLBA + 1);
		for (i = 1; i < 128; i++)
		{
			if (memcmp(&(PartTbl[i].PartGuid), &g_ZeroGuid, sizeof(GUID)) && NextPartStart > PartTbl[i].StartLBA)
			{
				Index = i;
				NextPartStart = PartTbl[i].StartLBA;
			}
		}
		NextPartStart *= 512ULL;
		printf("DiskSize:%llu NextPartStart:%llu(LBA:%llu) Index:%d\n",
            DiskSizeInBytes, NextPartStart, NextPartStart / 512ULL, Index);
    }
	printf("Valid partition table (%s): Valid partition count:%d\n", (PartStyle == 0) ? "MBR" : "GPT", Count);
	//Partition 1 MUST start at 1MB
	Part1Start *= 512ULL;
	Part1End *= 512ULL;
	printf("Partition 1 start at: %llu %lluKB, end:%llu, NextPartStart:%llu\n", 
		Part1Start, Part1Start / 1024, Part1End, NextPartStart);
    if (Part1Start != SIZE_1MB)
    {
        printf("###[FAIL] Partition 1 is not start at 1MB\n");
        goto out;
    }
	//If we have free space after partition 1
	if (NextPartStart - Part1End >= VENTOY_EFI_PART_SIZE)
	{
		printf("Free space after partition 1 (%llu) is enough for VTOYEFI part\n", NextPartStart - Part1End);
		rc = 1;
	}
	else if (NextPartStart == Part1End)
	{
		printf("There is no free space after partition 1\n");
        rc = 2;
	}
	else
	{
		printf("The free space after partition 1 is not enough\n");
        rc = 2;
	}
out:
    check_close(fd);        
    check_free(pGPT);
    return rc;
}
static int secureboot_proc(char *disk, UINT64 part2start)
{
	int rc = 0;
	int size;
    int fd = -1;
	char *filebuf = NULL;
	void *file = NULL;
    fd = open(disk, O_RDWR);
    if (fd < 0)
    {
        printf("Failed to open %s\n", disk);
        return 1;
    }
    g_disk_fd = fd;
    g_disk_offset = part2start * 512ULL;
	fl_init();
	if (0 == fl_attach_media(vtoy_disk_read, vtoy_disk_write))
	{
		file = fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
		printf("Open ventoy efi file %p\n", file);
		if (file)
		{
			fl_fseek(file, 0, SEEK_END);
			size = (int)fl_ftell(file);
			fl_fseek(file, 0, SEEK_SET);
			printf("ventoy x64 efi file size %d ...\n", size);
			filebuf = (char *)malloc(size);
			if (filebuf)
			{
				fl_fread(filebuf, 1, size, file);
			}
			fl_fclose(file);
			fl_remove("/EFI/BOOT/BOOTX64.EFI");
			fl_remove("/EFI/BOOT/grubx64.efi");
			fl_remove("/EFI/BOOT/grubx64_real.efi");
			fl_remove("/EFI/BOOT/MokManager.efi");
			fl_remove("/EFI/BOOT/mmx64.efi");
            fl_remove("/ENROLL_THIS_KEY_IN_MOKMANAGER.cer");
			file = fl_fopen("/EFI/BOOT/BOOTX64.EFI", "wb");
			printf("Open bootx64 efi file %p\n", file);
			if (file)
			{
				if (filebuf)
				{
					fl_fwrite(filebuf, 1, size, file);
				}
				
				fl_fflush(file);
				fl_fclose(file);
			}
			if (filebuf)
			{
				free(filebuf);
			}
		}
        file = fl_fopen("/EFI/BOOT/grubia32_real.efi", "rb");
        printf("Open ventoy ia32 efi file %p\n", file);
        if (file)
        {
            fl_fseek(file, 0, SEEK_END);
            size = (int)fl_ftell(file);
            fl_fseek(file, 0, SEEK_SET);
            printf("ventoy efi file size %d ...\n", size);
            filebuf = (char *)malloc(size);
            if (filebuf)
            {
                fl_fread(filebuf, 1, size, file);
            }
            fl_fclose(file);
            fl_remove("/EFI/BOOT/BOOTIA32.EFI");
            fl_remove("/EFI/BOOT/grubia32.efi");
            fl_remove("/EFI/BOOT/grubia32_real.efi");
            fl_remove("/EFI/BOOT/mmia32.efi");            
            file = fl_fopen("/EFI/BOOT/BOOTIA32.EFI", "wb");
            printf("Open bootia32 efi file %p\n", file);
            if (file)
            {
                if (filebuf)
                {
                    fl_fwrite(filebuf, 1, size, file);
                }
                fl_fflush(file);
                fl_fclose(file);
            }
            if (filebuf)
            {
                free(filebuf);
            }
        }
	}
	else
	{
		rc = 1;
	}
	fl_shutdown();
    fsync(fd);
	return rc;
}
static int VentoyFillMBRLocation(UINT64 DiskSizeInBytes, UINT32 StartSectorId, UINT32 SectorCount, PART_TABLE *Table)
{
    UINT8 Head;
    UINT8 Sector;
    UINT8 nSector = 63;
    UINT8 nHead = 8;    
    UINT32 Cylinder;
    UINT32 EndSectorId;
    while (nHead != 0 && (DiskSizeInBytes / 512 / nSector / nHead) > 1024)
    {
        nHead = (UINT8)nHead * 2;
    }
    if (nHead == 0)
    {
        nHead = 255;
    }
    Cylinder = StartSectorId / nSector / nHead;
    Head = StartSectorId / nSector % nHead;
    Sector = StartSectorId % nSector + 1;
    Table->StartHead = Head;
    Table->StartSector = Sector;
    Table->StartCylinder = Cylinder;
    EndSectorId = StartSectorId + SectorCount - 1;
    Cylinder = EndSectorId / nSector / nHead;
    Head = EndSectorId / nSector % nHead;
    Sector = EndSectorId % nSector + 1;
    Table->EndHead = Head;
    Table->EndSector = Sector;
    Table->EndCylinder = Cylinder;
    Table->StartSectorId = StartSectorId;
    Table->SectorCount = SectorCount;
    return 0;
}
static int WriteDataToPhyDisk(int fd, UINT64 offset, void *buffer, int len)
{
    ssize_t wrlen;
    off_t newseek;
        
    newseek = lseek(fd, offset, SEEK_SET);
    if (newseek != offset)
    {
        printf("Failed to lseek %llu %lld %d\n", offset, (long long)newseek, errno);
        return 0;
    }
    
    wrlen = write(fd, buffer, len);
    if ((int)wrlen != len)
    {
        printf("Failed to write %d %d %d\n", len, (int)wrlen, errno);
        return 0;
    }
    
    return 1;
}
static int VentoyFillBackupGptHead(VTOY_GPT_INFO *pInfo, VTOY_GPT_HDR *pHead)
{
    UINT64 LBA;
    UINT64 BackupLBA;
    memcpy(pHead, &pInfo->Head, sizeof(VTOY_GPT_HDR));
    LBA = pHead->EfiStartLBA;
    BackupLBA = pHead->EfiBackupLBA;
    
    pHead->EfiStartLBA = BackupLBA;
    pHead->EfiBackupLBA = LBA;
    pHead->PartTblStartLBA = BackupLBA + 1 - 33;
    pHead->Crc = 0;
    pHead->Crc = VtoyCrc32(pHead, pHead->Length);
    return 0;
}
static int update_part_table(char *disk, UINT64 part2start)
{
    int i;
    int j;
    int fd = -1;
    int rc = 1;
    int PartStyle = 0;
    ssize_t len = 0;
    UINT64 DiskSizeInBytes;
    VTOY_GPT_INFO *pGPT = NULL;
    VTOY_GPT_HDR *pBack = NULL;
    DiskSizeInBytes = get_disk_size_in_byte(disk);
    if (DiskSizeInBytes == 0)
    {
        printf("Failed to get disk size of %s\n", disk);
        goto out;
    }
    
    fd = open(disk, O_RDWR);
    if (fd < 0)
    {
        printf("Failed to open %s\n", disk);
        goto out;
    }
    pGPT = malloc(sizeof(VTOY_GPT_INFO) + sizeof(VTOY_GPT_HDR));
    if (NULL == pGPT)
    {
        goto out;
    }
    memset(pGPT, 0, sizeof(VTOY_GPT_INFO) + sizeof(VTOY_GPT_HDR));
    pBack = (VTOY_GPT_HDR *)(pGPT + 1);
    
    len = read(fd, pGPT, sizeof(VTOY_GPT_INFO));
    if (len != (ssize_t)sizeof(VTOY_GPT_INFO))
    {
        printf("Failed to read partition table %d err:%d\n", (int)len, errno);
        goto out;
    }
    if (pGPT->MBR.PartTbl[0].FsFlag == 0xEE && memcmp(pGPT->Head.Signature, "EFI PART", 8) == 0)
	{
        PartStyle = 1;
	}
	else
	{
        PartStyle = 0;
	}
    if (PartStyle == 0)
    {
		PART_TABLE *PartTbl = pGPT->MBR.PartTbl;
        for (i = 1; i < 4; i++)
        {
            if (PartTbl[i].SectorCount == 0)
            {
				break;
            }
        }
		if (i >= 4)
		{
			printf("###[FAIL] Can not find a free MBR partition table.\n");
			goto out;
		}
        for (j = i - 1; j > 0; j--)
		{
			printf("Move MBR partition table %d --> %d\n", j + 1, j + 2);
			memcpy(PartTbl + (j + 1), PartTbl + j, sizeof(PART_TABLE));
		}
        memset(PartTbl + 1, 0, sizeof(PART_TABLE));
        VentoyFillMBRLocation(DiskSizeInBytes, (UINT32)part2start, VENTOY_EFI_PART_SIZE / 512, PartTbl + 1);
		PartTbl[1].Active = 0x00;
		PartTbl[1].FsFlag = 0xEF; // EFI System Partition
        PartTbl[0].Active = 0x80; // bootable
        PartTbl[0].SectorCount = (UINT32)part2start - 2048;
        
        if (!WriteDataToPhyDisk(fd, 0, &(pGPT->MBR), 512))
		{
			printf("MBR write MBR failed\n");
			goto out;
		}
        fsync(fd);
        printf("MBR update partition table success.\n");
        rc = 0;
    }
    else
    {
		VTOY_GPT_PART_TBL *PartTbl = pGPT->PartTbl;
        for (i = 1; i < 128; i++)
        {
            if (memcmp(&(PartTbl[i].PartGuid), &g_ZeroGuid, sizeof(GUID)) == 0)
            {
				break;
            }
        }
		if (i >= 128)
		{
			printf("###[FAIL] Can not find a free GPT partition table.\n");
			goto out;
		}
		for (j = i - 1; j > 0; j--)
		{
			printf("Move GPT partition table %d --> %d\n", j + 1, j + 2);
			memcpy(PartTbl + (j + 1), PartTbl + j, sizeof(VTOY_GPT_PART_TBL));
		}
        // to fix windows issue
        memset(PartTbl + 1, 0, sizeof(VTOY_GPT_PART_TBL));
		memcpy(&(PartTbl[1].PartType), &g_WindowsDataPartGuid, sizeof(GUID));
		ventoy_gen_preudo_uuid(&(PartTbl[1].PartGuid));
        PartTbl[0].LastLBA = part2start - 1;
        PartTbl[1].StartLBA = PartTbl[0].LastLBA + 1;
		PartTbl[1].LastLBA = PartTbl[1].StartLBA + VENTOY_EFI_PART_SIZE / 512 - 1;
		PartTbl[1].Attr = 0xC000000000000001ULL;
        PartTbl[1].Name[0] = 'V';
        PartTbl[1].Name[1] = 'T';
        PartTbl[1].Name[2] = 'O';
        PartTbl[1].Name[3] = 'Y';
        PartTbl[1].Name[4] = 'E';
        PartTbl[1].Name[5] = 'F';
        PartTbl[1].Name[6] = 'I';
        PartTbl[1].Name[7] = 0;
		//Update CRC
		pGPT->Head.PartTblCrc = VtoyCrc32(pGPT->PartTbl, sizeof(pGPT->PartTbl));
		pGPT->Head.Crc = 0;
		pGPT->Head.Crc = VtoyCrc32(&(pGPT->Head), pGPT->Head.Length);
		printf("pGPT->Head.EfiStartLBA=%llu\n", pGPT->Head.EfiStartLBA);
		printf("pGPT->Head.EfiBackupLBA=%llu\n", pGPT->Head.EfiBackupLBA);
		VentoyFillBackupGptHead(pGPT, pBack);
		if (!WriteDataToPhyDisk(fd, pGPT->Head.EfiBackupLBA * 512, pBack, 512))
		{
			printf("GPT write backup head failed\n");
			goto out;
		}
		if (!WriteDataToPhyDisk(fd, (pGPT->Head.EfiBackupLBA - 32) * 512, pGPT->PartTbl, 512 * 32))
		{
			printf("GPT write backup partition table failed\n");
			goto out;
		}
		if (!WriteDataToPhyDisk(fd, 0, pGPT, 512 * 34))
		{
			printf("GPT write MBR & Main partition table failed\n");
			goto out;
		}
        fsync(fd);
        printf("GPT update partition table success.\n");
        rc = 0;
    }
out:
    check_close(fd);        
    check_free(pGPT);
    return rc;
}
int partresize_main(int argc, char **argv)
{
    UINT64 sector;
    
    if (argc != 3 && argc != 4)
    {
        printf("usage: partresize -c/-f /dev/sdb\n");
        return 1;
    }
    if (strcmp(argv[1], "-c") == 0)
    {
        return part_check(argv[2]);
    }
    else if (strcmp(argv[1], "-s") == 0)
    {
        sector = strtoull(argv[3], NULL, 10);
        return secureboot_proc(argv[2], sector);
    }
    else if (strcmp(argv[1], "-p") == 0)
    {
        sector = strtoull(argv[3], NULL, 10);    
        return update_part_table(argv[2], sector);
    }
    else if (strcmp(argv[1], "-t") == 0)
    {
        return gpt_check(argv[2]);
    }
    else
    {
        return 1;
    }
}
 | 16,319 | 
	C | 
	.c | 571 | 22.929947 | 119 | 0.588859 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 308 | 
	vtoycli.h | 
	ventoy_Ventoy/vtoycli/vtoycli.h | 
	/******************************************************************************
 * vtoycli.h
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#ifndef __VTOYCLI_H__
#define __VTOYCLI_H__
#define VENTOY_EFI_PART_ATTR   0xC000000000000001ULL
#define SIZE_1MB   (1024 * 1024)
#define VENTOY_EFI_PART_SIZE   (32 * SIZE_1MB)
#define check_free(p) if (p) free(p)
#define check_close(fd) if (fd >= 0) close(fd)
#define VOID   void
#define CHAR   char
#define UINT64 unsigned long long
#define UINT32 unsigned int
#define UINT16 unsigned short
#define CHAR16 unsigned short
#define UINT8  unsigned char
UINT32 VtoyCrc32(VOID *Buffer, UINT32 Length);
#define COMPILE_ASSERT(expr)  extern char __compile_assert[(expr) ? 1 : -1]
#pragma pack(1)
typedef struct PART_TABLE
{
    UINT8  Active;
    UINT8  StartHead;
    UINT16 StartSector : 6;
    UINT16 StartCylinder : 10;
    UINT8  FsFlag;
    UINT8  EndHead;
    UINT16 EndSector : 6;
    UINT16 EndCylinder : 10;
    UINT32 StartSectorId;
    UINT32 SectorCount;
}PART_TABLE;
typedef struct MBR_HEAD
{
    UINT8 BootCode[446];
    PART_TABLE PartTbl[4];
    UINT8 Byte55;
    UINT8 ByteAA;
}MBR_HEAD;
typedef struct GUID
{
    UINT32   data1;
    UINT16   data2;
    UINT16   data3;
    UINT8    data4[8];
}GUID;
typedef struct VTOY_GPT_HDR
{
    CHAR   Signature[8]; /* EFI PART */
    UINT8  Version[4];
    UINT32 Length;
    UINT32 Crc;
    UINT8  Reserved1[4];
    UINT64 EfiStartLBA;
    UINT64 EfiBackupLBA;
    UINT64 PartAreaStartLBA;
    UINT64 PartAreaEndLBA;
    GUID   DiskGuid;
    UINT64 PartTblStartLBA;
    UINT32 PartTblTotNum;
    UINT32 PartTblEntryLen;
    UINT32 PartTblCrc;
    UINT8  Reserved2[420];
}VTOY_GPT_HDR;
COMPILE_ASSERT(sizeof(VTOY_GPT_HDR) == 512);
typedef struct VTOY_GPT_PART_TBL
{
    GUID   PartType;
    GUID   PartGuid;
    UINT64 StartLBA;
    UINT64 LastLBA;
    UINT64 Attr;
    CHAR16 Name[36];
}VTOY_GPT_PART_TBL;
COMPILE_ASSERT(sizeof(VTOY_GPT_PART_TBL) == 128);
typedef struct VTOY_GPT_INFO
{
    MBR_HEAD MBR;
    VTOY_GPT_HDR Head;
    VTOY_GPT_PART_TBL PartTbl[128];
}VTOY_GPT_INFO;
typedef struct VTOY_BK_GPT_INFO
{
    VTOY_GPT_PART_TBL PartTbl[128];
    VTOY_GPT_HDR Head;
}VTOY_BK_GPT_INFO;
COMPILE_ASSERT(sizeof(VTOY_GPT_INFO) == 512 * 34);
COMPILE_ASSERT(sizeof(VTOY_BK_GPT_INFO) == 512 * 33);
#pragma pack()
UINT32 VtoyCrc32(VOID *Buffer, UINT32 Length);
int vtoygpt_main(int argc, char **argv);
int vtoyfat_main(int argc, char **argv);
int partresize_main(int argc, char **argv);
void ventoy_gen_preudo_uuid(void *uuid);
UINT64 get_disk_size_in_byte(const char *disk);
    
#endif /* __VTOYCLI_H__ */
 | 3,289 | 
	C | 
	.c | 113 | 26.115044 | 79 | 0.703845 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 339 | 
	Language.c | 
	ventoy_Ventoy/Ventoy2Disk/Ventoy2Disk/Language.c | 
	/******************************************************************************
 * Language.c
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
 
#include <Windows.h>
#include <versionhelpers.h>
#include "Ventoy2Disk.h"
#include "Language.h"
const TCHAR * GetString(enum STR_ID ID)
{
    if (g_cur_lang_data)
    {
        return g_cur_lang_data->MsgString[ID];
    }
    else
    {
        return NULL;
    }
};
 | 1,112 | 
	C | 
	.c | 34 | 28.794118 | 80 | 0.643989 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 343 | 
	DiskService.h | 
	ventoy_Ventoy/Ventoy2Disk/Ventoy2Disk/DiskService.h | 
	/******************************************************************************
 * DiskService.h
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#ifndef __DISKSERVICE_H__
#define __DISKSERVICE_H__
typedef struct VDS_PARA
{
    UINT64 Attr;
    GUID Type;
    GUID Id;
    WCHAR Name[36];
	ULONG NameLen;
    ULONGLONG Offset;
	CHAR DriveLetter;
    DWORD ClusterSize;
}VDS_PARA;
//DISK API
BOOL DISK_CleanDisk(int DriveIndex);
BOOL DISK_DeleteVtoyEFIPartition(int DriveIndex, UINT64 EfiPartOffset);
BOOL DISK_ChangeVtoyEFIAttr(int DriveIndex, UINT64 Offset, UINT64 Attr);
BOOL DISK_ChangeVtoyEFI2ESP(int DriveIndex, UINT64 Offset);
BOOL DISK_ChangeVtoyEFI2Basic(int DriveIndex, UINT64 Offset);
BOOL DISK_ShrinkVolume(int DriveIndex, const char* VolumeGuid, CHAR DriveLetter, UINT64 OldBytes, UINT64 ReduceBytes);
BOOL DISK_FormatVolume(char DriveLetter, int fs, UINT64 VolumeSize);
//VDS com
BOOL VDS_CleanDisk(int DriveIndex);
BOOL VDS_DeleteAllPartitions(int DriveIndex);
BOOL VDS_DeleteVtoyEFIPartition(int DriveIndex, UINT64 EfiPartOffset);
BOOL VDS_ChangeVtoyEFIAttr(int DriveIndex, UINT64 Offset, UINT64 Attr);
BOOL VDS_ChangeVtoyEFI2ESP(int DriveIndex, UINT64 Offset);
BOOL VDS_ChangeVtoyEFI2Basic(int DriveIndex, UINT64 Offset);
BOOL VDS_ShrinkVolume(int DriveIndex, const char* VolumeGuid, CHAR DriveLetter, UINT64 OldBytes, UINT64 ReduceBytes);
BOOL VDS_IsLastAvaliable(void);
BOOL VDS_FormatVolume(char DriveLetter, int fs, DWORD ClusterSize);
//diskpart.exe
BOOL DSPT_CleanDisk(int DriveIndex);
BOOL DSPT_FormatVolume(char DriveLetter, int fs, DWORD ClusterSize);
BOOL CMD_FormatVolume(char DriveLetter, int fs, DWORD ClusterSize);
//powershell.exe
BOOL PSHELL_CleanDisk(int DriveIndex);
BOOL PSHELL_DeleteVtoyEFIPartition(int DriveIndex, UINT64 EfiPartOffset);
BOOL PSHELL_ChangeVtoyEFI2ESP(int DriveIndex, UINT64 Offset);
BOOL PSHELL_ChangeVtoyEFI2Basic(int DriveIndex, UINT64 Offset);
BOOL PSHELL_ShrinkVolume(int DriveIndex, const char* VolumeGuid, CHAR DriveLetter, UINT64 OldBytes, UINT64 ReduceBytes);
BOOL PSHELL_FormatVolume(char DriveLetter, int fs, DWORD ClusterSize);
const CHAR* DISK_GetWindowsDir(void);
//
// Internel define
//
typedef BOOL(*FormatVolume_PF)(char DriveLetter, int fs, DWORD ClusterSize);
typedef struct FmtFunc
{
    const char* name;
    FormatVolume_PF formatFunc;
}FmtFunc;
#define FMT_DEF(func) { #func, func }
#endif
 | 3,135 | 
	C | 
	.c | 73 | 39.767123 | 121 | 0.759406 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 345 | 
	resource.h | 
	ventoy_Ventoy/Ventoy2Disk/Ventoy2Disk/resource.h | 
	//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ 生成的包含文件。
// 供 Ventoy2Disk.rc 使用
//
#define IDI_ICON1                       109
#define IDD_DIALOG1                     110
#define IDR_MENU1                       111
#define IDD_DIALOG2                     112
#define IDI_ICON2                       115
#define IDI_ICON3                       116
#define IDD_DIALOG3                     117
#define IDI_ICON4                       121
#define IDC_COMBO1                      1001
#define IDC_BUTTON2                     1003
#define IDC_BUTTON3                     1004
#define IDC_BUTTON4                     1005
#define IDC_PROGRESS1                   1006
#define IDC_STATIC_LOCAL_VER            1007
#define IDC_STATIC_DISK_VER             1008
#define IDC_STATIC_DEV                  1009
#define IDC_STATIC_LOCAL                1010
#define IDC_STATIC_DISK                 1011
#define IDC_STATIC_STATUS               1012
#define IDC_CHECK_RESERVE_SPACE         1018
#define IDC_EDIT_RESERVE_SPACE_VAL      1019
#define ID_PART_OK                      1020
#define ID_PART_CANCEL                  1021
#define IDC_COMBO_SPACE_UNIT            1022
#define IDC_COMMAND1                    1024
#define IDC_STATIC_LOCAL_STYLE          1025
#define IDC_STATIC_DEV_STYLE            1026
#define IDC_CHECK_PART_ALIGN_4KB        1027
#define IDC_STATIC_LOCAL_FS             1027
#define IDC_STATIC_DEV_FS               1028
#define IDC_STATIC_LOCAL_SECURE         1032
#define IDC_STATIC_DEV_SECURE           1033
#define IDC_SYSLINK1                    1035
#define IDC_SYSLINK2                    1036
#define IDC_YES_EDIT1                   1037
#define ID_YES_OK                       1038
#define ID_YES_CANCEL                   1039
#define IDC_YES_STATIC1                 1040
#define IDC_YES_STATIC2                 1041
#define ID_YES_STATIC4                  1043
#define IDC_YES_STATIC4                 1043
#define IDC_RADIO1                      1044
#define IDC_RADIO2                      1045
#define IDC_RADIO3                      1046
#define IDC_VENTOY_PART_FS              1047
#define IDC_RADIO4                      1048
#define IDC_COMBO_CLUSTER_SIZE          1049
#define IDC_STATIC_PART_FS              1050
#define IDC_STATIC_PART_FS_TITLE        1050
#define IDC_STATIC_PART_CLUSTER         1051
#define IDC_ICON_LOCAL_SECURE           1052
#define IDC_ICON_LOCAL_SECURE2          1053
#define IDC_ICON_DISK_SECURE            1053
#define IDC_STATIC_PRESERVER_SPACE      1053
#define IDC_STATIC_ALIGN_4KB            1054
#define IDC_STATIC_XX                   1055
#define IDC_STATIC_X4                   1056
#define ID_OPTION_SECUREBOOTSUPPORT     40001
#define ID_LANGUAGE                     40002
#define ID_40003                        40003
#define ID_40004                        40004
#define ID_LANGUAGE_XXX                 40005
#define ID_SECURE_BOOT                  40006
#define ID_40007                        40007
#define ID_40008                        40008
#define ID_40009                        40009
#define ID_40010                        40010
#define ID_40011                        40011
#define ID_PARTSTYLE_MBR                40012
#define ID_PARTSTYLE_GPT                40013
// Next default values for new objects
// 
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE        122
#define _APS_NEXT_COMMAND_VALUE         40014
#define _APS_NEXT_CONTROL_VALUE         1057
#define _APS_NEXT_SYMED_VALUE           101
#endif
#endif
 | 7,234 | 
	C | 
	.c | 84 | 41.011905 | 46 | 0.527762 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 347 | 
	VentoyJson.c | 
	ventoy_Ventoy/Ventoy2Disk/Ventoy2Disk/VentoyJson.c | 
	/******************************************************************************
 * VentoyJson.c
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#ifdef FOR_VTOY_JSON_CHECK
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#else
#include <Windows.h>
#include "Ventoy2Disk.h"
#endif
#include "VentoyJson.h"
static void vtoy_json_free(VTOY_JSON *pstJsonHead)
{
    VTOY_JSON *pstNext = NULL;
    while (NULL != pstJsonHead)
    {
        pstNext = pstJsonHead->pstNext;
        if ((pstJsonHead->enDataType < JSON_TYPE_BUTT) && (NULL != pstJsonHead->pstChild))
        {
            vtoy_json_free(pstJsonHead->pstChild);
        }
        free(pstJsonHead);
        pstJsonHead = pstNext;
    }
    return;
}
static char *vtoy_json_skip(const char *pcData)
{
    while ((NULL != pcData) && ('\0' != *pcData) && (*pcData <= 32))
    {
        pcData++;
    }
    return (char *)pcData;
}
VTOY_JSON *vtoy_json_find_item
(
    VTOY_JSON *pstJson,
    JSON_TYPE  enDataType,
    const char *szKey
)
{
    while (NULL != pstJson)
    {
        if ((enDataType == pstJson->enDataType) && 
            (0 == strcmp(szKey, pstJson->pcName)))
        {
            return pstJson;
        }
        pstJson = pstJson->pstNext;
    }
    
    return NULL;
}
static int vtoy_json_parse_number
(
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    unsigned long Value;
    Value = strtoul(pcData, (char **)ppcEnd, 10);
    if (*ppcEnd == pcData)
    {
        Log("Failed to parse json number %s.", pcData);
        return JSON_FAILED;
    }
    pstJson->enDataType = JSON_TYPE_NUMBER;
    pstJson->unData.lValue = Value;
    
    return JSON_SUCCESS;
}
static int vtoy_json_parse_string
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    UINT32 uiLen = 0;
    const char *pcPos = NULL;
    const char *pcTmp = pcData + 1;
    
    *ppcEnd = pcData;
    if ('\"' != *pcData)
    {
        return JSON_FAILED;
    }
    pcPos = strchr(pcTmp, '\"');
    if ((NULL == pcPos) || (pcPos < pcTmp))
    {
        Log("Invalid string %s.", pcData);
        return JSON_FAILED;
    }
    *ppcEnd = pcPos + 1;
    uiLen = (UINT32)(unsigned long)(pcPos - pcTmp);    
    
    pstJson->enDataType = JSON_TYPE_STRING;
    pstJson->unData.pcStrVal = pcNewStart + (pcTmp - pcRawStart);
    pstJson->unData.pcStrVal[uiLen] = '\0';
    
    return JSON_SUCCESS;
}
static int vtoy_json_parse_array
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    int Ret = JSON_SUCCESS;
    VTOY_JSON *pstJsonChild = NULL;
    VTOY_JSON *pstJsonItem = NULL;
    const char *pcTmp = pcData + 1;
    *ppcEnd = pcData;
    pstJson->enDataType = JSON_TYPE_ARRAY;
    if ('[' != *pcData)
    {
        return JSON_FAILED;
    }
    pcTmp = vtoy_json_skip(pcTmp);
    if (']' == *pcTmp)
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    JSON_NEW_ITEM(pstJson->pstChild, JSON_FAILED);
    Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJson->pstChild, pcTmp, ppcEnd);
    if (JSON_SUCCESS != Ret)
    {
        Log("Failed to parse array child.");
        return JSON_FAILED;
    }
    pstJsonChild = pstJson->pstChild;
    pcTmp = vtoy_json_skip(*ppcEnd);
    while ((NULL != pcTmp) && (',' == *pcTmp))
    {
        JSON_NEW_ITEM(pstJsonItem, JSON_FAILED);
        pstJsonChild->pstNext = pstJsonItem;
        pstJsonItem->pstPrev = pstJsonChild;
        pstJsonChild = pstJsonItem;
        Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
        if (JSON_SUCCESS != Ret)
        {
            Log("Failed to parse array child.");
            return JSON_FAILED;
        }
        pcTmp = vtoy_json_skip(*ppcEnd);
    }
    if ((NULL != pcTmp) && (']' == *pcTmp))
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    else
    {
        *ppcEnd = pcTmp;
        return JSON_FAILED;
    }
}
static int vtoy_json_parse_object
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    int Ret = JSON_SUCCESS;
    VTOY_JSON *pstJsonChild = NULL;
    VTOY_JSON *pstJsonItem = NULL;
    const char *pcTmp = pcData + 1;
    *ppcEnd = pcData;
    pstJson->enDataType = JSON_TYPE_OBJECT;
    if ('{' != *pcData)
    {
        return JSON_FAILED;
    }
    pcTmp = vtoy_json_skip(pcTmp);
    if ('}' == *pcTmp)
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    JSON_NEW_ITEM(pstJson->pstChild, JSON_FAILED);
    Ret = vtoy_json_parse_string(pcNewStart, pcRawStart, pstJson->pstChild, pcTmp, ppcEnd);
    if (JSON_SUCCESS != Ret)
    {
        Log("Failed to parse array child.");
        return JSON_FAILED;
    }
    pstJsonChild = pstJson->pstChild;
    pstJsonChild->pcName = pstJsonChild->unData.pcStrVal;
    pstJsonChild->unData.pcStrVal = NULL;
    pcTmp = vtoy_json_skip(*ppcEnd);
    if ((NULL == pcTmp) || (':' != *pcTmp))
    {
        *ppcEnd = pcTmp;
        return JSON_FAILED;
    }
    Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
    if (JSON_SUCCESS != Ret)
    {
        Log("Failed to parse array child.");
        return JSON_FAILED;
    }
    pcTmp = vtoy_json_skip(*ppcEnd);
    while ((NULL != pcTmp) && (',' == *pcTmp))
    {
        JSON_NEW_ITEM(pstJsonItem, JSON_FAILED);
        pstJsonChild->pstNext = pstJsonItem;
        pstJsonItem->pstPrev = pstJsonChild;
        pstJsonChild = pstJsonItem;
        Ret = vtoy_json_parse_string(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
        if (JSON_SUCCESS != Ret)
        {
            Log("Failed to parse array child.");
            return JSON_FAILED;
        }
        pcTmp = vtoy_json_skip(*ppcEnd);
        pstJsonChild->pcName = pstJsonChild->unData.pcStrVal;
        pstJsonChild->unData.pcStrVal = NULL;
        if ((NULL == pcTmp) || (':' != *pcTmp))
        {
            *ppcEnd = pcTmp;
            return JSON_FAILED;
        }
        Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
        if (JSON_SUCCESS != Ret)
        {
            Log("Failed to parse array child.");
            return JSON_FAILED;
        }
        pcTmp = vtoy_json_skip(*ppcEnd);
    }
    if ((NULL != pcTmp) && ('}' == *pcTmp))
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    else
    {
        *ppcEnd = pcTmp;
        return JSON_FAILED;
    }
}
int vtoy_json_parse_value
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    pcData = vtoy_json_skip(pcData);
    
    switch (*pcData)
    {
        case 'n':
        {
            if (0 == strncmp(pcData, "null", 4))
            {
                pstJson->enDataType = JSON_TYPE_NULL;
                *ppcEnd = pcData + 4;
                return JSON_SUCCESS;
            }
            break;
        }
        case 'f':
        {
            if (0 == strncmp(pcData, "false", 5))
            {
                pstJson->enDataType = JSON_TYPE_BOOL;
                pstJson->unData.lValue = 0;
                *ppcEnd = pcData + 5;
                return JSON_SUCCESS;
            }
            break;
        }
        case 't':
        {
            if (0 == strncmp(pcData, "true", 4))
            {
                pstJson->enDataType = JSON_TYPE_BOOL;
                pstJson->unData.lValue = 1;
                *ppcEnd = pcData + 4;
                return JSON_SUCCESS;
            }
            break;
        }
        case '\"':
        {
            return vtoy_json_parse_string(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
        }
        case '[':
        {
            return vtoy_json_parse_array(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
        }
        case '{':
        {
            return vtoy_json_parse_object(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
        }
        case '-':
        {
            return vtoy_json_parse_number(pstJson, pcData, ppcEnd);
        }
        default :
        {
            if (*pcData >= '0' && *pcData <= '9')
            {
                return vtoy_json_parse_number(pstJson, pcData, ppcEnd);
            }
        }
    }
    *ppcEnd = pcData;
    Log("Invalid json data %u.", (UINT8)(*pcData));
    return JSON_FAILED;
}
VTOY_JSON * vtoy_json_create(void)
{
    VTOY_JSON *pstJson = NULL;
    pstJson = (VTOY_JSON *)malloc(sizeof(VTOY_JSON));
    if (NULL == pstJson)
    {
        return NULL;
    }
    memset(pstJson, 0, sizeof(VTOY_JSON));
    return pstJson;
}
int vtoy_json_parse(VTOY_JSON *pstJson, const char *szJsonData)
{
    UINT32 uiMemSize = 0;
    int Ret = JSON_SUCCESS;
    char *pcNewBuf = NULL;
    const char *pcEnd = NULL;
	uiMemSize = (UINT32)strlen(szJsonData) + 1;
    pcNewBuf = (char *)malloc(uiMemSize);
    if (NULL == pcNewBuf)
    {
        Log("Failed to alloc new buf.");
        return JSON_FAILED;
    }
    memcpy(pcNewBuf, szJsonData, uiMemSize);
    pcNewBuf[uiMemSize - 1] = 0;
    Ret = vtoy_json_parse_value(pcNewBuf, (char *)szJsonData, pstJson, szJsonData, &pcEnd);
    if (JSON_SUCCESS != Ret)
    {
        Log("Failed to parse json data start=%p, end=%p", szJsonData, pcEnd);
        return JSON_FAILED;
    }
    return JSON_SUCCESS;
}
int vtoy_json_scan_parse
(
    const VTOY_JSON    *pstJson,
    UINT32       uiParseNum,
    JSON_PARSE         *pstJsonParse
)
{   
    UINT32 i = 0;
    const VTOY_JSON *pstJsonCur = NULL;
    JSON_PARSE *pstCurParse = NULL;
    for (pstJsonCur = pstJson; NULL != pstJsonCur; pstJsonCur = pstJsonCur->pstNext)
    {
        if ((JSON_TYPE_OBJECT == pstJsonCur->enDataType) ||
            (JSON_TYPE_ARRAY == pstJsonCur->enDataType))
        {
            continue;
        }
        for (i = 0, pstCurParse = NULL; i < uiParseNum; i++)
        {
            if (0 == strcmp(pstJsonParse[i].pcKey, pstJsonCur->pcName))
            {   
                pstCurParse = pstJsonParse + i;
                break;
            }
        }
        if (NULL == pstCurParse)
        {
            continue;
        }
    
        switch (pstJsonCur->enDataType)
        {
            case JSON_TYPE_NUMBER:
            {
                if (sizeof(UINT32) == pstCurParse->uiBufSize)
                {
                    *(UINT32 *)(pstCurParse->pDataBuf) = (UINT32)pstJsonCur->unData.lValue;
                }
                else if (sizeof(UINT16) == pstCurParse->uiBufSize)
                {
                    *(UINT16 *)(pstCurParse->pDataBuf) = (UINT16)pstJsonCur->unData.lValue;
                }
                else if (sizeof(UINT8) == pstCurParse->uiBufSize)
                {
                    *(UINT8 *)(pstCurParse->pDataBuf) = (UINT8)pstJsonCur->unData.lValue;
                }
                else if ((pstCurParse->uiBufSize > sizeof(UINT64)))
                {
                    sprintf_s((char *)pstCurParse->pDataBuf, pstCurParse->uiBufSize, "%llu",
                        (unsigned long long)(pstJsonCur->unData.lValue));
                }
                else
                {
                    Log("Invalid number data buf size %u.", pstCurParse->uiBufSize);
                }
                break;
            }
            case JSON_TYPE_STRING:
            {
                strcpy_s((char *)pstCurParse->pDataBuf, pstCurParse->uiBufSize, pstJsonCur->unData.pcStrVal);
                break;
            }
            case JSON_TYPE_BOOL:
            {
                *(UINT8 *)(pstCurParse->pDataBuf) = (pstJsonCur->unData.lValue) > 0 ? 1 : 0;
                break;
            }
            default :
            {
                break;
            }
        }
    }
    return JSON_SUCCESS;
}
int vtoy_json_scan_array
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     VTOY_JSON **ppstArrayItem
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_ARRAY, szKey);
    if (NULL == pstJsonItem)
    {
        Log("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *ppstArrayItem = pstJsonItem;
    return JSON_SUCCESS;
}
int vtoy_json_scan_array_ex
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     VTOY_JSON **ppstArrayItem
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_ARRAY, szKey);
    if (NULL == pstJsonItem)
    {
        Log("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    
    *ppstArrayItem = pstJsonItem->pstChild;
    return JSON_SUCCESS;
}
int vtoy_json_scan_object
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     VTOY_JSON **ppstObjectItem
)
{
    VTOY_JSON *pstJsonItem = NULL;
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_OBJECT, szKey);
    if (NULL == pstJsonItem)
    {
        Log("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *ppstObjectItem = pstJsonItem;
    return JSON_SUCCESS;
}
int vtoy_json_get_int
(
    VTOY_JSON *pstJson, 
    const char *szKey, 
    int *piValue
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
    if (NULL == pstJsonItem)
    {
        Log("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *piValue = (int)pstJsonItem->unData.lValue;
    return JSON_SUCCESS;
}
int vtoy_json_get_uint
(
    VTOY_JSON *pstJson, 
    const char *szKey, 
    UINT32 *puiValue
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
    if (NULL == pstJsonItem)
    {
        Log("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *puiValue = (UINT32)pstJsonItem->unData.lValue;
    return JSON_SUCCESS;
}
int vtoy_json_get_uint64
(
    VTOY_JSON *pstJson, 
    const char *szKey, 
    UINT64 *pui64Value
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
    if (NULL == pstJsonItem)
    {
        Log("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *pui64Value = (UINT64)pstJsonItem->unData.lValue;
    return JSON_SUCCESS;
}
int vtoy_json_get_bool
(
    VTOY_JSON *pstJson,
    const char *szKey, 
    UINT8 *pbValue
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_BOOL, szKey);
    if (NULL == pstJsonItem)
    {
        Log("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *pbValue = pstJsonItem->unData.lValue > 0 ? 1 : 0;
    return JSON_SUCCESS;
}
int vtoy_json_get_string
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     UINT32  uiBufLen,
     char *pcBuf
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_STRING, szKey);
    if (NULL == pstJsonItem)
    {
        Log("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    strcpy_s(pcBuf, uiBufLen, pstJsonItem->unData.pcStrVal);
    return JSON_SUCCESS;
}
const char * vtoy_json_get_string_ex(VTOY_JSON *pstJson,  const char *szKey)
{
    VTOY_JSON *pstJsonItem = NULL;
    if ((NULL == pstJson) || (NULL == szKey))
    {
        return NULL;
    }
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_STRING, szKey);
    if (NULL == pstJsonItem)
    {
        Log("Key %s is not found in json data.", szKey);
        return NULL;
    }
    return pstJsonItem->unData.pcStrVal;
}
int vtoy_json_destroy(VTOY_JSON *pstJson)
{
    if (NULL == pstJson)
    {   
        return JSON_SUCCESS;
    }
    if (NULL != pstJson->pstChild)
    {
        vtoy_json_free(pstJson->pstChild);
    }
    if (NULL != pstJson->pstNext)
    {
        vtoy_json_free(pstJson->pstNext);
    }
    free(pstJson);
    
    return JSON_SUCCESS;
}
#ifdef FOR_VTOY_JSON_CHECK
int main(int argc, char**argv)
{
    int ret = 1;
    int FileSize;
    FILE *fp;
    void *Data = NULL;
    VTOY_JSON *json = NULL;
    fp = fopen(argv[1], "rb");
    if (!fp)
    {
        Log("Failed to open %s\n", argv[1]);
        goto out;
    }
    fseek(fp, 0, SEEK_END);
    FileSize = (int)ftell(fp);
    fseek(fp, 0, SEEK_SET);
    Data = malloc(FileSize + 4);
    if (!Data)
    {
        Log("Failed to malloc %d\n", FileSize + 4);
        goto out;
    }
    *((char *)Data + FileSize) = 0;
    fread(Data, 1, FileSize, fp);
    json = vtoy_json_create();
    if (!json)
    {
        Log("Failed vtoy_json_create\n");
        goto out;
    }
    if (vtoy_json_parse(json, (char *)Data) != JSON_SUCCESS)
    {
        goto out;
    }
    ret = 0;
out:
    if (fp) fclose(fp);
    if (Data) free(Data);
    if (json) vtoy_json_destroy(json);
    printf("\n");
    return ret;
}
#endif
 | 18,505 | 
	C | 
	.c | 656 | 20.230183 | 111 | 0.550043 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 351 | 
	diskio.c | 
	ventoy_Ventoy/Ventoy2Disk/Ventoy2Disk/ff14/source/diskio.c | 
	/*-----------------------------------------------------------------------*/
/* Low level disk I/O module skeleton for FatFs     (C)ChaN, 2019        */
/*-----------------------------------------------------------------------*/
/* If a working storage control module is available, it should be        */
/* attached to the FatFs via a glue function rather than modifying it.   */
/* This is an example of glue functions to attach various exsisting      */
/* storage control modules to the FatFs module with a defined API.       */
/*-----------------------------------------------------------------------*/
#include <Windows.h>
#include "ff.h"			/* Obtains integer types */
#include "diskio.h"		/* Declarations of disk functions */
#include "../Ventoy2Disk.h"
/* Definitions of physical drive number for each drive */
#define DEV_RAM		0	/* Example: Map Ramdisk to physical drive 0 */
#define DEV_MMC		1	/* Example: Map MMC/SD card to physical drive 1 */
#define DEV_USB		2	/* Example: Map USB MSD to physical drive 2 */
void Log(const char *fmt, ...);
static UINT8 g_MbrSector[512];
HANDLE g_hPhyDrive;
UINT64 g_SectorCount;
FILE *g_VentoyImgFp = NULL;
VTSI_SEGMENT *g_VentoySegment = NULL;
int g_VentoyMaxSeg = 0;
int g_VentoyCurSeg = -1;
UINT64 g_VentoyDataOffset = 0;
int g_write_error = 0;
int g_error_print_cnt = 0;
void disk_io_reset_write_error(void)
{
	g_write_error = 0;
	g_error_print_cnt = 0;
}
int disk_io_is_write_error(void)
{
	return g_write_error;
}
void disk_io_set_param(HANDLE Handle, UINT64 SectorCount)
{
    g_hPhyDrive = Handle;
    g_SectorCount = SectorCount;
}
void disk_io_set_imghook(FILE *fp, VTSI_SEGMENT *segment, int maxseg, UINT64 data_offset)
{
    g_VentoyImgFp = fp;
    g_VentoySegment = segment;
    g_VentoyMaxSeg = maxseg;
    memset(segment, 0, maxseg * sizeof(VTSI_SEGMENT));
    g_VentoyCurSeg = -1;
    g_VentoyDataOffset = data_offset;
}
void disk_io_reset_imghook(int *psegnum, UINT64 *pDataOffset)
{
    *psegnum = g_VentoyCurSeg + 1;
    *pDataOffset = g_VentoyDataOffset;
    g_VentoyImgFp = NULL;
    g_VentoySegment = NULL;
    g_VentoyMaxSeg = 0;
    g_VentoyCurSeg = -1;
    g_VentoyDataOffset = 0;
}
/*-----------------------------------------------------------------------*/
/* Get Drive Status                                                      */
/*-----------------------------------------------------------------------*/
DSTATUS disk_status (
	BYTE pdrv		/* Physical drive nmuber to identify the drive */
)
{
    return RES_OK;
#if 0
	DSTATUS stat;
	int result;
	switch (pdrv) {
	case DEV_RAM :
		result = RAM_disk_status();
		// translate the reslut code here
		return stat;
	case DEV_MMC :
		result = MMC_disk_status();
		// translate the reslut code here
		return stat;
	case DEV_USB :
		result = USB_disk_status();
		// translate the reslut code here
		return stat;
	}
	return STA_NOINIT;
#endif
}
/*-----------------------------------------------------------------------*/
/* Inidialize a Drive                                                    */
/*-----------------------------------------------------------------------*/
DSTATUS disk_initialize (
	BYTE pdrv				/* Physical drive nmuber to identify the drive */
)
{
    return RES_OK;
#if 0
	DSTATUS stat;
	int result;
	switch (pdrv) {
	case DEV_RAM :
		result = RAM_disk_initialize();
		// translate the reslut code here
		return stat;
	case DEV_MMC :
		result = MMC_disk_initialize();
		// translate the reslut code here
		return stat;
	case DEV_USB :
		result = USB_disk_initialize();
		// translate the reslut code here
		return stat;
	}
	return STA_NOINIT;
#endif
}
/*-----------------------------------------------------------------------*/
/* Read Sector(s)                                                        */
/*-----------------------------------------------------------------------*/
DRESULT disk_read (
	BYTE pdrv,		/* Physical drive nmuber to identify the drive */
	BYTE *buff,		/* Data buffer to store read data */
	LBA_t sector,	/* Start sector in LBA */
	UINT count		/* Number of sectors to read */
)
{
    DWORD dwSize;
    BOOL bRet;
    LARGE_INTEGER liCurrentPosition;
    //Log("xxx disk_read: sector:%ld count:%ld", (long)sector, (long)count);
    if (g_VentoyImgFp)
    {
        return RES_OK;
    }
    liCurrentPosition.QuadPart = sector * 512;
    SetFilePointerEx(g_hPhyDrive, liCurrentPosition, &liCurrentPosition, FILE_BEGIN);
    bRet = ReadFile(g_hPhyDrive, buff, count * 512, &dwSize, NULL);
    if (dwSize != count * 512)
    {
        Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u", bRet, count * 512, dwSize, GetLastError());
    }
    if (sector == 0)
    {
        memcpy(buff, g_MbrSector, sizeof(g_MbrSector));
    }
    return RES_OK;
}
/*-----------------------------------------------------------------------*/
/* Write Sector(s)                                                       */
/*-----------------------------------------------------------------------*/
#if FF_FS_READONLY == 0
DRESULT disk_write (
	BYTE pdrv,			/* Physical drive nmuber to identify the drive */
	const BYTE *buff,	/* Data to be written */
	LBA_t sector,		/* Start sector in LBA */
	UINT count			/* Number of sectors to write */
)
{
    DWORD dwSize;
    BOOL bRet;
    LARGE_INTEGER liCurrentPosition;
    VTSI_SEGMENT *CurSeg = NULL;
    //Log("==== disk_write: sector:%ld count:%ld", (long)sector, (long)count);
    // skip MBR
    if (sector == 0)
    {
        memcpy(g_MbrSector, buff, sizeof(g_MbrSector));
        if (count == 1)
        {
            return RES_OK;
        }
        sector++;
        count--;
    }
    if (g_VentoyImgFp)
    {
        CurSeg = g_VentoySegment + g_VentoyCurSeg;
        if (g_VentoyCurSeg >= 0 && CurSeg->sector_num > 0 && sector == CurSeg->disk_start_sector + CurSeg->sector_num)
        {
            CurSeg->sector_num += count; //merge
        }
        else
        {
            g_VentoyCurSeg++;
            CurSeg++;
            CurSeg->disk_start_sector = sector;
            CurSeg->data_offset = g_VentoyDataOffset;
            CurSeg->sector_num = count;
        }
        g_VentoyDataOffset += count * 512;
        fwrite(buff, 1, count * 512, g_VentoyImgFp);
        return RES_OK;
    }
    liCurrentPosition.QuadPart = sector * 512;
    SetFilePointerEx(g_hPhyDrive, liCurrentPosition, &liCurrentPosition, FILE_BEGIN);
    bRet = WriteFile(g_hPhyDrive, buff, count * 512, &dwSize, NULL);
    if ((!bRet) || (dwSize != count * 512))
    {
		g_write_error = 1;
		g_error_print_cnt++;
		if (g_error_print_cnt <= 10)
		{
			Log("WriteFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u", bRet, count * 512, dwSize, GetLastError());
		}
    }
    return RES_OK;
}
#endif
/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions                                               */
/*-----------------------------------------------------------------------*/
DRESULT disk_ioctl (
	BYTE pdrv,		/* Physical drive nmuber (0..) */
	BYTE cmd,		/* Control code */
	void *buff		/* Buffer to send/receive control data */
)
{
    switch (cmd)
    {
        case CTRL_SYNC:
        {
            //FILE_FLAG_NO_BUFFERING & FILE_FLAG_WRITE_THROUGH was set, no need to sync
            break;
        }
        case GET_SECTOR_COUNT:
        {
            *(LBA_t *)buff = g_SectorCount;
            break;
        }
        case GET_SECTOR_SIZE:
        {
            *(WORD *)buff = 512;
            break;
        }
        case GET_BLOCK_SIZE:
        {
            *(DWORD *)buff = 8;
            break;
        }
    }
    return RES_OK;
#if 0
	DRESULT res;
	int result;
	switch (pdrv) {
	case DEV_RAM :
		// Process of the command for the RAM drive
		return res;
	case DEV_MMC :
		// Process of the command for the MMC/SD card
		return res;
	case DEV_USB :
		// Process of the command the USB drive
		return res;
	}
	return RES_PARERR;
#endif
}
 | 7,982 | 
	C | 
	.c | 258 | 26.666667 | 118 | 0.537908 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 446 | 
	main_linux.c | 
	ventoy_Ventoy/Plugson/src/main_linux.c | 
	#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <linux/limits.h>
#include <ventoy_define.h>
#include <ventoy_util.h>
#include <ventoy_json.h>
#include <ventoy_disk.h>
#include <ventoy_http.h>
char g_log_file[MAX_PATH];
char g_cur_dir[MAX_PATH];
char g_ventoy_dir[MAX_PATH];
int ventoy_log_init(void);
void ventoy_log_exit(void);
void ventoy_signal_stop(int sig)
{
    vlog("ventoy server exit due to signal ...\n");
    printf("ventoy server exit ...\n");
    
    ventoy_http_stop();
    ventoy_http_exit();
#ifndef VENTOY_SIM    
    ventoy_www_exit();
#endif
    ventoy_disk_exit();
    ventoy_log_exit();
    exit(0);
}
int main(int argc, char **argv)
{
    int rc;
    const char *ip = "127.0.0.1";
    const char *port = "24681";
    if (argc != 9)
    {
        printf("Invalid argc %d\n", argc);
        return 1;
    }
    if (isdigit(argv[1][0]))
    {
        ip = argv[1];
    }
    
    if (isdigit(argv[2][0]))
    {
        port = argv[2];
    }
    strlcpy(g_ventoy_dir, argv[3]);
    scnprintf(g_log_file, sizeof(g_log_file), "%s/%s", g_ventoy_dir, LOG_FILE);
    ventoy_log_init();
    getcwd(g_cur_dir, MAX_PATH);
    if (!ventoy_is_directory_exist("./ventoy"))
    {
        printf("%s/ventoy directory does not exist\n", g_cur_dir);
        return 1;
    }
    ventoy_get_disk_info(argv);    
    vlog("===============================================\n");
    vlog("===== Ventoy Plugson %s:%s =====\n", ip, port);
    vlog("===============================================\n");
    ventoy_disk_init();
#ifndef VENTOY_SIM
    rc = ventoy_www_init();
    if (rc)
	{
		printf("Failed to init web data, check log for details.\n");
		ventoy_disk_exit();
		ventoy_log_exit();
		return 1;
	}
#endif
    ventoy_http_init();
    
    rc = ventoy_http_start(ip, port);
    if (rc)
    {
        printf("Ventoy failed to start http server, check ./ventoy/plugson.log for detail\n");
    }
    else
    {
        signal(SIGINT, ventoy_signal_stop);
        signal(SIGTSTP, ventoy_signal_stop);
        signal(SIGQUIT, ventoy_signal_stop);
        while (1)
        {
            sleep(100);
        }
    }
    
    return 0;
}
 | 2,333 | 
	C | 
	.c | 95 | 19.989474 | 94 | 0.577324 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 447 | 
	ventoy_http.c | 
	ventoy_Ventoy/Plugson/src/Web/ventoy_http.c | 
	/******************************************************************************
 * ventoy_http.c  ---- ventoy http
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <stddef.h>
#include <errno.h>
#include <time.h>
#if defined(_MSC_VER) || defined(WIN32)
#else
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <linux/fs.h>
#include <linux/limits.h>
#include <dirent.h>
#include <pthread.h>
#endif
#include <ventoy_define.h>
#include <ventoy_json.h>
#include <ventoy_util.h>
#include <ventoy_disk.h>
#include <ventoy_http.h>
#include "fat_filelib.h"
static const char *g_json_title_postfix[bios_max + 1] = 
{
    "", "_legacy", "_uefi", "_ia32", "_aa64", "_mips", ""
};
static const char *g_ventoy_kbd_layout[] =
{
    "QWERTY_USA", "AZERTY", "CZECH_QWERTY", "CZECH_QWERTZ", "DANISH", 
    "DVORAK_USA", "FRENCH", "GERMAN", "ITALIANO", "JAPAN_106", "LATIN_USA", 
    "PORTU_BRAZIL", "QWERTY_UK", "QWERTZ", "QWERTZ_HUN", "QWERTZ_SLOV_CROAT", 
    "SPANISH", "SWEDISH", "TURKISH_Q", "VIETNAMESE",
    NULL
};
#define VTOY_DEL_ALL_PATH   "4119ae33-98ea-448e-b9c0-569aafcf1fb4"
static int g_json_exist[plugin_type_max][bios_max];
static const char *g_plugin_name[plugin_type_max] = 
{
    "control", "theme", "menu_alias", "menu_tip", 
    "menu_class", "auto_install", "persistence", "injection", 
    "conf_replace", "password", "image_list", 
    "auto_memdisk", "dud"
};
static char g_ventoy_menu_lang[MAX_LANGUAGE][8];
static char g_pub_path[2 * MAX_PATH];
static data_control g_data_control[bios_max + 1];
static data_theme g_data_theme[bios_max + 1];
static data_alias g_data_menu_alias[bios_max + 1];
static data_tip   g_data_menu_tip[bios_max + 1];
static data_class g_data_menu_class[bios_max + 1];
static data_image_list g_data_image_list[bios_max + 1];
static data_image_list *g_data_image_blacklist = g_data_image_list;
static data_auto_memdisk g_data_auto_memdisk[bios_max + 1];
static data_password g_data_password[bios_max + 1];
static data_conf_replace g_data_conf_replace[bios_max + 1];
static data_injection g_data_injection[bios_max + 1];
static data_auto_install g_data_auto_install[bios_max + 1];
static data_persistence g_data_persistence[bios_max + 1];
static data_dud g_data_dud[bios_max + 1];
static char *g_pub_json_buffer = NULL;
static char *g_pub_save_buffer = NULL;
#define JSON_BUFFER g_pub_json_buffer
#define JSON_SAVE_BUFFER g_pub_save_buffer
static pthread_mutex_t g_api_mutex;
static struct mg_context *g_ventoy_http_ctx = NULL;
#define ventoy_is_real_exist_common(xpath, xnode, xtype) \
    ventoy_path_is_real_exist(xpath, xnode, offsetof(xtype, path), offsetof(xtype, next))
static int ventoy_is_kbd_valid(const char *key)
{
    int i = 0;
    
    for (i = 0; g_ventoy_kbd_layout[i]; i++)
    {
        if (strcmp(g_ventoy_kbd_layout[i], key) == 0)
        {
            return 1;
        }
    }
    return 0;
}
static const char * ventoy_real_path(const char *org)
{
    int count = 0;
    
    if (g_sysinfo.pathcase)
    {
        scnprintf(g_pub_path, MAX_PATH, "%s", org);
        count = ventoy_path_case(g_pub_path + 1, 1);
        if (count > 0)
        {
            return g_pub_path;
        }
        return org;
    }
    else
    {
        return org;
    }
}
static int ventoy_json_result(struct mg_connection *conn, const char *err)
{
    mg_printf(conn, 
              "HTTP/1.1 200 OK \r\n"
              "Content-Type: application/json\r\n"
              "Content-Length: %d\r\n"
              "\r\n%s",
              (int)strlen(err), err);
    return 0;
}
static int ventoy_json_buffer(struct mg_connection *conn, const char *json_buf, int json_len)
{
    mg_printf(conn, 
              "HTTP/1.1 200 OK \r\n"
              "Content-Type: application/json\r\n"
              "Content-Length: %d\r\n"
              "\r\n%s",
              json_len, json_buf); 
    return 0;
}
static void ventoy_free_path_node_list(path_node *list)
{
    path_node *next = NULL;
    path_node *node = list;
    while (node)
    {
        next = node->next;
        free(node);
        node = next;
    }    
}
static int ventoy_path_is_real_exist(const char *path, void *head, size_t pathoff, size_t nextoff)
{
    char *node = NULL;
    const char *nodepath = NULL;
    const char *realpath = NULL;
    char pathbuf[MAX_PATH];
    if (strchr(path, '*'))
    {
        return 0;
    }
    realpath = ventoy_real_path(path);
    scnprintf(pathbuf, sizeof(pathbuf), "%s", realpath);
    node = (char *)head;
    while (node)
    {
        nodepath = node + pathoff;
        if (NULL == strchr(nodepath, '*'))
        {
            realpath = ventoy_real_path(nodepath);
            if (strcmp(pathbuf, realpath) == 0)
            {
                return 1;
            }
        }
        
        memcpy(&node, node + nextoff, sizeof(node));
    }
    return 0;
}
static path_node * ventoy_path_node_add_array(VTOY_JSON *array)
{
    path_node *head = NULL;
    path_node *node = NULL;
    path_node *cur = NULL;
    VTOY_JSON *item = NULL;
    for (item = array->pstChild; item; item = item->pstNext)
    {
        node = zalloc(sizeof(path_node));
        if (node)
        {                      
            scnprintf(node->path, sizeof(node->path), "%s", item->unData.pcStrVal);
            vtoy_list_add(head, cur, node);
        }
    }
    return head;
}
static int ventoy_check_fuzzy_path(char *path, int prefix)
{
    int rc;
    char c;
    char *cur = NULL;
    char *pos = NULL;
    
    if (!path)
    {
        return 0;
    }
    pos = strchr(path, '*');
    if (pos)
    {
        for (cur = pos; *cur; cur++)
        {
            if (*cur == '/')
            {
                return 0;
            }
        }
    
        while (pos != path)
        {
            if (*pos == '/')
            {
                break;
            }
            pos--;
        }
        if (*pos == '/')
        {
            if (pos != path)
            {
                c = *pos;
                *pos = 0;
                if (prefix)
                {
                    rc = ventoy_is_directory_exist("%s%s", g_cur_dir, path);
                }
                else
                {
                    rc = ventoy_is_directory_exist("%s", path);
                }
                *pos = c;
                if (rc == 0)
                {
                    return 0;
                }
            }
            return -1;
        }
        else
        {
            return 0;
        }
    }
    else
    {
        if (prefix)
        {
            return ventoy_is_file_exist("%s%s", g_cur_dir, path);                        
        }
        else
        {
            return ventoy_is_file_exist("%s", path);            
        }
    }
}
static int ventoy_path_list_cmp(path_node *list1, path_node *list2)
{
    if (NULL == list1 && NULL == list2)
    {
        return 0;
    }
    else if (list1 && list2)
    {
        while (list1 && list2)
        {
            if (strcmp(list1->path, list2->path))
            {
                return 1;
            }
        
            list1 = list1->next;
            list2 = list2->next;
        }
        if (list1 == NULL && list2 == NULL)
        {
            return 0;
        }
        return 1;
    }
    else
    {
        return 1;
    }
}
static int ventoy_api_device_info(struct mg_connection *conn, VTOY_JSON *json)
{
    int pos = 0;
    
    (void)json;
    VTOY_JSON_FMT_BEGIN(pos, JSON_BUFFER, JSON_BUF_MAX);
    VTOY_JSON_FMT_OBJ_BEGIN();
    
    VTOY_JSON_FMT_STRN("dev_name", g_sysinfo.cur_model);
    VTOY_JSON_FMT_STRN("dev_capacity", g_sysinfo.cur_capacity);
    VTOY_JSON_FMT_STRN("dev_fs", g_sysinfo.cur_fsname);
    VTOY_JSON_FMT_STRN("ventoy_ver", g_sysinfo.cur_ventoy_ver);
    VTOY_JSON_FMT_SINT("part_style", g_sysinfo.cur_part_style);
    VTOY_JSON_FMT_SINT("secure_boot", g_sysinfo.cur_secureboot);
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    ventoy_json_buffer(conn, JSON_BUFFER, pos);
    return 0;
}
static int ventoy_api_sysinfo(struct mg_connection *conn, VTOY_JSON *json)
{
    int pos = 0;
    
    (void)json;
    VTOY_JSON_FMT_BEGIN(pos, JSON_BUFFER, JSON_BUF_MAX);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_STRN("language", ventoy_get_os_language());
    VTOY_JSON_FMT_STRN("curdir", g_cur_dir);
    //read clear
    VTOY_JSON_FMT_SINT("syntax_error", g_sysinfo.syntax_error);
    g_sysinfo.syntax_error = 0;
    
    VTOY_JSON_FMT_SINT("invalid_config", g_sysinfo.invalid_config);
    g_sysinfo.invalid_config = 0;
    
    #if defined(_MSC_VER) || defined(WIN32)
    VTOY_JSON_FMT_STRN("os", "windows");
    #else
    VTOY_JSON_FMT_STRN("os", "linux");
    #endif
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    ventoy_json_buffer(conn, JSON_BUFFER, pos);
    return 0;
}
static int ventoy_api_handshake(struct mg_connection *conn, VTOY_JSON *json)
{
    int i = 0;
    int j = 0;
    int pos = 0;
    char key[128];
    
    (void)json;
    VTOY_JSON_FMT_BEGIN(pos, JSON_BUFFER, JSON_BUF_MAX);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_SINT("status", 0);
    VTOY_JSON_FMT_SINT("save_error", g_sysinfo.config_save_error);
    g_sysinfo.config_save_error = 0;
    for (i = 0; i < plugin_type_max; i++)
    {
        scnprintf(key, sizeof(key), "exist_%s", g_plugin_name[i]);
        VTOY_JSON_FMT_KEY(key);
        VTOY_JSON_FMT_ARY_BEGIN();
        for (j = 0; j < bios_max; j++)
        {
            VTOY_JSON_FMT_ITEM_INT(g_json_exist[i][j]);
        }
        VTOY_JSON_FMT_ARY_ENDEX();
    }
    
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    ventoy_json_buffer(conn, JSON_BUFFER, pos);
    return 0;
}
static int ventoy_api_check_exist(struct mg_connection *conn, VTOY_JSON *json)
{
    int dir = 0;
    int pos = 0;
    int exist = 0;
    const char *path = NULL;
    path = vtoy_json_get_string_ex(json, "path");
    vtoy_json_get_int(json, "dir", &dir);
    if (path)
    {
        if (dir)
        {
            exist = ventoy_is_directory_exist("%s", path);
        }
        else
        {
            exist = ventoy_is_file_exist("%s", path);
        }
    }
    VTOY_JSON_FMT_BEGIN(pos, JSON_BUFFER, JSON_BUF_MAX);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_SINT("exist", exist);
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    ventoy_json_buffer(conn, JSON_BUFFER, pos);
    return 0;
}
static int ventoy_api_check_exist2(struct mg_connection *conn, VTOY_JSON *json)
{
    int dir1 = 0;
    int dir2 = 0;
    int fuzzy1 = 0;
    int fuzzy2 = 0;
    int pos = 0;
    int exist1 = 0;
    int exist2 = 0;
    const char *path1 = NULL;
    const char *path2 = NULL;
    path1 = vtoy_json_get_string_ex(json, "path1");
    path2 = vtoy_json_get_string_ex(json, "path2");
    vtoy_json_get_int(json, "dir1", &dir1);
    vtoy_json_get_int(json, "dir2", &dir2);
    vtoy_json_get_int(json, "fuzzy1", &fuzzy1);
    vtoy_json_get_int(json, "fuzzy2", &fuzzy2);
    if (path1)
    {
        if (dir1)
        {
            exist1 = ventoy_is_directory_exist("%s", path1);
        }
        else
        {
            if (fuzzy1)
            {
                exist1 = ventoy_check_fuzzy_path((char *)path1, 0);                
            }
            else
            {
                exist1 = ventoy_is_file_exist("%s", path1);
            }
        }
    }
    
    if (path2)
    {
        if (dir2)
        {
            exist2 = ventoy_is_directory_exist("%s", path2);
        }
        else
        {
            if (fuzzy2)
            {
                exist2 = ventoy_check_fuzzy_path((char *)path2, 0);                
            }
            else
            {
                exist2 = ventoy_is_file_exist("%s", path2);
            }
        }
    }
    VTOY_JSON_FMT_BEGIN(pos, JSON_BUFFER, JSON_BUF_MAX);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_SINT("exist1", exist1);
    VTOY_JSON_FMT_SINT("exist2", exist2);
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    ventoy_json_buffer(conn, JSON_BUFFER, pos);
    return 0;
}
static int ventoy_api_check_fuzzy(struct mg_connection *conn, VTOY_JSON *json)
{
    int pos = 0;
    int exist = 0;
    const char *path = NULL;
    path = vtoy_json_get_string_ex(json, "path");
    if (path)
    {
        exist = ventoy_check_fuzzy_path((char *)path, 0);
    }
    VTOY_JSON_FMT_BEGIN(pos, JSON_BUFFER, JSON_BUF_MAX);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_SINT("exist", exist);
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    ventoy_json_buffer(conn, JSON_BUFFER, pos);
    return 0;
}
#if 0
#endif
void ventoy_data_default_control(data_control *data)
{
    memset(data, 0, sizeof(data_control));
    data->password_asterisk = 1;
    data->secondary_menu = 1;
    data->filter_dot_underscore = 1;
    data->max_search_level = -1;
    data->menu_timeout = 0;
    data->secondary_menu_timeout = 0;
    data->win11_bypass_check = 1;
    data->win11_bypass_nro = 1;
    
    strlcpy(data->default_kbd_layout, "QWERTY_USA");
    strlcpy(data->menu_language, "en_US");
}
int ventoy_data_cmp_control(data_control *data1, data_control *data2)
{
    if (data1->default_menu_mode != data2->default_menu_mode ||
        data1->treeview_style != data2->treeview_style ||
        data1->filter_dot_underscore != data2->filter_dot_underscore ||
        data1->sort_casesensitive != data2->sort_casesensitive ||
        data1->max_search_level != data2->max_search_level ||
        data1->vhd_no_warning != data2->vhd_no_warning ||
        data1->filter_iso != data2->filter_iso ||
        data1->filter_wim != data2->filter_wim ||
        data1->filter_efi != data2->filter_efi ||
        data1->filter_img != data2->filter_img ||
        data1->filter_vhd != data2->filter_vhd ||
        data1->filter_vtoy != data2->filter_vtoy ||
        data1->win11_bypass_check != data2->win11_bypass_check ||
        data1->win11_bypass_nro != data2->win11_bypass_nro ||
        data1->linux_remount != data2->linux_remount ||
        data1->password_asterisk != data2->password_asterisk ||
        data1->secondary_menu != data2->secondary_menu ||
        data1->menu_timeout != data2->menu_timeout ||
        data1->secondary_menu_timeout != data2->secondary_menu_timeout)
    {
        return 1;
    }
    if (strcmp(data1->default_search_root, data2->default_search_root) ||
        strcmp(data1->default_image, data2->default_image) ||
        strcmp(data1->default_kbd_layout, data2->default_kbd_layout) ||
        strcmp(data1->menu_language, data2->menu_language))
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_control(data_control *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    data_control *def = g_data_control + bios_max;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_ARY_BEGIN_N();
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_DEFAULT_MENU_MODE", default_menu_mode);        
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_TREE_VIEW_MENU_STYLE", treeview_style);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_FILT_DOT_UNDERSCORE_FILE", filter_dot_underscore);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_SORT_CASE_SENSITIVE",  sort_casesensitive);
    if (data->max_search_level >= 0)
    {
        VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_MAX_SEARCH_LEVEL",  max_search_level);            
    }
    
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_VHD_NO_WARNING",  vhd_no_warning);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_FILE_FLT_ISO", filter_iso);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_FILE_FLT_WIM", filter_wim);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_FILE_FLT_EFI", filter_efi);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_FILE_FLT_IMG", filter_img);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_FILE_FLT_VHD", filter_vhd);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_FILE_FLT_VTOY", filter_vtoy);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_WIN11_BYPASS_CHECK",  win11_bypass_check);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_WIN11_BYPASS_NRO",  win11_bypass_nro);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_LINUX_REMOUNT",  linux_remount);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_SECONDARY_BOOT_MENU",  secondary_menu);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_SHOW_PASSWORD_ASTERISK",  password_asterisk);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_MENU_TIMEOUT",  menu_timeout);
    VTOY_JSON_FMT_CTRL_INT(L2, "VTOY_SECONDARY_TIMEOUT",  secondary_menu_timeout);
    VTOY_JSON_FMT_CTRL_STRN(L2, "VTOY_DEFAULT_KBD_LAYOUT", default_kbd_layout);        
    VTOY_JSON_FMT_CTRL_STRN(L2, "VTOY_MENU_LANGUAGE", menu_language);  
    if (strcmp(def->default_search_root, data->default_search_root))
    {
        VTOY_JSON_FMT_CTRL_STRN_STR(L2, "VTOY_DEFAULT_SEARCH_ROOT", ventoy_real_path(data->default_search_root));
    }
    
    if (strcmp(def->default_image, data->default_image))
    {
        VTOY_JSON_FMT_CTRL_STRN_STR(L2, "VTOY_DEFAULT_IMAGE", ventoy_real_path(data->default_image));
    }
    VTOY_JSON_FMT_ARY_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_control(data_control *ctrl, char *buf, int buflen)
{
    int i = 0;
    int pos = 0;
    int valid = 0;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_SINT("default_menu_mode", ctrl->default_menu_mode);
    VTOY_JSON_FMT_SINT("treeview_style",  ctrl->treeview_style);
    VTOY_JSON_FMT_SINT("filter_dot_underscore",  ctrl->filter_dot_underscore);
    VTOY_JSON_FMT_SINT("sort_casesensitive",  ctrl->sort_casesensitive);
    VTOY_JSON_FMT_SINT("max_search_level",  ctrl->max_search_level);    
    VTOY_JSON_FMT_SINT("vhd_no_warning",  ctrl->vhd_no_warning);
    
    VTOY_JSON_FMT_SINT("filter_iso", ctrl->filter_iso);
    VTOY_JSON_FMT_SINT("filter_wim", ctrl->filter_wim);
    VTOY_JSON_FMT_SINT("filter_efi", ctrl->filter_efi);
    VTOY_JSON_FMT_SINT("filter_img", ctrl->filter_img);
    VTOY_JSON_FMT_SINT("filter_vhd", ctrl->filter_vhd);
    VTOY_JSON_FMT_SINT("filter_vtoy", ctrl->filter_vtoy);
    VTOY_JSON_FMT_SINT("win11_bypass_check",  ctrl->win11_bypass_check);
    VTOY_JSON_FMT_SINT("win11_bypass_nro",  ctrl->win11_bypass_nro);
    VTOY_JSON_FMT_SINT("linux_remount",  ctrl->linux_remount);
    VTOY_JSON_FMT_SINT("secondary_menu",  ctrl->secondary_menu);
    VTOY_JSON_FMT_SINT("password_asterisk",  ctrl->password_asterisk);
    VTOY_JSON_FMT_SINT("menu_timeout",  ctrl->menu_timeout);
    VTOY_JSON_FMT_SINT("secondary_menu_timeout",  ctrl->secondary_menu_timeout);
    VTOY_JSON_FMT_STRN("default_kbd_layout",  ctrl->default_kbd_layout);
    VTOY_JSON_FMT_STRN("menu_language",  ctrl->menu_language);
    valid = 0;
    if (ctrl->default_search_root[0] && ventoy_is_directory_exist("%s%s", g_cur_dir, ctrl->default_search_root))
    {
        valid = 1;
    }
    VTOY_JSON_FMT_STRN("default_search_root",  ctrl->default_search_root);
    VTOY_JSON_FMT_SINT("default_search_root_valid", valid);
    
    valid = 0;
    if (ctrl->default_image[0] && ventoy_is_file_exist("%s%s", g_cur_dir, ctrl->default_image))
    {
        valid = 1;
    }
    VTOY_JSON_FMT_STRN("default_image", ctrl->default_image);
    VTOY_JSON_FMT_SINT("default_image_valid", valid);
    VTOY_JSON_FMT_KEY("menu_list");
    VTOY_JSON_FMT_ARY_BEGIN();
    for (i = 0; g_ventoy_menu_lang[i][0]; i++)
    {
        VTOY_JSON_FMT_ITEM(g_ventoy_menu_lang[i]);        
    }
    VTOY_JSON_FMT_ARY_ENDEX();
    
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_control(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, control);
    return 0;
}
static int ventoy_api_save_control(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    data_control *ctrl = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    ctrl = g_data_control + index;
    VTOY_JSON_INT("default_menu_mode", ctrl->default_menu_mode);
    VTOY_JSON_INT("treeview_style", ctrl->treeview_style);
    VTOY_JSON_INT("filter_dot_underscore", ctrl->filter_dot_underscore);
    VTOY_JSON_INT("sort_casesensitive", ctrl->sort_casesensitive);
    VTOY_JSON_INT("max_search_level", ctrl->max_search_level);
    VTOY_JSON_INT("vhd_no_warning", ctrl->vhd_no_warning);
    VTOY_JSON_INT("filter_iso", ctrl->filter_iso);
    VTOY_JSON_INT("filter_wim", ctrl->filter_wim);
    VTOY_JSON_INT("filter_efi", ctrl->filter_efi);
    VTOY_JSON_INT("filter_img", ctrl->filter_img);
    VTOY_JSON_INT("filter_vhd", ctrl->filter_vhd);
    VTOY_JSON_INT("filter_vtoy", ctrl->filter_vtoy);
    VTOY_JSON_INT("win11_bypass_check", ctrl->win11_bypass_check);
    VTOY_JSON_INT("win11_bypass_nro", ctrl->win11_bypass_nro);
    VTOY_JSON_INT("linux_remount", ctrl->linux_remount);
    VTOY_JSON_INT("secondary_menu", ctrl->secondary_menu);
    VTOY_JSON_INT("password_asterisk", ctrl->password_asterisk);
    VTOY_JSON_INT("menu_timeout", ctrl->menu_timeout);
    VTOY_JSON_INT("secondary_menu_timeout", ctrl->secondary_menu_timeout);
    VTOY_JSON_STR("default_image", ctrl->default_image);
    VTOY_JSON_STR("default_search_root", ctrl->default_search_root);
    VTOY_JSON_STR("menu_language", ctrl->menu_language);
    VTOY_JSON_STR("default_kbd_layout", ctrl->default_kbd_layout);
    
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);
    return 0;
}
#if 0
#endif
void ventoy_data_default_theme(data_theme *data)
{
    memset(data, 0, sizeof(data_theme));
    strlcpy(data->gfxmode, "1024x768");
    scnprintf(data->ventoy_left, sizeof(data->ventoy_left), "5%%");
    scnprintf(data->ventoy_top, sizeof(data->ventoy_top), "95%%");
    scnprintf(data->ventoy_color, sizeof(data->ventoy_color), "%s", "#0000ff");
}
int ventoy_data_cmp_theme(data_theme *data1, data_theme *data2)
{
    if (data1->display_mode != data2->display_mode ||
        strcmp(data1->ventoy_left, data2->ventoy_left) ||
        strcmp(data1->ventoy_top, data2->ventoy_top) ||
        strcmp(data1->gfxmode, data2->gfxmode) ||
        strcmp(data1->ventoy_color, data2->ventoy_color)
        )
    {
        return 1;
    }
    if (ventoy_path_list_cmp(data1->filelist, data2->filelist))
    {
        return 1;
    }
    if (ventoy_path_list_cmp(data1->fontslist, data2->fontslist))
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_theme(data_theme *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    path_node *node = NULL;
    data_theme *def = g_data_theme + bios_max;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_OBJ_BEGIN_N();
    if (data->filelist)
    {
        if (data->filelist->next)
        {
            VTOY_JSON_FMT_KEY_L(L2, "file");
            VTOY_JSON_FMT_ARY_BEGIN_N();
            for (node = data->filelist; node; node = node->next)
            {
                VTOY_JSON_FMT_ITEM_PATH_LN(L3, node->path);
            }
            VTOY_JSON_FMT_ARY_ENDEX_LN(L2);
        
            if (def->default_file != data->default_file)
            {
                VTOY_JSON_FMT_SINT_LN(L2, "default_file", data->default_file);                
            }
            
            if (def->resolution_fit != data->resolution_fit)
            {
                VTOY_JSON_FMT_SINT_LN(L2, "resolution_fit", data->resolution_fit);                
            }
        }
        else
        {
            VTOY_JSON_FMT_STRN_PATH_LN(L2, "file", data->filelist->path);
        }
    }
    if (data->display_mode != def->display_mode)
    {
        if (display_mode_cli == data->display_mode)
        {
            VTOY_JSON_FMT_STRN_LN(L2, "display_mode", "CLI");
        }
        else if (display_mode_serial == data->display_mode)
        {
            VTOY_JSON_FMT_STRN_LN(L2, "display_mode", "serial");
        }
        else if (display_mode_ser_console == data->display_mode)
        {
            VTOY_JSON_FMT_STRN_LN(L2, "display_mode", "serial_console");
        }
        else
        {
            VTOY_JSON_FMT_STRN_LN(L2, "display_mode", "GUI");
        }
    }
    VTOY_JSON_FMT_DIFF_STRN(L2, "gfxmode", gfxmode);
    
    VTOY_JSON_FMT_DIFF_STRN(L2, "ventoy_left", ventoy_left);
    VTOY_JSON_FMT_DIFF_STRN(L2, "ventoy_top", ventoy_top);
    VTOY_JSON_FMT_DIFF_STRN(L2, "ventoy_color", ventoy_color);
    
    if (data->fontslist)
    {
        VTOY_JSON_FMT_KEY_L(L2, "fonts");
        VTOY_JSON_FMT_ARY_BEGIN_N();
        for (node = data->fontslist; node; node = node->next)
        {
			VTOY_JSON_FMT_ITEM_PATH_LN(L3, node->path);
        }
        
        VTOY_JSON_FMT_ARY_ENDEX_LN(L2);
    }
    
    VTOY_JSON_FMT_OBJ_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_theme(data_theme *data, char *buf, int buflen)
{
    int pos = 0;
    path_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_SINT("default_file",  data->default_file);
    VTOY_JSON_FMT_SINT("resolution_fit",  data->resolution_fit);
    VTOY_JSON_FMT_SINT("display_mode",  data->display_mode);
    VTOY_JSON_FMT_STRN("gfxmode", data->gfxmode);
    
    VTOY_JSON_FMT_STRN("ventoy_color", data->ventoy_color);
    VTOY_JSON_FMT_STRN("ventoy_left", data->ventoy_left);
    VTOY_JSON_FMT_STRN("ventoy_top", data->ventoy_top);
    
    VTOY_JSON_FMT_KEY("filelist");
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->filelist; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_STRN("path", node->path);
        VTOY_JSON_FMT_SINT("valid", ventoy_is_file_exist("%s%s", g_cur_dir, node->path));
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_ENDEX();
    
    VTOY_JSON_FMT_KEY("fontslist");
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->fontslist; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_STRN("path", node->path);
        VTOY_JSON_FMT_SINT("valid", ventoy_is_file_exist("%s%s", g_cur_dir, node->path));
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_ENDEX();
    
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_theme(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, theme);
    return 0;
}
static int ventoy_api_save_theme(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    data_theme *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_theme + index;
    VTOY_JSON_INT("default_file", data->default_file);
    VTOY_JSON_INT("resolution_fit", data->resolution_fit);
    VTOY_JSON_INT("display_mode", data->display_mode);
    VTOY_JSON_STR("gfxmode", data->gfxmode);
    VTOY_JSON_STR("ventoy_left", data->ventoy_left);
    VTOY_JSON_STR("ventoy_top", data->ventoy_top);
    VTOY_JSON_STR("ventoy_color", data->ventoy_color);
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
static int ventoy_api_theme_add_file(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    path_node *node = NULL;
    path_node *cur = NULL;
    data_theme *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_theme + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (ventoy_is_real_exist_common(path, data->filelist, path_node))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }
        node = zalloc(sizeof(path_node));
        if (node)
        {
            scnprintf(node->path, sizeof(node->path), "%s", path);
            vtoy_list_add(data->filelist, cur, node);            
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET); 
    return 0;
}
static int ventoy_api_theme_del_file(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    path_node *node = NULL;
    path_node *last = NULL;
    data_theme *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_theme + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            vtoy_list_free(path_node, data->filelist);
        }
        else
        {
            vtoy_list_del(last, node, data->filelist, path);
        }    
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
static int ventoy_api_theme_add_font(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    path_node *node = NULL;
    path_node *cur = NULL;
    data_theme *data = NULL;
    vtoy_json_get_int(json, "index", &index);
    data = g_data_theme + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (ventoy_is_real_exist_common(path, data->fontslist, path_node))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }
        node = zalloc(sizeof(path_node));
        if (node)
        {
            scnprintf(node->path, sizeof(node->path), "%s", path);
            vtoy_list_add(data->fontslist, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_theme_del_font(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    path_node *node = NULL;
    path_node *last = NULL;
    data_theme *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_theme + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            vtoy_list_free(path_node, data->fontslist);
        }
        else
        {
            vtoy_list_del(last, node, data->fontslist, path);            
        }    
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
#if 0
#endif
void ventoy_data_default_menu_alias(data_alias *data)
{
    memset(data, 0, sizeof(data_alias));
}
int ventoy_data_cmp_menu_alias(data_alias *data1, data_alias *data2)
{
    data_alias_node *list1 = NULL;
    data_alias_node *list2 = NULL;
    if (NULL == data1->list && NULL == data2->list)
    {
        return 0;
    }
    else if (data1->list && data2->list)
    {
        list1 = data1->list;
        list2 = data2->list;
    
        while (list1 && list2)
        {
            if ((list1->type != list2->type) || 
                strcmp(list1->path, list2->path) || 
                strcmp(list1->alias, list2->alias))
            {
                return 1;
            }
        
            list1 = list1->next;
            list2 = list2->next;
        }
        if (list1 == NULL && list2 == NULL)
        {
            return 0;
        }
        return 1;
    }
    else
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_menu_alias(data_alias *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    data_alias_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_ARY_BEGIN_N();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN_LN(L2);
        if (node->type == path_type_file)
        {
            VTOY_JSON_FMT_STRN_PATH_LN(L3, "image", node->path);            
        }
        else
        {
            VTOY_JSON_FMT_STRN_PATH_LN(L3, "dir", node->path);
        }
        
        VTOY_JSON_FMT_STRN_EX_LN(L3, "alias", node->alias);
        
        VTOY_JSON_FMT_OBJ_ENDEX_LN(L2);
    }
    VTOY_JSON_FMT_ARY_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_menu_alias(data_alias *data, char *buf, int buflen)
{
    int pos = 0;
    int valid = 0;
    data_alias_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_UINT("type", node->type);
        VTOY_JSON_FMT_STRN("path", node->path);
        if (node->type == path_type_file)
        {
            valid = ventoy_check_fuzzy_path(node->path, 1);
        }
        else
        {
            valid = ventoy_is_directory_exist("%s%s", g_cur_dir, node->path);
        }
        
        VTOY_JSON_FMT_SINT("valid", valid);
        VTOY_JSON_FMT_STRN("alias", node->alias);
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_alias(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, menu_alias);
    return 0;
}
static int ventoy_api_save_alias(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
static int ventoy_api_alias_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    int type = path_type_file;
    const char *path = NULL;
    const char *alias = NULL;
    data_alias_node *node = NULL;
    data_alias_node *cur = NULL;
    data_alias *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_menu_alias + index;
    vtoy_json_get_int(json, "type", &type);
    path = VTOY_JSON_STR_EX("path");
    alias = VTOY_JSON_STR_EX("alias");
    if (path && alias)
    {
        if (ventoy_is_real_exist_common(path, data->list, data_alias_node))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }
        node = zalloc(sizeof(data_alias_node));
        if (node)
        {
            node->type = type;
            scnprintf(node->path, sizeof(node->path), "%s", path);
            scnprintf(node->alias, sizeof(node->alias), "%s", alias);
            
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
static int ventoy_api_alias_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    data_alias_node *last = NULL;
    data_alias_node *node = NULL;
    data_alias *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_menu_alias + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            vtoy_list_free(data_alias_node, data->list);          
        }
        else
        {
            vtoy_list_del(last, node, data->list, path);            
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);    
    return 0;
}
#if 0
#endif
void ventoy_data_default_menu_tip(data_tip *data)
{
    memset(data, 0, sizeof(data_tip));
    scnprintf(data->left, sizeof(data->left), "10%%");
    scnprintf(data->top, sizeof(data->top), "81%%");
    scnprintf(data->color, sizeof(data->color), "%s", "blue");
}
int ventoy_data_cmp_menu_tip(data_tip *data1, data_tip *data2)
{
    data_tip_node *list1 = NULL;
    data_tip_node *list2 = NULL;
    if (strcmp(data1->left, data2->left) || strcmp(data1->top, data2->top) || strcmp(data1->color, data2->color))
    {
        return 1;
    }
    if (NULL == data1->list && NULL == data2->list)
    {
        return 0;
    }
    else if (data1->list && data2->list)
    {
        list1 = data1->list;
        list2 = data2->list;
    
        while (list1 && list2)
        {
            if ((list1->type != list2->type) || 
                strcmp(list1->path, list2->path) || 
                strcmp(list1->tip, list2->tip))
            {
                return 1;
            }
        
            list1 = list1->next;
            list2 = list2->next;
        }
        if (list1 == NULL && list2 == NULL)
        {
            return 0;
        }
        return 1;
    }
    else
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_menu_tip(data_tip *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    data_tip_node *node = NULL;
    data_tip *def = g_data_menu_tip + bios_max;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_OBJ_BEGIN_N();
    VTOY_JSON_FMT_DIFF_STRN(L2, "left", left);        
    VTOY_JSON_FMT_DIFF_STRN(L2, "top", top);        
    VTOY_JSON_FMT_DIFF_STRN(L2, "color", color);        
    if (data->list)
    {
        VTOY_JSON_FMT_KEY_L(L2, "tips");
        VTOY_JSON_FMT_ARY_BEGIN_N();
        for (node = data->list; node; node = node->next)
        {
            VTOY_JSON_FMT_OBJ_BEGIN_LN(L3);
            if (node->type == path_type_file)
            {
                VTOY_JSON_FMT_STRN_PATH_LN(L4, "image", node->path);            
            }
            else
            {
                VTOY_JSON_FMT_STRN_PATH_LN(L4, "dir", node->path);
            }
            VTOY_JSON_FMT_STRN_EX_LN(L4, "tip", node->tip);
            
            VTOY_JSON_FMT_OBJ_ENDEX_LN(L3);
        }
        VTOY_JSON_FMT_ARY_ENDEX_LN(L2);
    }
    
    VTOY_JSON_FMT_OBJ_ENDEX_LN(L1);
    
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_menu_tip(data_tip *data, char *buf, int buflen)
{
    int pos = 0;
    int valid = 0;
    data_tip_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    
    VTOY_JSON_FMT_STRN("left", data->left);
    VTOY_JSON_FMT_STRN("top", data->top);
    VTOY_JSON_FMT_STRN("color", data->color);
    VTOY_JSON_FMT_KEY("tips");
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_UINT("type", node->type);
        VTOY_JSON_FMT_STRN("path", node->path);
        if (node->type == path_type_file)
        {
            valid = ventoy_check_fuzzy_path(node->path, 1);
        }
        else
        {
            valid = ventoy_is_directory_exist("%s%s", g_cur_dir, node->path);
        }
        
        VTOY_JSON_FMT_SINT("valid", valid);
        VTOY_JSON_FMT_STRN("tip", node->tip);
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_ENDEX();
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_tip(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, menu_tip);
    return 0;
}
static int ventoy_api_save_tip(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    data_tip *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_menu_tip + index;
    VTOY_JSON_STR("left", data->left);
    VTOY_JSON_STR("top", data->top);
    VTOY_JSON_STR("color", data->color);
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_tip_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    int type = path_type_file;
    const char *path = NULL;
    const char *tip = NULL;
    data_tip_node *node = NULL;
    data_tip_node *cur = NULL;
    data_tip *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_menu_tip + index;
    vtoy_json_get_int(json, "type", &type);
    path = VTOY_JSON_STR_EX("path");
    tip = VTOY_JSON_STR_EX("tip");
    if (path && tip)
    {
        if (ventoy_is_real_exist_common(path, data->list, data_tip_node))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }
    
        node = zalloc(sizeof(data_tip_node));
        if (node)
        {
            node->type = type;
            scnprintf(node->path, sizeof(node->path), "%s", path);
            scnprintf(node->tip, sizeof(node->tip), "%s", tip);
            
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_tip_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    data_tip_node *last = NULL;
    data_tip_node *node = NULL;
    data_tip *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_menu_tip + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            vtoy_list_free(data_tip_node, data->list);          
        }
        else
        {
            vtoy_list_del(last, node, data->list, path);  
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
#if 0
#endif
void ventoy_data_default_menu_class(data_class *data)
{
    memset(data, 0, sizeof(data_class));
}
int ventoy_data_cmp_menu_class(data_class *data1, data_class *data2)
{
    data_class_node *list1 = NULL;
    data_class_node *list2 = NULL;
    if (NULL == data1->list && NULL == data2->list)
    {
        return 0;
    }
    else if (data1->list && data2->list)
    {
        list1 = data1->list;
        list2 = data2->list;
    
        while (list1 && list2)
        {
            if ((list1->type != list2->type) || 
                strcmp(list1->path, list2->path) || 
                strcmp(list1->class, list2->class))
            {
                return 1;
            }
        
            list1 = list1->next;
            list2 = list2->next;
        }
        if (list1 == NULL && list2 == NULL)
        {
            return 0;
        }
        return 1;
    }
    else
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_menu_class(data_class *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    data_class_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_ARY_BEGIN_N();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN_LN(L2);
        if (node->type == class_type_key)
        {
            VTOY_JSON_FMT_STRN_LN(L3, "key", node->path);            
        }
        else if (node->type == class_type_dir)
        {
            VTOY_JSON_FMT_STRN_PATH_LN(L3, "dir", node->path);
        }
        else
        {
            VTOY_JSON_FMT_STRN_PATH_LN(L3, "parent", node->path);
        }
        VTOY_JSON_FMT_STRN_LN(L3, "class", node->class);
        
        VTOY_JSON_FMT_OBJ_ENDEX_LN(L2);
    }
    VTOY_JSON_FMT_ARY_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_menu_class(data_class *data, char *buf, int buflen)
{
    int pos = 0;
    int valid = 0;
    data_class_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_UINT("type", node->type);
        VTOY_JSON_FMT_STRN("path", node->path);       
        if (node->type == class_type_key)
        {
            valid = 1;
        }
        else
        {
            valid = ventoy_is_directory_exist("%s%s", g_cur_dir, node->path);
        }
        VTOY_JSON_FMT_SINT("valid", valid);
        
        VTOY_JSON_FMT_STRN("class", node->class);
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_class(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, menu_class);
    return 0;
}
static int ventoy_api_save_class(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
static int ventoy_api_class_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    int type = class_type_key;
    const char *path = NULL;
    const char *class = NULL;
    data_class_node *node = NULL;
    data_class_node *cur = NULL;
    data_class *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_menu_class + index;
    vtoy_json_get_int(json, "type", &type);
    path = VTOY_JSON_STR_EX("path");
    class = VTOY_JSON_STR_EX("class");
    if (path && class)
    {
        node = zalloc(sizeof(data_class_node));
        if (node)
        {
            node->type = type;
        
            scnprintf(node->path, sizeof(node->path), "%s", path);
            scnprintf(node->class, sizeof(node->class), "%s", class);
            
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET); 
    return 0;
}
static int ventoy_api_class_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    data_class_node *last = NULL;
    data_class_node *node = NULL;
    data_class *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_menu_class + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            vtoy_list_free(data_class_node, data->list);
        }
        else
        {
            vtoy_list_del(last, node, data->list, path);            
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
#if 0
#endif
void ventoy_data_default_auto_memdisk(data_auto_memdisk *data)
{
    memset(data, 0, sizeof(data_auto_memdisk));
}
int ventoy_data_cmp_auto_memdisk(data_auto_memdisk *data1, data_auto_memdisk *data2)
{
    return ventoy_path_list_cmp(data1->list, data2->list);
}
int ventoy_data_save_auto_memdisk(data_auto_memdisk *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    path_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_ARY_BEGIN_N();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_ITEM_PATH_LN(L2, node->path);
    }
    VTOY_JSON_FMT_ARY_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_auto_memdisk(data_auto_memdisk *data, char *buf, int buflen)
{
    int pos = 0;
    int valid = 0;
    path_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_STRN("path", node->path); 
        valid = ventoy_check_fuzzy_path(node->path, 1);
        VTOY_JSON_FMT_SINT("valid", valid);        
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_auto_memdisk(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, auto_memdisk);
    return 0;
}
static int ventoy_api_save_auto_memdisk(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);
    return 0;
}
static int ventoy_api_auto_memdisk_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    path_node *node = NULL;
    path_node *cur = NULL;
    data_auto_memdisk *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_auto_memdisk + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (ventoy_is_real_exist_common(path, data->list, path_node))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }
        node = zalloc(sizeof(path_node));
        if (node)
        {
            scnprintf(node->path, sizeof(node->path), "%s", path);
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);
    return 0;
}
static int ventoy_api_auto_memdisk_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    path_node *last = NULL;
    path_node *node = NULL;
    data_auto_memdisk *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_auto_memdisk + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            vtoy_list_free(path_node, data->list);
        }
        else
        {
            vtoy_list_del(last, node, data->list, path);            
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);    
    return 0;
}
#if 0
#endif
void ventoy_data_default_image_list(data_image_list *data)
{
    memset(data, 0, sizeof(data_image_list));
}
int ventoy_data_cmp_image_list(data_image_list *data1, data_image_list *data2)
{
    if (data1->type != data2->type)
    {
        if (data1->list || data2->list)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    return ventoy_path_list_cmp(data1->list, data2->list);
}
int ventoy_data_save_image_list(data_image_list *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    int prelen;
    path_node *node = NULL;
    char newtitle[64];
    (void)title;
    if (!(data->list))
    {
        return 0;
    }
    prelen = (int)strlen("image_list");
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    if (data->type == 0)
    {
        scnprintf(newtitle, sizeof(newtitle), "image_list%s", title + prelen);
    }
    else
    {
        scnprintf(newtitle, sizeof(newtitle), "image_blacklist%s", title + prelen);
    }
    VTOY_JSON_FMT_KEY_L(L1, newtitle);
    
    VTOY_JSON_FMT_ARY_BEGIN_N();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_ITEM_PATH_LN(L2, node->path);
    }
    VTOY_JSON_FMT_ARY_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_image_list(data_image_list *data, char *buf, int buflen)
{
    int pos = 0;
    int valid = 0;
    path_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_SINT("type", data->type);   
    
    VTOY_JSON_FMT_KEY("list");
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_STRN("path", node->path); 
        valid = ventoy_check_fuzzy_path(node->path, 1);
        VTOY_JSON_FMT_SINT("valid", valid);        
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_ENDEX();
    VTOY_JSON_FMT_OBJ_END();
    
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_image_list(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, image_list);
    return 0;
}
static int ventoy_api_save_image_list(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    data_image_list *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_image_list + index;
    VTOY_JSON_INT("type", data->type);
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_image_list_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    path_node *node = NULL;
    path_node *cur = NULL;
    data_image_list *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_image_list + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (ventoy_is_real_exist_common(path, data->list, path_node))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }
        node = zalloc(sizeof(path_node));
        if (node)
        {
            scnprintf(node->path, sizeof(node->path), "%s", path);
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);
    return 0;
}
static int ventoy_api_image_list_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    path_node *last = NULL;
    path_node *node = NULL;
    data_image_list *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_image_list + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            vtoy_list_free(path_node, data->list);
        }
        else
        {
            vtoy_list_del(last, node, data->list, path);            
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
#if 0
#endif
void ventoy_data_default_password(data_password *data)
{
    memset(data, 0, sizeof(data_password));
}
int ventoy_data_cmp_password(data_password *data1, data_password *data2)
{
    menu_password *list1 = NULL;
    menu_password *list2 = NULL;
    if (strcmp(data1->bootpwd, data2->bootpwd) || 
        strcmp(data1->isopwd, data2->isopwd) || 
        strcmp(data1->wimpwd, data2->wimpwd) || 
        strcmp(data1->vhdpwd, data2->vhdpwd) || 
        strcmp(data1->imgpwd, data2->imgpwd) || 
        strcmp(data1->efipwd, data2->efipwd) || 
        strcmp(data1->vtoypwd, data2->vtoypwd)
        )
    {
        return 1;
    }
    if (NULL == data1->list && NULL == data2->list)
    {
        return 0;
    }
    else if (data1->list && data2->list)
    {
        list1 = data1->list;
        list2 = data2->list;
    
        while (list1 && list2)
        {
            if ((list1->type != list2->type) || strcmp(list1->path, list2->path))
            {
                return 1;
            }
        
            list1 = list1->next;
            list2 = list2->next;
        }
        if (list1 == NULL && list2 == NULL)
        {
            return 0;
        }
        return 1;
    }
    else
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_password(data_password *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    menu_password *node = NULL;
    data_password *def = g_data_password + bios_max;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_OBJ_BEGIN_N();
    VTOY_JSON_FMT_DIFF_STRN(L2, "bootpwd", bootpwd);
    VTOY_JSON_FMT_DIFF_STRN(L2, "isopwd", isopwd);
    VTOY_JSON_FMT_DIFF_STRN(L2, "wimpwd", wimpwd);
    VTOY_JSON_FMT_DIFF_STRN(L2, "vhdpwd", vhdpwd);
    VTOY_JSON_FMT_DIFF_STRN(L2, "imgpwd", imgpwd);
    VTOY_JSON_FMT_DIFF_STRN(L2, "efipwd", efipwd);
    VTOY_JSON_FMT_DIFF_STRN(L2, "vtoypwd", vtoypwd);
    if (data->list)
    {
        VTOY_JSON_FMT_KEY_L(L2, "menupwd");
        VTOY_JSON_FMT_ARY_BEGIN_N();
        for (node = data->list; node; node = node->next)
        {
            VTOY_JSON_FMT_OBJ_BEGIN_LN(L3);
            if (node->type == 0)
            {
                VTOY_JSON_FMT_STRN_PATH_LN(L4, "file", node->path);            
            }
            else
            {
                VTOY_JSON_FMT_STRN_PATH_LN(L4, "parent", node->path);
            }
            VTOY_JSON_FMT_STRN_LN(L4, "pwd", node->pwd);
            
            VTOY_JSON_FMT_OBJ_ENDEX_LN(L3);
        }
        VTOY_JSON_FMT_ARY_ENDEX_LN(L2);
    }
    
    VTOY_JSON_FMT_OBJ_ENDEX_LN(L1);
    
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_password(data_password *data, char *buf, int buflen)
{
    int pos = 0;
    int valid = 0;
    menu_password *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_STRN("bootpwd", data->bootpwd);
    VTOY_JSON_FMT_STRN("isopwd", data->isopwd);
    VTOY_JSON_FMT_STRN("wimpwd", data->wimpwd);
    VTOY_JSON_FMT_STRN("vhdpwd", data->vhdpwd);
    VTOY_JSON_FMT_STRN("imgpwd", data->imgpwd);
    VTOY_JSON_FMT_STRN("efipwd", data->efipwd);
    VTOY_JSON_FMT_STRN("vtoypwd", data->vtoypwd);
    VTOY_JSON_FMT_KEY("list");
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_SINT("type", node->type);
        VTOY_JSON_FMT_STRN("path", node->path);
        if (node->type == path_type_file)
        {
            valid = ventoy_check_fuzzy_path(node->path, 1);
        }
        else
        {
            valid = ventoy_is_directory_exist("%s%s", g_cur_dir, node->path);
        }
        
        VTOY_JSON_FMT_SINT("valid", valid);
        VTOY_JSON_FMT_STRN("pwd", node->pwd);
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_ENDEX();
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_password(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, password);
    return 0;
}
static int ventoy_api_save_password(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    data_password *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_password + index;
    VTOY_JSON_STR("bootpwd", data->bootpwd);
    VTOY_JSON_STR("isopwd", data->isopwd);
    VTOY_JSON_STR("wimpwd", data->wimpwd);
    VTOY_JSON_STR("vhdpwd", data->vhdpwd);
    VTOY_JSON_STR("imgpwd", data->imgpwd);
    VTOY_JSON_STR("efipwd", data->efipwd);
    VTOY_JSON_STR("vtoypwd", data->vtoypwd);
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
static int ventoy_api_password_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    int type = 0;
    const char *path = NULL;
    const char *pwd = NULL;
    menu_password *node = NULL;
    menu_password *cur = NULL;
    data_password *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_password + index;
    vtoy_json_get_int(json, "type", &type);
    path = VTOY_JSON_STR_EX("path");
    pwd = VTOY_JSON_STR_EX("pwd");
    if (path && pwd)
    {
        if (ventoy_is_real_exist_common(path, data->list, menu_password))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }
        node = zalloc(sizeof(menu_password));
        if (node)
        {
            node->type = type;
            scnprintf(node->path, sizeof(node->path), "%s", path);
            scnprintf(node->pwd, sizeof(node->pwd), "%s", pwd);
            
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);    
    return 0;
}
static int ventoy_api_password_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    menu_password *last = NULL;
    menu_password *node = NULL;
    data_password *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_password + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            vtoy_list_free(menu_password, data->list);
        }
        else
        {
            vtoy_list_del(last, node, data->list, path);            
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
#if 0
#endif
void ventoy_data_default_conf_replace(data_conf_replace *data)
{
    memset(data, 0, sizeof(data_conf_replace));
}
int ventoy_data_cmp_conf_replace(data_conf_replace *data1, data_conf_replace *data2)
{
    conf_replace_node *list1 = NULL;
    conf_replace_node *list2 = NULL;
    if (NULL == data1->list && NULL == data2->list)
    {
        return 0;
    }
    else if (data1->list && data2->list)
    {
        list1 = data1->list;
        list2 = data2->list;
    
        while (list1 && list2)
        {
            if (list1->image != list2->image ||
                strcmp(list1->path, list2->path) || 
                strcmp(list1->org, list2->org) || 
                strcmp(list1->new, list2->new)
                )
            {
                return 1;
            }
        
            list1 = list1->next;
            list2 = list2->next;
        }
        if (list1 == NULL && list2 == NULL)
        {
            return 0;
        }
        return 1;
    }
    else
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_conf_replace(data_conf_replace *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    conf_replace_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_ARY_BEGIN_N();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN_LN(L2);
        VTOY_JSON_FMT_STRN_PATH_LN(L3, "iso", node->path);
        VTOY_JSON_FMT_STRN_LN(L3, "org", node->org);
        VTOY_JSON_FMT_STRN_PATH_LN(L3, "new", node->new);
        if (node->image)
        {
            VTOY_JSON_FMT_SINT_LN(L3, "img", node->image);    
        }
        
        VTOY_JSON_FMT_OBJ_ENDEX_LN(L2);
    }
    VTOY_JSON_FMT_ARY_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_conf_replace(data_conf_replace *data, char *buf, int buflen)
{
    int pos = 0;
    conf_replace_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_STRN("path", node->path);
        VTOY_JSON_FMT_SINT("valid", ventoy_check_fuzzy_path(node->path, 1));
        VTOY_JSON_FMT_STRN("org", node->org);
        VTOY_JSON_FMT_STRN("new", node->new);
        VTOY_JSON_FMT_SINT("new_valid", ventoy_is_file_exist("%s%s", g_cur_dir, node->new));
        VTOY_JSON_FMT_SINT("img", node->image);
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_conf_replace(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, conf_replace);
    return 0;
}
static int ventoy_api_save_conf_replace(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_conf_replace_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int image = 0;
    int index = 0;
    const char *path = NULL;
    const char *org = NULL;
    const char *new = NULL;
    conf_replace_node *node = NULL;
    conf_replace_node *cur = NULL;
    data_conf_replace *data = NULL;
    
    vtoy_json_get_int(json, "img", &image);
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_conf_replace + index;
    path = VTOY_JSON_STR_EX("path");
    org = VTOY_JSON_STR_EX("org");
    new = VTOY_JSON_STR_EX("new");
    if (path && org && new)
    {
        node = zalloc(sizeof(conf_replace_node));
        if (node)
        {
            node->image = image;
            scnprintf(node->path, sizeof(node->path), "%s", path);
            scnprintf(node->org, sizeof(node->org), "%s", org);
            scnprintf(node->new, sizeof(node->new), "%s", new);
            
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
static int ventoy_api_conf_replace_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    conf_replace_node *last = NULL;
    conf_replace_node *node = NULL;
    data_conf_replace *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_conf_replace + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            vtoy_list_free(conf_replace_node, data->list);
        }
        else
        {
            vtoy_list_del(last, node, data->list, path);            
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
#if 0
#endif
void ventoy_data_default_dud(data_dud *data)
{
    memset(data, 0, sizeof(data_dud));
}
int ventoy_data_cmp_dud(data_dud *data1, data_dud *data2)
{
    dud_node *list1 = NULL;
    dud_node *list2 = NULL;
    if (NULL == data1->list && NULL == data2->list)
    {
        return 0;
    }
    else if (data1->list && data2->list)
    {
        list1 = data1->list;
        list2 = data2->list;
    
        while (list1 && list2)
        {
            if (strcmp(list1->path, list2->path))
            {
                return 1;
            }
            /* no need to compare dud list with default */
            list1 = list1->next;
            list2 = list2->next;
        }
        if (list1 == NULL && list2 == NULL)
        {
            return 0;
        }
        return 1;
    }
    else
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_dud(data_dud *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    dud_node *node = NULL;
    path_node *pathnode = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_ARY_BEGIN_N();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN_LN(L2);
        VTOY_JSON_FMT_STRN_PATH_LN(L3, "image", node->path);            
        VTOY_JSON_FMT_KEY_L(L3, "dud");
        VTOY_JSON_FMT_ARY_BEGIN_N();
        for (pathnode = node->list; pathnode; pathnode = pathnode->next)
        {
            VTOY_JSON_FMT_ITEM_PATH_LN(L4, pathnode->path);
        }
        VTOY_JSON_FMT_ARY_ENDEX_LN(L3);        
        
        VTOY_JSON_FMT_OBJ_ENDEX_LN(L2);
    }
    VTOY_JSON_FMT_ARY_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_dud(data_dud *data, char *buf, int buflen)
{
    int pos = 0;
    int valid = 0;
    dud_node *node = NULL;
    path_node *pathnode = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_STRN("path", node->path);
        valid = ventoy_check_fuzzy_path(node->path, 1);
        VTOY_JSON_FMT_SINT("valid", valid);
        
        VTOY_JSON_FMT_KEY("list");
        VTOY_JSON_FMT_ARY_BEGIN();
        for (pathnode = node->list; pathnode; pathnode = pathnode->next)
        {
            VTOY_JSON_FMT_OBJ_BEGIN();
            VTOY_JSON_FMT_STRN("path", pathnode->path);
            valid = ventoy_is_file_exist("%s%s", g_cur_dir, pathnode->path);
            VTOY_JSON_FMT_SINT("valid", valid);
            VTOY_JSON_FMT_OBJ_ENDEX();
        }
        VTOY_JSON_FMT_ARY_ENDEX(); 
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_dud(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, dud);
    return 0;
}
static int ventoy_api_save_dud(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_dud_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    dud_node *node = NULL;
    dud_node *cur = NULL;
    data_dud *data = NULL;
    VTOY_JSON *array = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_dud + index;
    array = vtoy_json_find_item(json, JSON_TYPE_ARRAY, "dud");
    path = VTOY_JSON_STR_EX("path");
    if (path && array)
    {
        if (ventoy_is_real_exist_common(path, data->list, dud_node))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }
        
        node = zalloc(sizeof(dud_node));
        if (node)
        {
            scnprintf(node->path, sizeof(node->path), "%s", path);
            node->list = ventoy_path_node_add_array(array);
            
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_dud_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    dud_node *next = NULL;
    dud_node *last = NULL;
    dud_node *node = NULL;
    data_dud *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_dud + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            for (node = data->list; node; node = next)
            {
                next = node->next;
                ventoy_free_path_node_list(node->list);
                free(node);
            }
            data->list = NULL;
        }
        else
        {
            vtoy_list_del_ex(last, node, data->list, path, ventoy_free_path_node_list);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_dud_add_inner(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    const char *outpath = NULL;
    path_node *pcur = NULL;
    path_node *pnode = NULL;
    dud_node *node = NULL;
    data_dud *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_dud + index;
    path = VTOY_JSON_STR_EX("path");
    outpath = VTOY_JSON_STR_EX("outpath");
    if (path && outpath)
    {
        for (node = data->list; node; node = node->next)
        {
            if (strcmp(outpath, node->path) == 0)
            {
                pnode = zalloc(sizeof(path_node));
                if (pnode)
                {
                    scnprintf(pnode->path, sizeof(pnode->path), "%s", path);
                    vtoy_list_add(node->list, pcur, pnode);
                }
            
                break;
            }
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET); 
    return 0;
}
static int ventoy_api_dud_del_inner(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    const char *outpath = NULL;
    path_node *plast = NULL;
    path_node *pnode = NULL;
    dud_node *node = NULL;
    data_dud *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_dud + index;
    path = VTOY_JSON_STR_EX("path");
    outpath = VTOY_JSON_STR_EX("outpath");
    if (path && outpath)
    {
        for (node = data->list; node; node = node->next)
        {
            if (strcmp(outpath, node->path) == 0)
            {
                vtoy_list_del(plast, pnode, node->list, path);
                break;
            }
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
#if 0
#endif
void ventoy_data_default_auto_install(data_auto_install *data)
{
    memset(data, 0, sizeof(data_auto_install));
}
int ventoy_data_cmp_auto_install(data_auto_install *data1, data_auto_install *data2)
{
    auto_install_node *list1 = NULL;
    auto_install_node *list2 = NULL;
    if (NULL == data1->list && NULL == data2->list)
    {
        return 0;
    }
    else if (data1->list && data2->list)
    {
        list1 = data1->list;
        list2 = data2->list;
    
        while (list1 && list2)
        {
            if (list1->timeout != list2->timeout ||
                list1->autosel != list2->autosel ||
                strcmp(list1->path, list2->path))
            {
                return 1;
            }
            /* no need to compare auto install list with default */
            list1 = list1->next;
            list2 = list2->next;
        }
        if (list1 == NULL && list2 == NULL)
        {
            return 0;
        }
        return 1;
    }
    else
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_auto_install(data_auto_install *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    auto_install_node *node = NULL;
    path_node *pathnode = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_ARY_BEGIN_N();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN_LN(L2);
        if (node->type == 0)
        {
            VTOY_JSON_FMT_STRN_PATH_LN(L3, "image", node->path);            
        }
        else
        {
            VTOY_JSON_FMT_STRN_PATH_LN(L3, "parent", node->path);                        
        }
        
        VTOY_JSON_FMT_KEY_L(L3, "template");
        VTOY_JSON_FMT_ARY_BEGIN_N();
        for (pathnode = node->list; pathnode; pathnode = pathnode->next)
        {
            VTOY_JSON_FMT_ITEM_PATH_LN(L4, pathnode->path);
        }
        VTOY_JSON_FMT_ARY_ENDEX_LN(L3);
        if (node->timeouten)
        {
            VTOY_JSON_FMT_SINT_LN(L3, "timeout", node->timeout);
        }
        if (node->autoselen)
        {
            VTOY_JSON_FMT_SINT_LN(L3, "autosel", node->autosel);                
        }
        VTOY_JSON_FMT_OBJ_ENDEX_LN(L2);
    }
    VTOY_JSON_FMT_ARY_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_auto_install(data_auto_install *data, char *buf, int buflen)
{
    int pos = 0;
    int valid = 0;
    auto_install_node *node = NULL;
    path_node *pathnode = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_STRN("path", node->path);
        if (node->type == 0)
        {
            valid = ventoy_check_fuzzy_path(node->path, 1);            
        }
        else
        {
            valid = ventoy_is_directory_exist("%s%s", g_cur_dir, node->path);
        }
        VTOY_JSON_FMT_SINT("valid", valid);
        VTOY_JSON_FMT_SINT("type", node->type);
        
        VTOY_JSON_FMT_BOOL("timeouten", node->timeouten);
        VTOY_JSON_FMT_BOOL("autoselen", node->autoselen);
        
        VTOY_JSON_FMT_SINT("autosel", node->autosel);
        VTOY_JSON_FMT_SINT("timeout", node->timeout);
        VTOY_JSON_FMT_KEY("list");
        VTOY_JSON_FMT_ARY_BEGIN();
        for (pathnode = node->list; pathnode; pathnode = pathnode->next)
        {
            VTOY_JSON_FMT_OBJ_BEGIN();
            VTOY_JSON_FMT_STRN("path", pathnode->path);
            valid = ventoy_is_file_exist("%s%s", g_cur_dir, pathnode->path);
            VTOY_JSON_FMT_SINT("valid", valid);
            VTOY_JSON_FMT_OBJ_ENDEX();
        }
        VTOY_JSON_FMT_ARY_ENDEX(); 
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_auto_install(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, auto_install);
    return 0;
}
static int ventoy_api_save_auto_install(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int id = -1;
    int cnt = 0;
    int index = 0;
    uint8_t timeouten = 0;
    uint8_t autoselen = 0;
    auto_install_node *node = NULL;
    data_auto_install *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    vtoy_json_get_int(json, "id", &id);
    vtoy_json_get_bool(json, "timeouten", &timeouten);
    vtoy_json_get_bool(json, "autoselen", &autoselen);
    
    data = g_data_auto_install + index;
    if (id >= 0)
    {
        for (node = data->list; node; node = node->next)
        {
            if (cnt == id)
            {
                node->timeouten = (int)timeouten;
                node->autoselen = (int)autoselen;
                VTOY_JSON_INT("timeout", node->timeout);
                VTOY_JSON_INT("autosel", node->autosel);
                break;
            }
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET); 
    return 0;
}
static int ventoy_api_auto_install_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    int type = 0;
    const char *path = NULL;
    auto_install_node *node = NULL;
    auto_install_node *cur = NULL;
    data_auto_install *data = NULL;
    VTOY_JSON *array = NULL;
    
    vtoy_json_get_int(json, "type", &type);
    vtoy_json_get_int(json, "index", &index);
    data = g_data_auto_install + index;
    array = vtoy_json_find_item(json, JSON_TYPE_ARRAY, "template");
    path = VTOY_JSON_STR_EX("path");
    if (path && array)
    {
        if (ventoy_is_real_exist_common(path, data->list, auto_install_node))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }     
    
        node = zalloc(sizeof(auto_install_node));
        if (node)
        {
            node->type = type;
            node->timeouten = 0;
            node->autoselen = 0;
            node->autosel = 1;
            node->timeout = 0;
            scnprintf(node->path, sizeof(node->path), "%s", path);
            node->list = ventoy_path_node_add_array(array);
            
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
static int ventoy_api_auto_install_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    auto_install_node *last = NULL;
    auto_install_node *next = NULL;
    auto_install_node *node = NULL;
    data_auto_install *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_auto_install + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            for (node = data->list; node; node = next)
            {
                next = node->next;
                ventoy_free_path_node_list(node->list);
                free(node);
            }
            data->list = NULL;
        }
        else
        {
            vtoy_list_del_ex(last, node, data->list, path, ventoy_free_path_node_list);            
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_auto_install_add_inner(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    const char *outpath = NULL;
    path_node *pcur = NULL;
    path_node *pnode = NULL;
    auto_install_node *node = NULL;
    data_auto_install *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_auto_install + index;
    path = VTOY_JSON_STR_EX("path");
    outpath = VTOY_JSON_STR_EX("outpath");
    if (path && outpath)
    {
        for (node = data->list; node; node = node->next)
        {
            if (strcmp(outpath, node->path) == 0)
            {
                pnode = zalloc(sizeof(path_node));
                if (pnode)
                {
                    scnprintf(pnode->path, sizeof(pnode->path), "%s", path);
                    vtoy_list_add(node->list, pcur, pnode);
                }
            
                break;
            }
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_auto_install_del_inner(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    const char *outpath = NULL;
    path_node *plast = NULL;
    path_node *pnode = NULL;
    auto_install_node *node = NULL;
    data_auto_install *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_auto_install + index;
    path = VTOY_JSON_STR_EX("path");
    outpath = VTOY_JSON_STR_EX("outpath");
    if (path && outpath)
    {
        for (node = data->list; node; node = node->next)
        {
            if (strcmp(outpath, node->path) == 0)
            {
                vtoy_list_del(plast, pnode, node->list, path);
                break;
            }
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
#if 0
#endif
void ventoy_data_default_persistence(data_persistence *data)
{
    memset(data, 0, sizeof(data_persistence));
}
int ventoy_data_cmp_persistence(data_persistence *data1, data_persistence *data2)
{
    persistence_node *list1 = NULL;
    persistence_node *list2 = NULL;
    if (NULL == data1->list && NULL == data2->list)
    {
        return 0;
    }
    else if (data1->list && data2->list)
    {
        list1 = data1->list;
        list2 = data2->list;
    
        while (list1 && list2)
        {
            if (list1->timeout != list2->timeout ||
                list1->autosel != list2->autosel ||
                strcmp(list1->path, list2->path))
            {
                return 1;
            }
            /* no need to compare auto install list with default */
            list1 = list1->next;
            list2 = list2->next;
        }
        if (list1 == NULL && list2 == NULL)
        {
            return 0;
        }
        return 1;
    }
    else
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_persistence(data_persistence *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    persistence_node *node = NULL;
    path_node *pathnode = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_ARY_BEGIN_N();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN_LN(L2);
        VTOY_JSON_FMT_STRN_PATH_LN(L3, "image", node->path);            
        VTOY_JSON_FMT_KEY_L(L3, "backend");
        VTOY_JSON_FMT_ARY_BEGIN_N();
        for (pathnode = node->list; pathnode; pathnode = pathnode->next)
        {
            VTOY_JSON_FMT_ITEM_PATH_LN(L4, pathnode->path);
        }
        VTOY_JSON_FMT_ARY_ENDEX_LN(L3);
        if (node->timeouten)
        {
            VTOY_JSON_FMT_SINT_LN(L3, "timeout", node->timeout);
        }
        if (node->autoselen)
        {
            VTOY_JSON_FMT_SINT_LN(L3, "autosel", node->autosel);                
        }
        VTOY_JSON_FMT_OBJ_ENDEX_LN(L2);
    }
    VTOY_JSON_FMT_ARY_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_persistence(data_persistence *data, char *buf, int buflen)
{
    int pos = 0;
    int valid = 0;
    persistence_node *node = NULL;
    path_node *pathnode = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_STRN("path", node->path);
        valid = ventoy_check_fuzzy_path(node->path, 1);            
        VTOY_JSON_FMT_SINT("valid", valid);
        VTOY_JSON_FMT_SINT("type", node->type);
        
        VTOY_JSON_FMT_BOOL("timeouten", node->timeouten);
        VTOY_JSON_FMT_BOOL("autoselen", node->autoselen);
        
        VTOY_JSON_FMT_SINT("autosel", node->autosel);
        VTOY_JSON_FMT_SINT("timeout", node->timeout);
        VTOY_JSON_FMT_KEY("list");
        VTOY_JSON_FMT_ARY_BEGIN();
        for (pathnode = node->list; pathnode; pathnode = pathnode->next)
        {
            VTOY_JSON_FMT_OBJ_BEGIN();
            VTOY_JSON_FMT_STRN("path", pathnode->path);
            valid = ventoy_is_file_exist("%s%s", g_cur_dir, pathnode->path);
            VTOY_JSON_FMT_SINT("valid", valid);
            VTOY_JSON_FMT_OBJ_ENDEX();
        }
        VTOY_JSON_FMT_ARY_ENDEX(); 
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_persistence(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, persistence);
    return 0;
}
static int ventoy_api_save_persistence(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int id = -1;
    int cnt = 0;
    int index = 0;
    uint8_t timeouten = 0;
    uint8_t autoselen = 0;
    persistence_node *node = NULL;
    data_persistence *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    vtoy_json_get_int(json, "id", &id);
    vtoy_json_get_bool(json, "timeouten", &timeouten);
    vtoy_json_get_bool(json, "autoselen", &autoselen);
    
    data = g_data_persistence + index;
    if (id >= 0)
    {
        for (node = data->list; node; node = node->next)
        {
            if (cnt == id)
            {
                node->timeouten = (int)timeouten;
                node->autoselen = (int)autoselen;
                VTOY_JSON_INT("timeout", node->timeout);
                VTOY_JSON_INT("autosel", node->autosel);
                break;
            }
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
static int ventoy_api_persistence_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    persistence_node *node = NULL;
    persistence_node *cur = NULL;
    data_persistence *data = NULL;
    VTOY_JSON *array = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_persistence + index;
    array = vtoy_json_find_item(json, JSON_TYPE_ARRAY, "backend");
    path = VTOY_JSON_STR_EX("path");
    if (path && array)
    {
        if (ventoy_is_real_exist_common(path, data->list, persistence_node))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }
        
        node = zalloc(sizeof(persistence_node));
        if (node)
        {
            node->timeouten = 0;
            node->autoselen = 0;
            node->autosel = 1;
            node->timeout = 0;
            scnprintf(node->path, sizeof(node->path), "%s", path);
            node->list = ventoy_path_node_add_array(array);
            
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET); 
    return 0;
}
static int ventoy_api_persistence_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    persistence_node *last = NULL;
    persistence_node *next = NULL;
    persistence_node *node = NULL;
    data_persistence *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_persistence + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            for (node = data->list; node; node = next)
            {
                next = node->next;
                ventoy_free_path_node_list(node->list);
                free(node);
            }
            data->list = NULL;
        }
        else
        {
            vtoy_list_del_ex(last, node, data->list, path, ventoy_free_path_node_list);            
        }    
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
static int ventoy_api_persistence_add_inner(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    const char *outpath = NULL;
    path_node *pcur = NULL;
    path_node *pnode = NULL;
    persistence_node *node = NULL;
    data_persistence *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_persistence + index;
    path = VTOY_JSON_STR_EX("path");
    outpath = VTOY_JSON_STR_EX("outpath");
    if (path && outpath)
    {
        for (node = data->list; node; node = node->next)
        {
            if (strcmp(outpath, node->path) == 0)
            {
                pnode = zalloc(sizeof(path_node));
                if (pnode)
                {
                    scnprintf(pnode->path, sizeof(pnode->path), "%s", path);
                    vtoy_list_add(node->list, pcur, pnode);
                }
            
                break;
            }
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_persistence_del_inner(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    const char *outpath = NULL;
    path_node *plast = NULL;
    path_node *pnode = NULL;
    persistence_node *node = NULL;
    data_persistence *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_persistence + index;
    path = VTOY_JSON_STR_EX("path");
    outpath = VTOY_JSON_STR_EX("outpath");
    if (path && outpath)
    {
        for (node = data->list; node; node = node->next)
        {
            if (strcmp(outpath, node->path) == 0)
            {
                vtoy_list_del(plast, pnode, node->list, path);
                break;
            }
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);  
    return 0;
}
#if 0
#endif
void ventoy_data_default_injection(data_injection *data)
{
    memset(data, 0, sizeof(data_injection));
}
int ventoy_data_cmp_injection(data_injection *data1, data_injection *data2)
{
    injection_node *list1 = NULL;
    injection_node *list2 = NULL;
    if (NULL == data1->list && NULL == data2->list)
    {
        return 0;
    }
    else if (data1->list && data2->list)
    {
        list1 = data1->list;
        list2 = data2->list;
    
        while (list1 && list2)
        {
            if ((list1->type != list2->type) ||
                strcmp(list1->path, list2->path) || 
                strcmp(list1->archive, list2->archive))
            {
                return 1;
            }
        
            list1 = list1->next;
            list2 = list2->next;
        }
        if (list1 == NULL && list2 == NULL)
        {
            return 0;
        }
        return 1;
    }
    else
    {
        return 1;
    }
    return 0;
}
int ventoy_data_save_injection(data_injection *data, const char *title, char *buf, int buflen)
{
    int pos = 0;
    injection_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_KEY_L(L1, title);
    VTOY_JSON_FMT_ARY_BEGIN_N();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN_LN(L2);
        if (node->type == 0)
        {
            VTOY_JSON_FMT_STRN_PATH_LN(L3, "image", node->path);            
        }
        else
        {
            VTOY_JSON_FMT_STRN_PATH_LN(L3, "parent", node->path);
        }
        VTOY_JSON_FMT_STRN_PATH_LN(L3, "archive", node->archive);
        
        VTOY_JSON_FMT_OBJ_ENDEX_LN(L2);
    }
    VTOY_JSON_FMT_ARY_ENDEX_LN(L1);
    VTOY_JSON_FMT_END(pos);
    return pos;
}
int ventoy_data_json_injection(data_injection *data, char *buf, int buflen)
{
    int pos = 0;
    int valid = 0;
    injection_node *node = NULL;
    
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_ARY_BEGIN();
    for (node = data->list; node; node = node->next)
    {
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_UINT("type", node->type);
        VTOY_JSON_FMT_STRN("path", node->path);       
        if (node->type == 0)
        {
            valid = ventoy_check_fuzzy_path(node->path, 1);
        }
        else
        {
            valid = ventoy_is_directory_exist("%s%s", g_cur_dir, node->path);
        }
        VTOY_JSON_FMT_SINT("valid", valid);
        
        VTOY_JSON_FMT_STRN("archive", node->archive);
        valid = ventoy_is_file_exist("%s%s", g_cur_dir, node->archive);
        VTOY_JSON_FMT_SINT("archive_valid", valid);
        
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    VTOY_JSON_FMT_ARY_END();
    VTOY_JSON_FMT_END(pos);
    return pos;
}
static int ventoy_api_get_injection(struct mg_connection *conn, VTOY_JSON *json)
{
    api_get_func(conn, json, injection);
    return 0;
}
static int ventoy_api_save_injection(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_injection_add(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    int type = 0;
    const char *path = NULL;
    const char *archive = NULL;
    injection_node *node = NULL;
    injection_node *cur = NULL;
    data_injection *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_injection + index;
    vtoy_json_get_int(json, "type", &type);
    path = VTOY_JSON_STR_EX("path");
    archive = VTOY_JSON_STR_EX("archive");
    if (path && archive)
    {
        if (ventoy_is_real_exist_common(path, data->list, injection_node))
        {
            ventoy_json_result(conn, VTOY_JSON_DUPLICATE);
            return 0;
        }
    
        node = zalloc(sizeof(injection_node));
        if (node)
        {
            node->type = type;
        
            scnprintf(node->path, sizeof(node->path), "%s", path);
            scnprintf(node->archive, sizeof(node->archive), "%s", archive);
            
            vtoy_list_add(data->list, cur, node);
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
static int ventoy_api_injection_del(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int index = 0;
    const char *path = NULL;
    injection_node *last = NULL;
    injection_node *node = NULL;
    data_injection *data = NULL;
    
    vtoy_json_get_int(json, "index", &index);
    data = g_data_injection + index;
    path = VTOY_JSON_STR_EX("path");
    if (path)
    {
        if (strcmp(path, VTOY_DEL_ALL_PATH) == 0)
        {
            vtoy_list_free(injection_node, data->list);
        }
        else
        {
            vtoy_list_del(last, node, data->list, path);            
        }
    }
    ret = ventoy_data_save_all();
    ventoy_json_result(conn, ret == 0 ? VTOY_JSON_SUCCESS_RET : VTOY_JSON_FAILED_RET);   
    return 0;
}
#if 0
#endif
static int ventoy_api_preview_json(struct mg_connection *conn, VTOY_JSON *json)
{
    int i = 0;
    int pos = 0;
    int len = 0;
    int utf16enclen = 0;
    char *encodebuf = NULL;
    unsigned short *utf16buf = NULL;
    
    (void)json;
    /* We can not use json directly, because it will be formated in the JS. */
    len = ventoy_data_real_save_all(0);
    utf16buf = (unsigned short *)malloc(2 * len + 16);    
    if (!utf16buf)
    {
        goto json;
    }
    utf16enclen = (int)utf8_to_utf16((unsigned char *)JSON_SAVE_BUFFER, len, utf16buf, len + 2);
    encodebuf = (char *)malloc(utf16enclen * 4 + 16);
    if (!encodebuf)
    {
        goto json;
    }
    for (i = 0; i < utf16enclen; i++)
    {
        scnprintf(encodebuf + i * 4, 5, "%04X", utf16buf[i]);
    }
json:
    VTOY_JSON_FMT_BEGIN(pos, JSON_BUFFER, JSON_BUF_MAX);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_STRN("json", (encodebuf ? encodebuf : ""));
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    CHECK_FREE(encodebuf);
    CHECK_FREE(utf16buf);
    ventoy_json_buffer(conn, JSON_BUFFER, pos);
    return 0;
}
#if 0
#endif
int ventoy_data_save_all(void)
{
    ventoy_set_writeback_event();
    return 0;
}
int ventoy_data_real_save_all(int apilock)
{
    int i = 0;
    int pos = 0;
    char title[64];
    if (apilock)
    {
        pthread_mutex_lock(&g_api_mutex);        
    }
    ssprintf(pos, JSON_SAVE_BUFFER, JSON_BUF_MAX, "{\n");
    ventoy_save_plug(control);
    ventoy_save_plug(theme);
    ventoy_save_plug(menu_alias);
    ventoy_save_plug(menu_tip);
    ventoy_save_plug(menu_class);
    ventoy_save_plug(auto_install);
    ventoy_save_plug(persistence);
    ventoy_save_plug(injection);
    ventoy_save_plug(conf_replace);
    ventoy_save_plug(password);
    ventoy_save_plug(image_list);
    ventoy_save_plug(auto_memdisk);
    ventoy_save_plug(dud);
    
    if (JSON_SAVE_BUFFER[pos - 1] == '\n' && JSON_SAVE_BUFFER[pos - 2] == ',')
    {
        JSON_SAVE_BUFFER[pos - 2] = '\n';
        pos--;
    }
    ssprintf(pos, JSON_SAVE_BUFFER, JSON_BUF_MAX, "}\n");
    if (apilock)
    {
        pthread_mutex_unlock(&g_api_mutex);        
    }
    return pos;
}
int ventoy_http_writeback(void)
{
    int ret;
    int pos;
    char filename[128];
    ventoy_get_json_path(filename, NULL);
    pos = ventoy_data_real_save_all(1);
        
    #ifdef VENTOY_SIM
    printf("%s", JSON_SAVE_BUFFER);
    #endif
    
    ret = ventoy_write_buf_to_file(filename, JSON_SAVE_BUFFER, pos);
    if (ret)
    {
        vlog("Failed to write ventoy.json file.\n");
        g_sysinfo.config_save_error = 1;
    }
    return 0;
}
static JSON_CB g_ventoy_json_cb[] = 
{
    { "sysinfo",        ventoy_api_sysinfo            },    
    { "handshake",      ventoy_api_handshake          },    
    { "check_path",     ventoy_api_check_exist        },    
    { "check_path2",    ventoy_api_check_exist2       },    
    { "check_fuzzy",    ventoy_api_check_fuzzy        },
    
    { "device_info",    ventoy_api_device_info        },    
    
    { "get_control",    ventoy_api_get_control        },    
    { "save_control",   ventoy_api_save_control       },  
    
    { "get_theme",      ventoy_api_get_theme          },    
    { "save_theme",     ventoy_api_save_theme         },    
    { "theme_add_file", ventoy_api_theme_add_file     },    
    { "theme_del_file", ventoy_api_theme_del_file     },    
    { "theme_add_font", ventoy_api_theme_add_font     },    
    { "theme_del_font", ventoy_api_theme_del_font     },
    
    { "get_alias",      ventoy_api_get_alias          },
    { "save_alias",     ventoy_api_save_alias         },   
    { "alias_add",      ventoy_api_alias_add          },
    { "alias_del",      ventoy_api_alias_del          },
    
    { "get_tip",        ventoy_api_get_tip            },
    { "save_tip",       ventoy_api_save_tip           },   
    { "tip_add",        ventoy_api_tip_add            },
    { "tip_del",        ventoy_api_tip_del            },
    
    { "get_class",      ventoy_api_get_class          },
    { "save_class",     ventoy_api_save_class         },   
    { "class_add",      ventoy_api_class_add          },
    { "class_del",      ventoy_api_class_del          },
    
    { "get_auto_memdisk",  ventoy_api_get_auto_memdisk  },
    { "save_auto_memdisk", ventoy_api_save_auto_memdisk },   
    { "auto_memdisk_add",  ventoy_api_auto_memdisk_add  },
    { "auto_memdisk_del",  ventoy_api_auto_memdisk_del  },
    
    { "get_image_list",  ventoy_api_get_image_list  },
    { "save_image_list", ventoy_api_save_image_list },
    { "image_list_add",  ventoy_api_image_list_add  },
    { "image_list_del",  ventoy_api_image_list_del  },
    { "get_conf_replace",      ventoy_api_get_conf_replace      },
    { "save_conf_replace",     ventoy_api_save_conf_replace     },   
    { "conf_replace_add",      ventoy_api_conf_replace_add      },
    { "conf_replace_del",      ventoy_api_conf_replace_del      },
    
    { "get_dud",            ventoy_api_get_dud      },
    { "save_dud",           ventoy_api_save_dud     },   
    { "dud_add",            ventoy_api_dud_add      },
    { "dud_del",            ventoy_api_dud_del      },
    { "dud_add_inner",      ventoy_api_dud_add_inner      },
    { "dud_del_inner",      ventoy_api_dud_del_inner      },
    
    { "get_auto_install",            ventoy_api_get_auto_install      },
    { "save_auto_install",           ventoy_api_save_auto_install     },   
    { "auto_install_add",            ventoy_api_auto_install_add      },
    { "auto_install_del",            ventoy_api_auto_install_del      },
    { "auto_install_add_inner",      ventoy_api_auto_install_add_inner      },
    { "auto_install_del_inner",      ventoy_api_auto_install_del_inner      },
    
    { "get_persistence",            ventoy_api_get_persistence      },
    { "save_persistence",           ventoy_api_save_persistence     },   
    { "persistence_add",            ventoy_api_persistence_add      },
    { "persistence_del",            ventoy_api_persistence_del      },
    { "persistence_add_inner",      ventoy_api_persistence_add_inner      },
    { "persistence_del_inner",      ventoy_api_persistence_del_inner      },
    
    { "get_password",      ventoy_api_get_password      },
    { "save_password",     ventoy_api_save_password     },   
    { "password_add",      ventoy_api_password_add      },
    { "password_del",      ventoy_api_password_del      },
    
    { "get_injection",      ventoy_api_get_injection     },
    { "save_injection",     ventoy_api_save_injection     },   
    { "injection_add",      ventoy_api_injection_add      },
    { "injection_del",      ventoy_api_injection_del      },
    { "preview_json",       ventoy_api_preview_json       },
    
};
static int ventoy_json_handler(struct mg_connection *conn, VTOY_JSON *json, char *jsonstr)
{
    int i;
    const char *method = NULL;
    method = vtoy_json_get_string_ex(json, "method");
    if (!method)
    {
        ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
        return 0;
    }
    if (strcmp(method, "handshake") == 0)
    {
        ventoy_api_handshake(conn, json);
        return 0;
    }
    for (i = 0; i < (int)(sizeof(g_ventoy_json_cb) / sizeof(g_ventoy_json_cb[0])); i++)
    {
        if (strcmp(method, g_ventoy_json_cb[i].method) == 0)
        {
            g_ventoy_json_cb[i].callback(conn, json);
            break;
        }
    }
    return 0;
}
static int ventoy_request_handler(struct mg_connection *conn)
{
    int post_data_len;
    int post_buf_len;
    VTOY_JSON *json = NULL;
    char *post_data_buf = NULL;
    const struct mg_request_info *ri = NULL;
    char stack_buf[512];
    
    ri = mg_get_request_info(conn);    
    if (strcmp(ri->uri, "/vtoy/json") == 0)
    {
        if (ri->content_length > 500)
        {
            post_data_buf = malloc((int)(ri->content_length + 4));
            post_buf_len  = (int)(ri->content_length + 1);
        }
        else
        {
            post_data_buf = stack_buf;
            post_buf_len = sizeof(stack_buf);
        }
        
        post_data_len = mg_read(conn, post_data_buf, post_buf_len);
        post_data_buf[post_data_len] = 0;
        json = vtoy_json_create();
        if (JSON_SUCCESS == vtoy_json_parse(json, post_data_buf))
        {
            pthread_mutex_lock(&g_api_mutex);
            ventoy_json_handler(conn, json->pstChild, post_data_buf);
            pthread_mutex_unlock(&g_api_mutex);
        }
        else
        {
            ventoy_json_result(conn, VTOY_JSON_INVALID_RET);
        }
        vtoy_json_destroy(json);
        if (post_data_buf != stack_buf)
        {
            free(post_data_buf);
        }
        return 1;
    }
    else
    {
        return 0;
    }
}
const char *ventoy_web_openfile(const struct mg_connection *conn, const char *path, size_t *data_len)
{
    ventoy_file *node = NULL;
    (void)conn;
    if (!path)
    {
        return NULL;
    }
    
    node = ventoy_tar_find_file(path);
    if (node)
    {
        *data_len = node->size;
        return node->addr;
    }
    else
    {
        return NULL;
    }
}
#if 0
#endif
static int ventoy_parse_control(VTOY_JSON *json, void *p)
{
    int i;
    VTOY_JSON *node = NULL;
    VTOY_JSON *child = NULL;
    data_control *data = (data_control *)p;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        return 0;
    }
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType == JSON_TYPE_OBJECT)
        {
            child = node->pstChild;
            
            if (child->enDataType != JSON_TYPE_STRING)
            {
                continue;
            }
            if (strcmp(child->pcName, "VTOY_DEFAULT_MENU_MODE") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->default_menu_mode);
            }
            else if (strcmp(child->pcName, "VTOY_WIN11_BYPASS_CHECK") == 0)
            {
                CONTROL_PARSE_INT_DEF_1(child, data->win11_bypass_check);
            }
            else if (strcmp(child->pcName, "VTOY_WIN11_BYPASS_NRO") == 0)
            {
                CONTROL_PARSE_INT_DEF_1(child, data->win11_bypass_nro);
            }
            else if (strcmp(child->pcName, "VTOY_LINUX_REMOUNT") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->linux_remount);
            }
            else if (strcmp(child->pcName, "VTOY_SECONDARY_BOOT_MENU") == 0)
            {
                CONTROL_PARSE_INT_DEF_1(child, data->secondary_menu);
            }
            else if (strcmp(child->pcName, "VTOY_SHOW_PASSWORD_ASTERISK") == 0)
            {
                CONTROL_PARSE_INT_DEF_1(child, data->password_asterisk);
            }
            else if (strcmp(child->pcName, "VTOY_TREE_VIEW_MENU_STYLE") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->treeview_style);
            }
            else if (strcmp(child->pcName, "VTOY_FILT_DOT_UNDERSCORE_FILE") == 0)
            {
                CONTROL_PARSE_INT_DEF_1(child, data->filter_dot_underscore);
            }
            else if (strcmp(child->pcName, "VTOY_SORT_CASE_SENSITIVE") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->sort_casesensitive);
            }
            else if (strcmp(child->pcName, "VTOY_MAX_SEARCH_LEVEL") == 0)
            {
                if (strcmp(child->unData.pcStrVal, "max") == 0)
                {
                    data->max_search_level = -1;
                }
                else
                {
                    data->max_search_level = (int)strtol(child->unData.pcStrVal, NULL, 10);
                }
            }
            else if (strcmp(child->pcName, "VTOY_DEFAULT_SEARCH_ROOT") == 0)
            {
                strlcpy(data->default_search_root, child->unData.pcStrVal);
            }
            else if (strcmp(child->pcName, "VTOY_DEFAULT_IMAGE") == 0)
            {
                strlcpy(data->default_image, child->unData.pcStrVal);
            }
            else if (strcmp(child->pcName, "VTOY_DEFAULT_KBD_LAYOUT") == 0)
            {
                for (i = 0; g_ventoy_kbd_layout[i]; i++)
                {
                    if (strcmp(child->unData.pcStrVal, g_ventoy_kbd_layout[i]) == 0)
                    {
                        strlcpy(data->default_kbd_layout, child->unData.pcStrVal);
                        break;
                    }
                }
            }
            else if (strcmp(child->pcName, "VTOY_MENU_LANGUAGE") == 0)
            {
                for (i = 0; g_ventoy_menu_lang[i][0]; i++)
                {
                    if (strcmp(child->unData.pcStrVal, g_ventoy_menu_lang[i]) == 0)
                    {
                        strlcpy(data->menu_language, child->unData.pcStrVal);
                        break;
                    }
                }
            }
            else if (strcmp(child->pcName, "VTOY_MENU_TIMEOUT") == 0)
            {
                data->menu_timeout = (int)strtol(child->unData.pcStrVal, NULL, 10);
            }
            else if (strcmp(child->pcName, "VTOY_SECONDARY_TIMEOUT") == 0)
            {
                data->secondary_menu_timeout = (int)strtol(child->unData.pcStrVal, NULL, 10);
            }
            else if (strcmp(child->pcName, "VTOY_VHD_NO_WARNING") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->vhd_no_warning);
            }
            else if (strcmp(child->pcName, "VTOY_FILE_FLT_ISO") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->filter_iso);
            }
            else if (strcmp(child->pcName, "VTOY_FILE_FLT_IMG") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->filter_img);
            }
            else if (strcmp(child->pcName, "VTOY_FILE_FLT_EFI") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->filter_efi);
            }
            else if (strcmp(child->pcName, "VTOY_FILE_FLT_WIM") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->filter_wim);
            }
            else if (strcmp(child->pcName, "VTOY_FILE_FLT_VHD") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->filter_vhd);
            }
            else if (strcmp(child->pcName, "VTOY_FILE_FLT_VTOY") == 0)
            {
                CONTROL_PARSE_INT_DEF_0(child, data->filter_vtoy);
            }
            
        }
    }
    return 0;
}
static int ventoy_parse_theme(VTOY_JSON *json, void *p)
{
    const char *dismode = NULL;
    VTOY_JSON *child = NULL;
    VTOY_JSON *node = NULL;
    path_node *tail = NULL;
    path_node *pnode = NULL;
    data_theme *data = (data_theme *)p;
    if (json->enDataType != JSON_TYPE_OBJECT)
    {
        return 0;
    }
    child = json->pstChild;
    dismode = vtoy_json_get_string_ex(child, "display_mode");
    vtoy_json_get_string(child, "ventoy_left", sizeof(data->ventoy_left), data->ventoy_left);
    vtoy_json_get_string(child, "ventoy_top", sizeof(data->ventoy_top), data->ventoy_top);
    vtoy_json_get_string(child, "ventoy_color", sizeof(data->ventoy_color), data->ventoy_color);
    
    vtoy_json_get_int(child, "default_file", &(data->default_file));    
    vtoy_json_get_int(child, "resolution_fit", &(data->resolution_fit));    
    vtoy_json_get_string(child, "gfxmode", sizeof(data->gfxmode), data->gfxmode);
    vtoy_json_get_string(child, "serial_param", sizeof(data->serial_param), data->serial_param);
    if (dismode)
    {
        if (strcmp(dismode, "CLI") == 0)
        {
            data->display_mode = display_mode_cli;
        }
        else if (strcmp(dismode, "serial") == 0)
        {
            data->display_mode = display_mode_serial;
        }
        else if (strcmp(dismode, "serial_console") == 0)
        {
            data->display_mode = display_mode_ser_console;
        }
        else
        {
            data->display_mode = display_mode_gui;
        }
    }
    node = vtoy_json_find_item(child, JSON_TYPE_STRING, "file");
    if (node)
    {
        data->default_file = 0;
        data->resolution_fit = 0;
        pnode = zalloc(sizeof(path_node));
        if (pnode)
        {
            strlcpy(pnode->path, node->unData.pcStrVal);
            data->filelist = pnode;
        }
    }
    else
    {
        node = vtoy_json_find_item(child, JSON_TYPE_ARRAY, "file");
        if (node)
        {
            for (node = node->pstChild; node; node = node->pstNext)
            {
                if (node->enDataType == JSON_TYPE_STRING)
                {
                    pnode = zalloc(sizeof(path_node));
                    if (pnode)
                    {
                        strlcpy(pnode->path, node->unData.pcStrVal);
                        if (data->filelist)
                        {
                            tail->next = pnode;
                            tail = pnode;
                        }
                        else
                        {
                            data->filelist = tail = pnode;
                        }
                    }
                }
            }
        }
    }
    
    node = vtoy_json_find_item(child, JSON_TYPE_ARRAY, "fonts");
    if (node)
    {
        for (node = node->pstChild; node; node = node->pstNext)
        {
            if (node->enDataType == JSON_TYPE_STRING)
            {
                pnode = zalloc(sizeof(path_node));
                if (pnode)
                {
                    strlcpy(pnode->path, node->unData.pcStrVal);
                    if (data->fontslist)
                    {
                        tail->next = pnode;
                        tail = pnode;
                    }
                    else
                    {
                        data->fontslist = tail = pnode;
                    }
                }
            }
        }
    }
    return 0;
}
static int ventoy_parse_menu_alias(VTOY_JSON *json, void *p)
{
    int type;
    const char *path = NULL;
    const char *alias = NULL;
    data_alias *data = (data_alias *)p;
    data_alias_node *tail = NULL;
    data_alias_node *pnode = NULL;
    VTOY_JSON *node = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        return 0;
    }
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType != JSON_TYPE_OBJECT)
        {
            continue;
        }
        type = path_type_file;
        path = vtoy_json_get_string_ex(node->pstChild, "image");
        if (!path)
        {
            path = vtoy_json_get_string_ex(node->pstChild, "dir");
            type = path_type_dir;
        }
        alias = vtoy_json_get_string_ex(node->pstChild, "alias");
        if (path && alias)
        {
            pnode = zalloc(sizeof(data_alias_node));
            if (pnode)
            {
                pnode->type = type;
                strlcpy(pnode->path, path);
                strlcpy(pnode->alias, alias);
                
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
        }
    }    
    return 0;
}
static int ventoy_parse_menu_tip(VTOY_JSON *json, void *p)
{
    int type;
    const char *path = NULL;
    const char *tip = NULL;
    data_tip *data = (data_tip *)p;
    data_tip_node *tail = NULL;
    data_tip_node *pnode = NULL;
    VTOY_JSON *node = NULL;
    VTOY_JSON *tips = NULL;
    if (json->enDataType != JSON_TYPE_OBJECT)
    {
        return 0;
    }
    vtoy_json_get_string(json->pstChild, "left", sizeof(data->left), data->left);
    vtoy_json_get_string(json->pstChild, "top", sizeof(data->top), data->top);
    vtoy_json_get_string(json->pstChild, "color", sizeof(data->color), data->color);
    tips = vtoy_json_find_item(json->pstChild, JSON_TYPE_ARRAY, "tips");
    if (!tips)
    {
        return 0;
    }
    for (node = tips->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType != JSON_TYPE_OBJECT)
        {
            continue;
        }
        type = path_type_file;
        path = vtoy_json_get_string_ex(node->pstChild, "image");
        if (!path)
        {
            path = vtoy_json_get_string_ex(node->pstChild, "dir");
            type = path_type_dir;
        }
        tip = vtoy_json_get_string_ex(node->pstChild, "tip");
        if (path && tip)
        {
            pnode = zalloc(sizeof(data_tip_node));
            if (pnode)
            {
                pnode->type = type;
                strlcpy(pnode->path, path);
                strlcpy(pnode->tip, tip);
                
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
        }
    }    
    return 0;
}
static int ventoy_parse_menu_class(VTOY_JSON *json, void *p)
{
    int type;
    const char *path = NULL;
    const char *class = NULL;
    data_class *data = (data_class *)p;
    data_class_node *tail = NULL;
    data_class_node *pnode = NULL;
    VTOY_JSON *node = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        return 0;
    }
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType != JSON_TYPE_OBJECT)
        {
            continue;
        }
        type = class_type_key;
        path = vtoy_json_get_string_ex(node->pstChild, "key");
        if (!path)
        {
            type = class_type_dir;
            path = vtoy_json_get_string_ex(node->pstChild, "dir");
            if (!path)
            {
                type = class_type_parent;
                path = vtoy_json_get_string_ex(node->pstChild, "parent");
            }
        }
        class = vtoy_json_get_string_ex(node->pstChild, "class");
        if (path && class)
        {
            pnode = zalloc(sizeof(data_class_node));
            if (pnode)
            {
                pnode->type = type;
                strlcpy(pnode->path, path);
                strlcpy(pnode->class, class);
                
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
        }
    }    
    return 0;
}
static int ventoy_parse_auto_install(VTOY_JSON *json, void *p)
{
    int type;
    int count;
    int timeout;
    int timeouten;
    int autosel;
    int autoselen;
    const char *path = NULL;
    const char *file = NULL;
    data_auto_install *data = (data_auto_install *)p;
    auto_install_node *tail = NULL;
    auto_install_node *pnode = NULL;
    path_node *pathnode = NULL;
    path_node *pathtail = NULL;
    VTOY_JSON *node = NULL;
    VTOY_JSON *filelist = NULL;
    VTOY_JSON *filenode = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        return 0;
    }
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType != JSON_TYPE_OBJECT)
        {
            continue;
        }
        type = 0;
        path = vtoy_json_get_string_ex(node->pstChild, "image");
        if (!path)
        {
            path = vtoy_json_get_string_ex(node->pstChild, "parent");
            type = 1;
        }
        if (!path)
        {
            continue;
        }
                
        file = vtoy_json_get_string_ex(node->pstChild, "template");
        if (file)
        {
            pnode = zalloc(sizeof(auto_install_node));
            if (pnode)
            {
                pnode->type = type;
                pnode->autosel = 1;
                strlcpy(pnode->path, path);
                pathnode = zalloc(sizeof(path_node));
                if (pathnode)
                {
                    strlcpy(pathnode->path, file);
                    pnode->list = pathnode;
                }
                else
                {
                    free(pnode);
                }
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
            continue;
        }
        timeouten = autoselen = 0;
        if (JSON_SUCCESS == vtoy_json_get_int(node->pstChild, "timeout", &timeout))
        {
            timeouten = 1;
        }
        if (JSON_SUCCESS == vtoy_json_get_int(node->pstChild, "autosel", &autosel))
        {
            autoselen = 1;
        }
        filelist = vtoy_json_find_item(node->pstChild, JSON_TYPE_ARRAY, "template");
        if (!filelist)
        {
            continue;
        }
        pnode = zalloc(sizeof(auto_install_node));
        if (!pnode)
        {
            continue;
        }
        pnode->type = type;
        pnode->autoselen = autoselen;
        pnode->timeouten = timeouten;
        pnode->timeout = timeout;
        pnode->autosel = autosel;
        strlcpy(pnode->path, path);
        count = 0;
        for (filenode = filelist->pstChild; filenode; filenode = filenode->pstNext)
        {
            if (filenode->enDataType != JSON_TYPE_STRING)
            {
                continue;
            }
            pathnode = zalloc(sizeof(path_node));
            if (pathnode)
            {
                count++;
                strlcpy(pathnode->path, filenode->unData.pcStrVal);
                if (pnode->list)
                {
                    pathtail->next = pathnode;
                    pathtail = pathnode;
                }
                else
                {
                    pnode->list = pathtail = pathnode;
                }                
            }
        }
        if (count == 0)
        {
            free(pnode);
        }
        else
        {
            if (pnode->autoselen && pnode->autosel > count)
            {
                pnode->autosel = 1;
            }
            if (data->list)
            {
                tail->next = pnode;
                tail = pnode;
            }
            else
            {
                data->list = tail = pnode;
            }
        }
    }
    return 0;
}
static int ventoy_parse_persistence(VTOY_JSON *json, void *p)
{
    int count;
    int timeout;
    int timeouten;
    int autosel;
    int autoselen;
    const char *path = NULL;
    const char *file = NULL;
    data_persistence *data = (data_persistence *)p;
    persistence_node *tail = NULL;
    persistence_node *pnode = NULL;
    path_node *pathnode = NULL;
    path_node *pathtail = NULL;
    VTOY_JSON *node = NULL;
    VTOY_JSON *filelist = NULL;
    VTOY_JSON *filenode = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        return 0;
    }
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType != JSON_TYPE_OBJECT)
        {
            continue;
        }
        path = vtoy_json_get_string_ex(node->pstChild, "image");
        if (!path)
        {
            continue;
        }
                
        file = vtoy_json_get_string_ex(node->pstChild, "backend");
        if (file)
        {
            pnode = zalloc(sizeof(persistence_node));
            if (pnode)
            {
                pnode->type = 0;
                pnode->autosel = 1;
                strlcpy(pnode->path, path);
                pathnode = zalloc(sizeof(path_node));
                if (pathnode)
                {
                    strlcpy(pathnode->path, file);
                    pnode->list = pathnode;
                }
                else
                {
                    free(pnode);
                }
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
            continue;
        }
        timeouten = autoselen = 0;
        if (JSON_SUCCESS == vtoy_json_get_int(node->pstChild, "timeout", &timeout))
        {
            timeouten = 1;
        }
        if (JSON_SUCCESS == vtoy_json_get_int(node->pstChild, "autosel", &autosel))
        {
            autoselen = 1;
        }
        filelist = vtoy_json_find_item(node->pstChild, JSON_TYPE_ARRAY, "backend");
        if (!filelist)
        {
            continue;
        }
        pnode = zalloc(sizeof(persistence_node));
        if (!pnode)
        {
            continue;
        }
        pnode->type = 0;
        pnode->autoselen = autoselen;
        pnode->timeouten = timeouten;
        pnode->timeout = timeout;
        pnode->autosel = autosel;
        strlcpy(pnode->path, path);
        count = 0;
        for (filenode = filelist->pstChild; filenode; filenode = filenode->pstNext)
        {
            if (filenode->enDataType != JSON_TYPE_STRING)
            {
                continue;
            }
            pathnode = zalloc(sizeof(path_node));
            if (pathnode)
            {
                count++;
                strlcpy(pathnode->path, filenode->unData.pcStrVal);
                if (pnode->list)
                {
                    pathtail->next = pathnode;
                    pathtail = pathnode;
                }
                else
                {
                    pnode->list = pathtail = pathnode;
                }                
            }
        }
        if (count == 0)
        {
            free(pnode);
        }
        else
        {
            if (pnode->autoselen && pnode->autosel > count)
            {
                pnode->autosel = 1;
            }
            if (data->list)
            {
                tail->next = pnode;
                tail = pnode;
            }
            else
            {
                data->list = tail = pnode;
            }
        }
    }
    return 0;
}
static int ventoy_parse_injection(VTOY_JSON *json, void *p)
{
    int type;
    const char *path = NULL;
    const char *archive = NULL;
    data_injection *data = (data_injection *)p;
    injection_node *tail = NULL;
    injection_node *pnode = NULL;
    VTOY_JSON *node = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        return 0;
    }
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType != JSON_TYPE_OBJECT)
        {
            continue;
        }
        type = 0;
        path = vtoy_json_get_string_ex(node->pstChild, "image");
        if (!path)
        {
            path = vtoy_json_get_string_ex(node->pstChild, "parent");
            type = 1;
        }
        archive = vtoy_json_get_string_ex(node->pstChild, "archive");
        if (path && archive)
        {
            pnode = zalloc(sizeof(injection_node));
            if (pnode)
            {
                pnode->type = type;
                strlcpy(pnode->path, path);
                strlcpy(pnode->archive, archive);
                
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
        }
    }    
    return 0;
}
static int ventoy_parse_conf_replace(VTOY_JSON *json, void *p)
{
    int img = 0;
    const char *path = NULL;
    const char *org = NULL;
    const char *new = NULL;
    data_conf_replace *data = (data_conf_replace *)p;
    conf_replace_node *tail = NULL;
    conf_replace_node *pnode = NULL;
    VTOY_JSON *node = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        return 0;
    }
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType != JSON_TYPE_OBJECT)
        {
            continue;
        }
        path = vtoy_json_get_string_ex(node->pstChild, "iso");
        org = vtoy_json_get_string_ex(node->pstChild, "org");
        new = vtoy_json_get_string_ex(node->pstChild, "new");
        img = 0;
        vtoy_json_get_int(node->pstChild, "img", &img);
        if (path && org && new)
        {
            pnode = zalloc(sizeof(conf_replace_node));
            if (pnode)
            {
                strlcpy(pnode->path, path);
                strlcpy(pnode->org, org);
                strlcpy(pnode->new, new);
                if (img == 1)
                {
                    pnode->image = img;                    
                }
                
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
        }
    }    
    return 0;
}
static int ventoy_parse_password(VTOY_JSON *json, void *p)
{
    int type;
    const char *bootpwd = NULL;
    const char *isopwd= NULL;
    const char *wimpwd= NULL;
    const char *imgpwd= NULL;
    const char *efipwd= NULL;
    const char *vhdpwd= NULL;
    const char *vtoypwd= NULL;
    const char *path = NULL;
    const char *pwd = NULL;
    data_password *data = (data_password *)p;
    menu_password *tail = NULL;
    menu_password *pnode = NULL;
    VTOY_JSON *node = NULL;
    VTOY_JSON *menupwd = NULL;
    if (json->enDataType != JSON_TYPE_OBJECT)
    {
        return 0;
    }
    bootpwd = vtoy_json_get_string_ex(json->pstChild, "bootpwd");
    isopwd = vtoy_json_get_string_ex(json->pstChild, "isopwd");
    wimpwd = vtoy_json_get_string_ex(json->pstChild, "wimpwd");
    imgpwd = vtoy_json_get_string_ex(json->pstChild, "imgpwd");
    efipwd = vtoy_json_get_string_ex(json->pstChild, "efipwd");
    vhdpwd = vtoy_json_get_string_ex(json->pstChild, "vhdpwd");
    vtoypwd = vtoy_json_get_string_ex(json->pstChild, "vtoypwd");
    if (bootpwd) strlcpy(data->bootpwd, bootpwd);
    if (isopwd) strlcpy(data->isopwd, isopwd);
    if (wimpwd) strlcpy(data->wimpwd, wimpwd);
    if (imgpwd) strlcpy(data->imgpwd, imgpwd);
    if (efipwd) strlcpy(data->efipwd, efipwd);
    if (vhdpwd) strlcpy(data->vhdpwd, vhdpwd);
    if (vtoypwd) strlcpy(data->vtoypwd, vtoypwd);
    
    
    menupwd = vtoy_json_find_item(json->pstChild, JSON_TYPE_ARRAY, "menupwd");
    if (!menupwd)
    {
        return 0;
    }
    for (node = menupwd->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType != JSON_TYPE_OBJECT)
        {
            continue;
        }
        type = 0;
        path = vtoy_json_get_string_ex(node->pstChild, "file");
        if (!path)
        {
            path = vtoy_json_get_string_ex(node->pstChild, "parent");
            type = 1;
        }
        pwd = vtoy_json_get_string_ex(node->pstChild, "pwd");
        if (path && pwd)
        {
            pnode = zalloc(sizeof(menu_password));
            if (pnode)
            {
                pnode->type = type;
                strlcpy(pnode->path, path);
                strlcpy(pnode->pwd, pwd);
                
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
        }
    }    
    return 0;
}
static int ventoy_parse_image_list_real(VTOY_JSON *json, int type, void *p)
{
    VTOY_JSON *node = NULL;
    data_image_list *data = (data_image_list *)p;
    path_node *tail = NULL;
    path_node *pnode = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        return 0;
    }
    data->type = type;
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType == JSON_TYPE_STRING)
        {
            pnode = zalloc(sizeof(path_node));
            if (pnode)
            {
                strlcpy(pnode->path, node->unData.pcStrVal);
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
        }
    }
    return 0;
}
static int ventoy_parse_image_blacklist(VTOY_JSON *json, void *p)
{
     return ventoy_parse_image_list_real(json, 1, p);
}
static int ventoy_parse_image_list(VTOY_JSON *json, void *p)
{
    return ventoy_parse_image_list_real(json, 0, p);
}
static int ventoy_parse_auto_memdisk(VTOY_JSON *json, void *p)
{
    VTOY_JSON *node = NULL;
    data_auto_memdisk *data = (data_auto_memdisk *)p;
    path_node *tail = NULL;
    path_node *pnode = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        return 0;
    }
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType == JSON_TYPE_STRING)
        {
            pnode = zalloc(sizeof(path_node));
            if (pnode)
            {
                strlcpy(pnode->path, node->unData.pcStrVal);
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
        }
    }
    return 0;
}
static int ventoy_parse_dud(VTOY_JSON *json, void *p)
{
    int count = 0;
    const char *path = NULL;
    const char *file = NULL;
    data_dud *data = (data_dud *)p;
    dud_node *tail = NULL;
    dud_node *pnode = NULL;
    path_node *pathnode = NULL;
    path_node *pathtail = NULL;
    VTOY_JSON *node = NULL;
    VTOY_JSON *filelist = NULL;
    VTOY_JSON *filenode = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        return 0;
    }
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (node->enDataType != JSON_TYPE_OBJECT)
        {
            continue;
        }
        path = vtoy_json_get_string_ex(node->pstChild, "image");
        if (!path)
        {
            continue;
        }
                
        file = vtoy_json_get_string_ex(node->pstChild, "dud");
        if (file)
        {
            pnode = zalloc(sizeof(dud_node));
            if (pnode)
            {
                strlcpy(pnode->path, path);
                pathnode = zalloc(sizeof(path_node));
                if (pathnode)
                {
                    strlcpy(pathnode->path, file);
                    pnode->list = pathnode;
                }
                else
                {
                    free(pnode);
                }
                if (data->list)
                {
                    tail->next = pnode;
                    tail = pnode;
                }
                else
                {
                    data->list = tail = pnode;
                }
            }
            continue;
        }
        filelist = vtoy_json_find_item(node->pstChild, JSON_TYPE_ARRAY, "dud");
        if (!filelist)
        {
            continue;
        }
        pnode = zalloc(sizeof(dud_node));
        if (!pnode)
        {
            continue;
        }
        strlcpy(pnode->path, path);
        for (filenode = filelist->pstChild; filenode; filenode = filenode->pstNext)
        {
            if (filenode->enDataType != JSON_TYPE_STRING)
            {
                continue;
            }
            pathnode = zalloc(sizeof(path_node));
            if (pathnode)
            {
                strlcpy(pathnode->path, filenode->unData.pcStrVal);
                count++;
                if (pnode->list)
                {
                    pathtail->next = pathnode;
                    pathtail = pathnode;
                }
                else
                {
                    pnode->list = pathtail = pathnode;
                }                
            }
        }
        if (count == 0)
        {
            free(pnode);
        }
        else
        {
            if (data->list)
            {
                tail->next = pnode;
                tail = pnode;
            }
            else
            {
                data->list = tail = pnode;
            }
        }
    }
    return 0;
}
#if 0
#endif
static int ventoy_load_old_json(const char *filename)
{
    int ret = 0;
    int offset = 0;
    int buflen = 0;
    char *buffer = NULL;
    unsigned char *start = NULL;
    VTOY_JSON *json = NULL;
    VTOY_JSON *node = NULL;
    VTOY_JSON *next = NULL;
    ret = ventoy_read_file_to_buf(filename, 4, (void **)&buffer, &buflen);
    if (ret)
    {
        vlog("Failed to read old ventoy.json file.\n");
        return 1;
    }
    buffer[buflen] = 0;
    start = (unsigned char *)buffer;
    if (start[0] == 0xef && start[1] == 0xbb && start[2] == 0xbf)
    {
        offset = 3;
    }
    else if ((start[0] == 0xff && start[1] == 0xfe) || (start[0] == 0xfe && start[1] == 0xff))
    {
        vlog("ventoy.json is in UCS-2 encoding, ignore it.\n");
        free(buffer);
        return 1;
    }
    json = vtoy_json_create();
    if (!json)
    {
        free(buffer);
        return 1;
    }
    
    if (vtoy_json_parse_ex(json, buffer + offset, buflen - offset) == JSON_SUCCESS)
    {
        vlog("parse ventoy.json success\n");
        for (node = json->pstChild; node; node = node->pstNext)
        for (next = node->pstNext; next; next = next->pstNext)
        {
            if (node->pcName && next->pcName && strcmp(node->pcName, next->pcName) == 0)
            {
                vlog("ventoy.json contains duplicate key <%s>.\n", node->pcName);
                g_sysinfo.invalid_config = 1;
                ret = 1;
                goto end;
            }
        }
        for (node = json->pstChild; node; node = node->pstNext)
        {
            ventoy_parse_json(control);
            ventoy_parse_json(theme);
            ventoy_parse_json(menu_alias);
            ventoy_parse_json(menu_tip);
            ventoy_parse_json(menu_class);
            ventoy_parse_json(auto_install);
            ventoy_parse_json(persistence);
            ventoy_parse_json(injection);
            ventoy_parse_json(conf_replace);
            ventoy_parse_json(password);
            ventoy_parse_json(image_list);
            ventoy_parse_json(image_blacklist);
            ventoy_parse_json(auto_memdisk);
            ventoy_parse_json(dud);
        }
    }
    else
    {
        vlog("ventoy.json has syntax error.\n");    
        g_sysinfo.syntax_error = 1;
        ret = 1;
    }
end:
    vtoy_json_destroy(json);
    free(buffer);
    return ret;
}
int ventoy_http_start(const char *ip, const char *port)
{
    int i = 0;
    int ret = 0;
    char addr[128];
    char filename[128];
    char backupname[128];
    struct mg_callbacks callbacks;
    const char *options[] = 
    {
	    "listening_ports",    "24681",
        "document_root",      "www",
        "index_files",        "index.html",
        "num_threads",        "16",
        "error_log_file",     LOG_FILE,
	    "request_timeout_ms", "10000",
	     NULL
    };
    for (i = 0; i <= bios_max; i++)
    {
        ventoy_data_default_control(g_data_control + i);
        ventoy_data_default_theme(g_data_theme + i);
        ventoy_data_default_menu_alias(g_data_menu_alias + i);
        ventoy_data_default_menu_class(g_data_menu_class + i);
        ventoy_data_default_menu_tip(g_data_menu_tip + i);        
        ventoy_data_default_auto_install(g_data_auto_install + i);
        ventoy_data_default_persistence(g_data_persistence + i);
        ventoy_data_default_injection(g_data_injection + i);
        ventoy_data_default_conf_replace(g_data_conf_replace + i);
        ventoy_data_default_password(g_data_password + i);
        ventoy_data_default_image_list(g_data_image_list + i);
        ventoy_data_default_auto_memdisk(g_data_auto_memdisk + i);
        ventoy_data_default_dud(g_data_dud + i);
    }
    ventoy_get_json_path(filename, backupname);
    if (ventoy_is_file_exist("%s", filename))
    {
        ventoy_copy_file(filename, backupname);
        ret = ventoy_load_old_json(filename);
        if (ret == 0)
        {
            ventoy_data_real_save_all(0);
        }
    }
    /* option */
    scnprintf(addr, sizeof(addr), "%s:%s", ip, port);
    options[1] = addr;
    memset(&callbacks, 0, sizeof(callbacks));
    callbacks.begin_request = ventoy_request_handler;
#ifndef VENTOY_SIM
    callbacks.open_file = ventoy_web_openfile;
#endif
    g_ventoy_http_ctx = mg_start(&callbacks, NULL, options);
    ventoy_start_writeback_thread(ventoy_http_writeback);
    return g_ventoy_http_ctx ? 0 : 1;
}
int ventoy_http_stop(void)
{
    if (g_ventoy_http_ctx)
    {
        mg_stop(g_ventoy_http_ctx);        
    }
    ventoy_stop_writeback_thread();
    return 0;
}
int ventoy_http_init(void)
{
    int i = 0;
    
#ifdef VENTOY_SIM
    char *Buffer = NULL;
    int BufLen = 0;
    ventoy_read_file_to_buf("www/menulist", 4, (void **)&Buffer, &BufLen);
    if (Buffer)
    {
        for (i = 0; i < BufLen / 5; i++)
        {
            memcpy(g_ventoy_menu_lang[i], Buffer + i * 5, 5);
            g_ventoy_menu_lang[i][5] = 0;
        }
        free(Buffer);
    }
#else
    ventoy_file *file;
    
    file = ventoy_tar_find_file("www/menulist");
    if (file)
    {
        for (i = 0; i < file->size / 5; i++)
        {
            memcpy(g_ventoy_menu_lang[i], (char *)(file->addr) + i * 5, 5);
            g_ventoy_menu_lang[i][5] = 0;
        }
    }
#endif
    if (!g_pub_json_buffer)
    {
        g_pub_json_buffer = malloc(JSON_BUF_MAX * 2);
        g_pub_save_buffer = g_pub_json_buffer + JSON_BUF_MAX;
    }   
    pthread_mutex_init(&g_api_mutex, NULL);
    return 0;
}
void ventoy_http_exit(void)
{
    check_free(g_pub_json_buffer);
    g_pub_json_buffer = NULL;
    g_pub_save_buffer = NULL;
    
    pthread_mutex_destroy(&g_api_mutex);
}
 | 143,591 | 
	C | 
	.c | 4,544 | 23.380722 | 113 | 0.548983 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 449 | 
	ventoy_util_linux.c | 
	ventoy_Ventoy/Plugson/src/Core/ventoy_util_linux.c | 
	/******************************************************************************
 * ventoy_util_linux.c  ---- ventoy util
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <linux/fs.h>
#include <dirent.h>
#include <time.h>
#include <semaphore.h>
#include <ventoy_define.h>
#include <ventoy_util.h>
void ventoy_gen_preudo_uuid(void *uuid)
{
    int i;
    int fd;
    fd = open("/dev/urandom", O_RDONLY | O_BINARY);
    if (fd < 0)
    {
        srand(time(NULL));
        for (i = 0; i < 8; i++)
        {
            *((uint16_t *)uuid + i) = (uint16_t)(rand() & 0xFFFF);
        }
    }
    else
    {
        read(fd, uuid, 16);
        close(fd);
    }
}
int ventoy_get_sys_file_line(char *buffer, int buflen, const char *fmt, ...)
{
    int len;
    char c;
    char path[256];
    va_list arg;
    va_start(arg, fmt);
    vsnprintf(path, 256, fmt, arg);
    va_end(arg);
    if (access(path, F_OK) >= 0)
    {
        FILE *fp = fopen(path, "r");
        memset(buffer, 0, buflen);
        len = (int)fread(buffer, 1, buflen - 1, fp);
        fclose(fp);
        while (len > 0)
        {
            c = buffer[len - 1];
            if (c == '\r' || c == '\n' || c == ' ' || c == '\t')
            {
                buffer[len - 1] = 0;
                len--;
            }
            else
            {
                break;
            }
        }
        
        return 0;
    }
    else
    {
        vdebug("%s not exist \n", path);
        return 1;
    }
}
int ventoy_is_disk_mounted(const char *devpath)
{
    int len;
    int mount = 0;
    char line[512];
    FILE *fp = NULL;
    fp = fopen("/proc/mounts", "r");
    if (!fp)
    {
        return 0;
    }
    len = (int)strlen(devpath);
    while (fgets(line, sizeof(line), fp))
    {
        if (strncmp(line, devpath, len) == 0)
        {
            mount = 1;
            vdebug("%s mounted <%s>\n", devpath, line);
            goto end;
        }
    }
end:
    fclose(fp);
    return mount;
}
const char * ventoy_get_os_language(void)
{
    const char *env = getenv("LANG");
    if (env && strncasecmp(env, "zh_CN", 5) == 0)
    {
        return "cn";
    }
    else
    {
        return "en";
    }
}
int ventoy_is_file_exist(const char *fmt, ...)
{
    va_list ap;
    struct stat sb;
    char fullpath[MAX_PATH];
    
    va_start (ap, fmt);
    vsnprintf(fullpath, MAX_PATH, fmt, ap);
    va_end (ap);
    if (stat(fullpath, &sb))
    {
        return 0;
    }
    if (S_ISREG(sb.st_mode))
    {
        return 1;
    }
    return 0;
}
int ventoy_is_directory_exist(const char *fmt, ...)
{
    va_list ap;
    struct stat sb;
    char fullpath[MAX_PATH];
    
    va_start (ap, fmt);
    vsnprintf(fullpath, MAX_PATH, fmt, ap);
    va_end (ap);
    if (stat(fullpath, &sb))
    {
        return 0;
    }
    if (S_ISDIR(sb.st_mode))
    {
        return 1;
    }
    return 0;
}
int ventoy_get_file_size(const char *file)
{
	int Size = -1;
    struct stat stStat;
    
	if (stat(file, &stStat) >= 0)
    {
        Size = (int)(stStat.st_size);
    }
	return Size;
}
int ventoy_write_buf_to_file(const char *FileName, void *Bufer, int BufLen)
{
    int fd;
    int rc;
    ssize_t size;
    fd = open(FileName, O_CREAT | O_RDWR | O_TRUNC, 0755);
    if (fd < 0)
    {
        vlog("Failed to open file %s %d\n", FileName, errno);
        return 1;
    }
    rc = fchmod(fd, 0755);
    if (rc)
    {
        vlog("Failed to chmod <%s> %d\n", FileName, errno);
    }
    
    size = write(fd, Bufer, BufLen);
    if ((int)size != BufLen)
    {
        close(fd);
        vlog("write file %s failed %d err:%d\n", FileName, (int)size, errno);
        return 1;
    }
    
    fsync(fd);
    close(fd);
    return 0;
}
static sem_t g_writeback_sem;
static volatile int g_thread_stop = 0;
static pthread_t g_writeback_thread;
static void * ventoy_local_thread_run(void* data)
{
    ventoy_http_writeback_pf callback = (ventoy_http_writeback_pf)data;
    while (0 == g_thread_stop)
    {
        sem_wait(&g_writeback_sem);
        callback();
    }    
    return NULL;
}
void ventoy_set_writeback_event(void)
{
    sem_post(&g_writeback_sem);
}
int ventoy_start_writeback_thread(ventoy_http_writeback_pf callback)
{
    g_thread_stop = 0;
    sem_init(&g_writeback_sem, 0, 0);
    pthread_create(&g_writeback_thread, NULL, ventoy_local_thread_run, callback);
    return 0;
}
void ventoy_stop_writeback_thread(void)
{
    g_thread_stop = 1;
    sem_post(&g_writeback_sem);
    pthread_join(g_writeback_thread, NULL);
    sem_destroy(&g_writeback_sem);
}
int ventoy_read_file_to_buf(const char *FileName, int ExtLen, void **Bufer, int *BufLen)
{
    int FileSize;
    FILE *fp = NULL;
    void *Data = NULL;
    fp = fopen(FileName, "rb");
    if (fp == NULL)
    {
        vlog("Failed to open file %s", FileName);
        return 1;
    }
    fseek(fp, 0, SEEK_END);
    FileSize = (int)ftell(fp);
    Data = malloc(FileSize + ExtLen);
    if (!Data)
    {
        fclose(fp);
        return 1;
    }
    fseek(fp, 0, SEEK_SET);
    fread(Data, 1, FileSize, fp);
    fclose(fp);
    *Bufer = Data;
    *BufLen = FileSize;
    return 0;
}
int ventoy_copy_file(const char *a, const char *b)
{
    int len = 0;
    char *buf = NULL;
    
    if (0 == ventoy_read_file_to_buf(a, 0, (void **)&buf, &len))
    {
        ventoy_write_buf_to_file(b, buf, len);        
        free(buf);
    }
    
    return 0;
}
 | 6,387 | 
	C | 
	.c | 271 | 18.321033 | 88 | 0.566495 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 451 | 
	ventoy_log.c | 
	ventoy_Ventoy/Plugson/src/Core/ventoy_log.c | 
	/******************************************************************************
 * ventoy_log.c  ---- ventoy log
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <ventoy_define.h>
#include <ventoy_util.h>
extern char g_log_file[MAX_PATH];
static int g_ventoy_log_level = VLOG_DEBUG;
static pthread_mutex_t g_log_mutex;
int ventoy_log_init(void)
{
	if (ventoy_get_file_size(g_log_file) >= SIZE_1MB)
	{
		#if defined(_MSC_VER) || defined(WIN32)
			DeleteFileA(g_log_file);
		#else
			remove(g_log_file);
		#endif
	}
    pthread_mutex_init(&g_log_mutex, NULL);
    return 0;
}
void ventoy_log_exit(void)
{
    pthread_mutex_destroy(&g_log_mutex);
}
void ventoy_set_loglevel(int level)
{
    g_ventoy_log_level = level;
}
void ventoy_syslog_printf(const char *Fmt, ...)
{
    char log[512];
    va_list arg;
    time_t stamp;
    struct tm ttm;
    FILE *fp;
    
    time(&stamp);
    localtime_r(&stamp, &ttm);
    va_start(arg, Fmt);
#if defined(_MSC_VER) || defined(WIN32)
    vsnprintf_s(log, 512, _TRUNCATE, Fmt, arg);
#else
    vsnprintf(log, 512, Fmt, arg);
#endif
    va_end(arg);
    pthread_mutex_lock(&g_log_mutex);
#if defined(_MSC_VER) || defined(WIN32)
    fopen_s(&fp, g_log_file, "a+");
#else
    fp = fopen(g_log_file, "a+");
#endif
    if (fp)
    {
        fprintf(fp, "[%04u/%02u/%02u %02u:%02u:%02u] %s", 
			ttm.tm_year, ttm.tm_mon + 1, ttm.tm_mday,
           ttm.tm_hour, ttm.tm_min, ttm.tm_sec,
           log);
        fclose(fp);
        #ifdef VENTOY_SIM
        printf("[%04u/%02u/%02u %02u:%02u:%02u] %s", 
			ttm.tm_year, ttm.tm_mon + 1, ttm.tm_mday,
           ttm.tm_hour, ttm.tm_min, ttm.tm_sec,
           log);
        #endif
    }
    pthread_mutex_unlock(&g_log_mutex);
}
void ventoy_syslog(int level, const char *Fmt, ...)
{
    char log[512];
    va_list arg;
    time_t stamp;
    struct tm ttm;
    FILE *fp;
    
    if (level > g_ventoy_log_level)
    {
        return;
    }
    time(&stamp);
    localtime_r(&stamp, &ttm);
    va_start(arg, Fmt);
#if defined(_MSC_VER) || defined(WIN32)
    vsnprintf_s(log, 512, _TRUNCATE, Fmt, arg);
#else
    vsnprintf(log, 512, Fmt, arg);
#endif
    va_end(arg);
    pthread_mutex_lock(&g_log_mutex);
#if defined(_MSC_VER) || defined(WIN32)
    fopen_s(&fp, g_log_file, "a+");
#else
    fp = fopen(g_log_file, "a+");
#endif
    if (fp)
    {
        fprintf(fp, "[%04u/%02u/%02u %02u:%02u:%02u] %s", 
           ttm.tm_year + 1900, ttm.tm_mon + 1, ttm.tm_mday,
           ttm.tm_hour, ttm.tm_min, ttm.tm_sec,
           log);
        fclose(fp);
        #ifdef VENTOY_SIM
        printf("[%04u/%02u/%02u %02u:%02u:%02u] %s", 
			ttm.tm_year + 1900, ttm.tm_mon + 1, ttm.tm_mday,
           ttm.tm_hour, ttm.tm_min, ttm.tm_sec,
           log);
        #endif
    }
    pthread_mutex_unlock(&g_log_mutex);
}
 | 3,572 | 
	C | 
	.c | 130 | 23.138462 | 79 | 0.61142 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 452 | 
	ventoy_json.c | 
	ventoy_Ventoy/Plugson/src/Core/ventoy_json.c | 
	/******************************************************************************
 * ventoy_json.c
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#if defined(_MSC_VER) || defined(WIN32)
#else
#include <unistd.h>
#include <sys/types.h>
#include <linux/limits.h>
#endif
#include <ventoy_define.h>
#include <ventoy_util.h>
#include <ventoy_json.h>
static void vtoy_json_free(VTOY_JSON *pstJsonHead)
{
    VTOY_JSON *pstNext = NULL;
    while (NULL != pstJsonHead)
    {
        pstNext = pstJsonHead->pstNext;
        if ((pstJsonHead->enDataType < JSON_TYPE_BUTT) && (NULL != pstJsonHead->pstChild))
        {
            vtoy_json_free(pstJsonHead->pstChild);
        }
        free(pstJsonHead);
        pstJsonHead = pstNext;
    }
    return;
}
static char *vtoy_json_skip(const char *pcData)
{
    while ((NULL != pcData) && ('\0' != *pcData) && (*pcData <= 32))
    {
        pcData++;
    }
    return (char *)pcData;
}
VTOY_JSON *vtoy_json_find_item
(
    VTOY_JSON *pstJson,
    JSON_TYPE  enDataType,
    const char *szKey
)
{
    while (NULL != pstJson)
    {
        if ((enDataType == pstJson->enDataType) && 
            (0 == strcmp(szKey, pstJson->pcName)))
        {
            return pstJson;
        }
        pstJson = pstJson->pstNext;
    }
    
    return NULL;
}
static int vtoy_json_parse_number
(
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    unsigned long Value;
    Value = strtoul(pcData, (char **)ppcEnd, 10);
    if (*ppcEnd == pcData)
    {
        vdebug("Failed to parse json number %s.\n", pcData);
        return JSON_FAILED;
    }
    pstJson->enDataType = JSON_TYPE_NUMBER;
    pstJson->unData.lValue = Value;
    
    return JSON_SUCCESS;
}
static int vtoy_json_parse_string
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    uint32_t uiLen = 0;
    const char *pcPos = NULL;
    const char *pcTmp = pcData + 1;
    
    *ppcEnd = pcData;
    if ('\"' != *pcData)
    {
        return JSON_FAILED;
    }
    pcPos = strchr(pcTmp, '\"');
    if ((NULL == pcPos) || (pcPos < pcTmp))
    {
        vdebug("Invalid string %s.\n", pcData);
        return JSON_FAILED;
    }
    if (*(pcPos - 1) == '\\')
    {
        for (pcPos++; *pcPos; pcPos++)
        {
            if (*pcPos == '"' && *(pcPos - 1) != '\\')
            {
                break;
            }
        }
        
        if (*pcPos == 0 || pcPos < pcTmp)
        {
            vdebug("Invalid quotes string %s.", pcData);
            return JSON_FAILED;
        }
    }
    *ppcEnd = pcPos + 1;
    uiLen = (uint32_t)(unsigned long)(pcPos - pcTmp);    
    
    pstJson->enDataType = JSON_TYPE_STRING;
    pstJson->unData.pcStrVal = pcNewStart + (pcTmp - pcRawStart);
    pstJson->unData.pcStrVal[uiLen] = '\0';
    
    return JSON_SUCCESS;
}
static int vtoy_json_parse_array
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    int Ret = JSON_SUCCESS;
    VTOY_JSON *pstJsonChild = NULL;
    VTOY_JSON *pstJsonItem = NULL;
    const char *pcTmp = pcData + 1;
    *ppcEnd = pcData;
    pstJson->enDataType = JSON_TYPE_ARRAY;
    if ('[' != *pcData)
    {
        return JSON_FAILED;
    }
    pcTmp = vtoy_json_skip(pcTmp);
    if (']' == *pcTmp)
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    JSON_NEW_ITEM(pstJson->pstChild, JSON_FAILED);
    Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJson->pstChild, pcTmp, ppcEnd);
    if (JSON_SUCCESS != Ret)
    {
        vdebug("Failed to parse array child.\n");
        return JSON_FAILED;
    }
    pstJsonChild = pstJson->pstChild;
    pcTmp = vtoy_json_skip(*ppcEnd);
    while ((NULL != pcTmp) && (',' == *pcTmp))
    {
        JSON_NEW_ITEM(pstJsonItem, JSON_FAILED);
        pstJsonChild->pstNext = pstJsonItem;
        pstJsonItem->pstPrev = pstJsonChild;
        pstJsonChild = pstJsonItem;
        Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
        if (JSON_SUCCESS != Ret)
        {
            vdebug("Failed to parse array child.\n");
            return JSON_FAILED;
        }
        pcTmp = vtoy_json_skip(*ppcEnd);
    }
    if ((NULL != pcTmp) && (']' == *pcTmp))
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    else
    {
        *ppcEnd = pcTmp;
        return JSON_FAILED;
    }
}
static int vtoy_json_parse_object
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    int Ret = JSON_SUCCESS;
    VTOY_JSON *pstJsonChild = NULL;
    VTOY_JSON *pstJsonItem = NULL;
    const char *pcTmp = pcData + 1;
    *ppcEnd = pcData;
    pstJson->enDataType = JSON_TYPE_OBJECT;
    if ('{' != *pcData)
    {
        return JSON_FAILED;
    }
    pcTmp = vtoy_json_skip(pcTmp);
    if ('}' == *pcTmp)
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    JSON_NEW_ITEM(pstJson->pstChild, JSON_FAILED);
    Ret = vtoy_json_parse_string(pcNewStart, pcRawStart, pstJson->pstChild, pcTmp, ppcEnd);
    if (JSON_SUCCESS != Ret)
    {
        vdebug("Failed to parse array child.\n");
        return JSON_FAILED;
    }
    pstJsonChild = pstJson->pstChild;
    pstJsonChild->pcName = pstJsonChild->unData.pcStrVal;
    pstJsonChild->unData.pcStrVal = NULL;
    pcTmp = vtoy_json_skip(*ppcEnd);
    if ((NULL == pcTmp) || (':' != *pcTmp))
    {
        *ppcEnd = pcTmp;
        return JSON_FAILED;
    }
    Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
    if (JSON_SUCCESS != Ret)
    {
        vdebug("Failed to parse array child.\n");
        return JSON_FAILED;
    }
    pcTmp = vtoy_json_skip(*ppcEnd);
    while ((NULL != pcTmp) && (',' == *pcTmp))
    {
        JSON_NEW_ITEM(pstJsonItem, JSON_FAILED);
        pstJsonChild->pstNext = pstJsonItem;
        pstJsonItem->pstPrev = pstJsonChild;
        pstJsonChild = pstJsonItem;
        Ret = vtoy_json_parse_string(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
        if (JSON_SUCCESS != Ret)
        {
            vdebug("Failed to parse array child.\n");
            return JSON_FAILED;
        }
        pcTmp = vtoy_json_skip(*ppcEnd);
        pstJsonChild->pcName = pstJsonChild->unData.pcStrVal;
        pstJsonChild->unData.pcStrVal = NULL;
        if ((NULL == pcTmp) || (':' != *pcTmp))
        {
            *ppcEnd = pcTmp;
            return JSON_FAILED;
        }
        Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
        if (JSON_SUCCESS != Ret)
        {
            vdebug("Failed to parse array child.\n");
            return JSON_FAILED;
        }
        pcTmp = vtoy_json_skip(*ppcEnd);
    }
    if ((NULL != pcTmp) && ('}' == *pcTmp))
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    else
    {
        *ppcEnd = pcTmp;
        return JSON_FAILED;
    }
}
int vtoy_json_parse_value
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    pcData = vtoy_json_skip(pcData);
    
    switch (*pcData)
    {
        case 'n':
        {
            if (0 == strncmp(pcData, "null", 4))
            {
                pstJson->enDataType = JSON_TYPE_NULL;
                *ppcEnd = pcData + 4;
                return JSON_SUCCESS;
            }
            break;
        }
        case 'f':
        {
            if (0 == strncmp(pcData, "false", 5))
            {
                pstJson->enDataType = JSON_TYPE_BOOL;
                pstJson->unData.lValue = 0;
                *ppcEnd = pcData + 5;
                return JSON_SUCCESS;
            }
            break;
        }
        case 't':
        {
            if (0 == strncmp(pcData, "true", 4))
            {
                pstJson->enDataType = JSON_TYPE_BOOL;
                pstJson->unData.lValue = 1;
                *ppcEnd = pcData + 4;
                return JSON_SUCCESS;
            }
            break;
        }
        case '\"':
        {
            return vtoy_json_parse_string(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
        }
        case '[':
        {
            return vtoy_json_parse_array(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
        }
        case '{':
        {
            return vtoy_json_parse_object(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
        }
        case '-':
        {
            return vtoy_json_parse_number(pstJson, pcData, ppcEnd);
        }
        default :
        {
            if (*pcData >= '0' && *pcData <= '9')
            {
                return vtoy_json_parse_number(pstJson, pcData, ppcEnd);
            }
        }
    }
    *ppcEnd = pcData;
    vdebug("Invalid json data %u.\n", (uint8_t)(*pcData));
    return JSON_FAILED;
}
VTOY_JSON * vtoy_json_create(void)
{
    VTOY_JSON *pstJson = NULL;
    pstJson = (VTOY_JSON *)zalloc(sizeof(VTOY_JSON));
    if (NULL == pstJson)
    {
        return NULL;
    }
    
    return pstJson;
}
int vtoy_json_parse(VTOY_JSON *pstJson, const char *szJsonData)
{
    uint32_t uiMemSize = 0;
    int Ret = JSON_SUCCESS;
    char *pcNewBuf = NULL;
    const char *pcEnd = NULL;
    uiMemSize = (uint32_t)strlen(szJsonData) + 1;
    pcNewBuf = (char *)malloc(uiMemSize);
    if (NULL == pcNewBuf)
    {
        vdebug("Failed to alloc new buf.\n");
        return JSON_FAILED;
    }
    memcpy(pcNewBuf, szJsonData, uiMemSize);
    pcNewBuf[uiMemSize - 1] = 0;
    Ret = vtoy_json_parse_value(pcNewBuf, (char *)szJsonData, pstJson, szJsonData, &pcEnd);
    if (JSON_SUCCESS != Ret)
    {
        vdebug("Failed to parse json data start=%p, end=%p.\n", szJsonData, pcEnd);
        return JSON_FAILED;
    }
    return JSON_SUCCESS;
}
int vtoy_json_parse_ex(VTOY_JSON *pstJson, const char *szJsonData, int szLen)
{
    uint32_t uiMemSize = 0;
    int Ret = JSON_SUCCESS;
    char *pcNewBuf = NULL;
    const char *pcEnd = NULL;
    uiMemSize = (uint32_t)szLen;
    pcNewBuf = (char *)malloc(uiMemSize + 1);
    if (NULL == pcNewBuf)
    {
        vdebug("Failed to alloc new buf.\n");
        return JSON_FAILED;
    }
    memcpy(pcNewBuf, szJsonData, szLen);
    pcNewBuf[uiMemSize] = 0;
    Ret = vtoy_json_parse_value(pcNewBuf, (char *)szJsonData, pstJson, szJsonData, &pcEnd);
    if (JSON_SUCCESS != Ret)
    {
        vdebug("Failed to parse json data start=%p, end=%p\n", szJsonData, pcEnd);
        return JSON_FAILED;
    }
    return JSON_SUCCESS;
}
int vtoy_json_scan_parse
(
    const VTOY_JSON    *pstJson,
    uint32_t            uiParseNum,
    VTOY_JSON_PARSE_S  *pstJsonParse
)
{   
    uint32_t i = 0;
    const VTOY_JSON *pstJsonCur = NULL;
    VTOY_JSON_PARSE_S *pstCurParse = NULL;
    for (pstJsonCur = pstJson; NULL != pstJsonCur; pstJsonCur = pstJsonCur->pstNext)
    {
        if ((JSON_TYPE_OBJECT == pstJsonCur->enDataType) ||
            (JSON_TYPE_ARRAY == pstJsonCur->enDataType))
        {
            continue;
        }
        for (i = 0, pstCurParse = NULL; i < uiParseNum; i++)
        {
            if (0 == strcmp(pstJsonParse[i].pcKey, pstJsonCur->pcName))
            {   
                pstCurParse = pstJsonParse + i;
                break;
            }
        }
        if (NULL == pstCurParse)
        {
            continue;
        }
    
        switch (pstJsonCur->enDataType)
        {
            case JSON_TYPE_NUMBER:
            {
                if (sizeof(uint32_t) == pstCurParse->uiBufSize)
                {
                    *(uint32_t *)(pstCurParse->pDataBuf) = (uint32_t)pstJsonCur->unData.lValue;
                }
                else if (sizeof(uint16_t) == pstCurParse->uiBufSize)
                {
                    *(uint16_t *)(pstCurParse->pDataBuf) = (uint16_t)pstJsonCur->unData.lValue;
                }
                else if (sizeof(uint8_t) == pstCurParse->uiBufSize)
                {
                    *(uint8_t *)(pstCurParse->pDataBuf) = (uint8_t)pstJsonCur->unData.lValue;
                }
                else if ((pstCurParse->uiBufSize > sizeof(uint64_t)))
                {
                    scnprintf((char *)pstCurParse->pDataBuf, pstCurParse->uiBufSize, "%llu", 
                        (unsigned long long)(pstJsonCur->unData.lValue));
                }
                else
                {
                    vdebug("Invalid number data buf size %u.\n", pstCurParse->uiBufSize);
                }
                break;
            }
            case JSON_TYPE_STRING:
            {
                scnprintf((char *)pstCurParse->pDataBuf, pstCurParse->uiBufSize, "%s", pstJsonCur->unData.pcStrVal);
                break;
            }
            case JSON_TYPE_BOOL:
            {
                *(uint8_t *)(pstCurParse->pDataBuf) = (pstJsonCur->unData.lValue) > 0 ? 1 : 0;
                break;
            }
            default :
            {
                break;
            }
        }
    }
    return JSON_SUCCESS;
}
int vtoy_json_scan_array
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     VTOY_JSON **ppstArrayItem
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_ARRAY, szKey);
    if (NULL == pstJsonItem)
    {
        vdebug("Key %s is not found in json data.\n", szKey);
        return JSON_NOT_FOUND;
    }
    *ppstArrayItem = pstJsonItem;
    return JSON_SUCCESS;
}
int vtoy_json_scan_array_ex
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     VTOY_JSON **ppstArrayItem
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_ARRAY, szKey);
    if (NULL == pstJsonItem)
    {
        vdebug("Key %s is not found in json data.\n", szKey);
        return JSON_NOT_FOUND;
    }
    
    *ppstArrayItem = pstJsonItem->pstChild;
    return JSON_SUCCESS;
}
int vtoy_json_scan_object
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     VTOY_JSON **ppstObjectItem
)
{
    VTOY_JSON *pstJsonItem = NULL;
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_OBJECT, szKey);
    if (NULL == pstJsonItem)
    {
        vdebug("Key %s is not found in json data.\n", szKey);
        return JSON_NOT_FOUND;
    }
    *ppstObjectItem = pstJsonItem;
    return JSON_SUCCESS;
}
int vtoy_json_get_int
(
    VTOY_JSON *pstJson, 
    const char *szKey, 
    int *piValue
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
    if (NULL == pstJsonItem)
    {
        //vdebug("Key %s is not found in json data.\n", szKey);
        return JSON_NOT_FOUND;
    }
    *piValue = (int)pstJsonItem->unData.lValue;
    return JSON_SUCCESS;
}
int vtoy_json_get_uint
(
    VTOY_JSON *pstJson, 
    const char *szKey, 
    uint32_t *puiValue
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
    if (NULL == pstJsonItem)
    {
        vdebug("Key %s is not found in json data.\n", szKey);
        return JSON_NOT_FOUND;
    }
    *puiValue = (uint32_t)pstJsonItem->unData.lValue;
    return JSON_SUCCESS;
}
int vtoy_json_get_uint64
(
    VTOY_JSON *pstJson, 
    const char *szKey, 
    uint64_t *pui64Value
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
    if (NULL == pstJsonItem)
    {
        vdebug("Key %s is not found in json data.\n", szKey);
        return JSON_NOT_FOUND;
    }
    *pui64Value = (uint64_t)pstJsonItem->unData.lValue;
    return JSON_SUCCESS;
}
int vtoy_json_get_bool
(
    VTOY_JSON *pstJson,
    const char *szKey, 
    uint8_t *pbValue
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_BOOL, szKey);
    if (NULL == pstJsonItem)
    {
        vdebug("Key %s is not found in json data.\n", szKey);
        return JSON_NOT_FOUND;
    }
    *pbValue = pstJsonItem->unData.lValue > 0 ? 1 : 0;
    return JSON_SUCCESS;
}
int vtoy_json_get_string
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     uint32_t  uiBufLen,
     char *pcBuf
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_STRING, szKey);
    if (NULL == pstJsonItem)
    {
        //vdebug("Key %s is not found in json data.\n", szKey);
        return JSON_NOT_FOUND;
    }
    scnprintf(pcBuf, uiBufLen, "%s", pstJsonItem->unData.pcStrVal);
    return JSON_SUCCESS;
}
const char * vtoy_json_get_string_ex(VTOY_JSON *pstJson,  const char *szKey)
{
    VTOY_JSON *pstJsonItem = NULL;
    if ((NULL == pstJson) || (NULL == szKey))
    {
        return NULL;
    }
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_STRING, szKey);
    if (NULL == pstJsonItem)
    {
        //vdebug("Key %s is not found in json data.\n", szKey);
        return NULL;
    }
    return pstJsonItem->unData.pcStrVal;
}
int vtoy_json_destroy(VTOY_JSON *pstJson)
{
    if (NULL == pstJson)
    {   
        return JSON_SUCCESS;
    }
    if (NULL != pstJson->pstChild)
    {
        vtoy_json_free(pstJson->pstChild);
    }
    if (NULL != pstJson->pstNext)
    {
        vtoy_json_free(pstJson->pstNext);
    }
    free(pstJson);
    
    return JSON_SUCCESS;
}
int vtoy_json_escape_string(char *buf, int buflen, const char *str, int newline)
{
    char last = 0;
    int count = 0;
    *buf++ = '"';
    count++;
    while (*str)
    {
        if (*str == '"' && last != '\\')
        {
            *buf = '\\';
            count++;
            buf++;
        }
    
        *buf = *str;
        count++;
        buf++;
        last = *str;
        str++;
    }
    *buf++ = '"';
    count++;
    
    *buf++ = ',';
    count++;
    if (newline)
    {
        *buf++ = '\n';
        count++;        
    }
    return count;
}
 | 19,568 | 
	C | 
	.c | 686 | 20.428571 | 117 | 0.545572 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 453 | 
	ventoy_disk_windows.c | 
	ventoy_Ventoy/Plugson/src/Core/ventoy_disk_windows.c | 
	/******************************************************************************
 * ventoy_disk.c  ---- ventoy disk
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <windows.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
#include <ventoy_define.h>
#include <ventoy_disk.h>
#include <ventoy_util.h>
#include <fat_filelib.h>
static int g_disk_num = 0;
ventoy_disk *g_disk_list = NULL;
int ventoy_disk_init(void)
{
	char Letter = 'A';
	DWORD Drives = GetLogicalDrives();
    vlog("ventoy disk init ...\n");   
    g_disk_list = zalloc(sizeof(ventoy_disk) * MAX_DISK);
	while (Drives)
	{
		if (Drives & 0x01)
		{
			if (CheckRuntimeEnvironment(Letter, g_disk_list + g_disk_num) == 0)
			{
				g_disk_list[g_disk_num].devname[0] = Letter;
				g_disk_num++;
                vlog("%C: is ventoy disk\n", Letter);
			}
			else
			{
				memset(g_disk_list + g_disk_num, 0, sizeof(ventoy_disk));
                vlog("%C: is NOT ventoy disk\n", Letter);
			}
		}
		Letter++;
		Drives >>= 1;
	}
    return 0;
}
void ventoy_disk_exit(void)
{
    vlog("ventoy disk exit ...\n");   
    check_free(g_disk_list);
    g_disk_list = NULL;
    g_disk_num = 0;
}
const ventoy_disk * ventoy_get_disk_list(int *num)
{
    *num = g_disk_num;
    return g_disk_list;
}
const ventoy_disk * ventoy_get_disk_node(int id)
{
    if (id >= 0 && id < g_disk_num)
    {
        return g_disk_list + id;
    }
    return NULL;
}
 | 2,092 | 
	C | 
	.c | 75 | 24.56 | 79 | 0.638723 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 454 | 
	ventoy_util.c | 
	ventoy_Ventoy/Plugson/src/Core/ventoy_util.c | 
	/******************************************************************************
 * ventoy_util.c  ---- ventoy util
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <ventoy_define.h>
#include <ventoy_util.h>
static int g_tar_filenum = 0;
static char *g_tar_buffer = NULL;
static ventoy_file *g_tar_filelist = NULL;
SYSINFO g_sysinfo;
unsigned char *g_unxz_buffer = NULL;
int g_unxz_len = 0;
void unxz_error(char *x)
{
	vlog("%s\n", x);
}
int unxz_flush(void *src, unsigned int size)
{
	memcpy(g_unxz_buffer + g_unxz_len, src, size);
	g_unxz_len += (int)size;
	return (int)size;
}
uint64_t ventoy_get_human_readable_gb(uint64_t SizeBytes)
{
    int i;
    int Pow2 = 1;
    double Delta;
    double GB = SizeBytes * 1.0 / 1000 / 1000 / 1000;
    if ((SizeBytes % SIZE_1GB) == 0)
    {
        return (uint64_t)(SizeBytes / SIZE_1GB);
    }
    for (i = 0; i < 12; i++)
    {
        if (Pow2 > GB)
        {
            Delta = (Pow2 - GB) / Pow2;
        }
        else
        {
            Delta = (GB - Pow2) / Pow2;
        }
        if (Delta < 0.05)
        {
            return Pow2;
        }
        Pow2 <<= 1;
    }
    return (uint64_t)GB;
}
ventoy_file * ventoy_tar_find_file(const char *path)
{
    int i;
    int len;
    ventoy_file *node = g_tar_filelist;
    len = (int)strlen(path);
    
    for (i = 0; i < g_tar_filenum; i++, node++)
    {
        if (node->pathlen == len && memcmp(node->path, path, len) == 0)
        {
            return node;
        }
        if (node->pathlen > len)
        {
            break;
        }
    }
    return NULL;
}
int ventoy_decompress_tar(char *tarbuf, int buflen, int *tarsize)
{
    int rc = 1;
	int inused = 0;
	int BufLen = 0;
	unsigned char *buffer = NULL;
    char tarxz[MAX_PATH];
#if defined(_MSC_VER) || defined(WIN32)
    scnprintf(tarxz, sizeof(tarxz), "%s\\ventoy\\%s", g_ventoy_dir, PLUGSON_TXZ);
#else
    scnprintf(tarxz, sizeof(tarxz), "%s/tool/%s", g_ventoy_dir, PLUGSON_TXZ);
#endif
    if (ventoy_read_file_to_buf(tarxz, 0, (void **)&buffer, &BufLen))
    {
        vlog("Failed to read file <%s>\n", tarxz);
        return 1;
    }
    g_unxz_buffer = (unsigned char *)tarbuf;
    g_unxz_len = 0;
    unxz(buffer, BufLen, NULL, unxz_flush, NULL, &inused, unxz_error);
    vlog("xzlen:%u rawdata size:%d\n", BufLen, g_unxz_len);
    if (inused != BufLen)
    {
        vlog("Failed to unxz data %d %d\n", inused, BufLen);
        rc = 1;
    }
    else
    {
        *tarsize = g_unxz_len;
        rc = 0;        
    }
	free(buffer);
    return rc;
}
int ventoy_www_init(void)
{
    int i = 0;
    int j = 0;
    int size = 0;
    int tarsize = 0;
    int offset = 0;
    ventoy_file *node = NULL;
    ventoy_file *node2 = NULL;
    VENTOY_TAR_HEAD *pHead = NULL;
    ventoy_file tmpnode;
    if (!g_tar_filelist)
    {
        g_tar_filelist = malloc(VENTOY_FILE_MAX * sizeof(ventoy_file));
        g_tar_buffer = malloc(TAR_BUF_MAX);
        g_tar_filenum = 0;
    }
    if ((!g_tar_filelist) || (!g_tar_buffer))
    {
        return 1;
    }
    if (ventoy_decompress_tar(g_tar_buffer, TAR_BUF_MAX, &tarsize))
    {
        vlog("Failed to decompress tar\n");
        return 1;
    }
    pHead = (VENTOY_TAR_HEAD *)g_tar_buffer;
    node = g_tar_filelist;
    while (g_tar_filenum < VENTOY_FILE_MAX && size < tarsize && memcmp(pHead->magic, TMAGIC, 5) == 0)
    {
        if (pHead->typeflag == REGTYPE)
        {
            node->size = (int)strtol(pHead->size, NULL, 8);
            node->pathlen = (int)scnprintf(node->path, MAX_PATH, "%s", pHead->name);
            node->addr = pHead + 1;
            if (node->pathlen == 13 && strcmp(pHead->name, "www/buildtime") == 0)
            {
                scnprintf(g_sysinfo.buildtime, sizeof(g_sysinfo.buildtime), "%s", (char *)node->addr);
                vlog("Plugson buildtime %s\n", g_sysinfo.buildtime);
            }
			offset = 512 + VENTOY_UP_ALIGN(node->size, 512);
            node++;
            g_tar_filenum++;
        }
        else
        {
            offset = 512;
        }
        pHead = (VENTOY_TAR_HEAD *)((char *)pHead + offset);
        size += offset;
    }
    //sort
    for (i = 0; i < g_tar_filenum; i++)
    for (j = i + 1; j < g_tar_filenum; j++)
    {
        node = g_tar_filelist + i;
        node2 = g_tar_filelist + j;
        if (node->pathlen > node2->pathlen)
        {
            memcpy(&tmpnode, node, sizeof(ventoy_file));
            memcpy(node, node2, sizeof(ventoy_file));
            memcpy(node2, &tmpnode, sizeof(ventoy_file));
        }
    }
    vlog("Total extract %d files from tar file.\n", g_tar_filenum);
    
    return 0;
}
void ventoy_www_exit(void)
{
    check_free(g_tar_filelist);
    check_free(g_tar_buffer);
    g_tar_filelist = NULL;
    g_tar_buffer = NULL;
    g_tar_filenum = 0;
}
void ventoy_get_json_path(char *path, char *backup)
{
#if defined(_MSC_VER) || defined(WIN32)
    scnprintf(path, 64, "%C:\\ventoy\\ventoy.json", g_cur_dir[0]);
if (backup)
{
    scnprintf(backup, 64, "%C:\\ventoy\\ventoy_backup.json", g_cur_dir[0]);
}
#else
    scnprintf(path, 64, "%s/ventoy/ventoy.json", g_cur_dir);
if (backup)
{
    scnprintf(backup, 64, "%s/ventoy/ventoy_backup.json", g_cur_dir);
}
#endif    
}
static const char g_encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                '4', '5', '6', '7', '8', '9', '+', '/'};
char * ventoy_base64_encode(const char *data, int input_length, int *output_length) 
{
    int i = 0;
    int j = 0;
    char *encoded_data = NULL;
    int mod_table[] = {0, 2, 1};
    
    *output_length = 4 * ((input_length + 2) / 3);
    encoded_data = malloc(*output_length + 4);
    if (!encoded_data)
    {
        return NULL;
    }
    while (i < input_length) 
    {
        unsigned int octet_a = i < input_length ? (unsigned char)data[i++] : 0;
        unsigned int octet_b = i < input_length ? (unsigned char)data[i++] : 0;
        unsigned int octet_c = i < input_length ? (unsigned char)data[i++] : 0;
        unsigned int triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
        encoded_data[j++] = g_encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = g_encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = g_encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = g_encoding_table[(triple >> 0 * 6) & 0x3F];
    }
    for (i = 0; i < mod_table[input_length % 3]; i++)
    {
        encoded_data[*output_length - 1 - i] = '=';        
    }
    return encoded_data;
}
 | 7,718 | 
	C | 
	.c | 248 | 24.625 | 102 | 0.538565 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 458 | 
	ventoy_disk_linux.c | 
	ventoy_Ventoy/Plugson/src/Core/ventoy_disk_linux.c | 
	/******************************************************************************
 * ventoy_disk.c  ---- ventoy disk
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/fs.h>
#include <dirent.h>
#include <time.h>
#include <ventoy_define.h>
#include <ventoy_disk.h>
#include <ventoy_util.h>
#include <fat_filelib.h>
static int g_fatlib_media_fd = 0;
static uint64_t g_fatlib_media_offset = 0;
static const char *g_ventoy_dev_type_str[VTOY_DEVICE_END] = 
{
    "unknown", "scsi", "USB", "ide", "dac960",
    "cpqarray", "file", "ataraid", "i2o",
    "ubd", "dasd", "viodasd", "sx8", "dm",
    "xvd", "sd/mmc", "virtblk", "aoe",
    "md", "loopback", "nvme", "brd", "pmem"
};
static const char * ventoy_get_dev_type_name(ventoy_dev_type type)
{
    return (type < VTOY_DEVICE_END) ? g_ventoy_dev_type_str[type] : "unknown";
}
static int ventoy_check_blk_major(int major, const char *type)
{
    int flag = 0;
    int valid = 0;
    int devnum = 0;
    int len = 0;
    char line[64];
    char *pos = NULL;
    FILE *fp = NULL;
    fp = fopen("/proc/devices", "r");
    if (!fp)
    {
        return 0;
    }
    len = (int)strlen(type);
    while (fgets(line, sizeof(line), fp))
    {
        if (flag)
        {
            pos = strchr(line, ' ');
            if (pos)
            {
                devnum = (int)strtol(line, NULL, 10);
                if (devnum == major)
                {
                    if (strncmp(pos + 1, type, len) == 0)
                    {
                        valid = 1;                        
                    }
                    break;
                }
            }
        }
        else if (strncmp(line, "Block devices:", 14) == 0)
        {
            flag = 1;
        }
    }
    fclose(fp);
    return valid;
}
static int ventoy_get_disk_devnum(const char *name, int *major, int* minor)
{
    int rc;
    char *pos;
    char devnum[16] = {0};
    
    rc = ventoy_get_sys_file_line(devnum, sizeof(devnum), "/sys/block/%s/dev", name);
    if (rc)
    {
        return 1;
    }
    pos = strstr(devnum, ":");
    if (!pos)
    {
        return 1;
    }
    *major = (int)strtol(devnum, NULL, 10);
    *minor = (int)strtol(pos + 1, NULL, 10);
    return 0;
}
static ventoy_dev_type ventoy_get_dev_type(const char *name, int major, int minor)
{
    int rc;
    char syspath[128];
    char dstpath[256];
    memset(syspath, 0, sizeof(syspath));
    memset(dstpath, 0, sizeof(dstpath));
    
    scnprintf(syspath, sizeof(syspath), "/sys/block/%s", name);
    rc = readlink(syspath, dstpath, sizeof(dstpath) - 1);
    if (rc > 0 && strstr(dstpath, "/usb"))
    {
        return VTOY_DEVICE_USB;
    }
    
    if (SCSI_BLK_MAJOR(major) && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_SCSI;
    }
    else if (IDE_BLK_MAJOR(major) && (minor % 0x40 == 0)) 
    {
        return VTOY_DEVICE_IDE;
    }
    else if (major == DAC960_MAJOR && (minor % 0x8 == 0)) 
    {
        return VTOY_DEVICE_DAC960;
    }
    else if (major == ATARAID_MAJOR && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_ATARAID;
    }
    else if (major == AOE_MAJOR && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_AOE;
    }
    else if (major == DASD_MAJOR && (minor % 0x4 == 0)) 
    {
        return VTOY_DEVICE_DASD;
    }
    else if (major == VIODASD_MAJOR && (minor % 0x8 == 0)) 
    {
        return VTOY_DEVICE_VIODASD;
    }
    else if (SX8_BLK_MAJOR(major) && (minor % 0x20 == 0)) 
    {
        return VTOY_DEVICE_SX8;
    }
    else if (I2O_BLK_MAJOR(major) && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_I2O;
    }
    else if (CPQARRAY_BLK_MAJOR(major) && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_CPQARRAY;
    }
    else if (UBD_MAJOR == major && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_UBD;
    }
    else if (XVD_MAJOR == major && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_XVD;
    }
    else if (SDMMC_MAJOR == major && (minor % 0x8 == 0)) 
    {
        return VTOY_DEVICE_SDMMC;
    }
    else if (ventoy_check_blk_major(major, "virtblk"))
    {
        return VTOY_DEVICE_VIRTBLK;
    }
    else if (major == LOOP_MAJOR)
    {
        return VTOY_DEVICE_LOOP;
    }
    else if (major == MD_MAJOR)
    {
        return VTOY_DEVICE_MD;
    }
    else if (major == RAM_MAJOR)
    {
        return VTOY_DEVICE_RAM;
    }
    else if (strstr(name, "nvme") && ventoy_check_blk_major(major, "blkext"))
    {
        return VTOY_DEVICE_NVME;
    }
    else if (strstr(name, "pmem") && ventoy_check_blk_major(major, "blkext"))
    {
        return VTOY_DEVICE_PMEM;
    }
    
    return VTOY_DEVICE_END;
}
static int ventoy_is_possible_blkdev(const char *name)
{
    if (name[0] == '.')
    {
        return 0;
    }
    /* /dev/ramX */
    if (name[0] == 'r' && name[1] == 'a' && name[2] == 'm')
    {
        return 0;
    }
    
    /* /dev/zramX */
    if (name[0] == 'z' && name[1] == 'r' && name[2] == 'a' && name[3] == 'm')
    {
        return 0;
    }
    /* /dev/loopX */
    if (name[0] == 'l' && name[1] == 'o' && name[2] == 'o' && name[3] == 'p')
    {
        return 0;
    }
    /* /dev/dm-X */
    if (name[0] == 'd' && name[1] == 'm' && name[2] == '-' && isdigit(name[3]))
    {
        return 0;
    }
    /* /dev/srX */
    if (name[0] == 's' && name[1] == 'r' && isdigit(name[2]))
    {
        return 0;
    }
    
    return 1;
}
uint64_t ventoy_get_disk_size_in_byte(const char *disk)
{
    int fd;
    int rc;
    unsigned long long size = 0;
    char diskpath[256] = {0};
    char sizebuf[64] = {0};
    // Try 1: get size from sysfs
    scnprintf(diskpath, sizeof(diskpath) - 1, "/sys/block/%s/size", disk);
    if (access(diskpath, F_OK) >= 0)
    {
        vdebug("get disk size from sysfs for %s\n", disk);
        
        fd = open(diskpath, O_RDONLY | O_BINARY);
        if (fd >= 0)
        {
            read(fd, sizebuf, sizeof(sizebuf));
            size = strtoull(sizebuf, NULL, 10);
            close(fd);
            return (uint64_t)(size * 512);
        }
    }
    else
    {
        vdebug("%s not exist \n", diskpath);
    }
    // Try 2: get size from ioctl
    scnprintf(diskpath, sizeof(diskpath) - 1, "/dev/%s", disk);
    fd = open(diskpath, O_RDONLY);
    if (fd >= 0)
    {
        vdebug("get disk size from ioctl for %s\n", disk);
        rc = ioctl(fd, BLKGETSIZE64, &size);
        if (rc == -1)
        {
            size = 0;
            vdebug("failed to ioctl %d\n", rc);
        }
        close(fd);
    }
    else
    {
        vdebug("failed to open %s %d\n", diskpath, errno);
    }
    vdebug("disk %s size %llu bytes\n", disk, size);
    return size;
}
int ventoy_get_disk_vendor(const char *name, char *vendorbuf, int bufsize)
{
    if (strncmp(name, "loop", 4) == 0)
    {
        scnprintf(vendorbuf, bufsize, "Local");
        return 0;
    }
    
    return ventoy_get_sys_file_line(vendorbuf, bufsize, "/sys/block/%s/device/vendor", name);        
}
int ventoy_get_disk_model(const char *name, char *modelbuf, int bufsize)
{
    if (strncmp(name, "loop", 4) == 0)
    {
        scnprintf(modelbuf, bufsize, "Loop Device");
        return 0;
    }
    return ventoy_get_sys_file_line(modelbuf, bufsize, "/sys/block/%s/device/model", name);  
}
static int fatlib_media_sector_read(uint32 sector, uint8 *buffer, uint32 sector_count)
{
    lseek(g_fatlib_media_fd, (sector + g_fatlib_media_offset) * 512ULL, SEEK_SET);
    read(g_fatlib_media_fd, buffer, sector_count * 512);
    
    return 1;
}
static int fatlib_is_secure_boot_enable(void)
{
    void *flfile = NULL;
    
    flfile = fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
    if (flfile)
    {
        vlog("/EFI/BOOT/grubx64_real.efi find, secure boot in enabled\n");
        fl_fclose(flfile);
        return 1;
    }
    else
    {
        vlog("/EFI/BOOT/grubx64_real.efi not exist\n");
    }
    
    return 0;
}
static int fatlib_get_ventoy_version(char *verbuf, int bufsize)
{
    int rc = 1;
    int size = 0;
    char *buf = NULL;
    char *pos = NULL;
    char *end = NULL;
    void *flfile = NULL;
    flfile = fl_fopen("/grub/grub.cfg", "rb");
    if (flfile)
    {
        fl_fseek(flfile, 0, SEEK_END);
        size = (int)fl_ftell(flfile);
        fl_fseek(flfile, 0, SEEK_SET);
        buf = malloc(size + 1);
        if (buf)
        {
            fl_fread(buf, 1, size, flfile);
            buf[size] = 0;
            pos = strstr(buf, "VENTOY_VERSION=");
            if (pos)
            {
                pos += strlen("VENTOY_VERSION=");
                if (*pos == '"')
                {
                    pos++;
                }
                end = pos;
                while (*end != 0 && *end != '"' && *end != '\r' && *end != '\n')
                {
                    end++;
                }
                *end = 0;
                scnprintf(verbuf, bufsize - 1, "%s", pos);
                rc = 0;
            }
            free(buf);
        }
        fl_fclose(flfile);
    }
    else
    {
        vdebug("No grub.cfg found\n");
    }
    
    return rc;
}
/* <BEGIN>: Deleted by longpanda, 20211028 PN:XX LABEL:XX */
#if 0
int ventoy_get_vtoy_data(ventoy_disk *info, int *ppartstyle)
{
    int i;
    int fd;
    int len;
    int rc = 1;
    int ret = 1;
    int part_style;
    uint64_t part1_start_sector;
    uint64_t part1_sector_count;
    uint64_t part2_start_sector;
    uint64_t part2_sector_count;
    uint64_t preserved_space;
    char name[64] = {0};
    disk_ventoy_data *vtoy = NULL;    
    VTOY_GPT_INFO *gpt = NULL;
    
    vtoy = &(info->vtoydata);
    gpt = &(vtoy->gptinfo);
    memset(vtoy, 0, sizeof(disk_ventoy_data));
    vdebug("ventoy_get_vtoy_data %s\n", info->disk_path);
    if (info->size_in_byte < (2 * VTOYEFI_PART_BYTES))
    {
        vdebug("disk %s is too small %llu\n", info->disk_path, (_ull)info->size_in_byte);
        return 1;
    }
    fd = open(info->disk_path, O_RDONLY | O_BINARY);
    if (fd < 0)
    {
        vdebug("failed to open %s %d\n", info->disk_path, errno);
        return 1;
    }
    len = (int)read(fd, &(vtoy->gptinfo), sizeof(VTOY_GPT_INFO));
    if (len != sizeof(VTOY_GPT_INFO))
    {
        vdebug("failed to read %s %d\n", info->disk_path, errno);
        goto end;
    }
    if (gpt->MBR.Byte55 != 0x55 || gpt->MBR.ByteAA != 0xAA)
    {
        vdebug("Invalid mbr magic 0x%x 0x%x\n", gpt->MBR.Byte55, gpt->MBR.ByteAA);
        goto end;
    }
    if (gpt->MBR.PartTbl[0].FsFlag == 0xEE && strncmp(gpt->Head.Signature, "EFI PART", 8) == 0)
    {
        part_style = GPT_PART_STYLE;
        if (ppartstyle)
        {
            *ppartstyle = part_style;
        }
        if (gpt->PartTbl[0].StartLBA == 0 || gpt->PartTbl[1].StartLBA == 0)
        {
            vdebug("NO ventoy efi part layout <%llu %llu>\n", 
                (_ull)gpt->PartTbl[0].StartLBA,
                (_ull)gpt->PartTbl[1].StartLBA);
            goto end;
        }
        for (i = 0; i < 36; i++)
        {
            name[i] = (char)(gpt->PartTbl[1].Name[i]);
        }
        if (strcmp(name, "VTOYEFI"))
        {
            vdebug("Invalid efi part2 name <%s>\n", name);
            goto end;
        }
        part1_start_sector = gpt->PartTbl[0].StartLBA;
        part1_sector_count = gpt->PartTbl[0].LastLBA - part1_start_sector + 1;
        part2_start_sector = gpt->PartTbl[1].StartLBA;
        part2_sector_count = gpt->PartTbl[1].LastLBA - part2_start_sector + 1;
        preserved_space = info->size_in_byte - (part2_start_sector + part2_sector_count + 33) * 512;
    }
    else
    {
        part_style = MBR_PART_STYLE;
        if (ppartstyle)
        {
            *ppartstyle = part_style;
        }
        
        part1_start_sector = gpt->MBR.PartTbl[0].StartSectorId;
        part1_sector_count = gpt->MBR.PartTbl[0].SectorCount;
        part2_start_sector = gpt->MBR.PartTbl[1].StartSectorId;
        part2_sector_count = gpt->MBR.PartTbl[1].SectorCount;
        preserved_space = info->size_in_byte - (part2_start_sector + part2_sector_count) * 512;
    }
    if (part1_start_sector != VTOYIMG_PART_START_SECTOR ||
        part2_sector_count != VTOYEFI_PART_SECTORS ||
        (part1_start_sector + part1_sector_count) != part2_start_sector)
    {
        vdebug("Not valid ventoy partition layout [%llu %llu] [%llu %llu]\n", 
               part1_start_sector, part1_sector_count, part2_start_sector, part2_sector_count);
        goto end;
    }
    vdebug("ventoy partition layout check OK: [%llu %llu] [%llu %llu]\n", 
               part1_start_sector, part1_sector_count, part2_start_sector, part2_sector_count);
    vtoy->ventoy_valid = 1;
    vdebug("now check secure boot for %s ...\n", info->disk_path);
    g_fatlib_media_fd = fd;
    g_fatlib_media_offset = part2_start_sector;
    fl_init();
    if (0 == fl_attach_media(fatlib_media_sector_read, NULL))
    {
        ret = fatlib_get_ventoy_version(vtoy->ventoy_ver, sizeof(vtoy->ventoy_ver));
        if (ret == 0 && vtoy->ventoy_ver[0])
        {
            vtoy->secure_boot_flag = fatlib_is_secure_boot_enable();            
        }
        else
        {
            vdebug("fatlib_get_ventoy_version failed %d\n", ret);
        }
    }
    else
    {
        vdebug("fl_attach_media failed\n");
    }
    fl_shutdown();
    g_fatlib_media_fd = -1;
    g_fatlib_media_offset = 0;
    if (vtoy->ventoy_ver[0] == 0)
    {
        vtoy->ventoy_ver[0] = '?';
    }
    if (0 == vtoy->ventoy_valid)
    {
        goto end;
    }
    
    lseek(fd, 2040 * 512, SEEK_SET);
    read(fd, vtoy->rsvdata, sizeof(vtoy->rsvdata));
    vtoy->preserved_space = preserved_space;
    vtoy->partition_style = part_style;
    vtoy->part2_start_sector = part2_start_sector;
    rc = 0;
end:
    vtoy_safe_close_fd(fd);
    return rc;
}
#endif /* #if 0 */
/* <END>  : Deleted by longpanda, 20211028 PN:XX LABEL:XX */
int ventoy_get_disk_info(char **argv)
{
    uint64_t size;
    char vendor[128];
    char model[128];
    char *disk = argv[4];
    if (strncmp(argv[4], "/dev/", 5) == 0)
    {
        disk += 5;
    }
    ventoy_get_disk_vendor(disk, vendor, sizeof(vendor));
    ventoy_get_disk_model(disk, model, sizeof(model));
    scnprintf(g_sysinfo.cur_model, sizeof(g_sysinfo.cur_model), "%s %s  [%s]", vendor, model, argv[4]);
    strlcpy(g_sysinfo.cur_ventoy_ver, argv[5]);
    strlcpy(g_sysinfo.cur_fsname, argv[6]);
    g_sysinfo.cur_part_style = (int)strtol(argv[7], NULL, 10);
    g_sysinfo.cur_secureboot = (int)strtol(argv[8], NULL, 10);
    size = ventoy_get_disk_size_in_byte(disk);
    scnprintf(g_sysinfo.cur_capacity, sizeof(g_sysinfo.cur_capacity), "%dGB", (int)ventoy_get_human_readable_gb(size));
    
    return 0;
}
int ventoy_disk_init(void)
{
    return 0;
}
void ventoy_disk_exit(void)
{
}
 | 15,716 | 
	C | 
	.c | 535 | 22.708411 | 119 | 0.55015 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 524 | 
	walk_disk.c | 
	ventoy_Ventoy/Unix/ventoy_unix_src/DragonFly/walk_disk.c | 
	/*-
 * Copyright (c) 1991, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Donn Seeley at Berkeley Software Design, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * @(#) Copyright (c) 1991, 1993 The Regents of the University of California.  All rights reserved.
 * @(#)init.c	8.1 (Berkeley) 7/15/93
 * $FreeBSD: src/sbin/init/init.c,v 1.38.2.8 2001/10/22 11:27:32 des Exp $
 */
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h>
#include <dirent.h>
#include <err.h>
#include <errno.h>
#include <fts.h>
#include <grp.h>
#include <inttypes.h>
#include <limits.h>
#include <locale.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <vtutil.h>
static int find_disk_by_signature(uint8_t *uuid, uint8_t *sig, uint64_t size, int *count, char *name)
{
    int fd;
    int len;
    int cnt = 0;
    FTS *ftsp;
	FTSENT *p;
    uint8_t mbr[512];
    char devname[MAXPATHLEN];
    static char dev[] = "/dev", *devav[] = {dev, NULL};
    vdebug("[VTOY] find_disk_by_signature %llu\n", size);
    ftsp = fts_open(devav, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
    while ((p = fts_read(ftsp)) != NULL)
    {
        if (p->fts_level == 1 && p->fts_statp && p->fts_name && p->fts_statp->st_size == size)
        {
            sprintf(devname, "/dev/%s", p->fts_name);
            fd = open(devname, O_RDONLY);
            if (fd < 0)
            {
                continue;
            }
            memset(mbr, 0, 512);
            read(fd, mbr, 512);
            close(fd);
            if (memcmp(mbr + 0x180, uuid, 16) == 0 && memcmp(mbr + 0x1B8, sig, 4) == 0)
            {
                cnt++;
                strcpy(name, p->fts_name);
                break;
            }
        }
    }
    *count = cnt;
    fts_close(ftsp);
    return 0;
}
static int find_disk_by_size(uint64_t size, const char *prefix, int *count, char *name)
{
    int len;
    int cnt = 0;
    FTS *ftsp;
	FTSENT *p;
    static char dev[] = "/dev", *devav[] = {dev, NULL};
    if (prefix)
    {
        len = strlen(prefix);
    }
    name[0] = 0;
    ftsp = fts_open(devav, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
    while ((p = fts_read(ftsp)) != NULL)
    {
        if (p->fts_level == 1 && p->fts_statp && p->fts_name && p->fts_statp->st_size == size)
        {
            if (prefix)
            {
                if (strncmp(p->fts_name, prefix, len) == 0)
                {
                    cnt++;
                    if (name[0] == 0)
                        strcpy(name, p->fts_name);
                }
            }
            else
            {
                cnt++;
                if (name[0] == 0)
                    strcpy(name, p->fts_name);
            }
        }
    }
    *count = cnt;
    fts_close(ftsp);
    return 0;
}
int prepare_dmtable(void)
{
    int count = 0;
    uint32_t i = 0;
    uint32_t sector_start = 0;
    uint32_t disk_sector_num = 0;
    FILE *fIn, *fOut;
    char disk[MAXPATHLEN];
    char prefix[MAXPATHLEN];
    ventoy_image_desc desc;
    ventoy_img_chunk chunk;
    
    fIn = fopen("/dmtable", "rb");
    if (!fIn)
    {
        printf("Failed to open dmtable\n");
        return 1;
    }
    
    fOut = fopen("/tmp/dmtable", "w+"); 
    if (!fOut)
    {
        printf("Failed to create /tmp/dmtable %d\n", errno);
        fclose(fIn);
        return 1;
    }
    fread(&desc, 1, sizeof(desc), fIn);
    
    vdebug("[VTOY] disksize:%lu part1size:%lu chunkcount:%u\n", desc.disk_size, desc.part1_size, desc.img_chunk_count);
    
    for (i = 0; count <= 0 && i < 10; i++)
    {
        sleep(2);
        find_disk_by_size(desc.part1_size, NULL, &count, disk);
        vdebug("[VTOY] find disk by part1 size, i=%d, count=%d, %s\n", i, count, disk);
    }
    if (count == 0)
    {
        goto end;
    }
    else if (count > 1)
    {
        find_disk_by_signature(desc.disk_uuid, desc.disk_signature, desc.disk_size, &count, prefix);
        vdebug("[VTOY] find disk by signature: %d %s\n", count, prefix);
        if (count != 1)
        {
            printf("[VTOY] Failed to find disk by signature\n");
            goto end;
        }
        find_disk_by_size(desc.part1_size, prefix, &count, disk);
        vdebug("[VTOY] find disk by part1 size with prefix %s : %d %s\n", prefix, count, disk);
    }
    for (i = 0; i < desc.img_chunk_count; i++)
    {
        fread(&chunk, 1, sizeof(chunk), fIn);
        sector_start = chunk.img_start_sector;
        disk_sector_num = (uint32_t)(chunk.disk_end_sector + 1 - chunk.disk_start_sector);
        fprintf(fOut, "%u %u linear /dev/%s %llu\n", 
               (sector_start << 2), disk_sector_num, 
               disk, (unsigned long long)chunk.disk_start_sector - 2048);
        
        vdebug("%u %u linear /dev/%s %llu\n", 
               (sector_start << 2), disk_sector_num, 
               disk, (unsigned long long)chunk.disk_start_sector - 2048);
    }
end:    
    fclose(fIn);   
    fclose(fOut);   
    return 0;
}
 | 6,591 | 
	C | 
	.c | 194 | 27.298969 | 119 | 0.593095 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 549 | 
	keyboard_layout.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/term/keyboard_layout.c | 
	
#define ventoy_keyboard_set_layout(name) if (grub_strcmp(layout, #name) == 0) return ventoy_keyboard_layout_##name()
static void ventoy_keyboard_layout_QWERTY_USA(void) {
    grub_keymap_reset();
    grub_keymap_disable();
}
static void ventoy_keyboard_layout_AZERTY(void) {
grub_keymap_reset();
grub_keymap_add_by_string("a", "q"); 
grub_keymap_add_by_string("A", "Q"); 
grub_keymap_add_by_string("z", "w"); 
grub_keymap_add_by_string("Z", "W"); 
grub_keymap_add_by_string("q", "a"); 
grub_keymap_add_by_string("Q", "A"); 
grub_keymap_add_by_string("m", "semicolon"); 
grub_keymap_add_by_string("M", "colon"); 
grub_keymap_add_by_string("w", "z"); 
grub_keymap_add_by_string("W", "Z"); 
grub_keymap_add_by_string("comma", "m"); 
grub_keymap_add_by_string("question", "M"); 
grub_keymap_add_by_string("semicolon", "comma"); 
grub_keymap_add_by_string("period", "less"); 
grub_keymap_add_by_string("colon", "period"); 
grub_keymap_add_by_string("slash", "greater"); 
grub_keymap_add_by_string("exclam", "slash"); 
grub_keymap_add_by_string("dollar", "bracketright"); 
grub_keymap_add_by_string("asterisk", "backslash"); 
grub_keymap_add_by_string("percent", "doublequote"); 
grub_keymap_add_by_string("ampersand", "1"); 
grub_keymap_add_by_string("1", "exclam"); 
grub_keymap_add_by_string("tilde", "2"); 
grub_keymap_add_by_string("2", "at"); 
grub_keymap_add_by_string("doublequote", "3"); 
grub_keymap_add_by_string("3", "numbersign"); 
grub_keymap_add_by_string("quote", "4"); 
grub_keymap_add_by_string("4", "dollar"); 
grub_keymap_add_by_string("parenleft", "5"); 
grub_keymap_add_by_string("5", "percent"); 
grub_keymap_add_by_string("minus", "6"); 
grub_keymap_add_by_string("6", "caret"); 
grub_keymap_add_by_string("backquote", "7"); 
grub_keymap_add_by_string("7", "ampersand"); 
grub_keymap_add_by_string("underscore", "8"); 
grub_keymap_add_by_string("8", "asterisk"); 
grub_keymap_add_by_string("caret", "9"); 
grub_keymap_add_by_string("9", "parenleft"); 
grub_keymap_add_by_string("at", "0"); 
grub_keymap_add_by_string("0", "parenright"); 
grub_keymap_add_by_string("parenright", "minus"); 
grub_keymap_add_by_string("less", "backquote"); 
grub_keymap_add_by_string("greater", "tilde"); 
grub_keymap_add_by_string("numbersign", "braceright"); 
grub_keymap_add_by_string("backslash", "question"); 
grub_keymap_add_by_string("bracketright", "braceleft"); 
grub_keymap_add_by_string("braceleft", "quote"); 
grub_keymap_add_by_string("braceright", "underscore"); 
grub_keymap_enable();
}
static void ventoy_keyboard_layout_CZECH_QWERTY(void) {
grub_keymap_reset();
grub_keymap_add_by_string("semicolon", "backquote");
grub_keymap_add_by_string("plus", "1");
grub_keymap_add_by_string("equal", "minus");
grub_keymap_add_by_string("quote", "equal");
grub_keymap_add_by_string("parenright", "bracketright");
grub_keymap_add_by_string("doublequote", "backslash");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("1", "exclam");
grub_keymap_add_by_string("2", "at");
grub_keymap_add_by_string("3", "numbersign");
grub_keymap_add_by_string("4", "dollar");
grub_keymap_add_by_string("5", "percent");
grub_keymap_add_by_string("6", "caret");
grub_keymap_add_by_string("7", "ampersand");
grub_keymap_add_by_string("8", "asterisk");
grub_keymap_add_by_string("9", "parenleft");
grub_keymap_add_by_string("0", "parenright");
grub_keymap_add_by_string("percent", "underscore");
grub_keymap_add_by_string("slash", "braceleft");
grub_keymap_add_by_string("parenleft", "braceright");
grub_keymap_add_by_string("doublequote", "colon");
grub_keymap_add_by_string("exclam", "doublequote");
grub_keymap_add_by_string("quote", "bar");
grub_keymap_add_by_string("question", "less");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("backquote", "Abackquote");
grub_keymap_add_by_string("exclam", "A1");
grub_keymap_add_by_string("at", "A2");
grub_keymap_add_by_string("numbersign", "A3");
grub_keymap_add_by_string("dollar", "A4");
grub_keymap_add_by_string("percent", "A5");
grub_keymap_add_by_string("caret", "A6");
grub_keymap_add_by_string("ampersand", "A7");
grub_keymap_add_by_string("asterisk", "A8");
grub_keymap_add_by_string("parenleft", "A9");
grub_keymap_add_by_string("parenright", "A0");
grub_keymap_add_by_string("minus", "Aminus");
grub_keymap_add_by_string("equal", "Aequal");
grub_keymap_add_by_string("bracketleft", "Abracketleft");
grub_keymap_add_by_string("bracketright", "Abracketright");
grub_keymap_add_by_string("semicolon", "Asemicolon");
grub_keymap_add_by_string("backslash", "Abackslash");
grub_keymap_add_by_string("less", "Acomma");
grub_keymap_add_by_string("greater", "Aperiod");
grub_keymap_add_by_string("slash", "Aslash");
grub_keymap_add_by_string("tilde", "Atilde");
grub_keymap_add_by_string("underscore", "Aunderscore");
grub_keymap_add_by_string("plus", "Aplus");
grub_keymap_add_by_string("braceleft", "Abraceleft");
grub_keymap_add_by_string("braceright", "Abraceright");
grub_keymap_add_by_string("caret", "Adoublequote");
grub_keymap_add_by_string("colon", "Acolon");
grub_keymap_add_by_string("question", "Aquestion");
grub_keymap_add_by_string("bar", "Abar");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_CZECH_QWERTZ(void) {
grub_keymap_reset();
grub_keymap_add_by_string("y", "z"); 
grub_keymap_add_by_string("z", "y"); 
grub_keymap_add_by_string("Y", "Z"); 
grub_keymap_add_by_string("Z", "Y");
grub_keymap_add_by_string("semicolon", "backquote");
grub_keymap_add_by_string("plus", "1");
grub_keymap_add_by_string("equal", "minus");
grub_keymap_add_by_string("quote", "equal");
grub_keymap_add_by_string("parenright", "bracketright");
grub_keymap_add_by_string("doublequote", "backslash");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("1", "exclam");
grub_keymap_add_by_string("2", "at");
grub_keymap_add_by_string("3", "numbersign");
grub_keymap_add_by_string("4", "dollar");
grub_keymap_add_by_string("5", "percent");
grub_keymap_add_by_string("6", "caret");
grub_keymap_add_by_string("7", "ampersand");
grub_keymap_add_by_string("8", "asterisk");
grub_keymap_add_by_string("9", "parenleft");
grub_keymap_add_by_string("0", "parenright");
grub_keymap_add_by_string("percent", "underscore");
grub_keymap_add_by_string("slash", "braceleft");
grub_keymap_add_by_string("parenleft", "braceright");
grub_keymap_add_by_string("doublequote", "colon");
grub_keymap_add_by_string("exclam", "doublequote");
grub_keymap_add_by_string("quote", "bar");
grub_keymap_add_by_string("question", "less");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("tilde", "A1");
grub_keymap_add_by_string("caret", "A3");
grub_keymap_add_by_string("backslash", "Aq");
grub_keymap_add_by_string("bar", "Aw");
grub_keymap_add_by_string("bracketleft", "Af");
grub_keymap_add_by_string("bracketright", "Ag");
grub_keymap_add_by_string("dollar", "Asemicolon");
grub_keymap_add_by_string("numbersign", "Ax");
grub_keymap_add_by_string("ampersand", "Ac");
grub_keymap_add_by_string("at", "Av");
grub_keymap_add_by_string("braceleft", "Ab");
grub_keymap_add_by_string("braceright", "An");
grub_keymap_add_by_string("less", "Acomma");
grub_keymap_add_by_string("greater", "Aperiod");
grub_keymap_add_by_string("asterisk", "Aslash");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_DANISH(void) {
grub_keymap_reset();
grub_keymap_add_by_string("plus", "minus");
grub_keymap_add_by_string("quote", "equal");
grub_keymap_add_by_string("doublequote", "bracketright");
grub_keymap_add_by_string("quote", "backslash");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("ampersand", "caret");
grub_keymap_add_by_string("slash", "ampersand");
grub_keymap_add_by_string("parenleft", "asterisk");
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("equal", "parenright");
grub_keymap_add_by_string("question", "underscore");
grub_keymap_add_by_string("caret", "braceright");
grub_keymap_add_by_string("asterisk", "bar");
grub_keymap_add_by_string("backquote", "plus");
grub_keymap_add_by_string("semicolon", "less");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("bar", "Atilde");
grub_keymap_add_by_string("backslash", "Abackquote");
grub_keymap_add_by_string("greater", "tilde");
grub_keymap_add_by_string("at", "A2");
grub_keymap_add_by_string("dollar", "A4");
grub_keymap_add_by_string("braceleft", "A7");
grub_keymap_add_by_string("bracketleft", "A8");
grub_keymap_add_by_string("bracketright", "A9");
grub_keymap_add_by_string("braceright", "A0");
grub_keymap_add_by_string("backslash", "Aminus");
grub_keymap_add_by_string("less", "quote");
grub_keymap_add_by_string("greater", "doublequote");
grub_keymap_add_by_string("tilde", "Abracketright");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_DVORAK_USA(void) {
grub_keymap_reset();
grub_keymap_add_by_string("[", "minus");
grub_keymap_add_by_string("braceleft", "underscore");
grub_keymap_add_by_string("quote", "q"); 
grub_keymap_add_by_string("doublequote", "Q"); 
grub_keymap_add_by_string("comma", "w"); 
grub_keymap_add_by_string("less", "W"); 
grub_keymap_add_by_string("s", "semicolon"); 
grub_keymap_add_by_string("S", "colon"); 
grub_keymap_add_by_string("semicolon", "z"); 
grub_keymap_add_by_string("colon", "Z"); 
grub_keymap_add_by_string("w", "comma"); 
grub_keymap_add_by_string("W", "less"); 
grub_keymap_add_by_string("v", "period"); 
grub_keymap_add_by_string("z", "greater"); 
grub_keymap_add_by_string("z", "slash"); 
grub_keymap_add_by_string("equal", "bracketright"); 
grub_keymap_add_by_string("backslash", "backslash"); 
grub_keymap_add_by_string("underscore", "doublequote"); 
grub_keymap_add_by_string("quote", "q");
grub_keymap_add_by_string("doublequote", "Q");
grub_keymap_add_by_string("comma", "w");
grub_keymap_add_by_string("less", "W");
grub_keymap_add_by_string("period", "e");
grub_keymap_add_by_string("greater", "E");
grub_keymap_add_by_string("p", "r");
grub_keymap_add_by_string("P", "R");
grub_keymap_add_by_string("y", "t");
grub_keymap_add_by_string("Y", "T");
grub_keymap_add_by_string("f", "y");
grub_keymap_add_by_string("F", "Y");
grub_keymap_add_by_string("g", "u");
grub_keymap_add_by_string("G", "U");
grub_keymap_add_by_string("c", "c");
grub_keymap_add_by_string("C", "I");
grub_keymap_add_by_string("r", "o");
grub_keymap_add_by_string("R", "O");
grub_keymap_add_by_string("l", "p");
grub_keymap_add_by_string("L", "P");
grub_keymap_add_by_string("bracketright", "equal");
grub_keymap_add_by_string("braceright", "plus");
grub_keymap_add_by_string("a", "a");
grub_keymap_add_by_string("A", "A");
grub_keymap_add_by_string("o", "s");
grub_keymap_add_by_string("O", "S");
grub_keymap_add_by_string("e", "d");
grub_keymap_add_by_string("E", "D");
grub_keymap_add_by_string("u", "f");
grub_keymap_add_by_string("U", "F");
grub_keymap_add_by_string("i", "g");
grub_keymap_add_by_string("I", "G");
grub_keymap_add_by_string("d", "h");
grub_keymap_add_by_string("D", "H");
grub_keymap_add_by_string("h", "j");
grub_keymap_add_by_string("H", "J");
grub_keymap_add_by_string("t", "k");
grub_keymap_add_by_string("T", "K");
grub_keymap_add_by_string("n", "l");
grub_keymap_add_by_string("N", "L");
grub_keymap_add_by_string("s", "semicolon");
grub_keymap_add_by_string("S", "colon");
grub_keymap_add_by_string("minus", "quote");
grub_keymap_add_by_string("underscore", "doublequote");
grub_keymap_add_by_string("semicolon", "z");
grub_keymap_add_by_string("colon", "Z");
grub_keymap_add_by_string("q", "x");
grub_keymap_add_by_string("Q", "X");
grub_keymap_add_by_string("j", "c");
grub_keymap_add_by_string("J", "C");
grub_keymap_add_by_string("k", "v");
grub_keymap_add_by_string("K", "V");
grub_keymap_add_by_string("x", "b");
grub_keymap_add_by_string("X", "B");
grub_keymap_add_by_string("b", "n");
grub_keymap_add_by_string("B", "N");
grub_keymap_add_by_string("w", "comma");
grub_keymap_add_by_string("W", "less");
grub_keymap_add_by_string("v", "period");
grub_keymap_add_by_string("V", "greater");
grub_keymap_add_by_string("z", "slash");
grub_keymap_add_by_string("Z", "question");
grub_keymap_add_by_string("slash", "bracketleft");
grub_keymap_add_by_string("question", "braceleft");
grub_keymap_add_by_string("equal", "bracketright");
grub_keymap_add_by_string("plus", "braceright");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_FRENCH(void) {
grub_keymap_reset();
grub_keymap_add_by_string("less", "backquote");
grub_keymap_add_by_string("greater", "tilde");
grub_keymap_add_by_string("ampersand", "1");
grub_keymap_add_by_string("1", "exclam");
grub_keymap_add_by_string("tilde", "2");
grub_keymap_add_by_string("2", "at");
grub_keymap_add_by_string("doublequote", "3");
grub_keymap_add_by_string("3", "numbersign");
grub_keymap_add_by_string("quote", "4");
grub_keymap_add_by_string("4", "dollar");
grub_keymap_add_by_string("parenleft", "5");
grub_keymap_add_by_string("5", "percent");
grub_keymap_add_by_string("minus", "6");
grub_keymap_add_by_string("6", "caret");
grub_keymap_add_by_string("backquote", "7");
grub_keymap_add_by_string("7", "ampersand");
grub_keymap_add_by_string("underscore", "8");
grub_keymap_add_by_string("8", "asterisk");
grub_keymap_add_by_string("backslash", "9");
grub_keymap_add_by_string("9", "parenleft");
grub_keymap_add_by_string("at", "0");
grub_keymap_add_by_string("0", "parenright");
grub_keymap_add_by_string("parenright", "minus");
grub_keymap_add_by_string("numbersign", "underscore");
grub_keymap_add_by_string("a", "q");
grub_keymap_add_by_string("A", "Q");
grub_keymap_add_by_string("z", "w");
grub_keymap_add_by_string("Z", "W");
grub_keymap_add_by_string("caret", "bracketleft");
grub_keymap_add_by_string("dollar", "bracketright");
grub_keymap_add_by_string("q", "a");
grub_keymap_add_by_string("Q", "A");
grub_keymap_add_by_string("m", "semicolon");
grub_keymap_add_by_string("M", "colon");
grub_keymap_add_by_string("bracketleft", "quote");
grub_keymap_add_by_string("percent", "doublequote");
grub_keymap_add_by_string("asterisk", "backslash");
grub_keymap_add_by_string("bracketright", "bar");
grub_keymap_add_by_string("w", "z");
grub_keymap_add_by_string("W", "Z");
grub_keymap_add_by_string("comma", "m");
grub_keymap_add_by_string("question", "M");
grub_keymap_add_by_string("semicolon", "comma");
grub_keymap_add_by_string("period", "less");
grub_keymap_add_by_string("colon", "period");
grub_keymap_add_by_string("slash", "greater");
grub_keymap_add_by_string("exclam", "slash");
grub_keymap_add_by_string("bar", "question");
grub_keymap_add_by_string("tilde", "A2");
grub_keymap_add_by_string("numbersign", "A3");
grub_keymap_add_by_string("braceleft", "A4");
grub_keymap_add_by_string("bracketleft", "A5");
grub_keymap_add_by_string("bar", "A6");
grub_keymap_add_by_string("quote", "A7");
grub_keymap_add_by_string("backslash", "A8");
grub_keymap_add_by_string("caret", "A9");
grub_keymap_add_by_string("at", "A0");
grub_keymap_add_by_string("bracketright", "Aminus");
grub_keymap_add_by_string("braceright", "Aequal");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_GERMAN(void) {
grub_keymap_reset();
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("ampersand", "caret");
grub_keymap_add_by_string("slash", "ampersand");
grub_keymap_add_by_string("parenleft", "asterisk");
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("equal", "parenright");
grub_keymap_add_by_string("question", "underscore");
grub_keymap_add_by_string("backslash", "minus");
grub_keymap_add_by_string("z", "y");
grub_keymap_add_by_string("Z", "Y");
grub_keymap_add_by_string("y", "z");
grub_keymap_add_by_string("Y", "Z");
grub_keymap_add_by_string("plus", "bracketright");
grub_keymap_add_by_string("asterisk", "braceright");
grub_keymap_add_by_string("semicolon", "less");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("backslash", "Aminus");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("caret", "backquote");
grub_keymap_add_by_string("quote", "equal");
grub_keymap_add_by_string("backquote", "plus");
grub_keymap_add_by_string("braceright", "doublequote");
grub_keymap_add_by_string("bar", "bracketleft");
grub_keymap_add_by_string("at", "braceleft");
grub_keymap_add_by_string("numbersign", "backslash");
grub_keymap_add_by_string("at", "Aq");
grub_keymap_add_by_string("less", "backquote");
grub_keymap_add_by_string("greater", "tilde");
grub_keymap_add_by_string("braceleft", "A7");
grub_keymap_add_by_string("bracketleft", "A8");
grub_keymap_add_by_string("bracketright", "A9");
grub_keymap_add_by_string("braceright", "A0");
grub_keymap_add_by_string("tilde", "Abracketright");
grub_keymap_add_by_string("backslash", "Aminus");
grub_keymap_add_by_string("quote", "bar");
grub_keymap_add_by_string("greater", "semicolon");
grub_keymap_add_by_string("less", "colon");
grub_keymap_add_by_string("bar", "quote");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_ITALIANO(void) {
grub_keymap_reset();
grub_keymap_add_by_string("backslash", "backquote");
grub_keymap_add_by_string("bar", "tilde");
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("tilde", "numbersign");
grub_keymap_add_by_string("ampersand", "caret");
grub_keymap_add_by_string("slash", "ampersand");
grub_keymap_add_by_string("parenleft", "asterisk");
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("equal", "parenright");
grub_keymap_add_by_string("quote", "minus");
grub_keymap_add_by_string("question", "underscore");
grub_keymap_add_by_string("caret", "plus");
grub_keymap_add_by_string("bracketleft", "bracketleft");
grub_keymap_add_by_string("bracketright", "braceleft");
grub_keymap_add_by_string("plus", "bracketright");
grub_keymap_add_by_string("asterisk", "braceright");
grub_keymap_add_by_string("at", "semicolon");
grub_keymap_add_by_string("braceleft", "colon");
grub_keymap_add_by_string("numbersign", "quote");
grub_keymap_add_by_string("braceright", "doublequote");
grub_keymap_add_by_string("less", "backslash");
grub_keymap_add_by_string("greater", "bar");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("semicolon", "less");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("bracketleft", "Abracketleft");
grub_keymap_add_by_string("bracketright", "Abracketright");
grub_keymap_add_by_string("at", "Asemicolon");
grub_keymap_add_by_string("numbersign", "Aquote");
grub_keymap_add_by_string("braceright", "Abraceright");
grub_keymap_add_by_string("braceleft", "Abraceleft");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_JAPAN_106(void) {
grub_keymap_reset();
grub_keymap_add_by_string("at", "bracketleft");
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("ampersand", "caret");
grub_keymap_add_by_string("quote", "ampersand");
grub_keymap_add_by_string("parenleft", "asterisk");
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("underscore", "parenright");
grub_keymap_add_by_string("equal", "underscore");
grub_keymap_add_by_string("plus", "colon");
grub_keymap_add_by_string("colon", "quote");
grub_keymap_add_by_string("asterisk", "doublequote");
grub_keymap_add_by_string("bracketleft", "bracketright");
grub_keymap_add_by_string("braceleft", "braceright");
grub_keymap_add_by_string("bracketright", "backslash");
grub_keymap_add_by_string("braceright", "bar");
grub_keymap_add_by_string("backslash", "backquote");
grub_keymap_add_by_string("tilde", "plus");
grub_keymap_add_by_string("caret", "equal");
grub_keymap_add_by_string("backquote", "braceleft");
grub_keymap_add_by_string("bar", "tilde");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_LATIN_USA(void) {
grub_keymap_reset();
grub_keymap_add_by_string("bar", "backquote");
grub_keymap_add_by_string("quote", "minus");
grub_keymap_add_by_string("question", "underscore");
grub_keymap_add_by_string("backquote", "bracketleft");
grub_keymap_add_by_string("plus", "bracketright");
grub_keymap_add_by_string("braceleft", "quote");
grub_keymap_add_by_string("braceright", "backslash");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("ampersand", "caret");
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("slash", "ampersand");
grub_keymap_add_by_string("parenleft", "asterisk");
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("equal", "parenright");
grub_keymap_add_by_string("asterisk", "braceright");
grub_keymap_add_by_string("bracketleft", "doublequote");
grub_keymap_add_by_string("bracketright", "bar");
grub_keymap_add_by_string("semicolon", "less");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("caret", "Aquote");
grub_keymap_add_by_string("doublequote", "braceleft");
grub_keymap_add_by_string("at", "Aq");
grub_keymap_add_by_string("backquote", "Abackslash");
grub_keymap_add_by_string("backslash", "Aminus");
grub_keymap_add_by_string("greater", "plus");
grub_keymap_add_by_string("less", "equal");
grub_keymap_add_by_string("backslash", "Aminus");
grub_keymap_add_by_string("backquote", "Abackslash");
grub_keymap_add_by_string("tilde", "Abracketright");
grub_keymap_add_by_string("caret", "Aquote");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_PORTU_BRAZIL(void) {
grub_keymap_reset();
grub_keymap_add_by_string("quote", "backquote");
grub_keymap_add_by_string("quote", "bracketleft");
grub_keymap_add_by_string("bracketleft", "bracketright");
grub_keymap_add_by_string("tilde", "quote");
grub_keymap_add_by_string("bracketright", "backslash");
grub_keymap_add_by_string("semicolon", "slash");
grub_keymap_add_by_string("bar", "colon");
grub_keymap_add_by_string("doublequote", "tilde");
grub_keymap_add_by_string("backquote", "braceleft");
grub_keymap_add_by_string("braceleft", "braceright");
grub_keymap_add_by_string("caret", "doublequote");
grub_keymap_add_by_string("braceright", "bar");
grub_keymap_add_by_string("colon", "question");
grub_keymap_add_by_string("backslash", "semicolon");
grub_keymap_add_by_string("bar", "Atilde");
grub_keymap_add_by_string("backslash", "Abackquote");
grub_keymap_add_by_string("slash", "Aq");
grub_keymap_add_by_string("question", "Aw");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_QWERTY_UK(void) {
grub_keymap_reset();
grub_keymap_add_by_string("at", "doublequote");
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("tilde", "bar");
grub_keymap_add_by_string("numbersign", "backslash");
grub_keymap_add_by_string("backslash", "numbersign");
grub_keymap_add_by_string("bar", "tilde");
grub_keymap_add_by_string("backslash", "Atilde");
grub_keymap_add_by_string("backslash", "Abackquote");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_QWERTZ(void) {
grub_keymap_reset();
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("ampersand", "percent");
grub_keymap_add_by_string("slash", "ampersand");
grub_keymap_add_by_string("equal", "parenright");
grub_keymap_add_by_string("question", "underscore");
grub_keymap_add_by_string("backslash", "minus");
grub_keymap_add_by_string("z", "y");
grub_keymap_add_by_string("Z", "Y");
grub_keymap_add_by_string("y", "z");
grub_keymap_add_by_string("Y", "Z");
grub_keymap_add_by_string("plus", "bracketright");
grub_keymap_add_by_string("asterisk", "braceright");
grub_keymap_add_by_string("semicolon", "less");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("caret", "backquote");
grub_keymap_add_by_string("backquote", "equal");
grub_keymap_add_by_string("numbersign", "backslash");
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("parenleft", "asterisk");
grub_keymap_add_by_string("percent", "caret"); 
grub_keymap_add_by_string("less", "numbersign"); 
grub_keymap_add_by_string("greater", "bar"); 
grub_keymap_enable();
}
static void ventoy_keyboard_layout_QWERTZ_HUN(void) {
grub_keymap_reset();
grub_keymap_add_by_string("y", "z"); 
grub_keymap_add_by_string("z", "y"); 
grub_keymap_add_by_string("Y", "Z"); 
grub_keymap_add_by_string("Z", "Y"); 
grub_keymap_add_by_string("0", "backquote");
grub_keymap_add_by_string("quote", "exclam");
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("plus", "numbersign");
grub_keymap_add_by_string("exclam", "dollar");
grub_keymap_add_by_string("slash", "caret");
grub_keymap_add_by_string("equal", "ampersand");
grub_keymap_add_by_string("parenleft", "asterisk"); 
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("backslash", "Aq");
grub_keymap_add_by_string("bar", "Aw");
grub_keymap_add_by_string("bracketleft", "Af"); 
grub_keymap_add_by_string("bracketright", "Ag");
grub_keymap_add_by_string("greater", "Az");
grub_keymap_add_by_string("numbersign", "Ax");
grub_keymap_add_by_string("ampersand", "Ac");
grub_keymap_add_by_string("at", "Av");
grub_keymap_add_by_string("braceleft", "Ab"); 
grub_keymap_add_by_string("braceright", "An");
grub_keymap_add_by_string("less", "Am");
grub_keymap_add_by_string("dollar", "colon");
grub_keymap_add_by_string("question", "less");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("at", "doublequote");
grub_keymap_add_by_string("tilde", "A1");
grub_keymap_add_by_string("caret", "A3");
grub_keymap_add_by_string("backquote", "A7");
grub_keymap_add_by_string("asterisk", "0");
grub_keymap_add_by_string("dollar", "Asemicolon");
grub_keymap_add_by_string("semicolon", "Acomma");
grub_keymap_add_by_string("greater", "Aperiod");
grub_keymap_add_by_string("asterisk", "Aslash");
grub_keymap_add_by_string("backquote", "A9");
grub_keymap_add_by_string("doublequote", "A0");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_QWERTZ_SLOV_CROAT(void) {
grub_keymap_reset();
grub_keymap_add_by_string("quote", "minus");
grub_keymap_add_by_string("plus", "equal");
grub_keymap_add_by_string("y", "z");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("doublequote", "tilde");
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("ampersand", "caret");
grub_keymap_add_by_string("slash", "ampersand");
grub_keymap_add_by_string("parenleft", "asterisk");
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("equal", "parenright");
grub_keymap_add_by_string("question", "underscore");
grub_keymap_add_by_string("asterisk", "plus");
grub_keymap_add_by_string("Y", "Z");
grub_keymap_add_by_string("semicolon", "less");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("tilde", "A1");
grub_keymap_add_by_string("caret", "A3");
grub_keymap_add_by_string("backquote", "A7");
grub_keymap_add_by_string("backslash", "Aq");
grub_keymap_add_by_string("bar", "Aw");
grub_keymap_add_by_string("bracketleft", "Af");
grub_keymap_add_by_string("bracketright", "Ag");
grub_keymap_add_by_string("at", "Av");
grub_keymap_add_by_string("braceleft", "Ab");
grub_keymap_add_by_string("braceright", "An");
grub_keymap_add_by_string("less", "Acomma");
grub_keymap_add_by_string("greater", "Aperiod");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_SPANISH(void) {
grub_keymap_reset();
grub_keymap_add_by_string("slash", "ampersand");
grub_keymap_add_by_string("ampersand", "caret");
grub_keymap_add_by_string("caret", "braceleft");
grub_keymap_add_by_string("asterisk", "braceright");
grub_keymap_add_by_string("parenleft", "asterisk");
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("equal", "parenright");
grub_keymap_add_by_string("quote", "minus");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("question", "underscore");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("greater", "bar");
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("backslash", "backquote");
grub_keymap_add_by_string("less", "backslash");
grub_keymap_add_by_string("semicolon", "less");
grub_keymap_add_by_string("backquote", "bracketleft");
grub_keymap_add_by_string("plus", "bracketright");
grub_keymap_add_by_string("plus", "colon");
grub_keymap_add_by_string("at", "semicolon");
grub_keymap_add_by_string("bar", "A1");
grub_keymap_add_by_string("at", "A2");
grub_keymap_add_by_string("numbersign", "A3");
grub_keymap_add_by_string("tilde", "A4");
grub_keymap_add_by_string("bracketleft", "Abracketleft");
grub_keymap_add_by_string("bracketright", "Abracketright");
grub_keymap_add_by_string("braceleft", "Aquote");
grub_keymap_add_by_string("braceright", "Abackslash");
grub_keymap_add_by_string("greater", "bar");
grub_keymap_add_by_string("less", "backslash");
grub_keymap_add_by_string("backslash", "Abackquote");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_SWEDISH(void) {
grub_keymap_reset();
grub_keymap_add_by_string("plus", "minus");
grub_keymap_add_by_string("quote", "equal");
grub_keymap_add_by_string("doublequote", "bracketright");
grub_keymap_add_by_string("quote", "backslash");
grub_keymap_add_by_string("minus", "slash");
grub_keymap_add_by_string("doublequote", "at");
grub_keymap_add_by_string("ampersand", "caret");
grub_keymap_add_by_string("slash", "ampersand");
grub_keymap_add_by_string("parenleft", "asterisk");
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("equal", "parenright");
grub_keymap_add_by_string("question", "underscore");
grub_keymap_add_by_string("caret", "braceright");
grub_keymap_add_by_string("asterisk", "bar");
grub_keymap_add_by_string("backquote", "plus");
grub_keymap_add_by_string("semicolon", "less");
grub_keymap_add_by_string("colon", "greater");
grub_keymap_add_by_string("underscore", "question");
grub_keymap_add_by_string("bar", "Atilde");
grub_keymap_add_by_string("backslash", "Abackquote");
grub_keymap_add_by_string("greater", "tilde");
grub_keymap_add_by_string("at", "A2");
grub_keymap_add_by_string("dollar", "A4");
grub_keymap_add_by_string("braceleft", "A7");
grub_keymap_add_by_string("bracketleft", "A8");
grub_keymap_add_by_string("bracketright", "A9");
grub_keymap_add_by_string("braceright", "A0");
grub_keymap_add_by_string("backslash", "Aminus");
grub_keymap_add_by_string("less", "quote");
grub_keymap_add_by_string("greater", "doublequote");
grub_keymap_add_by_string("tilde", "Abracketright");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_TURKISH_Q(void) {
grub_keymap_reset();
grub_keymap_add_by_string("doublequote", "backquote");
grub_keymap_add_by_string("asterisk", "minus");
grub_keymap_add_by_string("minus", "equal");
grub_keymap_add_by_string("comma", "backslash");
grub_keymap_add_by_string("period", "slash");
grub_keymap_add_by_string("quote", "at");
grub_keymap_add_by_string("caret", "numbersign");
grub_keymap_add_by_string("plus", "dollar");
grub_keymap_add_by_string("ampersand", "caret");
grub_keymap_add_by_string("slash", "ampersand");
grub_keymap_add_by_string("parenleft", "asterisk");
grub_keymap_add_by_string("parenright", "parenleft");
grub_keymap_add_by_string("equal", "parenright");
grub_keymap_add_by_string("question", "underscore");
grub_keymap_add_by_string("underscore", "plus");
grub_keymap_add_by_string("semicolon", "bar");
grub_keymap_add_by_string("colon", "question");
grub_keymap_add_by_string("less", "Abackquote");
grub_keymap_add_by_string("greater", "A1");
grub_keymap_add_by_string("numbersign", "A3");
grub_keymap_add_by_string("dollar", "A4");
grub_keymap_add_by_string("braceleft", "A7");
grub_keymap_add_by_string("bracketleft", "A8");
grub_keymap_add_by_string("bracketright", "A9");
grub_keymap_add_by_string("braceright", "A0");
grub_keymap_add_by_string("backslash", "Aminus");
grub_keymap_add_by_string("bar", "Aequal");
grub_keymap_add_by_string("at", "Aq");
grub_keymap_add_by_string("doublequote", "Abracketleft");
grub_keymap_add_by_string("tilde", "Abracketright");
grub_keymap_enable();
}
static void ventoy_keyboard_layout_VIETNAMESE(void) {
grub_keymap_reset();
grub_keymap_add_by_string("exclam", "A1");
grub_keymap_add_by_string("at", "A2");
grub_keymap_add_by_string("numbersign", "A3");
grub_keymap_add_by_string("dollar", "A4");
grub_keymap_add_by_string("percent", "A5");
grub_keymap_add_by_string("caret", "A6");
grub_keymap_add_by_string("ampersand", "A7");
grub_keymap_add_by_string("asterisk", "A8");
grub_keymap_add_by_string("parenleft", "A9");
grub_keymap_add_by_string("parenright", "A0");
grub_keymap_add_by_string("plus", "Aplus");
grub_keymap_add_by_string("equal", "Aequal");
grub_keymap_add_by_string("braceleft", "Abraceleft");
grub_keymap_add_by_string("braceright", "Abraceright");
grub_keymap_add_by_string("colon", "Acolon");
grub_keymap_add_by_string("semicolon", "Asemicolon");
grub_keymap_add_by_string("quote", "Aquote");
grub_keymap_add_by_string("backslash", "Abackslash");
grub_keymap_add_by_string("less", "Aless");
grub_keymap_add_by_string("greater", "Agreater");
grub_keymap_add_by_string("comma", "Acomma");
grub_keymap_add_by_string("period", "Aperiod");
grub_keymap_add_by_string("question", "Aquestion");
grub_keymap_add_by_string("slash", "Aslash");
grub_keymap_add_by_string("tilde", "Atilde");
grub_keymap_add_by_string("backquote", "Abackquote");
grub_keymap_add_by_string("bracketright", "Abracketright");
grub_keymap_add_by_string("bracketleft", "Abracketleft");
grub_keymap_add_by_string("bar", "Abar");
grub_keymap_add_by_string("doublequote", "Adoublequote");
grub_keymap_add_by_string("colon", "Acolon");
grub_keymap_add_by_string("minus", "Aminus");
grub_keymap_add_by_string("underscore", "Aunderscore");
grub_keymap_enable();
}
void ventoy_set_keyboard_layout(const char *layout);
void ventoy_set_keyboard_layout(const char *layout) {
ventoy_keyboard_set_layout(QWERTY_USA);
ventoy_keyboard_set_layout(AZERTY);
ventoy_keyboard_set_layout(CZECH_QWERTY);
ventoy_keyboard_set_layout(CZECH_QWERTZ);
ventoy_keyboard_set_layout(DANISH);
ventoy_keyboard_set_layout(DVORAK_USA);
ventoy_keyboard_set_layout(FRENCH);
ventoy_keyboard_set_layout(GERMAN);
ventoy_keyboard_set_layout(ITALIANO);
ventoy_keyboard_set_layout(JAPAN_106);
ventoy_keyboard_set_layout(LATIN_USA);
ventoy_keyboard_set_layout(PORTU_BRAZIL);
ventoy_keyboard_set_layout(QWERTY_UK);
ventoy_keyboard_set_layout(QWERTZ);
ventoy_keyboard_set_layout(QWERTZ_HUN);
ventoy_keyboard_set_layout(QWERTZ_SLOV_CROAT);
ventoy_keyboard_set_layout(SPANISH);
ventoy_keyboard_set_layout(SWEDISH);
ventoy_keyboard_set_layout(TURKISH_Q);
ventoy_keyboard_set_layout(VIETNAMESE);
}
 | 35,181 | 
	C | 
	.c | 793 | 43.254729 | 116 | 0.719682 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 550 | 
	setkey.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/term/setkey.c | 
	/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 2020  Free Software Foundation, Inc.
 *
 *  GRUB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GRUB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <grub/types.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/env.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/extcmd.h>
#include <grub/i18n.h>
#include <grub/term.h>
GRUB_MOD_LICENSE ("GPLv3+");
#define MAX_KEYMAP 255
struct keymap
{
  int cnt;
  int in[MAX_KEYMAP];
  int out[MAX_KEYMAP];
};
static struct keymap setkey_keymap;
struct keysym
{
  const char *name; /* the name in unshifted state */
  int code;   /* scan code */
};
/* The table for key symbols. (from GRUB4DOS) */
static struct keysym keysym_table[] =
{
  {"escape",        GRUB_TERM_ESC},    // ESC
  {"exclam",        0x21},    //    '!'
  {"at",            0x40},    //    '@'
  {"numbersign",    0x23},    //    '#'
  {"dollar",        0x24},    //    '$'
  {"percent",       0x25},    //    '%'
  {"caret",         0x5E},    //    '^'
  {"ampersand",     0x26},    //    '&'
  {"asterisk",      0x2A},    //    '*'
  {"parenleft",     0x28},    //    '('
  {"parenright",    0x29},    //    ')'
  {"minus",         0x2D},    //    '-'
  {"underscore",    0x5F},    //    '_'
  {"equal",         0x3D},    //    '='
  {"plus",          0x2B},    //    '+'
  {"backspace",     GRUB_TERM_BACKSPACE},    // BS
  {"ctrlbackspace", GRUB_TERM_CTRL | GRUB_TERM_BACKSPACE}, // (DEL)
  {"tab",           GRUB_TERM_TAB},    // Tab
  {"bracketleft",   0x5B},    // '['
  {"braceleft",     0x7B},    //    '{'
  {"bracketright",  0x5D},    // ']'
  {"braceright",    0x7D},    //    '}'
  {"enter",         0x0D},    // Enter
  {"semicolon",     0x3B},    // ';'
  {"colon",         0x3A},    //    ':'
  {"quote",         0x27},    // '\''
  {"doublequote",   0x22},    //    '"'
  {"backquote",     0x60},    // '`'
  {"tilde",         0x7E},    //    '~'
  {"backslash",     0x5C},    // '\\'
  {"bar",           0x7C},    //    '|'
  {"comma",         0x2C},    // ','
  {"less",          0x3C},    //    '<'
  {"period",        0x2E},    // '.'
  {"greater",       0x3E},    //    '>'
  {"slash",         0x2F},    // '/'
  {"question",      0x3F},    //    '?'
  {"space",         0x20},    // Space
  {"F1",            GRUB_TERM_KEY_F1},
  {"F2",            GRUB_TERM_KEY_F2},
  {"F3",            GRUB_TERM_KEY_F3},
  {"F4",            GRUB_TERM_KEY_F4},
  {"F5",            GRUB_TERM_KEY_F5},
  {"F6",            GRUB_TERM_KEY_F6},
  {"F7",            GRUB_TERM_KEY_F7},
  {"F8",            GRUB_TERM_KEY_F8},
  {"F9",            GRUB_TERM_KEY_F9},
  {"F10",           GRUB_TERM_KEY_F10},
  {"F11",           GRUB_TERM_KEY_F11},
  {"F12",           GRUB_TERM_KEY_F12},
  {"home",          GRUB_TERM_KEY_HOME},
  {"uparrow",       GRUB_TERM_KEY_UP},
  {"pageup",        GRUB_TERM_KEY_NPAGE},    // PgUp
  {"leftarrow",     GRUB_TERM_KEY_LEFT},
  {"center",        GRUB_TERM_KEY_CENTER},    // keypad center key
  {"rightarrow",    GRUB_TERM_KEY_RIGHT},
  {"end",           GRUB_TERM_KEY_END},
  {"downarrow",     GRUB_TERM_KEY_DOWN},
  {"pagedown",      GRUB_TERM_KEY_PPAGE},    // PgDn
  {"insert",        GRUB_TERM_KEY_INSERT},    // Insert
  {"delete",        GRUB_TERM_KEY_DC},    // Delete
  {"shiftF1",       GRUB_TERM_SHIFT | GRUB_TERM_KEY_F1},
  {"shiftF2",       GRUB_TERM_SHIFT | GRUB_TERM_KEY_F2},
  {"shiftF3",       GRUB_TERM_SHIFT | GRUB_TERM_KEY_F3},
  {"shiftF4",       GRUB_TERM_SHIFT | GRUB_TERM_KEY_F4},
  {"shiftF5",       GRUB_TERM_SHIFT | GRUB_TERM_KEY_F5},
  {"shiftF6",       GRUB_TERM_SHIFT | GRUB_TERM_KEY_F6},
  {"shiftF7",       GRUB_TERM_SHIFT | GRUB_TERM_KEY_F7},
  {"shiftF8",       GRUB_TERM_SHIFT | GRUB_TERM_KEY_F8},
  {"shiftF9",       GRUB_TERM_SHIFT | GRUB_TERM_KEY_F9},
  {"shiftF10",      GRUB_TERM_SHIFT | GRUB_TERM_KEY_F10},
  {"shiftF11",      GRUB_TERM_SHIFT | GRUB_TERM_KEY_F11},
  {"shiftF12",      GRUB_TERM_SHIFT | GRUB_TERM_KEY_F12},
  {"ctrlF1",        GRUB_TERM_CTRL | GRUB_TERM_KEY_F1},
  {"ctrlF2",        GRUB_TERM_CTRL | GRUB_TERM_KEY_F2},
  {"ctrlF3",        GRUB_TERM_CTRL | GRUB_TERM_KEY_F3},
  {"ctrlF4",        GRUB_TERM_CTRL | GRUB_TERM_KEY_F4},
  {"ctrlF5",        GRUB_TERM_CTRL | GRUB_TERM_KEY_F5},
  {"ctrlF6",        GRUB_TERM_CTRL | GRUB_TERM_KEY_F6},
  {"ctrlF7",        GRUB_TERM_CTRL | GRUB_TERM_KEY_F7},
  {"ctrlF8",        GRUB_TERM_CTRL | GRUB_TERM_KEY_F8},
  {"ctrlF9",        GRUB_TERM_CTRL | GRUB_TERM_KEY_F9},
  {"ctrlF10",       GRUB_TERM_CTRL | GRUB_TERM_KEY_F10},
  {"ctrlF11",       GRUB_TERM_CTRL | GRUB_TERM_KEY_F11},
  {"ctrlF12",       GRUB_TERM_CTRL | GRUB_TERM_KEY_F12},
  // A=Alt or AltGr.    Provided by steve.
  {"Aq",            GRUB_TERM_ALT | 0x71},
  {"Aw",            GRUB_TERM_ALT | 0x77},
  {"Ae",            GRUB_TERM_ALT | 0x65},
  {"Ar",            GRUB_TERM_ALT | 0x72},
  {"At",            GRUB_TERM_ALT | 0x74},
  {"Ay",            GRUB_TERM_ALT | 0x79},
  {"Au",            GRUB_TERM_ALT | 0x75},
  {"Ai",            GRUB_TERM_ALT | 0x69},
  {"Ao",            GRUB_TERM_ALT | 0x6F},
  {"Ap",            GRUB_TERM_ALT | 0x70},
  {"Aa",            GRUB_TERM_ALT | 0x61},
  {"As",            GRUB_TERM_ALT | 0x73},
  {"Ad",            GRUB_TERM_ALT | 0x64},
  {"Af",            GRUB_TERM_ALT | 0x66},
  {"Ag",            GRUB_TERM_ALT | 0x67},
  {"Ah",            GRUB_TERM_ALT | 0x68},
  {"Aj",            GRUB_TERM_ALT | 0x6A},
  {"Ak",            GRUB_TERM_ALT | 0x6B},
  {"Al",            GRUB_TERM_ALT | 0x6C},
  {"Az",            GRUB_TERM_ALT | 0x7A},
  {"Ax",            GRUB_TERM_ALT | 0x78},
  {"Ac",            GRUB_TERM_ALT | 0x63},
  {"Av",            GRUB_TERM_ALT | 0x76},
  {"Ab",            GRUB_TERM_ALT | 0x62},
  {"An",            GRUB_TERM_ALT | 0x6E},
  {"Am",            GRUB_TERM_ALT | 0x6D},
  {"A1",            GRUB_TERM_ALT | 0x31},
  {"A2",            GRUB_TERM_ALT | 0x32},
  {"A3",            GRUB_TERM_ALT | 0x33},
  {"A4",            GRUB_TERM_ALT | 0x34},
  {"A5",            GRUB_TERM_ALT | 0x35},
  {"A6",            GRUB_TERM_ALT | 0x36},
  {"A7",            GRUB_TERM_ALT | 0x37},
  {"A8",            GRUB_TERM_ALT | 0x38},
  {"A9",            GRUB_TERM_ALT | 0x39},
  {"A0",            GRUB_TERM_ALT | 0x30},
  //{"oem102",        0x5c},
  //{"shiftoem102",   0x7c},
  {"Aminus",        GRUB_TERM_ALT | 0x2D},
  {"Aequal",        GRUB_TERM_ALT | 0x3D},
  {"Abracketleft",  GRUB_TERM_ALT | 0x5B},
  {"Abracketright", GRUB_TERM_ALT | 0x5D},
  {"Asemicolon",    GRUB_TERM_ALT | 0x3B},
  {"Aquote",        GRUB_TERM_ALT | 0x27},
  {"Abackquote",    GRUB_TERM_ALT | 0x60},
  {"Abackslash",    GRUB_TERM_ALT | 0x5C},
  {"Acomma",        GRUB_TERM_ALT | 0x2C},
  {"Aperiod",       GRUB_TERM_ALT | 0x2E},
  {"Aslash",        GRUB_TERM_ALT | 0x2F},
  {"Acolon",        GRUB_TERM_ALT | 0x3A},
  {"Aplus",         GRUB_TERM_ALT | 0x2B},
  {"Aless",         GRUB_TERM_ALT | 0x3C},
  {"Aunderscore",   GRUB_TERM_ALT | 0x5F},
  {"Agreater",      GRUB_TERM_ALT | 0x3E},
  {"Aquestion",     GRUB_TERM_ALT | 0x3F},
  {"Atilde",        GRUB_TERM_ALT | 0x7E},
  {"Abraceleft",    GRUB_TERM_ALT | 0x7B},
  {"Abar",          GRUB_TERM_ALT | 0x7C},
  {"Abraceright",   GRUB_TERM_ALT | 0x7D},
  {"Adoublequote",  GRUB_TERM_ALT | 0x22},
};
static int grub_keymap_getkey (int key)
{
  int i;
  if (key == GRUB_TERM_NO_KEY)
    return key;
  if (setkey_keymap.cnt > MAX_KEYMAP)
    setkey_keymap.cnt = MAX_KEYMAP;
  for (i = 0; i < setkey_keymap.cnt; i++)
  {
    if (key == setkey_keymap.in[i])
    {
      key = setkey_keymap.out[i];
      break;
    }
  }
  return key;
}
static void
grub_keymap_reset (void)
{
  grub_memset (&setkey_keymap, 0, sizeof (struct keymap));
}
static grub_err_t
grub_keymap_add (int in, int out)
{
  if (in == GRUB_TERM_NO_KEY || out == GRUB_TERM_NO_KEY)
    return grub_error (GRUB_ERR_BAD_ARGUMENT, "invalid key: %d -> %d", in, out);
  if (setkey_keymap.cnt >= MAX_KEYMAP)
    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
                       "keymap FULL %d", setkey_keymap.cnt);
  setkey_keymap.in[setkey_keymap.cnt] = in;
  setkey_keymap.out[setkey_keymap.cnt] = out;
  setkey_keymap.cnt++;
  return GRUB_ERR_NONE;
}
static void
grub_keymap_enable (void)
{
  grub_key_remap = grub_keymap_getkey;
}
static void
grub_keymap_disable (void)
{
  grub_key_remap = NULL;
}
static void
grub_keymap_status (void)
{
  int i;
  if (setkey_keymap.cnt > MAX_KEYMAP)
    setkey_keymap.cnt = MAX_KEYMAP;
  for (i = 0; i < setkey_keymap.cnt; i++)
  {
    grub_printf ("0x%x -> 0x%x\n", setkey_keymap.in[i], setkey_keymap.out[i]);
  }
}
static const struct grub_arg_option options[] =
{
  {"reset", 'r', 0, N_("Reset keymap."), 0, 0},
  {"enable", 'e', 0, N_("Enable keymap."), 0, 0},
  {"disable", 'd', 0, N_("Disable keymap."), 0, 0},
  {"status", 's', 0, N_("Display keymap."), 0, 0},
  {0, 0, 0, 0, 0, 0}
};
enum options
{
  SETKEY_RESET,
  SETKEY_ENABLE,
  SETKEY_DISABLE,
  SETKEY_STATUS,
};
static int
ishex (const char *str)
{
  if (grub_strlen (str) < 3 || str[0] != '0')
    return 0;
  if (str[1] != 'x' && str[1] != 'X')
    return 0;
  return 1;
}
static int
parse_key (const char *str)
{
  int i;
  if (ishex (str))
    return grub_strtol (str, NULL, 16);
  if (grub_strlen (str) == 1)
    return (int) str[0];
  for (i = 0; i < (int) (sizeof (keysym_table) / sizeof (keysym_table[0])); i++)
  {
    if (grub_strcmp (str, keysym_table[i].name) == 0)
      return keysym_table[i].code;
  }
  grub_error (GRUB_ERR_BAD_ARGUMENT, "invalid key %s", str);
  return 0;
}
static grub_err_t
grub_cmd_setkey (grub_extcmd_context_t ctxt, int argc, char **args)
{
  struct grub_arg_list *state = ctxt->state;
  int in, out;
  if (state[SETKEY_ENABLE].set)
  {
    grub_keymap_enable ();
    goto out;
  }
  if (state[SETKEY_DISABLE].set)
  {
    grub_keymap_disable ();
    goto out;
  }
  if (state[SETKEY_RESET].set)
  {
    grub_keymap_reset ();
    goto out;
  }
  if (state[SETKEY_STATUS].set)
  {
    grub_keymap_status ();
    goto out;
  }
  if (argc != 2)
  {
    grub_printf
      ("Key names: 0-9, A-Z, a-z or escape, exclam, at, numbersign, dollar,"
       "percent, caret, ampersand, asterisk, parenleft, parenright, minus,"
       "underscore, equal, plus, backspace, tab, bracketleft, braceleft,"
       "bracketright, braceright, enter, semicolon, colon, quote, doublequote,"
       "backquote, tilde, backslash, bar, comma, less, period, greater,"
       "slash, question, alt, space, delete, [ctrl|shift]F1-12."
       "For Alt+ prefix with A, e.g. \'setkey at Aequal\'.");
    goto out;
  }
  in = parse_key (args[1]);
  out = parse_key (args[0]);
  if (!in || !out)
    goto out;
  grub_keymap_add (in, out);
out:
  return grub_errno;
}
static void grub_keymap_add_by_string(const char *src, const char *dst)
{
    int in = 0;
    int out = 0;
    
    in = parse_key(dst);
    out = parse_key(src);
    if (in && out)
    {
        grub_keymap_add (in, out);        
    }
}
#include "keyboard_layout.c"
static grub_err_t grub_cmd_set_keylayout (grub_extcmd_context_t ctxt, int argc, char **args)
{
    (void)ctxt;
    (void)argc;
    ventoy_set_keyboard_layout(args[0]);
    return 0;
}
static grub_extcmd_t cmd, setcmd;
GRUB_MOD_INIT(setkey)
{
  cmd = grub_register_extcmd ("setkey", grub_cmd_setkey, 0, N_("NEW_KEY USA_KEY"),
                              N_("Map default USA_KEY to NEW_KEY."), options);
  setcmd = grub_register_extcmd ("set_keyboard_layout", grub_cmd_set_keylayout, 0, N_("layout"),
                              N_("Set keyboard layout."), NULL);
}
GRUB_MOD_FINI(setkey)
{
  grub_unregister_extcmd (cmd);
}
 | 12,150 | 
	C | 
	.c | 362 | 30.383978 | 96 | 0.5438 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 551 | 
	mouse.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/term/efi/mouse.c | 
	/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 2022  Free Software Foundation, Inc.
 *
 *  GRUB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GRUB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <grub/dl.h>
#include <grub/term.h>
#include <grub/misc.h>
#include <grub/types.h>
#include <grub/command.h>
#include <grub/i18n.h>
#include <grub/err.h>
#include <grub/env.h>
#include <grub/efi/efi.h>
#include <grub/efi/api.h>
GRUB_MOD_LICENSE ("GPLv3+");
#define GRUB_EFI_SIMPLE_POINTER_GUID  \
  { 0x31878c87, 0x0b75, 0x11d5, \
    { 0x9a, 0x4f, 0x00, 0x90, 0x27, 0x3f, 0xc1, 0x4d } \
  }
typedef struct
{
  grub_efi_int32_t x;
  grub_efi_int32_t y;
  grub_efi_int32_t z;
  grub_efi_boolean_t left;
  grub_efi_boolean_t right;
} grub_efi_mouse_state;
grub_efi_mouse_state no_move = {0, 0, 0, 0, 0};
typedef struct
{
  grub_efi_uint64_t x;
  grub_efi_uint64_t y;
  grub_efi_uint64_t z;
  grub_efi_boolean_t left;
  grub_efi_boolean_t right;
} grub_efi_mouse_mode;
struct grub_efi_simple_pointer_protocol
{
  grub_efi_status_t (*reset) (struct grub_efi_simple_pointer_protocol *this,
                              grub_efi_boolean_t extended_verification);
  grub_efi_status_t (*get_state) (struct grub_efi_simple_pointer_protocol *this,
                                  grub_efi_mouse_state *state);
  grub_efi_event_t *wait_for_input;
  grub_efi_mouse_mode *mode;
};
typedef struct grub_efi_simple_pointer_protocol grub_efi_simple_pointer_protocol_t;
typedef struct
{
  grub_efi_uintn_t count;
  grub_efi_simple_pointer_protocol_t **mouse;
} grub_efi_mouse_prot_t;
static grub_int32_t
mouse_div (grub_int32_t a, grub_uint64_t b)
{
  grub_int32_t s = 1, q, ret;
  grub_uint64_t n = a;
  if (!b)
    return 0;
  if (a < 0)
  {
    s = -1;
    n = -a;
  }
  q = grub_divmod64 (n, b, NULL);
  ret = s * (q > 0 ? q : -q);
  return ret;
}
static grub_efi_mouse_prot_t *
grub_efi_mouse_prot_init (void)
{
  grub_efi_status_t status;
  grub_efi_guid_t mouse_guid = GRUB_EFI_SIMPLE_POINTER_GUID;
  grub_efi_mouse_prot_t *mouse_input = NULL;
  grub_efi_boot_services_t *b = grub_efi_system_table->boot_services;
  grub_efi_handle_t *buf;
  grub_efi_uintn_t count;
  grub_efi_uintn_t i;
  status = efi_call_5 (b->locate_handle_buffer, GRUB_EFI_BY_PROTOCOL,
                       &mouse_guid, NULL, &count, &buf);
  if (status != GRUB_EFI_SUCCESS)
  {
#ifdef MOUSE_DEBUG
    grub_printf ("ERROR: SimplePointerProtocol not found.\n");
#endif
    return NULL;
  }
  mouse_input = grub_malloc (sizeof (grub_efi_mouse_prot_t));
  if (!mouse_input)
    goto end;
  mouse_input->mouse = grub_malloc (count
            * sizeof (grub_efi_simple_pointer_protocol_t *));
  if (!mouse_input->mouse)
  {
    grub_free (mouse_input);
    mouse_input = NULL;
    goto end;
  }
  mouse_input->count = count;
  for (i = 0; i < count; i++)
  {
    efi_call_3 (b->handle_protocol,
                buf[i], &mouse_guid, (void **)&mouse_input->mouse[i]);
#ifdef MOUSE_DEBUG
    grub_printf ("%d %p ", (int)i, mouse_input->mouse[i]);
#endif
    efi_call_2 (mouse_input->mouse[i]->reset, mouse_input->mouse[i], 1);
#ifdef MOUSE_DEBUG
    grub_printf
      ("[%"PRIuGRUB_UINT64_T"] [%"PRIuGRUB_UINT64_T"] [%"PRIuGRUB_UINT64_T"]\n",
       mouse_input->mouse[i]->mode->x,
       mouse_input->mouse[i]->mode->y, mouse_input->mouse[i]->mode->z);
#endif
  }
  
end:  
  efi_call_1(b->free_pool, buf);
  return mouse_input;
}
static grub_err_t
grub_efi_mouse_input_init (struct grub_term_input *term)
{
  grub_efi_mouse_prot_t *mouse_input = NULL;
  if (term->data)
    return 0;
  mouse_input = grub_efi_mouse_prot_init ();
  if (!mouse_input)
    return GRUB_ERR_BAD_OS;
  term->data = (void *)mouse_input;
  return 0;
}
static int
grub_mouse_getkey (struct grub_term_input *term)
{
  grub_efi_mouse_state cur;
  grub_efi_mouse_prot_t *mouse = term->data;
  //int x;
  int y;
  int delta = 0;
  const char *env;
  grub_efi_uintn_t i;
  if (!mouse)
    return GRUB_TERM_NO_KEY;
  env = grub_env_get("mouse_delta");
  if (env)
    delta = (int)grub_strtol(env, NULL, 10);
  
  for (i = 0; i < mouse->count; i++)
  {
    efi_call_2 (mouse->mouse[i]->get_state, mouse->mouse[i], &cur);
    if (grub_memcmp (&cur, &no_move, sizeof (grub_efi_mouse_state)) != 0)
    {
      y = mouse_div (cur.y, mouse->mouse[i]->mode->y);
      if (cur.left)
        return 0x0d;
      if (cur.right)
        return GRUB_TERM_ESC;
      if (y > delta)
        return GRUB_TERM_KEY_DOWN;
      if (y < -delta)
        return GRUB_TERM_KEY_UP;
    }
  }
  return GRUB_TERM_NO_KEY;
}
#ifdef MOUSE_DEBUG
static grub_err_t
grub_cmd_mouse_test (grub_command_t cmd __attribute__ ((unused)),
                    int argc __attribute__ ((unused)),
                    char **args __attribute__ ((unused)))
{
  grub_efi_mouse_state cur;
  int x = 0, y = 0, z = 0;
  grub_efi_uintn_t i;
  grub_efi_mouse_prot_t *mouse = NULL;
  mouse = grub_efi_mouse_prot_init ();
  if (!mouse)
    return grub_error (GRUB_ERR_BAD_OS, "mouse not found.\n");
  grub_printf ("Press [1] to exit.\n");
  while (1)
  {
    if (grub_getkey_noblock () == '1')
      break;
    for (i = 0; i < mouse->count; i++)
    {
      efi_call_2 (mouse->mouse[i]->get_state, mouse->mouse[i], &cur);
      if (grub_memcmp (&cur, &no_move, sizeof (grub_efi_mouse_state)) != 0)
      {
        x = mouse_div (cur.x, mouse->mouse[i]->mode->x);
        y = mouse_div (cur.y, mouse->mouse[i]->mode->y);
        z = mouse_div (cur.z, mouse->mouse[i]->mode->z);
        grub_printf ("[ID=%d] X=%d Y=%d Z=%d L=%d R=%d\n",
                     (int)i, x, y, z, cur.left, cur.right);
      }
    }
    grub_refresh ();
  }
  grub_free (mouse->mouse);
  grub_free (mouse);
  return GRUB_ERR_NONE;
}
static grub_command_t cmd;
#endif
static struct grub_term_input grub_mouse_term_input =
{
  .name = "mouse",
  .getkey = grub_mouse_getkey,
  .init = grub_efi_mouse_input_init,
};
GRUB_MOD_INIT(mouse)
{
  grub_term_register_input ("mouse", &grub_mouse_term_input);
#ifdef MOUSE_DEBUG
  cmd = grub_register_command ("mouse_test", grub_cmd_mouse_test, 0,
                               N_("UEFI mouse test."));
#endif
}
GRUB_MOD_FINI(mouse)
{
  grub_term_unregister_input (&grub_mouse_term_input);
#ifdef MOUSE_DEBUG
  grub_unregister_command (cmd);
#endif
}
 | 6,812 | 
	C | 
	.c | 234 | 25.15812 | 83 | 0.639737 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 556 | 
	relocator.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/lib/mips64/relocator.c | 
	/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 2017  Free Software Foundation, Inc.
 *
 *  GRUB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GRUB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <grub/mm.h>
#include <grub/misc.h>
#include <grub/types.h>
#include <grub/types.h>
#include <grub/err.h>
#include <grub/cache.h>
#include <grub/mips64/relocator.h>
#include <grub/relocator_private.h>
extern grub_uint8_t grub_relocator_forward_start;
extern grub_uint8_t grub_relocator_forward_end;
extern grub_uint8_t grub_relocator_backward_start;
extern grub_uint8_t grub_relocator_backward_end;
#define REGW_SIZEOF (6 * sizeof (grub_uint32_t))
#define JUMP_SIZEOF (2 * sizeof (grub_uint32_t))
#define RELOCATOR_SRC_SIZEOF(x) (&grub_relocator_##x##_end \
				 - &grub_relocator_##x##_start)
#define RELOCATOR_SIZEOF(x)	(RELOCATOR_SRC_SIZEOF(x) \
				 + REGW_SIZEOF * 3)
grub_size_t grub_relocator_align = sizeof (grub_uint64_t);
grub_size_t grub_relocator_forward_size;
grub_size_t grub_relocator_backward_size;
grub_size_t grub_relocator_jumper_size = JUMP_SIZEOF + REGW_SIZEOF;
void
grub_cpu_relocator_init (void)
{
  grub_relocator_forward_size = RELOCATOR_SIZEOF(forward);
  grub_relocator_backward_size = RELOCATOR_SIZEOF(backward);
}
static void
write_reg (int regn, grub_uint64_t val, void **target)
{
  grub_uint32_t lui;
  grub_uint32_t ori;
  grub_uint32_t dsll;
  /* lui $r, 0 */
  lui = (0x3c00 | regn) << 16;
  /* ori $r, $r, 0 */
  ori = (0x3400 | (regn << 5) | regn) << 16;
  /* dsll $r, $r, 16 */
  dsll = (regn << 16) | (regn << 11) | (16 << 6) | 56;
  /* lui $r, val[63:48].  */
  *(grub_uint32_t *) *target = lui | (grub_uint16_t) (val >> 48);
  *target = ((grub_uint32_t *) *target) + 1;
  /* ori $r, val[47:32].  */
  *(grub_uint32_t *) *target = ori | (grub_uint16_t) (val >> 32);
  *target = ((grub_uint32_t *) *target) + 1;
  /* dsll $r, $r, 16 */
  *(grub_uint32_t *) *target = dsll;
  *target = ((grub_uint32_t *) *target) + 1;
  /* ori $r, val[31:16].  */
  *(grub_uint32_t *) *target = ori | (grub_uint16_t) (val >> 16);
  *target = ((grub_uint32_t *) *target) + 1;
  /* dsll $r, $r, 16 */
  *(grub_uint32_t *) *target = dsll;
  *target = ((grub_uint32_t *) *target) + 1;
  /* ori $r, val[15:0].  */
  *(grub_uint32_t *) *target = ori | (grub_uint16_t) val;
  *target = ((grub_uint32_t *) *target) + 1;
}
static void
write_jump (int regn, void **target)
{
  /* j $r.  */
  *(grub_uint32_t *) *target = (regn << 21) | 0x8;
  *target = ((grub_uint32_t *) *target) + 1;
  /* nop.  */
  *(grub_uint32_t *) *target = 0;
  *target = ((grub_uint32_t *) *target) + 1;
}
void
grub_cpu_relocator_jumper (void *rels, grub_addr_t addr)
{
  write_reg (1, addr, &rels);
  write_jump (1, &rels);
}
void
grub_cpu_relocator_backward (void *ptr0, void *src, void *dest,
			     grub_size_t size)
{
  void *ptr = ptr0;
  write_reg (8, (grub_uint64_t) src, &ptr);
  write_reg (9, (grub_uint64_t) dest, &ptr);
  write_reg (10, (grub_uint64_t) size, &ptr);
  grub_memcpy (ptr, &grub_relocator_backward_start,
	       RELOCATOR_SRC_SIZEOF (backward));
}
void
grub_cpu_relocator_forward (void *ptr0, void *src, void *dest,
			     grub_size_t size)
{
  void *ptr = ptr0;
  write_reg (8, (grub_uint64_t) src, &ptr);
  write_reg (9, (grub_uint64_t) dest, &ptr);
  write_reg (10, (grub_uint64_t) size, &ptr);
  grub_memcpy (ptr, &grub_relocator_forward_start,
	       RELOCATOR_SRC_SIZEOF (forward));
}
grub_err_t
grub_relocator64_boot (struct grub_relocator *rel,
		       struct grub_relocator64_state state)
{
  grub_relocator_chunk_t ch;
  void *ptr;
  grub_err_t err;
  void *relst;
  grub_size_t relsize;
  grub_size_t stateset_size = 31 * REGW_SIZEOF + JUMP_SIZEOF;
  unsigned i;
  grub_addr_t vtarget;
  err = grub_relocator_alloc_chunk_align (rel, &ch, 0,
					  (0xffffffff - stateset_size)
					  + 1, stateset_size,
					  grub_relocator_align,
					  GRUB_RELOCATOR_PREFERENCE_NONE, 0);
  if (err)
    return err;
  ptr = get_virtual_current_address (ch);
  for (i = 1; i < 32; i++)
    write_reg (i, state.gpr[i], &ptr);
  write_jump (state.jumpreg, &ptr);
  vtarget = (grub_addr_t) grub_map_memory (get_physical_target_address (ch),
					   stateset_size);
  err = grub_relocator_prepare_relocs (rel, vtarget, &relst, &relsize);
  if (err)
    return err;
  grub_arch_sync_caches ((void *) relst, relsize);
  ((void (*) (void)) relst) ();
  /* Not reached.  */
  return GRUB_ERR_NONE;
}
 | 4,972 | 
	C | 
	.c | 147 | 30.979592 | 76 | 0.655007 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 565 | 
	linux.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/loader/linux.c | 
	#include <grub/types.h>
#include <grub/err.h>
#include <grub/linux.h>
#include <grub/misc.h>
#include <grub/file.h>
#include <grub/mm.h>
#include <grub/env.h>
#include <grub/term.h>
struct newc_head
{
  char magic[6];
  char ino[8];
  char mode[8];
  char uid[8];
  char gid[8];
  char nlink[8];
  char mtime[8];
  char filesize[8];
  char devmajor[8];
  char devminor[8];
  char rdevmajor[8];
  char rdevminor[8];
  char namesize[8];
  char check[8];
} GRUB_PACKED;
struct grub_linux_initrd_component
{
  grub_file_t file;
  char *newc_name;
  grub_off_t size;
};
struct dir
{
  char *name;
  struct dir *next;
  struct dir *child;
};
static char
hex (grub_uint8_t val)
{
  if (val < 10)
    return '0' + val;
  return 'a' + val - 10;
}
static void
set_field (char *var, grub_uint32_t val)
{
  int i;
  char *ptr = var;
  for (i = 28; i >= 0; i -= 4)
    *ptr++ = hex((val >> i) & 0xf);
}
static grub_uint8_t *
make_header (grub_uint8_t *ptr,
	     const char *name, grub_size_t len,
	     grub_uint32_t mode,
	     grub_off_t fsize)
{
  struct newc_head *head = (struct newc_head *) ptr;
  grub_uint8_t *optr;
  grub_size_t oh = 0;
  grub_memcpy (head->magic, "070701", 6);
  set_field (head->ino, 0);
  set_field (head->mode, mode);
  set_field (head->uid, 0);
  set_field (head->gid, 0);
  set_field (head->nlink, 1);
  set_field (head->mtime, 0);
  set_field (head->filesize, fsize);
  set_field (head->devmajor, 0);
  set_field (head->devminor, 0);
  set_field (head->rdevmajor, 0);
  set_field (head->rdevminor, 0);
  set_field (head->namesize, len);
  set_field (head->check, 0);
  optr = ptr;
  ptr += sizeof (struct newc_head);
  grub_memcpy (ptr, name, len);
  ptr += len;
  oh = ALIGN_UP_OVERHEAD (ptr - optr, 4);
  grub_memset (ptr, 0, oh);
  ptr += oh;
  return ptr;
}
static void
free_dir (struct dir *root)
{
  if (!root)
    return;
  free_dir (root->next);
  free_dir (root->child);
  grub_free (root->name);
  grub_free (root);
}
static grub_size_t
insert_dir (const char *name, struct dir **root,
	    grub_uint8_t *ptr)
{
  struct dir *cur, **head = root;
  const char *cb, *ce = name;
  grub_size_t size = 0;
  while (1)
    {
      for (cb = ce; *cb == '/'; cb++);
      for (ce = cb; *ce && *ce != '/'; ce++);
      if (!*ce)
	break;
      for (cur = *root; cur; cur = cur->next)
	if (grub_memcmp (cur->name, cb, ce - cb)
	    && cur->name[ce - cb] == 0)
	  break;
      if (!cur)
	{
	  struct dir *n;
	  n = grub_zalloc (sizeof (*n));
	  if (!n)
	    return 0;
	  n->next = *head;
	  n->name = grub_strndup (cb, ce - cb);
	  if (ptr)
	    {
	      grub_dprintf ("linux", "Creating directory %s, %s\n", name, ce);
	      ptr = make_header (ptr, name, ce - name,
				 040777, 0);
	    }
	  size += ALIGN_UP ((ce - (char *) name)
			    + sizeof (struct newc_head), 4);
	  *head = n;
	  cur = n;
	}
      root = &cur->next;
    }
  return size;
}
grub_err_t
grub_initrd_init (int argc, char *argv[],
		  struct grub_linux_initrd_context *initrd_ctx)
{
  int i;
  int newc = 0;
  struct dir *root = 0;
  initrd_ctx->nfiles = 0;
  initrd_ctx->components = 0;
  initrd_ctx->components = grub_zalloc (argc
					* sizeof (initrd_ctx->components[0]));
  if (!initrd_ctx->components)
    return grub_errno;
  initrd_ctx->size = 0;
  for (i = 0; i < argc; i++)
    {
      const char *fname = argv[i];
      initrd_ctx->size = ALIGN_UP (initrd_ctx->size, 4);
      if (grub_memcmp (argv[i], "newc:", 5) == 0)
	{
	  const char *ptr, *eptr;
	  ptr = argv[i] + 5;
	  while (*ptr == '/')
	    ptr++;
	  eptr = grub_strchr (ptr, ':');
	  if (eptr)
	    {
	      initrd_ctx->components[i].newc_name = grub_strndup (ptr, eptr - ptr);
	      if (!initrd_ctx->components[i].newc_name)
		{
		  grub_initrd_close (initrd_ctx);
		  return grub_errno;
		}
	      initrd_ctx->size
		+= ALIGN_UP (sizeof (struct newc_head)
			    + grub_strlen (initrd_ctx->components[i].newc_name),
			     4);
	      initrd_ctx->size += insert_dir (initrd_ctx->components[i].newc_name,
					      &root, 0);
	      newc = 1;
	      fname = eptr + 1;
	    }
	}
      else if (newc)
	{
	  initrd_ctx->size += ALIGN_UP (sizeof (struct newc_head)
					+ sizeof ("TRAILER!!!") - 1, 4);
	  free_dir (root);
	  root = 0;
	  newc = 0;
	}
      initrd_ctx->components[i].file = grub_file_open (fname,
						       GRUB_FILE_TYPE_LINUX_INITRD
						       | GRUB_FILE_TYPE_NO_DECOMPRESS);
      if (!initrd_ctx->components[i].file)
	{
	  grub_initrd_close (initrd_ctx);
	  return grub_errno;
	}
      initrd_ctx->nfiles++;
      initrd_ctx->components[i].size
	= grub_file_size (initrd_ctx->components[i].file);
      initrd_ctx->size += initrd_ctx->components[i].size;
    }
  if (newc)
    {
      initrd_ctx->size = ALIGN_UP (initrd_ctx->size, 4);
      initrd_ctx->size += ALIGN_UP (sizeof (struct newc_head)
				    + sizeof ("TRAILER!!!") - 1, 4);
      free_dir (root);
      root = 0;
    }
  
  return GRUB_ERR_NONE;
}
grub_size_t
grub_get_initrd_size (struct grub_linux_initrd_context *initrd_ctx)
{
  return initrd_ctx->size;
}
void
grub_initrd_close (struct grub_linux_initrd_context *initrd_ctx)
{
  int i;
  if (!initrd_ctx->components)
    return;
  for (i = 0; i < initrd_ctx->nfiles; i++)
    {
      grub_free (initrd_ctx->components[i].newc_name);
      grub_file_close (initrd_ctx->components[i].file);
    }
  grub_free (initrd_ctx->components);
  initrd_ctx->components = 0;
}
extern int ventoy_need_prompt_load_file(void);
extern grub_ssize_t ventoy_load_file_with_prompt(grub_file_t file, void *buf, grub_ssize_t size);
grub_err_t
grub_initrd_load (struct grub_linux_initrd_context *initrd_ctx,
		  char *argv[], void *target)
{
  grub_uint8_t *ptr = target;
  int i;
  int newc = 0;
  struct dir *root = 0;
  grub_ssize_t cursize = 0;
  grub_ssize_t readsize = 0;
  
  for (i = 0; i < initrd_ctx->nfiles; i++)
    {
      grub_memset (ptr, 0, ALIGN_UP_OVERHEAD (cursize, 4));
      ptr += ALIGN_UP_OVERHEAD (cursize, 4);
      if (initrd_ctx->components[i].newc_name)
	{
	  ptr += insert_dir (initrd_ctx->components[i].newc_name,
			     &root, ptr);
	  ptr = make_header (ptr, initrd_ctx->components[i].newc_name,
			     grub_strlen (initrd_ctx->components[i].newc_name),
			     0100777,
			     initrd_ctx->components[i].size);
	  newc = 1;
	}
      else if (newc)
	{
	  ptr = make_header (ptr, "TRAILER!!!", sizeof ("TRAILER!!!") - 1,
			     0, 0);
	  free_dir (root);
	  root = 0;
	  newc = 0;
	}
    cursize = initrd_ctx->components[i].size;
    if (ventoy_need_prompt_load_file() && initrd_ctx->components[i].newc_name && 
        grub_strcmp(initrd_ctx->components[i].newc_name, "boot.wim") == 0)
    {
        readsize = ventoy_load_file_with_prompt(initrd_ctx->components[i].file, ptr, cursize);
    }
    else
    {
        readsize = grub_file_read (initrd_ctx->components[i].file, ptr, cursize);
    }
      if (readsize != cursize)
	{
	  if (!grub_errno)
	    grub_error (GRUB_ERR_FILE_READ_ERROR, N_("premature end of file %s"),
			argv[i]);
	  grub_initrd_close (initrd_ctx);
	  return grub_errno;
	}
      ptr += cursize;
    }
  if (newc)
    {
      grub_memset (ptr, 0, ALIGN_UP_OVERHEAD (cursize, 4));
      ptr += ALIGN_UP_OVERHEAD (cursize, 4);
      ptr = make_header (ptr, "TRAILER!!!", sizeof ("TRAILER!!!") - 1, 0, 0);
    }
  free_dir (root);
  root = 0;
  return GRUB_ERR_NONE;
}
 | 7,333 | 
	C | 
	.c | 291 | 21.168385 | 97 | 0.603308 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 566 | 
	linux.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/loader/arm64/linux.c | 
	/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 2013  Free Software Foundation, Inc.
 *
 *  GRUB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GRUB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <grub/charset.h>
#include <grub/command.h>
#include <grub/err.h>
#include <grub/file.h>
#include <grub/fdt.h>
#include <grub/linux.h>
#include <grub/loader.h>
#include <grub/mm.h>
#include <grub/types.h>
#include <grub/cpu/linux.h>
#include <grub/efi/efi.h>
#include <grub/efi/fdtload.h>
#include <grub/efi/memory.h>
#include <grub/efi/pe32.h>
#include <grub/i18n.h>
#include <grub/lib/cmdline.h>
#include <grub/verify.h>
#include <grub/term.h>
#include <grub/env.h>
GRUB_MOD_LICENSE ("GPLv3+");
static grub_dl_t my_mod;
static int loaded;
static void *kernel_addr;
static grub_uint64_t kernel_size;
static char *linux_args;
static grub_uint32_t cmdline_size;
static grub_addr_t initrd_start;
static grub_addr_t initrd_end;
#define LINUX_MAX_ARGC  1024
static int ventoy_debug = 0;
static int ventoy_initrd_called = 0;
static int ventoy_linux_argc = 0;
static char **ventoy_linux_args = NULL;
static int ventoy_extra_initrd_num = 0;
static char *ventoy_extra_initrd_list[256];
static grub_err_t
grub_cmd_initrd (grub_command_t cmd __attribute__ ((unused)),
		 int argc, char *argv[]);
grub_err_t
grub_arch_efi_linux_check_image (struct linux_arch_kernel_header * lh)
{
  if (lh->magic != GRUB_LINUX_ARMXX_MAGIC_SIGNATURE)
    return grub_error(GRUB_ERR_BAD_OS, "invalid magic number");
  if ((lh->code0 & 0xffff) != GRUB_PE32_MAGIC)
    return grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
		       N_("plain image kernel not supported - rebuild with CONFIG_(U)EFI_STUB enabled"));
  grub_dprintf ("linux", "UEFI stub kernel:\n");
  grub_dprintf ("linux", "PE/COFF header @ %08x\n", lh->hdr_offset);
  return GRUB_ERR_NONE;
}
static grub_err_t
finalize_params_linux (void)
{
  int node, retval;
  void *fdt;
  fdt = grub_fdt_load (GRUB_EFI_LINUX_FDT_EXTRA_SPACE);
  if (!fdt)
    goto failure;
  node = grub_fdt_find_subnode (fdt, 0, "chosen");
  if (node < 0)
    node = grub_fdt_add_subnode (fdt, 0, "chosen");
  if (node < 1)
    goto failure;
  /* Set initrd info */
  if (initrd_start && initrd_end > initrd_start)
    {
      grub_dprintf ("linux", "Initrd @ %p-%p\n",
		    (void *) initrd_start, (void *) initrd_end);
      retval = grub_fdt_set_prop64 (fdt, node, "linux,initrd-start",
				    initrd_start);
      if (retval)
	goto failure;
      retval = grub_fdt_set_prop64 (fdt, node, "linux,initrd-end",
				    initrd_end);
      if (retval)
	goto failure;
    }
  if (grub_fdt_install() != GRUB_ERR_NONE)
    goto failure;
  return GRUB_ERR_NONE;
failure:
  grub_fdt_unload();
  return grub_error(GRUB_ERR_BAD_OS, "failed to install/update FDT");
}
grub_err_t
grub_arch_efi_linux_boot_image (grub_addr_t addr, grub_size_t size, char *args)
{
  grub_efi_memory_mapped_device_path_t *mempath;
  grub_efi_handle_t image_handle;
  grub_efi_boot_services_t *b;
  grub_efi_status_t status;
  grub_efi_loaded_image_t *loaded_image;
  int len;
  mempath = grub_malloc (2 * sizeof (grub_efi_memory_mapped_device_path_t));
  if (!mempath)
    return grub_errno;
  mempath[0].header.type = GRUB_EFI_HARDWARE_DEVICE_PATH_TYPE;
  mempath[0].header.subtype = GRUB_EFI_MEMORY_MAPPED_DEVICE_PATH_SUBTYPE;
  mempath[0].header.length = grub_cpu_to_le16_compile_time (sizeof (*mempath));
  mempath[0].memory_type = GRUB_EFI_LOADER_DATA;
  mempath[0].start_address = addr;
  mempath[0].end_address = addr + size;
  mempath[1].header.type = GRUB_EFI_END_DEVICE_PATH_TYPE;
  mempath[1].header.subtype = GRUB_EFI_END_ENTIRE_DEVICE_PATH_SUBTYPE;
  mempath[1].header.length = sizeof (grub_efi_device_path_t);
  b = grub_efi_system_table->boot_services;
  status = b->load_image (0, grub_efi_image_handle,
			  (grub_efi_device_path_t *) mempath,
			  (void *) addr, size, &image_handle);
  if (status != GRUB_EFI_SUCCESS)
    return grub_error (GRUB_ERR_BAD_OS, "cannot load image");
  grub_dprintf ("linux", "linux command line: '%s'\n", args);
  /* Convert command line to UCS-2 */
  loaded_image = grub_efi_get_loaded_image (image_handle);
  loaded_image->load_options_size = len =
    (grub_strlen (args) + 1) * sizeof (grub_efi_char16_t);
  loaded_image->load_options =
    grub_efi_allocate_any_pages (GRUB_EFI_BYTES_TO_PAGES (loaded_image->load_options_size));
  if (!loaded_image->load_options)
    return grub_errno;
  loaded_image->load_options_size =
    2 * grub_utf8_to_utf16 (loaded_image->load_options, len,
			    (grub_uint8_t *) args, len, NULL);
  grub_dprintf ("linux", "starting image %p\n", image_handle);
  status = b->start_image (image_handle, 0, NULL);
  /* When successful, not reached */
  b->unload_image (image_handle);
  grub_efi_free_pages ((grub_addr_t) loaded_image->load_options,
		       GRUB_EFI_BYTES_TO_PAGES (loaded_image->load_options_size));
  return grub_errno;
}
static void ventoy_debug_pause(void)
{
    char key;
    if (0 == ventoy_debug) 
    {
        return;
    }
    
    grub_printf("press Enter to continue ......\n");
    while (1)
    {
        key = grub_getkey();
        if (key == '\n' || key == '\r')
        {
            break;
        }
    }    
}
static int ventoy_preboot(void)
{
    int i;
    const char *file;
    char buf[128];
    if (ventoy_debug) 
    {
        grub_printf("ventoy_preboot %d %d\n", ventoy_linux_argc, ventoy_initrd_called);
        ventoy_debug_pause();
    }
    if (ventoy_linux_argc == 0)
    {
        return 0;
    }
    if (ventoy_initrd_called)
    {
        ventoy_initrd_called = 0;
        return 0;
    }
    grub_snprintf(buf, sizeof(buf), "mem:%s:size:%s", grub_env_get("ventoy_cpio_addr"), grub_env_get("ventoy_cpio_size"));
    ventoy_extra_initrd_list[ventoy_extra_initrd_num++] = grub_strdup(buf);
    file = grub_env_get("vtoy_img_part_file");
    if (file)
    {
        ventoy_extra_initrd_list[ventoy_extra_initrd_num++] = grub_strdup(file);
    }
    if (ventoy_debug) 
    {
        grub_printf("========== initrd list ==========\n");
        for (i = 0; i < ventoy_extra_initrd_num; i++)
        {
            grub_printf("%s\n", ventoy_extra_initrd_list[i]);
        }
        grub_printf("=================================\n");
        
        ventoy_debug_pause();
    }
    grub_cmd_initrd(NULL, ventoy_extra_initrd_num, ventoy_extra_initrd_list);
    return 0;
}
static int ventoy_boot_opt_filter(char *opt)
{
    if (grub_strcmp(opt, "noinitrd") == 0)
    {
        return 1;
    }
    if (grub_strcmp(opt, "vga=current") == 0)
    {
        return 1;
    }
    if (grub_strncmp(opt, "rdinit=", 7) == 0)
    {
        if (grub_strcmp(opt, "rdinit=/vtoy/vtoy") != 0)
        {
            opt[0] = 'v';
            opt[1] = 't';
        }
        return 0;
    }
    
    if (grub_strncmp(opt, "init=", 5) == 0)
    {
        opt[0] = 'v';
        opt[1] = 't';
        return 0;
    }
    
    if (grub_strncmp(opt, "dm=", 3) == 0)
    {
        opt[0] = 'D';
        opt[1] = 'M';
        return 0;
    }
    if (ventoy_debug)
    {
        if (grub_strcmp(opt, "quiet") == 0)
        {
            return 1;
        }
        
        if (grub_strncmp(opt, "loglevel=", 9) == 0)
        {
            return 1;
        }
        
        if (grub_strcmp(opt, "splash") == 0)
        {
            return 1;
        }
    }
    return 0;
}
static int ventoy_bootopt_hook(int argc, char *argv[])
{
    int i;
    int TmpIdx;
    int count = 0;
    const char *env;
    char c;
    char *newenv;
    char *last, *pos;
    //grub_printf("ventoy_bootopt_hook: %d %d\n", argc, ventoy_linux_argc);
    if (ventoy_linux_argc == 0)
    {
        return 0;
    }
    /* To avoid --- parameter, we split two parts */
    for (TmpIdx = 0; TmpIdx < argc; TmpIdx++)
    {
        if (ventoy_boot_opt_filter(argv[TmpIdx]))
        {
            continue;
        }
        if (grub_strncmp(argv[TmpIdx], "--", 2) == 0)
        {
            break;
        }
        ventoy_linux_args[count++] = grub_strdup(argv[TmpIdx]);
    }
    for (i = 0; i < ventoy_linux_argc; i++)
    {
        ventoy_linux_args[count] = ventoy_linux_args[i + (LINUX_MAX_ARGC / 2)];
        ventoy_linux_args[i + (LINUX_MAX_ARGC / 2)] = NULL;
        
        if (ventoy_linux_args[count][0] == '@')
        {
            env = grub_env_get(ventoy_linux_args[count] + 1);
            if (env)
            {
                grub_free(ventoy_linux_args[count]);
                newenv = grub_strdup(env);
                last =  newenv;
                while (*last)
                {
                    while (*last)
                    {
                        if (*last != ' ' && *last != '\t')
                        {
                            break;
                        }
                        last++;
                    }
                    if (*last == 0)
                    {
                        break;
                    }
                    for (pos = last; *pos; pos++)
                    {
                        if (*pos == ' ' || *pos == '\t')
                        {
                            c = *pos;
                            *pos = 0;
                            if (0 == ventoy_boot_opt_filter(last))
                            {
                                ventoy_linux_args[count++] = grub_strdup(last);
                            }
                            *pos = c;
                            break;
                        }
                    }
                    if (*pos == 0)
                    {
                        if (0 == ventoy_boot_opt_filter(last))
                        {
                            ventoy_linux_args[count++] = grub_strdup(last);                            
                        }
                        break;
                    }
                    last = pos + 1;
                }
            }
            else
            {
                count++;
            }
        }
        else
        {
            count++;            
        }
    }
    while (TmpIdx < argc)
    {
        if (ventoy_boot_opt_filter(argv[TmpIdx]))
        {
            continue;
        }
        ventoy_linux_args[count++] = grub_strdup(argv[TmpIdx]);
        TmpIdx++;
    }
    if (ventoy_debug)
    {
        ventoy_linux_args[count++] = grub_strdup("loglevel=7");
    }
    ventoy_linux_argc = count;
    if (ventoy_debug)
    {
        grub_printf("========== bootoption ==========\n");
        for (i = 0; i < count; i++)
        {
            grub_printf("%s ", ventoy_linux_args[i]);
        }  
        grub_printf("\n================================\n");
    }
    
    return 0;
}
static grub_err_t
grub_cmd_set_boot_opt (grub_command_t cmd __attribute__ ((unused)),
		int argc, char *argv[])
{
    int i;
    const char *vtdebug;
    for (i = 0; i < argc; i++)
    {
        ventoy_linux_args[ventoy_linux_argc + (LINUX_MAX_ARGC / 2) ] = grub_strdup(argv[i]);
        ventoy_linux_argc++;
    }
    vtdebug = grub_env_get("vtdebug_flag");
    if (vtdebug && vtdebug[0])
    {
        ventoy_debug = 1;
    }
    if (ventoy_debug) grub_printf("ventoy set boot opt %d\n", ventoy_linux_argc);
    return 0;
}
static grub_err_t
grub_cmd_unset_boot_opt (grub_command_t cmd __attribute__ ((unused)),
		int argc, char *argv[])
{
    int i;
    
    (void)argc;
    (void)argv;
    for (i = 0; i < LINUX_MAX_ARGC; i++)
    {
        if (ventoy_linux_args[i])
        {
            grub_free(ventoy_linux_args[i]);
        }
    }
    ventoy_debug = 0;
    ventoy_linux_argc = 0;
    ventoy_initrd_called = 0;
    grub_memset(ventoy_linux_args, 0, sizeof(char *) * LINUX_MAX_ARGC);
    return 0;
}
static grub_err_t
grub_cmd_extra_initrd_append (grub_command_t cmd __attribute__ ((unused)),
		int argc, char *argv[])
{
    int newclen = 0;
    char *pos = NULL;
    char *end = NULL;
    char buf[256] = {0};
    
    if (argc != 1)
    {
        return 1;
    }
    for (pos = argv[0]; *pos; pos++)
    {
        if (*pos == '/')
        {
            end = pos;
        }
    }
    if (end)
    {
        /* grub2 newc bug workaround */
        newclen = (int)grub_strlen(end + 1);
        if ((110 + newclen) % 4 == 0)
        {
            grub_snprintf(buf, sizeof(buf), "newc:.%s:%s", end + 1, argv[0]);
        }
        else
        {
            grub_snprintf(buf, sizeof(buf), "newc:%s:%s", end + 1, argv[0]);
        }
    
        if (ventoy_extra_initrd_num < 256)
        {
            ventoy_extra_initrd_list[ventoy_extra_initrd_num++] = grub_strdup(buf);        
        }
    }
    return 0;
}
static grub_err_t
grub_cmd_extra_initrd_reset (grub_command_t cmd __attribute__ ((unused)),
		int argc, char *argv[])
{
    int i;
    
    (void)argc;
    (void)argv;
    for (i = 0; i < ventoy_extra_initrd_num; i++)
    {
        if (ventoy_extra_initrd_list[i])
        {
            grub_free(ventoy_extra_initrd_list[i]);
        }
    }
    grub_memset(ventoy_extra_initrd_list, 0, sizeof(ventoy_extra_initrd_list));
    return 0;
}
static grub_err_t
grub_linux_boot (void)
{
  ventoy_preboot();
  if (finalize_params_linux () != GRUB_ERR_NONE)
    return grub_errno;
  return (grub_arch_efi_linux_boot_image((grub_addr_t)kernel_addr,
                                          kernel_size, linux_args));
}
static grub_err_t
grub_linux_unload (void)
{
  grub_dl_unref (my_mod);
  loaded = 0;
  if (initrd_start)
    grub_efi_free_pages ((grub_efi_physical_address_t) initrd_start,
			 GRUB_EFI_BYTES_TO_PAGES (initrd_end - initrd_start));
  initrd_start = initrd_end = 0;
  grub_free (linux_args);
  if (kernel_addr)
    grub_efi_free_pages ((grub_addr_t) kernel_addr,
			 GRUB_EFI_BYTES_TO_PAGES (kernel_size));
  grub_fdt_unload ();
  return GRUB_ERR_NONE;
}
/*
 * As per linux/Documentation/arm/Booting
 * ARM initrd needs to be covered by kernel linear mapping,
 * so place it in the first 512MB of DRAM.
 *
 * As per linux/Documentation/arm64/booting.txt
 * ARM64 initrd needs to be contained entirely within a 1GB aligned window
 * of up to 32GB of size that covers the kernel image as well.
 * Since the EFI stub loader will attempt to load the kernel near start of
 * RAM, place the buffer in the first 32GB of RAM.
 */
#ifdef __arm__
#define INITRD_MAX_ADDRESS_OFFSET (512U * 1024 * 1024)
#else /* __aarch64__ */
#define INITRD_MAX_ADDRESS_OFFSET (32ULL * 1024 * 1024 * 1024)
#endif
/*
 * This function returns a pointer to a legally allocated initrd buffer,
 * or NULL if unsuccessful
 */
static void *
allocate_initrd_mem (int initrd_pages)
{
  grub_addr_t max_addr;
  if (grub_efi_get_ram_base (&max_addr) != GRUB_ERR_NONE)
    return NULL;
  max_addr += INITRD_MAX_ADDRESS_OFFSET - 1;
  return grub_efi_allocate_pages_real (max_addr, initrd_pages,
				       GRUB_EFI_ALLOCATE_MAX_ADDRESS,
				       GRUB_EFI_LOADER_DATA);
}
static grub_err_t
grub_cmd_initrd (grub_command_t cmd __attribute__ ((unused)),
		 int argc, char *argv[])
{
  struct grub_linux_initrd_context initrd_ctx = { 0, 0, 0 };
  int initrd_size, initrd_pages;
  void *initrd_mem = NULL;
  if (argc == 0)
    {
      grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected"));
      goto fail;
    }
  if (!loaded)
    {
      grub_error (GRUB_ERR_BAD_ARGUMENT,
		  N_("you need to load the kernel first"));
      goto fail;
    }
  if (grub_initrd_init (argc, argv, &initrd_ctx))
    goto fail;
  initrd_size = grub_get_initrd_size (&initrd_ctx);
  grub_dprintf ("linux", "Loading initrd\n");
  initrd_pages = (GRUB_EFI_BYTES_TO_PAGES (initrd_size));
  initrd_mem = allocate_initrd_mem (initrd_pages);
  if (!initrd_mem)
    {
      grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("out of memory"));
      goto fail;
    }
  if (grub_initrd_load (&initrd_ctx, argv, initrd_mem))
    goto fail;
  initrd_start = (grub_addr_t) initrd_mem;
  initrd_end = initrd_start + initrd_size;
  grub_dprintf ("linux", "[addr=%p, size=0x%x]\n",
		(void *) initrd_start, initrd_size);
 fail:
  grub_initrd_close (&initrd_ctx);
  if (initrd_mem && !initrd_start)
    grub_efi_free_pages ((grub_addr_t) initrd_mem, initrd_pages);
  return grub_errno;
}
static grub_err_t
grub_cmd_linux (grub_command_t cmd __attribute__ ((unused)),
		int argc, char *argv[])
{
  grub_file_t file = 0;
  struct linux_arch_kernel_header lh;
  grub_err_t err;
  grub_dl_ref (my_mod);
  if (argc == 0)
    {
      grub_error (GRUB_ERR_BAD_ARGUMENT, N_("filename expected"));
      goto fail;
    }
  file = grub_file_open (argv[0], GRUB_FILE_TYPE_LINUX_KERNEL);
  if (!file)
    goto fail;
  kernel_size = grub_file_size (file);
  if (grub_file_read (file, &lh, sizeof (lh)) < (long) sizeof (lh))
    return grub_errno;
  if (grub_arch_efi_linux_check_image (&lh) != GRUB_ERR_NONE)
    goto fail;
  grub_loader_unset();
  grub_dprintf ("linux", "kernel file size: %lld\n", (long long) kernel_size);
  kernel_addr = grub_efi_allocate_any_pages (GRUB_EFI_BYTES_TO_PAGES (kernel_size));
  grub_dprintf ("linux", "kernel numpages: %lld\n",
		(long long) GRUB_EFI_BYTES_TO_PAGES (kernel_size));
  if (!kernel_addr)
    {
      grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("out of memory"));
      goto fail;
    }
  grub_file_seek (file, 0);
  if (grub_file_read (file, kernel_addr, kernel_size)
      < (grub_int64_t) kernel_size)
    {
      if (!grub_errno)
	grub_error (GRUB_ERR_BAD_OS, N_("premature end of file %s"), argv[0]);
      goto fail;
    }
  grub_dprintf ("linux", "kernel @ %p\n", kernel_addr);
  cmdline_size = grub_loader_cmdline_size (argc, argv) + sizeof (LINUX_IMAGE);
  linux_args = grub_malloc (cmdline_size);
  if (!linux_args)
    {
      grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("out of memory"));
      goto fail;
    }
  grub_memcpy (linux_args, LINUX_IMAGE, sizeof (LINUX_IMAGE));
  if (ventoy_linux_argc)
  {
      ventoy_bootopt_hook(argc, argv);
      err = grub_create_loader_cmdline (ventoy_linux_argc, ventoy_linux_args,
    				    linux_args + sizeof (LINUX_IMAGE) - 1,
    				    cmdline_size,
    				    GRUB_VERIFY_KERNEL_CMDLINE);  }
  else
  {      
      err = grub_create_loader_cmdline (argc, argv,
    				    linux_args + sizeof (LINUX_IMAGE) - 1,
    				    cmdline_size,
    				    GRUB_VERIFY_KERNEL_CMDLINE);
  }
  if (err)
    goto fail;
  if (grub_errno == GRUB_ERR_NONE)
    {
      grub_loader_set (grub_linux_boot, grub_linux_unload, 0);
      loaded = 1;
    }
fail:
  if (file)
    grub_file_close (file);
  if (grub_errno != GRUB_ERR_NONE)
    {
      grub_dl_unref (my_mod);
      loaded = 0;
    }
  if (linux_args && !loaded)
    grub_free (linux_args);
  if (kernel_addr && !loaded)
    grub_efi_free_pages ((grub_addr_t) kernel_addr,
			 GRUB_EFI_BYTES_TO_PAGES (kernel_size));
  return grub_errno;
}
static grub_err_t
ventoy_cmd_initrd (grub_command_t cmd __attribute__ ((unused)),
		 int argc, char *argv[])
{
    int i;
    const char *file;
    char buf[64];
    if (ventoy_debug) grub_printf("ventoy_cmd_initrd %d\n", ventoy_linux_argc);
    if (ventoy_linux_argc == 0)
    {
        return grub_cmd_initrd(cmd, argc, argv);        
    }
    grub_snprintf(buf, sizeof(buf), "mem:%s:size:%s", grub_env_get("ventoy_cpio_addr"), grub_env_get("ventoy_cpio_size"));
    if (ventoy_debug) grub_printf("membuf=%s\n", buf);
    ventoy_extra_initrd_list[ventoy_extra_initrd_num++] = grub_strdup(buf);
    file = grub_env_get("vtoy_img_part_file");
    if (file)
    {
        ventoy_extra_initrd_list[ventoy_extra_initrd_num++] = grub_strdup(file);
    }
    for (i = 0; i < argc; i++)
    {
        ventoy_extra_initrd_list[ventoy_extra_initrd_num++] = grub_strdup(argv[i]);
    }
    ventoy_initrd_called = 1;
    if (ventoy_debug)
    {
        grub_printf("========== initrd list ==========\n");
        for (i = 0; i < ventoy_extra_initrd_num; i++)
        {
            grub_printf("%s\n", ventoy_extra_initrd_list[i]);
        }
        grub_printf("=================================\n");
    }
    
    return grub_cmd_initrd(cmd, ventoy_extra_initrd_num, ventoy_extra_initrd_list);
}
static grub_command_t cmd_linux, cmd_initrd, cmd_linuxefi, cmd_initrdefi;
static grub_command_t cmd_set_bootopt, cmd_unset_bootopt, cmd_extra_initrd_append, cmd_extra_initrd_reset;
GRUB_MOD_INIT (linux)
{
  cmd_linux = grub_register_command ("linux", grub_cmd_linux, 0,
				     N_("Load Linux."));
  cmd_initrd = grub_register_command ("initrd", ventoy_cmd_initrd, 0,
				      N_("Load initrd."));
  cmd_linuxefi = grub_register_command ("linuxefi", grub_cmd_linux,
				     0, N_("Load Linux."));
  cmd_initrdefi = grub_register_command ("initrdefi", ventoy_cmd_initrd,
				      0, N_("Load initrd."));
  cmd_set_bootopt = grub_register_command ("vt_set_boot_opt", grub_cmd_set_boot_opt, 0, N_("set ext boot opt"));
  cmd_unset_bootopt = grub_register_command ("vt_unset_boot_opt", grub_cmd_unset_boot_opt, 0, N_("unset ext boot opt"));
  
  cmd_extra_initrd_append = grub_register_command ("vt_img_extra_initrd_append", grub_cmd_extra_initrd_append, 0, N_(""));
  cmd_extra_initrd_reset = grub_register_command ("vt_img_extra_initrd_reset", grub_cmd_extra_initrd_reset, 0, N_(""));
  ventoy_linux_args = grub_zalloc(sizeof(char *) * LINUX_MAX_ARGC);
                      
  my_mod = mod;
}
GRUB_MOD_FINI (linux)
{
  grub_unregister_command (cmd_linux);
  grub_unregister_command (cmd_initrd);
}
 | 21,959 | 
	C | 
	.c | 700 | 24.88 | 122 | 0.58354 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 578 | 
	init.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/kern/mips64/init.c | 
	/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 2009,2017  Free Software Foundation, Inc.
 *
 *  GRUB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GRUB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <grub/kernel.h>
#include <grub/env.h>
#include <grub/time.h>
#include <grub/cpu/mips.h>
grub_uint32_t grub_arch_cpuclock;
/* FIXME: use interrupt to count high.  */
grub_uint64_t
grub_get_rtc (void)
{
  static grub_uint32_t high = 0;
  static grub_uint32_t last = 0;
  grub_uint32_t low;
  asm volatile ("mfc0 %0, " GRUB_CPU_MIPS_COP0_TIMER_COUNT : "=r" (low));
  if (low < last)
    high++;
  last = low;
  return (((grub_uint64_t) high) << 32) | low;
}
void
grub_timer_init (grub_uint32_t cpuclock)
{
  grub_arch_cpuclock = cpuclock;
  grub_install_get_time_ms (grub_rtc_get_time_ms);
}
 | 1,345 | 
	C | 
	.c | 41 | 30.731707 | 73 | 0.714176 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 581 | 
	loongson.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/kern/mips64/efi/loongson.c | 
	/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 2017 Free Software Foundation, Inc.
 *
 *  GRUB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GRUB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <grub/efi/efi.h>
#include <grub/cpu/time.h>
#include <grub/loader.h>
#include <grub/machine/loongson.h>
void
grub_efi_loongson_init (void)
{
}
void
grub_efi_loongson_fini (void)
{
}
 | 930 | 
	C | 
	.c | 29 | 30.37931 | 72 | 0.742475 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 602 | 
	fwload.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/commands/efi/fwload.c | 
	/*
 *  GRUB  --  GRand Unified Bootloader
 *  Copyright (C) 2022  Free Software Foundation, Inc.
 *
 *  GRUB is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  GRUB is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <grub/dl.h>
#include <grub/efi/api.h>
#include <grub/efi/efi.h>
#include <grub/err.h>
#include <grub/extcmd.h>
#include <grub/file.h>
#include <grub/i18n.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/types.h>
GRUB_MOD_LICENSE ("GPLv3+");
static grub_efi_guid_t loaded_image_guid = GRUB_EFI_LOADED_IMAGE_GUID;
static grub_efi_status_t
grub_efi_connect_all (void)
{
  grub_efi_status_t status;
  grub_efi_uintn_t handle_count;
  grub_efi_handle_t *handle_buffer;
  grub_efi_uintn_t index;
  grub_efi_boot_services_t *b;
  grub_dprintf ("efi", "Connecting ...\n");
  b = grub_efi_system_table->boot_services;
  status = efi_call_5 (b->locate_handle_buffer,
                       GRUB_EFI_ALL_HANDLES, NULL, NULL,
                       &handle_count, &handle_buffer);
  if (status != GRUB_EFI_SUCCESS)
    return status;
  for (index = 0; index < handle_count; index++)
  {
    status = efi_call_4 (b->connect_controller,
                         handle_buffer[index], NULL, NULL, 1);
  }
  if (handle_buffer)
  {
    efi_call_1 (b->free_pool, handle_buffer);
  }
  return GRUB_EFI_SUCCESS;
}
static grub_err_t
grub_efi_load_driver (grub_size_t size, void *boot_image, int connect)
{
  grub_efi_status_t status;
  grub_efi_handle_t driver_handle;
  grub_efi_boot_services_t *b;
  grub_efi_loaded_image_t *loaded_image;
  b = grub_efi_system_table->boot_services;
  status = efi_call_6 (b->load_image, 0, grub_efi_image_handle, NULL,
                       boot_image, size, &driver_handle);
  if (status != GRUB_EFI_SUCCESS)
  {
    if (status == GRUB_EFI_OUT_OF_RESOURCES)
      grub_error (GRUB_ERR_OUT_OF_MEMORY, "out of resources");
    else
      grub_error (GRUB_ERR_BAD_OS, "cannot load image");
    goto fail;
  }
  loaded_image = grub_efi_get_loaded_image (driver_handle);
  if (! loaded_image)
  {
    grub_error (GRUB_ERR_BAD_OS, "no loaded image available");
    goto fail;
  }
  grub_dprintf ("efi", "Registering loaded image\n");
  status = efi_call_3 (b->handle_protocol, driver_handle,
                       &loaded_image_guid, (void **)&loaded_image);
  if (status != GRUB_EFI_SUCCESS)
  {
    grub_error (GRUB_ERR_BAD_OS, "not a dirver");
    goto fail;
  }
  grub_dprintf ("efi", "StartImage: %p\n", boot_image);
  status = efi_call_3 (b->start_image, driver_handle, NULL, NULL);
  if (status != GRUB_EFI_SUCCESS)
  {
    grub_error (GRUB_ERR_BAD_OS, "StartImage failed");
    goto fail;
  }
  if (connect)
  {
    status = grub_efi_connect_all ();
    if (status != GRUB_EFI_SUCCESS)
    {
      grub_error (GRUB_ERR_BAD_OS, "cannot connect controllers\n");
      goto fail;
    }
  }
  grub_dprintf ("efi", "Driver installed\n");
  return 0;
fail:
  return grub_errno;
}
static const struct grub_arg_option options_fwload[] =
{
  {"nc", 'n', 0, N_("Loads the driver, but does not connect the driver."), 0, 0},
  {0, 0, 0, 0, 0, 0}
};
static grub_err_t
grub_cmd_fwload (grub_extcmd_context_t ctxt, int argc, char **args)
{
  struct grub_arg_list *state = ctxt->state;
  int connect = 1;
  grub_file_t file = 0;
  grub_efi_boot_services_t *b;
  grub_efi_status_t status;
  grub_efi_uintn_t pages = 0;
  grub_ssize_t size;
  grub_efi_physical_address_t address;
  void *boot_image = 0;
  b = grub_efi_system_table->boot_services;
  if (argc != 1)
    goto fail;
  file = grub_file_open (args[0], GRUB_FILE_TYPE_EFI_CHAINLOADED_IMAGE);
  if (! file)
    goto fail;
  size = grub_file_size (file);
  if (!size)
  {
    grub_error (GRUB_ERR_BAD_OS, N_("premature end of file %s"), args[0]);
    goto fail;
  }
  pages = (((grub_efi_uintn_t) size + ((1 << 12) - 1)) >> 12);
  status = efi_call_4 (b->allocate_pages, GRUB_EFI_ALLOCATE_ANY_PAGES,
                       GRUB_EFI_LOADER_CODE, pages, &address);
  if (status != GRUB_EFI_SUCCESS)
  {
    grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("out of memory"));
    goto fail;
  }
  boot_image = (void *) ((grub_addr_t) address);
  if (grub_file_read (file, boot_image, size) != size)
  {
    if (grub_errno == GRUB_ERR_NONE)
      grub_error (GRUB_ERR_BAD_OS, N_("premature end of file %s"), args[0]);
    goto fail;
  }
  grub_file_close (file);
  if (state[0].set)
    connect = 0;
  if (grub_efi_load_driver (size, boot_image, connect))
    goto fail;
  return GRUB_ERR_NONE;
fail:
  if (file)
    grub_file_close (file);
  if (address)
    efi_call_2 (b->free_pages, address, pages);
  return grub_errno;
}
static grub_err_t
grub_cmd_fwconnect (grub_extcmd_context_t ctxt __attribute__ ((unused)),
                    int argc __attribute__ ((unused)),
                    char **args __attribute__ ((unused)))
{
  grub_efi_connect_all ();
  return GRUB_ERR_NONE;
}
static grub_extcmd_t cmd_fwload, cmd_fwconnect;
GRUB_MOD_INIT(fwload)
{
  cmd_fwload = grub_register_extcmd ("fwload", grub_cmd_fwload, 0, N_("FILE"),
                                     N_("Install UEFI driver."), options_fwload);
  cmd_fwconnect = grub_register_extcmd ("fwconnect", grub_cmd_fwconnect, 0,
                                        NULL, N_("Connect drivers."), 0);
}
GRUB_MOD_FINI(fwload)
{
  grub_unregister_extcmd (cmd_fwload);
  grub_unregister_extcmd (cmd_fwconnect);
}
 | 6,109 | 
	C | 
	.c | 187 | 27.331551 | 82 | 0.627761 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 613 | 
	huffman.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/huffman.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Huffman alphabets
 *
 */
#include "wimboot.h"
#include "huffman.h"
/**
 * Transcribe binary value (for debugging)
 *
 * @v value		Value
 * @v bits		Length of value (in bits)
 * @ret string		Transcribed value
 */
const char * huffman_bin ( unsigned long value, unsigned int bits ) {
	static char buf[ ( 8 * sizeof ( value ) ) + 1 /* NUL */ ];
	char *out = buf;
	/* Sanity check */
	assert ( bits < sizeof ( buf ) );
	/* Transcribe value */
	while ( bits-- )
		*(out++) = ( ( value & ( 1 << bits ) ) ? '1' : '0' );
	*out = '\0';
	return buf;
}
/**
 * Dump Huffman alphabet (for debugging)
 *
 * @v alphabet		Huffman alphabet
 */
static void __attribute__ (( unused ))
huffman_dump_alphabet ( struct huffman_alphabet *alphabet ) {
	struct huffman_symbols *sym;
	unsigned int bits;
	unsigned int huf;
	unsigned int i;
    (void)huf;
	/* Dump symbol table for each utilised length */
	for ( bits = 1 ; bits <= ( sizeof ( alphabet->huf ) /
				   sizeof ( alphabet->huf[0] ) ) ; bits++ ) {
		sym = &alphabet->huf[ bits - 1 ];
		if ( sym->freq == 0 )
			continue;
		huf = ( sym->start >> sym->shift );
		DBG ( "Huffman length %d start \"%s\" freq %d:", bits,
		      huffman_bin ( huf, sym->bits ), sym->freq );
		for ( i = 0 ; i < sym->freq ; i++ ) {
			DBG ( " %03x", sym->raw[ huf + i ] );
		}
		DBG ( "\n" );
	}
	/* Dump quick lookup table */
	DBG ( "Huffman quick lookup:" );
	for ( i = 0 ; i < ( sizeof ( alphabet->lookup ) /
			    sizeof ( alphabet->lookup[0] ) ) ; i++ ) {
		DBG ( " %d", ( alphabet->lookup[i] + 1 ) );
	}
	DBG ( "\n" );
}
/**
 * Construct Huffman alphabet
 *
 * @v alphabet		Huffman alphabet
 * @v lengths		Symbol length table
 * @v count		Number of symbols
 * @ret rc		Return status code
 */
int huffman_alphabet ( struct huffman_alphabet *alphabet,
		       uint8_t *lengths, unsigned int count ) {
	struct huffman_symbols *sym;
	unsigned int huf;
	unsigned int cum_freq;
	unsigned int bits;
	unsigned int raw;
	unsigned int adjustment;
	unsigned int prefix;
	int empty;
	int complete;
	/* Clear symbol table */
	memset ( alphabet->huf, 0, sizeof ( alphabet->huf ) );
	/* Count number of symbols with each Huffman-coded length */
	empty = 1;
	for ( raw = 0 ; raw < count ; raw++ ) {
		bits = lengths[raw];
		if ( bits ) {
			alphabet->huf[ bits - 1 ].freq++;
			empty = 0;
		}
	}
	/* In the degenerate case of having no symbols (i.e. an unused
	 * alphabet), generate a trivial alphabet with exactly two
	 * single-bit codes.  This allows callers to avoid having to
	 * check for this special case.
	 */
	if ( empty )
		alphabet->huf[0].freq = 2;
	/* Populate Huffman-coded symbol table */
	huf = 0;
	cum_freq = 0;
	for ( bits = 1 ; bits <= ( sizeof ( alphabet->huf ) /
				   sizeof ( alphabet->huf[0] ) ) ; bits++ ) {
		sym = &alphabet->huf[ bits - 1 ];
		sym->bits = bits;
		sym->shift = ( HUFFMAN_BITS - bits );
		sym->start = ( huf << sym->shift );
		sym->raw = &alphabet->raw[cum_freq];
		huf += sym->freq;
		if ( huf > ( 1U << bits ) ) {
			DBG ( "Huffman alphabet has too many symbols with "
			      "lengths <=%d\n", bits );
			return -1;
		}
		huf <<= 1;
		cum_freq += sym->freq;
	}
	complete = ( huf == ( 1U << bits ) );
	/* Populate raw symbol table */
	for ( raw = 0 ; raw < count ; raw++ ) {
		bits = lengths[raw];
		if ( bits ) {
			sym = &alphabet->huf[ bits - 1 ];
			*(sym->raw++) = raw;
		}
	}
	/* Adjust Huffman-coded symbol table raw pointers and populate
	 * quick lookup table.
	 */
	for ( bits = 1 ; bits <= ( sizeof ( alphabet->huf ) /
				   sizeof ( alphabet->huf[0] ) ) ; bits++ ) {
		sym = &alphabet->huf[ bits - 1 ];
		/* Adjust raw pointer */
		sym->raw -= sym->freq; /* Reset to first symbol */
		adjustment = ( sym->start >> sym->shift );
		sym->raw -= adjustment; /* Adjust for quick indexing */
		/* Populate quick lookup table */
		for ( prefix = ( sym->start >> HUFFMAN_QL_SHIFT ) ;
		      prefix < ( 1 << HUFFMAN_QL_BITS ) ; prefix++ ) {
			alphabet->lookup[prefix] = ( bits - 1 );
		}
	}
	/* Check that there are no invalid codes */
	if ( ! complete ) {
		DBG ( "Huffman alphabet is incomplete\n" );
		return -1;
	}
	return 0;
}
/**
 * Get Huffman symbol set
 *
 * @v alphabet		Huffman alphabet
 * @v huf		Raw input value (normalised to HUFFMAN_BITS bits)
 * @ret sym		Huffman symbol set
 */
struct huffman_symbols * huffman_sym ( struct huffman_alphabet *alphabet,
				       unsigned int huf ) {
	struct huffman_symbols *sym;
	unsigned int lookup_index;
	/* Find symbol set for this length */
	lookup_index = ( huf >> HUFFMAN_QL_SHIFT );
	sym = &alphabet->huf[ alphabet->lookup[ lookup_index ] ];
	while ( huf < sym->start )
		sym--;
	return sym;
}
 | 5,449 | 
	C | 
	.c | 184 | 26.88587 | 73 | 0.632774 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 614 | 
	xpress.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/xpress.c | 
	/*
 * Copyright (C) 2012 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * Xpress Compression Algorithm (MS-XCA) decompression
 *
 */
#include "wimboot.h"
#include "huffman.h"
#include "xpress.h"
#pragma GCC diagnostic ignored "-Wcast-align"
/**
 * Decompress XCA-compressed data
 *
 * @v data		Compressed data
 * @v len		Length of compressed data
 * @v buf		Decompression buffer, or NULL
 * @ret out_len		Length of decompressed data, or negative error
 */
ssize_t xca_decompress ( const void *data, size_t len, void *buf ) {
	const void *src = data;
	const void *end = ( uint8_t * ) src + len;
	uint8_t *out = buf;
	size_t out_len = 0;
	size_t out_len_threshold = 0;
	const struct xca_huf_len *lengths;
	struct xca xca;
	uint32_t accum = 0;
	int extra_bits = 0;
	unsigned int huf;
	struct huffman_symbols *sym;
	unsigned int raw;
	unsigned int match_len;
	unsigned int match_offset_bits;
	unsigned int match_offset;
	const uint8_t *copy;
	int rc;
	/* Process data stream */
	while ( src < end ) {
		/* (Re)initialise decompressor if applicable */
		if ( out_len >= out_len_threshold ) {
			/* Construct symbol lengths */
			lengths = src;
			src = ( uint8_t * ) src + sizeof ( *lengths );
			if ( src > end ) {
				DBG ( "XCA too short to hold Huffman lengths table.\n");
				return -1;
			}
			for ( raw = 0 ; raw < XCA_CODES ; raw++ )
				xca.lengths[raw] = xca_huf_len ( lengths, raw );
			/* Construct Huffman alphabet */
			if ( ( rc = huffman_alphabet ( &xca.alphabet,
						       xca.lengths,
						       XCA_CODES ) ) != 0 )
				return rc;
			/* Initialise state */
			accum = XCA_GET16 ( src );
			accum <<= 16;
			accum |= XCA_GET16 ( src );
			extra_bits = 16;
			/* Determine next threshold */
			out_len_threshold = ( out_len + XCA_BLOCK_SIZE );
		}
		/* Determine symbol */
		huf = ( accum >> ( 32 - HUFFMAN_BITS ) );
		sym = huffman_sym ( &xca.alphabet, huf );
		raw = huffman_raw ( sym, huf );
		accum <<= huffman_len ( sym );
		extra_bits -= huffman_len ( sym );
		if ( extra_bits < 0 ) {
			accum |= ( XCA_GET16 ( src ) << ( -extra_bits ) );
			extra_bits += 16;
		}
		/* Process symbol */
		if ( raw < XCA_END_MARKER ) {
			/* Literal symbol - add to output stream */
			if ( buf )
				*(out++) = raw;
			out_len++;
		} else if ( ( raw == XCA_END_MARKER ) &&
			    ( (uint8_t *) src >= ( ( uint8_t * ) end - 1 ) ) ) {
			/* End marker symbol */
			return out_len;
		} else {
			/* LZ77 match symbol */
			raw -= XCA_END_MARKER;
			match_offset_bits = ( raw >> 4 );
			match_len = ( raw & 0x0f );
			if ( match_len == 0x0f ) {
				match_len = XCA_GET8 ( src );
				if ( match_len == 0xff ) {
					match_len = XCA_GET16 ( src );
				} else {
					match_len += 0x0f;
				}
			}
			match_len += 3;
			if ( match_offset_bits ) {
				match_offset =
					( ( accum >> ( 32 - match_offset_bits ))
					  + ( 1 << match_offset_bits ) );
			} else {
				match_offset = 1;
			}
			accum <<= match_offset_bits;
			extra_bits -= match_offset_bits;
			if ( extra_bits < 0 ) {
				accum |= ( XCA_GET16 ( src ) << (-extra_bits) );
				extra_bits += 16;
			}
			/* Copy data */
			out_len += match_len;
			if ( buf ) {
				copy = ( out - match_offset );
				while ( match_len-- )
					*(out++) = *(copy++);
			}
		}
	}
	return out_len;
}
 | 4,001 | 
	C | 
	.c | 138 | 25.521739 | 70 | 0.618366 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 615 | 
	ventoy_plugin.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/ventoy_plugin.c | 
	/******************************************************************************
 * ventoy_plugin.c 
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <grub/types.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/disk.h>
#include <grub/device.h>
#include <grub/term.h>
#include <grub/partition.h>
#include <grub/file.h>
#include <grub/normal.h>
#include <grub/extcmd.h>
#include <grub/datetime.h>
#include <grub/i18n.h>
#include <grub/net.h>
#include <grub/crypto.h>
#include <grub/time.h>
#include <grub/font.h>
#include <grub/video.h>
#include <grub/ventoy.h>
#include "ventoy_def.h"
GRUB_MOD_LICENSE ("GPLv3+");
char g_arch_mode_suffix[64];
static char g_iso_disk_name[128];
static vtoy_password g_boot_pwd;
static vtoy_password g_file_type_pwd[img_type_max];
static install_template *g_install_template_head = NULL;
static dud *g_dud_head = NULL;
static menu_password *g_pwd_head = NULL;
static persistence_config *g_persistence_head = NULL;
static menu_tip *g_menu_tip_head = NULL;
static menu_alias *g_menu_alias_head = NULL;
static menu_class *g_menu_class_head = NULL;
static custom_boot *g_custom_boot_head = NULL;
static injection_config *g_injection_head = NULL;
static auto_memdisk *g_auto_memdisk_head = NULL;
static image_list *g_image_list_head = NULL;
static conf_replace *g_conf_replace_head = NULL;
static VTOY_JSON *g_menu_lang_json = NULL;
static int g_theme_id = 0;
static int g_theme_res_fit = 0;
static int g_theme_num = 0;
static theme_list *g_theme_head = NULL;
static int g_theme_random = vtoy_theme_random_boot_second;
static char g_theme_single_file[256];
static char g_cur_menu_language[32] = {0};
static char g_push_menu_language[32] = {0};
static int ventoy_plugin_is_parent(const char *pat, int patlen, const char *isopath)
{
    if (patlen > 1)
    {
        if (isopath[patlen] == '/' && ventoy_strncmp(pat, isopath, patlen) == 0 &&
            grub_strchr(isopath + patlen + 1, '/') == NULL)
        {
            return 1;
        }
    }
    else
    {
        if (pat[0] == '/' && grub_strchr(isopath + 1, '/') == NULL)
        {
            return 1;
        }
    }
    return 0;
}
static int ventoy_plugin_control_check(VTOY_JSON *json, const char *isodisk)
{
    int rc = 0;
    VTOY_JSON *pNode = NULL;
    VTOY_JSON *pChild = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array type %d\n", json->enDataType);
        return 1;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->enDataType == JSON_TYPE_OBJECT)
        {
            pChild = pNode->pstChild;
            if (pChild->enDataType == JSON_TYPE_STRING)
            {
                if (grub_strcmp(pChild->pcName, "VTOY_DEFAULT_IMAGE") == 0)
                {                    
                    grub_printf("%s: %s [%s]\n", pChild->pcName, pChild->unData.pcStrVal,
                        ventoy_check_file_exist("%s%s", isodisk, pChild->unData.pcStrVal) ? "OK" : "NOT EXIST");
                }
                else
                {
                    grub_printf("%s: %s\n", pChild->pcName, pChild->unData.pcStrVal);                    
                }
            }
            else
            {
                grub_printf("%s is NOT string type\n", pChild->pcName);
                rc = 1;
            }
        }
        else
        {
            grub_printf("%s is not an object\n", pNode->pcName);
            rc = 1;
        }
    }
    return rc;
}
static int ventoy_plugin_control_entry(VTOY_JSON *json, const char *isodisk)
{
    VTOY_JSON *pNode = NULL;
    VTOY_JSON *pChild = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->enDataType == JSON_TYPE_OBJECT)
        {
            pChild = pNode->pstChild;
            if (pChild->enDataType == JSON_TYPE_STRING && pChild->pcName && pChild->unData.pcStrVal)
            {
                ventoy_set_env(pChild->pcName, pChild->unData.pcStrVal);
            }
        }
    }
    return 0;
}
static int ventoy_plugin_theme_check(VTOY_JSON *json, const char *isodisk)
{
    int exist = 0;
    const char *value;
    VTOY_JSON *node;
    
    value = vtoy_json_get_string_ex(json->pstChild, "file");
    if (value)
    {
        grub_printf("file: %s\n", value);
        if (value[0] == '/')
        {
            exist = ventoy_check_file_exist("%s%s", isodisk, value);
        }
        else
        {
            exist = ventoy_check_file_exist("%s/ventoy/%s", isodisk, value);
        }
        
        if (exist == 0)
        {
            grub_printf("Theme file %s does NOT exist\n", value);
            return 1;
        }
    }
    else
    {
        node = vtoy_json_find_item(json->pstChild, JSON_TYPE_ARRAY, "file");
        if (node)
        {
            for (node = node->pstChild; node; node = node->pstNext)
            {
                value = node->unData.pcStrVal;
                grub_printf("file: %s\n", value);
                if (value[0] == '/')
                {
                    exist = ventoy_check_file_exist("%s%s", isodisk, value);
                }
                else
                {
                    exist = ventoy_check_file_exist("%s/ventoy/%s", isodisk, value);
                }
                if (exist == 0)
                {
                    grub_printf("Theme file %s does NOT exist\n", value);
                    return 1;
                }
            }
            value = vtoy_json_get_string_ex(json->pstChild, "random");
            if (value)
            {
                grub_printf("random: %s\n", value);
            }
        }
    }
    
    value = vtoy_json_get_string_ex(json->pstChild, "gfxmode");
    if (value)
    {
        grub_printf("gfxmode: %s\n", value);
    }
    
    value = vtoy_json_get_string_ex(json->pstChild, "display_mode");
    if (value)
    {
        grub_printf("display_mode: %s\n", value);
    }
    value = vtoy_json_get_string_ex(json->pstChild, "serial_param");
    if (value)
    {
        grub_printf("serial_param %s\n", value);
    }
    value = vtoy_json_get_string_ex(json->pstChild, "ventoy_left");
    if (value)
    {
        grub_printf("ventoy_left: %s\n", value);
    }
    
    value = vtoy_json_get_string_ex(json->pstChild, "ventoy_top");
    if (value)
    {
        grub_printf("ventoy_top: %s\n", value);
    }
    
    value = vtoy_json_get_string_ex(json->pstChild, "ventoy_color");
    if (value)
    {
        grub_printf("ventoy_color: %s\n", value);
    }
    node = vtoy_json_find_item(json->pstChild, JSON_TYPE_ARRAY, "fonts");
    if (node)
    {
        for (node = node->pstChild; node; node = node->pstNext)
        {
            if (node->enDataType == JSON_TYPE_STRING)
            {
                if (ventoy_check_file_exist("%s%s", isodisk, node->unData.pcStrVal))
                {
                    grub_printf("%s [OK]\n", node->unData.pcStrVal);
                }
                else
                {
                    grub_printf("%s [NOT EXIST]\n", node->unData.pcStrVal);
                }
            }
        }
    }
    else
    {
        grub_printf("fonts NOT found\n");
    }
    return 0;
}
static int ventoy_plugin_theme_entry(VTOY_JSON *json, const char *isodisk)
{
    const char *value;
    char val[64];
    char filepath[256];
    VTOY_JSON *node = NULL;
    theme_list *tail = NULL;
    theme_list *themenode = NULL;
    value = vtoy_json_get_string_ex(json->pstChild, "file");
    if (value)
    {
        if (value[0] == '/')
        {
            grub_snprintf(filepath, sizeof(filepath), "%s%s", isodisk, value);
        }
        else
        {
            grub_snprintf(filepath, sizeof(filepath), "%s/ventoy/%s", isodisk, value);
        }
        
        if (ventoy_check_file_exist(filepath) == 0)
        {
            debug("Theme file %s does not exist\n", filepath);
            return 0;
        }
        debug("vtoy_theme %s\n", filepath);
        ventoy_env_export("vtoy_theme", filepath);
        grub_snprintf(g_theme_single_file, sizeof(g_theme_single_file), "%s", filepath);
    }
    else
    {
        node = vtoy_json_find_item(json->pstChild, JSON_TYPE_ARRAY, "file");
        if (node)
        {
            for (node = node->pstChild; node; node = node->pstNext)
            {
                value = node->unData.pcStrVal;
                if (value[0] == '/')
                {
                    grub_snprintf(filepath, sizeof(filepath), "%s%s", isodisk, value);
                }
                else
                {
                    grub_snprintf(filepath, sizeof(filepath), "%s/ventoy/%s", isodisk, value);
                }
                if (ventoy_check_file_exist(filepath) == 0)
                {
                    continue;
                }
                themenode = grub_zalloc(sizeof(theme_list));
                if (themenode)
                {
                    grub_snprintf(themenode->theme.path, sizeof(themenode->theme.path), "%s", filepath);
                    if (g_theme_head)
                    {
                        tail->next = themenode;
                    }
                    else
                    {
                        g_theme_head = themenode;
                    }
                    tail = themenode;
                    g_theme_num++;
                }
            }
            ventoy_env_export("vtoy_theme", "random");
            value = vtoy_json_get_string_ex(json->pstChild, "random");
            if (value)
            {
                if (grub_strcmp(value, "boot_second") == 0)
                {
                    g_theme_random = vtoy_theme_random_boot_second;
                }
                else if (grub_strcmp(value, "boot_day") == 0)
                {
                    g_theme_random = vtoy_theme_random_boot_day;
                }
                else if (grub_strcmp(value, "boot_month") == 0)
                {
                    g_theme_random = vtoy_theme_random_boot_month;
                }
            }
        }
    }
    grub_snprintf(val, sizeof(val), "%d", g_theme_num);
    grub_env_set("VTOY_THEME_COUNT", val);
    grub_env_export("VTOY_THEME_COUNT");
    if (g_theme_num > 0)
    {
        vtoy_json_get_int(json->pstChild, "default_file", &g_theme_id);
        if (g_theme_id == 0)
        {
            vtoy_json_get_int(json->pstChild, "resolution_fit", &g_theme_res_fit);
            if (g_theme_res_fit != 1)
            {
                g_theme_res_fit = 0;
            }
            grub_snprintf(val, sizeof(val), "%d", g_theme_res_fit);
            ventoy_env_export("vtoy_res_fit", val);
        }
        
        if (g_theme_id > g_theme_num || g_theme_id < 0)
        {
            g_theme_id = 0;
        }
    }
    
    value = vtoy_json_get_string_ex(json->pstChild, "gfxmode");
    if (value)
    {
        debug("vtoy_gfxmode %s\n", value);
        ventoy_env_export("vtoy_gfxmode", value);
    }
    
    value = vtoy_json_get_string_ex(json->pstChild, "display_mode");
    if (value)
    {
        debug("display_mode %s\n", value);
        ventoy_env_export("vtoy_display_mode", value);
    }
    
    value = vtoy_json_get_string_ex(json->pstChild, "serial_param");
    if (value)
    {
        debug("serial_param %s\n", value);
        ventoy_env_export("vtoy_serial_param", value);
    }
    value = vtoy_json_get_string_ex(json->pstChild, "ventoy_left");
    if (value)
    {
        ventoy_env_export(ventoy_left_key, value);
    }
    
    value = vtoy_json_get_string_ex(json->pstChild, "ventoy_top");
    if (value)
    {
        ventoy_env_export(ventoy_top_key, value);
    }
    
    value = vtoy_json_get_string_ex(json->pstChild, "ventoy_color");
    if (value)
    {
        ventoy_env_export(ventoy_color_key, value);
    }
    node = vtoy_json_find_item(json->pstChild, JSON_TYPE_ARRAY, "fonts");
    if (node)
    {
        for (node = node->pstChild; node; node = node->pstNext)
        {
            if (node->enDataType == JSON_TYPE_STRING && 
                ventoy_check_file_exist("%s%s", isodisk, node->unData.pcStrVal))
            {
                grub_snprintf(filepath, sizeof(filepath), "%s%s", isodisk, node->unData.pcStrVal);
                grub_font_load(filepath);
            }
        }
    }
    return 0;
}
static int ventoy_plugin_check_path(const char *path, const char *file)
{
    if (file[0] != '/')
    {
        grub_printf("%s is NOT begin with '/' \n", file);
        return 1;
    }
    if (grub_strchr(file, '\\'))
    {
        grub_printf("%s contains invalid '\\' \n", file);
        return 1;
    }
    
    if (grub_strstr(file, "//"))
    {
        grub_printf("%s contains invalid double slash\n", file);
        return 1;
    }
    if (grub_strstr(file, "../"))
    {
        grub_printf("%s contains invalid '../' \n", file);
        return 1;
    }
    if (!ventoy_check_file_exist("%s%s", path, file))
    {
        grub_printf("%s%s does NOT exist\n", path, file);
        return 1;
    }
    return 0;
}
static int ventoy_plugin_check_fullpath
(
    VTOY_JSON *json, 
    const char *isodisk, 
    const char *key,
    int *pathnum
)
{
    int rc = 0;
    int ret = 0;
    int cnt = 0;
    VTOY_JSON *node = json;
    VTOY_JSON *child = NULL;
    
    while (node)
    {
        if (0 == grub_strcmp(key, node->pcName))
        {
            break;
        }
        node = node->pstNext;
    }
    if (!node)
    {
        return 1;
    }
    if (JSON_TYPE_STRING == node->enDataType)
    {
        cnt = 1;
        ret = ventoy_plugin_check_path(isodisk, node->unData.pcStrVal);
        grub_printf("%s: %s [%s]\n", key, node->unData.pcStrVal, ret ? "FAIL" : "OK");
    }
    else if (JSON_TYPE_ARRAY == node->enDataType)
    {
        for (child = node->pstChild; child; child = child->pstNext)
        {
            if (JSON_TYPE_STRING != child->enDataType)
            {
                grub_printf("Non string json type\n");
            }
            else
            {
                rc = ventoy_plugin_check_path(isodisk, child->unData.pcStrVal);
                grub_printf("%s: %s [%s]\n", key, child->unData.pcStrVal, rc ? "FAIL" : "OK");
                ret += rc;
                cnt++;
            }
        }
    }
    *pathnum = cnt;
    return ret;
}
static int ventoy_plugin_parse_fullpath
(
    VTOY_JSON *json, 
    const char *isodisk, 
    const char *key, 
    file_fullpath **fullpath,
    int *pathnum
)
{
    int rc = 1;
    int count = 0;
    VTOY_JSON *node = json;
    VTOY_JSON *child = NULL;
    file_fullpath *path = NULL;
    
    while (node)
    {
        if (0 == grub_strcmp(key, node->pcName))
        {
            break;
        }
        node = node->pstNext;
    }
    if (!node)
    {
        return 1;
    }
    if (JSON_TYPE_STRING == node->enDataType)
    {
        debug("%s is string type data\n", node->pcName);
        if ((node->unData.pcStrVal[0] != '/') || (!ventoy_check_file_exist("%s%s", isodisk, node->unData.pcStrVal)))
        {
            debug("%s%s file not found\n", isodisk, node->unData.pcStrVal);
            return 1;
        }
        
        path = (file_fullpath *)grub_zalloc(sizeof(file_fullpath));
        if (path)
        {
            grub_snprintf(path->path, sizeof(path->path), "%s", node->unData.pcStrVal);
            *fullpath = path;
            *pathnum = 1;
            rc = 0;
        }
    }
    else if (JSON_TYPE_ARRAY == node->enDataType)
    {
        for (child = node->pstChild; child; child = child->pstNext)
        {
            if ((JSON_TYPE_STRING != child->enDataType) || (child->unData.pcStrVal[0] != '/'))
            {
                debug("Invalid data type:%d\n", child->enDataType);
                return 1;
            }
            count++;
        }
        debug("%s is array type data, count=%d\n", node->pcName, count);
        
        path = (file_fullpath *)grub_zalloc(sizeof(file_fullpath) * count);
        if (path)
        {
            *fullpath = path;
            
            for (count = 0, child = node->pstChild; child; child = child->pstNext)
            {
                if (ventoy_check_file_exist("%s%s", isodisk, child->unData.pcStrVal))
                {
                    grub_snprintf(path->path, sizeof(path->path), "%s", child->unData.pcStrVal);
                    path++;
                    count++;
                }
            }
            *pathnum = count;
            rc = 0;
        }
    }
    return rc;
}
static int ventoy_plugin_auto_install_check(VTOY_JSON *json, const char *isodisk)
{
    int pathnum = 0;
    int autosel = 0;
    int timeout = 0;
    char *pos = NULL;
    const char *iso = NULL;
    VTOY_JSON *pNode = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array type %d\n", json->enDataType);
        return 1;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->enDataType != JSON_TYPE_OBJECT)
        {
            grub_printf("NOT object type\n");
        }
    
        if ((iso = vtoy_json_get_string_ex(pNode->pstChild, "image")) != NULL)
        {
            pos = grub_strchr(iso, '*');
            if (pos || 0 == ventoy_plugin_check_path(isodisk, iso))
            {
                grub_printf("image: %s [%s]\n", iso, (pos ? "*" : "OK"));                
                ventoy_plugin_check_fullpath(pNode->pstChild, isodisk, "template", &pathnum);
                
                if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "autosel", &autosel))
                {
                    if (autosel >= 0 && autosel <= pathnum)
                    {
                        grub_printf("autosel: %d [OK]\n", autosel);
                    }
                    else
                    {
                        grub_printf("autosel: %d [FAIL]\n", autosel);
                    }
                }
                
                if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "timeout", &timeout))
                {
                    if (timeout >= 0)
                    {
                        grub_printf("timeout: %d [OK]\n", timeout);
                    }
                    else
                    {
                        grub_printf("timeout: %d [FAIL]\n", timeout);
                    }
                }
            }
            else
            {
                grub_printf("image: %s [FAIL]\n", iso);
            }
        }
        else if ((iso = vtoy_json_get_string_ex(pNode->pstChild, "parent")) != NULL)
        {
            if (ventoy_is_dir_exist("%s%s", isodisk, iso))
            {
                grub_printf("parent: %s [OK]\n", iso);
                ventoy_plugin_check_fullpath(pNode->pstChild, isodisk, "template", &pathnum);
                
                if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "autosel", &autosel))
                {
                    if (autosel >= 0 && autosel <= pathnum)
                    {
                        grub_printf("autosel: %d [OK]\n", autosel);
                    }
                    else
                    {
                        grub_printf("autosel: %d [FAIL]\n", autosel);
                    }
                }
                
                if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "timeout", &timeout))
                {
                    if (timeout >= 0)
                    {
                        grub_printf("timeout: %d [OK]\n", timeout);
                    }
                    else
                    {
                        grub_printf("timeout: %d [FAIL]\n", timeout);
                    }
                }
            }
            else
            {
                grub_printf("parent: %s [FAIL]\n", iso);
            }
        }
        else
        {
            grub_printf("image not found\n");
        }
    }
    return 0;
}
static int ventoy_plugin_auto_install_entry(VTOY_JSON *json, const char *isodisk)
{
    int type = 0;
    int pathnum = 0;
    int autosel = 0;
    int timeout = 0;
    const char *iso = NULL;
    VTOY_JSON *pNode = NULL;
    install_template *node = NULL;
    install_template *next = NULL;
    file_fullpath *templatepath = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    if (g_install_template_head)
    {
        for (node = g_install_template_head; node; node = next)
        {
            next = node->next;
            grub_check_free(node->templatepath);
            grub_free(node);
        }
        g_install_template_head = NULL;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        type = auto_install_type_file;
        iso = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (!iso)
        {
            type = auto_install_type_parent;
            iso = vtoy_json_get_string_ex(pNode->pstChild, "parent");
        }
        
        if (iso && iso[0] == '/')
        {
            if (0 == ventoy_plugin_parse_fullpath(pNode->pstChild, isodisk, "template", &templatepath, &pathnum))
            {
                node = grub_zalloc(sizeof(install_template));
                if (node)
                {
                    node->type = type;
                    node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", iso);
                    node->templatepath = templatepath;
                    node->templatenum = pathnum;
                    node->autosel = -1;
                    node->timeout = -1;
                    if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "autosel", &autosel))
                    {
                        if (autosel >= 0 && autosel <= pathnum)
                        {
                            node->autosel = autosel;
                        }
                    }
                    
                    if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "timeout", &timeout))
                    {
                        if (timeout >= 0)
                        {
                            node->timeout = timeout;
                        }
                    }
                    if (g_install_template_head)
                    {
                        node->next = g_install_template_head;
                    }
                    
                    g_install_template_head = node;
                }
            }
        }
    }
    return 0;
}
static int ventoy_plugin_dud_check(VTOY_JSON *json, const char *isodisk)
{
    int pathnum = 0;
    char *pos = NULL;
    const char *iso = NULL;
    VTOY_JSON *pNode = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array type %d\n", json->enDataType);
        return 1;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->enDataType != JSON_TYPE_OBJECT)
        {
            grub_printf("NOT object type\n");
        }
    
        iso = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (iso)
        {
            pos = grub_strchr(iso, '*');
            if (pos || 0 == ventoy_plugin_check_path(isodisk, iso))
            {
                grub_printf("image: %s [%s]\n", iso, (pos ? "*" : "OK"));
                ventoy_plugin_check_fullpath(pNode->pstChild, isodisk, "dud", &pathnum);
            }
            else
            {
                grub_printf("image: %s [FAIL]\n", iso);
            }
        }
        else
        {
            grub_printf("image not found\n");
        }
    }
    return 0;
}
static int ventoy_plugin_dud_entry(VTOY_JSON *json, const char *isodisk)
{
    int pathnum = 0;
    const char *iso = NULL;
    VTOY_JSON *pNode = NULL;
    dud *node = NULL;
    dud *next = NULL;
    file_fullpath *dudpath = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    if (g_dud_head)
    {
        for (node = g_dud_head; node; node = next)
        {
            next = node->next;
            grub_check_free(node->dudpath);
            grub_free(node);
        }
        g_dud_head = NULL;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        iso = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (iso && iso[0] == '/')
        {
            if (0 == ventoy_plugin_parse_fullpath(pNode->pstChild, isodisk, "dud", &dudpath, &pathnum))
            {
                node = grub_zalloc(sizeof(dud));
                if (node)
                {
                    node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", iso);
                    node->dudpath = dudpath;
                    node->dudnum = pathnum;
                    node->files = grub_zalloc(sizeof(dudfile) * pathnum);
                    if (node->files)
                    {
                        if (g_dud_head)
                        {
                            node->next = g_dud_head;
                        }
                        
                        g_dud_head = node;
                    }
                    else
                    {
                        grub_free(node);
                    }
                }
            }
        }
    }
    return 0;
}
static int ventoy_plugin_parse_pwdstr(char *pwdstr, vtoy_password *pwd)
{
    int i;
    int len;
    char ch;
    char *pos;
    char bytes[3];
    vtoy_password tmpPwd;
    
    len = (int)grub_strlen(pwdstr);
    if (len > 64)
    {
        if (NULL == pwd) grub_printf("Password too long %d\n", len);
        return 1;
    }
    grub_memset(&tmpPwd, 0, sizeof(tmpPwd));
    if (grub_strncmp(pwdstr, "txt#", 4) == 0)
    {
        tmpPwd.type = VTOY_PASSWORD_TXT;
        grub_snprintf(tmpPwd.text, sizeof(tmpPwd.text), "%s", pwdstr + 4);
    }
    else if (grub_strncmp(pwdstr, "md5#", 4) == 0)
    {
        if ((len - 4) == 32)
        {
            for (i = 0; i < 16; i++)
            {
                bytes[0] = pwdstr[4 + i * 2];
                bytes[1] = pwdstr[4 + i * 2 + 1];
                bytes[2] = 0;
                
                if (grub_isxdigit(bytes[0]) && grub_isxdigit(bytes[1]))
                {
                    tmpPwd.md5[i] = (grub_uint8_t)grub_strtoul(bytes, NULL, 16);
                }
                else
                {
                    if (NULL == pwd) grub_printf("Invalid md5 hex format %s %d\n", pwdstr, i);
                    return 1;
                }
            }
            tmpPwd.type = VTOY_PASSWORD_MD5;
        }
        else if ((len - 4) > 32)
        {
            pos = grub_strchr(pwdstr + 4, '#');
            if (!pos)
            {
                if (NULL == pwd) grub_printf("Invalid md5 password format %s\n", pwdstr);
                return 1;
            }
            if (len - 1 - ((long)pos - (long)pwdstr) != 32)
            {
                if (NULL == pwd) grub_printf("Invalid md5 salt password format %s\n", pwdstr);
                return 1;
            }
        
            ch = *pos;
            *pos = 0;
            grub_snprintf(tmpPwd.salt, sizeof(tmpPwd.salt), "%s", pwdstr + 4);
            *pos = ch;
            pos++;
            for (i = 0; i < 16; i++)
            {
                bytes[0] = pos[i * 2];
                bytes[1] = pos[i * 2 + 1];
                bytes[2] = 0;
                
                if (grub_isxdigit(bytes[0]) && grub_isxdigit(bytes[1]))
                {
                    tmpPwd.md5[i] = (grub_uint8_t)grub_strtoul(bytes, NULL, 16);
                }
                else
                {
                    if (NULL == pwd) grub_printf("Invalid md5 hex format %s %d\n", pwdstr, i);
                    return 1;
                }
            }
            tmpPwd.type = VTOY_PASSWORD_SALT_MD5;
        }
        else
        {
            if (NULL == pwd) grub_printf("Invalid md5 password format %s\n", pwdstr);
            return 1;
        }
    }
    else
    {
        if (NULL == pwd) grub_printf("Invalid password format %s\n", pwdstr);
        return 1;
    }
    if (pwd)
    {
        grub_memcpy(pwd, &tmpPwd, sizeof(tmpPwd));
    }
    return 0;
}
static int ventoy_plugin_get_pwd_type(const char *pwd)
{
    int i;
    char pwdtype[64];
    for (i = 0; pwd && i < (int)ARRAY_SIZE(g_menu_prefix); i++)
    {
        grub_snprintf(pwdtype, sizeof(pwdtype), "%spwd", g_menu_prefix[i]);
        if (grub_strcmp(pwdtype, pwd) == 0)
        {
            return img_type_start + i; 
        }
    }
    
    return -1;
}
static int ventoy_plugin_pwd_entry(VTOY_JSON *json, const char *isodisk)
{
    int type = -1;
    const char *iso = NULL;
    const char *pwd = NULL;
    VTOY_JSON *pNode = NULL;
    VTOY_JSON *pCNode = NULL;
    menu_password *node = NULL;
    menu_password *tail = NULL;
    menu_password *next = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_OBJECT)
    {
        debug("Not object %d\n", json->enDataType);
        return 0;
    }
    if (g_pwd_head)
    {
        for (node = g_pwd_head; node; node = next)
        {
            next = node->next;
            grub_free(node);
        }
        g_pwd_head = NULL;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->pcName && grub_strcmp("bootpwd", pNode->pcName) == 0)
        {
            ventoy_plugin_parse_pwdstr(pNode->unData.pcStrVal, &g_boot_pwd);
        }
        else if ((type = ventoy_plugin_get_pwd_type(pNode->pcName)) >= 0)
        {
            ventoy_plugin_parse_pwdstr(pNode->unData.pcStrVal, g_file_type_pwd + type);
        }
        else if (pNode->pcName && grub_strcmp("menupwd", pNode->pcName) == 0)
        {
            for (pCNode = pNode->pstChild; pCNode; pCNode = pCNode->pstNext)
            {
                if (pCNode->enDataType != JSON_TYPE_OBJECT)
                {
                    continue;
                }
                type = vtoy_menu_pwd_file;
                iso = vtoy_json_get_string_ex(pCNode->pstChild, "file");
                if (!iso)
                {
                    type = vtoy_menu_pwd_parent;
                    iso = vtoy_json_get_string_ex(pCNode->pstChild, "parent");                    
                }                
                
                pwd = vtoy_json_get_string_ex(pCNode->pstChild, "pwd");
                if (iso && pwd && iso[0] == '/')
                {
                    node = grub_zalloc(sizeof(menu_password));
                    if (node)
                    {
                        node->type = type;
                        node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", iso);
                        if (ventoy_plugin_parse_pwdstr((char *)pwd, &(node->password)))
                        {
                            grub_free(node);
                            continue;
                        }
                        if (g_pwd_head)
                        {
                            tail->next = node;
                        }
                        else
                        {
                            g_pwd_head = node;
                        }
                        tail = node;
                    }
                }
            }
        }
    }
    return 0;
}
static int ventoy_plugin_pwd_check(VTOY_JSON *json, const char *isodisk)
{
    int type = -1;
    char *pos = NULL;
    const char *iso = NULL;
    const char *pwd = NULL;
    VTOY_JSON *pNode = NULL;
    VTOY_JSON *pCNode = NULL;
    if (json->enDataType != JSON_TYPE_OBJECT)
    {
        grub_printf("Not object %d\n", json->enDataType);
        return 0;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->pcName && grub_strcmp("bootpwd", pNode->pcName) == 0)
        {
            if (0 == ventoy_plugin_parse_pwdstr(pNode->unData.pcStrVal, NULL))
            {
                grub_printf("bootpwd:<%s>\n", pNode->unData.pcStrVal);
            }
            else
            {
                grub_printf("Invalid bootpwd.\n");
            }
        }
        else if ((type = ventoy_plugin_get_pwd_type(pNode->pcName)) >= 0)
        {
            if (0 == ventoy_plugin_parse_pwdstr(pNode->unData.pcStrVal, NULL))
            {
                grub_printf("%s:<%s>\n", pNode->pcName, pNode->unData.pcStrVal);
            }
            else
            {
                grub_printf("Invalid pwd <%s>\n", pNode->unData.pcStrVal);
            }
        }
        else if (pNode->pcName && grub_strcmp("menupwd", pNode->pcName) == 0)
        {
            grub_printf("\n");
            for (pCNode = pNode->pstChild; pCNode; pCNode = pCNode->pstNext)
            {
                if (pCNode->enDataType != JSON_TYPE_OBJECT)
                {
                    grub_printf("Not object %d\n", pCNode->enDataType);
                    continue;
                }
                if ((iso = vtoy_json_get_string_ex(pCNode->pstChild, "file")) != NULL)
                {
                    pos = grub_strchr(iso, '*');
                    if (pos || 0 == ventoy_plugin_check_path(isodisk, iso))
                    {
                        pwd = vtoy_json_get_string_ex(pCNode->pstChild, "pwd");
                        if (0 == ventoy_plugin_parse_pwdstr((char *)pwd, NULL))
                        {
                            grub_printf("file:<%s> [%s]\n", iso, (pos ? "*" : "OK"));
                            grub_printf("pwd:<%s>\n\n", pwd);
                        }
                        else
                        {
                            grub_printf("Invalid password for <%s>\n", iso);
                        }
                    }
                    else
                    {
                        grub_printf("<%s%s> not found\n", isodisk, iso);
                    }
                }
                else if ((iso = vtoy_json_get_string_ex(pCNode->pstChild, "parent")) != NULL)
                {
                    if (ventoy_is_dir_exist("%s%s", isodisk, iso))
                    {
                        pwd = vtoy_json_get_string_ex(pCNode->pstChild, "pwd");
                        if (0 == ventoy_plugin_parse_pwdstr((char *)pwd, NULL))
                        {
                            grub_printf("dir:<%s> [%s]\n", iso, (pos ? "*" : "OK"));
                            grub_printf("pwd:<%s>\n\n", pwd);
                        }
                        else
                        {
                            grub_printf("Invalid password for <%s>\n", iso);
                        }
                    }
                    else
                    {
                        grub_printf("<%s%s> not found\n", isodisk, iso);
                    }
                }
                else
                {
                    grub_printf("No file item found in json.\n");
                }
            }
        }
    }
    return 0;
}
static int ventoy_plugin_persistence_check(VTOY_JSON *json, const char *isodisk)
{
    int autosel = 0;
    int timeout = 0;
    int pathnum = 0;
    char *pos = NULL;
    const char *iso = NULL;
    VTOY_JSON *pNode = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array type %d\n", json->enDataType);
        return 1;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->enDataType != JSON_TYPE_OBJECT)
        {
            grub_printf("NOT object type\n");
        }
    
        iso = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (iso)
        {
            pos = grub_strchr(iso, '*');
            if (pos || 0 == ventoy_plugin_check_path(isodisk, iso))
            {
                grub_printf("image: %s [%s]\n", iso, (pos ? "*" : "OK"));
                ventoy_plugin_check_fullpath(pNode->pstChild, isodisk, "backend", &pathnum);
                if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "autosel", &autosel))
                {
                    if (autosel >= 0 && autosel <= pathnum)
                    {
                        grub_printf("autosel: %d [OK]\n", autosel);
                    }
                    else
                    {
                        grub_printf("autosel: %d [FAIL]\n", autosel);
                    }
                }
                
                if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "timeout", &timeout))
                {
                    if (timeout >= 0)
                    {
                        grub_printf("timeout: %d [OK]\n", timeout);
                    }
                    else
                    {
                        grub_printf("timeout: %d [FAIL]\n", timeout);
                    }
                }
            } 
            else
            {
                grub_printf("image: %s [FAIL]\n", iso);
            }
        }
        else
        {
            grub_printf("image not found\n");
        }
    }
    return 0;
}
static int ventoy_plugin_persistence_entry(VTOY_JSON *json, const char *isodisk)
{
    int autosel = 0;
    int timeout = 0;
    int pathnum = 0;
    const char *iso = NULL;
    VTOY_JSON *pNode = NULL;
    persistence_config *node = NULL;
    persistence_config *next = NULL;
    file_fullpath *backendpath = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    if (g_persistence_head)
    {
        for (node = g_persistence_head; node; node = next)
        {
            next = node->next;
            grub_check_free(node->backendpath);
            grub_free(node);
        }
        g_persistence_head = NULL;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        iso = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (iso && iso[0] == '/')
        {
            if (0 == ventoy_plugin_parse_fullpath(pNode->pstChild, isodisk, "backend", &backendpath, &pathnum))
            {
                node = grub_zalloc(sizeof(persistence_config));
                if (node)
                {
                    node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", iso);
                    node->backendpath = backendpath;
                    node->backendnum = pathnum;
                    node->autosel = -1;
                    node->timeout = -1;
                    if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "autosel", &autosel))
                    {
                        if (autosel >= 0 && autosel <= pathnum)
                        {
                            node->autosel = autosel;
                        }
                    }
                    
                    if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "timeout", &timeout))
                    {
                        if (timeout >= 0)
                        {
                            node->timeout = timeout;
                        }
                    }
                    if (g_persistence_head)
                    {
                        node->next = g_persistence_head;
                    }
                    
                    g_persistence_head = node;
                }
            }
        }
    }
    return 0;
}
static int ventoy_plugin_menualias_check(VTOY_JSON *json, const char *isodisk)
{
    int type;
    const char *path = NULL;
    const char *alias = NULL;
    VTOY_JSON *pNode = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array %d\n", json->enDataType);
        return 1;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        type = vtoy_alias_image_file;
        path = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (!path)
        {
            path = vtoy_json_get_string_ex(pNode->pstChild, "dir");
            type = vtoy_alias_directory;
        }
        
        alias = vtoy_json_get_string_ex(pNode->pstChild, "alias");
        if (path && path[0] == '/' && alias)
        {
            if (vtoy_alias_image_file == type)
            {
                if (grub_strchr(path, '*'))
                {
                    grub_printf("image: <%s> [ * ]\n", path);
                }
                else if (ventoy_check_file_exist("%s%s", isodisk, path))
                {
                    grub_printf("image: <%s> [ OK ]\n", path);
                }
                else
                {
                    grub_printf("image: <%s> [ NOT EXIST ]\n", path);
                }
            }
            else
            {
                if (ventoy_is_dir_exist("%s%s", isodisk, path))
                {
                    grub_printf("dir: <%s> [ OK ]\n", path);
                }
                else
                {
                    grub_printf("dir: <%s> [ NOT EXIST ]\n", path);
                }
            }
            grub_printf("alias: <%s>\n\n", alias);
        }
    }
    return 0;
}
static int ventoy_plugin_menualias_entry(VTOY_JSON *json, const char *isodisk)
{
    int type;
    const char *path = NULL;
    const char *alias = NULL;
    VTOY_JSON *pNode = NULL;
    menu_alias *node = NULL;
    menu_alias *next = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    if (g_menu_alias_head)
    {
        for (node = g_menu_alias_head; node; node = next)
        {
            next = node->next;
            grub_free(node);
        }
        g_menu_alias_head = NULL;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        type = vtoy_alias_image_file;
        path = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (!path)
        {
            path = vtoy_json_get_string_ex(pNode->pstChild, "dir");
            type = vtoy_alias_directory;
        }
        
        alias = vtoy_json_get_string_ex(pNode->pstChild, "alias");
        if (path && path[0] == '/' && alias)
        {
            node = grub_zalloc(sizeof(menu_alias));
            if (node)
            {
                node->type = type;
                node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", path);
                grub_snprintf(node->alias, sizeof(node->alias), "%s", alias);
                if (g_menu_alias_head)
                {
                    node->next = g_menu_alias_head;
                }
                
                g_menu_alias_head = node;
            }
        }
    }
    return 0;
}
static int ventoy_plugin_menutip_check(VTOY_JSON *json, const char *isodisk)
{
    int type;
    const char *path = NULL;
    const char *tip = NULL;
    VTOY_JSON *pNode = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_OBJECT)
    {
        grub_printf("Not object %d\n", json->enDataType);
        return 1;
    }
    tip = vtoy_json_get_string_ex(json->pstChild, "left");
    if (tip)
    {
        grub_printf("left: <%s>\n", tip);
    }
    
    tip = vtoy_json_get_string_ex(json->pstChild, "top");
    if (tip)
    {
        grub_printf("top: <%s>\n", tip);
    }
    
    tip = vtoy_json_get_string_ex(json->pstChild, "color");
    if (tip)
    {
        grub_printf("color: <%s>\n", tip);
    }
    pNode = vtoy_json_find_item(json->pstChild, JSON_TYPE_ARRAY, "tips");
    for (pNode = pNode->pstChild; pNode; pNode = pNode->pstNext)
    {
        type = vtoy_tip_image_file;
        path = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (!path)
        {
            path = vtoy_json_get_string_ex(pNode->pstChild, "dir");
            type = vtoy_tip_directory;
        }
        
        if (path && path[0] == '/')
        {
            if (vtoy_tip_image_file == type)
            {
                if (grub_strchr(path, '*'))
                {
                    grub_printf("image: <%s> [ * ]\n", path);
                }
                else if (ventoy_check_file_exist("%s%s", isodisk, path))
                {
                    grub_printf("image: <%s> [ OK ]\n", path);
                }
                else
                {
                    grub_printf("image: <%s> [ NOT EXIST ]\n", path);
                }
            }
            else
            {
                if (ventoy_is_dir_exist("%s%s", isodisk, path))
                {
                    grub_printf("dir: <%s> [ OK ]\n", path);
                }
                else
                {
                    grub_printf("dir: <%s> [ NOT EXIST ]\n", path);
                }
            }
            tip = vtoy_json_get_string_ex(pNode->pstChild, "tip");
            if (tip)
            {
                grub_printf("tip: <%s>\n", tip);
            }
            else
            {
                tip = vtoy_json_get_string_ex(pNode->pstChild, "tip1");
                if (tip)
                    grub_printf("tip1: <%s>\n", tip);
                else
                    grub_printf("tip1: <NULL>\n");
                
                tip = vtoy_json_get_string_ex(pNode->pstChild, "tip2");
                if (tip)
                    grub_printf("tip2: <%s>\n", tip);
                else
                    grub_printf("tip2: <NULL>\n");
            }
        }
        else
        {
            grub_printf("image: <%s> [ INVALID ]\n", path);
        }
    }
    return 0;
}
static int ventoy_plugin_menutip_entry(VTOY_JSON *json, const char *isodisk)
{
    int type;
    const char *path = NULL;
    const char *tip = NULL;
    VTOY_JSON *pNode = NULL;
    menu_tip *node = NULL;
    menu_tip *next = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_OBJECT)
    {
        debug("Not object %d\n", json->enDataType);
        return 0;
    }
    pNode = vtoy_json_find_item(json->pstChild, JSON_TYPE_ARRAY, "tips");
    if (pNode == NULL)
    {
        debug("Not tips found\n");
        return 0;
    }
    if (g_menu_tip_head)
    {
        for (node = g_menu_tip_head; node; node = next)
        {
            next = node->next;
            grub_free(node);
        }
        g_menu_tip_head = NULL;
    }
    tip = vtoy_json_get_string_ex(json->pstChild, "left");
    if (tip)
    {
        grub_env_set("VTOY_TIP_LEFT", tip);
    }
    
    tip = vtoy_json_get_string_ex(json->pstChild, "top");
    if (tip)
    {
        grub_env_set("VTOY_TIP_TOP", tip);
    }
    
    tip = vtoy_json_get_string_ex(json->pstChild, "color");
    if (tip)
    {
        grub_env_set("VTOY_TIP_COLOR", tip);
    }
    for (pNode = pNode->pstChild; pNode; pNode = pNode->pstNext)
    {
        type = vtoy_tip_image_file;
        path = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (!path)
        {
            path = vtoy_json_get_string_ex(pNode->pstChild, "dir");
            type = vtoy_tip_directory;
        }
        
        if (path && path[0] == '/')
        {
            node = grub_zalloc(sizeof(menu_tip));
            if (node)
            {
                node->type = type;
                node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", path);
                tip = vtoy_json_get_string_ex(pNode->pstChild, "tip");
                if (tip)
                {
                    grub_snprintf(node->tip1, 1000, "%s", tip);
                }
                else
                {
                    tip = vtoy_json_get_string_ex(pNode->pstChild, "tip1");
                    if (tip)
                        grub_snprintf(node->tip1, 1000, "%s", tip);
                    tip = vtoy_json_get_string_ex(pNode->pstChild, "tip2");
                    if (tip)
                        grub_snprintf(node->tip2, 1000, "%s", tip);
                }
                if (g_menu_tip_head)
                {
                    node->next = g_menu_tip_head;
                }
                
                g_menu_tip_head = node;
            }
        }
    }
    return 0;
}
static int ventoy_plugin_injection_check(VTOY_JSON *json, const char *isodisk)
{
    int type = 0;
    const char *path = NULL;
    const char *archive = NULL;
    VTOY_JSON *pNode = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array %d\n", json->enDataType);
        return 0;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        type = injection_type_file;
        path = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (!path)
        {
            type = injection_type_parent;
            path = vtoy_json_get_string_ex(pNode->pstChild, "parent");
            if (!path)
            {
                grub_printf("image/parent not found\n");
                continue;
            }
        }
        archive = vtoy_json_get_string_ex(pNode->pstChild, "archive");
        if (!archive)
        {
            grub_printf("archive not found\n");
            continue;
        }
        if (type == injection_type_file)
        {
            if (grub_strchr(path, '*'))
            {
                grub_printf("image: <%s> [*]\n", path);
            }
            else
            {
                grub_printf("image: <%s> [%s]\n", path, ventoy_check_file_exist("%s%s", isodisk, path) ? "OK" : "NOT EXIST");            
            }
        }
        else
        {
            grub_printf("parent: <%s> [%s]\n", path, 
                ventoy_is_dir_exist("%s%s", isodisk, path) ? "OK" : "NOT EXIST");
        }
        grub_printf("archive: <%s> [%s]\n\n", archive, ventoy_check_file_exist("%s%s", isodisk, archive) ? "OK" : "NOT EXIST");
    }
    return 0;
}
static int ventoy_plugin_injection_entry(VTOY_JSON *json, const char *isodisk)
{
    int type = 0;
    const char *path = NULL;
    const char *archive = NULL;
    VTOY_JSON *pNode = NULL;
    injection_config *node = NULL;
    injection_config *next = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    if (g_injection_head)
    {
        for (node = g_injection_head; node; node = next)
        {
            next = node->next;
            grub_free(node);
        }
        g_injection_head = NULL;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        type = injection_type_file;
        path = vtoy_json_get_string_ex(pNode->pstChild, "image");
        if (!path)
        {
            type = injection_type_parent;
            path = vtoy_json_get_string_ex(pNode->pstChild, "parent");
        }
        
        archive = vtoy_json_get_string_ex(pNode->pstChild, "archive");
        if (path && path[0] == '/' && archive && archive[0] == '/')
        {
            node = grub_zalloc(sizeof(injection_config));
            if (node)
            {
                node->type = type;
                node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", path);
                grub_snprintf(node->archive, sizeof(node->archive), "%s", archive);
                if (g_injection_head)
                {
                    node->next = g_injection_head;
                }
                
                g_injection_head = node;
            }
        }
    }
    return 0;
}
static int ventoy_plugin_menuclass_entry(VTOY_JSON *json, const char *isodisk)
{
    int type;
    int parent = 0;
    const char *key = NULL;
    const char *class = NULL;
    VTOY_JSON *pNode = NULL;
    menu_class *tail = NULL;
    menu_class *node = NULL;
    menu_class *next = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    if (g_menu_class_head)
    {
        for (node = g_menu_class_head; node; node = next)
        {
            next = node->next;
            grub_free(node);
        }
        g_menu_class_head = NULL;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        parent = 0;
        type = vtoy_class_image_file;
        key = vtoy_json_get_string_ex(pNode->pstChild, "key");
        if (!key)
        {
            key = vtoy_json_get_string_ex(pNode->pstChild, "parent");
            if (key)
            {
                parent = 1;
            }
            else
            {
                key = vtoy_json_get_string_ex(pNode->pstChild, "dir");
                type = vtoy_class_directory;
            }
        }
        
        class = vtoy_json_get_string_ex(pNode->pstChild, "class");
        if (key && class)
        {
            node = grub_zalloc(sizeof(menu_class));
            if (node)
            {
                node->type = type;
                node->parent = parent;
                node->patlen = grub_snprintf(node->pattern, sizeof(node->pattern), "%s", key);
                grub_snprintf(node->class, sizeof(node->class), "%s", class);
                if (g_menu_class_head)
                {
                    tail->next = node;
                }
                else
                {
                    g_menu_class_head = node;
                }
                tail = node;
            }
        }
    }
    return 0;
}
static int ventoy_plugin_menuclass_check(VTOY_JSON *json, const char *isodisk)
{
    const char *name = NULL;
    const char *key = NULL;
    const char *class = NULL;
    VTOY_JSON *pNode = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array %d\n", json->enDataType);
        return 1;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        name = "key";
        key = vtoy_json_get_string_ex(pNode->pstChild, "key");
        if (!key)
        {
            name = "parent";
            key = vtoy_json_get_string_ex(pNode->pstChild, "parent");
            if (!key)
            {
                name = "dir";       
                key = vtoy_json_get_string_ex(pNode->pstChild, "dir"); 
            }
        }
        
        class = vtoy_json_get_string_ex(pNode->pstChild, "class");
        if (key && class)
        {
            grub_printf("%s: <%s>\n", name,  key);
            grub_printf("class: <%s>\n\n", class);
        }
    }
    return 0;
}
static int ventoy_plugin_custom_boot_entry(VTOY_JSON *json, const char *isodisk)
{
    int type;
    int len;
    const char *key = NULL;
    const char *cfg = NULL;
    VTOY_JSON *pNode = NULL;
    custom_boot *tail = NULL;
    custom_boot *node = NULL;
    custom_boot *next = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    if (g_custom_boot_head)
    {
        for (node = g_custom_boot_head; node; node = next)
        {
            next = node->next;
            grub_free(node);
        }
        g_custom_boot_head = NULL;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        type = vtoy_custom_boot_image_file;
        key = vtoy_json_get_string_ex(pNode->pstChild, "file");
        if (!key)
        {
            key = vtoy_json_get_string_ex(pNode->pstChild, "dir");
            type = vtoy_custom_boot_directory;
        }
        
        cfg = vtoy_json_get_string_ex(pNode->pstChild, "vcfg");
        if (key && cfg)
        {
            node = grub_zalloc(sizeof(custom_boot));
            if (node)
            {
                node->type = type;
                node->pathlen = grub_snprintf(node->path, sizeof(node->path), "%s", key);
                len = (int)grub_snprintf(node->cfg, sizeof(node->cfg), "%s", cfg);
                if (len >= 5 && grub_strncmp(node->cfg + len - 5, ".vcfg", 5) == 0)
                {
                    if (g_custom_boot_head)
                    {
                        tail->next = node;
                    }
                    else
                    {
                        g_custom_boot_head = node;
                    }
                    tail = node;
                }
                else
                {
                    grub_free(node);
                }
            }
        }
    }
    return 0;
}
static int ventoy_plugin_custom_boot_check(VTOY_JSON *json, const char *isodisk)
{
    int type;
    int len;
    const char *key = NULL;
    const char *cfg = NULL;
    VTOY_JSON *pNode = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array %d\n", json->enDataType);
        return 1;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        type = vtoy_custom_boot_image_file;
        key = vtoy_json_get_string_ex(pNode->pstChild, "file");
        if (!key)
        {
            key = vtoy_json_get_string_ex(pNode->pstChild, "dir"); 
            type = vtoy_custom_boot_directory;
        }
        
        cfg = vtoy_json_get_string_ex(pNode->pstChild, "vcfg");
        len = (int)grub_strlen(cfg);
        if (key && cfg)
        {
            if (len < 5 || grub_strncmp(cfg + len - 5, ".vcfg", 5))
            {
                grub_printf("<%s> does not have \".vcfg\" suffix\n\n", cfg);
            }
            else
            {
                grub_printf("%s: <%s>\n", (type == vtoy_custom_boot_directory) ? "dir" : "file",  key);
                grub_printf("vcfg: <%s>\n\n", cfg);                
            }
        }
    }
    return 0;
}
static int ventoy_plugin_conf_replace_entry(VTOY_JSON *json, const char *isodisk)
{
    int img = 0;
    const char *isof = NULL;
    const char *orgf = NULL;
    const char *newf = NULL;
    VTOY_JSON *pNode = NULL;
    conf_replace *tail = NULL;
    conf_replace *node = NULL;
    conf_replace *next = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    if (g_conf_replace_head)
    {
        for (node = g_conf_replace_head; node; node = next)
        {
            next = node->next;
            grub_free(node);
        }
        g_conf_replace_head = NULL;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        isof = vtoy_json_get_string_ex(pNode->pstChild, "iso");
        orgf = vtoy_json_get_string_ex(pNode->pstChild, "org");
        newf = vtoy_json_get_string_ex(pNode->pstChild, "new");
        if (isof && orgf && newf && isof[0] == '/' && orgf[0] == '/' && newf[0] == '/')
        {
            node = grub_zalloc(sizeof(conf_replace));
            if (node)
            {
                if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "img", &img))
                {
                    node->img = img;
                }
                node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", isof);
                grub_snprintf(node->orgconf, sizeof(node->orgconf), "%s", orgf);
                grub_snprintf(node->newconf, sizeof(node->newconf), "%s", newf);
                if (g_conf_replace_head)
                {
                    tail->next = node;
                }
                else
                {
                    g_conf_replace_head = node;
                }
                tail = node;
            }
        }
    }
    return 0;
}
static int ventoy_plugin_conf_replace_check(VTOY_JSON *json, const char *isodisk)
{
    int img = 0;
    const char *isof = NULL;
    const char *orgf = NULL;
    const char *newf = NULL;
    VTOY_JSON *pNode = NULL;
    grub_file_t file = NULL;
    char cmd[256];
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array %d\n", json->enDataType);
        return 1;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        isof = vtoy_json_get_string_ex(pNode->pstChild, "iso");
        orgf = vtoy_json_get_string_ex(pNode->pstChild, "org");
        newf = vtoy_json_get_string_ex(pNode->pstChild, "new");
        if (isof && orgf && newf && isof[0] == '/' && orgf[0] == '/' && newf[0] == '/')
        {
            if (ventoy_check_file_exist("%s%s", isodisk, isof))
            {
                grub_printf("iso:<%s> [OK]\n", isof);
                
                grub_snprintf(cmd, sizeof(cmd), "loopback vtisocheck \"%s%s\"", isodisk, isof);
                grub_script_execute_sourcecode(cmd);
                file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "(vtisocheck)/%s", orgf);
                if (file)
                {
                    if (grub_strcmp(file->fs->name, "iso9660") == 0)
                    {
                        grub_printf("org:<%s> [OK]\n", orgf);
                    }
                    else
                    {
                        grub_printf("org:<%s> [Exist But NOT ISO9660]\n", orgf);
                    }
                    grub_file_close(file);
                }
                else
                {
                    grub_printf("org:<%s> [NOT Exist]\n", orgf);
                }
                
                grub_script_execute_sourcecode("loopback -d vtisocheck");
            }
            else if (grub_strchr(isof, '*'))
            {
                grub_printf("iso:<%s> [*]\n", isof);
                grub_printf("org:<%s>\n", orgf);
            }
            else
            {
                grub_printf("iso:<%s> [NOT Exist]\n", isof);
                grub_printf("org:<%s>\n", orgf);
            }
            file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s%s", isodisk, newf);
            if (file)
            {
                if (file->size > vtoy_max_replace_file_size)
                {
                    grub_printf("new:<%s> [Too Big %lu] \n", newf, (ulong)file->size);
                }
                else
                {
                    grub_printf("new1:<%s> [OK]\n", newf);                    
                }
                grub_file_close(file);
            }
            else
            {
                grub_printf("new:<%s> [NOT Exist]\n", newf);   
            }
            if (JSON_SUCCESS == vtoy_json_get_int(pNode->pstChild, "img", &img))
            {
                grub_printf("img:<%d>\n", img);           
            }
            
            grub_printf("\n");
        }
    }
    return 0;
}
static int ventoy_plugin_auto_memdisk_entry(VTOY_JSON *json, const char *isodisk)
{
    VTOY_JSON *pNode = NULL;
    auto_memdisk *node = NULL;
    auto_memdisk *next = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    if (g_auto_memdisk_head)
    {
        for (node = g_auto_memdisk_head; node; node = next)
        {
            next = node->next;
            grub_free(node);
        }
        g_auto_memdisk_head = NULL;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->enDataType == JSON_TYPE_STRING)
        {
            node = grub_zalloc(sizeof(auto_memdisk));
            if (node)
            {
                node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", pNode->unData.pcStrVal);
                if (g_auto_memdisk_head)
                {
                    node->next = g_auto_memdisk_head;
                }
                
                g_auto_memdisk_head = node;
            }
        }
    }
    return 0;
}
static int ventoy_plugin_auto_memdisk_check(VTOY_JSON *json, const char *isodisk)
{
    VTOY_JSON *pNode = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array %d\n", json->enDataType);
        return 1;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->enDataType == JSON_TYPE_STRING)
        {
            grub_printf("<%s> ", pNode->unData.pcStrVal);
            if (grub_strchr(pNode->unData.pcStrVal, '*'))
            {
                grub_printf(" [*]\n");
            }
            else if (ventoy_check_file_exist("%s%s", isodisk, pNode->unData.pcStrVal))
            {
                grub_printf(" [OK]\n");
            }
            else
            {
                grub_printf(" [NOT EXIST]\n");
            }
        }
    }
    return 0;
}
static int ventoy_plugin_image_list_entry(VTOY_JSON *json, const char *isodisk)
{
    VTOY_JSON *pNode = NULL;
    image_list *node = NULL;
    image_list *next = NULL;
    image_list *tail = NULL;
    (void)isodisk;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        debug("Not array %d\n", json->enDataType);
        return 0;
    }
    if (g_image_list_head)
    {
        for (node = g_image_list_head; node; node = next)
        {
            next = node->next;
            grub_free(node);
        }
        g_image_list_head = NULL;
    }
    if (grub_strncmp(json->pcName, "image_blacklist", 15) == 0)
    {
        g_plugin_image_list = VENTOY_IMG_BLACK_LIST;
    }
    else
    {
        g_plugin_image_list = VENTOY_IMG_WHITE_LIST;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->enDataType == JSON_TYPE_STRING)
        {
            node = grub_zalloc(sizeof(image_list));
            if (node)
            {
                node->pathlen = grub_snprintf(node->isopath, sizeof(node->isopath), "%s", pNode->unData.pcStrVal);
                if (g_image_list_head)
                {
                    tail->next = node;
                }
                else
                {
                    g_image_list_head = node;
                }
                tail = node;
            }
        }
    }
    return 0;
}
static int ventoy_plugin_image_list_check(VTOY_JSON *json, const char *isodisk)
{
    VTOY_JSON *pNode = NULL;
    if (json->enDataType != JSON_TYPE_ARRAY)
    {
        grub_printf("Not array %d\n", json->enDataType);
        return 1;
    }
    for (pNode = json->pstChild; pNode; pNode = pNode->pstNext)
    {
        if (pNode->enDataType == JSON_TYPE_STRING)
        {
            grub_printf("<%s> ", pNode->unData.pcStrVal);
            if (grub_strchr(pNode->unData.pcStrVal, '*'))
            {
                grub_printf(" [*]\n");
            }
            else if (ventoy_check_file_exist("%s%s", isodisk, pNode->unData.pcStrVal))
            {
                grub_printf(" [OK]\n");
            }
            else
            {
                grub_printf(" [NOT EXIST]\n");
            }
        }
    }
    return 0;
}
static plugin_entry g_plugin_entries[] = 
{
    { "control", ventoy_plugin_control_entry, ventoy_plugin_control_check, 0 },
    { "theme", ventoy_plugin_theme_entry, ventoy_plugin_theme_check, 0 },
    { "auto_install", ventoy_plugin_auto_install_entry, ventoy_plugin_auto_install_check, 0 },
    { "persistence", ventoy_plugin_persistence_entry, ventoy_plugin_persistence_check, 0 },
    { "menu_alias", ventoy_plugin_menualias_entry, ventoy_plugin_menualias_check, 0 },
    { "menu_tip", ventoy_plugin_menutip_entry, ventoy_plugin_menutip_check, 0 },
    { "menu_class", ventoy_plugin_menuclass_entry, ventoy_plugin_menuclass_check, 0 },
    { "injection", ventoy_plugin_injection_entry, ventoy_plugin_injection_check, 0 },
    { "auto_memdisk", ventoy_plugin_auto_memdisk_entry, ventoy_plugin_auto_memdisk_check, 0 },
    { "image_list", ventoy_plugin_image_list_entry, ventoy_plugin_image_list_check, 0 },
    { "image_blacklist", ventoy_plugin_image_list_entry, ventoy_plugin_image_list_check, 0 },
    { "conf_replace", ventoy_plugin_conf_replace_entry, ventoy_plugin_conf_replace_check, 0 },
    { "dud", ventoy_plugin_dud_entry, ventoy_plugin_dud_check, 0 },
    { "password", ventoy_plugin_pwd_entry, ventoy_plugin_pwd_check, 0 },
    { "custom_boot", ventoy_plugin_custom_boot_entry, ventoy_plugin_custom_boot_check, 0 },
};
static int ventoy_parse_plugin_config(VTOY_JSON *json, const char *isodisk)
{
    int i;
    char key[128];
    VTOY_JSON *cur = NULL;
    grub_snprintf(g_iso_disk_name, sizeof(g_iso_disk_name), "%s", isodisk);
    for (cur = json; cur; cur = cur->pstNext)
    {
        for (i = 0; i < (int)ARRAY_SIZE(g_plugin_entries); i++)
        {
            grub_snprintf(key, sizeof(key), "%s_%s", g_plugin_entries[i].key, g_arch_mode_suffix);
            if (g_plugin_entries[i].flag == 0 && grub_strcmp(key, cur->pcName) == 0)
            {
                debug("Plugin entry for %s\n", g_plugin_entries[i].key);
                g_plugin_entries[i].entryfunc(cur, isodisk);
                g_plugin_entries[i].flag = 1;
                break;
            }
        }
    }
    
    for (cur = json; cur; cur = cur->pstNext)
    {
        for (i = 0; i < (int)ARRAY_SIZE(g_plugin_entries); i++)
        {
            if (g_plugin_entries[i].flag == 0 && grub_strcmp(g_plugin_entries[i].key, cur->pcName) == 0)
            {
                debug("Plugin entry for %s\n", g_plugin_entries[i].key);
                g_plugin_entries[i].entryfunc(cur, isodisk);
                g_plugin_entries[i].flag = 1;
                break;
            }
        }
    }
    return 0;
}
grub_err_t ventoy_cmd_load_plugin(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int ret = 0;
    int offset = 0;
    char *buf = NULL;
    grub_uint8_t *code = NULL;
    grub_file_t file;
    VTOY_JSON *json = NULL;
    
    (void)ctxt;
    (void)argc;
    grub_env_set("VTOY_TIP_LEFT", "10%");
    grub_env_set("VTOY_TIP_TOP", "80%+5");
    grub_env_set("VTOY_TIP_COLOR", "blue");
    grub_env_set("VTOY_TIP_ALIGN", "left");
    file = ventoy_grub_file_open(GRUB_FILE_TYPE_LINUX_INITRD, "%s/ventoy/ventoy.json", args[0]);
    if (!file)
    {
        return GRUB_ERR_NONE;
    }
    debug("json configuration file size %d\n", (int)file->size);
    buf = grub_malloc(file->size + 1);
    if (!buf)
    {
        grub_file_close(file);
        return 1;
    }
    
    buf[file->size] = 0;
    grub_file_read(file, buf, file->size);
    grub_file_close(file);
    json = vtoy_json_create();
    if (!json)
    {
        return 1;
    }
    code = (grub_uint8_t *)buf;
    if (code[0] == 0xef && code[1] == 0xbb && code[2] == 0xbf)
    {
        offset = 3; /* Skip UTF-8 BOM */
    }
    else if ((code[0] == 0xff && code[1] == 0xfe) || (code[0] == 0xfe && code[1] == 0xff))
    {
        grub_env_set("VTOY_PLUGIN_SYNTAX_ERROR", "1");
        grub_env_export("VTOY_PLUGIN_SYNTAX_ERROR");
        grub_env_set("VTOY_PLUGIN_ENCODE_ERROR", "1");
        grub_env_export("VTOY_PLUGIN_ENCODE_ERROR");
        debug("Failed to parse json string %d\n", ret);
        grub_free(buf);
        return 1;
    }
    
    ret = vtoy_json_parse(json, buf + offset);
    if (ret)
    {
        grub_env_set("VTOY_PLUGIN_SYNTAX_ERROR", "1");
        grub_env_export("VTOY_PLUGIN_SYNTAX_ERROR");
        
        debug("Failed to parse json string %d\n", ret);
        grub_free(buf);
        return 1;
    }
    ventoy_parse_plugin_config(json->pstChild, args[0]);
    vtoy_json_destroy(json);
    grub_free(buf);
    if (g_boot_pwd.type)
    {        
        grub_printf("\n\n======= %s ======\n\n", grub_env_get("VTOY_TEXT_MENU_VER"));
        if (ventoy_check_password(&g_boot_pwd, 3))
        {
            grub_printf("\n!!! Password check failed, will exit after 5 seconds. !!!\n");
            grub_refresh();
            grub_sleep(5);
            grub_exit();
        }
    }
    if (g_menu_tip_head)
    {
        grub_env_set("VTOY_MENU_TIP_ENABLE", "1");
    }
    else
    {
        grub_env_unset("VTOY_MENU_TIP_ENABLE");
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
void ventoy_plugin_dump_injection(void)
{
    injection_config *node = NULL;
    for (node = g_injection_head; node; node = node->next)
    {
        grub_printf("\n%s:<%s>\n", (node->type == injection_type_file) ? "IMAGE" : "PARENT", node->isopath);
        grub_printf("ARCHIVE:<%s>\n", node->archive);
    }
    return;
}
void ventoy_plugin_dump_auto_install(void)
{
    int i;
    install_template *node = NULL;
    for (node = g_install_template_head; node; node = node->next)
    {
        grub_printf("\n%s:<%s> <%d>\n", 
            (node->type == auto_install_type_file) ? "IMAGE" : "PARENT",
            node->isopath, node->templatenum);
        for (i = 0; i < node->templatenum; i++)
        {
            grub_printf("SCRIPT %d:<%s>\n", i, node->templatepath[i].path);            
        }
    }
    return;
}
void ventoy_plugin_dump_persistence(void)
{
    int rc;
    int i = 0;
    persistence_config *node = NULL;
    ventoy_img_chunk_list chunk_list;
    for (node = g_persistence_head; node; node = node->next)
    {
        grub_printf("\nIMAGE:<%s> <%d>\n", node->isopath, node->backendnum);
        for (i = 0; i < node->backendnum; i++)
        {
            grub_printf("PERSIST %d:<%s>", i, node->backendpath[i].path);            
            rc = ventoy_plugin_get_persistent_chunklist(node->isopath, i, &chunk_list);
            if (rc == 0)
            {
                grub_printf(" [ SUCCESS ]\n");
                grub_free(chunk_list.chunk);
            }
            else
            {
                grub_printf(" [ FAILED ]\n");
            }
        }
    }
    return;
}
install_template * ventoy_plugin_find_install_template(const char *isopath)
{
    int len;
    install_template *node = NULL;
    if (!g_install_template_head)
    {
        return NULL;
    }
    len = (int)grub_strlen(isopath);
    for (node = g_install_template_head; node; node = node->next)
    {
        if (node->type == auto_install_type_file)
        {
            if (node->pathlen == len && ventoy_strcmp(node->isopath, isopath) == 0)
            {
                return node;
            }
        }
    }
    
    for (node = g_install_template_head; node; node = node->next)
    {
        if (node->type == auto_install_type_parent)
        {
            if (node->pathlen < len && ventoy_plugin_is_parent(node->isopath, node->pathlen, isopath))
            {
                return node;
            }
        }
    }
    return NULL;
}
char * ventoy_plugin_get_cur_install_template(const char *isopath, install_template **cur)
{
    install_template *node = NULL;
    if (cur)
    {
        *cur = NULL;
    }
    node = ventoy_plugin_find_install_template(isopath);
    if ((!node) || (!node->templatepath))
    {
        return NULL;
    }
    if (node->cursel < 0 || node->cursel >= node->templatenum)
    {
        return NULL;
    }
    if (cur)
    {
        *cur = node;
    }
    return node->templatepath[node->cursel].path;
}
persistence_config * ventoy_plugin_find_persistent(const char *isopath)
{
    int len;
    persistence_config *node = NULL;
    if (!g_persistence_head)
    {
        return NULL;
    }
    len = (int)grub_strlen(isopath);
    for (node = g_persistence_head; node; node = node->next)
    {
        if ((len == node->pathlen) && (ventoy_strcmp(node->isopath, isopath) == 0))
        {
            return node;
        }
    }
    return NULL;
}
int ventoy_plugin_get_persistent_chunklist(const char *isopath, int index, ventoy_img_chunk_list *chunk_list)
{
    int rc = 1;
    int len = 0;
    char *path = NULL;
    grub_uint64_t start = 0;
    grub_file_t file = NULL;
    persistence_config *node = NULL;
    node = ventoy_plugin_find_persistent(isopath);
    if ((!node) || (!node->backendpath))
    {
        return 1;
    }
    if (index < 0)
    {
        index = node->cursel;
    }
    if (index < 0 || index >= node->backendnum)
    {
        return 1;
    }
    path = node->backendpath[index].path;
    if (node->backendpath[index].vlnk_add == 0)
    {
        len = grub_strlen(path);
        if (len > 9 && grub_strncmp(path + len - 9, ".vlnk.dat", 9) == 0)
        {
            ventoy_add_vlnk_file(NULL, path);
            node->backendpath[index].vlnk_add = 1;
        }
    }
    
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s%s", g_iso_disk_name, path);
    if (!file)
    {
        debug("Failed to open file %s%s\n", g_iso_disk_name, path);
        goto end;
    }
    grub_memset(chunk_list, 0, sizeof(ventoy_img_chunk_list));
    chunk_list->chunk = grub_malloc(sizeof(ventoy_img_chunk) * DEFAULT_CHUNK_NUM);
    if (NULL == chunk_list->chunk)
    {
        goto end;
    }
    
    chunk_list->max_chunk = DEFAULT_CHUNK_NUM;
    chunk_list->cur_chunk = 0;
    start = file->device->disk->partition->start;
    ventoy_get_block_list(file, chunk_list, start);
    
    if (0 != ventoy_check_block_list(file, chunk_list, start))
    {
        grub_free(chunk_list->chunk);
        chunk_list->chunk = NULL;
        goto end;
    }
    rc = 0;
end:
    if (file)
        grub_file_close(file);
    return rc;
}
const char * ventoy_plugin_get_injection(const char *isopath)
{
    int len;
    injection_config *node = NULL;
    if (!g_injection_head)
    {
        return NULL;
    }
    len = (int)grub_strlen(isopath);
    for (node = g_injection_head; node; node = node->next)
    {
        if (node->type == injection_type_file)
        {
            if (node->pathlen == len && ventoy_strcmp(node->isopath, isopath) == 0)
            {
                return node->archive;
            }
        }
    }
    
    for (node = g_injection_head; node; node = node->next)
    {
        if (node->type == injection_type_parent)
        {
            if (node->pathlen < len && ventoy_plugin_is_parent(node->isopath, node->pathlen, isopath))
            {
                return node->archive;
            }
        }
    }
    return NULL;
}
const char * ventoy_plugin_get_menu_alias(int type, const char *isopath)
{
    int len;
    menu_alias *node = NULL;
    if (!g_menu_alias_head)
    {
        return NULL;
    }
    len = (int)grub_strlen(isopath);
    for (node = g_menu_alias_head; node; node = node->next)
    {
        if (node->type == type && node->pathlen && 
            node->pathlen == len && ventoy_strcmp(node->isopath, isopath) == 0)
        {
            return node->alias;
        }
    }
    return NULL;
}
const menu_tip * ventoy_plugin_get_menu_tip(int type, const char *isopath)
{
    int len;
    menu_tip *node = NULL;
    if (!g_menu_tip_head)
    {
        return NULL;
    }
    len = (int)grub_strlen(isopath);
    for (node = g_menu_tip_head; node; node = node->next)
    {
        if (node->type == type && node->pathlen && 
            node->pathlen == len && ventoy_strcmp(node->isopath, isopath) == 0)
        {
            return node;
        }
    }
    return NULL;
}
const char * ventoy_plugin_get_menu_class(int type, const char *name, const char *path)
{
    int namelen;
    int pathlen;
    menu_class *node = NULL;
    if (!g_menu_class_head)
    {
        return NULL;
    }
    
    namelen = (int)grub_strlen(name); 
    pathlen = (int)grub_strlen(path); 
    
    if (vtoy_class_image_file == type)
    {
        for (node = g_menu_class_head; node; node = node->next)
        {
            if (node->type != type)
            {
                continue;
            }
            if (node->parent == 0)
            {
                if ((node->patlen < namelen) && grub_strstr(name, node->pattern))
                {
                    return node->class;
                }
            }
        }
        
        for (node = g_menu_class_head; node; node = node->next)
        {
            if (node->type != type)
            {
                continue;
            }
            if (node->parent)
            {
                if ((node->patlen < pathlen) && ventoy_plugin_is_parent(node->pattern, node->patlen, path))
                {
                    return node->class;
                }
            }
        }
    }
    else
    {
        for (node = g_menu_class_head; node; node = node->next)
        {
            if (node->type == type && node->patlen == namelen && grub_strncmp(name, node->pattern, namelen) == 0)
            {
                return node->class;
            }
        }
    }
    return NULL;
}
int ventoy_plugin_add_custom_boot(const char *vcfgpath)
{
    int len;
    custom_boot *node = NULL;
    
    node = grub_zalloc(sizeof(custom_boot));
    if (node)
    {
        node->type = vtoy_custom_boot_image_file;
        node->pathlen = grub_snprintf(node->path, sizeof(node->path), "%s", vcfgpath);
        grub_snprintf(node->cfg, sizeof(node->cfg), "%s", vcfgpath);
        /* .vcfg */
        len = node->pathlen - 5;
        node->path[len] = 0;
        node->pathlen = len;
        if (g_custom_boot_head)
        {
            node->next = g_custom_boot_head;
        }
        g_custom_boot_head = node;
    }
    
    return 0;
}
const char * ventoy_plugin_get_custom_boot(const char *isopath)
{
    int i;
    int len;
    custom_boot *node = NULL;
    if (!g_custom_boot_head)
    {
        return NULL;
    }
    len = (int)grub_strlen(isopath);
    
    for (node = g_custom_boot_head; node; node = node->next)
    {
        if (node->type == vtoy_custom_boot_image_file)
        {
            if (node->pathlen == len && grub_strncmp(isopath, node->path, len) == 0)
            {
                return node->cfg;                
            }
        }
        else
        {
            if (node->pathlen < len && isopath[node->pathlen] == '/' && 
                grub_strncmp(isopath, node->path, node->pathlen) == 0)
            {
                for (i = node->pathlen + 1; i < len; i++)
                {
                    if (isopath[i] == '/')
                    {
                        break;
                    }
                }
                if (i >= len)
                {
                    return node->cfg;                
                }
            }
        }
    }
    return NULL;
}
grub_err_t ventoy_cmd_dump_custom_boot(grub_extcmd_context_t ctxt, int argc, char **args)
{
    custom_boot *node = NULL;
    (void)argc;
    (void)ctxt;
    (void)args;
    for (node = g_custom_boot_head; node; node = node->next)
    {
        grub_printf("[%s] <%s>:<%s>\n", (node->type == vtoy_custom_boot_directory) ? "dir" : "file", 
            node->path, node->cfg);
    }
    return 0;
}
int ventoy_plugin_check_memdisk(const char *isopath)
{
    int len;
    auto_memdisk *node = NULL;
    if (!g_auto_memdisk_head)
    {
        return 0;
    }
    len = (int)grub_strlen(isopath);    
    for (node = g_auto_memdisk_head; node; node = node->next)
    {
        if (node->pathlen == len && ventoy_strncmp(node->isopath, isopath, len) == 0)
        {
            return 1;
        }
    }
    return 0;
}
int ventoy_plugin_get_image_list_index(int type, const char *name)
{
    int len;
    int index = 1;
    image_list *node = NULL;
    if (!g_image_list_head)
    {
        return 0;
    }
    len = (int)grub_strlen(name);    
    
    for (node = g_image_list_head; node; node = node->next, index++)
    {
        if (vtoy_class_directory == type)
        {
            if (len < node->pathlen && ventoy_strncmp(node->isopath, name, len) == 0)
            {
                return index;
            }
        }
        else
        {
            if (len == node->pathlen && ventoy_strncmp(node->isopath, name, len) == 0)
            {
                return index;
            }
        }
    }
    return 0;
}
int ventoy_plugin_find_conf_replace(const char *iso, conf_replace *nodes[VTOY_MAX_CONF_REPLACE])
{
    int n = 0;
    int len;
    conf_replace *node;
    if (!g_conf_replace_head)
    {
        return 0;
    }
    len = (int)grub_strlen(iso);
    
    for (node = g_conf_replace_head; node; node = node->next)
    {
        if (node->pathlen == len && ventoy_strncmp(node->isopath, iso, len) == 0)
        {
            nodes[n++] = node;
            if (n >= VTOY_MAX_CONF_REPLACE)
            {
                return n;
            }
        }
    }
    
    return n;
}
dud * ventoy_plugin_find_dud(const char *iso)
{
    int len;
    dud *node;
    if (!g_dud_head)
    {
        return NULL;
    }
    len = (int)grub_strlen(iso);
    for (node = g_dud_head; node; node = node->next)
    {
        if (node->pathlen == len && ventoy_strncmp(node->isopath, iso, len) == 0)
        {
            return node;
        }
    }
    
    return NULL;
}
int ventoy_plugin_load_dud(dud *node, const char *isopart)
{
    int i;
    char *buf;
    grub_file_t file;
    for (i = 0; i < node->dudnum; i++)
    {
        if (node->files[i].size > 0)
        {
            debug("file %d has been loaded\n", i);
            continue;
        }
    
        file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s%s", isopart, node->dudpath[i].path);
        if (file)
        {
            buf = grub_malloc(file->size);
            if (buf)
            {
                grub_file_read(file, buf, file->size);            
                node->files[i].size = (int)file->size;
                node->files[i].buf = buf;                
            }
            grub_file_close(file);
        }
    }
    return 0;
}
static const vtoy_password * ventoy_plugin_get_password(const char *isopath)
{
    int i;
    int len;
    const char *pos = NULL;
    menu_password *node = NULL;
    if (!isopath)
    {
        return NULL;
    }
    if (g_pwd_head)
    {
        len = (int)grub_strlen(isopath);    
        for (node = g_pwd_head; node; node = node->next)
        {
            if (node->type == vtoy_menu_pwd_file)
            {
                if (node->pathlen == len && ventoy_strncmp(node->isopath, isopath, len) == 0)
                {
                    return &(node->password);
                }
            }
        }
        for (node = g_pwd_head; node; node = node->next)
        {   
            if (node->type == vtoy_menu_pwd_parent)
            {
                if (node->pathlen < len && ventoy_plugin_is_parent(node->isopath, node->pathlen, isopath))
                {
                    return &(node->password);
                }
            }
        }
    }
    while (*isopath)
    {
        if (*isopath == '.')
        {
            pos = isopath;
        }
        isopath++;
    }
    if (pos)
    {
        for (i = 0; i < (int)ARRAY_SIZE(g_menu_prefix); i++)
        {
            if (g_file_type_pwd[i].type && 0 == grub_strcasecmp(pos + 1, g_menu_prefix[i]))
            {
                return g_file_type_pwd + i;
            }
        }
    }
    return NULL;
}
grub_err_t ventoy_cmd_check_password(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int ret;
    const vtoy_password *pwd = NULL;
    
    (void)ctxt;
    (void)argc;
    pwd = ventoy_plugin_get_password(args[0]);
    if (pwd)
    {
        if (0 == ventoy_check_password(pwd, 1))
        {
            ret = 1;
        }
        else
        {
            ret = 0;
        }
    }
    else
    {
        ret = 1;
    }
    grub_errno = 0;
    return ret;
}
grub_err_t ventoy_cmd_plugin_check_json(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int i = 0;
    int ret = 0;
    char *buf = NULL;
    char key[128];
    grub_file_t file;
    VTOY_JSON *node = NULL;
    VTOY_JSON *json = NULL;
    
    (void)ctxt;
    if (argc != 3)
    {
        return 0;
    }
    file = ventoy_grub_file_open(GRUB_FILE_TYPE_LINUX_INITRD, "%s/ventoy/ventoy.json", args[0]);
    if (!file)
    {
        grub_printf("Plugin json file /ventoy/ventoy.json does NOT exist.\n");
        grub_printf("Attention: directory name and filename are both case-sensitive.\n");
        goto end;
    }
    buf = grub_malloc(file->size + 1);
    if (!buf)
    {
        grub_printf("Failed to malloc memory %lu.\n", (ulong)(file->size + 1));
        goto end;
    }
    
    buf[file->size] = 0;
    grub_file_read(file, buf, file->size);
    json = vtoy_json_create();
    if (!json)
    {
        grub_printf("Failed to create json\n");
        goto end;
    }
    ret = vtoy_json_parse(json, buf);
    if (ret)
    {
        grub_printf("Syntax error detected in ventoy.json, please check it.\n");
        goto end;
    }
    grub_snprintf(key, sizeof(key), "%s_%s", args[1], g_arch_mode_suffix);
    for (node = json->pstChild; node; node = node->pstNext)
    {
        if (grub_strcmp(node->pcName, key) == 0)
        {
            break;
        }
    }
    if (!node)
    {
        for (node = json->pstChild; node; node = node->pstNext)
        {
            if (grub_strcmp(node->pcName, args[1]) == 0)
            {
                break;
            }
        }
        if (!node)
        {
            grub_printf("%s is NOT found in ventoy.json\n", args[1]);
            goto end;            
        }
    }
    for (i = 0; i < (int)ARRAY_SIZE(g_plugin_entries); i++)
    {
        if (grub_strcmp(g_plugin_entries[i].key, args[1]) == 0)
        {
            if (g_plugin_entries[i].checkfunc)
            {
                ret = g_plugin_entries[i].checkfunc(node, args[2]);                
            }
            break;
        }
    }
    
end:
    check_free(file, grub_file_close);
    check_free(json, vtoy_json_destroy);
    grub_check_free(buf);
    return 0;
}
grub_err_t ventoy_cmd_select_theme_cfg(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int pos = 0;
    int bufsize = 0;
    char *name = NULL;
    char *buf = NULL;
    theme_list *node = NULL;
    (void)argc;
    (void)args;
    (void)ctxt;
    if (g_theme_single_file[0])
    {
        return 0;
    }
    if (g_theme_num < 2)
    {
        return 0;
    }
    bufsize = (g_theme_num + 1) * 1024;
    buf = grub_malloc(bufsize);
    if (!buf)
    {
        return 0;
    }
    
    for (node = g_theme_head; node; node = node->next)
    {
        name = grub_strstr(node->theme.path, ")/");
        if (name)
        {
            name++;
        }
        else
        {
            name = node->theme.path;
        }
    
        pos += grub_snprintf(buf + pos, bufsize - pos, 
            "menuentry \"%s\" --class=debug_theme_item --class=debug_theme_select --class=F5tool {\n"
                "vt_set_theme_path \"%s\"\n"
            "}\n",
            name, node->theme.path);
    }
    pos += grub_snprintf(buf + pos, bufsize - pos, 
            "menuentry \"$VTLANG_RETURN_PREVIOUS\" --class=vtoyret VTOY_RET {\n"
                "echo 'Return ...'\n"
            "}\n");
    grub_script_execute_sourcecode(buf);
    grub_free(buf);
    
    return 0;
}
extern char g_ventoy_theme_path[256];
grub_err_t ventoy_cmd_set_theme(grub_extcmd_context_t ctxt, int argc, char **args)
{
    grub_uint32_t i = 0;
    grub_uint32_t mod = 0;
    grub_uint32_t theme_num = 0;
    theme_list *node = g_theme_head;
    struct grub_datetime datetime;
    struct grub_video_mode_info info;
    char buf[64];
    char **pThemePath = NULL;
    (void)argc;
    (void)args;
    (void)ctxt;
    if (g_theme_single_file[0])
    {
        debug("single theme %s\n", g_theme_single_file);
        grub_env_set("theme", g_theme_single_file);
        goto end;
    }
    debug("g_theme_num = %d\n", g_theme_num);
    
    if (g_theme_num == 0)
    {
        goto end;
    }
    
    if (g_theme_id > 0 && g_theme_id <= g_theme_num)
    {
        for (i = 0; i < (grub_uint32_t)(g_theme_id - 1) && node; i++)
        {
            node = node->next;
        }
        grub_env_set("theme", node->theme.path);
        goto end;
    }
    pThemePath = (char **)grub_zalloc(sizeof(char *) * g_theme_num);
    if (!pThemePath)
    {
        goto end;
    }
    if (g_theme_res_fit)
    {
        if (grub_video_get_info(&info) == GRUB_ERR_NONE)
        {
            debug("get video info success %ux%u\n", info.width, info.height);
            grub_snprintf(buf, sizeof(buf), "%ux%u", info.width, info.height);
            for (node = g_theme_head; node; node = node->next)
            {
                if (grub_strstr(node->theme.path, buf))
                {
                    pThemePath[theme_num++] = node->theme.path;
                }
            }
        }
    }
    if (theme_num == 0)
    {
        for (node = g_theme_head; node; node = node->next)
        {
            pThemePath[theme_num++] = node->theme.path;
        }
    }
    if (theme_num == 1)
    {
        mod = 0;
        debug("Only 1 theme match, no need to random.\n");
    }
    else
    {
        grub_memset(&datetime, 0, sizeof(datetime));
        grub_get_datetime(&datetime);
        if (g_theme_random == vtoy_theme_random_boot_second)
        {
            grub_divmod32((grub_uint32_t)datetime.second, theme_num, &mod);
        }
        else if (g_theme_random == vtoy_theme_random_boot_day)
        {
            grub_divmod32((grub_uint32_t)datetime.day, theme_num, &mod);
        }
        else if (g_theme_random == vtoy_theme_random_boot_month)
        {
            grub_divmod32((grub_uint32_t)datetime.month, theme_num, &mod);
        }
        debug("%04d/%02d/%02d %02d:%02d:%02d theme_num:%d mod:%d\n",
              datetime.year, datetime.month, datetime.day,
              datetime.hour, datetime.minute, datetime.second,
              theme_num, mod);
    }
    if (argc > 0 && grub_strcmp(args[0], "switch") == 0)
    {
        grub_snprintf(g_ventoy_theme_path, sizeof(g_ventoy_theme_path), "%s", pThemePath[mod]);        
    }
    else
    {        
        debug("random theme %s\n", pThemePath[mod]);
        grub_env_set("theme", pThemePath[mod]);
    }
    g_ventoy_menu_refresh = 1;
end:
    grub_check_free(pThemePath);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_set_theme_path(grub_extcmd_context_t ctxt, int argc, char **args)
{
    (void)argc;
    (void)ctxt;
    if (argc == 0)
    {
        g_ventoy_theme_path[0] = 0;
    }
    else
    {
        grub_snprintf(g_ventoy_theme_path, sizeof(g_ventoy_theme_path), "%s", args[0]);
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
const char *ventoy_get_vmenu_title(const char *vMenu)
{
    return vtoy_json_get_string_ex(g_menu_lang_json->pstChild, vMenu);
}
int ventoy_plugin_load_menu_lang(int init, const char *lang)
{
    int ret = 1;
    grub_file_t file = NULL;
    char *buf = NULL;
    if (grub_strcmp(lang, g_cur_menu_language) == 0)
    {
        debug("Same menu lang %s\n", lang);
        return 0;
    }
    grub_snprintf(g_cur_menu_language, sizeof(g_cur_menu_language), "%s", lang);
    debug("Load menu lang %s\n", g_cur_menu_language);
    if (g_menu_lang_json)
    {
        vtoy_json_destroy(g_menu_lang_json);
        g_menu_lang_json = NULL;
    }
    g_menu_lang_json = vtoy_json_create();
    if (!g_menu_lang_json)
    {
        goto end;
    }
    file = ventoy_grub_file_open(GRUB_FILE_TYPE_LINUX_INITRD, "(vt_menu_tarfs)/menu/%s.json", lang);
    if (!file)
    {
        goto end;
    }
    buf = grub_malloc(file->size + 1);
    if (!buf)
    {
        grub_printf("Failed to malloc memory %lu.\n", (ulong)(file->size + 1));
        goto end;
    }
    buf[file->size] = 0;
    grub_file_read(file, buf, file->size);
    vtoy_json_parse(g_menu_lang_json, buf);
    if (g_default_menu_mode == 0)
    {
        grub_snprintf(g_ventoy_hotkey_tip, sizeof(g_ventoy_hotkey_tip), "%s", ventoy_get_vmenu_title("VTLANG_STR_HOTKEY_TREE"));
    }
    else
    {
        grub_snprintf(g_ventoy_hotkey_tip, sizeof(g_ventoy_hotkey_tip), "%s", ventoy_get_vmenu_title("VTLANG_STR_HOTKEY_LIST"));
    }
    if (init == 0)
    {
        ventoy_menu_push_key(GRUB_TERM_ESC);
        ventoy_menu_push_key(GRUB_TERM_ESC);
        g_ventoy_menu_refresh = 1;        
    }
    ret = 0;
end:
    check_free(file, grub_file_close);
    grub_check_free(buf);
    return ret;
}
grub_err_t ventoy_cmd_cur_menu_lang(grub_extcmd_context_t ctxt, int argc, char **args)
{
    (void)ctxt;
    (void)argc;
    if (argc > 0)
    {
        grub_env_set(args[0], g_cur_menu_language);
    }
    else
    {
        grub_printf("%s\n", g_cur_menu_language);
        grub_printf("%s\n", g_ventoy_hotkey_tip);
        grub_refresh();        
    }
    VENTOY_CMD_RETURN(0);
}
grub_err_t ventoy_cmd_push_menulang(grub_extcmd_context_t ctxt, int argc, char **args)
{
    (void)argc;
    (void)ctxt;
    if (g_push_menu_language[0] == 0)
    {
        grub_memcpy(g_push_menu_language, g_cur_menu_language, sizeof(g_push_menu_language));
        ventoy_plugin_load_menu_lang(0, args[0]);
    }
    VENTOY_CMD_RETURN(0);
}
grub_err_t ventoy_cmd_pop_menulang(grub_extcmd_context_t ctxt, int argc, char **args)
{
    (void)argc;
    (void)ctxt;
    (void)args;
    if (g_push_menu_language[0])
    {
        ventoy_plugin_load_menu_lang(0, g_push_menu_language);
        g_push_menu_language[0] = 0;
    }
    VENTOY_CMD_RETURN(0);
}
 | 97,634 | 
	C | 
	.c | 3,162 | 20.826376 | 137 | 0.487471 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 617 | 
	ventoy_json.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/ventoy_json.c | 
	/******************************************************************************
 * ventoy_json.c 
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <grub/types.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/disk.h>
#include <grub/device.h>
#include <grub/term.h>
#include <grub/partition.h>
#include <grub/file.h>
#include <grub/normal.h>
#include <grub/extcmd.h>
#include <grub/datetime.h>
#include <grub/i18n.h>
#include <grub/net.h>
#include <grub/time.h>
#include <grub/ventoy.h>
#include "ventoy_def.h"
GRUB_MOD_LICENSE ("GPLv3+");
static void json_debug(const char *fmt, ...)
{
    va_list args;
    if (g_ventoy_debug == 0)
    {
        return;
    }
    va_start (args, fmt);
    grub_vprintf (fmt, args);
    va_end (args);
    grub_printf("\n");
}
static void vtoy_json_free(VTOY_JSON *pstJsonHead)
{
    VTOY_JSON *pstNext = NULL;
    while (NULL != pstJsonHead)
    {
        pstNext = pstJsonHead->pstNext;
        if ((pstJsonHead->enDataType < JSON_TYPE_BUTT) && (NULL != pstJsonHead->pstChild))
        {
            vtoy_json_free(pstJsonHead->pstChild);
        }
        grub_free(pstJsonHead);
        pstJsonHead = pstNext;
    }
    return;
}
static char *vtoy_json_skip(const char *pcData)
{
    while ((NULL != pcData) && ('\0' != *pcData) && (*pcData <= 32))
    {
        pcData++;
    }
    return (char *)pcData;
}
VTOY_JSON *vtoy_json_find_item
(
    VTOY_JSON *pstJson,
    JSON_TYPE  enDataType,
    const char *szKey
)
{
    while (NULL != pstJson)
    {
        if ((enDataType == pstJson->enDataType) && 
            (0 == grub_strcmp(szKey, pstJson->pcName)))
        {
            return pstJson;
        }
        pstJson = pstJson->pstNext;
    }
    
    return NULL;
}
static int vtoy_json_parse_number
(
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    unsigned long Value;
    Value = grub_strtoul(pcData, (char **)ppcEnd, 10);
    if (*ppcEnd == pcData)
    {
        json_debug("Failed to parse json number %s.", pcData);
        return JSON_FAILED;
    }
    pstJson->enDataType = JSON_TYPE_NUMBER;
    pstJson->unData.lValue = Value;
    
    return JSON_SUCCESS;
}
static int vtoy_json_parse_string
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    grub_uint32_t uiLen = 0;
    const char *pcPos = NULL;
    const char *pcTmp = pcData + 1;
    
    *ppcEnd = pcData;
    if ('\"' != *pcData)
    {
        return JSON_FAILED;
    }
    pcPos = grub_strchr(pcTmp, '\"');
    if ((NULL == pcPos) || (pcPos < pcTmp))
    {
        json_debug("Invalid string %s.", pcData);
        return JSON_FAILED;
    }
    if (*(pcPos - 1) == '\\')
    {
        for (pcPos++; *pcPos; pcPos++)
        {
            if (*pcPos == '"' && *(pcPos - 1) != '\\')
            {
                break;
            }
        }
        
        if (*pcPos == 0 || pcPos < pcTmp)
        {
            json_debug("Invalid quotes string %s.", pcData);
            return JSON_FAILED;
        }
    }
    *ppcEnd = pcPos + 1;
    uiLen = (grub_uint32_t)(unsigned long)(pcPos - pcTmp);    
    
    pstJson->enDataType = JSON_TYPE_STRING;
    pstJson->unData.pcStrVal = pcNewStart + (pcTmp - pcRawStart);
    pstJson->unData.pcStrVal[uiLen] = '\0';
    
    return JSON_SUCCESS;
}
static int vtoy_json_parse_array
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    int Ret = JSON_SUCCESS;
    VTOY_JSON *pstJsonChild = NULL;
    VTOY_JSON *pstJsonItem = NULL;
    const char *pcTmp = pcData + 1;
    *ppcEnd = pcData;
    pstJson->enDataType = JSON_TYPE_ARRAY;
    if ('[' != *pcData)
    {
        return JSON_FAILED;
    }
    pcTmp = vtoy_json_skip(pcTmp);
    if (']' == *pcTmp)
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    JSON_NEW_ITEM(pstJson->pstChild, JSON_FAILED);
    Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJson->pstChild, pcTmp, ppcEnd);
    if (JSON_SUCCESS != Ret)
    {
        json_debug("Failed to parse array child.");
        return JSON_FAILED;
    }
    pstJsonChild = pstJson->pstChild;
    pcTmp = vtoy_json_skip(*ppcEnd);
    while ((NULL != pcTmp) && (',' == *pcTmp))
    {
        JSON_NEW_ITEM(pstJsonItem, JSON_FAILED);
        pstJsonChild->pstNext = pstJsonItem;
        pstJsonItem->pstPrev = pstJsonChild;
        pstJsonChild = pstJsonItem;
        Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
        if (JSON_SUCCESS != Ret)
        {
            json_debug("Failed to parse array child.");
            return JSON_FAILED;
        }
        pcTmp = vtoy_json_skip(*ppcEnd);
    }
    if ((NULL != pcTmp) && (']' == *pcTmp))
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    else
    {
        *ppcEnd = pcTmp;
        return JSON_FAILED;
    }
}
static int vtoy_json_parse_object
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    int Ret = JSON_SUCCESS;
    VTOY_JSON *pstJsonChild = NULL;
    VTOY_JSON *pstJsonItem = NULL;
    const char *pcTmp = pcData + 1;
    *ppcEnd = pcData;
    pstJson->enDataType = JSON_TYPE_OBJECT;
    if ('{' != *pcData)
    {
        return JSON_FAILED;
    }
    pcTmp = vtoy_json_skip(pcTmp);
    if ('}' == *pcTmp)
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    JSON_NEW_ITEM(pstJson->pstChild, JSON_FAILED);
    Ret = vtoy_json_parse_string(pcNewStart, pcRawStart, pstJson->pstChild, pcTmp, ppcEnd);
    if (JSON_SUCCESS != Ret)
    {
        json_debug("Failed to parse array child.");
        return JSON_FAILED;
    }
    pstJsonChild = pstJson->pstChild;
    pstJsonChild->pcName = pstJsonChild->unData.pcStrVal;
    pstJsonChild->unData.pcStrVal = NULL;
    pcTmp = vtoy_json_skip(*ppcEnd);
    if ((NULL == pcTmp) || (':' != *pcTmp))
    {
        *ppcEnd = pcTmp;
        return JSON_FAILED;
    }
    Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
    if (JSON_SUCCESS != Ret)
    {
        json_debug("Failed to parse array child.");
        return JSON_FAILED;
    }
    pcTmp = vtoy_json_skip(*ppcEnd);
    while ((NULL != pcTmp) && (',' == *pcTmp))
    {
        JSON_NEW_ITEM(pstJsonItem, JSON_FAILED);
        pstJsonChild->pstNext = pstJsonItem;
        pstJsonItem->pstPrev = pstJsonChild;
        pstJsonChild = pstJsonItem;
        Ret = vtoy_json_parse_string(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
        if (JSON_SUCCESS != Ret)
        {
            json_debug("Failed to parse array child.");
            return JSON_FAILED;
        }
        pcTmp = vtoy_json_skip(*ppcEnd);
        pstJsonChild->pcName = pstJsonChild->unData.pcStrVal;
        pstJsonChild->unData.pcStrVal = NULL;
        if ((NULL == pcTmp) || (':' != *pcTmp))
        {
            *ppcEnd = pcTmp;
            return JSON_FAILED;
        }
        Ret = vtoy_json_parse_value(pcNewStart, pcRawStart, pstJsonChild, vtoy_json_skip(pcTmp + 1), ppcEnd);
        if (JSON_SUCCESS != Ret)
        {
            json_debug("Failed to parse array child.");
            return JSON_FAILED;
        }
        pcTmp = vtoy_json_skip(*ppcEnd);
    }
    if ((NULL != pcTmp) && ('}' == *pcTmp))
    {
        *ppcEnd = pcTmp + 1;
        return JSON_SUCCESS;
    }
    else
    {
        *ppcEnd = pcTmp;
        return JSON_FAILED;
    }
}
int vtoy_json_parse_value
(
    char *pcNewStart,
    char *pcRawStart,
    VTOY_JSON *pstJson, 
    const char *pcData,
    const char **ppcEnd
)
{
    pcData = vtoy_json_skip(pcData);
    
    switch (*pcData)
    {
        case 'n':
        {
            if (0 == grub_strncmp(pcData, "null", 4))
            {
                pstJson->enDataType = JSON_TYPE_NULL;
                *ppcEnd = pcData + 4;
                return JSON_SUCCESS;
            }
            break;
        }
        case 'f':
        {
            if (0 == grub_strncmp(pcData, "false", 5))
            {
                pstJson->enDataType = JSON_TYPE_BOOL;
                pstJson->unData.lValue = 0;
                *ppcEnd = pcData + 5;
                return JSON_SUCCESS;
            }
            break;
        }
        case 't':
        {
            if (0 == grub_strncmp(pcData, "true", 4))
            {
                pstJson->enDataType = JSON_TYPE_BOOL;
                pstJson->unData.lValue = 1;
                *ppcEnd = pcData + 4;
                return JSON_SUCCESS;
            }
            break;
        }
        case '\"':
        {
            return vtoy_json_parse_string(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
        }
        case '[':
        {
            return vtoy_json_parse_array(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
        }
        case '{':
        {
            return vtoy_json_parse_object(pcNewStart, pcRawStart, pstJson, pcData, ppcEnd);
        }
        case '-':
        {
            return vtoy_json_parse_number(pstJson, pcData, ppcEnd);
        }
        default :
        {
            if (*pcData >= '0' && *pcData <= '9')
            {
                return vtoy_json_parse_number(pstJson, pcData, ppcEnd);
            }
        }
    }
    *ppcEnd = pcData;
    json_debug("Invalid json data %u.", (grub_uint8_t)(*pcData));
    return JSON_FAILED;
}
VTOY_JSON * vtoy_json_create(void)
{
    VTOY_JSON *pstJson = NULL;
    pstJson = (VTOY_JSON *)grub_zalloc(sizeof(VTOY_JSON));
    if (NULL == pstJson)
    {
        return NULL;
    }
    
    return pstJson;
}
int vtoy_json_parse(VTOY_JSON *pstJson, const char *szJsonData)
{
    grub_uint32_t uiMemSize = 0;
    int Ret = JSON_SUCCESS;
    char *pcNewBuf = NULL;
    const char *pcEnd = NULL;
    uiMemSize = grub_strlen(szJsonData) + 1;
    pcNewBuf = (char *)grub_malloc(uiMemSize);
    if (NULL == pcNewBuf)
    {
        json_debug("Failed to alloc new buf.");
        return JSON_FAILED;
    }
    grub_memcpy(pcNewBuf, szJsonData, uiMemSize);
    pcNewBuf[uiMemSize - 1] = 0;
    Ret = vtoy_json_parse_value(pcNewBuf, (char *)szJsonData, pstJson, szJsonData, &pcEnd);
    if (JSON_SUCCESS != Ret)
    {
        json_debug("Failed to parse json data %s start=%p, end=%p:%s.", 
                    szJsonData, szJsonData, pcEnd, pcEnd);
        return JSON_FAILED;
    }
    return JSON_SUCCESS;
}
int vtoy_json_scan_parse
(
    const VTOY_JSON    *pstJson,
    grub_uint32_t       uiParseNum,
    JSON_PARSE         *pstJsonParse
)
{   
    grub_uint32_t i = 0;
    const VTOY_JSON *pstJsonCur = NULL;
    JSON_PARSE *pstCurParse = NULL;
    for (pstJsonCur = pstJson; NULL != pstJsonCur; pstJsonCur = pstJsonCur->pstNext)
    {
        if ((JSON_TYPE_OBJECT == pstJsonCur->enDataType) ||
            (JSON_TYPE_ARRAY == pstJsonCur->enDataType))
        {
            continue;
        }
        for (i = 0, pstCurParse = NULL; i < uiParseNum; i++)
        {
            if (0 == grub_strcmp(pstJsonParse[i].pcKey, pstJsonCur->pcName))
            {   
                pstCurParse = pstJsonParse + i;
                break;
            }
        }
        if (NULL == pstCurParse)
        {
            continue;
        }
    
        switch (pstJsonCur->enDataType)
        {
            case JSON_TYPE_NUMBER:
            {
                if (sizeof(grub_uint32_t) == pstCurParse->uiBufSize)
                {
                    *(grub_uint32_t *)(pstCurParse->pDataBuf) = (grub_uint32_t)pstJsonCur->unData.lValue;
                }
                else if (sizeof(grub_uint16_t) == pstCurParse->uiBufSize)
                {
                    *(grub_uint16_t *)(pstCurParse->pDataBuf) = (grub_uint16_t)pstJsonCur->unData.lValue;
                }
                else if (sizeof(grub_uint8_t) == pstCurParse->uiBufSize)
                {
                    *(grub_uint8_t *)(pstCurParse->pDataBuf) = (grub_uint8_t)pstJsonCur->unData.lValue;
                }
                else if ((pstCurParse->uiBufSize > sizeof(grub_uint64_t)))
                {
                    grub_snprintf((char *)pstCurParse->pDataBuf, pstCurParse->uiBufSize, "%llu", 
                        (unsigned long long)(pstJsonCur->unData.lValue));
                }
                else
                {
                    json_debug("Invalid number data buf size %u.", pstCurParse->uiBufSize);
                }
                break;
            }
            case JSON_TYPE_STRING:
            {
                grub_strncpy((char *)pstCurParse->pDataBuf, pstJsonCur->unData.pcStrVal, pstCurParse->uiBufSize);
                break;
            }
            case JSON_TYPE_BOOL:
            {
                *(grub_uint8_t *)(pstCurParse->pDataBuf) = (pstJsonCur->unData.lValue) > 0 ? 1 : 0;
                break;
            }
            default :
            {
                break;
            }
        }
    }
    return JSON_SUCCESS;
}
int vtoy_json_scan_array
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     VTOY_JSON **ppstArrayItem
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_ARRAY, szKey);
    if (NULL == pstJsonItem)
    {
        json_debug("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *ppstArrayItem = pstJsonItem;
    return JSON_SUCCESS;
}
int vtoy_json_scan_array_ex
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     VTOY_JSON **ppstArrayItem
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_ARRAY, szKey);
    if (NULL == pstJsonItem)
    {
        json_debug("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    
    *ppstArrayItem = pstJsonItem->pstChild;
    return JSON_SUCCESS;
}
int vtoy_json_scan_object
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     VTOY_JSON **ppstObjectItem
)
{
    VTOY_JSON *pstJsonItem = NULL;
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_OBJECT, szKey);
    if (NULL == pstJsonItem)
    {
        json_debug("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *ppstObjectItem = pstJsonItem;
    return JSON_SUCCESS;
}
int vtoy_json_get_int
(
    VTOY_JSON *pstJson, 
    const char *szKey, 
    int *piValue
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
    if (NULL == pstJsonItem)
    {
        json_debug("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *piValue = (int)pstJsonItem->unData.lValue;
    return JSON_SUCCESS;
}
int vtoy_json_get_uint
(
    VTOY_JSON *pstJson, 
    const char *szKey, 
    grub_uint32_t *puiValue
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
    if (NULL == pstJsonItem)
    {
        json_debug("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *puiValue = (grub_uint32_t)pstJsonItem->unData.lValue;
    return JSON_SUCCESS;
}
int vtoy_json_get_uint64
(
    VTOY_JSON *pstJson, 
    const char *szKey, 
    grub_uint64_t *pui64Value
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_NUMBER, szKey);
    if (NULL == pstJsonItem)
    {
        json_debug("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *pui64Value = (grub_uint64_t)pstJsonItem->unData.lValue;
    return JSON_SUCCESS;
}
int vtoy_json_get_bool
(
    VTOY_JSON *pstJson,
    const char *szKey, 
    grub_uint8_t *pbValue
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_BOOL, szKey);
    if (NULL == pstJsonItem)
    {
        json_debug("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    *pbValue = pstJsonItem->unData.lValue > 0 ? 1 : 0;
    return JSON_SUCCESS;
}
int vtoy_json_get_string
(
     VTOY_JSON *pstJson, 
     const char *szKey, 
     grub_uint32_t  uiBufLen,
     char *pcBuf
)
{
    VTOY_JSON *pstJsonItem = NULL;
    
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_STRING, szKey);
    if (NULL == pstJsonItem)
    {
        json_debug("Key %s is not found in json data.", szKey);
        return JSON_NOT_FOUND;
    }
    grub_strncpy(pcBuf, pstJsonItem->unData.pcStrVal, uiBufLen);
    return JSON_SUCCESS;
}
const char * vtoy_json_get_string_ex(VTOY_JSON *pstJson,  const char *szKey)
{
    VTOY_JSON *pstJsonItem = NULL;
    if ((NULL == pstJson) || (NULL == szKey))
    {
        return NULL;
    }
    pstJsonItem = vtoy_json_find_item(pstJson, JSON_TYPE_STRING, szKey);
    if (NULL == pstJsonItem)
    {
        json_debug("Key %s is not found in json data.", szKey);
        return NULL;
    }
    return pstJsonItem->unData.pcStrVal;
}
int vtoy_json_destroy(VTOY_JSON *pstJson)
{
    if (NULL == pstJson)
    {   
        return JSON_SUCCESS;
    }
    if (NULL != pstJson->pstChild)
    {
        vtoy_json_free(pstJson->pstChild);
    }
    if (NULL != pstJson->pstNext)
    {
        vtoy_json_free(pstJson->pstNext);
    }
    grub_free(pstJson);
    
    return JSON_SUCCESS;
}
 | 18,073 | 
	C | 
	.c | 649 | 20.94453 | 113 | 0.574395 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 620 | 
	ventoy.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/ventoy.c | 
	/******************************************************************************
 * ventoy.c 
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <grub/types.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/disk.h>
#include <grub/device.h>
#include <grub/term.h>
#include <grub/partition.h>
#include <grub/file.h>
#include <grub/normal.h>
#include <grub/extcmd.h>
#include <grub/datetime.h>
#include <grub/net.h>
#include <grub/misc.h>
#include <grub/kernel.h>
#include <grub/time.h>
#include <grub/memory.h>
#ifdef GRUB_MACHINE_EFI
#include <grub/efi/efi.h>
#include <grub/efi/memory.h>
#endif
#include <grub/ventoy.h>
#include "ventoy_def.h"
GRUB_MOD_LICENSE ("GPLv3+");
int g_ventoy_debug = 0;
static int g_efi_os = 0xFF;
grub_uint32_t g_ventoy_plat_data;
void ventoy_debug(const char *fmt, ...)
{
    va_list args;
    va_start (args, fmt);
    grub_vprintf (fmt, args);
    va_end (args);
}
void ventoy_str_tolower(char *str)
{
    while (*str)
    {
        *str = grub_tolower(*str);
        str++;
    }
}
void ventoy_str_toupper(char *str)
{
    while (*str)
    {
        *str = grub_toupper(*str);
        str++;
    }
}
char *ventoy_str_last(char *str, char ch)
{
    char *pos = NULL;
    char *last = NULL;
    if (!str)
    {
        return NULL;
    }
    for (pos = str; *pos; pos++)
    {
        if (*pos == ch)
        {
            last = pos;
        }
    }
    return last;
}
int ventoy_str_all_digit(const char *str)
{
    if (NULL == str || 0 == *str)
    {
        return 0;
    }
    while (*str)
    {
        if (*str < '0' || *str > '9')
        {
            return 0;
        }
    }
    return 1;
}
int ventoy_str_all_alnum(const char *str)
{
    if (NULL == str || 0 == *str)
    {
        return 0;
    }
    while (*str)
    {
        if (!grub_isalnum(*str))
        {
            return 0;
        }
    }
    return 1;
}
int ventoy_str_len_alnum(const char *str, int len)
{
    int i;
    int slen;
    
    if (NULL == str || 0 == *str)
    {
        return 0;
    }
    slen = grub_strlen(str);
    if (slen <= len)
    {
        return 0;
    }
    for (i = 0; i < len; i++)
    {
        if (!grub_isalnum(str[i]))
        {
            return 0;
        }
    }
    if (str[len] == 0 || grub_isspace(str[len]))
    {
        return 1;
    }
    return 0;
}
char * ventoy_str_basename(char *path)
{
    char *pos = NULL;
    
    pos = grub_strrchr(path, '/');
    if (pos)
    {
        pos++;
    }
    else
    {
        pos = path;
    }
    return pos;
}
int ventoy_str_chrcnt(const char *str, char c)
{
    int n = 0;
    
    if (str)
    {
        while (*str)
        {
            if (*str == c)
            {
                n++;                
            }
            str++;
        }        
    }
    return n;
}
int ventoy_strcmp(const char *pattern, const char *str)
{
    while (*pattern && *str)
    {
        if ((*pattern != *str) && (*pattern != '*'))
            break;
        pattern++;
        str++;
    }
    return (int)(grub_uint8_t)*pattern - (int)(grub_uint8_t)*str;
}
int ventoy_strncmp (const char *pattern, const char *str, grub_size_t n)
{
    if (n == 0)
        return 0;
    while (*pattern && *str && --n)
    {
        if ((*pattern != *str) && (*pattern != '*'))
            break;
        pattern++;
        str++;
    }
    return (int)(grub_uint8_t)*pattern - (int)(grub_uint8_t)*str;
}
grub_err_t ventoy_env_int_set(const char *name, int value)
{
    char buf[16];
    
    grub_snprintf(buf, sizeof(buf), "%d", value);
    return grub_env_set(name, buf);
}
void ventoy_debug_dump_guid(const char *prefix, grub_uint8_t *guid)
{
    int i;
    if (!g_ventoy_debug)
    {
        return;
    }
    
    debug("%s", prefix);
    for (i = 0; i < 16; i++)
    {
        grub_printf("%02x ", guid[i]);
    }
    grub_printf("\n");       
}
int ventoy_is_efi_os(void)
{
    if (g_efi_os > 1)
    {
        g_efi_os = (grub_strstr(GRUB_PLATFORM, "efi")) ? 1 : 0;
    }
    return g_efi_os;
}
void * ventoy_alloc_chain(grub_size_t size)
{
    void *p = NULL;
    p = grub_malloc(size);
#ifdef GRUB_MACHINE_EFI
    if (!p)
    {
        p = grub_efi_allocate_any_pages(GRUB_EFI_BYTES_TO_PAGES(size));
    }
#endif
    return p;
}
void ventoy_memfile_env_set(const char *prefix, const void *buf, unsigned long long len)
{
    char name[128];
    char val[64];
    grub_snprintf(name, sizeof(name), "%s_addr", prefix);
    grub_snprintf(val, sizeof(val), "0x%llx", (ulonglong)(ulong)buf);
    grub_env_set(name, val);
    
    grub_snprintf(name, sizeof(name), "%s_size", prefix);
    grub_snprintf(val, sizeof(val), "%llu", len);
    grub_env_set(name, val);
    return;
}
static int ventoy_arch_mode_init(void)
{
    #ifdef GRUB_MACHINE_EFI
    if (grub_strcmp(GRUB_TARGET_CPU, "i386") == 0)
    {
        g_ventoy_plat_data = VTOY_PLAT_I386_UEFI;
        grub_snprintf(g_arch_mode_suffix, sizeof(g_arch_mode_suffix), "%s", "ia32");
    }
    else if (grub_strcmp(GRUB_TARGET_CPU, "arm64") == 0)
    {
        g_ventoy_plat_data = VTOY_PLAT_ARM64_UEFI;
        grub_snprintf(g_arch_mode_suffix, sizeof(g_arch_mode_suffix), "%s", "aa64");
    }
    else if (grub_strcmp(GRUB_TARGET_CPU, "mips64el") == 0)
    {
        g_ventoy_plat_data = VTOY_PLAT_MIPS_UEFI;
        grub_snprintf(g_arch_mode_suffix, sizeof(g_arch_mode_suffix), "%s", "mips");
    }
    else
    {
        g_ventoy_plat_data = VTOY_PLAT_X86_64_UEFI;
        grub_snprintf(g_arch_mode_suffix, sizeof(g_arch_mode_suffix), "%s", "uefi");
    }
#else
    g_ventoy_plat_data = VTOY_PLAT_X86_LEGACY;
    grub_snprintf(g_arch_mode_suffix, sizeof(g_arch_mode_suffix), "%s", "legacy");
#endif
    return 0;
}
#ifdef GRUB_MACHINE_EFI
static void ventoy_get_uefi_version(char *str, grub_size_t len)
{
    grub_efi_uint8_t uefi_minor_1, uefi_minor_2;
    uefi_minor_1 = (grub_efi_system_table->hdr.revision & 0xffff) / 10;
    uefi_minor_2 = (grub_efi_system_table->hdr.revision & 0xffff) % 10;
    grub_snprintf(str, len, "%d.%d", (grub_efi_system_table->hdr.revision >> 16), uefi_minor_1);
    if (uefi_minor_2)
        grub_snprintf(str, len, "%s.%d", str, uefi_minor_2);
}
#endif
static int ventoy_calc_totalmem(grub_uint64_t addr, grub_uint64_t size, grub_memory_type_t type, void *data)
{
    grub_uint64_t *total_mem = (grub_uint64_t *)data;
    (void)addr;
    (void)type;
    *total_mem += size;
    return 0;
}
static int ventoy_hwinfo_init(void)
{
    char str[256];
    grub_uint64_t total_mem = 0;
    grub_machine_mmap_iterate(ventoy_calc_totalmem, &total_mem);
    grub_snprintf(str, sizeof(str), "%ld", (long)(total_mem / VTOY_SIZE_1MB));
    ventoy_env_export("grub_total_ram", str);
#ifdef GRUB_MACHINE_EFI
    ventoy_get_uefi_version(str, sizeof(str));
    ventoy_env_export("grub_uefi_version", str);
#else
    ventoy_env_export("grub_uefi_version", "NA");
#endif
    return 0;
}
static global_var_cfg g_global_vars[] = 
{
    { "gfxmode",            "1024x768",   NULL },
    { ventoy_left_key,      "5%",         NULL },
    { ventoy_top_key,       "95%",        NULL },
    { ventoy_color_key,     "#0000ff",    NULL },
    { NULL,                 NULL,         NULL }
};
static const char * ventoy_global_var_read_hook(struct grub_env_var *var, const char *val)
{
    int i;
    for (i = 0; g_global_vars[i].name; i++)
    {
        if (grub_strcmp(g_global_vars[i].name, var->name) == 0)
        {
            return g_global_vars[i].value;
        }
    }
    return val;
}
static char * ventoy_global_var_write_hook(struct grub_env_var *var, const char *val)
{
    int i;
    for (i = 0; g_global_vars[i].name; i++)
    {
        if (grub_strcmp(g_global_vars[i].name, var->name) == 0)
        {
            grub_check_free(g_global_vars[i].value);
            g_global_vars[i].value = grub_strdup(val);
            break;
        }
    }
    return grub_strdup(val);
}
int ventoy_global_var_init(void)
{
    int i;
    for (i = 0; g_global_vars[i].name; i++)
    {
        g_global_vars[i].value = grub_strdup(g_global_vars[i].defval);
        ventoy_env_export(g_global_vars[i].name, g_global_vars[i].defval);        
        grub_register_variable_hook(g_global_vars[i].name, ventoy_global_var_read_hook, ventoy_global_var_write_hook);
    }
    return 0;
}
static ctrl_var_cfg g_ctrl_vars[] = 
{
    { "VTOY_WIN11_BYPASS_CHECK",  1 },
    { "VTOY_WIN11_BYPASS_NRO",    1 },
    { "VTOY_LINUX_REMOUNT",       0 },
    { "VTOY_SECONDARY_BOOT_MENU", 1 },
    { NULL, 0 }
};
static const char * ventoy_ctrl_var_read_hook(struct grub_env_var *var, const char *val)
{
    int i;
    for (i = 0; g_ctrl_vars[i].name; i++)
    {
        if (grub_strcmp(g_ctrl_vars[i].name, var->name) == 0)
        {
            return g_ctrl_vars[i].value ? "1" : "0";
        }
    }
    return val;
}
static char * ventoy_ctrl_var_write_hook(struct grub_env_var *var, const char *val)
{
    int i;
    for (i = 0; g_ctrl_vars[i].name; i++)
    {
        if (grub_strcmp(g_ctrl_vars[i].name, var->name) == 0)
        {
            if (val && val[0] == '1' && val[1] == 0)
            {
                g_ctrl_vars[i].value = 1;
                return grub_strdup("1");
            }
            else
            {
                g_ctrl_vars[i].value = 0;
                return grub_strdup("0");
            }
        }
    }
    return grub_strdup(val);
}
int ventoy_ctrl_var_init(void)
{
    int i;
    for (i = 0; g_ctrl_vars[i].name; i++)
    {
        ventoy_env_export(g_ctrl_vars[i].name, g_ctrl_vars[i].value ? "1" : "0");
        grub_register_variable_hook(g_ctrl_vars[i].name, ventoy_ctrl_var_read_hook, ventoy_ctrl_var_write_hook);
    }
    return 0;
}
GRUB_MOD_INIT(ventoy)
{
    ventoy_hwinfo_init();
    ventoy_env_init();
    ventoy_arch_mode_init();
    ventoy_register_all_cmd();
}
GRUB_MOD_FINI(ventoy)
{
    ventoy_unregister_all_cmd();
}
 | 10,612 | 
	C | 
	.c | 419 | 20.155131 | 118 | 0.568283 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 621 | 
	ventoy_linux.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/ventoy_linux.c | 
	/******************************************************************************
 * ventoy_linux.c 
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <grub/types.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/disk.h>
#include <grub/device.h>
#include <grub/term.h>
#include <grub/partition.h>
#include <grub/file.h>
#include <grub/normal.h>
#include <grub/extcmd.h>
#include <grub/datetime.h>
#include <grub/i18n.h>
#include <grub/net.h>
#include <grub/time.h>
#include <grub/ventoy.h>
#include "ventoy_def.h"
GRUB_MOD_LICENSE ("GPLv3+");
#define VTOY_APPEND_EXT_SIZE 4096
static int g_append_ext_sector = 0;
char * ventoy_get_line(char *start)
{
    if (start == NULL)
    {
        return NULL;
    }
    while (*start && *start != '\n')
    {
        start++;
    }
    if (*start == 0)
    {
        return NULL;
    }
    else
    {
        *start = 0;
        return start + 1;
    }
}
static initrd_info * ventoy_find_initrd_by_name(initrd_info *list, const char *name)
{
    initrd_info *node = list;
    while (node)
    {
        if (grub_strcmp(node->name, name) == 0)
        {
            return node;
        }
        node = node->next;
    }
    return NULL;
}
grub_err_t ventoy_cmd_clear_initrd_list(grub_extcmd_context_t ctxt, int argc, char **args)
{
    initrd_info *node = g_initrd_img_list;
    initrd_info *next;
    
    (void)ctxt;
    (void)argc;
    (void)args;
    while (node)
    {
        next = node->next;
        grub_free(node);
        node = next;
    }
    g_initrd_img_list = NULL;
    g_initrd_img_tail = NULL;
    g_initrd_img_count = 0;
    g_valid_initrd_count = 0;
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_dump_initrd_list(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int i = 0;
    initrd_info *node = g_initrd_img_list;
    
    (void)ctxt;
    (void)argc;
    (void)args;
    grub_printf("###################\n");
    grub_printf("initrd info list: valid count:%d\n", g_valid_initrd_count);
    while (node)
    {
        grub_printf("%s ", node->size > 0 ? "*" : " ");
        grub_printf("%02u %s  offset:%llu  size:%llu \n", i++, node->name, (unsigned long long)node->offset, 
                    (unsigned long long)node->size);
        node = node->next;
    }
    grub_printf("###################\n");
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static void ventoy_parse_directory(char *path, char *dir, int buflen)
{   
    int end;
    char *pos;
    pos = grub_strstr(path, ")");
    if (!pos)
    {
        pos = path;
    }
    end = grub_snprintf(dir, buflen, "%s", pos + 1);
    while (end > 0)
    {
        if (dir[end] == '/')
        {
            dir[end + 1] = 0;
            break;
        }
        end--;
    }
}
static grub_err_t ventoy_isolinux_initrd_collect(grub_file_t file, const char *prefix)
{
    int i = 0;
    int offset;
    int prefixlen = 0;
    char *buf = NULL;
    char *pos = NULL;
    char *start = NULL;
    char *nextline = NULL;
    initrd_info *img = NULL;
    prefixlen = grub_strlen(prefix);
    buf = grub_zalloc(file->size + 2);
    if (!buf)
    {
        return 0;
    }
    grub_file_read(file, buf, file->size);
    for (start = buf; start; start = nextline)
    {
        nextline = ventoy_get_line(start);
        VTOY_SKIP_SPACE(start);
        offset = 7; // strlen("initrd=") or "INITRD " or "initrd "
        pos = grub_strstr(start, "initrd=");
        if (pos == NULL)
        {
            pos = start;
            if (grub_strncmp(start, "INITRD", 6) != 0 && grub_strncmp(start, "initrd", 6) != 0)
            {
                if (grub_strstr(start, "xen") &&
                    ((pos = grub_strstr(start, "--- /install.img")) != NULL ||
                     (pos = grub_strstr(start, "--- initrd.img")) != NULL
                    ))
                {
                    offset = 4; // "--- "
                }
                else
                {
                    continue;
                }
            }
        }
        pos += offset; 
        while (1)
        {
            i = 0;
            img = grub_zalloc(sizeof(initrd_info));
            if (!img)
            {
                break;
            }
            if (*pos != '/')
            {
                grub_strcpy(img->name, prefix);
                i = prefixlen;
            }
            while (i < 255 && (0 == ventoy_is_word_end(*pos)))
            {
                img->name[i++] = *pos++;
            }
            if (ventoy_find_initrd_by_name(g_initrd_img_list, img->name))
            {
                grub_free(img);
            }
            else
            {
                if (g_initrd_img_list)
                {
                    img->prev = g_initrd_img_tail;
                    g_initrd_img_tail->next = img;
                }
                else
                {
                    g_initrd_img_list = img;
                }
                g_initrd_img_tail = img;
                g_initrd_img_count++;
            }
            if (*pos == ',')
            {
                pos++;
            }
            else
            {
                break;
            }
        }
    }
    grub_free(buf);
    return GRUB_ERR_NONE;
}
static int ventoy_isolinux_initrd_hook(const char *filename, const struct grub_dirhook_info *info, void *data)
{
    grub_file_t file = NULL;
    ventoy_initrd_ctx *ctx = (ventoy_initrd_ctx *)data;
    (void)info;
    if (NULL == grub_strstr(filename, ".cfg") && NULL == grub_strstr(filename, ".CFG"))
    {
        return 0;
    }
    debug("init hook dir <%s%s>\n", ctx->path_prefix, filename);
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s%s", ctx->path_prefix, filename);
    if (!file)
    {
        return 0;
    }
    ventoy_isolinux_initrd_collect(file, ctx->dir_prefix);
    grub_file_close(file);
    return 0;
}
grub_err_t ventoy_cmd_isolinux_initrd_collect(grub_extcmd_context_t ctxt, int argc, char **args)
{
    grub_fs_t fs;
    grub_device_t dev = NULL;
    char *device_name = NULL;
    ventoy_initrd_ctx ctx;
    char directory[256];
    
    (void)ctxt;
    (void)argc;
    device_name = grub_file_get_device_name(args[0]);
    if (!device_name)
    {
        goto end;
    }
    dev = grub_device_open(device_name);
    if (!dev)
    {
        goto end;        
    }
    fs = grub_fs_probe(dev);
    if (!fs)
    {
        goto end;
    }
    debug("isolinux initrd collect %s\n", args[0]);
    ventoy_parse_directory(args[0], directory, sizeof(directory) - 1);
    ctx.path_prefix = args[0];
    ctx.dir_prefix = (argc > 1) ? args[1] : directory;
    debug("path_prefix=<%s> dir_prefix=<%s>\n", ctx.path_prefix, ctx.dir_prefix);
    fs->fs_dir(dev, directory, ventoy_isolinux_initrd_hook, &ctx);
end:
    check_free(device_name, grub_free);
    check_free(dev, grub_device_close);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static int ventoy_linux_initrd_collect_hook(const char *filename, const struct grub_dirhook_info *info, void *data)
{
    int len;
    initrd_info *img = NULL;
    
    (void)data;
    if (0 == info->dir)
    {
        if (grub_strncmp(filename, "initrd", 6) == 0)
        {
            len = (int)grub_strlen(filename);
            if (grub_strcmp(filename + len - 4, ".img") == 0)
            {
                img = grub_zalloc(sizeof(initrd_info));
                if (img)
                {
                    grub_snprintf(img->name, sizeof(img->name), "/boot/%s", filename);
                    if (ventoy_find_initrd_by_name(g_initrd_img_list, img->name))
                    {
                        grub_free(img);
                    }
                    else
                    {                        
                        if (g_initrd_img_list)
                        {
                            img->prev = g_initrd_img_tail;
                            g_initrd_img_tail->next = img;
                        }
                        else
                        {
                            g_initrd_img_list = img;
                        }
                        g_initrd_img_tail = img;
                        g_initrd_img_count++;
                    }
                }
            }
        }
    }
    return 0;
}
static int ventoy_linux_collect_boot_initrds(void)
{
    grub_fs_t fs;
    grub_device_t dev = NULL;
    dev = grub_device_open("loop");
    if (!dev)
    {
        debug("failed to open device loop\n");
        goto end;        
    }
    fs = grub_fs_probe(dev);
    if (!fs)
    {
        debug("failed to probe fs %d\n", grub_errno);
        goto end;
    }
    fs->fs_dir(dev, "/boot", ventoy_linux_initrd_collect_hook, NULL);
end:
    return 0;    
}
static grub_err_t ventoy_grub_cfg_initrd_collect(const char *fileName)
{
    int i = 0;
    int len = 0;
    int dollar = 0;
    int quotation = 0;
    int initrd_dollar = 0;
    grub_file_t file = NULL;
    char *buf = NULL;
    char *start = NULL;
    char *nextline = NULL;
    initrd_info *img = NULL;
    debug("grub initrd collect %s\n", fileName);
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", fileName);
    if (!file)
    {
        return 0;
    }
    
    buf = grub_zalloc(file->size + 2);
    if (!buf)
    {
        grub_file_close(file);
        return 0;
    }
    grub_file_read(file, buf, file->size);
    for (start = buf; start; start = nextline)
    {
        nextline = ventoy_get_line(start);
        VTOY_SKIP_SPACE(start);
        if (grub_strncmp(start, "initrd", 6) != 0)
        {
            continue;
        }
        start += 6;
        while (*start && (!ventoy_isspace(*start)))
        {
            start++;
        }
        VTOY_SKIP_SPACE(start);
        if (*start == '"')
        {
            quotation = 1;
            start++;
        }
        while (*start)
        {
            img = grub_zalloc(sizeof(initrd_info));
            if (!img)
            {
                break;
            }
            dollar = 0;
            for (i = 0; i < 255 && (0 == ventoy_is_word_end(*start)); i++)
            {
                img->name[i] = *start++;
                if (img->name[i] == '$')
                {
                    dollar = 1;
                }
            }
            if (quotation)
            {
                len = (int)grub_strlen(img->name);
                if (len > 2 && img->name[len - 1] == '"')
                {
                    img->name[len - 1] = 0;
                }
                debug("Remove quotation <%s>\n", img->name);
            }
            /* special process for /boot/initrd$XXX.img */
            if (dollar == 1)
            {
                if (grub_strncmp(img->name, "/boot/initrd$", 13) == 0)
                {
                    len = (int)grub_strlen(img->name);
                    if (grub_strcmp(img->name + len - 4, ".img") == 0)
                    {
                        initrd_dollar++;                        
                    }                    
                }
            }
            if (dollar == 1 || ventoy_find_initrd_by_name(g_initrd_img_list, img->name))
            {
                grub_free(img);
            }
            else
            {
                if (g_initrd_img_list)
                {
                    img->prev = g_initrd_img_tail;
                    g_initrd_img_tail->next = img;
                }
                else
                {
                    g_initrd_img_list = img;
                }
                g_initrd_img_tail = img;
                g_initrd_img_count++;
            }
            if (*start == ' ' || *start == '\t')
            {
                VTOY_SKIP_SPACE(start);
            }
            else
            {
                break;
            }
        }
    }
    grub_free(buf);
    grub_file_close(file);
    if (initrd_dollar > 0 && grub_strncmp(fileName, "(loop)/", 7) == 0)
    {
        debug("collect initrd variable %d\n", initrd_dollar);
        ventoy_linux_collect_boot_initrds();
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static int ventoy_grub_initrd_hook(const char *filename, const struct grub_dirhook_info *info, void *data)
{
    char filePath[256];
    ventoy_initrd_ctx *ctx = (ventoy_initrd_ctx *)data;
    (void)info;
    debug("ventoy_grub_initrd_hook %s\n", filename);
    if (NULL == grub_strstr(filename, ".cfg") && 
        NULL == grub_strstr(filename, ".CFG") && 
        NULL == grub_strstr(filename, ".conf"))
    {
        return 0;
    }
    debug("init hook dir <%s%s>\n", ctx->path_prefix, filename);
    grub_snprintf(filePath, sizeof(filePath) - 1, "%s%s", ctx->dir_prefix, filename);
    ventoy_grub_cfg_initrd_collect(filePath);
    return 0;
}
grub_err_t ventoy_cmd_grub_initrd_collect(grub_extcmd_context_t ctxt, int argc, char **args)
{
    grub_fs_t fs;
    grub_device_t dev = NULL;
    char *device_name = NULL;
    ventoy_initrd_ctx ctx;
    
    (void)ctxt;
    (void)argc;
    if (argc != 2)
    {
        return 0;
    }
    debug("grub initrd collect %s %s\n", args[0], args[1]);
    if (grub_strcmp(args[0], "file") == 0)
    {
        return ventoy_grub_cfg_initrd_collect(args[1]);
    }
    device_name = grub_file_get_device_name(args[1]);
    if (!device_name)
    {
        debug("failed to get device name %s\n", args[1]);
        goto end;
    }
    dev = grub_device_open(device_name);
    if (!dev)
    {
        debug("failed to open device %s\n", device_name);
        goto end;        
    }
    fs = grub_fs_probe(dev);
    if (!fs)
    {
        debug("failed to probe fs %d\n", grub_errno);
        goto end;
    }
    ctx.dir_prefix = args[1];
    ctx.path_prefix = grub_strstr(args[1], device_name);
    if (ctx.path_prefix)
    {
        ctx.path_prefix += grub_strlen(device_name) + 1;
    }
    else
    {
        ctx.path_prefix = args[1];
    }
    debug("ctx.path_prefix:<%s>\n", ctx.path_prefix);
    fs->fs_dir(dev, ctx.path_prefix, ventoy_grub_initrd_hook, &ctx);
end:
    check_free(device_name, grub_free);
    check_free(dev, grub_device_close);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_specify_initrd_file(grub_extcmd_context_t ctxt, int argc, char **args)
{
    initrd_info *img = NULL;
    (void)ctxt;
    (void)argc;
    debug("ventoy_cmd_specify_initrd_file %s\n", args[0]);
    img = grub_zalloc(sizeof(initrd_info));
    if (!img)
    {
        return 1;
    }
    grub_strncpy(img->name, args[0], sizeof(img->name));
    if (ventoy_find_initrd_by_name(g_initrd_img_list, img->name))
    {
        debug("%s is already exist\n", args[0]);
        grub_free(img);
    }
    else
    {
        if (g_initrd_img_list)
        {
            img->prev = g_initrd_img_tail;
            g_initrd_img_tail->next = img;
        }
        else
        {
            g_initrd_img_list = img;
        }
        g_initrd_img_tail = img;
        g_initrd_img_count++;
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static int ventoy_cpio_newc_get_int(char *value)
{
    char buf[16] = {0};
    grub_memcpy(buf, value, 8);
    return (int)grub_strtoul(buf, NULL, 16);
}
static void ventoy_cpio_newc_fill_int(grub_uint32_t value, char *buf, int buflen)
{
    int i;
    int len;
    char intbuf[32];
    len = grub_snprintf(intbuf, sizeof(intbuf), "%x", value);
    for (i = 0; i < buflen; i++)
    {
        buf[i] = '0';
    }
    if (len > buflen)
    {
        grub_printf("int buf len overflow %d %d\n", len, buflen);
    }
    else
    {
        grub_memcpy(buf + buflen - len, intbuf, len);    
    }
}
int ventoy_cpio_newc_fill_head(void *buf, int filesize, const void *filedata, const char *name)
{
    int namelen = 0;
    int headlen = 0;
    static grub_uint32_t cpio_ino = 0xFFFFFFF0;
    cpio_newc_header *cpio = (cpio_newc_header *)buf;
    
    namelen = grub_strlen(name) + 1;
    headlen = sizeof(cpio_newc_header) + namelen;
    headlen = ventoy_align(headlen, 4);
    grub_memset(cpio, '0', sizeof(cpio_newc_header));
    grub_memset(cpio + 1, 0, headlen - sizeof(cpio_newc_header));
    grub_memcpy(cpio->c_magic, "070701", 6);
    ventoy_cpio_newc_fill_int(cpio_ino--, cpio->c_ino, 8);
    ventoy_cpio_newc_fill_int(0100777, cpio->c_mode, 8);
    ventoy_cpio_newc_fill_int(1, cpio->c_nlink, 8);
    ventoy_cpio_newc_fill_int(filesize, cpio->c_filesize, 8);
    ventoy_cpio_newc_fill_int(namelen, cpio->c_namesize, 8);
    grub_memcpy(cpio + 1, name, namelen);
    if (filedata)
    {
        grub_memcpy((char *)cpio + headlen, filedata, filesize);
    }
    return headlen;
}
static grub_uint32_t ventoy_linux_get_virt_chunk_count(void)
{
    int i;
    grub_uint32_t count = g_valid_initrd_count;
    
    if (g_conf_replace_count > 0)
    {
        for (i = 0; i < g_conf_replace_count; i++)
        {
            if (g_conf_replace_offset[i] > 0)
            {
                count++;
            }
        }
    }
    
    if (g_append_ext_sector > 0)
    {
        count++;
    }
    
    return count;
}
static grub_uint32_t ventoy_linux_get_virt_chunk_size(void)
{
    int i;
    grub_uint32_t size;
    
    size = (sizeof(ventoy_virt_chunk) + g_ventoy_cpio_size) * g_valid_initrd_count;
    if (g_conf_replace_count > 0)
    {
        for (i = 0; i < g_conf_replace_count; i++)
        {
            if (g_conf_replace_offset[i] > 0)
            {
                size += sizeof(ventoy_virt_chunk) + g_conf_replace_new_len_align[i];
            }
        }
    }
    
    if (g_append_ext_sector > 0)
    {
        size += sizeof(ventoy_virt_chunk) + VTOY_APPEND_EXT_SIZE;
    }
    return size;
}
static void ventoy_linux_fill_virt_data(    grub_uint64_t isosize, ventoy_chain_head *chain)
{
    int i = 0;
    int id = 0;
    int virtid = 0;
    initrd_info *node;
    grub_uint64_t sector;
    grub_uint32_t offset;
    grub_uint32_t cpio_secs;
    grub_uint32_t initrd_secs;
    char *override;
    ventoy_virt_chunk *cur;
    ventoy_grub_param_file_replace *replace = NULL;
    char name[32];
    override = (char *)chain + chain->virt_chunk_offset;
    sector = (isosize + 2047) / 2048;
    cpio_secs = g_ventoy_cpio_size / 2048;
    offset = ventoy_linux_get_virt_chunk_count() * sizeof(ventoy_virt_chunk);
    cur = (ventoy_virt_chunk *)override;
    for (node = g_initrd_img_list; node; node = node->next)
    {
        if (node->size == 0)
        {
            continue;
        }
        initrd_secs = (grub_uint32_t)((node->size + 2047) / 2048);
        cur->mem_sector_start   = sector;
        cur->mem_sector_end     = cur->mem_sector_start + cpio_secs;
        cur->mem_sector_offset  = offset;
        cur->remap_sector_start = cur->mem_sector_end;
        cur->remap_sector_end   = cur->remap_sector_start + initrd_secs;
        cur->org_sector_start   = (grub_uint32_t)(node->offset / 2048);
        grub_memcpy(g_ventoy_runtime_buf, &chain->os_param, sizeof(ventoy_os_param));
        grub_memset(name, 0, 16);
        grub_snprintf(name, sizeof(name), "initrd%03d", ++id);
        grub_memcpy(g_ventoy_initrd_head + 1, name, 16);
        ventoy_cpio_newc_fill_int((grub_uint32_t)node->size, g_ventoy_initrd_head->c_filesize, 8);
        grub_memcpy(override + offset, g_ventoy_cpio_buf, g_ventoy_cpio_size);
        chain->virt_img_size_in_bytes += g_ventoy_cpio_size + initrd_secs * 2048;
        offset += g_ventoy_cpio_size;
        sector += cpio_secs + initrd_secs;
        cur++;
        virtid++;
    }
    /* Lenovo EasyStartup need an addional sector for boundary check */
    if (g_append_ext_sector > 0)
    {
        cpio_secs = VTOY_APPEND_EXT_SIZE / 2048;
    
        cur->mem_sector_start   = sector;
        cur->mem_sector_end     = cur->mem_sector_start + cpio_secs;
        cur->mem_sector_offset  = offset;
        cur->remap_sector_start = 0;
        cur->remap_sector_end   = 0;
        cur->org_sector_start   = 0;
        grub_memset(override + offset, 0, VTOY_APPEND_EXT_SIZE);
        chain->virt_img_size_in_bytes += VTOY_APPEND_EXT_SIZE;
        offset += VTOY_APPEND_EXT_SIZE;
        sector += cpio_secs;
        cur++;
        virtid++;
    }
    if (g_conf_replace_count > 0)
    {
        for (i = 0; i < g_conf_replace_count; i++)
        {
            if (g_conf_replace_offset[i] > 0)
            {
                cpio_secs = g_conf_replace_new_len_align[i] / 2048;
            
                cur->mem_sector_start   = sector;
                cur->mem_sector_end     = cur->mem_sector_start + cpio_secs;
                cur->mem_sector_offset  = offset;
                cur->remap_sector_start = 0;
                cur->remap_sector_end   = 0;
                cur->org_sector_start   = 0;
                grub_memcpy(override + offset, g_conf_replace_new_buf[i], g_conf_replace_new_len[i]);
                chain->virt_img_size_in_bytes += g_conf_replace_new_len_align[i];
                replace = g_grub_param->img_replace + i;
                if (replace->magic == GRUB_IMG_REPLACE_MAGIC)
                {
                    replace->new_file_virtual_id = virtid;
                }
                offset += g_conf_replace_new_len_align[i];
                sector += cpio_secs;
                cur++;
                virtid++;
            }
        }
    }
    return;
}
static grub_uint32_t ventoy_linux_get_override_chunk_count(void)
{
    int i;
    grub_uint32_t count = g_valid_initrd_count;
    if (g_conf_replace_count > 0)
    {
        for (i = 0; i < g_conf_replace_count; i++)
        {
            if (g_conf_replace_offset[i] > 0)
            {
                count++;
            }
        }
    }
    if (g_svd_replace_offset > 0)
    {
        count++;
    }
    
    return count;
}
static grub_uint32_t ventoy_linux_get_override_chunk_size(void)
{
    int i;
    int count = g_valid_initrd_count;
    if (g_conf_replace_count > 0)
    {
        for (i = 0; i < g_conf_replace_count; i++)
        {
            if (g_conf_replace_offset[i] > 0)
            {
                count++;
            }
        }
    }
    if (g_svd_replace_offset > 0)
    {
        count++;
    }
    return sizeof(ventoy_override_chunk) * count;
}
static void ventoy_linux_fill_override_data(    grub_uint64_t isosize, void *override)
{
    int i;
    initrd_info *node;
    grub_uint32_t mod;
    grub_uint32_t newlen;
    grub_uint64_t sector;
    ventoy_override_chunk *cur;
    ventoy_iso9660_override *dirent;
    ventoy_udf_override *udf;
    sector = (isosize + 2047) / 2048;
    cur = (ventoy_override_chunk *)override;
    for (node = g_initrd_img_list; node; node = node->next)
    {
        if (node->size == 0)
        {
            continue;
        }
        newlen = (grub_uint32_t)(node->size + g_ventoy_cpio_size);
        mod = newlen % 4; 
        if (mod > 0)
        {
            newlen += 4 - mod; /* cpio must align with 4 */
        }
        if (node->iso_type == 0)
        {
            dirent = (ventoy_iso9660_override *)node->override_data;
            node->override_length   = sizeof(ventoy_iso9660_override);
            dirent->first_sector    = (grub_uint32_t)sector;
            dirent->size            = newlen;
            dirent->first_sector_be = grub_swap_bytes32(dirent->first_sector);
            dirent->size_be         = grub_swap_bytes32(dirent->size);
            sector += (dirent->size + 2047) / 2048;
        }
        else
        {
            udf = (ventoy_udf_override *)node->override_data;
            
            node->override_length = sizeof(ventoy_udf_override);
            udf->length   = newlen;
            udf->position = (grub_uint32_t)sector - node->udf_start_block;
            sector += (udf->length + 2047) / 2048;
        }
        cur->img_offset = node->override_offset;
        cur->override_size = node->override_length;
        grub_memcpy(cur->override_data, node->override_data, cur->override_size);
        cur++;
    }
    if (g_conf_replace_count > 0)
    {
        for (i = 0; i < g_conf_replace_count; i++)
        {
            if (g_conf_replace_offset[i] > 0)
            {        
                cur->img_offset = g_conf_replace_offset[i];
                cur->override_size = sizeof(ventoy_iso9660_override);
                newlen = (grub_uint32_t)(g_conf_replace_new_len[i]);
                dirent = (ventoy_iso9660_override *)cur->override_data;
                dirent->first_sector    = (grub_uint32_t)sector;
                dirent->size            = newlen;
                dirent->first_sector_be = grub_swap_bytes32(dirent->first_sector);
                dirent->size_be         = grub_swap_bytes32(dirent->size);
                sector += (dirent->size + 2047) / 2048;
                cur++;
            }
        }
    }
    if (g_svd_replace_offset > 0)
    {        
        cur->img_offset = g_svd_replace_offset;
        cur->override_size = 1;
        cur->override_data[0] = 0xFF;
        cur++;
    }
    return;
}
grub_err_t ventoy_cmd_initrd_count(grub_extcmd_context_t ctxt, int argc, char **args)
{
    char buf[32] = {0};
    
    (void)ctxt;
    (void)argc;
    (void)args;
    if (argc == 1)
    {
        grub_snprintf(buf, sizeof(buf), "%d", g_initrd_img_count);
        grub_env_set(args[0], buf);
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_valid_initrd_count(grub_extcmd_context_t ctxt, int argc, char **args)
{
    char buf[32] = {0};
    
    (void)ctxt;
    (void)argc;
    (void)args;
    if (argc == 1)
    {
        grub_snprintf(buf, sizeof(buf), "%d", g_valid_initrd_count);
        grub_env_set(args[0], buf);
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static grub_err_t ventoy_linux_locate_initrd(int filt, int *filtcnt)
{
    int data;
    int filtbysize = 1;
    int sizefilt = 0;
    grub_file_t file;
    initrd_info *node;
    debug("ventoy_linux_locate_initrd %d\n", filt);
    g_valid_initrd_count = 0;
    if (grub_env_get("INITRD_NO_SIZE_FILT"))
    {
        filtbysize = 0;
    }
    
    for (node = g_initrd_img_list; node; node = node->next)
    {
        file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "(loop)%s", node->name);
        if (!file)
        {
            continue;
        }
        debug("file <%s> size:%d\n", node->name, (int)file->size);
        /* initrd file too small */
        if (filtbysize 
            && (NULL == grub_strstr(node->name, "minirt.gz"))
            && (NULL == grub_strstr(node->name, "initrd.xz"))
            && (NULL == grub_strstr(node->name, "initrd.gz"))
            )
        {
            if (filt > 0 && file->size <= g_ventoy_cpio_size + 2048)
            {
                debug("file size too small %d\n", (int)g_ventoy_cpio_size);
                grub_file_close(file);
                sizefilt++;
                continue;
            }
        }
        /* skip hdt.img */
        if (file->size <= VTOY_SIZE_1MB && grub_strcmp(node->name, "/boot/hdt.img") == 0)
        {
            continue;
        }
        if (grub_strcmp(file->fs->name, "iso9660") == 0)
        {
            node->iso_type = 0;
            node->override_offset = grub_iso9660_get_last_file_dirent_pos(file) + 2;
            
            grub_file_read(file, &data, 1); // just read for hook trigger
            node->offset = grub_iso9660_get_last_read_pos(file);
        }
        else
        {
            /* TBD */
        }
        node->size = file->size;
        g_valid_initrd_count++;
        grub_file_close(file);
    }
    *filtcnt = sizefilt;
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_linux_get_main_initrd_index(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int index = 0;
    char buf[32];
    initrd_info *node = NULL;
    
    (void)ctxt;
    (void)argc;
    (void)args;
    if (argc != 1)
    {
        return 1;
    }
    if (g_initrd_img_count == 1)
    {
        ventoy_set_env(args[0], "0");
        VENTOY_CMD_RETURN(GRUB_ERR_NONE);
    }
    for (node = g_initrd_img_list; node; node = node->next)
    {
        if (node->size <= 0)
        {
            continue;
        }
    
        if (grub_strstr(node->name, "ucode") || grub_strstr(node->name, "-firmware"))
        {
            index++;
            continue;
        }
        grub_snprintf(buf, sizeof(buf), "%d", index);
        ventoy_set_env(args[0], buf);
        break;
    }
    debug("main initrd index:%d\n", index);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_linux_locate_initrd(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int sizefilt = 0;
    (void)ctxt;
    (void)argc;
    (void)args;
    ventoy_linux_locate_initrd(1, &sizefilt);
    if (g_valid_initrd_count == 0 && sizefilt > 0)
    {
        ventoy_linux_locate_initrd(0, &sizefilt);
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static int ventoy_cpio_busybox64(cpio_newc_header *head, const char *file)
{
    char *name;
    int namelen;
    int offset;
    int count = 0;
    char filepath[128];
    grub_snprintf(filepath, sizeof(filepath), "ventoy/busybox/%s", file);
    
    name = (char *)(head + 1);
    while (name[0] && count < 2)
    {
        if (grub_strcmp(name, "ventoy/busybox/ash") == 0)
        {
            grub_memcpy(name, "ventoy/busybox/32h", 18);
            count++;
        }
        else if (grub_strcmp(name, filepath) == 0)
        {
            grub_memcpy(name, "ventoy/busybox/ash", 18);
            count++;
        }
        namelen = ventoy_cpio_newc_get_int(head->c_namesize);
        offset = sizeof(cpio_newc_header) + namelen;
        offset = ventoy_align(offset, 4);
        offset += ventoy_cpio_newc_get_int(head->c_filesize);
        offset = ventoy_align(offset, 4);
        
        head = (cpio_newc_header *)((char *)head + offset);
        name = (char *)(head + 1);
    }
    return 0;
}
grub_err_t ventoy_cmd_cpio_busybox_64(grub_extcmd_context_t ctxt, int argc, char **args)
{
    (void)ctxt;
    (void)argc;
    (void)args;
    debug("ventoy_cmd_busybox_64 %d\n", argc);
    ventoy_cpio_busybox64((cpio_newc_header *)g_ventoy_cpio_buf, args[0]);
    return 0;
}
grub_err_t ventoy_cmd_skip_svd(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int i;
    grub_file_t file;
    char buf[16];
    
    (void)ctxt;
    (void)argc;
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]);
    if (!file)
    {
        return grub_error(GRUB_ERR_BAD_ARGUMENT, "Can't open file %s\n", args[0]); 
    }
    for (i = 0; i < 10; i++)
    {
        buf[0] = 0;
        grub_file_seek(file, (17 + i) * 2048);
        grub_file_read(file, buf, 16);
        if (buf[0] == 2 && grub_strncmp(buf + 1, "CD001", 5) == 0)
        {
            debug("Find SVD at VD %d\n", i);
            g_svd_replace_offset = (17 + i) * 2048;
            break;
        }
    }
    if (i >= 10)
    {
        debug("SVD not found %d\n", (int)g_svd_replace_offset);
    }
    grub_file_close(file);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_append_ext_sector(grub_extcmd_context_t ctxt, int argc, char **args)
{
    (void)ctxt;
    (void)argc;
    (void)args;
    if (args[0][0] == '1')
    {
        g_append_ext_sector = 1;        
    }
    else
    {
        g_append_ext_sector = 0;
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_load_cpio(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int i;
    int rc;
    char *pos = NULL;
    char *template_file = NULL;
    char *template_buf = NULL;
    char *persistent_buf = NULL;
    char *injection_buf = NULL;
    dud *dudnode = NULL;
    char tmpname[128];
    const char *injection_file = NULL;
    grub_uint8_t *buf = NULL;
    grub_uint32_t mod;
    grub_uint32_t headlen;
    grub_uint32_t initrd_head_len;
    grub_uint32_t padlen;
    grub_uint32_t img_chunk_size;
    grub_uint32_t template_size = 0;
    grub_uint32_t persistent_size = 0;
    grub_uint32_t injection_size = 0;
    grub_uint32_t dud_size = 0;
    grub_file_t file;
    grub_file_t archfile;
    grub_file_t tmpfile;
    install_template *template_node = NULL;
    ventoy_img_chunk_list chunk_list;
    (void)ctxt;
    (void)argc;
    if (argc != 4)
    {
        return grub_error(GRUB_ERR_BAD_ARGUMENT, "Usage: %s cpiofile\n", cmd_raw_name); 
    }
    if (g_img_chunk_list.chunk == NULL || g_img_chunk_list.cur_chunk == 0)
    {
        return grub_error(GRUB_ERR_BAD_ARGUMENT, "image chunk is null\n");
    }
    img_chunk_size = g_img_chunk_list.cur_chunk * sizeof(ventoy_img_chunk);
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s/%s", args[0], VTOY_COMM_CPIO);
    if (!file)
    {
        return grub_error(GRUB_ERR_BAD_ARGUMENT, "Can't open file %s/%s\n", args[0], VTOY_COMM_CPIO); 
    }
    archfile = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s/%s", args[0], VTOY_ARCH_CPIO);
    if (!archfile)
    {
        return grub_error(GRUB_ERR_BAD_ARGUMENT, "Can't open file %s/%s\n", args[0], VTOY_ARCH_CPIO);
        grub_file_close(file);
    }
    debug("load %s %s success\n", VTOY_COMM_CPIO, VTOY_ARCH_CPIO);
    if (g_ventoy_cpio_buf)
    {
        grub_free(g_ventoy_cpio_buf);
        g_ventoy_cpio_buf = NULL;
        g_ventoy_cpio_size = 0;
    }
    rc = ventoy_plugin_get_persistent_chunklist(args[1], -1, &chunk_list);
    if (rc == 0 && chunk_list.cur_chunk > 0 && chunk_list.chunk)
    {
        persistent_size = chunk_list.cur_chunk * sizeof(ventoy_img_chunk);
        persistent_buf = (char *)(chunk_list.chunk);
    }
    template_file = ventoy_plugin_get_cur_install_template(args[1], &template_node);
    if (template_file)
    {
        debug("auto install template: <%s> <addr:%p> <len:%d>\n", 
            template_file, template_node->filebuf, template_node->filelen);
        
        template_size = template_node->filelen;
        template_buf = grub_malloc(template_size);
        if (template_buf)
        {
            grub_memcpy(template_buf, template_node->filebuf, template_size);
        }
    }
    else
    {
        debug("auto install script skipped or not configed %s\n", args[1]);
    }
    injection_file = ventoy_plugin_get_injection(args[1]);
    if (injection_file)
    {
        debug("injection archive: <%s>\n", injection_file);
        tmpfile = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s%s", args[2], injection_file);
        if (tmpfile)
        {
            debug("injection archive size:%d\n", (int)tmpfile->size);
            injection_size = tmpfile->size;
            injection_buf = grub_malloc(injection_size);
            if (injection_buf)
            {
                grub_file_read(tmpfile, injection_buf, injection_size);
            }
            grub_file_close(tmpfile);
        }
        else
        {
            debug("Failed to open injection archive %s%s\n", args[2], injection_file);
        }
    }
    else
    {
        debug("injection not configed %s\n", args[1]);
    }
    dudnode = ventoy_plugin_find_dud(args[1]);
    if (dudnode)
    {
        debug("dud file: <%d>\n", dudnode->dudnum);
        ventoy_plugin_load_dud(dudnode, args[2]);
        for (i = 0; i < dudnode->dudnum; i++)
        {
            if (dudnode->files[i].size > 0)
            {
                dud_size += dudnode->files[i].size + sizeof(cpio_newc_header);                
            }
        }
    }
    else
    {
        debug("dud not configed %s\n", args[1]);
    }
    g_ventoy_cpio_buf = grub_malloc(file->size + archfile->size + 40960 + template_size + 
        persistent_size + injection_size + dud_size + img_chunk_size);
    if (NULL == g_ventoy_cpio_buf)
    {
        grub_file_close(file);
        grub_file_close(archfile);
        return grub_error(GRUB_ERR_BAD_ARGUMENT, "Can't alloc memory %llu\n", file->size);
    }
    grub_file_read(file, g_ventoy_cpio_buf, file->size);
    buf = (grub_uint8_t *)(g_ventoy_cpio_buf + file->size - 4);
    while (*((grub_uint32_t *)buf) != 0x37303730)
    {
        buf -= 4;
    }
    grub_file_read(archfile, buf, archfile->size);
    buf += (archfile->size - 4);
    while (*((grub_uint32_t *)buf) != 0x37303730)
    {
        buf -= 4;
    }
    /* get initrd head len */
    initrd_head_len = ventoy_cpio_newc_fill_head(buf, 0, NULL, "initrd000.xx");
    /* step1: insert image chunk data to cpio */
    headlen = ventoy_cpio_newc_fill_head(buf, img_chunk_size, g_img_chunk_list.chunk, "ventoy/ventoy_image_map");
    buf += headlen + ventoy_align(img_chunk_size, 4);
    if (template_buf)
    {
        headlen = ventoy_cpio_newc_fill_head(buf, template_size, template_buf, "ventoy/autoinstall");
        buf += headlen + ventoy_align(template_size, 4);
        grub_check_free(template_buf);
    }
    if (persistent_size > 0 && persistent_buf)
    {
        headlen = ventoy_cpio_newc_fill_head(buf, persistent_size, persistent_buf, "ventoy/ventoy_persistent_map");
        buf += headlen + ventoy_align(persistent_size, 4);
        grub_check_free(persistent_buf);
    }
    if (injection_size > 0 && injection_buf)
    {
        headlen = ventoy_cpio_newc_fill_head(buf, injection_size, injection_buf, "ventoy/ventoy_injection");
        buf += headlen + ventoy_align(injection_size, 4);
        grub_free(injection_buf);
        injection_buf = NULL;
    }
    if (dud_size > 0)
    {
        for (i = 0; i < dudnode->dudnum; i++)
        {
            pos = grub_strrchr(dudnode->dudpath[i].path, '.');
            grub_snprintf(tmpname, sizeof(tmpname), "ventoy/ventoy_dud%d%s", i, (pos ? pos : ".iso"));
            dud_size = dudnode->files[i].size;
            headlen = ventoy_cpio_newc_fill_head(buf, dud_size, dudnode->files[i].buf, tmpname);
            buf += headlen + ventoy_align(dud_size, 4);
        }
    }
    /* step2: insert os param to cpio */
    headlen = ventoy_cpio_newc_fill_head(buf, 0, NULL, "ventoy/ventoy_os_param");
    padlen = sizeof(ventoy_os_param);
    g_ventoy_cpio_size = (grub_uint32_t)(buf - g_ventoy_cpio_buf) + headlen + padlen + initrd_head_len;
    mod = g_ventoy_cpio_size % 2048;
    if (mod)
    {
        g_ventoy_cpio_size += 2048 - mod;
        padlen += 2048 - mod;
    }
    /* update os param data size, the data will be updated before chain boot */
    ventoy_cpio_newc_fill_int(padlen, ((cpio_newc_header *)buf)->c_filesize, 8);
    g_ventoy_runtime_buf = (grub_uint8_t *)buf + headlen;
    /* step3: fill initrd cpio head, the file size will be updated before chain boot */
    g_ventoy_initrd_head = (cpio_newc_header *)(g_ventoy_runtime_buf + padlen);
    ventoy_cpio_newc_fill_head(g_ventoy_initrd_head, 0, NULL, "initrd000.xx");
    grub_file_close(file);
    grub_file_close(archfile);
    if (grub_strcmp(args[3], "busybox=64") == 0)
    {
        debug("cpio busybox proc %s\n", args[3]);
        ventoy_cpio_busybox64((cpio_newc_header *)g_ventoy_cpio_buf, "64h");
    }
    else if (grub_strcmp(args[3], "busybox=a64") == 0)
    {
        debug("cpio busybox proc %s\n", args[3]);
        ventoy_cpio_busybox64((cpio_newc_header *)g_ventoy_cpio_buf, "a64");
    }
    else if (grub_strcmp(args[3], "busybox=m64") == 0)
    {
        debug("cpio busybox proc %s\n", args[3]);
        ventoy_cpio_busybox64((cpio_newc_header *)g_ventoy_cpio_buf, "m64");
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_trailer_cpio(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int mod;
    int bufsize;
    int namelen;
    int offset;
    char *name;
    grub_uint8_t *bufend;
    cpio_newc_header *head;
    grub_file_t file;
    const grub_uint8_t trailler[124] = {
        0x30, 0x37, 0x30, 0x37, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x30, 0x30,
        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
        0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30,
        0x30, 0x30, 0x30, 0x30, 0x30, 0x42, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x54, 0x52,
        0x41, 0x49, 0x4C, 0x45, 0x52, 0x21, 0x21, 0x21, 0x00, 0x00, 0x00, 0x00 
    };
    (void)ctxt;
    (void)argc;
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s%s", args[0], args[1]);
    if (!file)
    {
        return 1;
    }
    grub_memset(g_ventoy_runtime_buf, 0, sizeof(ventoy_os_param));
    ventoy_fill_os_param(file, (ventoy_os_param *)g_ventoy_runtime_buf);
    grub_file_close(file);
    grub_memcpy(g_ventoy_initrd_head, trailler, sizeof(trailler));
    bufend = (grub_uint8_t *)g_ventoy_initrd_head + sizeof(trailler);
    bufsize = (int)(bufend - g_ventoy_cpio_buf);
    mod = bufsize % 512;
    if (mod)
    {
        grub_memset(bufend, 0, 512 - mod);
        bufsize += 512 - mod;
    }
    if (argc > 1 && grub_strcmp(args[2], "noinit") == 0)
    {
        head = (cpio_newc_header *)g_ventoy_cpio_buf;
        name = (char *)(head + 1);
        while (grub_strcmp(name, "TRAILER!!!"))
        {
            if (grub_strcmp(name, "init") == 0)
            {
                grub_memcpy(name, "xxxx", 4);
            }
            else if (grub_strcmp(name, "linuxrc") == 0)
            {
                grub_memcpy(name, "vtoyxrc", 7);
            }
            else if (grub_strcmp(name, "sbin") == 0)
            {
                grub_memcpy(name, "vtoy", 4);
            }
            else if (grub_strcmp(name, "sbin/init") == 0)
            {
                grub_memcpy(name, "vtoy/vtoy", 9);
            }
            namelen = ventoy_cpio_newc_get_int(head->c_namesize);
            offset = sizeof(cpio_newc_header) + namelen;
            offset = ventoy_align(offset, 4);
            offset += ventoy_cpio_newc_get_int(head->c_filesize);
            offset = ventoy_align(offset, 4);
            
            head = (cpio_newc_header *)((char *)head + offset);
            name = (char *)(head + 1);
        }
    }
    ventoy_memfile_env_set("ventoy_cpio", g_ventoy_cpio_buf, (ulonglong)bufsize);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_linux_chain_data(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int len = 0;
    int ventoy_compatible = 0;
    grub_uint32_t size = 0;
    grub_uint64_t isosize = 0;
    grub_uint32_t boot_catlog = 0;
    grub_uint32_t img_chunk_size = 0;
    grub_uint32_t override_count = 0;
    grub_uint32_t override_size = 0;
    grub_uint32_t virt_chunk_count = 0;
    grub_uint32_t virt_chunk_size = 0;
    grub_file_t file;
    grub_disk_t disk;
    const char *pLastChain = NULL;
    const char *compatible;
    ventoy_chain_head *chain;
    
    (void)ctxt;
    (void)argc;
    compatible = grub_env_get("ventoy_compatible");
    if (compatible && compatible[0] == 'Y')
    {
        ventoy_compatible = 1;
    }
    if ((NULL == g_img_chunk_list.chunk) || (0 == ventoy_compatible && g_ventoy_cpio_buf == NULL))
    {
        grub_printf("ventoy not ready\n");
        return 1;
    }
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]);
    if (!file)
    {
        return 1;
    }
    isosize = file->size;
    len = (int)grub_strlen(args[0]);
    if (len >= 4 && 0 == grub_strcasecmp(args[0] + len - 4, ".img"))
    {
        debug("boot catlog %u for img file\n", boot_catlog);
    }
    else
    {
        boot_catlog = ventoy_get_iso_boot_catlog(file);
        if (boot_catlog)
        {
            if (ventoy_is_efi_os() && (!ventoy_has_efi_eltorito(file, boot_catlog)))
            {
                grub_env_set("LoadIsoEfiDriver", "on");
            }
        }
        else
        {
            if (ventoy_is_efi_os())
            {
                grub_env_set("LoadIsoEfiDriver", "on");
            }
            else
            {
                return grub_error(GRUB_ERR_BAD_ARGUMENT, "File %s is not bootable", args[0]);
            }
        }
    }
    
    img_chunk_size = g_img_chunk_list.cur_chunk * sizeof(ventoy_img_chunk);
    override_count = ventoy_linux_get_override_chunk_count();
    virt_chunk_count = ventoy_linux_get_virt_chunk_count();
    
    if (ventoy_compatible)
    {
        size = sizeof(ventoy_chain_head) + img_chunk_size;
    }
    else
    {
        override_size = ventoy_linux_get_override_chunk_size();
        virt_chunk_size = ventoy_linux_get_virt_chunk_size();
        size = sizeof(ventoy_chain_head) + img_chunk_size + override_size + virt_chunk_size;
    }
    
    pLastChain = grub_env_get("vtoy_chain_mem_addr");
    if (pLastChain)
    {
        chain = (ventoy_chain_head *)grub_strtoul(pLastChain, NULL, 16);
        if (chain)
        {
            debug("free last chain memory %p\n", chain);
            grub_free(chain);
        }
    }
    chain = ventoy_alloc_chain(size);
    if (!chain)
    {
        grub_printf("Failed to alloc chain linux memory size %u\n", size);
        grub_file_close(file);
        return 1;
    }
    ventoy_memfile_env_set("vtoy_chain_mem", chain, (ulonglong)size);
    grub_memset(chain, 0, sizeof(ventoy_chain_head));
    /* part 1: os parameter */
    g_ventoy_chain_type = ventoy_chain_linux;
    ventoy_fill_os_param(file, &(chain->os_param));
    /* part 2: chain head */
    disk = file->device->disk;
    chain->disk_drive = disk->id;
    chain->disk_sector_size = (1 << disk->log_sector_size);
    chain->real_img_size_in_bytes = file->size;
    chain->virt_img_size_in_bytes = (file->size + 2047) / 2048 * 2048;
    chain->boot_catalog = boot_catlog;
    if (!ventoy_is_efi_os())
    {
        grub_file_seek(file, boot_catlog * 2048);
        grub_file_read(file, chain->boot_catalog_sector, sizeof(chain->boot_catalog_sector));
    }
    /* part 3: image chunk */
    chain->img_chunk_offset = sizeof(ventoy_chain_head);
    chain->img_chunk_num = g_img_chunk_list.cur_chunk;
    grub_memcpy((char *)chain + chain->img_chunk_offset, g_img_chunk_list.chunk, img_chunk_size);
    if (ventoy_compatible)
    {
        return 0;
    }
    /* part 4: override chunk */
    if (override_count > 0)
    {
        chain->override_chunk_offset = chain->img_chunk_offset + img_chunk_size;
        chain->override_chunk_num = override_count;
        ventoy_linux_fill_override_data(isosize, (char *)chain + chain->override_chunk_offset);        
    }
    /* part 5: virt chunk */
    if (virt_chunk_count > 0)
    {        
        chain->virt_chunk_offset = chain->override_chunk_offset + override_size;
        chain->virt_chunk_num = virt_chunk_count;
        ventoy_linux_fill_virt_data(isosize, chain);
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static char *ventoy_systemd_conf_tag(char *buf, const char *tag, int optional)
{
    int taglen = 0;
    char *start = NULL;
    char *nextline = NULL;
    taglen = grub_strlen(tag);
    for (start = buf; start; start = nextline)
    {
        nextline = ventoy_get_line(start);
        VTOY_SKIP_SPACE(start);
        if (grub_strncmp(start, tag, taglen) == 0 && (start[taglen] == ' ' || start[taglen] == '\t'))
        {
            start += taglen;
            VTOY_SKIP_SPACE(start); 
            return start;
        }
    }
    if (optional == 0)
    {
        debug("tag<%s> NOT found\n", tag);        
    }
    return NULL;
}
static int ventoy_systemd_conf_hook(const char *filename, const struct grub_dirhook_info *info, void *data)
{
    int oldpos = 0;
    char *tag = NULL;
    char *bkbuf = NULL;
    char *filebuf = NULL;
    grub_file_t file = NULL;
    systemd_menu_ctx *ctx = (systemd_menu_ctx *)data;
    debug("ventoy_systemd_conf_hook %s\n", filename);
    if (info->dir || NULL == grub_strstr(filename, ".conf"))
    {
        return 0;
    }
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s/loader/entries/%s", ctx->dev, filename);
    if (!file)
    {
        return 0;
    }
    filebuf = grub_zalloc(2 * file->size + 8);
    if (!filebuf)
    {
        goto out;
    }
    bkbuf = filebuf + file->size + 4;
    grub_file_read(file, bkbuf, file->size);
    oldpos = ctx->pos;
    /* title --> menuentry */
    grub_memcpy(filebuf, bkbuf, file->size);
    tag = ventoy_systemd_conf_tag(filebuf, "title", 0);
    vtoy_check_goto_out(tag);
    vtoy_len_ssprintf(ctx->buf, ctx->pos, ctx->len, "menuentry \"%s\" {\n", tag);
    /* linux xxx */
    grub_memcpy(filebuf, bkbuf, file->size);
    tag = ventoy_systemd_conf_tag(filebuf, "linux", 0);
    if (!tag)
    {
        ctx->pos = oldpos;
        goto out;
    }
    vtoy_len_ssprintf(ctx->buf, ctx->pos, ctx->len, "  echo \"Downloading kernel ...\"\n  linux %s ", tag);
    /* kernel options */
    grub_memcpy(filebuf, bkbuf, file->size);
    tag = ventoy_systemd_conf_tag(filebuf, "options", 0);
    vtoy_len_ssprintf(ctx->buf, ctx->pos, ctx->len, "%s \n", tag ? tag : "");
    
    /* initrd xxx xxx xxx */
    vtoy_len_ssprintf(ctx->buf, ctx->pos, ctx->len, "  echo \"Downloading initrd ...\"\n  initrd ");
    grub_memcpy(filebuf, bkbuf, file->size);
    tag = ventoy_systemd_conf_tag(filebuf, "initrd", 1);
    while (tag)
    {
        vtoy_len_ssprintf(ctx->buf, ctx->pos, ctx->len, "%s ", tag);
        tag = ventoy_systemd_conf_tag(tag + grub_strlen(tag) + 1, "initrd", 1);
    }
    vtoy_len_ssprintf(ctx->buf, ctx->pos, ctx->len, "\n  boot\n}\n");
out:
    grub_check_free(filebuf);
    grub_file_close(file);
    return 0;
}
grub_err_t ventoy_cmd_linux_systemd_menu(grub_extcmd_context_t ctxt, int argc, char **args)
{
    static char *buf = NULL;
    grub_fs_t fs;
    char *device_name = NULL;
    grub_device_t dev = NULL;
    systemd_menu_ctx ctx;
    
    (void)ctxt;
    (void)argc;
    if (!buf)
    {
        buf = grub_malloc(VTOY_LINUX_SYSTEMD_MENU_MAX_BUF);
        if (!buf)
        {
            goto end;
        }        
    }
    device_name = grub_file_get_device_name(args[0]);
    if (!device_name)
    {
        debug("failed to get device name %s\n", args[0]);
        goto end;
    }
    dev = grub_device_open(device_name);
    if (!dev)
    {
        debug("failed to open device %s\n", device_name);
        goto end;        
    }
    fs = grub_fs_probe(dev);
    if (!fs)
    {
        debug("failed to probe fs %d\n", grub_errno);
        goto end;
    }
    ctx.dev = args[0];
    ctx.buf = buf;
    ctx.pos = 0;
    ctx.len = VTOY_LINUX_SYSTEMD_MENU_MAX_BUF;
    fs->fs_dir(dev, "/loader/entries", ventoy_systemd_conf_hook, &ctx);
    ventoy_memfile_env_set(args[1], buf, (ulonglong)(ctx.pos));
end:
    grub_check_free(device_name);
    check_free(dev, grub_device_close);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static int ventoy_limine_path_convert(char *path)
{
    char newpath[256] = {0};
    if (grub_strncmp(path, "boot://2/", 9) == 0)
    {
        grub_snprintf(newpath, sizeof(newpath), "(vtimghd,2)/%s", path + 9);
    }
    else if (grub_strncmp(path, "boot://1/", 9) == 0)
    {
        grub_snprintf(newpath, sizeof(newpath), "(vtimghd,1)/%s", path + 9);
    }
    if (newpath[0])
    {
        grub_snprintf(path, 1024, "%s", newpath);
    }
    return 0;
}
grub_err_t ventoy_cmd_linux_limine_menu(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int pos = 0;
    int sub = 0;
    int len = VTOY_LINUX_SYSTEMD_MENU_MAX_BUF;
    char *filebuf = NULL;
    char *start = NULL;
    char *nextline = NULL;
    grub_file_t file = NULL;
    char *title = NULL;
    char *kernel = NULL;
    char *initrd = NULL;
    char *param = NULL;
    static char *buf = NULL;
    
    (void)ctxt;
    (void)argc;
    if (!buf)
    {
        buf = grub_malloc(len + 4 * 1024);
        if (!buf)
        {
            goto end;
        }        
    }
    title = buf + len;
    kernel = title + 1024;
    initrd = kernel + 1024;
    param = initrd + 1024;
    
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, args[0]);
    if (!file)
    {
        return 0;
    }
    filebuf = grub_zalloc(file->size + 8);
    if (!filebuf)
    {
        goto end;
    }
    grub_file_read(file, filebuf, file->size);
    grub_file_close(file);
    
    title[0] = kernel[0] = initrd[0] = param[0] = 0;
    for (start = filebuf; start; start = nextline)
    {
        nextline = ventoy_get_line(start);
        VTOY_SKIP_SPACE(start);
        if (start[0] == ':')
        {
            if (start[1] == ':')
            {
                grub_snprintf(title, 1024, "%s", start + 2);
            }
            else
            {
                if (sub)
                {
                    vtoy_len_ssprintf(buf, pos, len, "}\n");
                    sub = 0;
                }
                if (nextline && nextline[0] == ':' && nextline[1] == ':')
                {
                    vtoy_len_ssprintf(buf, pos, len, "submenu \"[+] %s\" {\n", start + 2);
                    sub = 1;
                    title[0] = 0;
                }
                else
                {
                    grub_snprintf(title, 1024, "%s", start + 1);                    
                }
            }
        }
        else if (grub_strncmp(start, "KERNEL_PATH=", 12) == 0)
        {
            grub_snprintf(kernel, 1024, "%s", start + 12);
        }
        else if (grub_strncmp(start, "MODULE_PATH=", 12) == 0)
        {
            grub_snprintf(initrd, 1024, "%s", start + 12);
        }
        else if (grub_strncmp(start, "KERNEL_CMDLINE=", 15) == 0)
        {
            grub_snprintf(param, 1024, "%s", start + 15);
        }
        if (title[0] && kernel[0] && initrd[0] && param[0])
        {
            ventoy_limine_path_convert(kernel);
            ventoy_limine_path_convert(initrd);
        
            vtoy_len_ssprintf(buf, pos, len, "menuentry \"%s\" {\n", title);
            vtoy_len_ssprintf(buf, pos, len, "  echo \"Downloading kernel ...\"\n  linux %s %s\n", kernel, param);
            vtoy_len_ssprintf(buf, pos, len, "  echo \"Downloading initrd ...\"\n  initrd %s\n", initrd);
            vtoy_len_ssprintf(buf, pos, len, "}\n");
        
            title[0] = kernel[0] = initrd[0] = param[0] = 0;
        }
    }
    if (sub)
    {
        vtoy_len_ssprintf(buf, pos, len, "}\n");
        sub = 0;
    }
    ventoy_memfile_env_set(args[1], buf, (ulonglong)pos);
end:
    grub_check_free(filebuf);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
 | 55,100 | 
	C | 
	.c | 1,733 | 23.747836 | 115 | 0.541953 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 623 | 
	ventoy_windows.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/ventoy_windows.c | 
	/******************************************************************************
 * ventoy_windows.c 
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <grub/types.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/disk.h>
#include <grub/device.h>
#include <grub/term.h>
#include <grub/partition.h>
#include <grub/file.h>
#include <grub/normal.h>
#include <grub/extcmd.h>
#include <grub/datetime.h>
#include <grub/i18n.h>
#include <grub/net.h>
#include <grub/time.h>
#include <grub/crypto.h>
#include <grub/ventoy.h>
#include "ventoy_def.h"
GRUB_MOD_LICENSE ("GPLv3+");
static int g_iso_fs_type = 0;
static int g_wim_total_patch_count = 0;
static int g_wim_valid_patch_count = 0;
static wim_patch *g_wim_patch_head = NULL;
static grub_uint64_t g_suppress_wincd_override_offset = 0;
static grub_uint32_t g_suppress_wincd_override_data = 0;
grub_uint8_t g_temp_buf[512];
grub_ssize_t lzx_decompress ( const void *data, grub_size_t len, void *buf );
grub_ssize_t xca_decompress ( const void *data, grub_size_t len, void *buf );
static wim_patch *ventoy_find_wim_patch(const char *path)
{
    int len = (int)grub_strlen(path);
    wim_patch *node = g_wim_patch_head;
    while (node)
    {
        if (len == node->pathlen && 0 == grub_strcmp(path, node->path))
        {
            return node;
        }
        node = node->next;
    }
    return NULL;
}
static int ventoy_collect_wim_patch(const char *bcdfile)
{
    int i, j, k;
    int rc = 1;
    grub_uint64_t magic;
    grub_file_t file = NULL;
    char *buf = NULL;
    wim_patch *node = NULL;
    char c;
    grub_uint8_t byte;
    char valid;
    char path[256];
    g_ventoy_case_insensitive = 1;
    file = grub_file_open(bcdfile, VENTOY_FILE_TYPE);
    g_ventoy_case_insensitive = 0;
    if (!file)
    {
        debug("Failed to open file %s\n", bcdfile);
        grub_errno = 0;
        goto end;
    }
    buf = grub_malloc(file->size + 8);
    if (!buf)
    {
        goto end;
    }
    grub_file_read(file, buf, file->size);
    for (i = 0; i < (int)file->size - 8; i++)
    {        
        if (buf[i + 8] != 0)
        {
            continue;
        }
        
        magic = *(grub_uint64_t *)(buf + i);
        
        /* .wim .WIM .Wim */
        if ((magic == 0x006D00690077002EULL) ||
            (magic == 0x004D00490057002EULL) ||
            (magic == 0x006D00690057002EULL))
        {
            for (j = i; j > 0; j-= 2)
            {
                if (*(grub_uint16_t *)(buf + j) == 0)
                {
                    break;
                }
            }
            if (j > 0)
            {
                byte = (grub_uint8_t)(*(grub_uint16_t *)(buf + j + 2));
                if (byte != '/' && byte != '\\')
                {
                    continue;
                }
                
                valid = 1;
                for (k = 0, j += 2; k < (int)sizeof(path) - 1 && j < i + 8; j += 2)
                {
                    byte = (grub_uint8_t)(*(grub_uint16_t *)(buf + j));
                    c = (char)byte;
                    if (byte > '~' || byte < ' ') /* not printable */
                    {
                        valid = 0;
                        break;
                    }
                    else if (c == '\\')
                    {
                        c = '/';
                    }
                    
                    path[k++] = c;
                }
                path[k++] = 0;
                debug("@@@@ Find wim flag:<%s>\n", path);
                if (0 == valid)
                {
                    debug("Invalid wim file %d\n", k);
                }
                else if (NULL == ventoy_find_wim_patch(path))
                {
                    node = grub_zalloc(sizeof(wim_patch));
                    if (node)
                    {
                        node->pathlen = grub_snprintf(node->path, sizeof(node->path), "%s", path);
                        debug("add patch <%s>\n", path);
                        
                        if (g_wim_patch_head)
                        {
                            node->next = g_wim_patch_head;
                        }
                        g_wim_patch_head = node;
                        g_wim_total_patch_count++;
                    }
                }
                else
                {
                    debug("wim <%s> already exist\n", path);
                }
            }
        }
    }
end:
    check_free(file, grub_file_close);
    grub_check_free(buf);
    return rc;
}
grub_err_t ventoy_cmd_wim_patch_count(grub_extcmd_context_t ctxt, int argc, char **args)
{
    char buf[32];
    
    (void)ctxt;
    (void)argc;
    (void)args;
    if (argc == 1)
    {
        grub_snprintf(buf, sizeof(buf), "%d", g_wim_total_patch_count);
        ventoy_set_env(args[0], buf);
    }
    
    return 0;
}
grub_err_t ventoy_cmd_collect_wim_patch(grub_extcmd_context_t ctxt, int argc, char **args)
{
    wim_patch *node = NULL;
    
    (void)ctxt;
    (void)argc;
    (void)args;
    if (argc != 2)
    {
        return 1;
    }
    debug("ventoy_cmd_collect_wim_patch %s %s\n", args[0], args[1]);
    if (grub_strcmp(args[0], "bcd") == 0)
    {
        ventoy_collect_wim_patch(args[1]);
        return 0;
    }
    if (NULL == ventoy_find_wim_patch(args[1]))
    {
        node = grub_zalloc(sizeof(wim_patch));
        if (node)
        {
            node->pathlen = grub_snprintf(node->path, sizeof(node->path), "%s", args[1]);
            debug("add patch <%s>\n", args[1]);
            
            if (g_wim_patch_head)
            {
                node->next = g_wim_patch_head;
            }
            g_wim_patch_head = node;
            g_wim_total_patch_count++;
        }
    }
    return 0;
}
grub_err_t ventoy_cmd_dump_wim_patch(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int i = 0;
    wim_patch *node = NULL;
    (void)ctxt;
    (void)argc;
    (void)args;
    for (node = g_wim_patch_head; node; node = node->next)
    {
        grub_printf("%d %s [%s]\n", i++, node->path, node->valid ? "SUCCESS" : "FAIL");
    }
    return 0;
}
static int wim_name_cmp(const char *search, grub_uint16_t *name, grub_uint16_t namelen)
{
    char c1 = vtoy_to_upper(*search);
    char c2 = vtoy_to_upper(*name);
    while (namelen > 0 && (c1 == c2))
    {
        search++;
        name++;
        namelen--;
        
        c1 = vtoy_to_upper(*search);
        c2 = vtoy_to_upper(*name);
    }
    if (namelen == 0 && *search == 0)
    {
        return 0;
    }
    return 1;
}
static int ventoy_is_pe64(grub_uint8_t *buffer)
{
    grub_uint32_t pe_off;
    if (buffer[0] != 'M' || buffer[1] != 'Z')
    {
        return 0;
    }
    
    pe_off = *(grub_uint32_t *)(buffer + 60);
    if (buffer[pe_off] != 'P' || buffer[pe_off + 1] != 'E')
    {
        return 0;
    }
    if (*(grub_uint16_t *)(buffer + pe_off + 24) == 0x020b)
    {
        return 1;
    }
    return 0;
}
grub_err_t ventoy_cmd_is_pe64(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int ret = 1;
    grub_file_t file;
    grub_uint8_t buf[512];
    
    (void)ctxt;
    (void)argc;
    file = grub_file_open(args[0], VENTOY_FILE_TYPE);
    if (!file)
    {
        return 1;
    }
    grub_memset(buf, 0, 512);
    grub_file_read(file, buf, 512);
    if (ventoy_is_pe64(buf))
    {
        debug("%s is PE64\n", args[0]);
        ret = 0;
    }
    else
    {
        debug("%s is PE32\n", args[0]);
    }
    grub_file_close(file);
    return ret;
}
grub_err_t ventoy_cmd_sel_wimboot(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int size;
    char *buf = NULL;
    char configfile[128];
    
    (void)ctxt;
    (void)argc;
    (void)args;
    debug("select wimboot argc:%d\n", argc);
    buf = (char *)grub_malloc(8192);
    if (!buf)
    {
        return 0;
    }
    size = (int)grub_snprintf(buf, 8192, 
        "menuentry \"Windows Setup (32-bit)\" {\n"
        "    set vtoy_wimboot_sel=32\n"
        "}\n"
        "menuentry \"Windows Setup (64-bit)\" {\n"
        "    set vtoy_wimboot_sel=64\n"
        "}\n"
        );
    buf[size] = 0;
    g_ventoy_menu_esc = 1;
    g_ventoy_suppress_esc = 1;
    g_ventoy_suppress_esc_default = 1;
    grub_snprintf(configfile, sizeof(configfile), "configfile mem:0x%llx:size:%d", (ulonglong)(ulong)buf, size);
    grub_script_execute_sourcecode(configfile);
    
    g_ventoy_menu_esc = 0;
    g_ventoy_suppress_esc = 0;
    grub_free(buf);
    if (g_ventoy_last_entry == 0)
    {
        debug("last entry=%d %s=32\n", g_ventoy_last_entry, args[0]);
        grub_env_set(args[0], "32");
    }
    else
    {
        debug("last entry=%d %s=64\n", g_ventoy_last_entry, args[0]);
        grub_env_set(args[0], "64");
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_wimdows_reset(grub_extcmd_context_t ctxt, int argc, char **args)
{
    wim_patch *next = NULL;
    wim_patch *node = g_wim_patch_head;
    (void)ctxt;
    (void)argc;
    (void)args;
    while (node)
    {
        next = node->next;
        grub_free(node);
        node = next;
    }
    g_wim_patch_head = NULL;
    g_wim_total_patch_count = 0;
    g_wim_valid_patch_count = 0;
    return 0;
}
static int ventoy_load_jump_exe(const char *path, grub_uint8_t **data, grub_uint32_t *size, wim_hash *hash)
{
    grub_uint32_t i;
    grub_uint32_t align;
    grub_file_t file;
    debug("windows load jump %s\n", path);
    
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", path);
    if (!file)
    {
        debug("Can't open file %s\n", path); 
        return 1;
    }
    align = ventoy_align((int)file->size, 2048);
    debug("file %s size:%d align:%u\n", path, (int)file->size, align);
    *size = (grub_uint32_t)file->size;
    *data = (grub_uint8_t *)grub_malloc(align);
    if ((*data) == NULL)
    {
        debug("Failed to alloc memory size %u\n", align);
        goto end;
    }
    grub_file_read(file, (*data), file->size);
    if (hash)
    {
        grub_crypto_hash(GRUB_MD_SHA1, hash->sha1, (*data), file->size);
        if (g_ventoy_debug)
        {
            debug("%s", "jump bin 64 hash: ");
            for (i = 0; i < sizeof(hash->sha1); i++)
            {
                ventoy_debug("%02x ", hash->sha1[i]);
            }
            ventoy_debug("\n");
        }
    }
end:
    grub_file_close(file);
    return 0;
}
static int ventoy_get_override_info(grub_file_t file, wim_tail *wim_data)
{
    grub_uint32_t start_block;
    grub_uint64_t file_offset;
    grub_uint64_t override_offset;
    grub_uint32_t override_len;
    grub_uint64_t fe_entry_size_offset;
    
    if (grub_strcmp(file->fs->name, "iso9660") == 0)
    {
        g_iso_fs_type = wim_data->iso_type = 0;
        override_len = sizeof(ventoy_iso9660_override);
        override_offset = grub_iso9660_get_last_file_dirent_pos(file) + 2;
        grub_file_read(file, &start_block, 1); // just read for hook trigger
        file_offset = grub_iso9660_get_last_read_pos(file);
        debug("iso9660 wim size:%llu override_offset:%llu file_offset:%llu\n", 
            (ulonglong)file->size, (ulonglong)override_offset, (ulonglong)file_offset);
    }
    else
    {
        g_iso_fs_type = wim_data->iso_type = 1;    
        override_len = sizeof(ventoy_udf_override);
        override_offset = grub_udf_get_last_file_attr_offset(file, &start_block, &fe_entry_size_offset);
        
        file_offset = grub_udf_get_file_offset(file);
        debug("UDF wim size:%llu override_offset:%llu file_offset:%llu start_block=%u\n", 
            (ulonglong)file->size, (ulonglong)override_offset, (ulonglong)file_offset, start_block);
    }
    wim_data->file_offset = file_offset;
    wim_data->udf_start_block = start_block;
    wim_data->fe_entry_size_offset = fe_entry_size_offset;
    wim_data->override_offset = override_offset;
    wim_data->override_len = override_len;
    return 0;
}
static int ventoy_read_resource(grub_file_t fp, wim_header *wimhdr, wim_resource_header *head, void **buffer)
{
    int decompress_len = 0;
    int total_decompress = 0;
    grub_uint32_t i = 0;
    grub_uint32_t chunk_num = 0;
    grub_uint32_t chunk_size = 0;
    grub_uint32_t last_chunk_size = 0;
    grub_uint32_t last_decompress_size = 0;
    grub_uint32_t cur_offset = 0;
    grub_uint8_t *cur_dst = NULL;
    grub_uint8_t *buffer_compress = NULL;
    grub_uint8_t *buffer_decompress = NULL;
    grub_uint32_t *chunk_offset = NULL;
    buffer_decompress = (grub_uint8_t *)grub_malloc(head->raw_size + head->size_in_wim);
    if (NULL == buffer_decompress)
    {
        return 0;
    }
    grub_file_seek(fp, head->offset);
    if (head->size_in_wim == head->raw_size)
    {
        grub_file_read(fp, buffer_decompress, head->size_in_wim);
        *buffer = buffer_decompress;
        return 0;
    }
    buffer_compress = buffer_decompress + head->raw_size;
    grub_file_read(fp, buffer_compress, head->size_in_wim);
    chunk_num = (head->raw_size + WIM_CHUNK_LEN - 1) / WIM_CHUNK_LEN;
    cur_offset = (chunk_num - 1) * 4;
    chunk_offset = (grub_uint32_t *)buffer_compress;
    //debug("%llu %llu chunk_num=%lu", (ulonglong)head->size_in_wim, (ulonglong)head->raw_size, chunk_num);
    
    cur_dst = buffer_decompress;
    
    for (i = 0; i < chunk_num - 1; i++)
    {
        chunk_size = (i == 0) ? chunk_offset[i] : chunk_offset[i] - chunk_offset[i - 1];
        if (WIM_CHUNK_LEN == chunk_size)
        {
            grub_memcpy(cur_dst, buffer_compress + cur_offset, chunk_size);
            decompress_len = (int)chunk_size; 
        }
        else
        {
            if (wimhdr->flags & FLAG_HEADER_COMPRESS_XPRESS)
            {
                decompress_len = (int)xca_decompress(buffer_compress + cur_offset, chunk_size, cur_dst);
            }
            else
            {
                decompress_len = (int)lzx_decompress(buffer_compress + cur_offset, chunk_size, cur_dst);                
            }
        }
        //debug("chunk_size:%u decompresslen:%d\n", chunk_size, decompress_len);
        
        total_decompress += decompress_len;
        cur_dst += decompress_len;
        cur_offset += chunk_size;
    }
    /* last chunk */
    last_chunk_size = (grub_uint32_t)(head->size_in_wim - cur_offset);
    last_decompress_size = head->raw_size - total_decompress;
    
    if (last_chunk_size < WIM_CHUNK_LEN && last_chunk_size == last_decompress_size)
    {
        debug("Last chunk %u uncompressed\n", last_chunk_size);
        grub_memcpy(cur_dst, buffer_compress + cur_offset, last_chunk_size);
        decompress_len = (int)last_chunk_size; 
    }
    else
    {
        if (wimhdr->flags & FLAG_HEADER_COMPRESS_XPRESS)
        {
            decompress_len = (int)xca_decompress(buffer_compress + cur_offset, head->size_in_wim - cur_offset, cur_dst);
        }
        else
        {
            decompress_len = (int)lzx_decompress(buffer_compress + cur_offset, head->size_in_wim - cur_offset, cur_dst);
        }
    }
    cur_dst += decompress_len;
    total_decompress += decompress_len;
    
    //debug("last chunk_size:%u decompresslen:%d tot:%d\n", last_chunk_size, decompress_len, total_decompress);
    if (cur_dst != buffer_decompress + head->raw_size)
    {
        debug("head->size_in_wim:%llu head->raw_size:%llu cur_dst:%p buffer_decompress:%p total_decompress:%d\n", 
            (ulonglong)head->size_in_wim, (ulonglong)head->raw_size, cur_dst, buffer_decompress, total_decompress);
        grub_free(buffer_decompress);
        return 1;
    }
    
    *buffer = buffer_decompress;
    return 0;
}
static wim_directory_entry * search_wim_dirent(wim_directory_entry *dir, const char *search_name)
{
    do 
    {
        if (dir->len && dir->name_len)
        {
            if (wim_name_cmp(search_name, (grub_uint16_t *)(dir + 1), dir->name_len / 2) == 0)
            {
                return dir;
            }
        }
        dir = (wim_directory_entry *)((grub_uint8_t *)dir + dir->len);
    } while(dir->len);
        
    return NULL;
}
static wim_directory_entry * search_full_wim_dirent
(
    void *meta_data, 
    wim_directory_entry *dir,
    const char **path    
)
{
    wim_directory_entry *subdir = NULL;
    wim_directory_entry *search = dir;
    while (*path)
    {
        subdir = (wim_directory_entry *)((char *)meta_data + search->subdir);
        search = search_wim_dirent(subdir, *path);
        path++;
    }
    
    return search;
}
static wim_lookup_entry * ventoy_find_look_entry(wim_header *header, wim_lookup_entry *lookup, wim_hash *hash)
{
    grub_uint32_t i = 0;
    
    for (i = 0; i < (grub_uint32_t)header->lookup.raw_size / sizeof(wim_lookup_entry); i++)
    {
        if (grub_memcmp(&lookup[i].hash, hash, sizeof(wim_hash)) == 0)
        {
            return lookup + i;
        }
    }
    return NULL;
}
static int parse_registry_setup_cmdline
(
    grub_file_t file, 
    wim_header *head, 
    wim_lookup_entry *lookup, 
    void *meta_data, 
    wim_directory_entry *dir, 
    char *buf, 
    grub_uint32_t buflen
)
{
    char c;
    int ret = 0;
    grub_uint32_t i = 0;    
    grub_uint32_t reglen = 0;
    wim_hash zerohash;
    reg_vk *regvk = NULL;
    wim_lookup_entry *look = NULL;
    wim_directory_entry *wim_dirent = NULL;
    char *decompress_data = NULL;
    const char *reg_path[] = { "Windows", "System32", "config", "SYSTEM", NULL };
    wim_dirent = search_full_wim_dirent(meta_data, dir, reg_path);
    debug("search reg SYSTEM %p\n", wim_dirent);
    if (!wim_dirent)
    {
        return 1;
    }
    grub_memset(&zerohash, 0, sizeof(zerohash));
    if (grub_memcmp(&zerohash, wim_dirent->hash.sha1, sizeof(wim_hash)) == 0)
    {
        return 2;
    }
    look = ventoy_find_look_entry(head, lookup, &wim_dirent->hash);
    if (!look)
    {
        return 3;
    }
    reglen = (grub_uint32_t)look->resource.raw_size;
    debug("find system lookup entry_id:%ld raw_size:%u\n", 
        ((long)look - (long)lookup) / sizeof(wim_lookup_entry), reglen);
    if (0 != ventoy_read_resource(file, head, &(look->resource), (void **)&(decompress_data)))
    {
        return 4;
    }
    if (grub_strncmp(decompress_data + 0x1000, "hbin", 4))
    {
        ret_goto_end(5);
    }
    for (i = 0x1000; i + sizeof(reg_vk) < reglen; i += 8)
    {
        regvk = (reg_vk *)(decompress_data + i);
        if (regvk->sig == 0x6B76 && regvk->namesize == 7 &&
            regvk->datatype == 1 && regvk->flag == 1)
        {
            if (grub_strncasecmp((char *)(regvk + 1), "cmdline", 7) == 0)
            {
                debug("find registry cmdline i:%u offset:(0x%x)%u size:(0x%x)%u\n", 
                        i, regvk->dataoffset, regvk->dataoffset, regvk->datasize, regvk->datasize);
                break;
            }
        }
    }
    if (i + sizeof(reg_vk) >= reglen || regvk == NULL)
    {
        ret_goto_end(6);
    }
    if (regvk->datasize == 0 || (regvk->datasize & 0x80000000) > 0 ||
        regvk->dataoffset == 0 || regvk->dataoffset == 0xFFFFFFFF)
    {
        ret_goto_end(7);
    }
    if (regvk->datasize / 2 >= buflen)
    {
        ret_goto_end(8);
    }
    debug("start offset is 0x%x(%u)\n", 0x1000 + regvk->dataoffset + 4, 0x1000 + regvk->dataoffset + 4);
    for (i = 0; i < regvk->datasize; i+=2)
    {
        c = (char)(*(grub_uint16_t *)(decompress_data + 0x1000 + regvk->dataoffset + 4 + i));
        *buf++ = c;
    }
    ret = 0;
end:
    grub_check_free(decompress_data);
    return ret;
}
static int parse_custom_setup_path(char *cmdline, const char **path, char *exefile)
{
    int i = 0;
    int len = 0;
    char *pos1 = NULL;
    char *pos2 = NULL;
    
    if ((cmdline[0] == 'x' || cmdline[0] == 'X') && cmdline[1] == ':')
    {
        pos1 = pos2 = cmdline + 3;
        while (i < VTOY_MAX_DIR_DEPTH && *pos2)
        {
            while (*pos2 && *pos2 != '\\' && *pos2 != '/')
            {
                pos2++;
            }
            path[i++] = pos1;
            
            if (*pos2 == 0)
            {                
                break;
            }
            *pos2 = 0;
            pos1 = pos2 + 1;
            pos2 = pos1;
        }
        if (i == 0 || i >= VTOY_MAX_DIR_DEPTH)
        {
            return 1;
        }
    }
    else
    {
        path[i++] = "Windows";
        path[i++] = "System32";
        path[i++] = cmdline;
    }
    pos1 = (char *)path[i - 1];
    while (*pos1 != ' ' && *pos1 != '\t' && *pos1)
    {
        pos1++;
    }
    *pos1 = 0;
    len = (int)grub_strlen(path[i - 1]);
    if (len < 4 || grub_strcasecmp(path[i - 1] + len - 4, ".exe") != 0)
    {
        grub_snprintf(exefile, 256, "%s.exe", path[i - 1]);
        path[i - 1] = exefile;            
    }
    debug("custom setup: %d <%s>\n", i, path[i - 1]);
    return 0;
}
static wim_directory_entry * search_replace_wim_dirent
(
    grub_file_t file, 
    wim_header *head, 
    wim_lookup_entry *lookup, 
    void *meta_data, 
    wim_directory_entry *dir
)
{
    int ret;
    char exefile[256] = {0};
    char cmdline[256] = {0};
    wim_directory_entry *wim_dirent = NULL;
    wim_directory_entry *pecmd_dirent = NULL;
    const char *peset_path[] = { "Windows", "System32", "peset.exe", NULL };
    const char *pecmd_path[] = { "Windows", "System32", "pecmd.exe", NULL };
    const char *winpeshl_path[] = { "Windows", "System32", "winpeshl.exe", NULL };
    const char *custom_path[VTOY_MAX_DIR_DEPTH + 1] = { NULL };
    pecmd_dirent = search_full_wim_dirent(meta_data, dir, pecmd_path);
    debug("search pecmd.exe %p\n", pecmd_dirent);
    if (pecmd_dirent)
    {
        ret = parse_registry_setup_cmdline(file, head, lookup, meta_data, dir, cmdline, sizeof(cmdline) - 1);
        if (0 == ret)
        {
            debug("registry setup cmdline:<%s>\n", cmdline);
            
            if (grub_strncasecmp(cmdline, "PECMD", 5) == 0)
            {
                wim_dirent = pecmd_dirent;
            }
            else if (grub_strncasecmp(cmdline, "PESET", 5) == 0)
            {
                wim_dirent = search_full_wim_dirent(meta_data, dir, peset_path);
                debug("search peset.exe %p\n", wim_dirent);
            }
            else if (grub_strncasecmp(cmdline, "WINPESHL", 8) == 0)
            {
                wim_dirent = search_full_wim_dirent(meta_data, dir, winpeshl_path);
                debug("search winpeshl.exe %p\n", wim_dirent);
            }
            else if (0 == parse_custom_setup_path(cmdline, custom_path, exefile))
            {
                wim_dirent = search_full_wim_dirent(meta_data, dir, custom_path);
                debug("search custom path %p\n", wim_dirent);
            }
            if (wim_dirent)
            {
                return wim_dirent;
            }
        }
        else
        {
            debug("registry setup cmdline failed : %d\n", ret);
        }
    }
    wim_dirent = pecmd_dirent;
    if (wim_dirent)
    {
        return wim_dirent;
    }
    wim_dirent = search_full_wim_dirent(meta_data, dir, winpeshl_path);
    debug("search winpeshl.exe %p\n", wim_dirent);
    if (wim_dirent)
    {
        return wim_dirent;
    }
    return NULL;
}
static wim_lookup_entry * ventoy_find_meta_entry(wim_header *header, wim_lookup_entry *lookup)
{
    grub_uint32_t i = 0;
    grub_uint32_t index = 0;;
    if ((header == NULL) || (lookup == NULL))
    {
        return NULL;
    }
    
    for (i = 0; i < (grub_uint32_t)header->lookup.raw_size / sizeof(wim_lookup_entry); i++)
    {
        if (lookup[i].resource.flags & RESHDR_FLAG_METADATA)
        {
            index++;
            if (index == header->boot_index)
            {
                return lookup + i;
            }
        }
    }
    return NULL;
}
static grub_uint64_t ventoy_get_stream_len(wim_directory_entry *dir)
{
    grub_uint16_t i;
    grub_uint64_t offset = 0;
    wim_stream_entry *stream = (wim_stream_entry *)((char *)dir + dir->len);
    for (i = 0; i < dir->streams; i++)
    {
        offset += stream->len;
        stream = (wim_stream_entry *)((char *)stream + stream->len);
    }
    return offset;
}
static int ventoy_update_stream_hash(wim_patch *patch, wim_directory_entry *dir)
{
    grub_uint16_t i;
    grub_uint64_t offset = 0;
    wim_stream_entry *stream = (wim_stream_entry *)((char *)dir + dir->len);
    for (i = 0; i < dir->streams; i++)
    {
        if (grub_memcmp(stream->hash.sha1, patch->old_hash.sha1, sizeof(wim_hash)) == 0)
        {
            debug("find target stream %u, name_len:%u upadte hash\n", i, stream->name_len);
            grub_memcpy(stream->hash.sha1, &(patch->wim_data.bin_hash), sizeof(wim_hash));
        }
        offset += stream->len;
        stream = (wim_stream_entry *)((char *)stream + stream->len);
    }
    return offset;
}
static int ventoy_update_all_hash(wim_patch *patch, void *meta_data, wim_directory_entry *dir)
{
    if ((meta_data == NULL) || (dir == NULL))
    {
        return 0;
    }
    if (dir->len < sizeof(wim_directory_entry))
    {
        return 0;
    }
    do
    {
        if (dir->subdir == 0 && grub_memcmp(dir->hash.sha1, patch->old_hash.sha1, sizeof(wim_hash)) == 0)
        {
            debug("find target file, name_len:%u upadte hash\n", dir->name_len);
            grub_memcpy(dir->hash.sha1, &(patch->wim_data.bin_hash), sizeof(wim_hash));
        }
        
        if (dir->subdir)
        {
            ventoy_update_all_hash(patch, meta_data, (wim_directory_entry *)((char *)meta_data + dir->subdir));
        }
        if (dir->streams)
        {
            ventoy_update_stream_hash(patch, dir);
            dir = (wim_directory_entry *)((char *)dir + dir->len + ventoy_get_stream_len(dir));
        }
        else
        {
            dir = (wim_directory_entry *)((char *)dir + dir->len);            
        }
    } while (dir->len >= sizeof(wim_directory_entry));
    return 0;
}
static int ventoy_cat_exe_file_data(wim_tail *wim_data, grub_uint32_t exe_len, grub_uint8_t *exe_data, int windatalen)
{
    int pe64 = 0;
    char file[256];
    grub_uint32_t jump_len = 0;
    grub_uint32_t jump_align = 0;
    grub_uint8_t *jump_data = NULL;
    pe64 = ventoy_is_pe64(exe_data);
    
    grub_snprintf(file, sizeof(file), "%s/vtoyjump%d.exe", grub_env_get("vtoy_path"), pe64 ? 64 : 32);
    ventoy_load_jump_exe(file, &jump_data, &jump_len, NULL);
    jump_align = ventoy_align(jump_len, 16);
    
    wim_data->jump_exe_len = jump_len;
    wim_data->bin_raw_len = jump_align + sizeof(ventoy_os_param) + windatalen + exe_len;
    wim_data->bin_align_len = ventoy_align(wim_data->bin_raw_len, 2048);
    
    wim_data->jump_bin_data = grub_malloc(wim_data->bin_align_len);
    if (wim_data->jump_bin_data)
    {
        grub_memcpy(wim_data->jump_bin_data, jump_data, jump_len);
        grub_memcpy(wim_data->jump_bin_data + jump_align + sizeof(ventoy_os_param) + windatalen, exe_data, exe_len);
    }
    debug("jump_exe_len:%u bin_raw_len:%u bin_align_len:%u\n", 
        wim_data->jump_exe_len, wim_data->bin_raw_len, wim_data->bin_align_len);
    
    return 0;
}
static int ventoy_get_windows_rtdata_len(const char *iso, int *flag)
{
    int size = 0;
    int template_file_len = 0;
    char *pos = NULL;
    char *script = NULL;
    install_template *template_node = NULL;
    *flag = 0;
    size = (int)sizeof(ventoy_windows_data);
    
    pos = grub_strstr(iso, "/");
    if (!pos)
    {
        return size;
    }
    
    script = ventoy_plugin_get_cur_install_template(pos, &template_node);
    if (script)
    {
        (*flag) |= WINDATA_FLAG_TEMPLATE;
        template_file_len = template_node->filelen;
    }
    return size + template_file_len;
}
static int ventoy_fill_windows_rtdata(void *buf, char *isopath, int dataflag)
{
    int template_len = 0;
    char *pos = NULL;
    char *end = NULL;
    char *script = NULL;
    const char *env = NULL;
    install_template *template_node = NULL;
    ventoy_windows_data *data = (ventoy_windows_data *)buf;
    grub_memset(data, 0, sizeof(ventoy_windows_data));
    env = grub_env_get("VTOY_WIN11_BYPASS_CHECK");
    if (env && env[0] == '1' && env[1] == 0)
    {
        data->windows11_bypass_check = 1;
    }
    
    env = grub_env_get("VTOY_WIN11_BYPASS_NRO");
    if (env && env[0] == '1' && env[1] == 0)
    {
        data->windows11_bypass_nro = 1;
    }
    pos = grub_strstr(isopath, "/");
    if (!pos)
    {
        return 1;
    }
    if (dataflag & WINDATA_FLAG_TEMPLATE)
    {
        script = ventoy_plugin_get_cur_install_template(pos, &template_node);
        if (script)
        {
            data->auto_install_len = template_len = template_node->filelen;
            debug("auto install script OK <%s> <len:%d>\n", script, template_len);
            end = ventoy_str_last(script, '/');
            grub_snprintf(data->auto_install_script, sizeof(data->auto_install_script) - 1, "%s", end ? end + 1 : script);
            grub_memcpy(data + 1, template_node->filebuf, template_len);
        }
    }
    else
    {
        debug("auto install script skipped or not configed %s\n", pos);
    }
    script = (char *)ventoy_plugin_get_injection(pos);
    if (script)
    {
        if (ventoy_check_file_exist("%s%s", ventoy_get_env("vtoy_iso_part"), script))
        {
            debug("injection archive <%s> OK\n", script);
            grub_snprintf(data->injection_archive, sizeof(data->injection_archive) - 1, "%s", script);
        }
        else
        {
            debug("injection archive <%s> NOT exist\n", script);
        }
    }
    else
    {
        debug("injection archive not configed %s\n", pos);
    }
    return 0;
}
static int ventoy_update_before_chain(ventoy_os_param *param, char *isopath)
{
    grub_uint32_t jump_align = 0;
    wim_lookup_entry *meta_look = NULL;
    wim_security_header *security = NULL;
    wim_directory_entry *rootdir = NULL;
    wim_header *head = NULL;
    wim_lookup_entry *lookup = NULL;
    wim_patch *node = NULL;
    wim_tail *wim_data = NULL;
    for (node = g_wim_patch_head; node; node = node->next)
    {
        if (0 == node->valid)
        {
            continue;
        }
        wim_data = &node->wim_data;
        head = &wim_data->wim_header;
        lookup = (wim_lookup_entry *)wim_data->new_lookup_data;
        jump_align = ventoy_align(wim_data->jump_exe_len, 16);
        if (wim_data->jump_bin_data)
        {
            grub_memcpy(wim_data->jump_bin_data + jump_align, param, sizeof(ventoy_os_param));        
            ventoy_fill_windows_rtdata(wim_data->jump_bin_data + jump_align + sizeof(ventoy_os_param), isopath, wim_data->windata_flag);
        }
        grub_crypto_hash(GRUB_MD_SHA1, wim_data->bin_hash.sha1, wim_data->jump_bin_data, wim_data->bin_raw_len);
        security = (wim_security_header *)wim_data->new_meta_data;
        if (security->len > 0)
        {
            rootdir = (wim_directory_entry *)(wim_data->new_meta_data + ((security->len + 7) & 0xFFFFFFF8U));
        }
        else
        {
            rootdir = (wim_directory_entry *)(wim_data->new_meta_data + 8);
        }
        /* update all winpeshl.exe dirent entry's hash */
        ventoy_update_all_hash(node, wim_data->new_meta_data, rootdir);
        /* update winpeshl.exe lookup entry data (hash/offset/length) */
        if (node->replace_look)
        {
            debug("update replace lookup entry_id:%ld\n", ((long)node->replace_look - (long)lookup) / sizeof(wim_lookup_entry));
            node->replace_look->resource.raw_size = wim_data->bin_raw_len;
            node->replace_look->resource.size_in_wim = wim_data->bin_raw_len;
            node->replace_look->resource.flags = 0;
            node->replace_look->resource.offset = wim_data->wim_align_size;
            grub_memcpy(node->replace_look->hash.sha1, wim_data->bin_hash.sha1, sizeof(wim_hash));
        }
        /* update metadata's hash */
        meta_look = ventoy_find_meta_entry(head, lookup);
        if (meta_look)
        {
            debug("find meta lookup entry_id:%ld\n", ((long)meta_look - (long)lookup) / sizeof(wim_lookup_entry));
            grub_memcpy(&meta_look->resource, &head->metadata, sizeof(wim_resource_header));
            grub_crypto_hash(GRUB_MD_SHA1, meta_look->hash.sha1, wim_data->new_meta_data, wim_data->new_meta_len);
        }
    }
    return 0;
}
static int ventoy_wimdows_locate_wim(const char *disk, wim_patch *patch, int windatalen)
{
    int rc;
    grub_uint16_t i;
    grub_file_t file;
    grub_uint32_t exe_len;
    grub_uint8_t *exe_data = NULL;
    grub_uint8_t *decompress_data = NULL;
    wim_lookup_entry *lookup = NULL;
    wim_security_header *security = NULL;
    wim_directory_entry *rootdir = NULL;
    wim_directory_entry *search = NULL;
    wim_stream_entry *stream = NULL;
    wim_header *head = &(patch->wim_data.wim_header);    
    wim_tail *wim_data = &patch->wim_data;
    
    debug("windows locate wim start %s\n", patch->path);
    g_ventoy_case_insensitive = 1;
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s%s", disk, patch->path);
    g_ventoy_case_insensitive = 0;
    
    if (!file)
    {
        debug("File %s%s NOT exist\n", disk, patch->path);
        return 1;
    }
    ventoy_get_override_info(file, &patch->wim_data);
    grub_file_seek(file, 0);
    grub_file_read(file, head, sizeof(wim_header));
    if (grub_memcmp(head->signature, WIM_HEAD_SIGNATURE, sizeof(head->signature)))
    {
        debug("Not a valid wim file %s\n", (char *)head->signature);
        grub_file_close(file);
        return 1;
    }
    if (head->flags & FLAG_HEADER_COMPRESS_LZMS)
    {
        debug("LZMS compress is not supported 0x%x\n", head->flags);
        grub_file_close(file);
        return 1;
    }
    rc = ventoy_read_resource(file, head, &head->metadata, (void **)&decompress_data);
    if (rc)
    {
        grub_printf("failed to read meta data %d\n", rc);
        grub_file_close(file);
        return 1;
    }
    security = (wim_security_header *)decompress_data;
    if (security->len > 0)
    {
        rootdir = (wim_directory_entry *)(decompress_data + ((security->len + 7) & 0xFFFFFFF8U));
    }
    else
    {
        rootdir = (wim_directory_entry *)(decompress_data + 8);
    }
    debug("read lookup offset:%llu size:%llu\n", (ulonglong)head->lookup.offset, (ulonglong)head->lookup.raw_size);
    lookup = grub_malloc(head->lookup.raw_size);
    grub_file_seek(file, head->lookup.offset);
    grub_file_read(file, lookup, head->lookup.raw_size);
    /* search winpeshl.exe dirent entry */
    search = search_replace_wim_dirent(file, head, lookup, decompress_data, rootdir);
    if (!search)
    {
        debug("Failed to find replace file %p\n", search);
        grub_file_close(file);
        return 1;
    }
    
    debug("find replace file at %p\n", search);
    grub_memset(&patch->old_hash, 0, sizeof(wim_hash));
    if (grub_memcmp(&patch->old_hash, search->hash.sha1, sizeof(wim_hash)) == 0)
    {
        debug("search hash all 0, now do deep search\n");
        stream = (wim_stream_entry *)((char *)search + search->len);
        for (i = 0; i < search->streams; i++)
        {
            if (stream->name_len == 0)
            {
                grub_memcpy(&patch->old_hash, stream->hash.sha1, sizeof(wim_hash));
                debug("new search hash: %02x %02x %02x %02x %02x %02x %02x %02x\n", 
                    ventoy_varg_8(patch->old_hash.sha1));
                break;
            }
            stream = (wim_stream_entry *)((char *)stream + stream->len);
        }
    }
    else
    {
        grub_memcpy(&patch->old_hash, search->hash.sha1, sizeof(wim_hash));        
    }
    
    /* find and extact winpeshl.exe */
    patch->replace_look = ventoy_find_look_entry(head, lookup, &patch->old_hash);
    if (patch->replace_look)
    {
        exe_len = (grub_uint32_t)patch->replace_look->resource.raw_size;
        debug("find replace lookup entry_id:%ld raw_size:%u\n", 
            ((long)patch->replace_look - (long)lookup) / sizeof(wim_lookup_entry), exe_len);
        if (0 == ventoy_read_resource(file, head, &(patch->replace_look->resource), (void **)&(exe_data)))
        {
            ventoy_cat_exe_file_data(wim_data, exe_len, exe_data, windatalen);
            grub_free(exe_data);
        }
        else
        {
            debug("failed to read replace file meta data %u\n", exe_len);
        }
    }
    else
    {
        debug("failed to find lookup entry for replace file %02x %02x %02x %02x\n", 
            ventoy_varg_4(patch->old_hash.sha1));
    }
    wim_data->wim_raw_size = (grub_uint32_t)file->size;
    wim_data->wim_align_size = ventoy_align(wim_data->wim_raw_size, 2048);
    
    grub_check_free(wim_data->new_meta_data);
    wim_data->new_meta_data = decompress_data;
    wim_data->new_meta_len = head->metadata.raw_size;
    wim_data->new_meta_align_len = ventoy_align(wim_data->new_meta_len, 2048);
    
    grub_check_free(wim_data->new_lookup_data);
    wim_data->new_lookup_data = (grub_uint8_t *)lookup;
    wim_data->new_lookup_len = (grub_uint32_t)head->lookup.raw_size;
    wim_data->new_lookup_align_len = ventoy_align(wim_data->new_lookup_len, 2048);
    head->metadata.flags = RESHDR_FLAG_METADATA;
    head->metadata.offset = wim_data->wim_align_size + wim_data->bin_align_len;
    head->metadata.size_in_wim = wim_data->new_meta_len;
    head->metadata.raw_size = wim_data->new_meta_len;
    head->lookup.flags = 0;
    head->lookup.offset = head->metadata.offset + wim_data->new_meta_align_len;
    head->lookup.size_in_wim = wim_data->new_lookup_len;
    head->lookup.raw_size = wim_data->new_lookup_len;
    grub_file_close(file);
    debug("%s", "windows locate wim finish\n");
    return 0;
}
grub_err_t ventoy_cmd_sel_winpe_wim(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int i = 0;
    int pos = 0;
    int len = 0;
    int find = 0;
    char *cmd = NULL;
    wim_patch *node = NULL;
    wim_patch *tmp = NULL;
    grub_file_t file = NULL;
    wim_header *head = NULL;
    char cfgfile[128];
    (void)ctxt;
    (void)argc;
    len = 8 * VTOY_SIZE_1KB;
    cmd = (char *)grub_malloc(len + sizeof(wim_header));
    if (!cmd)
    {
        return 1;
    }
    head = (wim_header *)(cmd + len);
    grub_env_unset("vtoy_pe_wim_path");
    for (node = g_wim_patch_head; node; node = node->next)
    {
        find = 0;
        for (tmp = g_wim_patch_head; tmp != node; tmp = tmp->next)
        {
            if (tmp->valid && grub_strcasecmp(tmp->path, node->path) == 0)
            {
                find = 1;
                break;
            }
        }
        if (find)
        {
            continue;
        }
        
        g_ventoy_case_insensitive = 1;
        file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s%s", args[0], node->path);
        g_ventoy_case_insensitive = 0;
        if (!file)
        {
            debug("File %s%s NOT exist\n", args[0], node->path);
            continue;
        }
        grub_file_read(file, head, sizeof(wim_header));
        if (grub_memcmp(head->signature, WIM_HEAD_SIGNATURE, sizeof(head->signature)))
        {
            debug("Not a valid wim file %s\n", (char *)head->signature);
            grub_file_close(file);
            continue;
        }
        if (head->flags & FLAG_HEADER_COMPRESS_LZMS)
        {
            debug("LZMS compress is not supported 0x%x\n", head->flags);
            grub_file_close(file);
            continue;
        }
        grub_file_close(file);
        node->valid = 1;
        vtoy_len_ssprintf(cmd, pos, len, "menuentry \"%s\" --class=\"sel_wim\"  {\n  echo \"\"\n}\n", node->path);
    }
    if (pos > 0)
    {
        g_ventoy_menu_esc = 1;
        g_ventoy_suppress_esc = 1;
        g_ventoy_suppress_esc_default = 0;
        g_ventoy_secondary_menu_on = 1;
        grub_snprintf(cfgfile, sizeof(cfgfile), "configfile mem:0x%llx:size:%d", (ulonglong)(ulong)cmd, pos);
        grub_script_execute_sourcecode(cfgfile);   
        g_ventoy_menu_esc = 0;
        g_ventoy_suppress_esc = 0;
        g_ventoy_suppress_esc_default = 1;
        g_ventoy_secondary_menu_on = 0;
        for (node = g_wim_patch_head; node; node = node->next)
        {
            if (node->valid)
            {
                if (i == g_ventoy_last_entry)
                {
                    grub_env_set("vtoy_pe_wim_path", node->path);
                    break;
                }
                i++;
            }
        }
    }
    grub_free(cmd);
    return 0;
}
grub_err_t ventoy_cmd_locate_wim_patch(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int datalen = 0;
    int dataflag = 0;
    wim_patch *node = g_wim_patch_head;
    (void)ctxt;
    (void)argc;
    (void)args;
    datalen = ventoy_get_windows_rtdata_len(args[1], &dataflag);
    while (node)
    {
        node->wim_data.windata_flag = dataflag;
        if (0 == ventoy_wimdows_locate_wim(args[0], node, datalen))
        {
            node->valid = 1;
            g_wim_valid_patch_count++;
        }
        node = node->next;
    }
    return 0;
}
static grub_uint32_t ventoy_get_override_chunk_num(void)
{
    grub_uint32_t chunk_num = 0;
    
    if (g_iso_fs_type == 0)
    {
        /* ISO9660: */
        /* per wim */
        /* 1: file_size and file_offset */
        /* 2: new wim file header */
        chunk_num = g_wim_valid_patch_count * 2;
    }
    else
    {
        /* UDF: */
        /* global: */
        /* 1: block count in Partition Descriptor */
        /* per wim */
        /* 1: file_size in file_entry or extend_file_entry */
        /* 2: data_size and position in extend data short ad */
        /* 3: new wim file header */
        chunk_num = g_wim_valid_patch_count * 3 + 1;
    }
    if (g_suppress_wincd_override_offset > 0)
    {
        chunk_num++;
    }
    return chunk_num;
}
static void ventoy_fill_suppress_wincd_override_data(void *override)
{
    ventoy_override_chunk *cur = (ventoy_override_chunk *)override;
    cur->override_size = 4;
    cur->img_offset = g_suppress_wincd_override_offset;
    grub_memcpy(cur->override_data, &g_suppress_wincd_override_data, cur->override_size);
}
static void ventoy_windows_fill_override_data_iso9660(    grub_uint64_t isosize, void *override)
{
    grub_uint64_t sector;
    grub_uint32_t new_wim_size;
    ventoy_override_chunk *cur;
    wim_patch *node = NULL;
    wim_tail *wim_data = NULL;
    ventoy_iso9660_override *dirent = NULL;
    sector = (isosize + 2047) / 2048;
    cur = (ventoy_override_chunk *)override;
    if (g_suppress_wincd_override_offset > 0)
    {
        ventoy_fill_suppress_wincd_override_data(cur);
        cur++;
    }
    debug("ventoy_windows_fill_override_data_iso9660 %lu\n", (ulong)isosize);
    for (node = g_wim_patch_head; node; node = node->next)
    {
        wim_data = &node->wim_data;
        if (0 == node->valid)
        {
            continue;
        }
        
        new_wim_size = wim_data->wim_align_size + wim_data->bin_align_len + 
                wim_data->new_meta_align_len + wim_data->new_lookup_align_len;
        dirent = (ventoy_iso9660_override *)wim_data->override_data;
        dirent->first_sector    = (grub_uint32_t)sector;
        dirent->size            = new_wim_size;
        dirent->first_sector_be = grub_swap_bytes32(dirent->first_sector);
        dirent->size_be         = grub_swap_bytes32(dirent->size);
        sector += (new_wim_size / 2048);
        /* override 1: position and length in dirent */
        cur->img_offset = wim_data->override_offset;
        cur->override_size = wim_data->override_len;
        grub_memcpy(cur->override_data, wim_data->override_data, cur->override_size);
        cur++;
        /* override 2: new wim file header */
        cur->img_offset = wim_data->file_offset;
        cur->override_size = sizeof(wim_header);
        grub_memcpy(cur->override_data, &(wim_data->wim_header), cur->override_size);
        cur++;
    }
    return;
}
static int ventoy_windows_fill_udf_short_ad(grub_file_t isofile, grub_uint32_t curpos, 
    wim_tail *wim_data, grub_uint32_t new_wim_size)
{
    int i;
    grub_uint32_t total = 0;
    grub_uint32_t left_size = 0;
    ventoy_udf_override *udf = NULL;
    ventoy_udf_override tmp[4];
    
    grub_memset(tmp, 0, sizeof(tmp));
    grub_file_seek(isofile, wim_data->override_offset);
    grub_file_read(isofile, tmp, sizeof(tmp));
    left_size = new_wim_size;
    udf = (ventoy_udf_override *)wim_data->override_data;
    for (i = 0; i < 4; i++)
    {
        total += tmp[i].length;
        if (total >= wim_data->wim_raw_size)
        {
            udf->length   = left_size;
            udf->position = curpos;
            return 0;
        }
        else
        {
            udf->length   = tmp[i].length;
            udf->position = curpos;
        }
        left_size -= tmp[i].length;
        curpos += udf->length / 2048;
        udf++;
        wim_data->override_len += sizeof(ventoy_udf_override);
    }
    debug("######## Too many udf ad ######\n");
    return 1;
}
static void ventoy_windows_fill_override_data_udf(grub_file_t isofile, void *override)
{
    grub_uint32_t data32;
    grub_uint64_t data64;
    grub_uint64_t sector;
    grub_uint32_t new_wim_size;
    grub_uint64_t total_wim_size = 0;
    grub_uint32_t udf_start_block = 0;
    ventoy_override_chunk *cur;
    wim_patch *node = NULL;
    wim_tail *wim_data = NULL;
    sector = (isofile->size + 2047) / 2048;
    cur = (ventoy_override_chunk *)override;
    
    if (g_suppress_wincd_override_offset > 0)
    {
        ventoy_fill_suppress_wincd_override_data(cur);
        cur++;
    }
    debug("ventoy_windows_fill_override_data_udf %lu\n", (ulong)isofile->size);
    for (node = g_wim_patch_head; node; node = node->next)
    {
        wim_data = &node->wim_data;
        if (node->valid)
        {
            if (udf_start_block == 0)
            {
                udf_start_block = wim_data->udf_start_block;
            }
            new_wim_size = wim_data->wim_align_size + wim_data->bin_align_len + 
                wim_data->new_meta_align_len + wim_data->new_lookup_align_len;
            total_wim_size += new_wim_size;
        }
    }
    //override 1: sector number in pd data 
    cur->img_offset = grub_udf_get_last_pd_size_offset();
    cur->override_size = 4;
    data32 = sector - udf_start_block + (total_wim_size / 2048);
    grub_memcpy(cur->override_data, &(data32), 4);
    for (node = g_wim_patch_head; node; node = node->next)
    {
        wim_data = &node->wim_data;
        if (0 == node->valid)
        {
            continue;
        }
        
        new_wim_size = wim_data->wim_align_size + wim_data->bin_align_len + 
                wim_data->new_meta_align_len + wim_data->new_lookup_align_len;
        //override 2: filesize in file_entry
        cur++;
        cur->img_offset = wim_data->fe_entry_size_offset;
        cur->override_size = 8;
        data64 = new_wim_size;
        grub_memcpy(cur->override_data, &(data64), 8);
        /* override 3: position and length in extend data */
        ventoy_windows_fill_udf_short_ad(isofile, (grub_uint32_t)sector - udf_start_block, wim_data, new_wim_size);
        sector += (new_wim_size / 2048);
        
        cur++;
        cur->img_offset = wim_data->override_offset;
        cur->override_size = wim_data->override_len;
        grub_memcpy(cur->override_data, wim_data->override_data, cur->override_size);
        /* override 4: new wim file header */
        cur++;
        cur->img_offset = wim_data->file_offset;
        cur->override_size = sizeof(wim_header);
        grub_memcpy(cur->override_data, &(wim_data->wim_header), cur->override_size);
    }
    return;
}
static grub_uint32_t ventoy_windows_get_virt_data_size(void)
{
    grub_uint32_t size = 0;
    wim_tail *wim_data = NULL;
    wim_patch *node = g_wim_patch_head;
    
    while (node)
    {
        if (node->valid)
        {
            wim_data = &node->wim_data;
            size += sizeof(ventoy_virt_chunk) + wim_data->bin_align_len + 
                    wim_data->new_meta_align_len + wim_data->new_lookup_align_len;
        }
        node = node->next;
    }
    
    return size;
}
static void ventoy_windows_fill_virt_data(    grub_uint64_t isosize, ventoy_chain_head *chain)
{
    grub_uint64_t sector;
    grub_uint32_t offset;
    grub_uint32_t wim_secs;
    grub_uint32_t mem_secs;
    char *override = NULL;
    ventoy_virt_chunk *cur = NULL;
    wim_tail *wim_data = NULL;
    wim_patch *node = NULL;    
    sector = (isosize + 2047) / 2048;
    offset = sizeof(ventoy_virt_chunk) * g_wim_valid_patch_count;
    override = (char *)chain + chain->virt_chunk_offset;
    cur = (ventoy_virt_chunk *)override;
    for (node = g_wim_patch_head; node; node = node->next)
    {
        if (0 == node->valid)
        {
            continue;
        }
        wim_data = &node->wim_data;
        wim_secs = wim_data->wim_align_size / 2048;
        mem_secs = (wim_data->bin_align_len + wim_data->new_meta_align_len + wim_data->new_lookup_align_len) / 2048;
        cur->remap_sector_start = sector;
        cur->remap_sector_end   = cur->remap_sector_start + wim_secs;
        cur->org_sector_start   = (grub_uint32_t)(wim_data->file_offset / 2048);
        
        cur->mem_sector_start   = cur->remap_sector_end;
        cur->mem_sector_end     = cur->mem_sector_start + mem_secs;
        cur->mem_sector_offset  = offset;
        sector += wim_secs + mem_secs;
        cur++;
        grub_memcpy(override + offset, wim_data->jump_bin_data, wim_data->bin_raw_len);
        offset += wim_data->bin_align_len;
        grub_memcpy(override + offset, wim_data->new_meta_data, wim_data->new_meta_len);
        offset += wim_data->new_meta_align_len;
        
        grub_memcpy(override + offset, wim_data->new_lookup_data, wim_data->new_lookup_len);
        offset += wim_data->new_lookup_align_len;
        chain->virt_img_size_in_bytes += wim_data->wim_align_size + 
                                         wim_data->bin_align_len + 
                                         wim_data->new_meta_align_len + 
                                         wim_data->new_lookup_align_len;
    }
    return;
}
static int ventoy_windows_drive_map(ventoy_chain_head *chain, int vlnk)
{
    int hd1 = 0;
    grub_disk_t disk;
        
    debug("drive map begin <%p> <%d> ...\n", chain, vlnk);
    disk = grub_disk_open("hd1");
    if (disk)
    {
        grub_disk_close(disk);
        hd1 = 1;
        debug("BIOS hd1 exist\n");
    }
    else
    {
        debug("failed to open disk %s\n", "hd1");
    }
    if (vlnk)
    {
        if (g_ventoy_disk_bios_id == 0x80 && hd1)
        {
            debug("drive map needed vlnk %p\n", disk);
            chain->drive_map = 0x81;
        }
    }
    else if (chain->disk_drive == 0x80)
    {
        if (hd1)
        {
            debug("drive map needed normal %p\n", disk);
            chain->drive_map = 0x81;
        }
    }
    else
    {
        debug("no need to map 0x%x\n", chain->disk_drive);
    }
    return 0;
}
static int ventoy_suppress_windows_cd_prompt(void)
{
    int rc = 1;
    const char  *cdprompt = NULL;
    grub_uint64_t readpos = 0;
    grub_file_t file = NULL;
    grub_uint8_t data[32];
    cdprompt = ventoy_get_env("VTOY_WINDOWS_CD_PROMPT");
    if (cdprompt && cdprompt[0] == '1' && cdprompt[1] == 0)
    {
        debug("VTOY_WINDOWS_CD_PROMPT:<%s>\n", cdprompt);
        return 0;
    }
    g_ventoy_case_insensitive = 1;
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s/boot/bootfix.bin", "(loop)");
    g_ventoy_case_insensitive = 0;
    if (!file)
    {
        debug("Failed to open %s\n", "bootfix.bin");
        goto end;
    }
    grub_file_read(file, data, 32);
    if (file->fs && file->fs->name && grub_strcmp(file->fs->name, "udf") == 0)
    {
        readpos = grub_udf_get_file_offset(file);
    }
    else
    {
        readpos = grub_iso9660_get_last_read_pos(file);
    }
    debug("bootfix.bin readpos:%lu (sector:%lu)  data: %02x %02x %02x %02x\n", 
        (ulong)readpos, (ulong)readpos / 2048, data[24], data[25], data[26], data[27]);
    if (*(grub_uint32_t *)(data + 24) == 0x13cd0080)
    {
        g_suppress_wincd_override_offset = readpos + 24;
        g_suppress_wincd_override_data = 0x13cd00fd;
        rc = 0;
    }
    debug("g_suppress_wincd_override_offset:%lu\n", (ulong)g_suppress_wincd_override_offset);
end:
    check_free(file, grub_file_close);
    return rc;
}
static int ventoy_extract_init_exe(char *wimfile, grub_uint8_t **pexe_data, grub_uint32_t *pexe_len, char *exe_name)
{
    int rc;
    int ret = 1;
    grub_uint16_t i;
    grub_file_t file = NULL;
    grub_uint32_t exe_len = 0;
    wim_header *head = NULL;
    grub_uint16_t *uname = NULL;
    grub_uint8_t *exe_data = NULL;
    grub_uint8_t *decompress_data = NULL;
    wim_lookup_entry *lookup = NULL;
    wim_security_header *security = NULL;
    wim_directory_entry *rootdir = NULL;
    wim_directory_entry *search = NULL;
    wim_stream_entry *stream = NULL;
    wim_lookup_entry *replace_look = NULL;
    wim_header wimhdr;
    wim_hash hashdata;
    head = &wimhdr;
    file = grub_file_open(wimfile, VENTOY_FILE_TYPE);
    if (!file)
    {
        goto out;
    }
    grub_file_read(file, head, sizeof(wim_header));
    rc = ventoy_read_resource(file, head, &head->metadata, (void **)&decompress_data);
    if (rc)
    {
        grub_printf("failed to read meta data %d\n", rc);
        goto out;
    }
    security = (wim_security_header *)decompress_data;
    if (security->len > 0)
    {
        rootdir = (wim_directory_entry *)(decompress_data + ((security->len + 7) & 0xFFFFFFF8U));
    }
    else
    {
        rootdir = (wim_directory_entry *)(decompress_data + 8);
    }
    debug("read lookup offset:%llu size:%llu\n", (ulonglong)head->lookup.offset, (ulonglong)head->lookup.raw_size);
    lookup = grub_malloc(head->lookup.raw_size);
    grub_file_seek(file, head->lookup.offset);
    grub_file_read(file, lookup, head->lookup.raw_size);
    /* search winpeshl.exe dirent entry */
    search = search_replace_wim_dirent(file, head, lookup, decompress_data, rootdir);
    if (!search)
    {
        debug("Failed to find replace file %p\n", search);
        goto out;
    }
    
    uname = (grub_uint16_t *)(search + 1);
    for (i = 0; i < search->name_len / 2 && i < 200; i++)
    {
        exe_name[i] = (char)uname[i];
    }
    exe_name[i] = 0;
    debug("find replace file at %p <%s>\n", search, exe_name);
    grub_memset(&hashdata, 0, sizeof(wim_hash));
    if (grub_memcmp(&hashdata, search->hash.sha1, sizeof(wim_hash)) == 0)
    {
        debug("search hash all 0, now do deep search\n");
        stream = (wim_stream_entry *)((char *)search + search->len);
        for (i = 0; i < search->streams; i++)
        {
            if (stream->name_len == 0)
            {
                grub_memcpy(&hashdata, stream->hash.sha1, sizeof(wim_hash));
                debug("new search hash: %02x %02x %02x %02x %02x %02x %02x %02x\n", 
                    ventoy_varg_8(hashdata.sha1));
                break;
            }
            stream = (wim_stream_entry *)((char *)stream + stream->len);
        }
    }
    else
    {
        grub_memcpy(&hashdata, search->hash.sha1, sizeof(wim_hash));        
    }
    /* find and extact winpeshl.exe */
    replace_look = ventoy_find_look_entry(head, lookup, &hashdata);
    if (replace_look)
    {
        exe_len = (grub_uint32_t)replace_look->resource.raw_size;
        debug("find replace lookup entry_id:%ld raw_size:%u\n", 
            ((long)replace_look - (long)lookup) / sizeof(wim_lookup_entry), exe_len);
        if (0 != ventoy_read_resource(file, head, &(replace_look->resource), (void **)&(exe_data)))
        {
            exe_len = 0;
            exe_data = NULL;
            debug("failed to read replace file meta data %u\n", exe_len);
        }
    }
    else
    {
        debug("failed to find lookup entry for replace file %02x %02x %02x %02x\n", 
            ventoy_varg_4(hashdata.sha1));
    }
    if (exe_data)
    {
        ret = 0;
        *pexe_data = exe_data;
        *pexe_len = exe_len;
    }
    
out:
    grub_check_free(lookup);
    grub_check_free(decompress_data);
    check_free(file, grub_file_close);
    return ret;
}
grub_err_t ventoy_cmd_windows_wimboot_data(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int rc = 0;
    int wim64 = 0;
    int datalen = 0;
    int dataflag = 0;
    grub_uint32_t exe_len = 0;
    grub_uint32_t jump_align = 0;
    const char *addr = NULL;
    ventoy_chain_head *chain = NULL;
    grub_uint8_t *param = NULL;
    grub_uint8_t *exe_data = NULL;
    ventoy_windows_data *rtdata = NULL;
    char exename[128] = {0};
    wim_tail wim_data;
    (void)ctxt;
    (void)argc;
    addr = grub_env_get("vtoy_chain_mem_addr");
    if (!addr)
    {
        debug("Failed to find vtoy_chain_mem_addr\n");
        return 1;
    }
    chain = (ventoy_chain_head *)(void *)grub_strtoul(addr, NULL, 16);
    if (grub_memcmp(&g_ventoy_guid, &chain->os_param.guid, 16) != 0)
    {
        debug("os_param.guid not match\n");
        return 1;
    }
    datalen = ventoy_get_windows_rtdata_len(chain->os_param.vtoy_img_path, &dataflag);
    rc = ventoy_extract_init_exe(args[0], &exe_data, &exe_len, exename);
    if (rc)
    {
        return 1;
    }
    wim64 = ventoy_is_pe64(exe_data);
    grub_memset(&wim_data, 0, sizeof(wim_data));
    ventoy_cat_exe_file_data(&wim_data, exe_len, exe_data, datalen);
    grub_check_free(exe_data);
    jump_align = ventoy_align(wim_data.jump_exe_len, 16);
    param = wim_data.jump_bin_data;
    grub_memcpy(param + jump_align, &chain->os_param, sizeof(ventoy_os_param));
    rtdata = (ventoy_windows_data *)(param + jump_align + sizeof(ventoy_os_param));
    ventoy_fill_windows_rtdata(rtdata, chain->os_param.vtoy_img_path, dataflag);
    ventoy_memfile_env_set("vtoy_wimboot_mem", param, (ulonglong)(wim_data.bin_align_len));
    grub_env_set(args[1], exename);
    grub_env_set(args[2], wim64 ? "64" : "32");
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_windows_chain_data(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int unknown_image = 0;
    int ventoy_compatible = 0;
    grub_uint32_t size = 0;
    grub_uint64_t isosize = 0;
    grub_uint32_t boot_catlog = 0;
    grub_uint32_t img_chunk_size = 0;
    grub_uint32_t override_size = 0;
    grub_uint32_t virt_chunk_size = 0;
    grub_file_t file;
    grub_disk_t disk;
    const char *pLastChain = NULL;
    const char *compatible;
    ventoy_chain_head *chain;
    
    (void)ctxt;
    (void)argc;
    debug("chain data begin <%s> ...\n", args[0]);
    compatible = grub_env_get("ventoy_compatible");
    if (compatible && compatible[0] == 'Y')
    {
        ventoy_compatible = 1;
    }
    if (NULL == g_img_chunk_list.chunk)
    {
        grub_printf("ventoy not ready\n");
        return 1;
    }
    if (0 == ventoy_compatible && g_wim_valid_patch_count == 0)
    {
        unknown_image = 1;
        if (!g_ventoy_wimboot_mode)
        {
            debug("Warning: %s was not recognized by Ventoy\n", args[0]);            
        }
    }
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]);
    if (!file)
    {
        return 1;
    }
    isosize = file->size;
    boot_catlog = ventoy_get_iso_boot_catlog(file);
    if (boot_catlog)
    {
        if (ventoy_is_efi_os() && (!ventoy_has_efi_eltorito(file, boot_catlog)))
        {
            grub_env_set("LoadIsoEfiDriver", "on");
        }
    }
    else
    {
        if (ventoy_is_efi_os())
        {
            grub_env_set("LoadIsoEfiDriver", "on");
        }
        else
        {
            return grub_error(GRUB_ERR_BAD_ARGUMENT, "File %s is not bootable", args[0]);
        }
    }
    g_suppress_wincd_override_offset = 0;
    if (!ventoy_is_efi_os()) /* legacy mode */
    {
        ventoy_suppress_windows_cd_prompt();
    }
    img_chunk_size = g_img_chunk_list.cur_chunk * sizeof(ventoy_img_chunk);
    
    if (ventoy_compatible || unknown_image)
    {
        override_size = g_suppress_wincd_override_offset > 0 ? sizeof(ventoy_override_chunk) : 0;
        size = sizeof(ventoy_chain_head) + img_chunk_size + override_size;
    }
    else
    {
        override_size = ventoy_get_override_chunk_num() * sizeof(ventoy_override_chunk);
        virt_chunk_size = ventoy_windows_get_virt_data_size();
        size = sizeof(ventoy_chain_head) + img_chunk_size + override_size + virt_chunk_size;
    }
    pLastChain = grub_env_get("vtoy_chain_mem_addr");
    if (pLastChain)
    {
        chain = (ventoy_chain_head *)grub_strtoul(pLastChain, NULL, 16);
        if (chain)
        {
            debug("free last chain memory %p\n", chain);
            grub_free(chain);
        }
    }
    chain = ventoy_alloc_chain(size);
    if (!chain)
    {
        grub_printf("Failed to alloc chain win1 memory size %u\n", size);
        grub_file_close(file);
        return 1;
    }
    ventoy_memfile_env_set("vtoy_chain_mem", chain, (ulonglong)size);
    grub_memset(chain, 0, sizeof(ventoy_chain_head));
    /* part 1: os parameter */
    g_ventoy_chain_type = ventoy_chain_windows;
    ventoy_fill_os_param(file, &(chain->os_param));
    if (0 == unknown_image)
    {
        ventoy_update_before_chain(&(chain->os_param), args[0]);
    }
    /* part 2: chain head */
    disk = file->device->disk;
    chain->disk_drive = disk->id;
    chain->disk_sector_size = (1 << disk->log_sector_size);
    chain->real_img_size_in_bytes = file->size;
    chain->virt_img_size_in_bytes = (file->size + 2047) / 2048 * 2048;
    chain->boot_catalog = boot_catlog;
    if (!ventoy_is_efi_os())
    {
        grub_file_seek(file, boot_catlog * 2048);
        grub_file_read(file, chain->boot_catalog_sector, sizeof(chain->boot_catalog_sector));
    }
    /* part 3: image chunk */
    chain->img_chunk_offset = sizeof(ventoy_chain_head);
    chain->img_chunk_num = g_img_chunk_list.cur_chunk;
    grub_memcpy((char *)chain + chain->img_chunk_offset, g_img_chunk_list.chunk, img_chunk_size);
    if (ventoy_compatible || unknown_image)
    {
        if (g_suppress_wincd_override_offset > 0)
        {
            chain->override_chunk_offset = chain->img_chunk_offset + img_chunk_size;
            chain->override_chunk_num = 1;
            ventoy_fill_suppress_wincd_override_data((char *)chain + chain->override_chunk_offset);
        }
        return 0;
    }
    if (0 == g_wim_valid_patch_count)
    {
        return 0;
    }
    /* part 4: override chunk */
    chain->override_chunk_offset = chain->img_chunk_offset + img_chunk_size;
    chain->override_chunk_num = ventoy_get_override_chunk_num();
    if (g_iso_fs_type == 0)
    {
        ventoy_windows_fill_override_data_iso9660(isosize, (char *)chain + chain->override_chunk_offset);
    }
    else
    {
        ventoy_windows_fill_override_data_udf(file, (char *)chain + chain->override_chunk_offset);        
    }
    /* part 5: virt chunk */
    chain->virt_chunk_offset = chain->override_chunk_offset + override_size;
    chain->virt_chunk_num = g_wim_valid_patch_count;
    ventoy_windows_fill_virt_data(isosize, chain);
    if (ventoy_is_efi_os() == 0)
    {
        ventoy_windows_drive_map(chain, file->vlnk);        
    }
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static grub_uint32_t ventoy_get_wim_iso_offset(const char *filepath)
{
    grub_uint32_t imgoffset;
    grub_file_t file;
    char cmdbuf[128];
    
    grub_snprintf(cmdbuf, sizeof(cmdbuf), "loopback wimiso \"%s\"", filepath);
    grub_script_execute_sourcecode(cmdbuf);
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", "(wimiso)/boot/boot.wim");
    if (!file)
    {
        grub_printf("Failed to open boot.wim file in the image file\n");
        return 0;
    }
    imgoffset = (grub_uint32_t)grub_iso9660_get_last_file_dirent_pos(file) + 2;
    debug("wimiso wim direct offset: %u\n", imgoffset);
    
    grub_file_close(file);
    
    grub_script_execute_sourcecode("loopback -d wimiso");
    return imgoffset;
}
static int ventoy_get_wim_chunklist(grub_file_t wimfile, ventoy_img_chunk_list *wimchunk)
{
    grub_memset(wimchunk, 0, sizeof(ventoy_img_chunk_list));
    wimchunk->chunk = grub_malloc(sizeof(ventoy_img_chunk) * DEFAULT_CHUNK_NUM);
    if (NULL == wimchunk->chunk)
    {
        return grub_error(GRUB_ERR_OUT_OF_MEMORY, "Can't allocate image chunk memoty\n");
    }
    
    wimchunk->max_chunk = DEFAULT_CHUNK_NUM;
    wimchunk->cur_chunk = 0;
    
    ventoy_get_block_list(wimfile, wimchunk, wimfile->device->disk->partition->start);
    return 0;
}
grub_err_t ventoy_cmd_is_standard_winiso(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int i;
    int ret = 1;
    char prefix[32] = {0};
    const char *chkfile[] = 
    {
        "boot/bcd", "boot/boot.sdi", NULL
    };
    (void)ctxt;
    (void)argc;
    if (ventoy_check_file_exist("%s/sources/boot.wim", args[0]))
    {
        prefix[0] = 0;
    }
    else if (ventoy_check_file_exist("%s/x86/sources/boot.wim", args[0]))
    {
        grub_snprintf(prefix, sizeof(prefix), "/x86");
    }
    else if (ventoy_check_file_exist("%s/x64/sources/boot.wim", args[0]))
    {
        grub_snprintf(prefix, sizeof(prefix), "/x64");
    }
    else
    {
        debug("No boot.wim found.\n");
        goto out;
    }
    for (i = 0; chkfile[i]; i++)
    {
        if (!ventoy_check_file_exist("%s%s/%s", args[0], prefix, chkfile[i]))
        {
            debug("%s not found.\n", chkfile[i]);
            goto out;
        }
    }
    if ((!ventoy_check_file_exist("%s%s/sources/install.wim", args[0], prefix)) && 
        (!ventoy_check_file_exist("%s%s/sources/install.esd", args[0], prefix)))
    {
        debug("No install.wim(esd) found.\n");
        goto out;
    }
    if (!ventoy_check_file_exist("%s/setup.exe", args[0]))
    {
        debug("No setup.exe found.\n");
        goto out;
    }
    ret = 0;
    debug("This is standard Windows ISO.\n");
out:
    return ret;
}
grub_err_t ventoy_cmd_wim_check_bootable(grub_extcmd_context_t ctxt, int argc, char **args)
{
    grub_uint32_t boot_index;
    grub_file_t file = NULL;
    wim_header *wimhdr = NULL;
    
    (void)ctxt;
    (void)argc;
    wimhdr = grub_zalloc(sizeof(wim_header));
    if (!wimhdr)
    {
        return 1;
    }
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]);
    if (!file)
    {
        grub_free(wimhdr);
        return 1;
    }
    grub_file_read(file, wimhdr, sizeof(wim_header));
    grub_file_close(file);
    boot_index = wimhdr->boot_index;
    grub_free(wimhdr);
    if (boot_index == 0)
    {
        return 1;
    }
    
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static grub_err_t ventoy_vlnk_wim_chain_data(grub_file_t wimfile)
{
    grub_uint32_t i = 0;
    grub_uint32_t imgoffset = 0;
    grub_uint32_t size = 0;
    grub_uint32_t isosector = 0;
    grub_uint64_t wimsize = 0;
    grub_uint32_t boot_catlog = 0;
    grub_uint32_t img_chunk1_size = 0;
    grub_uint32_t img_chunk2_size = 0;
    grub_uint32_t override_size = 0;
    grub_file_t file;
    grub_disk_t disk;
    const char *pLastChain = NULL;
    ventoy_chain_head *chain;
    ventoy_iso9660_override *dirent;
    ventoy_img_chunk *chunknode;
    ventoy_override_chunk *override;
    ventoy_img_chunk_list wimchunk;
    
    debug("vlnk wim chain data begin <%s> ...\n", wimfile->name);
    if (NULL == g_wimiso_chunk_list.chunk || NULL == g_wimiso_path)
    {
        grub_printf("ventoy not ready\n");
        return 1;
    }
    imgoffset = ventoy_get_wim_iso_offset(g_wimiso_path);
    if (imgoffset == 0)
    {
        grub_printf("image offset not found\n");
        return 1;
    }
    if (0 != ventoy_get_wim_chunklist(wimfile, &wimchunk))
    {
        grub_printf("Failed to get wim chunklist\n");
        return 1;
    }
    wimsize = wimfile->size;
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", g_wimiso_path);
    if (!file)
    {
        return 1;
    }
    boot_catlog = ventoy_get_iso_boot_catlog(file);
    img_chunk1_size = g_wimiso_chunk_list.cur_chunk * sizeof(ventoy_img_chunk);
    img_chunk2_size = wimchunk.cur_chunk * sizeof(ventoy_img_chunk);
    override_size = sizeof(ventoy_override_chunk) + g_wimiso_size;
    size = sizeof(ventoy_chain_head) + img_chunk1_size + img_chunk2_size + override_size;
    pLastChain = grub_env_get("vtoy_chain_mem_addr");
    if (pLastChain)
    {
        chain = (ventoy_chain_head *)grub_strtoul(pLastChain, NULL, 16);
        if (chain)
        {
            debug("free last chain memory %p\n", chain);
            grub_free(chain);
        }
    }
    chain = ventoy_alloc_chain(size);
    if (!chain)
    {
        grub_printf("Failed to alloc chain win2 memory size %u\n", size);
        grub_file_close(file);
        return 1;
    }
    ventoy_memfile_env_set("vtoy_chain_mem", chain, (ulonglong)size);
    grub_memset(chain, 0, sizeof(ventoy_chain_head));
    /* part 1: os parameter */
    g_ventoy_chain_type = ventoy_chain_wim;
    ventoy_fill_os_param(wimfile, &(chain->os_param));
    /* part 2: chain head */
    disk = wimfile->device->disk;
    chain->disk_drive = disk->id;
    chain->disk_sector_size = (1 << disk->log_sector_size);
    chain->real_img_size_in_bytes = ventoy_align_2k(file->size) + ventoy_align_2k(wimsize);
    chain->virt_img_size_in_bytes = chain->real_img_size_in_bytes;
    chain->boot_catalog = boot_catlog;
    if (!ventoy_is_efi_os())
    {
        grub_file_seek(file, boot_catlog * 2048);
        grub_file_read(file, chain->boot_catalog_sector, sizeof(chain->boot_catalog_sector));
    }
    /* part 3: image chunk */
    chain->img_chunk_offset = sizeof(ventoy_chain_head);
    chain->img_chunk_num = g_wimiso_chunk_list.cur_chunk + wimchunk.cur_chunk;
    grub_memcpy((char *)chain + chain->img_chunk_offset, g_wimiso_chunk_list.chunk, img_chunk1_size);
    chunknode = (ventoy_img_chunk *)((char *)chain + chain->img_chunk_offset);
    for (i = 0; i < g_wimiso_chunk_list.cur_chunk; i++)
    {
        chunknode->disk_end_sector = chunknode->disk_end_sector - chunknode->disk_start_sector;
        chunknode->disk_start_sector = 0;
        chunknode++;
    }
    /* fs cluster size >= 2048, so don't need to proc align */
    /* align by 2048 */
    chunknode = wimchunk.chunk + wimchunk.cur_chunk - 1;
    i = (chunknode->disk_end_sector + 1 - chunknode->disk_start_sector) % 4;
    if (i)
    {
        chunknode->disk_end_sector += 4 - i;
    }
    isosector = (grub_uint32_t)((file->size + 2047) / 2048);
    for (i = 0; i < wimchunk.cur_chunk; i++)
    {
        chunknode = wimchunk.chunk + i;
        chunknode->img_start_sector = isosector;
        chunknode->img_end_sector = chunknode->img_start_sector + 
            ((chunknode->disk_end_sector + 1 - chunknode->disk_start_sector) / 4) - 1;
        isosector = chunknode->img_end_sector + 1;
    }
    
    grub_memcpy((char *)chain + chain->img_chunk_offset + img_chunk1_size, wimchunk.chunk, img_chunk2_size);
    /* part 4: override chunk */
    chain->override_chunk_offset = chain->img_chunk_offset + img_chunk1_size + img_chunk2_size;
    chain->override_chunk_num = 1;
    override = (ventoy_override_chunk *)((char *)chain + chain->override_chunk_offset);
    override->img_offset = 0;
    override->override_size = g_wimiso_size;
    grub_file_seek(file, 0);
    grub_file_read(file, override->override_data, file->size);
    
    dirent = (ventoy_iso9660_override *)(override->override_data + imgoffset);
    dirent->first_sector    = (grub_uint32_t)((file->size + 2047) / 2048);
    dirent->size            = (grub_uint32_t)(wimsize);
    dirent->first_sector_be = grub_swap_bytes32(dirent->first_sector);
    dirent->size_be         = grub_swap_bytes32(dirent->size);
    debug("imgoffset=%u first_sector=0x%x size=0x%x\n", imgoffset, dirent->first_sector, dirent->size);
    if (ventoy_is_efi_os() == 0)
    {
        ventoy_windows_drive_map(chain, 0);        
    }
    grub_file_close(file);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
static grub_err_t ventoy_normal_wim_chain_data(grub_file_t wimfile)
{
    grub_uint32_t i = 0;
    grub_uint32_t imgoffset = 0;
    grub_uint32_t size = 0;
    grub_uint32_t isosector = 0;
    grub_uint64_t wimsize = 0;
    grub_uint32_t boot_catlog = 0;
    grub_uint32_t img_chunk1_size = 0;
    grub_uint32_t img_chunk2_size = 0;
    grub_uint32_t override_size = 0;
    grub_file_t file;
    grub_disk_t disk;
    const char *pLastChain = NULL;
    ventoy_chain_head *chain;
    ventoy_iso9660_override *dirent;
    ventoy_img_chunk *chunknode;
    ventoy_override_chunk *override;
    ventoy_img_chunk_list wimchunk;
    
    debug("normal wim chain data begin <%s> ...\n", wimfile->name);
    if (NULL == g_wimiso_chunk_list.chunk || NULL == g_wimiso_path)
    {
        grub_printf("ventoy not ready\n");
        return 1;
    }
    imgoffset = ventoy_get_wim_iso_offset(g_wimiso_path);
    if (imgoffset == 0)
    {
        grub_printf("image offset not found\n");
        return 1;
    }
    if (0 != ventoy_get_wim_chunklist(wimfile, &wimchunk))
    {
        grub_printf("Failed to get wim chunklist\n");
        return 1;
    }
    wimsize = wimfile->size;
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", g_wimiso_path);
    if (!file)
    {
        return 1;
    }
    boot_catlog = ventoy_get_iso_boot_catlog(file);
    img_chunk1_size = g_wimiso_chunk_list.cur_chunk * sizeof(ventoy_img_chunk);
    img_chunk2_size = wimchunk.cur_chunk * sizeof(ventoy_img_chunk);
    override_size = sizeof(ventoy_override_chunk);
    
    size = sizeof(ventoy_chain_head) + img_chunk1_size + img_chunk2_size + override_size;
    pLastChain = grub_env_get("vtoy_chain_mem_addr");
    if (pLastChain)
    {
        chain = (ventoy_chain_head *)grub_strtoul(pLastChain, NULL, 16);
        if (chain)
        {
            debug("free last chain memory %p\n", chain);
            grub_free(chain);
        }
    }
    chain = ventoy_alloc_chain(size);
    if (!chain)
    {
        grub_printf("Failed to alloc chain win3 memory size %u\n", size);
        grub_file_close(file);
        return 1;
    }
    ventoy_memfile_env_set("vtoy_chain_mem", chain, (ulonglong)size);
    grub_memset(chain, 0, sizeof(ventoy_chain_head));
    /* part 1: os parameter */
    g_ventoy_chain_type = ventoy_chain_wim;
    ventoy_fill_os_param(file, &(chain->os_param));
    /* part 2: chain head */
    disk = file->device->disk;
    chain->disk_drive = disk->id;
    chain->disk_sector_size = (1 << disk->log_sector_size);
    chain->real_img_size_in_bytes = ventoy_align_2k(file->size) + ventoy_align_2k(wimsize);
    chain->virt_img_size_in_bytes = chain->real_img_size_in_bytes;
    chain->boot_catalog = boot_catlog;
    if (!ventoy_is_efi_os())
    {
        grub_file_seek(file, boot_catlog * 2048);
        grub_file_read(file, chain->boot_catalog_sector, sizeof(chain->boot_catalog_sector));
    }
    /* part 3: image chunk */
    chain->img_chunk_offset = sizeof(ventoy_chain_head);
    chain->img_chunk_num = g_wimiso_chunk_list.cur_chunk + wimchunk.cur_chunk;
    grub_memcpy((char *)chain + chain->img_chunk_offset, g_wimiso_chunk_list.chunk, img_chunk1_size);
    /* fs cluster size >= 2048, so don't need to proc align */
    /* align by 2048 */
    chunknode = wimchunk.chunk + wimchunk.cur_chunk - 1;
    i = (chunknode->disk_end_sector + 1 - chunknode->disk_start_sector) % 4;
    if (i)
    {
        chunknode->disk_end_sector += 4 - i;
    }
    isosector = (grub_uint32_t)((file->size + 2047) / 2048);
    for (i = 0; i < wimchunk.cur_chunk; i++)
    {
        chunknode = wimchunk.chunk + i;
        chunknode->img_start_sector = isosector;
        chunknode->img_end_sector = chunknode->img_start_sector + 
            ((chunknode->disk_end_sector + 1 - chunknode->disk_start_sector) / 4) - 1;
        isosector = chunknode->img_end_sector + 1;
    }
    
    grub_memcpy((char *)chain + chain->img_chunk_offset + img_chunk1_size, wimchunk.chunk, img_chunk2_size);
    /* part 4: override chunk */
    chain->override_chunk_offset = chain->img_chunk_offset + img_chunk1_size + img_chunk2_size;
    chain->override_chunk_num = 1;
    override = (ventoy_override_chunk *)((char *)chain + chain->override_chunk_offset);
    override->img_offset = imgoffset;
    override->override_size = sizeof(ventoy_iso9660_override);
    
    dirent = (ventoy_iso9660_override *)(override->override_data);
    dirent->first_sector    = (grub_uint32_t)((file->size + 2047) / 2048);
    dirent->size            = (grub_uint32_t)(wimsize);
    dirent->first_sector_be = grub_swap_bytes32(dirent->first_sector);
    dirent->size_be         = grub_swap_bytes32(dirent->size);
    debug("imgoffset=%u first_sector=0x%x size=0x%x\n", imgoffset, dirent->first_sector, dirent->size);
    if (ventoy_is_efi_os() == 0)
    {
        ventoy_windows_drive_map(chain, 0);        
    }
    grub_file_close(file);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_wim_chain_data(grub_extcmd_context_t ctxt, int argc, char **args)
{
    grub_err_t ret;
    grub_file_t wimfile;
    (void)ctxt;
    (void)argc;
    wimfile = grub_file_open(args[0], VENTOY_FILE_TYPE);
    if (!wimfile)
    {
        return 1;
    }
    if (wimfile->vlnk)
    {
        ret = ventoy_vlnk_wim_chain_data(wimfile);
    }
    else
    {
        ret = ventoy_normal_wim_chain_data(wimfile);
    }
    grub_file_close(wimfile);
    return ret;
}
int ventoy_chain_file_size(const char *path)
{
    int size;
    grub_file_t file;
    file = grub_file_open(path, VENTOY_FILE_TYPE);
    size = (int)(file->size);
    grub_file_close(file);
    
    return size;
}
int ventoy_chain_file_read(const char *path, int offset, int len, void *buf)
{
    int size;
    grub_file_t file;
    file = grub_file_open(path, VENTOY_FILE_TYPE);
    grub_file_seek(file, offset);
    size = grub_file_read(file, buf, len);
    grub_file_close(file);
    
    return size;
}
 | 79,057 | 
	C | 
	.c | 2,292 | 27.175829 | 136 | 0.580718 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 624 | 
	lzx.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/lzx.c | 
	/*
 * Copyright (C) 2014 Michael Brown <mbrown@fensystems.co.uk>.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
/**
 * @file
 *
 * LZX decompression
 *
 * This algorithm is derived jointly from the document "[MS-PATCH]:
 * LZX DELTA Compression and Decompression", available from
 *
 *     http://msdn.microsoft.com/en-us/library/cc483133.aspx
 *
 * and from the file lzx-decompress.c in the wimlib source code.
 *
 */
#include "wimboot.h"
#include "huffman.h"
#include "lzx.h"
/** Base positions, indexed by position slot */
static unsigned int lzx_position_base[LZX_POSITION_SLOTS];
/**
 * Attempt to accumulate bits from LZX bitstream
 *
 * @v lzx		Decompressor
 * @v bits		Number of bits to accumulate
 * @v norm_value	Accumulated value (normalised to 16 bits)
 *
 * Note that there may not be sufficient accumulated bits in the
 * bitstream; callers must check that sufficient bits are available
 * before using the value.
 */
static int lzx_accumulate ( struct lzx *lzx, unsigned int bits ) {
	const uint16_t *src16;
	/* Accumulate more bits if required */
	if ( ( lzx->bits < bits ) &&
	     ( lzx->input.offset < lzx->input.len ) ) {
		src16 = (const uint16_t *)( ( char * ) lzx->input.data + lzx->input.offset );
		lzx->input.offset += sizeof ( *src16 );
		lzx->accumulator |= ( *src16 << ( 16 - lzx->bits ) );
		lzx->bits += 16;
	}
	return ( lzx->accumulator >> 16 );
}
/**
 * Consume accumulated bits from LZX bitstream
 *
 * @v lzx		Decompressor
 * @v bits		Number of bits to consume
 * @ret rc		Return status code
 */
static int lzx_consume ( struct lzx *lzx, unsigned int bits ) {
	/* Fail if insufficient bits are available */
	if ( lzx->bits < bits ) {
		DBG ( "LZX input overrun in %#zx/%#zx out %#zx)\n",
		      lzx->input.offset, lzx->input.len, lzx->output.offset );
		return -1;
	}
	/* Consume bits */
	lzx->accumulator <<= bits;
	lzx->bits -= bits;
	return 0;
}
/**
 * Get bits from LZX bitstream
 *
 * @v lzx		Decompressor
 * @v bits		Number of bits to fetch
 * @ret value		Value, or negative error
 */
static int lzx_getbits ( struct lzx *lzx, unsigned int bits ) {
	int norm_value;
	int rc;
	/* Accumulate more bits if required */
	norm_value = lzx_accumulate ( lzx, bits );
	/* Consume bits */
	if ( ( rc = lzx_consume ( lzx, bits ) ) != 0 )
		return rc;
	return ( norm_value >> ( 16 - bits ) );
}
/**
 * Align LZX bitstream for byte access
 *
 * @v lzx		Decompressor
 * @v bits		Minimum number of padding bits
 * @ret rc		Return status code
 */
static int lzx_align ( struct lzx *lzx, unsigned int bits ) {
	int pad;
	/* Get padding bits */
	pad = lzx_getbits ( lzx, bits );
	if ( pad < 0 )
		return pad;
	/* Consume all accumulated bits */
	lzx_consume ( lzx, lzx->bits );
	return 0;
}
/**
 * Get bytes from LZX bitstream
 *
 * @v lzx		Decompressor
 * @v data		Data buffer, or NULL
 * @v len		Length of data buffer
 * @ret rc		Return status code
 */
static int lzx_getbytes ( struct lzx *lzx, void *data, size_t len ) {
	/* Sanity check */
	if ( ( lzx->input.offset + len ) > lzx->input.len ) {
		DBG ( "LZX input overrun in %#zx/%#zx out %#zx)\n",
		      lzx->input.offset, lzx->input.len, lzx->output.offset );
		return -1;
	}
	/* Copy data */
	if ( data )
		memcpy ( data, ( lzx->input.data + lzx->input.offset ), len );
	lzx->input.offset += len;
	return 0;
}
/**
 * Decode LZX Huffman-coded symbol
 *
 * @v lzx		Decompressor
 * @v alphabet		Huffman alphabet
 * @ret raw		Raw symbol, or negative error
 */
static int lzx_decode ( struct lzx *lzx, struct huffman_alphabet *alphabet ) {
	struct huffman_symbols *sym;
	int huf;
	int rc;
	/* Accumulate sufficient bits */
	huf = lzx_accumulate ( lzx, HUFFMAN_BITS );
	if ( huf < 0 )
		return huf;
	/* Decode symbol */
	sym = huffman_sym ( alphabet, huf );
	/* Consume bits */
	if ( ( rc = lzx_consume ( lzx, huffman_len ( sym ) ) ) != 0 )
		return rc;
	return huffman_raw ( sym, huf );
}
/**
 * Generate Huffman alphabet from raw length table
 *
 * @v lzx		Decompressor
 * @v count		Number of symbols
 * @v bits		Length of each length (in bits)
 * @v lengths		Lengths table to fill in
 * @v alphabet		Huffman alphabet to fill in
 * @ret rc		Return status code
 */
static int lzx_raw_alphabet ( struct lzx *lzx, unsigned int count,
			      unsigned int bits, uint8_t *lengths,
			      struct huffman_alphabet *alphabet ) {
	unsigned int i;
	int len;
	int rc;
	/* Read lengths */
	for ( i = 0 ; i < count ; i++ ) {
		len = lzx_getbits ( lzx, bits );
		if ( len < 0 )
			return len;
		lengths[i] = len;
	}
	/* Generate Huffman alphabet */
	if ( ( rc = huffman_alphabet ( alphabet, lengths, count ) ) != 0 )
		return rc;
	return 0;
}
/**
 * Generate pretree
 *
 * @v lzx		Decompressor
 * @v count		Number of symbols
 * @v lengths		Lengths table to fill in
 * @ret rc		Return status code
 */
static int lzx_pretree ( struct lzx *lzx, unsigned int count,
			 uint8_t *lengths ) {
	unsigned int i;
	unsigned int length;
	int dup = 0;
	int code;
	int rc;
	/* Generate pretree alphabet */
	if ( ( rc =  lzx_raw_alphabet ( lzx, LZX_PRETREE_CODES,
					LZX_PRETREE_BITS, lzx->pretree_lengths,
					&lzx->pretree ) ) != 0 )
		return rc;
	/* Read lengths */
	for ( i = 0 ; i < count ; i++ ) {
		if ( dup ) {
			/* Duplicate previous length */
			lengths[i] = lengths[ i - 1 ];
			dup--;
		} else {
			/* Get next code */
			code = lzx_decode ( lzx, &lzx->pretree );
			if ( code < 0 )
				return code;
			/* Interpret code */
			if ( code <= 16 ) {
				length = ( ( lengths[i] - code + 17 ) % 17 );
			} else if ( code == 17 ) {
				length = 0;
				dup = lzx_getbits ( lzx, 4 );
				if ( dup < 0 )
					return dup;
				dup += 3;
			} else if ( code == 18 ) {
				length = 0;
				dup = lzx_getbits ( lzx, 5 );
				if ( dup < 0 )
					return dup;
				dup += 19;
			} else if ( code == 19 ) {
				length = 0;
				dup = lzx_getbits ( lzx, 1 );
				if ( dup < 0 )
					return dup;
				dup += 3;
				code = lzx_decode ( lzx, &lzx->pretree );
				if ( code < 0 )
					return code;
				length = ( ( lengths[i] - code + 17 ) % 17 );
			} else {
				DBG ( "Unrecognised pretree code %d\n", code );
				return -1;
			}
			lengths[i] = length;
		}
	}
	/* Sanity check */
	if ( dup ) {
		DBG ( "Pretree duplicate overrun\n" );
		return -1;
	}
	return 0;
}
/**
 * Generate aligned offset Huffman alphabet
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 */
static int lzx_alignoffset_alphabet ( struct lzx *lzx ) {
	int rc;
	/* Generate aligned offset alphabet */
	if ( ( rc = lzx_raw_alphabet ( lzx, LZX_ALIGNOFFSET_CODES,
				       LZX_ALIGNOFFSET_BITS,
				       lzx->alignoffset_lengths,
				       &lzx->alignoffset ) ) != 0 )
		return rc;
	return 0;
}
/**
 * Generate main Huffman alphabet
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 */
static int lzx_main_alphabet ( struct lzx *lzx ) {
	int rc;
	/* Generate literal symbols pretree */
	if ( ( rc = lzx_pretree ( lzx, LZX_MAIN_LIT_CODES,
				  lzx->main_lengths.literals ) ) != 0 ) {
		DBG ( "Could not construct main literal pretree\n" );
		return rc;
	}
	/* Generate remaining symbols pretree */
	if ( ( rc = lzx_pretree ( lzx, ( LZX_MAIN_CODES - LZX_MAIN_LIT_CODES ),
				  lzx->main_lengths.remainder ) ) != 0 ) {
		DBG ( "Could not construct main remainder pretree\n" );
		return rc;
	}
	/* Generate Huffman alphabet */
	if ( ( rc = huffman_alphabet ( &lzx->main, lzx->main_lengths.literals,
				       LZX_MAIN_CODES ) ) != 0 ) {
		DBG ( "Could not generate main alphabet\n" );
		return rc;
	}
	return 0;
}
/**
 * Generate length Huffman alphabet
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 */
static int lzx_length_alphabet ( struct lzx *lzx ) {
	int rc;
	/* Generate pretree */
	if ( ( rc = lzx_pretree ( lzx, LZX_LENGTH_CODES,
				  lzx->length_lengths ) ) != 0 ) {
		DBG ( "Could not generate length pretree\n" );
		return rc;
	}
	/* Generate Huffman alphabet */
	if ( ( rc = huffman_alphabet ( &lzx->length, lzx->length_lengths,
				       LZX_LENGTH_CODES ) ) != 0 ) {
		DBG ( "Could not generate length alphabet\n" );
		return rc;
	}
	return 0;
}
/**
 * Process LZX block header
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 */
static int lzx_block_header ( struct lzx *lzx ) {
	size_t block_len;
	int block_type;
	int default_len;
	int len_high;
	int len_low;
	int rc;
	/* Get block type */
	block_type = lzx_getbits ( lzx, LZX_BLOCK_TYPE_BITS );
	if ( block_type < 0 )
		return block_type;
	lzx->block_type = block_type;
	/* Check block length */
	default_len = lzx_getbits ( lzx, 1 );
	if ( default_len < 0 )
		return default_len;
	if ( default_len ) {
		block_len = LZX_DEFAULT_BLOCK_LEN;
	} else {
		len_high = lzx_getbits ( lzx, 8 );
		if ( len_high < 0 )
			return len_high;
		len_low = lzx_getbits ( lzx, 8 );
		if ( len_low < 0 )
			return len_low;
		block_len = ( ( len_high << 8 ) | len_low );
	}
	lzx->output.threshold = ( lzx->output.offset + block_len );
	/* Handle block type */
	switch ( block_type ) {
	case LZX_BLOCK_ALIGNOFFSET :
		/* Generated aligned offset alphabet */
		if ( ( rc = lzx_alignoffset_alphabet ( lzx ) ) != 0 )
			return rc;
		/* Fall through */
	case LZX_BLOCK_VERBATIM :
		/* Generate main alphabet */
		if ( ( rc = lzx_main_alphabet ( lzx ) ) != 0 )
			return rc;
		/* Generate lengths alphabet */
		if ( ( rc = lzx_length_alphabet ( lzx ) ) != 0 )
			return rc;
		break;
	case LZX_BLOCK_UNCOMPRESSED :
		/* Align input stream */
		if ( ( rc = lzx_align ( lzx, 1 ) ) != 0 )
			return rc;
		/* Read new repeated offsets */
		if ( ( rc = lzx_getbytes ( lzx, &lzx->repeated_offset,
					   sizeof ( lzx->repeated_offset )))!=0)
			return rc;
		break;
	default:
		DBG ( "Unrecognised block type %d\n", block_type );
		return -1;
	}
	return 0;
}
/**
 * Process uncompressed data
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 */
static int lzx_uncompressed ( struct lzx *lzx ) {
	void *data;
	size_t len;
	int rc;
	/* Copy bytes */
	data = ( lzx->output.data ?
		 ( lzx->output.data + lzx->output.offset ) : NULL );
	len = ( lzx->output.threshold - lzx->output.offset );
	if ( ( rc = lzx_getbytes ( lzx, data, len ) ) != 0 )
		return rc;
	/* Align input stream */
	if ( len % 2 )
		lzx->input.offset++;
    lzx->output.offset += len;
	return 0;
}
/**
 * Process an LZX token
 *
 * @v lzx		Decompressor
 * @ret rc		Return status code
 *
 * Variable names are chosen to match the LZX specification
 * pseudo-code.
 */
static int lzx_token ( struct lzx *lzx ) {
	unsigned int length_header;
	unsigned int position_slot;
	unsigned int offset_bits;
	unsigned int i;
	size_t match_offset;
	size_t match_length;
	int verbatim_bits;
	int aligned_bits;
	int maindata;
	int length;
	uint8_t *copy;
	/* Get maindata symelse*/
	maindata = lzx_decode ( lzx, &lzx->main );
	if ( maindata < 0 )
		return maindata;
	/* Check for literals */
	if ( maindata < LZX_MAIN_LIT_CODES ) {
		if ( lzx->output.data )
			lzx->output.data[lzx->output.offset] = maindata;
		lzx->output.offset++;
		return 0;
	}
	maindata -= LZX_MAIN_LIT_CODES;
	/* Calculate the match length */
	length_header = ( maindata & 7 );
	if ( length_header == 7 ) {
		length = lzx_decode ( lzx, &lzx->length );
		if ( length < 0 )
			return length;
	} else {
		length = 0;
	}
	match_length = ( length_header + 2 + length );
	/* Calculate the position slot */
	position_slot = ( maindata >> 3 );
	if ( position_slot < LZX_REPEATED_OFFSETS ) {
		/* Repeated offset */
		match_offset = lzx->repeated_offset[position_slot];
		lzx->repeated_offset[position_slot] = lzx->repeated_offset[0];
		lzx->repeated_offset[0] = match_offset;
	} else {
		/* Non-repeated offset */
		offset_bits = lzx_footer_bits ( position_slot );
		if ( ( lzx->block_type == LZX_BLOCK_ALIGNOFFSET ) &&
		     ( offset_bits >= 3 ) ) {
			verbatim_bits = lzx_getbits ( lzx, ( offset_bits - 3 ));
			if ( verbatim_bits < 0 )
				return verbatim_bits;
			verbatim_bits <<= 3;
			aligned_bits = lzx_decode ( lzx, &lzx->alignoffset );
			if ( aligned_bits < 0 )
				return aligned_bits;
		} else {
			verbatim_bits = lzx_getbits ( lzx, offset_bits );
			if ( verbatim_bits < 0 )
				return verbatim_bits;
			aligned_bits = 0;
		}
		match_offset = ( lzx_position_base[position_slot] +
				 verbatim_bits + aligned_bits - 2 );
		/* Update repeated offset list */
		for ( i = ( LZX_REPEATED_OFFSETS - 1 ) ; i > 0 ; i-- )
			lzx->repeated_offset[i] = lzx->repeated_offset[ i - 1 ];
		lzx->repeated_offset[0] = match_offset;
	}
	/* Copy data */
	if ( match_offset > lzx->output.offset ) {
		DBG ( "LZX match underrun out 0x%x offset 0x%x len 0x%x\n",
		      lzx->output.offset, match_offset, match_length );
		return -1;
	}
	if ( lzx->output.data ) {
		copy = &lzx->output.data[lzx->output.offset];
		for ( i = 0 ; i < match_length ; i++ )
			copy[i] = copy[ i - match_offset ];
	}
	lzx->output.offset += match_length;
	return 0;
}
/**
 * Translate E8 jump addresses
 *
 * @v lzx		Decompressor
 */
static void lzx_translate_jumps ( struct lzx *lzx ) {
	size_t offset;
	int32_t *target;
	/* Sanity check */
	if ( lzx->output.offset < 10 )
		return;
	/* Scan for jump instructions */
	for ( offset = 0 ; offset < ( lzx->output.offset - 10 ) ; offset++ ) {
		/* Check for jump instruction */
		if ( lzx->output.data[offset] != 0xe8 )
			continue;
		/* Translate jump target */
		target = ( ( int32_t * ) &lzx->output.data[ offset + 1 ] );
		if ( *target >= 0 ) {
			if ( *target < LZX_WIM_MAGIC_FILESIZE )
				*target -= offset;
		} else {
			if ( *target >= -( ( int32_t ) offset ) )
				*target += LZX_WIM_MAGIC_FILESIZE;
		}
		offset += sizeof ( *target );
	}
}
/**
 * Decompress LZX-compressed data
 *
 * @v data		Compressed data
 * @v len		Length of compressed data
 * @v buf		Decompression buffer, or NULL
 * @ret out_len		Length of decompressed data, or negative error
 */
ssize_t lzx_decompress ( const void *data, size_t len, void *buf ) {
	struct lzx lzx;
	unsigned int i;
	int rc;
	/* Sanity check */
	if ( len % 2 ) {
		DBG ( "LZX cannot handle odd-length input data\n" );
		//return -1;
	}
	/* Initialise global state, if required */
	if ( ! lzx_position_base[ LZX_POSITION_SLOTS - 1 ] ) {
		for ( i = 1 ; i < LZX_POSITION_SLOTS ; i++ ) {
			lzx_position_base[i] =
				( lzx_position_base[i-1] +
				  ( 1 << lzx_footer_bits ( i - 1 ) ) );
		}
	}
	/* Initialise decompressor */
	memset ( &lzx, 0, sizeof ( lzx ) );
	lzx.input.data = data;
	lzx.input.len = len;
	lzx.output.data = buf;
	for ( i = 0 ; i < LZX_REPEATED_OFFSETS ; i++ )
		lzx.repeated_offset[i] = 1;
	/* Process blocks */
	while ( lzx.input.offset < lzx.input.len ) {
		/* Process block header */
		if ( ( rc = lzx_block_header ( &lzx ) ) != 0 )
			return rc;
		/* Process block contents */
		if ( lzx.block_type == LZX_BLOCK_UNCOMPRESSED ) {
			/* Copy uncompressed data */
			if ( ( rc = lzx_uncompressed ( &lzx ) ) != 0 )
				return rc;
		} else {
			/* Process token stream */
			while ( lzx.output.offset < lzx.output.threshold ) {
				if ( ( rc = lzx_token ( &lzx ) ) != 0 )
					return rc;
			}
		}
	}
	/* Postprocess to undo E8 jump compression */
	if ( lzx.output.data )
		lzx_translate_jumps ( &lzx );
	return lzx.output.offset;
}
 | 15,819 | 
	C | 
	.c | 577 | 24.594454 | 79 | 0.638902 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | true | 
| 625 | 
	ventoy_vhd.c | 
	ventoy_Ventoy/GRUB2/MOD_SRC/grub-2.04/grub-core/ventoy/ventoy_vhd.c | 
	/******************************************************************************
 * ventoy_vhd.c 
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <grub/types.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/err.h>
#include <grub/dl.h>
#include <grub/disk.h>
#include <grub/device.h>
#include <grub/term.h>
#include <grub/partition.h>
#include <grub/file.h>
#include <grub/normal.h>
#include <grub/extcmd.h>
#include <grub/datetime.h>
#include <grub/i18n.h>
#include <grub/net.h>
#include <grub/time.h>
#include <grub/crypto.h>
#include <grub/charset.h>
#ifdef GRUB_MACHINE_EFI
#include <grub/efi/efi.h>
#endif
#include <grub/ventoy.h>
#include "ventoy_def.h"
GRUB_MOD_LICENSE ("GPLv3+");
static int g_vhdboot_isolen = 0;
static char *g_vhdboot_totbuf = NULL;
static char *g_vhdboot_isobuf = NULL;
static grub_uint64_t g_img_trim_head_secnum = 0;
static int ventoy_vhd_find_bcd(int *bcdoffset, int *bcdlen, const char *path)
{
    grub_uint32_t offset;
    grub_file_t file;
    char cmdbuf[128];
    
    grub_snprintf(cmdbuf, sizeof(cmdbuf), "loopback vhdiso mem:0x%lx:size:%d", (ulong)g_vhdboot_isobuf, g_vhdboot_isolen);
    
    grub_script_execute_sourcecode(cmdbuf);
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "(vhdiso)%s", path);
    if (!file)
    {
        return 1;
    }
    grub_file_read(file, &offset, 4);
    offset = (grub_uint32_t)grub_iso9660_get_last_read_pos(file);
    *bcdoffset = (int)offset;
    *bcdlen = (int)file->size;
    debug("vhdiso bcd file offset:%d len:%d\n", *bcdoffset, *bcdlen);
    
    grub_file_close(file);
    
    grub_script_execute_sourcecode("loopback -d vhdiso");
    return 0;
}
static int ventoy_vhd_patch_path(char *vhdpath, ventoy_patch_vhd *patch1, ventoy_patch_vhd *patch2, 
    int bcdoffset, int bcdlen)
{
    int i;
    int cnt = 0;
    char *pos;
    grub_size_t pathlen;
    const char *plat;
    char *newpath = NULL;
    grub_uint16_t *unicode_path;
    const grub_uint8_t winloadexe[] = 
    {
        0x77, 0x00, 0x69, 0x00, 0x6E, 0x00, 0x6C, 0x00, 0x6F, 0x00, 0x61, 0x00, 0x64, 0x00, 0x2E, 0x00,
        0x65, 0x00, 0x78, 0x00, 0x65, 0x00 
    };
    while ((*vhdpath) != '/')
    {
        vhdpath++;
    }
    pathlen = sizeof(grub_uint16_t) * (grub_strlen(vhdpath) + 1);
    debug("unicode path for <%s> len:%d\n", vhdpath, (int)pathlen);
    
    unicode_path = grub_zalloc(pathlen);
    if (!unicode_path)
    {
        return 0;
    }
    plat = grub_env_get("grub_platform");
    if (plat && (plat[0] == 'e')) /* UEFI */
    {
        pos = g_vhdboot_isobuf + bcdoffset;
    
        /* winload.exe ==> winload.efi */
        for (i = 0; i + (int)sizeof(winloadexe) < bcdlen; i++)
        {
            if (*((grub_uint32_t *)(pos + i)) == 0x00690077 && 
                grub_memcmp(pos + i, winloadexe, sizeof(winloadexe)) == 0)
            {
                pos[i + sizeof(winloadexe) - 4] = 0x66;
                pos[i + sizeof(winloadexe) - 2] = 0x69;
                cnt++;
            }
        }
        debug("winload patch %d times\n", cnt);
    }
    newpath = grub_strdup(vhdpath);
    for (pos = newpath; *pos; pos++)
    {
        if (*pos == '/')
        {
            *pos = '\\';
        }
    }
    
    grub_utf8_to_utf16(unicode_path, pathlen, (grub_uint8_t *)newpath, -1, NULL);
    grub_memcpy(patch1->vhd_file_path, unicode_path, pathlen);
    grub_memcpy(patch2->vhd_file_path, unicode_path, pathlen);
    grub_free(newpath);
    return 0;
}
static int ventoy_vhd_read_parttbl(const char *filename, ventoy_gpt_info *gpt, int *index, grub_uint64_t *poffset)
{
    int i;
    int find = 0;
    int ret = 1;
    grub_uint64_t start;
    grub_file_t file = NULL;
    grub_disk_t disk = NULL;
    grub_uint8_t zeroguid[16] = {0};
    file = grub_file_open(filename, VENTOY_FILE_TYPE);
    if (!file)
    {
        goto end;
    }
    disk = grub_disk_open(file->device->disk->name);
    if (!disk)
    {
        goto end;
    }
    grub_disk_read(disk, 0, 0, sizeof(ventoy_gpt_info), gpt);
    start = file->device->disk->partition->start;
    if (grub_memcmp(gpt->Head.Signature, "EFI PART", 8) == 0)
    {
        debug("GPT part start: %llu\n", (ulonglong)start);
        for (i = 0; i < 128; i++)
        {
            if (grub_memcmp(gpt->PartTbl[i].PartGuid, zeroguid, 16))
            {
                if (start == gpt->PartTbl[i].StartLBA)
                {
                    *index = i;
                    find = 1;
                    break;
                }
            }
        }
    }
    else
    {
        debug("MBR part start: %llu\n", (ulonglong)start);
        for (i = 0; i < 4; i++)
        {
            if ((grub_uint32_t)start == gpt->MBR.PartTbl[i].StartSectorId)
            {
                *index = i;
                find = 1;
                break;
            }
        }
    }    
    if (find == 0) // MBR Logical partition
    {
        if (file->device->disk->partition->number > 0)
        {
            *index = file->device->disk->partition->number;
            debug("Fall back part number: %d\n", *index);
        }
    }
    *poffset = start;
    ret = 0;
end:
    check_free(file, grub_file_close);
    check_free(disk, grub_disk_close);
    return ret;
}
static int ventoy_vhd_patch_disk(const char *vhdpath, ventoy_patch_vhd *patch1, ventoy_patch_vhd *patch2)
{
    int partIndex = 0;
    grub_uint64_t offset = 0;
    char efipart[16] = {0};
    ventoy_gpt_info *gpt = NULL;
    if (vhdpath[0] == '/')
    {
        gpt = g_ventoy_part_info;  
        partIndex = 0;
        debug("This is Ventoy ISO partIndex %d %s\n", partIndex, vhdpath);
    }
    else
    {
        gpt = grub_zalloc(sizeof(ventoy_gpt_info));
        ventoy_vhd_read_parttbl(vhdpath, gpt, &partIndex, &offset);
        debug("This is HDD partIndex %d %s\n", partIndex, vhdpath);
    }
    grub_memcpy(efipart, gpt->Head.Signature, sizeof(gpt->Head.Signature));
    grub_memset(patch1, 0, OFFSET_OF(ventoy_patch_vhd, vhd_file_path));
    grub_memset(patch2, 0, OFFSET_OF(ventoy_patch_vhd, vhd_file_path));
    if (grub_strncmp(efipart, "EFI PART", 8) == 0)
    {
        ventoy_debug_dump_guid("GPT disk GUID: ", gpt->Head.DiskGuid);
        ventoy_debug_dump_guid("GPT partIndex GUID: ", gpt->PartTbl[partIndex].PartGuid);
        
        grub_memcpy(patch1->disk_signature_or_guid, gpt->Head.DiskGuid, 16);
        grub_memcpy(patch1->part_offset_or_guid, gpt->PartTbl[partIndex].PartGuid, 16);
        grub_memcpy(patch2->disk_signature_or_guid, gpt->Head.DiskGuid, 16);
        grub_memcpy(patch2->part_offset_or_guid, gpt->PartTbl[partIndex].PartGuid, 16);
        patch1->part_type = patch2->part_type = 0;
    }
    else
    {
        if (offset == 0)
        {
            offset = gpt->MBR.PartTbl[partIndex].StartSectorId;
        }
        offset *= 512;
        debug("MBR disk signature: %02x%02x%02x%02x Part(%d) offset:%llu\n",
            gpt->MBR.BootCode[0x1b8 + 0], gpt->MBR.BootCode[0x1b8 + 1],
            gpt->MBR.BootCode[0x1b8 + 2], gpt->MBR.BootCode[0x1b8 + 3],
            partIndex + 1, offset);
        grub_memcpy(patch1->part_offset_or_guid, &offset, 8);
        grub_memcpy(patch2->part_offset_or_guid, &offset, 8);
        
        grub_memcpy(patch1->disk_signature_or_guid, gpt->MBR.BootCode + 0x1b8, 4);
        grub_memcpy(patch2->disk_signature_or_guid, gpt->MBR.BootCode + 0x1b8, 4);
        patch1->part_type = patch2->part_type = 1;
    }
    if (gpt != g_ventoy_part_info)
    {
        grub_free(gpt);
    }
    return 0;
}
static int ventoy_find_vhdpatch_offset(int bcdoffset, int bcdlen, int *offset)
{
    int i;
    int cnt = 0;
    grub_uint8_t *buf = (grub_uint8_t *)(g_vhdboot_isobuf + bcdoffset);
    grub_uint8_t magic[16] = { 
        0x5C, 0x00, 0x58, 0x00, 0x58, 0x00, 0x58, 0x00, 0x58, 0x00, 0x58, 0x00, 0x58, 0x00, 0x58, 0x00 
    };
    for (i = 0; i < bcdlen - 16 && cnt < 2; i++)
    {
        if (*(grub_uint32_t *)(buf + i) == 0x0058005C)
        {
            if (grub_memcmp(magic, buf + i, 16) == 0)
            {
                *offset++ = i - (int)OFFSET_OF(ventoy_patch_vhd, vhd_file_path); 
                cnt++;
            }
        }
    }
    return 0;
}
grub_err_t ventoy_cmd_patch_vhdboot(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int rc;
    int bcdoffset, bcdlen;
    int patchoffset[2];
    ventoy_patch_vhd *patch1;
    ventoy_patch_vhd *patch2;
    (void)ctxt;
    (void)argc;
    grub_env_unset("vtoy_vhd_buf_addr");
    debug("patch vhd <%s>\n", args[0]);
    if ((!g_vhdboot_enable) || (!g_vhdboot_totbuf))
    {
        debug("vhd boot not ready %d %p\n", g_vhdboot_enable, g_vhdboot_totbuf);
        return 0;
    }
    rc = ventoy_vhd_find_bcd(&bcdoffset, &bcdlen, "/boot/bcd");
    if (rc)
    {
        debug("failed to get bcd location %d\n", rc);
    }
    else
    {
        ventoy_find_vhdpatch_offset(bcdoffset, bcdlen, patchoffset);
        patch1 = (ventoy_patch_vhd *)(g_vhdboot_isobuf + bcdoffset + patchoffset[0]);
        patch2 = (ventoy_patch_vhd *)(g_vhdboot_isobuf + bcdoffset + patchoffset[1]);
        debug("Find /boot/bcd (%d %d) now patch it (offset: 0x%x 0x%x) ...\n", 
              bcdoffset, bcdlen, patchoffset[0], patchoffset[1]);
        ventoy_vhd_patch_disk(args[0], patch1, patch2);
        ventoy_vhd_patch_path(args[0], patch1, patch2, bcdoffset, bcdlen);
    }
    rc = ventoy_vhd_find_bcd(&bcdoffset, &bcdlen, "/boot/BCD");
    if (rc)
    {
        debug("No file /boot/BCD \n");
    }
    else
    {
        ventoy_find_vhdpatch_offset(bcdoffset, bcdlen, patchoffset);
        patch1 = (ventoy_patch_vhd *)(g_vhdboot_isobuf + bcdoffset + patchoffset[0]);
        patch2 = (ventoy_patch_vhd *)(g_vhdboot_isobuf + bcdoffset + patchoffset[1]);
        
        debug("Find /boot/BCD (%d %d) now patch it (offset: 0x%x 0x%x) ...\n", 
              bcdoffset, bcdlen, patchoffset[0], patchoffset[1]);
        ventoy_vhd_patch_disk(args[0], patch1, patch2);
        ventoy_vhd_patch_path(args[0], patch1, patch2, bcdoffset, bcdlen);
    }
    /* set buffer and size */
#ifdef GRUB_MACHINE_EFI
    ventoy_memfile_env_set("vtoy_vhd_buf", g_vhdboot_totbuf, (ulonglong)(g_vhdboot_isolen + sizeof(ventoy_chain_head)));
#else
    ventoy_memfile_env_set("vtoy_vhd_buf", g_vhdboot_isobuf, (ulonglong)g_vhdboot_isolen);
#endif
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
grub_err_t ventoy_cmd_load_vhdboot(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int buflen;
    grub_file_t file;
    
    (void)ctxt;
    (void)argc;
    g_vhdboot_enable = 0;
    grub_check_free(g_vhdboot_totbuf);
    file = grub_file_open(args[0], VENTOY_FILE_TYPE);
    if (!file)
    {
        return 0;
    }
    debug("load vhd boot: <%s> <%lu>\n", args[0], (ulong)file->size);
    if (file->size < VTOY_SIZE_1KB * 32)
    {
        grub_file_close(file);
        return 0;
    }
    g_vhdboot_isolen = (int)file->size;
    buflen = (int)(file->size + sizeof(ventoy_chain_head));
#ifdef GRUB_MACHINE_EFI
    g_vhdboot_totbuf = (char *)grub_efi_allocate_iso_buf(buflen);
#else
    g_vhdboot_totbuf = (char *)grub_malloc(buflen);
#endif
    
    if (!g_vhdboot_totbuf)
    {
        grub_file_close(file);
        return 0;
    }
    g_vhdboot_isobuf = g_vhdboot_totbuf + sizeof(ventoy_chain_head);
    grub_file_read(file, g_vhdboot_isobuf, file->size);
    grub_file_close(file);
    g_vhdboot_enable = 1;
    return 0;
}
static int ventoy_raw_trim_head(grub_uint64_t offset)
{
    grub_uint32_t i;
    grub_uint32_t memsize;
    grub_uint32_t imgstart = 0;
    grub_uint32_t imgsecs = 0;
    grub_uint64_t sectors = 0;
    grub_uint64_t cursecs = 0;
    grub_uint64_t delta = 0;
    if ((!g_img_chunk_list.chunk) || (!offset))
    {
        debug("image chunk not ready %p %lu\n", g_img_chunk_list.chunk, (ulong)offset);
        return 0;
    }
    debug("image trim head %lu\n", (ulong)offset);
    for (i = 0; i < g_img_chunk_list.cur_chunk; i++)
    {
        cursecs = g_img_chunk_list.chunk[i].disk_end_sector + 1 - g_img_chunk_list.chunk[i].disk_start_sector;
        sectors += cursecs;
        if (sectors >= offset)
        {
            delta = cursecs - (sectors - offset);
            break;
        }
    }
    if (sectors < offset || i >= g_img_chunk_list.cur_chunk)
    {
        debug("Invalid size %lu %lu\n", (ulong)sectors, (ulong)offset);
        return 0;
    }
    if (sectors == offset)
    {
        memsize = (g_img_chunk_list.cur_chunk - (i + 1)) * sizeof(ventoy_img_chunk);
        grub_memmove(g_img_chunk_list.chunk, g_img_chunk_list.chunk + i + 1, memsize);
        g_img_chunk_list.cur_chunk -= (i + 1);
    }
    else
    {
        g_img_chunk_list.chunk[i].disk_start_sector += delta;
        g_img_chunk_list.chunk[i].img_start_sector += (grub_uint32_t)(delta / 4);
    
        if (i > 0)
        {
            memsize = (g_img_chunk_list.cur_chunk - i) * sizeof(ventoy_img_chunk);
            grub_memmove(g_img_chunk_list.chunk, g_img_chunk_list.chunk + i, memsize);
            g_img_chunk_list.cur_chunk -= i;
        }
    }
    for (i = 0; i < g_img_chunk_list.cur_chunk; i++)
    {
        imgsecs = g_img_chunk_list.chunk[i].img_end_sector + 1 - g_img_chunk_list.chunk[i].img_start_sector;        
        g_img_chunk_list.chunk[i].img_start_sector = imgstart;
        g_img_chunk_list.chunk[i].img_end_sector = imgstart + (imgsecs - 1);
        imgstart += imgsecs;
    }
    return 0;
}
grub_err_t ventoy_cmd_get_vtoy_type(grub_extcmd_context_t ctxt, int argc, char **args)
{
    int i;
    int altboot = 0;
    int offset = -1;
    grub_file_t file;
    grub_uint8_t data = 0;
    vhd_footer_t vhdfoot;
    VDIPREHEADER vdihdr;
    char type[16] = {0};
    ventoy_gpt_info *gpt = NULL;
    
    (void)ctxt;
    g_img_trim_head_secnum = 0;
    if (argc != 4)
    {
        return 0;
    }
    file = grub_file_open(args[0], VENTOY_FILE_TYPE);
    if (!file)
    {
        debug("Failed to open file %s\n", args[0]);
        return 0;
    }
    grub_snprintf(type, sizeof(type), "unknown");
    
    grub_file_seek(file, file->size - 512);
    grub_file_read(file, &vhdfoot, sizeof(vhdfoot));
    if (grub_strncmp(vhdfoot.cookie, "conectix", 8) == 0)
    {
        offset = 0;
        grub_snprintf(type, sizeof(type), "vhd%u", grub_swap_bytes32(vhdfoot.disktype));
    }
    else
    {
        grub_file_seek(file, 0);
        grub_file_read(file, &vdihdr, sizeof(vdihdr));
        if (vdihdr.u32Signature == VDI_IMAGE_SIGNATURE &&
            grub_strncmp(vdihdr.szFileInfo, VDI_IMAGE_FILE_INFO, grub_strlen(VDI_IMAGE_FILE_INFO)) == 0)
        {
            offset = 2 * 1048576;
            g_img_trim_head_secnum = offset / 512;
            grub_snprintf(type, sizeof(type), "vdi");
        }
        else
        {
            offset = 0;
            grub_snprintf(type, sizeof(type), "raw");
        }
    }
    grub_env_set(args[1], type);
    debug("<%s> vtoy type: <%s> offset:%d\n", args[0], type, offset);
    
    if (offset >= 0)
    {
        gpt = grub_zalloc(sizeof(ventoy_gpt_info));
        if (!gpt)
        {
            grub_env_set(args[1], "unknown");
            goto end;
        }
    
        grub_file_seek(file, offset);
        grub_file_read(file, gpt, sizeof(ventoy_gpt_info));
        if (gpt->MBR.Byte55 != 0x55 || gpt->MBR.ByteAA != 0xAA)
        {
            grub_env_set(args[1], "unknown");
            debug("invalid mbr signature: 0x%x 0x%x\n", gpt->MBR.Byte55, gpt->MBR.ByteAA);
            goto end;
        }
        if (grub_memcmp(gpt->Head.Signature, "EFI PART", 8) == 0)
        {
            grub_env_set(args[2], "gpt");
            debug("part type: %s\n", "GPT");
            if (gpt->MBR.PartTbl[0].FsFlag == 0xEE)
            {
                for (i = 0; i < 128; i++)
                {
                    if (grub_memcmp(gpt->PartTbl[i].PartType, "Hah!IdontNeedEFI", 16) == 0)
                    {
                        debug("part %d is grub_bios part\n", i);
                        altboot = 1;
                        grub_env_set(args[3], "1");
                        break;
                    }
                    else if (gpt->PartTbl[i].LastLBA == 0)
                    {
                        break;
                    }
                }
            }
            if (!altboot)
            {
                if (gpt->MBR.BootCode[92] == 0x22)
                {
                    grub_file_seek(file, offset + 17908);
                    grub_file_read(file, &data, 1);
                    if (data == 0x23)
                    {
                        altboot = 1;
                        grub_env_set(args[3], "1");                        
                    }
                    else
                    {
                        debug("offset data=0x%x\n", data);
                    }
                }
                else
                {
                    debug("BootCode: 0x%x\n", gpt->MBR.BootCode[92]);
                }
            }
        }
        else
        {
            grub_env_set(args[2], "mbr");
            debug("part type: %s\n", "MBR");
            for (i = 0; i < 4; i++)
            {
                if (gpt->MBR.PartTbl[i].FsFlag == 0xEF)
                {
                    debug("part %d is esp part in MBR mode\n", i);
                    altboot = 1;
                    grub_env_set(args[3], "1");
                    break;
                }
            }
        }
    }
    else
    {
        debug("part type: %s\n", "xxx");
    }
end:
    grub_check_free(gpt);
    grub_file_close(file);
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);    
}
grub_err_t ventoy_cmd_raw_chain_data(grub_extcmd_context_t ctxt, int argc, char **args)
{
    grub_uint32_t size = 0;
    grub_uint32_t img_chunk_size = 0;
    grub_file_t file;
    grub_disk_t disk;
    const char *pLastChain = NULL;
    ventoy_chain_head *chain;
    
    (void)ctxt;
    (void)argc;
    if (NULL == g_img_chunk_list.chunk)
    {
        grub_printf("ventoy not ready\n");
        return 1;
    }
    if (g_img_trim_head_secnum > 0)
    {
        ventoy_raw_trim_head(g_img_trim_head_secnum);
    }
    file = ventoy_grub_file_open(VENTOY_FILE_TYPE, "%s", args[0]);
    if (!file)
    {
        return 1;
    }
    if (grub_strncmp(args[0], g_iso_path, grub_strlen(g_iso_path)))
    {
        file->vlnk = 1;
    }
    img_chunk_size = g_img_chunk_list.cur_chunk * sizeof(ventoy_img_chunk);
    
    size = sizeof(ventoy_chain_head) + img_chunk_size;
    
    pLastChain = grub_env_get("vtoy_chain_mem_addr");
    if (pLastChain)
    {
        chain = (ventoy_chain_head *)grub_strtoul(pLastChain, NULL, 16);
        if (chain)
        {
            debug("free last chain memory %p\n", chain);
            grub_free(chain);
        }
    }
    chain = ventoy_alloc_chain(size);
    if (!chain)
    {
        grub_printf("Failed to alloc chain raw memory size %u\n", size);
        grub_file_close(file);
        return 1;
    }
    ventoy_memfile_env_set("vtoy_chain_mem", chain, (ulonglong)size);
    grub_env_export("vtoy_chain_mem_addr");
    grub_env_export("vtoy_chain_mem_size");
    grub_memset(chain, 0, sizeof(ventoy_chain_head));
    /* part 1: os parameter */
    g_ventoy_chain_type = ventoy_chain_linux;
    ventoy_fill_os_param(file, &(chain->os_param));
    /* part 2: chain head */
    disk = file->device->disk;
    chain->disk_drive = disk->id;
    chain->disk_sector_size = (1 << disk->log_sector_size);
    chain->real_img_size_in_bytes = file->size;
    if (g_img_trim_head_secnum > 0)
    {
        chain->real_img_size_in_bytes -= g_img_trim_head_secnum * 512;
    }
    
    chain->virt_img_size_in_bytes = chain->real_img_size_in_bytes;
    chain->boot_catalog = 0;
    /* part 3: image chunk */
    chain->img_chunk_offset = sizeof(ventoy_chain_head);
    chain->img_chunk_num = g_img_chunk_list.cur_chunk;
    grub_memcpy((char *)chain + chain->img_chunk_offset, g_img_chunk_list.chunk, img_chunk_size);
    grub_file_seek(file, g_img_trim_head_secnum * 512);
    grub_file_read(file, chain->boot_catalog_sector, 512);
    grub_file_close(file);
    
    VENTOY_CMD_RETURN(GRUB_ERR_NONE);
}
 | 20,859 | 
	C | 
	.c | 620 | 25.854839 | 122 | 0.562344 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 626 | 
	vtoykmod.c | 
	ventoy_Ventoy/VtoyTool/vtoykmod.c | 
	/******************************************************************************
 * vtoykmod.c  ---- ventoy kmod
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#ifdef VTOY_X86_64
#include <cpuid.h>
#endif
#define _ull unsigned long long
#define magic_sig 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF
#define EI_NIDENT (16)
#define	EI_MAG0		0		/* e_ident[] indexes */
#define	EI_MAG1		1
#define	EI_MAG2		2
#define	EI_MAG3		3
#define	EI_CLASS	4
#define	EI_DATA		5
#define	EI_VERSION	6
#define	EI_OSABI	7
#define	EI_PAD		8
#define	ELFMAG0		0x7f		/* EI_MAG */
#define	ELFMAG1		'E'
#define	ELFMAG2		'L'
#define	ELFMAG3		'F'
#define	ELFMAG		"\177ELF"
#define	SELFMAG		4
#define	ELFCLASSNONE	0		/* EI_CLASS */
#define	ELFCLASS32	1
#define	ELFCLASS64	2
#define	ELFCLASSNUM	3
#define ELFDATANONE	0		/* e_ident[EI_DATA] */
#define ELFDATA2LSB	1
#define ELFDATA2MSB	2
#define EV_NONE		0		/* e_version, EI_VERSION */
#define EV_CURRENT	1
#define EV_NUM		2
#define ELFOSABI_NONE	0
#define ELFOSABI_LINUX	3
#define SHT_STRTAB	3
#pragma pack(1)
typedef struct
{
    unsigned char	e_ident[EI_NIDENT];	/* Magic number and other info */
    uint16_t	e_type;			/* Object file type */
    uint16_t	e_machine;		/* Architecture */
    uint32_t	e_version;		/* Object file version */
    uint32_t	e_entry;		/* Entry point virtual address */
    uint32_t	e_phoff;		/* Program header table file offset */
    uint32_t	e_shoff;		/* Section header table file offset */
    uint32_t	e_flags;		/* Processor-specific flags */
    uint16_t	e_ehsize;		/* ELF header size in bytes */
    uint16_t	e_phentsize;	/* Program header table entry size */
    uint16_t	e_phnum;		/* Program header table entry count */
    uint16_t	e_shentsize;	/* Section header table entry size */
    uint16_t	e_shnum;		/* Section header table entry count */
    uint16_t	e_shstrndx;		/* Section header string table index */
} Elf32_Ehdr;
typedef struct
{
    unsigned char	e_ident[EI_NIDENT];	/* Magic number and other info */
    uint16_t	e_type;			/* Object file type */
    uint16_t	e_machine;		/* Architecture */
    uint32_t	e_version;		/* Object file version */
    uint64_t	e_entry;		/* Entry point virtual address */
    uint64_t	e_phoff;		/* Program header table file offset */
    uint64_t	e_shoff;		/* Section header table file offset */
    uint32_t	e_flags;		/* Processor-specific flags */
    uint16_t	e_ehsize;		/* ELF header size in bytes */
    uint16_t	e_phentsize;	/* Program header table entry size */
    uint16_t	e_phnum;		/* Program header table entry count */
    uint16_t	e_shentsize;	/* Section header table entry size */
    uint16_t	e_shnum;		/* Section header table entry count */
    uint16_t	e_shstrndx;		/* Section header string table index */
} Elf64_Ehdr;
typedef struct
{
    uint32_t	sh_name;		/* Section name (string tbl index) */
    uint32_t	sh_type;		/* Section type */
    uint32_t	sh_flags;		/* Section flags */
    uint32_t	sh_addr;		/* Section virtual addr at execution */
    uint32_t	sh_offset;		/* Section file offset */
    uint32_t	sh_size;		/* Section size in bytes */
    uint32_t	sh_link;		/* Link to another section */
    uint32_t	sh_info;		/* Additional section information */
    uint32_t	sh_addralign;	/* Section alignment */
    uint32_t	sh_entsize;		/* Entry size if section holds table */
} Elf32_Shdr;
typedef struct
{
    uint32_t	sh_name;		/* Section name (string tbl index) */
    uint32_t	sh_type;		/* Section type */
    uint64_t	sh_flags;		/* Section flags */
    uint64_t	sh_addr;		/* Section virtual addr at execution */
    uint64_t	sh_offset;		/* Section file offset */
    uint64_t	sh_size;		/* Section size in bytes */
    uint32_t	sh_link;		/* Link to another section */
    uint32_t	sh_info;		/* Additional section information */
    uint64_t	sh_addralign;	/* Section alignment */
    uint64_t	sh_entsize;		/* Entry size if section holds table */
} Elf64_Shdr;
typedef struct elf32_rel {
  uint32_t	r_offset;
  uint32_t	r_info;
} Elf32_Rel;
typedef struct elf64_rel {
  uint64_t r_offset;	/* Location at which to apply the action */
  uint64_t r_info;	    /* index and type of relocation */
} Elf64_Rel;
typedef struct elf32_rela{
  uint32_t	r_offset;
  uint32_t	r_info;
  int32_t	r_addend;
} Elf32_Rela;
typedef struct elf64_rela {
  uint64_t r_offset;	/* Location at which to apply the action */
  uint64_t r_info;	    /* index and type of relocation */
  int64_t  r_addend;	/* Constant addend used to compute value */
} Elf64_Rela;
struct modversion_info {
	unsigned long crc;
	char name[64 - sizeof(unsigned long)];
};
struct modversion_info2 {
	/* Offset of the next modversion entry in relation to this one. */
	uint32_t next;
	uint32_t crc;
	char name[0];
};
typedef struct ko_param
{
    unsigned char magic[16];
    unsigned long struct_size;
    unsigned long pgsize;
    unsigned long printk_addr;
    unsigned long ro_addr;
    unsigned long rw_addr;
    unsigned long reg_kprobe_addr;
    unsigned long unreg_kprobe_addr;
    unsigned long sym_get_addr;
    unsigned long sym_get_size;
    unsigned long sym_put_addr;
    unsigned long sym_put_size;
    unsigned long kv_major;
    unsigned long ibt;
    unsigned long kv_minor;
    unsigned long blkdev_get_addr;
    unsigned long blkdev_put_addr;
    unsigned long bdev_open_addr;
    unsigned long kv_subminor;
    unsigned long bdev_file_open_addr;
    unsigned long padding[1];
}ko_param;
#pragma pack()
static int verbose = 0;
#define debug(fmt, ...) if(verbose) printf(fmt, ##__VA_ARGS__)
static int vtoykmod_write_file(char *name, void *buf, int size)
{
    FILE *fp;
    fp = fopen(name, "wb+");
    if (!fp)
    {
        return -1;
    }
    
    fwrite(buf, 1, size, fp);
    fclose(fp);
    return 0;
}
static int vtoykmod_read_file(char *name, char **buf)
{
    int size;
    FILE *fp;
    char *databuf;
    fp = fopen(name, "rb");
    if (!fp)
    {
        debug("failed to open %s %d\n", name, errno);
        return -1;
    }
    
    fseek(fp, 0, SEEK_END);
    size = (int)ftell(fp);
    fseek(fp, 0, SEEK_SET);
    databuf = malloc(size);
    if (!databuf)
    {
        debug("failed to open malloc %d\n", size);
        return -1;
    }
    
    fread(databuf, 1, size, fp);
    fclose(fp);
    *buf = databuf;
    return size;
}
static int vtoykmod_find_section64(char *buf, char *section, int *offset, int *len, Elf64_Shdr **shdr)
{
    uint16_t i;
    int cmplen;
    char *name = NULL;
    char *strtbl = NULL;
    Elf64_Ehdr *elf = NULL;
    Elf64_Shdr *sec = NULL;
    cmplen = (int)strlen(section);
    elf = (Elf64_Ehdr *)buf;
    sec = (Elf64_Shdr *)(buf + elf->e_shoff);
    strtbl = buf + sec[elf->e_shstrndx].sh_offset;
    for (i = 0; i < elf->e_shnum; i++)
    {
        name = strtbl + sec[i].sh_name;
        if (name && strncmp(name, section, cmplen) == 0)
        {
            *offset = (int)(sec[i].sh_offset);
            *len = (int)(sec[i].sh_size);
            if (shdr)
            {
                *shdr = sec + i;
            }
            return 0;
        }
    }
    return 1;
}
static int vtoykmod_find_section32(char *buf, char *section, int *offset, int *len, Elf32_Shdr **shdr)
{
    uint16_t i;
    int cmplen;
    char *name = NULL;
    char *strtbl = NULL;
    Elf32_Ehdr *elf = NULL;
    Elf32_Shdr *sec = NULL;
    cmplen = (int)strlen(section);
    elf = (Elf32_Ehdr *)buf;
    sec = (Elf32_Shdr *)(buf + elf->e_shoff);
    strtbl = buf + sec[elf->e_shstrndx].sh_offset;
    for (i = 0; i < elf->e_shnum; i++)
    {
        name = strtbl + sec[i].sh_name;
        if (name && strncmp(name, section, cmplen) == 0)
        {
            *offset = (int)(sec[i].sh_offset);
            *len = (int)(sec[i].sh_size);
            if (shdr)
            {
                *shdr = sec + i;
            }
            return 0;
        }
    }
    return 1;
}
static int vtoykmod_update_modcrc1(char *oldmodver, int oldcnt, char *newmodver, int newcnt)
{
    int i, j;
    struct modversion_info *pold, *pnew;
    pold = (struct modversion_info *)oldmodver;
    pnew = (struct modversion_info *)newmodver;
    debug("module update modver format 1\n");
    for (i = 0; i < oldcnt; i++)
    {
        for (j = 0; j < newcnt; j++)
        {
            if (strcmp(pold[i].name, pnew[j].name) == 0)
            {
                debug("CRC  0x%08lx --> 0x%08lx  %s\n", pold[i].crc, pnew[i].crc, pold[i].name);
                pold[i].crc = pnew[j].crc;
                break;
            }
        }
    }
    return 0;
}
static int vtoykmod_update_modcrc2(char *oldmodver, int oldlen, char *newmodver, int newlen)
{
    struct modversion_info2 *pold, *pnew, *pnewend;
    pold = (struct modversion_info2 *)oldmodver;
    pnew = (struct modversion_info2 *)newmodver;
    pnewend = (struct modversion_info2 *)(newmodver + newlen);
    debug("module update modver format 2\n");
    /* here we think that there is only module_layout in oldmodver */
    for (; pnew < pnewend && pnew->next; pnew = (struct modversion_info2 *)((char *)pnew + pnew->next))
    {
	    if (strcmp(pnew->name, "module_layout") == 0)
        {
            debug("CRC  0x%08x --> 0x%08x  %s\n", pold->crc, pnew->crc, pnew->name);
            memset(pold, 0, oldlen);
            pold->next = 0x18;  /* 8 + module_layout align 8 */
            pold->crc = pnew->crc;
            strcpy(pold->name, pnew->name);
            break;
        }
    }
    return 0;
}
static int vtoykmod_update_modcrc(char *oldmodver, int oldlen, char *newmodver, int newlen)
{
    uint32_t uiCrc = 0;
    memcpy(&uiCrc, newmodver + 4, 4);
    if (uiCrc > 0)
    {
        return vtoykmod_update_modcrc2(oldmodver, oldlen, newmodver, newlen);
    }
    else
    {
        return vtoykmod_update_modcrc1(oldmodver, oldlen / 64, newmodver, newlen / 64);
    }
}
static int vtoykmod_update_vermagic(char *oldbuf, int oldsize, char *newbuf, int newsize, int *modver)
{
    int i = 0;
    char *oldver = NULL;
    char *newver = NULL;
    *modver = 0;
    for (i = 0; i < oldsize - 9; i++)
    {
        if (strncmp(oldbuf + i, "vermagic=", 9) == 0)
        {
            oldver = oldbuf + i + 9;
            debug("Find old vermagic at %d <%s>\n", i, oldver);
            break;
        }
    }
    
    for (i = 0; i < newsize - 9; i++)
    {
        if (strncmp(newbuf + i, "vermagic=", 9) == 0)
        {
            newver = newbuf + i + 9;
            debug("Find new vermagic at %d <%s>\n", i, newver);
            break;
        }
    }
    if (oldver && newver)
    {
        memcpy(oldver, newver, strlen(newver) + 1);
        //if (strstr(newver, "modversions"))
        {
            *modver = 1;
        }
    }
    return 0;
}
int vtoykmod_update(int kvMajor, int kvMinor, char *oldko, char *newko)
{
    int rc = 0;
    int modver = 0;
    int oldoff, oldlen;
    int newoff, newlen;
    int oldsize, newsize;
    char *newbuf, *oldbuf;
    Elf64_Shdr *sec = NULL;
    oldsize = vtoykmod_read_file(oldko, &oldbuf);
    newsize = vtoykmod_read_file(newko, &newbuf);
    if (oldsize < 0 || newsize < 0)
    {
        return 1;
    }
    /* 1: update vermagic */
    vtoykmod_update_vermagic(oldbuf, oldsize, newbuf, newsize, &modver);
    /* 2: update modversion crc */
    if (modver)
    {
        if (oldbuf[EI_CLASS] == ELFCLASS64)
        {
            rc  = vtoykmod_find_section64(oldbuf, "__versions", &oldoff, &oldlen, NULL);
            rc += vtoykmod_find_section64(newbuf, "__versions", &newoff, &newlen, NULL);            
        }
        else
        {
            rc  = vtoykmod_find_section32(oldbuf, "__versions", &oldoff, &oldlen, NULL);
            rc += vtoykmod_find_section32(newbuf, "__versions", &newoff, &newlen, NULL);
        }
        if (rc == 0)
        {
            vtoykmod_update_modcrc(oldbuf + oldoff, oldlen, newbuf + newoff, newlen);
        }
    }
    else
    {
        debug("no need to proc modversions\n");
    }
    
    /* 3: update relocate address */
    if (oldbuf[EI_CLASS] == ELFCLASS64)
    {
        Elf64_Rela *oldRela, *newRela;
        
        rc  = vtoykmod_find_section64(oldbuf, ".rela.gnu.linkonce.this_module", &oldoff, &oldlen, NULL);
        rc += vtoykmod_find_section64(newbuf, ".rela.gnu.linkonce.this_module", &newoff, &newlen, NULL);
        if (rc == 0)
        {
            oldRela = (Elf64_Rela *)(oldbuf + oldoff);
            newRela = (Elf64_Rela *)(newbuf + newoff);
            
            debug("init_module rela: 0x%llx --> 0x%llx\n", (_ull)(oldRela[0].r_offset), (_ull)(newRela[0].r_offset));
            oldRela[0].r_offset = newRela[0].r_offset;
            oldRela[0].r_addend = newRela[0].r_addend;
            
            debug("cleanup_module rela: 0x%llx --> 0x%llx\n", (_ull)(oldRela[1].r_offset), (_ull)(newRela[1].r_offset));
            oldRela[1].r_offset = newRela[1].r_offset;
            oldRela[1].r_addend = newRela[1].r_addend;
        }
        else
        {
            debug("section .rela.gnu.linkonce.this_module not found\n");
        }
        if (kvMajor > 6 || (kvMajor == 6 && kvMinor >= 3))
        {
            rc  = vtoykmod_find_section64(oldbuf, ".gnu.linkonce.this_module", &oldoff, &oldlen, &sec);
            rc += vtoykmod_find_section64(newbuf, ".gnu.linkonce.this_module", &newoff, &newlen, NULL);
            if (rc == 0)
            {
                debug("section .gnu.linkonce.this_module change oldlen:0x%x to newlen:0x%x\n", oldlen, newlen);
                if (sec)
                {
                    sec->sh_size = newlen;                
                }
            }
            else
            {
                debug("section .gnu.linkonce.this_module not found\n");
            }
        }
    }
    else
    {
        Elf32_Rel *oldRel, *newRel;
        
        rc  = vtoykmod_find_section32(oldbuf, ".rel.gnu.linkonce.this_module", &oldoff, &oldlen, NULL);
        rc += vtoykmod_find_section32(newbuf, ".rel.gnu.linkonce.this_module", &newoff, &newlen, NULL);
        if (rc == 0)
        {
            oldRel = (Elf32_Rel *)(oldbuf + oldoff);
            newRel = (Elf32_Rel *)(newbuf + newoff);
            debug("init_module rel: 0x%x --> 0x%x\n", oldRel[0].r_offset, newRel[0].r_offset);
            oldRel[0].r_offset = newRel[0].r_offset;
            debug("cleanup_module rel: 0x%x --> 0x%x\n", oldRel[0].r_offset, newRel[0].r_offset);
            oldRel[1].r_offset = newRel[1].r_offset;
        }
        else
        {
            debug("section .rel.gnu.linkonce.this_module not found\n");
        }
    }
    vtoykmod_write_file(oldko, oldbuf, oldsize);
    free(oldbuf);
    free(newbuf);
    return 0;
}
int vtoykmod_fill_param(char **argv)
{
    int i;
    int size;
    char *buf = NULL;
    ko_param *param;
    unsigned char magic[16] = { magic_sig };
    
    size = vtoykmod_read_file(argv[0], &buf);
    if (size < 0)
    {
        return 1;
    }
    for (i = 0; i < size; i++)
    {
        if (memcmp(buf + i, magic, 16) == 0)
        {
            debug("Find param magic at %d\n", i);
            param = (ko_param *)(buf + i);
            
            param->struct_size = (unsigned long)sizeof(ko_param);
            param->pgsize = strtoul(argv[1], NULL, 10);
            param->printk_addr = strtoul(argv[2], NULL, 16);
            param->ro_addr = strtoul(argv[3], NULL, 16);
            param->rw_addr = strtoul(argv[4], NULL, 16);
            param->sym_get_addr = strtoul(argv[5], NULL, 16);
            param->sym_get_size = strtoul(argv[6], NULL, 10);
            param->sym_put_addr = strtoul(argv[7], NULL, 16);
            param->sym_put_size = strtoul(argv[8], NULL, 10);
            param->reg_kprobe_addr = strtoul(argv[9], NULL, 16);
            param->unreg_kprobe_addr = strtoul(argv[10], NULL, 16);
            param->kv_major = strtoul(argv[11], NULL, 10);
            param->ibt = strtoul(argv[12], NULL, 16);;
            param->kv_minor = strtoul(argv[13], NULL, 10);
            param->blkdev_get_addr = strtoul(argv[14], NULL, 16);
            param->blkdev_put_addr = strtoul(argv[15], NULL, 16);
            param->kv_subminor = strtoul(argv[16], NULL, 10);
            param->bdev_open_addr = strtoul(argv[17], NULL, 16);
            param->bdev_file_open_addr = strtoul(argv[18], NULL, 16);
            debug("pgsize=%lu (%s)\n", param->pgsize, argv[1]);
            debug("printk_addr=0x%lx (%s)\n", param->printk_addr, argv[2]);
            debug("ro_addr=0x%lx (%s)\n", param->ro_addr, argv[3]);
            debug("rw_addr=0x%lx (%s)\n", param->rw_addr, argv[4]);
            debug("sym_get_addr=0x%lx (%s)\n", param->sym_get_addr, argv[5]);
            debug("sym_get_size=%lu (%s)\n", param->sym_get_size, argv[6]);
            debug("sym_put_addr=0x%lx (%s)\n", param->sym_put_addr, argv[7]);
            debug("sym_put_size=%lu (%s)\n", param->sym_put_size, argv[8]);
            debug("reg_kprobe_addr=0x%lx (%s)\n", param->reg_kprobe_addr, argv[9]);
            debug("unreg_kprobe_addr=0x%lx (%s)\n", param->unreg_kprobe_addr, argv[10]);
            debug("kv_major=%lu (%s)\n", param->kv_major, argv[11]);
            debug("ibt=0x%lx (%s)\n", param->ibt, argv[12]);
            debug("kv_minor=%lu (%s)\n", param->kv_minor, argv[13]);
            debug("blkdev_get_addr=0x%lx (%s)\n", param->blkdev_get_addr, argv[14]);
            debug("blkdev_put_addr=0x%lx (%s)\n", param->blkdev_put_addr, argv[15]);
            debug("kv_subminor=%lu (%s)\n", param->kv_subminor, argv[16]);
            debug("bdev_open_addr=0x%lx (%s)\n", param->bdev_open_addr, argv[17]);
            debug("bdev_file_open_addr=0x%lx (%s)\n", param->bdev_file_open_addr, argv[18]);
            
            break;
        }
    }
    if (i >= size)
    {
        debug("### param magic not found \n");
    }
    
    vtoykmod_write_file(argv[0], buf, size);
    free(buf);
    return 0;
}
#ifdef VTOY_X86_64
static int vtoykmod_check_ibt(void)
{
    uint32_t eax = 0, ebx = 0, ecx = 0, edx = 0;
    
    __cpuid_count(7, 0, eax, ebx, ecx, edx);
    
    if (edx & (1 << 20))
    {
        return 0;
    }
    return 1;
}
#else
static int vtoykmod_check_ibt(void)
{
    return 1;
}
#endif
int vtoykmod_main(int argc, char **argv)
{
    int i;
    int kvMajor = 0;
    int kvMinor = 0;
    for (i = 0; i < argc; i++)
    {
        if (argv[i][0] == '-' && argv[i][1] == 'v')
        {
            verbose = 1;
            break;
        }
    }
    if (verbose)
    {
        printf("==== Dump Argv ====\n");
        for (i = 0; i < argc; i++)
        {
            printf("<%s> ", argv[i]);
        }
        printf("\n");
    }
    if (argv[1][0] == '-' && argv[1][1] == 'f')
    {
        return vtoykmod_fill_param(argv + 2);
    }
    else if (argv[1][0] == '-' && argv[1][1] == 'u')
    {
        kvMajor = (int)strtol(argv[2], NULL, 10);
        kvMinor = (int)strtol(argv[3], NULL, 10);
        return vtoykmod_update(kvMajor, kvMinor, argv[4], argv[5]);
    }
    else if (argv[1][0] == '-' && argv[1][1] == 'I')
    {
        return vtoykmod_check_ibt();
    }
    return 0;
}
// wrapper main
#ifndef BUILD_VTOY_TOOL
int main(int argc, char **argv)
{
    return vtoykmod_main(argc, argv);
}
#endif
 | 20,007 | 
	C | 
	.c | 588 | 27.457483 | 120 | 0.579673 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 627 | 
	vtoyloader.c | 
	ventoy_Ventoy/VtoyTool/vtoyloader.c | 
	/******************************************************************************
 * vtoyloader.c  ---- ventoy loader (wapper for binary loader)
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#define MAX_EXT_PARAM       256
#define CMDLINE_BUF_LEN     (1024 * 1024 * 1)
#define EXEC_PATH_FILE      "/ventoy/loader_exec_file"
#define CMDLINE_FILE        "/ventoy/loader_exec_cmdline"
#define HOOK_CMD_FILE       "/ventoy/loader_hook_cmd"
#define DEBUG_FLAG_FILE     "/ventoy/loader_debug"
static int verbose = 0;
#define debug(fmt, ...) if(verbose) printf(fmt, ##__VA_ARGS__)
static char g_exec_file[512];
static char g_hook_cmd[512];
static int vtoy_read_file_to_buf(const char *file, void *buf, int buflen)
{
    FILE *fp;
    fp = fopen(file, "r");
    if (!fp)
    {
        fprintf(stderr, "Failed to open file %s err:%d\n", file, errno);
        return 1;
    }
    fread(buf, 1, buflen, fp);
    fclose(fp);
    return 0;
}
int vtoyloader_main(int argc, char **argv)
{
    int i;
    int len;
    int rc;
    char *pos;
    char *cmdline;
    char **cmdlist;
    if (access(DEBUG_FLAG_FILE, F_OK) >= 0)
    {
        verbose = 1;
    }
    debug("ventoy loader ...\n");
    
    rc = vtoy_read_file_to_buf(EXEC_PATH_FILE, g_exec_file, sizeof(g_exec_file) - 1);
    if (rc)
    {
        return rc;
    }
    if (access(g_exec_file, F_OK) < 0)
    {
        fprintf(stderr, "File %s not exist\n", g_exec_file);
        return 1;
    }
    if (access(HOOK_CMD_FILE, F_OK) >= 0)
    {
        rc = vtoy_read_file_to_buf(HOOK_CMD_FILE,  g_hook_cmd,  sizeof(g_hook_cmd) - 1);
        debug("g_hook_cmd=<%s>\n", g_hook_cmd);
    }
    cmdline = (char *)malloc(CMDLINE_BUF_LEN);
    if (!cmdline)
    {
        fprintf(stderr, "Failed to alloc memory err:%d\n", errno);
        return 1;
    }
    memset(cmdline, 0, CMDLINE_BUF_LEN);
    if (access(CMDLINE_FILE, F_OK) >= 0)
    {
        rc = vtoy_read_file_to_buf(CMDLINE_FILE, cmdline, CMDLINE_BUF_LEN - 1);
        if (rc)
        {
            return rc;
        }
    }
    len = (int)((argc + MAX_EXT_PARAM) * sizeof(char *));
    cmdlist = (char **)malloc(len);
    if (!cmdlist)
    {
        free(cmdline);
        fprintf(stderr, "Failed to alloc memory err:%d\n", errno);
        return 1;
    }
    memset(cmdlist, 0, len);
    for (i = 0; i < argc; i++)
    {
        cmdlist[i] = argv[i];
    }
    
    cmdlist[0] = g_exec_file;
    debug("g_exec_file=<%s>\n", g_exec_file);
    pos = cmdline;
    while ((*pos) && i < MAX_EXT_PARAM)
    {
        cmdlist[i++] = pos;
        while (*pos)
        {
            if (*pos == '\r')
            {
                *pos = ' ';
            }
            else if (*pos == '\n')
            {
                *pos = 0;
                pos++;
                break;
            }
        
            pos++;
        }
    }
    debug("execv [%s]...\n", cmdlist[0]);
    // call hook script
    if (g_hook_cmd[0])
    {
        rc = system(g_hook_cmd);
        debug("system return code =<%d>  errno=<%d>\n", rc, errno);        
    }
    execv(cmdlist[0], cmdlist);
    
    return 0;
}
// wrapper main
#ifndef BUILD_VTOY_TOOL
int main(int argc, char **argv)
{
    return vtoyloader_main(argc, argv);
}
#endif
 | 4,133 | 
	C | 
	.c | 147 | 22.598639 | 88 | 0.567801 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 628 | 
	vtoyksym.c | 
	ventoy_Ventoy/VtoyTool/vtoyksym.c | 
	/******************************************************************************
 * vtoyksym.c  ---- ventoy ksym
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
static int verbose = 0;
#define debug(fmt, ...) if(verbose) printf(fmt, ##__VA_ARGS__)
int vtoyksym_main(int argc, char **argv)
{
    int i;
    int len = 0;
    unsigned long long addr1 = 0;
    unsigned long long addr2 = 0;
    char sym[256];
    char line[1024];
    char *start = NULL;
    const char *name = NULL;
    FILE *fp;
    for (i = 0; i < argc; i++)
    {
        if (argv[i][0] == '-' && argv[i][1] == 'p')
        {
            printf("%d", getpagesize());
            return 0;
        }
    }
    
    for (i = 0; i < argc; i++)
    {
        if (argv[i][0] == '-' && argv[i][1] == 'v')
        {
            verbose = 1;
            break;
        }
    }
    name = argv[2] ? argv[2] : "/proc/kallsyms";
    fp = fopen(name, "r");
    if (!fp)
    {
        fprintf(stderr, "Failed to open file %s err:%d\n", name, errno);
        return 1;
    }
    debug("open %s success\n", name);
    snprintf(sym, sizeof(sym), " %s", argv[1]);
    debug("lookup for <%s>\n", sym);
    len = (int)strlen(sym);
    while (fgets(line, sizeof(line), fp))
    {
        start = strstr(line, sym);
        if (start && (start > line) && isspace(*(start + len)))
        {
            addr1 = strtoull(line, NULL, 16);
            if (!fgets(line, sizeof(line), fp))
            {
                addr1 = 0;
                fprintf(stderr, "Failed to read next line\n");
            }
            else
            {
                addr2 = strtoull(line, NULL, 16);                
            }
            debug("addr1=<0x%llx> addr2=<0x%llx>\n", addr1, addr2);
            break;
        }
    }
    if (addr1 > addr2)
    {
        debug("Invalid addr range\n");
        printf("0 0\n");
    }
    else
    {
        printf("0x%llx %llu\n", addr1, addr2 - addr1);
    }
    fclose(fp);
    return 0;
}
// wrapper main
#ifndef BUILD_VTOY_TOOL
int main(int argc, char **argv)
{
    return vtoyksym_main(argc, argv);
}
#endif
 | 2,884 | 
	C | 
	.c | 103 | 21.92233 | 79 | 0.539464 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 629 | 
	vtoydump.c | 
	ventoy_Ventoy/VtoyTool/vtoydump.c | 
	/******************************************************************************
 * vtoydump.c  ---- Dump ventoy os parameters 
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/fs.h>
#include <dirent.h>
#include "vtoytool.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
#if defined(_dragon_fly) || defined(_free_BSD) || defined(_QNX)
#define MMAP_FLAGS          MAP_SHARED
#else
#define MMAP_FLAGS          MAP_PRIVATE
#endif
#define SEARCH_MEM_START 0x80000
#define SEARCH_MEM_LEN   0x1c000
static int verbose = 0;
#define debug(fmt, ...) if(verbose) printf(fmt, ##__VA_ARGS__)
static ventoy_guid vtoy_guid = VENTOY_GUID;
static const char *g_ventoy_fs[ventoy_fs_max] = 
{
    "exfat", "ntfs", "ext*", "xfs", "udf", "fat"
};
static int vtoy_check_os_param(ventoy_os_param *param)
{
    uint32_t i;
    uint8_t  chksum = 0;
    uint8_t *buf = (uint8_t *)param;
    
    if (memcmp(¶m->guid, &vtoy_guid, sizeof(ventoy_guid)))
    {
        uint8_t *data1 = (uint8_t *)(¶m->guid);
        uint8_t *data2 = (uint8_t *)(&vtoy_guid);
        
        for (i = 0; i < 16; i++)
        {
            if (data1[i] != data2[i])
            {
                debug("guid not equal i = %u, 0x%02x, 0x%02x\n", i, data1[i], data2[i]);
            }
        }
        return 1;
    }
    for (i = 0; i < sizeof(ventoy_os_param); i++)
    {
        chksum += buf[i];
    }
    if (chksum)
    {
        debug("Invalid checksum 0x%02x\n", chksum);
        return 1;
    }
    return 0;
}
static int vtoy_os_param_from_file(const char *filename, ventoy_os_param *param)
{
    int fd = 0;
    int rc = 0;
    fd = open(filename, O_RDONLY | O_BINARY);
    if (fd < 0)
    {
        fprintf(stderr, "Failed to open file %s error %d\n", filename, errno);
        return errno;
    }
    read(fd, param, sizeof(ventoy_os_param));
    if (vtoy_check_os_param(param) == 0)
    {
        debug("find ventoy os param in file %s\n", filename);
    }
    else
    {
        debug("ventoy os pararm NOT found in file %s\n", filename);
        rc = 1;
    }
    
    close(fd);
    return rc;
}
static void vtoy_dump_os_param(ventoy_os_param *param)
{
    printf("################# dump os param ################\n");
    printf("param->chksum = 0x%x\n", param->chksum);
    printf("param->vtoy_disk_guid = %02x %02x %02x %02x\n", 
        param->vtoy_disk_guid[0], param->vtoy_disk_guid[1], 
        param->vtoy_disk_guid[2], param->vtoy_disk_guid[3]);
    
    printf("param->vtoy_disk_signature = %02x %02x %02x %02x\n", 
        param->vtoy_disk_signature[0], param->vtoy_disk_signature[1], 
        param->vtoy_disk_signature[2], param->vtoy_disk_signature[3]);
    
    printf("param->vtoy_disk_size = %llu\n", (unsigned long long)param->vtoy_disk_size);
    printf("param->vtoy_disk_part_id = %u\n", param->vtoy_disk_part_id);
    printf("param->vtoy_disk_part_type = %u\n", param->vtoy_disk_part_type);
    printf("param->vtoy_img_path = <%s>\n", param->vtoy_img_path);
    printf("param->vtoy_img_size = <%llu>\n", (unsigned long long)param->vtoy_img_size);
    printf("param->vtoy_img_location_addr = <0x%llx>\n", (unsigned long long)param->vtoy_img_location_addr);
    printf("param->vtoy_img_location_len = <%u>\n", param->vtoy_img_location_len);
    printf("param->vtoy_reserved = %02x %02x %02x %02x %02x %02x %02x %02x\n", 
        param->vtoy_reserved[0],
        param->vtoy_reserved[1],
        param->vtoy_reserved[2],
        param->vtoy_reserved[3],
        param->vtoy_reserved[4],
        param->vtoy_reserved[5],
        param->vtoy_reserved[6],
        param->vtoy_reserved[7]
        );
    
    printf("\n");
}
static int vtoy_get_disk_guid(const char *diskname, uint8_t *vtguid, uint8_t *vtsig)
{
    int i = 0;
    int fd = 0;
    char devdisk[128] = {0};
    snprintf(devdisk, sizeof(devdisk) - 1, "/dev/%s", diskname);
    
    fd = open(devdisk, O_RDONLY | O_BINARY);
    if (fd >= 0)
    {
        lseek(fd, 0x180, SEEK_SET);
        read(fd, vtguid, 16);
        
        lseek(fd, 0x1b8, SEEK_SET);
        read(fd, vtsig, 4);
        close(fd);
        debug("GUID for %s: <", devdisk);
        for (i = 0; i < 16; i++)
        {
            debug("%02x", vtguid[i]);
        }
        debug(">\n");
        
        return 0;
    }
    else
    {
        debug("failed to open %s %d\n", devdisk, errno);
        return errno;
    }
}
static unsigned long long vtoy_get_disk_size_in_byte(const char *disk)
{
    int fd;
    int rc;
    unsigned long long size = 0;
    char diskpath[256] = {0};
    char sizebuf[64] = {0};
    // Try 1: get size from sysfs
    snprintf(diskpath, sizeof(diskpath) - 1, "/sys/block/%s/size", disk);
    if (access(diskpath, F_OK) >= 0)
    {
        debug("get disk size from sysfs for %s\n", disk);
        
        fd = open(diskpath, O_RDONLY | O_BINARY);
        if (fd >= 0)
        {
            read(fd, sizebuf, sizeof(sizebuf));
            size = strtoull(sizebuf, NULL, 10);
            close(fd);
            return (size * 512);
        }
    }
    else
    {
        debug("%s not exist \n", diskpath);
    }
    // Try 2: get size from ioctl
    snprintf(diskpath, sizeof(diskpath) - 1, "/dev/%s", disk);
    fd = open(diskpath, O_RDONLY);
    if (fd >= 0)
    {
        debug("get disk size from ioctl for %s\n", disk);
        rc = ioctl(fd, BLKGETSIZE64, &size);
        if (rc == -1)
        {
            size = 0;
            debug("failed to ioctl %d\n", rc);
        }
        close(fd);
    }
    else
    {
        debug("failed to open %s %d\n", diskpath, errno);
    }
    debug("disk %s size %llu bytes\n", disk, (unsigned long long)size);
    return size;
}
static int vtoy_is_possible_blkdev(const char *name)
{
    if (name[0] == '.')
    {
        return 0;
    }
    /* /dev/ramX */
    if (name[0] == 'r' && name[1] == 'a' && name[2] == 'm')
    {
        return 0;
    }
    /* /dev/loopX */
    if (name[0] == 'l' && name[1] == 'o' && name[2] == 'o' && name[3] == 'p')
    {
        return 0;
    }
    /* /dev/dm-X */
    if (name[0] == 'd' && name[1] == 'm' && name[2] == '-' && IS_DIGIT(name[3]))
    {
        return 0;
    }
    /* /dev/srX */
    if (name[0] == 's' && name[1] == 'r' && IS_DIGIT(name[2]))
    {
        return 0;
    }
    
    return 1;
}
static int vtoy_find_disk_by_size(unsigned long long size, char *diskname)
{
    unsigned long long cursize = 0;
    DIR* dir = NULL;
    struct dirent* p = NULL;
    int rc = 0;
    dir = opendir("/sys/block");
    if (!dir)
    {
        return 0;
    }
    
    while ((p = readdir(dir)) != NULL)
    {
        if (!vtoy_is_possible_blkdev(p->d_name))
        {
            debug("disk %s is filted by name\n", p->d_name);
            continue;
        }
    
        cursize = vtoy_get_disk_size_in_byte(p->d_name);
        debug("disk %s size %llu\n", p->d_name, (unsigned long long)cursize);
        if (cursize == size)
        {
            sprintf(diskname, "%s", p->d_name);
            rc++;
        }
    }
    closedir(dir);
    return rc;    
}
int vtoy_find_disk_by_guid(ventoy_os_param *param, char *diskname)
{
    int rc = 0;
    int count = 0;
    DIR* dir = NULL;
    struct dirent* p = NULL;
    uint8_t vtguid[16];
    uint8_t vtsig[16];
    dir = opendir("/sys/block");
    if (!dir)
    {
        return 0;
    }
    
    while ((p = readdir(dir)) != NULL)
    {
        if (!vtoy_is_possible_blkdev(p->d_name))
        {
            debug("disk %s is filted by name\n", p->d_name);        
            continue;
        }
    
        memset(vtguid, 0, sizeof(vtguid));
        memset(vtsig, 0, sizeof(vtsig));
        rc = vtoy_get_disk_guid(p->d_name, vtguid, vtsig);
        if (rc == 0 && memcmp(vtguid, param->vtoy_disk_guid, 16) == 0 && 
            memcmp(vtsig, param->vtoy_disk_signature, 4) == 0)
        {
            sprintf(diskname, "%s", p->d_name);
            count++;
        }
    }
    closedir(dir);
    
    return count;    
}
static int vtoy_find_disk_by_sig(uint8_t *sig, char *diskname)
{
    int rc = 0;
    int count = 0;
    DIR* dir = NULL;
    struct dirent* p = NULL;
    uint8_t vtguid[16];
    uint8_t vtsig[16];
    dir = opendir("/sys/block");
    if (!dir)
    {
        return 0;
    }
    
    while ((p = readdir(dir)) != NULL)
    {
        if (!vtoy_is_possible_blkdev(p->d_name))
        {
            debug("disk %s is filted by name\n", p->d_name);        
            continue;
        }
        memset(vtguid, 0, sizeof(vtguid));
        memset(vtsig, 0, sizeof(vtsig));
        rc = vtoy_get_disk_guid(p->d_name, vtguid, vtsig);
        if (rc == 0 && memcmp(vtsig, sig, 4) == 0)
        {
            sprintf(diskname, "%s", p->d_name);
            count++;
        }
    }
    closedir(dir);
    
    return count;    
}
static int vtoy_printf_iso_path(ventoy_os_param *param)
{
    printf("%s\n", param->vtoy_img_path);
    return 0;
}
static int vtoy_printf_fs(ventoy_os_param *param)
{
    const char *fs[] = 
    {
        "exfat", "ntfs", "ext", "xfs", "udf", "fat"
    };
    if (param->vtoy_disk_part_type < 6)
    {
        printf("%s\n", fs[param->vtoy_disk_part_type]);
    }
    else
    {
        printf("unknown\n");
    }
    return 0;
}
static int vtoy_vlnk_printf(ventoy_os_param *param, char *diskname)
{
    int cnt = 0;
    uint8_t disk_sig[4];
    uint8_t mbr[512];
    int fd = -1;
    char diskpath[128];
    uint8_t check[8] = { 0x56, 0x54, 0x00, 0x47, 0x65, 0x00, 0x48, 0x44 };
    
    memcpy(disk_sig, param->vtoy_reserved + 7, 4);
    debug("vlnk disk sig: %02x %02x %02x %02x \n", disk_sig[0], disk_sig[1], disk_sig[2], disk_sig[3]);
    cnt = vtoy_find_disk_by_sig(disk_sig, diskname);
    if (cnt == 1)
    {
        snprintf(diskpath, sizeof(diskpath), "/dev/%s", diskname);
        fd = open(diskpath, O_RDONLY | O_BINARY);
        if (fd >= 0)
        {
            memset(mbr, 0, sizeof(mbr));
            read(fd, mbr, sizeof(mbr));
            close(fd);
            if (memcmp(mbr + 0x190, check, 8) == 0)
            {
                printf("/dev/%s", diskname);
                return 0;                
            }
            else
            {
                debug("check data failed /dev/%s\n", diskname);
            }
        }
    }
    debug("find count=%d\n", cnt);
    printf("unknown");
    return 1;
}
static int vtoy_check_iso_path_alpnum(ventoy_os_param *param)
{
    char c;
    int i = 0;
    
    while (param->vtoy_img_path[i])
    {
        c = param->vtoy_img_path[i]; 
        
        if (isalnum(c) || c == '_' || c == '-')
        {
            
        }
        else
        {
            return 1;
        }
        i++;
    }
    return 0;
}
static int vtoy_check_device(ventoy_os_param *param, const char *device)
{
    unsigned long long size; 
    uint8_t vtguid[16] = {0};
    uint8_t vtsig[4] = {0};
    debug("vtoy_check_device for <%s>\n", device);
    size = vtoy_get_disk_size_in_byte(device);
    vtoy_get_disk_guid(device, vtguid, vtsig);
    debug("param->vtoy_disk_size=%llu size=%llu\n", 
        (unsigned long long)param->vtoy_disk_size, (unsigned long long)size);
    if (memcmp(vtguid, param->vtoy_disk_guid, 16) == 0 &&
        memcmp(vtsig, param->vtoy_disk_signature, 4) == 0)
    {
        debug("<%s> is right ventoy disk\n", device);
        return 0;
    }
    else
    {
        debug("<%s> is NOT right ventoy disk\n", device);
        return 1;
    }
}
static int vtoy_print_os_param(ventoy_os_param *param, char *diskname)
{
    int fd, size;
    int cnt = 0;
    char *path = param->vtoy_img_path;
    const char *fs;
    char diskpath[256] = {0};
    char sizebuf[64] = {0};
    
    cnt = vtoy_find_disk_by_size(param->vtoy_disk_size, diskname);
    debug("find disk by size %llu, cnt=%d...\n", (unsigned long long)param->vtoy_disk_size, cnt);
    if (1 == cnt)
    {
        if (vtoy_check_device(param, diskname) != 0)
        {
            cnt = 0;
        }
    }
    else
    {
        cnt = vtoy_find_disk_by_guid(param, diskname);
        debug("find disk by guid cnt=%d...\n", cnt);
    }
    
    if (param->vtoy_disk_part_type < ventoy_fs_max)
    {
        fs = g_ventoy_fs[param->vtoy_disk_part_type];
    }
    else
    {
        fs = "unknown";
    }
    if (1 == cnt)
    {
        if (strstr(diskname, "nvme") || strstr(diskname, "mmc") || strstr(diskname, "nbd"))
        {
            snprintf(diskpath, sizeof(diskpath) - 1, "/sys/class/block/%sp2/size", diskname);
        }
        else
        {
            snprintf(diskpath, sizeof(diskpath) - 1, "/sys/class/block/%s2/size", diskname);
        }
        if (param->vtoy_reserved[6] == 0 && access(diskpath, F_OK) >= 0)
        {
            debug("get part size from sysfs for %s\n", diskpath);
            fd = open(diskpath, O_RDONLY | O_BINARY);
            if (fd >= 0)
            {
                read(fd, sizebuf, sizeof(sizebuf));
                size = (int)strtoull(sizebuf, NULL, 10);
                close(fd);
                if ((size != (64 * 1024)) && (size != (8 * 1024)))
                {
                    debug("sizebuf=<%s> size=%d\n", sizebuf, size);
                    return 1;
                }
            }
        }
        else
        {
            debug("%s not exist \n", diskpath);
        }
        printf("/dev/%s#%s#%s\n", diskname, fs, path);
        return 0;
    }
    else
    {
        return 1;
    }
}
/*
 *  Find disk and image path from ventoy runtime data.
 *  By default data is read from phymem(legacy bios) or efivar(UEFI), if -f is input, data is read from file.
 *  
 *  -f datafile     os param data file. 
 *  -c /dev/xxx     check ventoy disk
 *  -v              be verbose
 *  -l              also print image disk location 
 */
int vtoydump_main(int argc, char **argv)
{
    int rc;
    int ch;
    int print_path = 0;
    int check_ascii = 0;
    int print_fs = 0;
    int vlnk_print = 0;
    char filename[256] = {0};
    char diskname[256] = {0};
    char device[64] = {0};
    ventoy_os_param *param = NULL;
    while ((ch = getopt(argc, argv, "a:c:f:p:t:s:v::")) != -1)
    {
        if (ch == 'f')
        {
            strncpy(filename, optarg, sizeof(filename) - 1);
        }
        else if (ch == 'v')
        {
            verbose = 1;
        }
        else if (ch == 'c')
        {
            strncpy(device, optarg, sizeof(device) - 1);
        }
        else if (ch == 'p')
        {
            print_path = 1;
            strncpy(filename, optarg, sizeof(filename) - 1);
        }
        else if (ch == 'a')
        {
            check_ascii = 1;
            strncpy(filename, optarg, sizeof(filename) - 1);
        }
        else if (ch == 't')
        {
            vlnk_print = 1;
            strncpy(filename, optarg, sizeof(filename) - 1);
        }
        else if (ch == 's')
        {
            print_fs = 1;
            strncpy(filename, optarg, sizeof(filename) - 1);
        }
        else
        {
            fprintf(stderr, "Usage: %s -f datafile [ -v ] \n", argv[0]);
            return 1;
        }
    }
    if (filename[0] == 0)
    {
        fprintf(stderr, "Usage: %s -f datafile [ -v ] \n", argv[0]);
        return 1;
    }
    param = malloc(sizeof(ventoy_os_param));
    if (NULL == param)
    {
        fprintf(stderr, "failed to alloc memory with size %d error %d\n", 
                (int)sizeof(ventoy_os_param), errno);
        return 1;
    }
    
    memset(param, 0, sizeof(ventoy_os_param));
    debug("get os pararm from file %s\n", filename);
    rc = vtoy_os_param_from_file(filename, param);
    if (rc)
    {
        debug("ventoy os param not found %d %d\n", rc, ENOENT);
        if (ENOENT == rc)
        {
            debug("now try with file %s\n", "/ventoy/ventoy_os_param");
            rc = vtoy_os_param_from_file("/ventoy/ventoy_os_param", param);
            if (rc)
            {
                goto end;
            }
        }
        else
        {
            goto end;            
        }        
    }
    if (verbose)
    {
        vtoy_dump_os_param(param);
    }
    if (print_path)
    {
        rc = vtoy_printf_iso_path(param);
    }
    else if (print_fs)
    {
        rc = vtoy_printf_fs(param);
    }
    else if (vlnk_print)
    {
        rc = vtoy_vlnk_printf(param, diskname);
    }
    else if (device[0])
    {
        rc = vtoy_check_device(param, device);
    }
    else if (check_ascii)
    {
        rc = vtoy_check_iso_path_alpnum(param);
    }
    else
    {
        // print os param, you can change the output format in the function
        rc = vtoy_print_os_param(param, diskname);
    }
end:
    if (param)
    {
        free(param);
    }
    return rc;
}
// wrapper main
#ifndef BUILD_VTOY_TOOL
int main(int argc, char **argv)
{
    return vtoydump_main(argc, argv);
}
#endif
 | 17,734 | 
	C | 
	.c | 628 | 21.272293 | 109 | 0.528482 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 630 | 
	vtoyvine.c | 
	ventoy_Ventoy/VtoyTool/vtoyvine.c | 
	/******************************************************************************
 * vtoyloader.c  ---- ventoy loader (wapper for binary loader)
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
static int verbose = 0;
#define debug(fmt, ...) if(verbose) printf(fmt, ##__VA_ARGS__)
static int vine_patch_loader(unsigned char *buf, int len, int major)
{
    int i;
    int ptrlen;
    unsigned int *data1;
    unsigned int *data2;
    /*
     * http://vinelinux.ime.cmc.osaka-u.ac.jp/Vine-6.5/SRPMS/SRPMS.main/anaconda-vine-11.0.2.1-1vl7.src.rpm
     * http://vinelinux.ime.cmc.osaka-u.ac.jp/Vine-6.5/SRPMS/SRPMS.main/kudzu-1.2.86-3vl6.src.rpm
     * anaconda-vine-11.0.2.1
     * isys/devnodes.c
     * static struct devnum devices[] = {
     *     { "aztcd",   29,	0,	0 },
     *     { "pcd",		46,	0,	0 },
     *
     * Patch 29 ---> 253
     */
    ptrlen = (buf[4] == 1) ? 4 : 8;
    debug("ELF %d bit major:%d ptrlen:%d\n", (buf[4] == 1) ? 32 : 64, major, ptrlen);    
    for (i = 0; i < len - 8 - 8 - ptrlen; i++)
    {
        data1 = (unsigned int *)(buf + i);
        data2 = (unsigned int *)(buf + i + 8 + ptrlen);
        if (data1[0] == 0x1D && data1[1] == 0x00 && data2[0] == 0x2E && data2[1] == 0x00)
        {
            debug("Find aztcd patch point at %d\n", i);
            data1[0] = major;
            break;
        }
    }
    for (i = 0; i < len; i++)
    {
        if (buf[i] != '/')
        {
            continue;
        }
        data1 = (unsigned int *)(buf + i + 1);
        /* /proc/ide */
        if (data1[0] == 0x636F7270 && data1[1] == 0x6564692F)
        {
            debug("patch string %s\n", (char *)(buf + i));
            buf[i + 1] = 'v';
            buf[i + 2] = 't';
            buf[i + 3] = 'o';
            buf[i + 4] = 'y';
        }
    }
    return 0;
}
int vtoyvine_main(int argc, char **argv)
{
    int i;
    int len;
    unsigned char *buf;
    FILE *fp;
    for (i = 0; i < argc; i++)
    {
        if (argv[i][0] == '-' && argv[i][1] == 'v')
        {
            verbose = 1;
            break;
        }
    }
    fp = fopen(argv[1], "rb");
    if (!fp)
    {
        fprintf(stderr, "Failed to open file %s err:%d\n", argv[1], errno);
        return 1;
    }
    fseek(fp, 0, SEEK_END);
    len = (int)ftell(fp);
    debug("file length:%d\n", len);
    fseek(fp, 0, SEEK_SET);
    buf = (unsigned char *)malloc(len);
    if (!buf)
    {
        fclose(fp);
        return 1;
    }
    fread(buf, 1, len, fp);
    fclose(fp);
    vine_patch_loader(buf, len, (int)strtoul(argv[2], NULL, 10));
    fp = fopen(argv[1], "wb+");
    if (!fp)
    {
        fprintf(stderr, "Failed to open file %s err:%d\n", argv[1], errno);
        free(buf);
        return 1;
    }
    debug("write new data length:%d\n", len);
    fwrite(buf, 1, len, fp);
    fclose(fp);
    free(buf);
    
    return 0;
}
// wrapper main
#ifndef BUILD_VTOY_TOOL
int main(int argc, char **argv)
{
    return vtoyvine_main(argc, argv);
}
#endif
 | 3,883 | 
	C | 
	.c | 134 | 23.477612 | 107 | 0.544086 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 631 | 
	vtoytool.c | 
	ventoy_Ventoy/VtoyTool/vtoytool.c | 
	/******************************************************************************
 * vtoytool.c  ---- ventoy os tool
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef int (*main_func)(int argc, char **argv);
typedef struct cmd_def
{
    const char *cmd;
    main_func func;
}cmd_def;
int vtoydump_main(int argc, char **argv);
int vtoydm_main(int argc, char **argv);
int vtoytool_install(int argc, char **argv);
int vtoyloader_main(int argc, char **argv);
int vtoyvine_main(int argc, char **argv);
int vtoyksym_main(int argc, char **argv);
int vtoykmod_main(int argc, char **argv);
int vtoyexpand_main(int argc, char **argv);
static char *g_vtoytool_name = NULL;
static cmd_def g_cmd_list[] = 
{
    { "vine_patch_loader",  vtoyvine_main  },
    { "vtoydump",    vtoydump_main    },
    { "vtoydm",      vtoydm_main      },
    { "loader",      vtoyloader_main  },
    { "hald",        vtoyloader_main  },
    { "vtoyksym",    vtoyksym_main  },
    { "vtoykmod",    vtoykmod_main  },
    { "vtoyexpand",  vtoyexpand_main  },
    { "--install",   vtoytool_install },
};
int vtoytool_install(int argc, char **argv)
{
    int i;
    char toolpath[128];
    char filepath[128];
    
    for (i = 0; i < sizeof(g_cmd_list) / sizeof(g_cmd_list[0]); i++)
    {
        if (g_cmd_list[i].cmd[0] != '-')
        {
            snprintf(toolpath, sizeof(toolpath), "/ventoy/tool/%s", g_vtoytool_name);
            snprintf(filepath, sizeof(filepath), "/ventoy/tool/%s", g_cmd_list[i].cmd);
            link(toolpath, filepath);
        }
    }
    
    return 0;
}
int main(int argc, char **argv)
{
    int i;
    
    if ((g_vtoytool_name = strstr(argv[0], "vtoytool")) != NULL)
    {
        argc--;
        argv++;
    }
    if (argc == 0)
    {
        fprintf(stderr, "Invalid param number\n");
        return 1;
    }
    for (i = 0; i < sizeof(g_cmd_list) / sizeof(g_cmd_list[0]); i++)
    {
        if (strstr(argv[0], g_cmd_list[i].cmd))
        {
            return g_cmd_list[i].func(argc, argv);
        }
    }
    fprintf(stderr, "Invalid cmd %s\n", argv[0]);
    return 1;
}
 | 2,837 | 
	C | 
	.c | 89 | 27.550562 | 87 | 0.608232 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 632 | 
	vtoyexpand.c | 
	ventoy_Ventoy/VtoyTool/vtoyexpand.c | 
	/******************************************************************************
 * vtoyexpand.c  ---- ventoy auto install script variable expansion
 *
 * Copyright (c) 2022, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/fs.h>
#include <dirent.h>
#include "vtoytool.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
#define TMP_FILE    "/ventoy/tmp_var_expansion"
#define SIZE_1MB    (1024 * 1024)
#define ulong unsigned long
#define ulonglong  unsigned long long
typedef struct disk_info
{
    char name[128];
    ulonglong size;
    int isUSB;
    int isSDX;
}disk_info;
static disk_info *g_disk_list = NULL;
static int g_disk_num = 0;
static const char *g_vtoy_disk_name = NULL;
static void vlog(const char *fmt, ...)
{
    int n = 0;
    va_list arg;
    FILE *fp = NULL;
    char log[1024];
    fp = fopen("/ventoy/autoinstall.log", "a+");
    if (fp)
    {
        va_start(arg, fmt);
        n += vsnprintf(log, sizeof(log) - 1, fmt, arg);
        va_end(arg);
        fwrite(log, 1, n, fp);        
        fclose(fp);
    }
}
static int copy_file(const char *file1, const char *file2)
{
    int n;
    int size;
    int ret = 1;
    FILE *fp1 = NULL;
    FILE *fp2 = NULL;
    char *buf = NULL;
    fp1 = fopen(file1, "rb");
    if (!fp1)
    {
        vlog("Failed to read file <%s>\n", file1);
        goto end;
    }
    
    fp2 = fopen(file2, "wb+");
    if (!fp2)
    {
        vlog("Failed to create file <%s>\n", file2);
        goto end;
    }
    fseek(fp1, 0, SEEK_END);
    size = (int)ftell(fp1);
    fseek(fp1, 0, SEEK_SET);
    buf = malloc(size);
    if (!buf)
    {
        vlog("Failed to malloc buf\n");
        goto end;
    }
    n = fread(buf, 1, size, fp1);
    if (n != size)
    {
        vlog("Failed to read <%s> %d %d\n", file1, n, size);
        goto end;
    }
    
    n = fwrite(buf, 1, size, fp2);
    if (n != size)
    {
        vlog("Failed to write <%s> %d %d\n", file2, n, size);
        goto end;
    }
    ret = 0;
end:
    if (fp1)
        fclose(fp1);
    if (fp2)
        fclose(fp2);
    if (buf)
        free(buf);
    return ret;
}
static int vtoy_is_possible_blkdev(const char *name)
{
    if (name[0] == '.')
    {
        return 0;
    }
    /* /dev/ramX */
    if (name[0] == 'r' && name[1] == 'a' && name[2] == 'm')
    {
        return 0;
    }
    /* /dev/loopX */
    if (name[0] == 'l' && name[1] == 'o' && name[2] == 'o' && name[3] == 'p')
    {
        return 0;
    }
    /* /dev/dm-X */
    if (name[0] == 'd' && name[1] == 'm' && name[2] == '-' && IS_DIGIT(name[3]))
    {
        return 0;
    }
    /* /dev/srX */
    if (name[0] == 's' && name[1] == 'r' && (name[2] >= '0' && name[2] <= '9'))
    {
        return 0;
    }
    
    return 1;
}
static ulonglong vtoy_get_disk_size_in_byte(const char *disk)
{
    int fd;
    int rc;
    unsigned long long size = 0;
    char diskpath[256] = {0};
    char sizebuf[64] = {0};
    // Try 1: get size from sysfs
    snprintf(diskpath, sizeof(diskpath) - 1, "/sys/block/%s/size", disk);
    if (access(diskpath, F_OK) >= 0)
    {
        vlog("get disk size from sysfs for %s\n", disk);
        
        fd = open(diskpath, O_RDONLY | O_BINARY);
        if (fd >= 0)
        {
            read(fd, sizebuf, sizeof(sizebuf));
            size = strtoull(sizebuf, NULL, 10);
            close(fd);
            return (size * 512);
        }
    }
    else
    {
        vlog("%s not exist \n", diskpath);
    }
    // Try 2: get size from ioctl
    snprintf(diskpath, sizeof(diskpath) - 1, "/dev/%s", disk);
    fd = open(diskpath, O_RDONLY);
    if (fd >= 0)
    {
        vlog("get disk size from ioctl for %s\n", disk);
        rc = ioctl(fd, BLKGETSIZE64, &size);
        if (rc == -1)
        {
            size = 0;
            vlog("failed to ioctl %d\n", rc);
        }
        close(fd);
    }
    else
    {
        vlog("failed to open %s %d\n", diskpath, errno);
    }
    vlog("disk %s size %llu bytes\n", disk, (ulonglong)size);
    return size;
}
static int get_disk_num(void)
{
    int n = 0;
    DIR* dir = NULL;
    struct dirent* p = NULL;
    dir = opendir("/sys/block");
    if (!dir)
    {
        return 0;
    }
    
    while ((p = readdir(dir)) != NULL)
    {
        n++;
    }
    closedir(dir);
    return n;
}
static int is_usb_disk(const char *diskname)
{
    int rc;
    char dstpath[1024] = { 0 };
    char syspath[1024] = { 0 };
    
    snprintf(syspath, sizeof(syspath), "/sys/block/%s", diskname);
    rc = readlink(syspath, dstpath, sizeof(dstpath) - 1);
    if (rc > 0 && strstr(dstpath, "/usb"))
    {
        return 1;
    }
    return 0;
}
static int get_all_disk(void)
{
    int i = 0;
    int j = 0;
    int num = 0;
    ulonglong cursize = 0;
    DIR* dir = NULL;
    struct dirent* p = NULL;
    disk_info *node = NULL;
    disk_info tmpnode;
    num = get_disk_num();
    if (num <= 0)
    {
        return 1;
    }
    g_disk_list = malloc(num * sizeof(disk_info));
    if (!g_disk_list)
    {
        return 1;
    }
    memset(g_disk_list, 0, num * sizeof(disk_info));
    dir = opendir("/sys/block");
    if (!dir)
    {
        return 0;
    }
    while (((p = readdir(dir)) != NULL) && g_disk_num < num)
    {
        if (!vtoy_is_possible_blkdev(p->d_name))
        {
            vlog("disk %s is filted by name\n", p->d_name);
            continue;
        }
    
        cursize = vtoy_get_disk_size_in_byte(p->d_name);
        node = g_disk_list + g_disk_num;
        g_disk_num++;
        
        snprintf(node->name, sizeof(node->name), p->d_name);
        node->size = cursize;
        node->isUSB = is_usb_disk(p->d_name);
        if (strncmp(node->name, "sd", 2) == 0)
        {
            node->isSDX = 1;
        }
    }
    closedir(dir);
    /* sort disks */
    for (i = 0; i < g_disk_num; i++)
    {
        for (j = i + 1; j < g_disk_num; j++)
        {
            if (g_disk_list[i].isSDX && g_disk_list[j].isSDX)
            {
                if (strcmp(g_disk_list[i].name, g_disk_list[j].name) > 0)
                {
                    memcpy(&tmpnode, g_disk_list + i, sizeof(tmpnode));
                    memcpy(g_disk_list + i, g_disk_list + j, sizeof(tmpnode));
                    memcpy(g_disk_list + j, &tmpnode, sizeof(tmpnode));
                }
            }
        }
    }
    vlog("============ DISK DUMP BEGIN ===========\n");
    for (i = 0; i < g_disk_num; i++)
    {
        node = g_disk_list + i;
        vlog("[%d] %s %dGB(%llu) USB:%d\n", i, node->name,
            node->size / 1024 / 1024 / 1024, node->size, node->isUSB);
    }
    vlog("============ DISK DUMP END ===========\n");
    
    return 0;
}
static int expand_var(const char *var, char *value, int len)
{
    int i;
    int index = -1;
    ulonglong uiDst = 0;
    ulonglong delta = 0;
    ulonglong maxsize = 0;
    ulonglong maxdelta = 0xFFFFFFFFFFFFFFFFULL;
    disk_info *node = NULL;
    value[0] = 0;
    if (strcmp(var, "VT_LINUX_DISK_SDX_1ST_NONVTOY") == 0)
    {
        for (i = 0; i < g_disk_num; i++)
        {
            node = g_disk_list + i;
            if (node->size > 0 && node->isSDX && strcmp(node->name, g_vtoy_disk_name) != 0)
            {
                vlog("%s=<%s>\n", var, node->name);
                snprintf(value, len, "%s", node->name);
                return 0;
            }
        }
        vlog("[Error] %s not found\n", var);
    }
    else if (strcmp(var, "VT_LINUX_DISK_SDX_1ST_NONUSB") == 0)
    {
        for (i = 0; i < g_disk_num; i++)
        {
            node = g_disk_list + i;
            if (node->size > 0 && node->isSDX && node->isUSB == 0)
            {
                vlog("%s=<%s>\n", var, node->name);
                snprintf(value, len, "%s", node->name);
                return 0;
            }
        }
        vlog("[Error] %s not found\n", var);
    }
    else if (strcmp(var, "VT_LINUX_DISK_MAX_SIZE") == 0)
    {
        for (i = 0; i < g_disk_num; i++)
        {
            node = g_disk_list + i;
            if (node->size > 0 && node->size > maxsize)
            {
                index = i;
                maxsize = node->size;
            }
        }
        if (index >= 0)
        {
            vlog("%s=<%s>\n", var, g_disk_list[index].name);
            snprintf(value, len, "%s", g_disk_list[index].name);
            return 0;
        }
        else
        {
            vlog("[Error] %s not found\n", var);
        }
    }
    else if (strncmp(var, "VT_LINUX_DISK_CLOSEST_", 22) == 0)
    {
        uiDst = strtoul(var + 22, NULL, 10);
        uiDst = uiDst * (1024ULL * 1024ULL * 1024ULL);
    
        for (i = 0; i < g_disk_num; i++)
        {
            node = g_disk_list + i;
            if (node->size == 0)
            {
                continue;
            }
        
            if (node->size > uiDst)
            {
                delta = node->size - uiDst;
            }
            else
            {
                delta = uiDst - node->size;
            }
            
            if (delta < maxdelta)
            {
                index = i;
                maxdelta = delta;
            }
        }
        if (index >= 0)
        {
            vlog("%s=<%s>\n", var, g_disk_list[index].name);
            snprintf(value, len, "%s", g_disk_list[index].name);
            return 0;
        }
        else
        {
            vlog("[Error] %s not found\n", var);
        }
    }
    else
    {
        vlog("Invalid var name <%s>\n", var);
        snprintf(value, len, "$$%s$$", var);
    }
    if (value[0] == 0)
    {
        snprintf(value, len, "$$%s$$", var);
    }
    return 0;
}
int vtoyexpand_main(int argc, char **argv)
{
    FILE *fp = NULL;
    FILE *fout = NULL;
    char *start = NULL;
    char *end = NULL;
    char line[4096];
    char value[256];
    vlog("========= vtoyexpand_main %d ========\n", argc);
    if (argc != 3)
    {
        return 1;
    }
    g_vtoy_disk_name = argv[2];
    if (strncmp(g_vtoy_disk_name, "/dev/", 5) == 0)
    {
        g_vtoy_disk_name += 5;
    }
    vlog("<%s> <%s> <%s>\n", argv[1], argv[2], g_vtoy_disk_name);    
    get_all_disk();
    
    fp = fopen(argv[1], "r");
    if (!fp)
    {
        vlog("Failed to open file <%s>\n", argv[1]);
        return 1;
    }
    fout = fopen(TMP_FILE, "w+");
    if (!fout)
    {
        vlog("Failed to create file <%s>\n", TMP_FILE);
        fclose(fp);
        return 1;
    }
    memset(line, 0, sizeof(line));
    memset(value, 0, sizeof(value));
    
    while (fgets(line, sizeof(line), fp))
    {
        start = strstr(line, "$$VT_");
        if (start)
        {
            end = strstr(start + 5, "$$");
        }
        if (start && end)
        {
            *start = 0;
            fprintf(fout, "%s", line);
            *end = 0;
            expand_var(start + 2, value, sizeof(value));
            fprintf(fout, "%s", value);
            
            fprintf(fout, "%s", end + 2);
            memset(value, 0, sizeof(value));
        }
        else
        {
            fprintf(fout, "%s", line);
        }
        line[0] = line[4095] = 0;
    }
    
    fclose(fp);
    fclose(fout);
    vlog("delete file <%s>\n", argv[1]);
    remove(argv[1]);
    vlog("Copy file <%s> --> <%s>\n", TMP_FILE, argv[1]);
    copy_file(TMP_FILE, argv[1]);
    
    return 0;
}
// wrapper main
#ifndef BUILD_VTOY_TOOL
int main(int argc, char **argv)
{
    return vtoyexpand_main(argc, argv);
}
#endif
 | 12,350 | 
	C | 
	.c | 473 | 19.002114 | 91 | 0.490085 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 633 | 
	vtoydm.c | 
	ventoy_Ventoy/VtoyTool/vtoydm.c | 
	/******************************************************************************
 * vtoydm.c  ---- ventoy device mapper tool
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/fs.h>
#include <dirent.h>
#include "biso.h"
#include "biso_list.h"
#include "biso_util.h"
#include "biso_plat.h"
#include "biso_9660.h"
#include "vtoytool.h"
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef USE_DIET_C
#ifndef __mips__
typedef unsigned long long uint64_t;
#endif
typedef unsigned int    uint32_t;
#endif
#pragma pack(4)
typedef struct ventoy_img_chunk
{
    uint32_t img_start_sector; // sector size: 2KB
    uint32_t img_end_sector;   // included
    uint64_t disk_start_sector; // in disk_sector_size
    uint64_t disk_end_sector;   // included
}ventoy_img_chunk;
#pragma pack()
static int verbose = 0;
#define debug(fmt, ...) if(verbose) printf(fmt, ##__VA_ARGS__)
#define CMD_PRINT_TABLE       1
#define CMD_CREATE_DM         2
#define CMD_DUMP_ISO_INFO     3
#define CMD_EXTRACT_ISO_FILE  4
#define CMD_PRINT_EXTRACT_ISO_FILE  5
static uint64_t g_iso_file_size;
static char g_disk_name[128];
static int g_img_chunk_num = 0;
static ventoy_img_chunk *g_img_chunk = NULL;
static unsigned char g_iso_sector_buf[2048];
ventoy_img_chunk * vtoydm_get_img_map_data(const char *img_map_file, int *plen)
{
    int len;
    int rc = 1;
    FILE *fp = NULL;
    ventoy_img_chunk *chunk = NULL;
    
    fp = fopen(img_map_file, "rb");
    if (NULL == fp)
    {
        fprintf(stderr, "Failed to open file %s err:%d\n", img_map_file, errno);
        return NULL;
    }
    fseek(fp, 0, SEEK_END);
    len = (int)ftell(fp);
    fseek(fp, 0, SEEK_SET);
    debug("File <%s> len:%d\n", img_map_file, len);
    chunk = (ventoy_img_chunk *)malloc(len);
    if (NULL == chunk)
    {
        fprintf(stderr, "Failed to malloc memory len:%d err:%d\n", len, errno);
        goto end;
    }
    if (fread(chunk, 1, len, fp) != len)
    {
        fprintf(stderr, "Failed to read file err:%d\n", errno);
        goto end;
    }
    if (len % sizeof(ventoy_img_chunk))
    {
        fprintf(stderr, "image map file size %d is not aligned with %d\n", 
                len, (int)sizeof(ventoy_img_chunk));
        goto end;
    }
    rc = 0;
end:
    fclose(fp);
    if (rc)
    {
        if (chunk)
        {
            free(chunk);
            chunk = NULL;
        }
    }
    *plen = len;
    return chunk;
}
UINT64 vtoydm_get_file_size(const char *pcFileName)
{
    (void)pcFileName;
    debug("vtoydm_get_file_size %s %lu\n", pcFileName, (unsigned long)g_iso_file_size);
    
    return g_iso_file_size;
}
BISO_FILE_S * vtoydm_open_file(const char *pcFileName)
{
    BISO_FILE_S *file;
    debug("vtoydm_open_file %s\n", pcFileName);
    file = malloc(sizeof(BISO_FILE_S));
    if (file)
    {
        memset(file, 0, sizeof(BISO_FILE_S));
        file->FileSize = g_iso_file_size;
        file->CurPos = 0;
    }
    
    return file;
}
void vtoydm_close_file(BISO_FILE_S *pstFile)
{
    debug("vtoydm_close_file\n");
    
    if (pstFile)
    {
        free(pstFile);
    }
}
INT64 vtoydm_seek_file(BISO_FILE_S *pstFile, INT64 i64Offset, INT iFromWhere)
{
    debug("vtoydm_seek_file %d\n", (int)i64Offset);
    if (iFromWhere == SEEK_SET)
    {
        pstFile->CurPos = (UINT64)i64Offset;
    }
    return 0;
}
UINT64 vtoydm_map_iso_sector(UINT64 sector)
{
    int i;
    UINT64 disk_sector = 0;
    
    for (i = 0; i < g_img_chunk_num; i++)
    {
        if (sector >= g_img_chunk[i].img_start_sector && sector <= g_img_chunk[i].img_end_sector)
        {
            disk_sector = ((sector - g_img_chunk[i].img_start_sector) << 2) + g_img_chunk[i].disk_start_sector;
            break;
        }
    }
    return disk_sector;
}
int vtoydm_read_iso_sector(UINT64 sector, void *buf)
{
    int i;
    int fd;
    UINT64 disk_sector = 0;
    
    for (i = 0; i < g_img_chunk_num; i++)
    {
        if (sector >= g_img_chunk[i].img_start_sector && sector <= g_img_chunk[i].img_end_sector)
        {
            disk_sector = ((sector - g_img_chunk[i].img_start_sector) << 2) + g_img_chunk[i].disk_start_sector;
            break;
        }
    }
    fd = open(g_disk_name, O_RDONLY | O_BINARY);
    if (fd < 0)
    {
        debug("Failed to open %s\n", g_disk_name);
        return 1;
    }
    lseek(fd, disk_sector * 512, SEEK_SET);
    read(fd, buf, 2048);
    close(fd);
    return 0;
}
UINT64 vtoydm_read_file
(
    BISO_FILE_S *pstFile, 
    UINT         uiBlkSize, 
    UINT         uiBlkNum, 
    VOID        *pBuf
)
{
    int pos = 0;
    int align = 0;
    UINT64 readlen = uiBlkSize * uiBlkNum;
    char *curbuf = (char *)pBuf;
    debug("vtoydm_read_file length:%u\n", uiBlkSize * uiBlkNum);
    pos = (int)(pstFile->CurPos % 2048);
    if (pos > 0)
    {
        align = 2048 - pos;
        
        vtoydm_read_iso_sector(pstFile->CurPos / 2048, g_iso_sector_buf);
        if (readlen > align)
        {
            memcpy(curbuf, g_iso_sector_buf + pos, align);
            curbuf  += align;
            readlen -= align;
            pstFile->CurPos += align;
        }
        else
        {
            memcpy(curbuf, g_iso_sector_buf + pos, readlen);
            pstFile->CurPos += readlen;
            return readlen;
        }
    }
    while (readlen > 2048)
    {
        vtoydm_read_iso_sector(pstFile->CurPos / 2048, curbuf);
        pstFile->CurPos += 2048;
        
        curbuf += 2048;
        readlen -= 2048;
    }
    if (readlen > 0)
    {
        vtoydm_read_iso_sector(pstFile->CurPos / 2048, g_iso_sector_buf);
        memcpy(curbuf, g_iso_sector_buf, readlen);
        pstFile->CurPos += readlen;
    }
    
    return uiBlkSize * uiBlkNum;
}
int vtoydm_dump_iso(const char *img_map_file, const char *diskname)
{
    int i = 0;
    int len = 0;
    uint64_t sector_num;
    unsigned long ret;
    ventoy_img_chunk *chunk = NULL;
    BISO_READ_S *iso;
    BISO_PARSER_S *parser = NULL;
    char label[64] = {0};
    
    chunk = vtoydm_get_img_map_data(img_map_file, &len);
    if (NULL == chunk)
    {
        return 1;
    }
    for (i = 0; i < len / sizeof(ventoy_img_chunk); i++)
    {
        sector_num = chunk[i].img_end_sector - chunk[i].img_start_sector + 1;
        g_iso_file_size += sector_num * 2048;
    }
    strncpy(g_disk_name, diskname, sizeof(g_disk_name) - 1);
    g_img_chunk = chunk;
    g_img_chunk_num = len / sizeof(ventoy_img_chunk);
    debug("iso file size : %llu\n", (unsigned long long)g_iso_file_size);
    iso = BISO_AllocReadHandle();
    if (iso == NULL)
    {
        free(chunk);
        return 1;
    }
    ret = BISO_OpenImage("XXX", iso);
    debug("open iso image ret=0x%lx\n", ret);
    parser = (BISO_PARSER_S *)iso;    
    memcpy(label, parser->pstPVD->szVolumeId, 32);
    for (i = 32; i >=0; i--)
    {
        if (label[i] != 0 && label[i] != ' ')
        {
            break;
        }
        else
        {
            label[i] = 0;
        }
    }
    if (label[0])
    {
        printf("VENTOY_ISO_LABEL %s\n", label);    
    }
    
    BISO_DumpFileTree(iso);
    
    BISO_FreeReadHandle(iso);
    free(chunk);
    return 0;
}
static int vtoydm_extract_iso
(
    const char *img_map_file, 
    const char *diskname,
    unsigned long first_sector,
    unsigned long long file_size,
    const char *outfile
)
{
    int len;
    FILE *fp = NULL;
    g_img_chunk = vtoydm_get_img_map_data(img_map_file, &len);
    if (NULL == g_img_chunk)
    {
        return 1;
    }
    strncpy(g_disk_name, diskname, sizeof(g_disk_name) - 1);
    g_img_chunk_num = len / sizeof(ventoy_img_chunk);
    fp = fopen(outfile, "wb");
    if (fp == NULL)
    {
        fprintf(stderr, "Failed to create file %s err:%d\n", outfile, errno);
        free(g_img_chunk);
        return 1;
    }
    while (file_size > 0)
    {
        vtoydm_read_iso_sector(first_sector++, g_iso_sector_buf);
        if (file_size > 2048)
        {
            fwrite(g_iso_sector_buf, 2048, 1, fp);
            file_size -= 2048;
        }
        else
        {
            fwrite(g_iso_sector_buf, 1, file_size, fp);
            file_size = 0;
        }
    }
    
    fclose(fp);
    free(g_img_chunk);
    return 0;
}
static int vtoydm_print_extract_iso
(
    const char *img_map_file, 
    const char *diskname,
    unsigned long first_sector,
    unsigned long long file_size,
    const char *outfile
)
{
    int len;
    uint32_t last = 0;
    uint32_t sector = 0;
    uint32_t disk_first = 0;
    uint32_t count = 0;
    uint32_t buf[2];
    uint64_t size = file_size;
    FILE *fp = NULL;
    g_img_chunk = vtoydm_get_img_map_data(img_map_file, &len);
    if (NULL == g_img_chunk)
    {
        return 1;
    }
    strncpy(g_disk_name, diskname, sizeof(g_disk_name) - 1);
    g_img_chunk_num = len / sizeof(ventoy_img_chunk);
    fp = fopen(outfile, "wb");
    if (fp == NULL)
    {
        fprintf(stderr, "Failed to create file %s err:%d\n", outfile, errno);
        free(g_img_chunk);
        return 1;
    }
    fwrite(g_disk_name, 1, 32, fp);
    fwrite(&size, 1, 8, fp);
    while (file_size > 0)
    {
        sector = vtoydm_map_iso_sector(first_sector++);
        if (count > 0 && sector == last + 4)
        {
            last += 4;
            count += 4;
        }
        else
        {
            if (count > 0)
            {
                buf[0] = disk_first;
                buf[1] = count;
                fwrite(buf, 1, sizeof(buf), fp);
            }
            disk_first = sector;
            last = sector;
            count = 4;
        }
        
        if (file_size > 2048)
        {
            file_size -= 2048;
        }
        else
        {
            file_size = 0;
        }
    }
    if (count > 0)
    {
        buf[0] = disk_first;
        buf[1] = count;
        fwrite(buf, 1, sizeof(buf), fp);
    }
    
    fclose(fp);
    free(g_img_chunk);
    return 0;
}
static int vtoydm_print_linear_table(const char *img_map_file, const char *diskname, int part, uint64_t offset)
{
    int i;
    int len;
    uint32_t disk_sector_num;
    uint32_t sector_start;
    ventoy_img_chunk *chunk = NULL;
    
    chunk = vtoydm_get_img_map_data(img_map_file, &len);
    if (NULL == chunk)
    {
        return 1;
    }
    for (i = 0; i < len / sizeof(ventoy_img_chunk); i++)
    {
        sector_start = chunk[i].img_start_sector;
        disk_sector_num = (uint32_t)(chunk[i].disk_end_sector + 1 - chunk[i].disk_start_sector);
        /* TBD: to be more flexible */
        #if 0
        printf("%u %u linear %s %llu\n", 
               (sector_start << 2), disk_sector_num, 
               diskname, (unsigned long long)chunk[i].disk_start_sector);
        #else
        if (strstr(diskname, "nvme") || strstr(diskname, "mmc") || strstr(diskname, "nbd"))
        {
            printf("%u %u linear %sp%d %llu\n", 
               (sector_start << 2), disk_sector_num, 
               diskname, part, (unsigned long long)chunk[i].disk_start_sector - offset);
        }
        else
        {
            printf("%u %u linear %s%d %llu\n", 
               (sector_start << 2), disk_sector_num, 
               diskname, part, (unsigned long long)chunk[i].disk_start_sector - offset);
        }
        #endif
    }
    free(chunk);
    return 0;
}
static int vtoydm_print_help(FILE *fp)
{
    fprintf(fp, "Usage: \n"
            "   vtoydm -p -f img_map_file -d diskname [ -v ] \n"
            "   vtoydm -c -f img_map_file -d diskname [ -v ] \n"
            "   vtoydm -i -f img_map_file -d diskname [ -v ] \n"
            "   vtoydm -e -f img_map_file -d diskname -s sector -l len -o file [ -v ] \n"
            );
    return 0;        
}
static uint64_t vtoydm_get_part_start(const char *diskname, int part)
{
    int fd;
    unsigned long long size = 0;
    char diskpath[256] = {0};
    char sizebuf[64] = {0};
    if (strstr(diskname, "nvme") || strstr(diskname, "mmc") || strstr(diskname, "nbd"))
    {
        snprintf(diskpath, sizeof(diskpath) - 1, "/sys/class/block/%sp%d/start", diskname, part);
    }
    else
    {
        snprintf(diskpath, sizeof(diskpath) - 1, "/sys/class/block/%s%d/start", diskname, part);
    }
    if (access(diskpath, F_OK) >= 0)
    {
        debug("get part start from sysfs for %s %d\n", diskname, part);
        
        fd = open(diskpath, O_RDONLY | O_BINARY);
        if (fd >= 0)
        {
            read(fd, sizebuf, sizeof(sizebuf));
            size = strtoull(sizebuf, NULL, 10);
            close(fd);
            return size;
        }
    }
    else
    {
        debug("%s not exist \n", diskpath);
    }
    return size;
}
static int vtoydm_vlnk_convert(char *disk, int len, int *part, uint64_t *offset)
{
    int rc = 1;
    int cnt = 0;
    int rdlen;
    FILE *fp = NULL;
    ventoy_os_param param;
    char diskname[128] = {0};
    fp = fopen("/ventoy/ventoy_os_param", "rb");
    if (!fp)
    {
        debug("dm vlnk convert not exist %d\n", errno);
        goto end;
    }
    memset(¶m, 0, sizeof(param));
    rdlen = (int)fread(¶m, 1, sizeof(param), fp);
    if (rdlen != (int)sizeof(param))
    {
        debug("fread failed %d %d\n", rdlen, errno);
        goto end;
    }
    debug("dm vlnk convert vtoy_reserved=%d\n", param.vtoy_reserved[6]);
    if (param.vtoy_reserved[6])
    {
        cnt = vtoy_find_disk_by_guid(¶m, diskname);
        debug("vtoy_find_disk_by_guid cnt=%d\n", cnt);        
        if (cnt == 1)
        {
            *part = param.vtoy_disk_part_id;
            *offset = vtoydm_get_part_start(diskname, *part);
            
            debug("VLNK <%s> <%s> <P%d> <%llu>\n", disk, diskname, *part, (unsigned long long)(*offset));
            snprintf(disk, len, "/dev/%s", diskname);
            rc = 0;
        }
    }
end:
    if (fp)
        fclose(fp);
    return rc;
}
int vtoydm_main(int argc, char **argv)
{
    int ch;
    int cmd = 0;
    int part = 1;
    uint64_t offset = 2048;
    unsigned long first_sector = 0;
    unsigned long long file_size = 0;
    char diskname[128] = {0};
    char filepath[300] = {0};
    char outfile[300] = {0};
    while ((ch = getopt(argc, argv, "s:l:o:d:f:v::i::p::c::h::e::E::")) != -1)
    {
        if (ch == 'd')
        {
            strncpy(diskname, optarg, sizeof(diskname) - 1);
        }
        else if (ch == 'f')
        {
            strncpy(filepath, optarg, sizeof(filepath) - 1);
        }
        else if (ch == 'p')
        {
            cmd = CMD_PRINT_TABLE;
        }
        else if (ch == 'c')
        {
            cmd = CMD_CREATE_DM;
        }
        else if (ch == 'i')
        {
            cmd = CMD_DUMP_ISO_INFO;
        }
        else if (ch == 'e')
        {
            cmd = CMD_EXTRACT_ISO_FILE;
        }
        else if (ch == 'E')
        {
            cmd = CMD_PRINT_EXTRACT_ISO_FILE;
        }
        else if (ch == 's')
        {
            first_sector = strtoul(optarg, NULL, 10);
        }
        else if (ch == 'l')
        {
            file_size = strtoull(optarg, NULL, 10);
        }
        else if (ch == 'o')
        {
            strncpy(outfile, optarg, sizeof(outfile) - 1);
        }
        else if (ch == 'v')
        {
            verbose = 1;
        }
        else if (ch == 'h')
        {
            return vtoydm_print_help(stdout);
        }
        else
        {
            vtoydm_print_help(stderr);
            return 1;
        }
    }
    if (filepath[0] == 0 || diskname[0] == 0)
    {
        fprintf(stderr, "Must input file and disk\n");
        return 1;
    }
    debug("cmd=%d file=<%s> disk=<%s> first_sector=%lu file_size=%llu\n", 
          cmd, filepath, diskname, first_sector, file_size);
    vtoydm_vlnk_convert(diskname, sizeof(diskname), &part, &offset);
    
    switch (cmd)
    {
        case CMD_PRINT_TABLE:
        {
            return vtoydm_print_linear_table(filepath, diskname, part, offset);
        }
        case CMD_CREATE_DM:
        {
            break;
        }
        case CMD_DUMP_ISO_INFO:
        {
            return vtoydm_dump_iso(filepath, diskname);
        }
        case CMD_EXTRACT_ISO_FILE:
        {
            return vtoydm_extract_iso(filepath, diskname, first_sector, file_size, outfile);
        }
        case CMD_PRINT_EXTRACT_ISO_FILE:
        {
            return vtoydm_print_extract_iso(filepath, diskname, first_sector, file_size, outfile);
        }
        default :
        {
            fprintf(stderr, "Invalid cmd \n");
            return 1;
        }
    }
	return 0;
}
// wrapper main
#ifndef BUILD_VTOY_TOOL
int main(int argc, char **argv)
{
    return vtoydm_main(argc, argv);
}
#endif
 | 17,560 | 
	C | 
	.c | 638 | 20.797806 | 111 | 0.549339 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 645 | 
	disksize.c | 
	ventoy_Ventoy/LiveCD/VTOY/ventoy/disksize.c | 
	#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef unsigned long long UINT64;
int GetHumanReadableGBSize(UINT64 SizeBytes)
{
    int i;
    int Pow2 = 1;
    double Delta;
    double GB = SizeBytes * 1.0 / 1000 / 1000 / 1000;
    for (i = 0; i < 12; i++)
    {
        if (Pow2 > GB)
        {
            Delta = (Pow2 - GB) / Pow2;
        }
        else
        {
            Delta = (GB - Pow2) / Pow2;
        }
        if (Delta < 0.05)
        {
            return Pow2;
        }
        Pow2 <<= 1;
    }
    return (int)GB;
}
int main(int argc, char **argv)
{
    UINT64 value = strtoul(argv[1], NULL, 10);
    
    printf("%d", GetHumanReadableGBSize(value * 512));
    
    return 0;
}
 | 764 | 
	C | 
	.c | 34 | 15 | 55 | 0.491477 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 705 | 
	vtoygpt.c | 
	ventoy_Ventoy/vtoygpt/vtoygpt.c | 
	/******************************************************************************
 * vtoygpt.c  ---- ventoy gpt util
 *
 * Copyright (c) 2020, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/fs.h>
#include <dirent.h>
#define VOID   void
#define CHAR   char
#define UINT64 unsigned long long
#define UINT32 unsigned int
#define UINT16 unsigned short
#define CHAR16 unsigned short
#define UINT8  unsigned char
UINT32 VtoyCrc32(VOID *Buffer, UINT32 Length);
#define COMPILE_ASSERT(expr)  extern char __compile_assert[(expr) ? 1 : -1]
#pragma pack(1)
typedef struct PART_TABLE
{
    UINT8  Active;
    UINT8  StartHead;
    UINT16 StartSector : 6;
    UINT16 StartCylinder : 10;
    UINT8  FsFlag;
    UINT8  EndHead;
    UINT16 EndSector : 6;
    UINT16 EndCylinder : 10;
    UINT32 StartSectorId;
    UINT32 SectorCount;
}PART_TABLE;
typedef struct MBR_HEAD
{
    UINT8 BootCode[446];
    PART_TABLE PartTbl[4];
    UINT8 Byte55;
    UINT8 ByteAA;
}MBR_HEAD;
typedef struct GUID
{
    UINT32   data1;
    UINT16   data2;
    UINT16   data3;
    UINT8    data4[8];
}GUID;
typedef struct VTOY_GPT_HDR
{
    CHAR   Signature[8]; /* EFI PART */
    UINT8  Version[4];
    UINT32 Length;
    UINT32 Crc;
    UINT8  Reserved1[4];
    UINT64 EfiStartLBA;
    UINT64 EfiBackupLBA;
    UINT64 PartAreaStartLBA;
    UINT64 PartAreaEndLBA;
    GUID   DiskGuid;
    UINT64 PartTblStartLBA;
    UINT32 PartTblTotNum;
    UINT32 PartTblEntryLen;
    UINT32 PartTblCrc;
    UINT8  Reserved2[420];
}VTOY_GPT_HDR;
COMPILE_ASSERT(sizeof(VTOY_GPT_HDR) == 512);
typedef struct VTOY_GPT_PART_TBL
{
    GUID   PartType;
    GUID   PartGuid;
    UINT64 StartLBA;
    UINT64 LastLBA;
    UINT64 Attr;
    CHAR16 Name[36];
}VTOY_GPT_PART_TBL;
COMPILE_ASSERT(sizeof(VTOY_GPT_PART_TBL) == 128);
typedef struct VTOY_GPT_INFO
{
    MBR_HEAD MBR;
    VTOY_GPT_HDR Head;
    VTOY_GPT_PART_TBL PartTbl[128];
}VTOY_GPT_INFO;
typedef struct VTOY_BK_GPT_INFO
{
    VTOY_GPT_PART_TBL PartTbl[128];
    VTOY_GPT_HDR Head;
}VTOY_BK_GPT_INFO;
COMPILE_ASSERT(sizeof(VTOY_GPT_INFO) == 512 * 34);
COMPILE_ASSERT(sizeof(VTOY_BK_GPT_INFO) == 512 * 33);
#pragma pack()
void DumpGuid(const char *prefix, GUID *guid)
{
    printf("%s: %08x-%04x-%04x-%02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x\n",
        prefix,
        guid->data1, guid->data2, guid->data3,
        guid->data4[0], guid->data4[1], guid->data4[2], guid->data4[3],
        guid->data4[4], guid->data4[5], guid->data4[6], guid->data4[7]
        );
}
void DumpHead(VTOY_GPT_HDR *pHead)
{
    UINT32 CrcRead;
    UINT32 CrcCalc;
    
    printf("Signature:<%s>\n", pHead->Signature);
    printf("Version:<%02x %02x %02x %02x>\n", pHead->Version[0], pHead->Version[1], pHead->Version[2], pHead->Version[3]);
    printf("Length:%u\n", pHead->Length);
    printf("Crc:0x%08x\n", pHead->Crc);
    printf("EfiStartLBA:%lu\n", pHead->EfiStartLBA);
    printf("EfiBackupLBA:%lu\n", pHead->EfiBackupLBA);
    printf("PartAreaStartLBA:%lu\n", pHead->PartAreaStartLBA);
    printf("PartAreaEndLBA:%lu\n", pHead->PartAreaEndLBA);
    DumpGuid("DiskGuid", &pHead->DiskGuid);
    
    printf("PartTblStartLBA:%lu\n", pHead->PartTblStartLBA);
    printf("PartTblTotNum:%u\n", pHead->PartTblTotNum);
    printf("PartTblEntryLen:%u\n", pHead->PartTblEntryLen);
    printf("PartTblCrc:0x%08x\n", pHead->PartTblCrc);
    CrcRead = pHead->Crc;
    pHead->Crc = 0;
    CrcCalc = VtoyCrc32(pHead, pHead->Length);
    if (CrcCalc != CrcRead)
    {
        printf("Head CRC Check Failed\n");
    }
    else
    {
        printf("Head CRC Check SUCCESS [%x] [%x]\n", CrcCalc, CrcRead);
    }
    CrcRead = pHead->PartTblCrc;
    CrcCalc = VtoyCrc32(pHead + 1, pHead->PartTblEntryLen * pHead->PartTblTotNum);
    if (CrcCalc != CrcRead)
    {
        printf("Part Table CRC Check Failed\n");
    }
    else
    {
        printf("Part Table CRC Check SUCCESS [%x] [%x]\n", CrcCalc, CrcRead);
    }
}
void DumpPartTable(VTOY_GPT_PART_TBL *Tbl)
{
    int i;
    
    DumpGuid("PartType", &Tbl->PartType);
    DumpGuid("PartGuid", &Tbl->PartGuid);
    printf("StartLBA:%lu\n", Tbl->StartLBA);
    printf("LastLBA:%lu\n", Tbl->LastLBA);
    printf("Attr:0x%lx\n", Tbl->Attr);
    printf("Name:");
    for (i = 0; i < 36 && Tbl->Name[i]; i++)
    {
        printf("%c", (CHAR)(Tbl->Name[i]));
    }
    printf("\n");    
}
void DumpMBR(MBR_HEAD *pMBR)
{
    int i;
    
    for (i = 0; i < 4; i++)
    {
        printf("=========== Partition Table %d ============\n", i + 1);
        printf("PartTbl.Active = 0x%x\n", pMBR->PartTbl[i].Active);
        printf("PartTbl.FsFlag = 0x%x\n", pMBR->PartTbl[i].FsFlag);
        printf("PartTbl.StartSectorId = %u\n", pMBR->PartTbl[i].StartSectorId);
        printf("PartTbl.SectorCount = %u\n", pMBR->PartTbl[i].SectorCount);
        printf("PartTbl.StartHead = %u\n", pMBR->PartTbl[i].StartHead);
        printf("PartTbl.StartSector = %u\n", pMBR->PartTbl[i].StartSector);
        printf("PartTbl.StartCylinder = %u\n", pMBR->PartTbl[i].StartCylinder);
        printf("PartTbl.EndHead = %u\n", pMBR->PartTbl[i].EndHead);
        printf("PartTbl.EndSector = %u\n", pMBR->PartTbl[i].EndSector);
        printf("PartTbl.EndCylinder = %u\n", pMBR->PartTbl[i].EndCylinder);
    }
}
int DumpGptInfo(VTOY_GPT_INFO *pGptInfo)
{
    int i;
    DumpMBR(&pGptInfo->MBR);
    DumpHead(&pGptInfo->Head);
    for (i = 0; i < 128; i++)
    {
        if (pGptInfo->PartTbl[i].StartLBA == 0)
        {
            break;
        }
    
        printf("=====Part %d=====\n", i);
        DumpPartTable(pGptInfo->PartTbl + i);
    }
    return 0;
}
#define VENTOY_EFI_PART_ATTR   0xC000000000000001ULL
int main(int argc, const char **argv)
{
    int i;
    int fd;
    UINT64 DiskSize;
    CHAR16 *Name = NULL;
    VTOY_GPT_INFO *pMainGptInfo = NULL;
    VTOY_BK_GPT_INFO *pBackGptInfo = NULL;
    if (argc != 3)
    {
        printf("usage: vtoygpt -f /dev/sdb\n");
        return 1;
    }
    fd = open(argv[2], O_RDWR);
    if (fd < 0)
    {
        printf("Failed to open %s\n", argv[2]);
        return 1;
    }
    pMainGptInfo = malloc(sizeof(VTOY_GPT_INFO));
    pBackGptInfo = malloc(sizeof(VTOY_BK_GPT_INFO));
    if (NULL == pMainGptInfo || NULL == pBackGptInfo)
    {
        close(fd);
        return 1;
    }
    read(fd, pMainGptInfo, sizeof(VTOY_GPT_INFO));
    
    if (argv[1][0] == '-' && argv[1][1] == 'd')
    {
        DumpGptInfo(pMainGptInfo);
    }
    else
    {
        DiskSize = lseek(fd, 0, SEEK_END);
        lseek(fd, DiskSize - 33 * 512, SEEK_SET);
        read(fd, pBackGptInfo, sizeof(VTOY_BK_GPT_INFO));
        Name = pMainGptInfo->PartTbl[1].Name;
        if (Name[0] == 'V' && Name[1] == 'T' && Name[2] == 'O' && Name[3] == 'Y')
        {
            pMainGptInfo->PartTbl[1].Attr = VENTOY_EFI_PART_ATTR;
            pMainGptInfo->Head.PartTblCrc = VtoyCrc32(pMainGptInfo->PartTbl, sizeof(pMainGptInfo->PartTbl));
            pMainGptInfo->Head.Crc = 0;
            pMainGptInfo->Head.Crc = VtoyCrc32(&pMainGptInfo->Head, pMainGptInfo->Head.Length);
            pBackGptInfo->PartTbl[1].Attr = VENTOY_EFI_PART_ATTR;
            pBackGptInfo->Head.PartTblCrc = VtoyCrc32(pBackGptInfo->PartTbl, sizeof(pBackGptInfo->PartTbl));
            pBackGptInfo->Head.Crc = 0;
            pBackGptInfo->Head.Crc = VtoyCrc32(&pBackGptInfo->Head, pBackGptInfo->Head.Length);
            lseek(fd, 512, SEEK_SET);
            write(fd, (UINT8 *)pMainGptInfo + 512, sizeof(VTOY_GPT_INFO) - 512);
            lseek(fd, DiskSize - 33 * 512, SEEK_SET);
            write(fd, pBackGptInfo, sizeof(VTOY_BK_GPT_INFO));
            fsync(fd);
        }
    }
    free(pMainGptInfo);
    free(pBackGptInfo);
    close(fd);
    return 0;
}
 | 8,603 | 
	C | 
	.c | 270 | 26.796296 | 122 | 0.631796 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 725 | 
	main_webui.c | 
	ventoy_Ventoy/LinuxGUI/Ventoy2Disk/main_webui.c | 
	#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <linux/limits.h>
#include <ventoy_define.h>
#include <ventoy_util.h>
#include <ventoy_json.h>
#include <ventoy_disk.h>
#include <ventoy_http.h>
char g_log_file[PATH_MAX];
char g_ini_file[PATH_MAX];
int ventoy_log_init(void);
void ventoy_log_exit(void);
void ventoy_signal_stop(int sig)
{
    vlog("ventoy server exit due to signal ...\n");
    printf("ventoy server exit ...\n");
    
    ventoy_http_stop();
    ventoy_http_exit();
    ventoy_disk_exit();
    ventoy_log_exit();
    exit(0);
}
int main(int argc, char **argv)
{
    int i;
    int rc;
    const char *ip = "127.0.0.1";
    const char *port = "24680";
    if (argc != 3)
    {
        printf("Invalid argc %d\n", argc);
        return 1;
    }
    if (isdigit(argv[1][0]))
    {
        ip = argv[1];
    }
    
    if (isdigit(argv[2][0]))
    {
        port = argv[2];
    }
    snprintf(g_log_file, sizeof(g_log_file), "log.txt");
    snprintf(g_ini_file, sizeof(g_ini_file), "./Ventoy2Disk.ini");
    for (i = 0; i < argc; i++)
    {
        if (argv[i] && argv[i + 1] && strcmp(argv[i], "-l") == 0)
        {
            snprintf(g_log_file, sizeof(g_log_file), "%s", argv[i + 1]);
        }
        else if (argv[i] && argv[i + 1] &&  strcmp(argv[i], "-i") == 0)
        {
            snprintf(g_ini_file, sizeof(g_ini_file), "%s", argv[i + 1]);
        }
    }
    ventoy_log_init();
    vlog("===============================================\n");
    vlog("===== Ventoy2Disk %s %s:%s =====\n", ventoy_get_local_version(), ip, port);
    vlog("===============================================\n");
    ventoy_disk_init();
    ventoy_http_init();
    
    rc = ventoy_http_start(ip, port);
    if (rc)
    {
        printf("Ventoy failed to start http server, check log.txt for detail\n");
    }
    else
    {
        signal(SIGINT, ventoy_signal_stop);
        signal(SIGTSTP, ventoy_signal_stop);
        signal(SIGQUIT, ventoy_signal_stop);
        while (1)
        {
            sleep(100);
        }
    }
    
    return 0;
}
 | 2,226 | 
	C | 
	.c | 85 | 20.952941 | 85 | 0.536273 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 727 | 
	main_gtk.c | 
	ventoy_Ventoy/LinuxGUI/Ventoy2Disk/main_gtk.c | 
	
#include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/limits.h>
#include <ventoy_define.h>
#include <ventoy_util.h>
#include "ventoy_gtk.h"
static int g_kiosk_mode = 0;
char g_log_file[PATH_MAX];
char g_ini_file[PATH_MAX];
static int set_image_from_pixbuf(GtkBuilder *pBuilder, const char *id, const void *pData, int len)
{
    GtkImage *pImage = NULL;
    GdkPixbuf *pPixbuf = NULL;
    GInputStream *pStream = NULL;
    pImage = (GtkImage *)gtk_builder_get_object(pBuilder, id);
    pStream = g_memory_input_stream_new_from_data(pData, len, NULL);
    pPixbuf = gdk_pixbuf_new_from_stream(pStream, NULL, NULL);
    gtk_image_set_from_pixbuf(pImage, pPixbuf);
    return 0;
}
static int set_window_icon_from_pixbuf(GtkWindow *window, const void *pData, int len)
{
    GdkPixbuf *pPixbuf = NULL;
    GInputStream *pStream = NULL;
    pStream = g_memory_input_stream_new_from_data(pData, len, NULL);
    pPixbuf = gdk_pixbuf_new_from_stream(pStream, NULL, NULL);
    gtk_window_set_icon(window, pPixbuf);
    return 0;
}
int early_msgbox(GtkMessageType type, GtkButtonsType buttons, const char *str)
{
    int ret;
    GtkWidget *pMsgBox = NULL;
    
    pMsgBox= gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, type, buttons, str);
    
    ret = gtk_dialog_run(GTK_DIALOG(pMsgBox));
    gtk_widget_destroy(pMsgBox);
    return ret;
}
static int adjust_cur_dir(char *argv0)
{
    int ret = 2;
    char c;
    char *pos = NULL;
    char *end = NULL;
    if (argv0[0] == '.')
    {
        return 1;
    }
    for (pos = argv0; pos && *pos; pos++)
    {
        if (*pos == '/')
        {
            end = pos;
        }
    }
    if (end)
    {
        c = *end;
        *end = 0;
        pos = strstr(argv0, "/tool/");
        if (pos)
        {
            *pos = 0;
        }
        
        ret = chdir(argv0);
        
        *end = c;
        if (pos)
        {
            *pos = '/';
        }
    }
    return ret;
}
int main(int argc, char *argv[])
{
    int i;
    int len;
    const void *pData = NULL;
    GtkWidget *pWidget = NULL;
    GtkBuilder *pBuilder = NULL;
    GError *error = NULL;
    struct stat logstat;
    gtk_init(&argc, &argv);
    
    if (geteuid() != 0)
    {
        early_msgbox(GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, 
                     "Ventoy2Disk permission denied!\r\nPlease run with root privileges.");
        return EACCES;
    }
    if (access("./boot/boot.img", F_OK) == -1)
    {
        adjust_cur_dir(argv[0]);        
    }
    if (access("./boot/boot.img", F_OK) == -1)
    {
        early_msgbox(GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "Please run under the correct directory.");
        return 1;
    }
    for (i = 0; i < argc; i++)
    {
        if (argv[i] && strcmp(argv[i], "--kiosk") == 0)
        {
            g_kiosk_mode = 1;
            break;
        }
    }
    
    snprintf(g_log_file, sizeof(g_log_file), "log.txt");
    snprintf(g_ini_file, sizeof(g_ini_file), "./Ventoy2Disk.ini");
    for (i = 0; i < argc; i++)
    {
        if (argv[i] && argv[i + 1] && strcmp(argv[i], "-l") == 0)
        {
            snprintf(g_log_file, sizeof(g_log_file), "%s", argv[i + 1]);
        }
        else if (argv[i] && argv[i + 1] &&  strcmp(argv[i], "-i") == 0)
        {
            snprintf(g_ini_file, sizeof(g_ini_file), "%s", argv[i + 1]);
        }
    }
    memset(&logstat, 0, sizeof(logstat));
    if (0 == stat(g_log_file, &logstat))
    {
        if (logstat.st_size >= 4 * SIZE_1MB)
        {
            remove(g_log_file);
        }
    }
    ventoy_log_init();
    vlog("================================================\n");
    vlog("===== Ventoy2Disk %s powered by GTK%d.x =====\n", ventoy_get_local_version(), GTK_MAJOR_VERSION);
    vlog("================================================\n");
    vlog("log file is <%s> lastsize:%lld\n", g_log_file, (long long)logstat.st_size);
    vlog("ini file is <%s>\n", g_ini_file);
    ventoy_disk_init();
    ventoy_http_init();
    pBuilder = gtk_builder_new();
    if (!pBuilder)
    {
        vlog("failed to create builder\n");
        return 1;
    }
    if (!gtk_builder_add_from_file(pBuilder, "./tool/VentoyGTK.glade", &error))
    {
        vlog("gtk_builder_add_from_file failed:%s\n", error->message);
        g_clear_error(&error);
        return 1;
    }
    if (g_kiosk_mode)
    {
        gtk_image_set_from_file((GtkImage *)gtk_builder_get_object(pBuilder, "image_refresh"), "/ventoy/refresh.png");        
        gtk_image_set_from_file((GtkImage *)gtk_builder_get_object(pBuilder, "image_secure_local"), "/ventoy/secure.png");        
        gtk_image_set_from_file((GtkImage *)gtk_builder_get_object(pBuilder, "image_secure_dev"), "/ventoy/secure.png");        
    }
    else
    {
        pData = get_refresh_icon_raw_data(&len);
        set_image_from_pixbuf(pBuilder, "image_refresh", pData, len);        
        pData = get_secure_icon_raw_data(&len);
        set_image_from_pixbuf(pBuilder, "image_secure_local", pData, len);
        set_image_from_pixbuf(pBuilder, "image_secure_dev", pData, len);
    }
    pWidget = GTK_WIDGET(gtk_builder_get_object(pBuilder, "window"));
    gtk_widget_show_all(pWidget);
    pData = get_window_icon_raw_data(&len);
    set_window_icon_from_pixbuf(GTK_WINDOW(pWidget), pData, len);
    on_init_window(pBuilder);
    g_signal_connect(G_OBJECT(pWidget), "delete_event", G_CALLBACK(on_exit_window), NULL);
    g_signal_connect(G_OBJECT(pWidget), "destroy", G_CALLBACK(gtk_main_quit), NULL);
    gtk_main();
    ventoy_disk_exit();
    ventoy_http_exit();
    
    g_object_unref (G_OBJECT(pBuilder));
    
    vlog("######## Ventoy2Disk GTK %s exit ########\n", ventoy_get_local_version());
    /* log exit must at the end */
    ventoy_log_exit();
    return 0;
}
 | 6,179 | 
	C | 
	.c | 186 | 25.709677 | 131 | 0.558643 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 728 | 
	ventoy_gtk.c | 
	ventoy_Ventoy/LinuxGUI/Ventoy2Disk/GTK/ventoy_gtk.c | 
	/******************************************************************************
 * ventoy_gtk.c
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <linux/limits.h>
#include <ventoy_define.h>
#include <ventoy_json.h>
#include <ventoy_util.h>
#include <ventoy_disk.h>
#include <ventoy_http.h>
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
#include "ventoy_gtk.h"
int g_secure_boot_support = 0;
GtkWidget *g_topWindow = NULL;
GtkWidget *g_partCfgWindow = NULL;
GtkBuilder *g_pXmlBuilder = NULL;
GtkComboBoxText *g_dev_combobox = NULL;
GtkButton *g_refresh_button = NULL;
GtkButton *g_install_button = NULL;
GtkButton *g_update_button = NULL;
GtkMenu *g_lang_menu = NULL;;
GtkCheckMenuItem *g_menu_item_secure_boot = NULL;
GtkCheckMenuItem *g_menu_item_mbr = NULL;
GtkCheckMenuItem *g_menu_item_gpt = NULL;
GtkCheckMenuItem *g_menu_item_show_all = NULL;
GtkLabel *g_device_title = NULL;
GtkLabel *g_label_local_part_style = NULL;
GtkLabel *g_label_dev_part_style = NULL;
GtkLabel *g_label_local_ver = NULL;
GtkLabel *g_label_disk_ver = NULL;
GtkLabel *g_label_status = NULL;
GtkImage *g_image_secure_local = NULL;
GtkImage *g_image_secure_device = NULL;
GtkToggleButton *g_part_align_checkbox = NULL;
GtkToggleButton *g_part_preserve_checkbox = NULL;
GtkEntry *g_part_reserve_space_value = NULL;
GtkComboBoxText *g_part_space_unit_combox = NULL;
GtkProgressBar *g_progress_bar = NULL;
VTOY_JSON *g_languages_json = NULL;
int g_languages_toggled_proc = 0;
int g_dev_changed_proc = 0;
gboolean g_align_part_with_4k = TRUE;
gboolean g_preserve_space_check = FALSE;
int g_preserve_space_unit = 1;
int g_preserve_space_number = 0;
gboolean g_thread_run = FALSE;
const char *language_string(const char *id)
{
    const char *pName = NULL;
    VTOY_JSON *node = NULL;
    const char *pCurLang = ventoy_code_get_cur_language();
    for (node = g_languages_json->pstChild; node; node = node->pstNext)
    {
        pName = vtoy_json_get_string_ex(node->pstChild, "name");
        if (0 == g_strcmp0(pName, pCurLang))
        {
            break;
        }
    }
    if (NULL == node)
    {
        return "xxx";
    }
    return vtoy_json_get_string_ex(node->pstChild, id);
}
int msgbox(GtkMessageType type, GtkButtonsType buttons, const char *strid)
{
    int ret;
    GtkWidget *pMsgBox = NULL;
    pMsgBox = gtk_message_dialog_new(NULL, GTK_DIALOG_MODAL, type, buttons, "%s", language_string(strid));
    ret = gtk_dialog_run(GTK_DIALOG(pMsgBox));
    gtk_widget_destroy(pMsgBox);
    return ret;
}
static void set_item_visible(const char *id, int visible)
{
    GtkWidget *pWidget = NULL;
    
    pWidget = GTK_WIDGET(gtk_builder_get_object(g_pXmlBuilder, id));
    if (visible)
    {
        gtk_widget_show(pWidget);        
    }
    else
    {
        gtk_widget_hide(pWidget);        
    }
}
static void init_part_style_menu(void)
{
    int style;
    style = ventoy_code_get_cur_part_style();
    gtk_check_menu_item_set_active(g_menu_item_mbr, (0 == style));
    gtk_check_menu_item_set_active(g_menu_item_gpt, (1 == style)); 
    gtk_label_set_text(g_label_local_part_style, style ? "GPT" : "MBR");
}
static void select_language(const char *lang)
{
    const char *pName = NULL;
    const char *pPos = NULL;
    const char *pDevice = NULL;
    VTOY_JSON *node = NULL;
    char device[256];
    
    for (node = g_languages_json->pstChild; node; node = node->pstNext)
    {
        pName = vtoy_json_get_string_ex(node->pstChild, "name");
        if (0 == g_strcmp0(pName, lang))
        {
            break;
        }
    }
    if (NULL == node)
    {
        return;
    }
    pDevice = gtk_label_get_text(g_device_title);
    if (pDevice && (pPos = strchr(pDevice, '[')) != NULL)
    {
        g_snprintf(device, sizeof(device), "%s  %s", vtoy_json_get_string_ex(node->pstChild, "STR_DEVICE"), pPos);
        gtk_label_set_text(g_device_title, device);
    }
    else
    {
        gtk_label_set_text(g_device_title, vtoy_json_get_string_ex(node->pstChild, "STR_DEVICE"));
    }
    
    LANG_LABEL_TEXT("label_local_ver", "STR_LOCAL_VER");
    LANG_LABEL_TEXT("label_device_ver", "STR_DISK_VER");
    
    LANG_LABEL_TEXT("label_status", "STR_STATUS");
    
    LANG_BUTTON_TEXT("button_install", "STR_INSTALL");
    LANG_BUTTON_TEXT("button_update", "STR_UPDATE");
    
    LANG_MENU_ITEM_TEXT("menu_option", "STR_MENU_OPTION");
    LANG_MENU_ITEM_TEXT("menu_item_secure", "STR_MENU_SECURE_BOOT");
    LANG_MENU_ITEM_TEXT("menu_part_style", "STR_MENU_PART_STYLE");
    LANG_MENU_ITEM_TEXT("menu_item_part_cfg", "STR_MENU_PART_CFG");
    LANG_MENU_ITEM_TEXT("menu_item_clear", "STR_MENU_CLEAR");
    LANG_MENU_ITEM_TEXT("menu_item_show_all", "STR_SHOW_ALL_DEV");
    LANG_BUTTON_TEXT("space_check_btn", "STR_PRESERVE_SPACE");
    LANG_BUTTON_TEXT("space_align_btn", "STR_PART_ALIGN_4KB");
    LANG_BUTTON_TEXT("button_partcfg_ok", "STR_BTN_OK");
    LANG_BUTTON_TEXT("button_partcfg_cancel", "STR_BTN_CANCEL");
    gtk_window_set_title(GTK_WINDOW(g_partCfgWindow), vtoy_json_get_string_ex(node->pstChild, "STR_MENU_PART_CFG"));
    /* 
     * refresh screen 
     */
     
    gtk_widget_hide(g_topWindow);
    gtk_widget_show(g_topWindow);
}
void on_secure_boot_toggled(GtkMenuItem *menuItem, gpointer data) 
{
    g_secure_boot_support = 1 - g_secure_boot_support;
    if (g_secure_boot_support)
    {
        gtk_widget_show((GtkWidget *)g_image_secure_local);        
    }
    else
    {
        gtk_widget_hide((GtkWidget *)g_image_secure_local);        
    }
}
void on_devlist_changed(GtkWidget *widget, gpointer data) 
{
    int active;
    ventoy_disk *cur = NULL;
    char version[512];
    if (g_dev_changed_proc == 0)
    {
        return;
    }
    gtk_widget_set_sensitive(GTK_WIDGET(g_update_button), FALSE);
    gtk_widget_hide((GtkWidget *)g_image_secure_device);
    gtk_label_set_markup(g_label_disk_ver, "");
    gtk_label_set_text(g_label_dev_part_style, "");
    active = gtk_combo_box_get_active((GtkComboBox *)g_dev_combobox);
    if (active < 0 || active >= g_disk_num)
    {
        vlog("invalid active combox id %d\n", active);
        return;
    }
    cur = g_disk_list + active;
    if (cur->vtoydata.ventoy_valid)
    {
        if (cur->vtoydata.secure_boot_flag)
        {
            gtk_widget_show((GtkWidget *)g_image_secure_device);
        }
        else
        {
            gtk_widget_hide((GtkWidget *)g_image_secure_device);
        }
        if (g_secure_boot_support != cur->vtoydata.secure_boot_flag)
        {
            gtk_check_menu_item_set_active(g_menu_item_secure_boot, 1 - g_secure_boot_support);
        }
        g_snprintf(version, sizeof(version), VTOY_VER_FMT, cur->vtoydata.ventoy_ver);
        gtk_label_set_markup(g_label_disk_ver, version);
        gtk_label_set_text(g_label_dev_part_style, cur->vtoydata.partition_style ? "GPT" : "MBR");
        gtk_widget_set_sensitive(GTK_WIDGET(g_update_button), TRUE);
    }
    else
    {
        if (!g_secure_boot_support)
        {
            gtk_check_menu_item_set_active(g_menu_item_secure_boot, 1 - g_secure_boot_support);
        }
    }
}
void on_language_toggled(GtkMenuItem *menuItem, gpointer data) 
{
    const char *cur_lang = NULL; 
    if (g_languages_toggled_proc == 0)
    {
        return;
    }
    cur_lang = ventoy_code_get_cur_language();
    if (g_strcmp0(cur_lang, (char *)data) != 0)
    {
        ventoy_code_set_cur_language((char *)data);
        select_language((char *)data);
    }
}
void on_part_style_toggled(GtkMenuItem *menuItem, gpointer data) 
{
    int style;
    
    style = ventoy_code_get_cur_part_style();
    ventoy_code_set_cur_part_style(1 - style);
    gtk_label_set_text(g_label_local_part_style, style ? "MBR" : "GPT");
}
static ventoy_disk *select_active_dev(const char *select, int *activeid)
{
    int i;
    int alldev;
    ventoy_disk *cur = NULL;
    alldev = ventoy_code_get_cur_show_all();
    
    /* find the match one */
    if (select)
    {
        for (i = 0; i < g_disk_num; i++)
        {
            cur = g_disk_list + i;
            if (alldev == 0 && cur->type != VTOY_DEVICE_USB)
            {
                continue;
            }
            
            if (strcmp(cur->disk_name, select) == 0)
            {
                *activeid = i;
                return cur;
            }
        }
    }
    /* find the first one that installed with Ventoy */
    for (i = 0; i < g_disk_num; i++)
    {
        cur = g_disk_list + i;
        if (alldev == 0 && cur->type != VTOY_DEVICE_USB)
        {
            continue;
        }
        
        if (cur->vtoydata.ventoy_valid)
        {
            *activeid = i;
            return cur;
        }
    }
    /* find the first USB interface device */
    for (i = 0; i < g_disk_num; i++)
    {
        cur = g_disk_list + i;
        if (alldev == 0 && cur->type != VTOY_DEVICE_USB)
        {
            continue;
        }
        
        if (cur->type == VTOY_DEVICE_USB)
        {
            *activeid = i;
            return cur;
        }
    }
    /* use the first one */
    for (i = 0; i < g_disk_num; i++)
    {
        cur = g_disk_list + i;
        if (alldev == 0 && cur->type != VTOY_DEVICE_USB)
        {
            continue;
        }
        
        *activeid = i;
        return cur;
    }
        
    return NULL;
}
static void fill_dev_list(const char *select)
{
    int i;
    int alldev;
    int activeid;
    int count = 0;
    char line[512];
    ventoy_disk *cur = NULL;
    ventoy_disk *active = NULL;
    GtkListStore *store = NULL;
    g_dev_changed_proc = 0;
    alldev = ventoy_code_get_cur_show_all();
    
    vlog("fill_dev_list total disk: %d showall:%d\n", g_disk_num, alldev);
    /* gtk_combo_box_text_remove_all */
    store = GTK_LIST_STORE(gtk_combo_box_get_model(GTK_COMBO_BOX(g_dev_combobox)));
    gtk_list_store_clear(store);
    for (i = 0; i < g_disk_num; i++)
    {
        cur = g_disk_list + i;
        if (alldev == 0 && cur->type != VTOY_DEVICE_USB)
        {
            continue;
        }
        g_snprintf(line, sizeof(line), "%s  [%s]  %s", cur->disk_name, cur->human_readable_size, cur->disk_model);
        gtk_combo_box_text_append_text(g_dev_combobox, line);
        count++;
    }
    active = select_active_dev(select, &activeid);
    if (active)
    {
        vlog("combox count:%d, active:%s id:%d\n", count, active->disk_name, activeid);
        gtk_combo_box_set_active((GtkComboBox *)g_dev_combobox, activeid); 
        gtk_widget_set_sensitive(GTK_WIDGET(g_install_button), TRUE);
        gtk_widget_set_sensitive(GTK_WIDGET(g_update_button), active->vtoydata.ventoy_valid);
    }
    else
    {
        vlog("combox count:%d, no active id\n", count);
        gtk_widget_set_sensitive(GTK_WIDGET(g_install_button), FALSE);
        gtk_widget_set_sensitive(GTK_WIDGET(g_update_button), FALSE);
    }
    g_dev_changed_proc = 1;
    on_devlist_changed(NULL, NULL);
}
void on_show_all_toggled(GtkMenuItem *menuItem, gpointer data) 
{
    int show_all = ventoy_code_get_cur_show_all();
    
    ventoy_code_set_cur_show_all(1 - show_all);
    fill_dev_list(NULL);
}
void on_button_refresh_clicked(GtkWidget *widget, gpointer data) 
{
    if (g_thread_run || ventoy_code_is_busy())
    {
        msgbox(GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "STR_WAIT_PROCESS");
        return;
    }    
    ventoy_code_refresh_device();
    fill_dev_list(NULL);
}
static void set_progress_bar_percent(int percent)
{
    char *pos = NULL;
    const char *text = NULL;
    char tmp[128];
    gtk_progress_bar_set_fraction(g_progress_bar, percent * 1.0 / 100);
    vlog("set percent %d\n", percent);
    
    text = language_string("STR_STATUS");
    if (percent == 0)
    {
        gtk_label_set_text(g_label_status, text);
    }
    else
    {
        g_snprintf(tmp, sizeof(tmp), "%s", text);
        pos = strchr(tmp, '-');
        if (pos)
        {
            g_snprintf(pos + 2, sizeof(tmp), "%d%%", percent);
            gtk_label_set_text(g_label_status, tmp);
        }
    }
}
void on_clear_ventoy(GtkMenuItem *menuItem, gpointer data) 
{
    int ret;
    int active;
    char buf[1024];
    char out[256];
    char disk_name[32]; 
    ventoy_disk *cur = NULL;
    if (g_thread_run || ventoy_code_is_busy())
    {
        msgbox(GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "STR_WAIT_PROCESS");
        return;
    }
    active = gtk_combo_box_get_active((GtkComboBox *)g_dev_combobox);
    if (active < 0 || active >= g_disk_num)
    {
        vlog("invalid active combox id %d\n", active);
        return;
    }
    if (GTK_RESPONSE_OK != msgbox(GTK_MESSAGE_WARNING, GTK_BUTTONS_OK_CANCEL, "STR_INSTALL_TIP"))
    {
        return;
    }
    if (GTK_RESPONSE_OK != msgbox(GTK_MESSAGE_WARNING, GTK_BUTTONS_OK_CANCEL, "STR_INSTALL_TIP2"))
    {
        return;
    }
    gtk_widget_set_sensitive (GTK_WIDGET(g_refresh_button), FALSE);    
    gtk_widget_set_sensitive (GTK_WIDGET(g_install_button), FALSE);    
    gtk_widget_set_sensitive (GTK_WIDGET(g_update_button), FALSE);
    g_thread_run = TRUE;
    cur = g_disk_list + active;
    g_snprintf(disk_name, sizeof(disk_name), "%s", cur->disk_name);
    g_snprintf(buf, sizeof(buf), "{\"method\":\"clean\",\"disk\":\"%s\"}", disk_name);
    out[0] = 0;
    ventoy_func_handler(buf, out, sizeof(out));
    vlog("func handler clean <%s>\n", out);
    if (strstr(out, "success"))
    {
        ret = ventoy_code_get_result();
        ventoy_code_refresh_device();
        cur = NULL;
    }
    else
    {
        ret = 1;
    }
    if (ret == 0)
    {
        msgbox(GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "STR_CLEAR_SUCCESS");
    }
    else
    {
        msgbox(GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "STR_CLEAR_FAILED");
    }
    set_progress_bar_percent(0);
    gtk_widget_set_sensitive(GTK_WIDGET(g_refresh_button), TRUE);    
    gtk_widget_set_sensitive(GTK_WIDGET(g_install_button), TRUE);    
    gtk_widget_set_sensitive(GTK_WIDGET(g_update_button), TRUE);
    fill_dev_list(disk_name);
    g_thread_run = FALSE;
}
static int install_proc(ventoy_disk *cur)
{
    int ret = 0;
    int pos = 0;
    int buflen = 0;
    int percent = 0;
    char buf[1024];
    char dec[64];
    char out[256];
    char disk_name[32]; 
    long long space;
    vlog("install_thread ...\n");
    g_snprintf(disk_name, sizeof(disk_name), "%s", cur->disk_name);
    buflen = sizeof(buf);
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_STRN("method", "install");
    VTOY_JSON_FMT_STRN("disk", disk_name);
    if (g_preserve_space_check)
    {
        space = g_preserve_space_number;
        if (g_preserve_space_unit == 1)
        {
            space = space * 1024 * 1024 * 1024LL;
        }
        else
        {
            space = space * 1024 * 1024LL;
        }
        snprintf(dec, sizeof(dec), "%lld", space);
        VTOY_JSON_FMT_STRN("reserve_space", dec);
    }
    else
    {
        VTOY_JSON_FMT_STRN("reserve_space", "0");
    }
    VTOY_JSON_FMT_UINT("partstyle", ventoy_code_get_cur_part_style());
    VTOY_JSON_FMT_UINT("secure_boot", g_secure_boot_support);
    VTOY_JSON_FMT_UINT("align_4kb", g_align_part_with_4k);
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    
    out[0] = 0;
    ventoy_func_handler(buf, out, sizeof(out));
    vlog("func handler install <%s>\n", out);
    if (strstr(out, "success"))
    {
        while (percent != 100)
        {
            percent = ventoy_code_get_percent();
            set_progress_bar_percent(percent);
            GTK_MSG_ITERATION();
            usleep(50 * 1000);
        }
        ret = ventoy_code_get_result();
        ventoy_code_refresh_device();
        cur = NULL;
    }
    else
    {
        ret = 1;
    }
    if (ret)
    {
        msgbox(GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "STR_INSTALL_FAILED");
    }
    else
    {   
        msgbox(GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "STR_INSTALL_SUCCESS");
    }
    set_progress_bar_percent(0);
    gtk_widget_set_sensitive(GTK_WIDGET(g_refresh_button), TRUE);    
    gtk_widget_set_sensitive(GTK_WIDGET(g_install_button), TRUE);    
    gtk_widget_set_sensitive(GTK_WIDGET(g_update_button), TRUE);
    fill_dev_list(disk_name);
    g_thread_run = FALSE;
    return 0;
}
void on_button_install_clicked(GtkWidget *widget, gpointer data) 
{
    int active;
    long long size;
    long long space;
    ventoy_disk *cur = NULL;
    if (g_thread_run || ventoy_code_is_busy())
    {
        msgbox(GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "STR_WAIT_PROCESS");
        return;
    }
    active = gtk_combo_box_get_active((GtkComboBox *)g_dev_combobox);
    if (active < 0 || active >= g_disk_num)
    {
        vlog("invalid active combox id %d\n", active);
        return;
    }
    cur = g_disk_list + active;
    if (cur->is4kn)
    {
        msgbox(GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "STR_4KN_UNSUPPORTED");
        return;
    }
    if (ventoy_code_get_cur_part_style() == 0 && cur->size_in_byte > 2199023255552ULL)
    {
        msgbox(GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "STR_DISK_2TB_MBR_ERROR");
        return;
    }
    if (g_preserve_space_check)
    {
        space = g_preserve_space_number;
        if (g_preserve_space_unit == 1)
        {
            space = space * 1024;
        }
        else
        {
            space = space;
        }
        size = cur->size_in_byte / SIZE_1MB;
        if (size <= space || (size - space) <= (VTOYEFI_PART_BYTES / SIZE_1MB))
    	{
    	    msgbox(GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "STR_SPACE_VAL_INVALID");
    		vlog("reserved space value too big ...\n");
    		return;
    	}
    }
    if (GTK_RESPONSE_OK != msgbox(GTK_MESSAGE_WARNING, GTK_BUTTONS_OK_CANCEL, "STR_INSTALL_TIP"))
    {
        return;
    }
    if (GTK_RESPONSE_OK != msgbox(GTK_MESSAGE_WARNING, GTK_BUTTONS_OK_CANCEL, "STR_INSTALL_TIP2"))
    {
        return;
    }
    gtk_widget_set_sensitive (GTK_WIDGET(g_refresh_button), FALSE);    
    gtk_widget_set_sensitive (GTK_WIDGET(g_install_button), FALSE);    
    gtk_widget_set_sensitive (GTK_WIDGET(g_update_button), FALSE);
    
    g_thread_run = TRUE;
    install_proc(cur);
}
static int update_proc(ventoy_disk *cur)
{
    int ret = 0;
    int percent = 0;
    char buf[1024];
    char out[256];
    char disk_name[32]; 
    g_snprintf(disk_name, sizeof(disk_name), "%s", cur->disk_name);
    g_snprintf(buf, sizeof(buf), "{\"method\":\"update\",\"disk\":\"%s\",\"secure_boot\":%d}", 
        disk_name, g_secure_boot_support);
    out[0] = 0;
    ventoy_func_handler(buf, out, sizeof(out));
    vlog("func handler update <%s>\n", out);
    if (strstr(out, "success"))
    {
        while (percent != 100)
        {
            percent = ventoy_code_get_percent();
            set_progress_bar_percent(percent);
            GTK_MSG_ITERATION();
            usleep(50 * 1000);
        }
        ret = ventoy_code_get_result();
        ventoy_code_refresh_device();
        cur = NULL;
    }
    else
    {
        ret = 1;
    }
    if (ret)
    {
        msgbox(GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "STR_UPDATE_FAILED");
    }
    else
    {   
        msgbox(GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "STR_UPDATE_SUCCESS");
    }
    set_progress_bar_percent(0);
    gtk_widget_set_sensitive(GTK_WIDGET(g_refresh_button), TRUE);    
    gtk_widget_set_sensitive(GTK_WIDGET(g_install_button), TRUE);    
    gtk_widget_set_sensitive(GTK_WIDGET(g_update_button), TRUE);
    fill_dev_list(disk_name);
    g_thread_run = FALSE;
    return 0;
}
void on_button_update_clicked(GtkWidget *widget, gpointer data) 
{
    int active;
    ventoy_disk *cur = NULL;
    if (g_thread_run || ventoy_code_is_busy())
    {
        msgbox(GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "STR_WAIT_PROCESS");
        return;
    }
    active = gtk_combo_box_get_active((GtkComboBox *)g_dev_combobox);
    if (active < 0 || active >= g_disk_num)
    {
        vlog("invalid active combox id %d\n", active);
        return;
    }
    cur = g_disk_list + active;    
    if (cur->vtoydata.ventoy_valid == 0)
    {
        vlog("invalid ventoy version.\n");
        return;
    }
    if (GTK_RESPONSE_OK != msgbox(GTK_MESSAGE_INFO, GTK_BUTTONS_OK_CANCEL, "STR_UPDATE_TIP"))
    {
        return;
    }
    gtk_widget_set_sensitive (GTK_WIDGET(g_refresh_button), FALSE);    
    gtk_widget_set_sensitive (GTK_WIDGET(g_install_button), FALSE);    
    gtk_widget_set_sensitive (GTK_WIDGET(g_update_button), FALSE);
    
    g_thread_run = TRUE;
    
    update_proc(cur);
}
static gint lang_compare(gconstpointer a, gconstpointer b)
{
    const char *name1 = (const char *)a;
    const char *name2 = (const char *)b;
    if (strncmp(name1, "Chinese Simplified", 18) == 0)
    {
        return -1;
    }
    else if (strncmp(name2, "Chinese Simplified", 18) == 0)
    {
        return 1;
    }
    else
    {
        return g_strcmp0(name1, name2);        
    }
}
static int load_languages(void)
{
    int size = 0;
    char *pBuf = NULL;
    char *pCur = NULL;
    const char *pCurLang = NULL;
    const char *pName = NULL;
    VTOY_JSON *json = NULL;
    VTOY_JSON *node = NULL;
    VTOY_JSON *lang = NULL;
    GSList *pGroup = NULL;
    GList *pNameNode = NULL;
    GList *pNameList = NULL;
    GtkRadioMenuItem *pItem = NULL;
    vlog("load_languages ...\n");
    pCurLang = ventoy_code_get_cur_language();
    if (pCurLang[0] == 0)
    {
        pName = getenv("LANG");
        if (pName && strncmp(pName, "zh_CN", 5) == 0)
        {
            ventoy_code_set_cur_language("Chinese Simplified (简体中文)");            
        }
        else
        {
            ventoy_code_set_cur_language("English (English)");            
        }
        pCurLang = ventoy_code_get_cur_language();
    }
    vlog("current language <%s>\n", pCurLang);
    
    ventoy_read_file_to_buf("./tool/languages.json", 1, (void **)&pBuf, &size);
    json = vtoy_json_create();
    vtoy_json_parse(json, pBuf);
    g_languages_json = json;
    for (node = json->pstChild; node; node = node->pstNext)
    {
        pName = vtoy_json_get_string_ex(node->pstChild, "name");
        if (pName)
        {
            pNameList = g_list_append(pNameList, (gpointer)pName);
        }
        for (lang = node->pstChild; lang; lang = lang->pstNext)
        {
            if (lang->enDataType == JSON_TYPE_STRING)
            {
                pCur = lang->unData.pcStrVal;
                while (*pCur)
                {
                    if (*pCur == '#')
                    {
                        *pCur = '\r';
                    }
                    else if (*pCur == '@')
                    {
                        *pCur = '\n';
                    }
                    pCur++;
                }
            }
        }
    }
    pNameList = g_list_sort(pNameList, lang_compare);
    for (pNameNode = g_list_first(pNameList); pNameNode; pNameNode = g_list_next(pNameNode))
    {
        pName = (char *)(pNameNode->data);
        pItem = (GtkRadioMenuItem *)gtk_radio_menu_item_new_with_label(pGroup, pName);
        pGroup = gtk_radio_menu_item_get_group(pItem);
        
        if (strcmp(pCurLang, pName) == 0)
        {
            gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(pItem), TRUE);
        }
        g_signal_connect(pItem, "toggled", G_CALLBACK(on_language_toggled), (gpointer)pName);
        gtk_widget_show((GtkWidget *)pItem);
        gtk_menu_shell_append(GTK_MENU_SHELL(g_lang_menu), (GtkWidget *)pItem);
    }
    
    g_list_free(pNameList);
    free(pBuf);
    select_language(pCurLang);
    g_languages_toggled_proc = 1;
    
    return 0;
}
void on_part_cfg_ok(GtkWidget *widget, gpointer data) 
{
    const char *pos = NULL;
    const char *input = NULL;
    char device[256];
    gboolean checked = gtk_toggle_button_get_active(g_part_preserve_checkbox);
    if (checked)
    {
        input = gtk_entry_get_text(g_part_reserve_space_value);
        if (input == NULL || input[0] == 0)
        {
            msgbox(GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "STR_SPACE_VAL_INVALID");
            return;
        }
        for (pos = input; *pos; pos++)
        {
            if (*pos < '0' || *pos > '9')
            {
                msgbox(GTK_MESSAGE_ERROR, GTK_BUTTONS_OK, "STR_SPACE_VAL_INVALID");
                return;
            }
        }
        g_preserve_space_unit = gtk_combo_box_get_active((GtkComboBox *)g_part_space_unit_combox);
        g_preserve_space_number = (int)strtol(input, NULL, 10);
        g_snprintf(device, sizeof(device), "%s  [ -%d%s ]", 
            language_string("STR_DEVICE"), g_preserve_space_number, 
            g_preserve_space_unit ? "GB" : "MB");
        gtk_label_set_text(g_device_title, device);
    }
    else
    {
        gtk_label_set_text(g_device_title, language_string("STR_DEVICE"));
    }
    g_preserve_space_check = checked;
    g_align_part_with_4k = gtk_toggle_button_get_active(g_part_align_checkbox);
    gtk_widget_hide(g_partCfgWindow);
}
void on_part_cfg_cancel(GtkWidget *widget, gpointer data) 
{
    gtk_widget_hide(g_partCfgWindow);
}
int on_part_cfg_close(GtkWidget *widget, gpointer data) 
{
    gtk_widget_hide(g_partCfgWindow);
    return TRUE;
}
void on_part_config(GtkMenuItem *menuItem, gpointer data) 
{
    char value[64];
    gtk_toggle_button_set_active(g_part_align_checkbox, g_align_part_with_4k);
    gtk_toggle_button_set_active(g_part_preserve_checkbox, g_preserve_space_check);
    gtk_widget_set_sensitive(GTK_WIDGET(g_part_reserve_space_value), g_preserve_space_check);
    gtk_widget_set_sensitive(GTK_WIDGET(g_part_space_unit_combox), g_preserve_space_check);
    if (g_preserve_space_check)
    {
        g_snprintf(value, sizeof(value), "%d", g_preserve_space_number);
        gtk_entry_set_text(g_part_reserve_space_value, value);
        gtk_combo_box_set_active((GtkComboBox *)g_part_space_unit_combox, g_preserve_space_unit);
    }
    gtk_widget_show_all(g_partCfgWindow);
}
void on_reserve_space_toggled(GtkMenuItem *menuItem, gpointer data) 
{
    gboolean checked = gtk_toggle_button_get_active(g_part_preserve_checkbox);
    gtk_widget_set_sensitive(GTK_WIDGET(g_part_reserve_space_value), checked);
    gtk_widget_set_sensitive(GTK_WIDGET(g_part_space_unit_combox), checked);
}
static void init_part_cfg_window(GtkBuilder *pBuilder)
{
#if GTK_CHECK_VERSION(3, 0, 0)
    GtkWidget *pHeader = NULL;
    pHeader = gtk_header_bar_new();
    gtk_header_bar_set_show_close_button(GTK_HEADER_BAR(pHeader), FALSE);
    gtk_window_set_titlebar (GTK_WINDOW(g_partCfgWindow), pHeader);
    gtk_window_set_title(GTK_WINDOW(g_partCfgWindow), "Partition Configuration");
#endif
    gtk_combo_box_set_active((GtkComboBox *)g_part_space_unit_combox, g_preserve_space_unit);
    gtk_widget_set_sensitive (GTK_WIDGET(g_part_reserve_space_value), FALSE);
    gtk_widget_set_sensitive (GTK_WIDGET(g_part_space_unit_combox), FALSE);
    SIGNAL("space_check_btn",   "toggled",  on_reserve_space_toggled);
    SIGNAL("button_partcfg_ok", "clicked", on_part_cfg_ok);
    SIGNAL("button_partcfg_cancel", "clicked", on_part_cfg_cancel);
    SIGNAL("part_cfg_dlg", "delete_event", on_part_cfg_close);
}
static void add_accelerator(GtkAccelGroup *agMain, void *widget, const char *signal, guint accel_key)
{
    gtk_widget_add_accelerator(GTK_WIDGET(widget), signal, agMain, accel_key, GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
    gtk_widget_add_accelerator(GTK_WIDGET(widget), signal, agMain, accel_key, GDK_SHIFT_MASK | GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);
}
void on_init_window(GtkBuilder *pBuilder)
{
    GSList *pGroup = NULL;
    GtkAccelGroup *agMain = NULL;
    char version[512];
    vlog("on_init_window ...\n");
    
    g_pXmlBuilder = pBuilder;
    g_topWindow = BUILDER_ITEM(GtkWidget, "window");
    g_partCfgWindow = BUILDER_ITEM(GtkWidget, "part_cfg_dlg");
    g_dev_combobox = BUILDER_ITEM(GtkComboBoxText, "combobox_devlist");
    g_refresh_button = BUILDER_ITEM(GtkButton, "button_refresh");
    g_install_button = BUILDER_ITEM(GtkButton, "button_install");
    g_update_button = BUILDER_ITEM(GtkButton, "button_update");
    
    g_lang_menu = BUILDER_ITEM(GtkMenu, "submenu_language");
    g_menu_item_secure_boot = BUILDER_ITEM(GtkCheckMenuItem, "menu_item_secure");
    g_menu_item_mbr = BUILDER_ITEM(GtkCheckMenuItem, "menu_item_mbr");
    g_menu_item_gpt = BUILDER_ITEM(GtkCheckMenuItem, "menu_item_gpt");
    g_menu_item_show_all = BUILDER_ITEM(GtkCheckMenuItem, "menu_item_show_all");
    
    g_device_title = BUILDER_ITEM(GtkLabel, "label_device");
    g_label_local_part_style = BUILDER_ITEM(GtkLabel, "label_local_part_style");
    g_label_dev_part_style = BUILDER_ITEM(GtkLabel, "label_dev_part_style");
    
    g_label_local_ver = BUILDER_ITEM(GtkLabel, "label_local_ver_value");
    g_label_disk_ver = BUILDER_ITEM(GtkLabel, "label_dev_ver_value");
    
    g_label_status = BUILDER_ITEM(GtkLabel, "label_status");
    
    g_image_secure_local = BUILDER_ITEM(GtkImage, "image_secure_local");
    g_image_secure_device = BUILDER_ITEM(GtkImage, "image_secure_dev");
    
    g_part_preserve_checkbox = BUILDER_ITEM(GtkToggleButton, "space_check_btn");
    g_part_align_checkbox = BUILDER_ITEM(GtkToggleButton, "space_align_btn");
    g_part_reserve_space_value = BUILDER_ITEM(GtkEntry, "entry_reserve_space");
    g_part_space_unit_combox = BUILDER_ITEM(GtkComboBoxText, "comboboxtext_unit");
    
    g_progress_bar = BUILDER_ITEM(GtkProgressBar, "progressbar1");
    init_part_cfg_window(pBuilder);
    /* for gtk2 */
    gtk_frame_set_shadow_type(BUILDER_ITEM(GtkFrame, "frame_dummy1"), GTK_SHADOW_NONE); 
    gtk_frame_set_shadow_type(BUILDER_ITEM(GtkFrame, "frame_dummy2"), GTK_SHADOW_NONE); 
    /* join group */
    pGroup = gtk_radio_menu_item_get_group((GtkRadioMenuItem *)g_menu_item_mbr);
    gtk_radio_menu_item_set_group((GtkRadioMenuItem *)g_menu_item_gpt, pGroup);
    gtk_widget_hide((GtkWidget *)g_image_secure_local);
    gtk_widget_hide((GtkWidget *)g_image_secure_device);
    g_snprintf(version, sizeof(version), VTOY_VER_FMT, ventoy_get_local_version());
    gtk_label_set_markup(g_label_local_ver, version);
    init_part_style_menu();
    gtk_check_menu_item_set_active(g_menu_item_show_all, ventoy_code_get_cur_show_all());
    load_languages();
    SIGNAL("combobox_devlist", "changed", on_devlist_changed);
    
    SIGNAL("button_refresh", "clicked", on_button_refresh_clicked);
    SIGNAL("button_install", "clicked", on_button_install_clicked);
    SIGNAL("button_update",  "clicked", on_button_update_clicked);
    
    SIGNAL("menu_item_secure",   "toggled",  on_secure_boot_toggled);
    SIGNAL("menu_item_mbr",      "toggled",  on_part_style_toggled);
    SIGNAL("menu_item_show_all", "toggled",  on_show_all_toggled);
    
    SIGNAL("menu_item_part_cfg", "activate",  on_part_config);
    SIGNAL("menu_item_clear", "activate",  on_clear_ventoy);
    agMain = gtk_accel_group_new();
    gtk_window_add_accel_group(GTK_WINDOW(g_topWindow), agMain);
    add_accelerator(agMain, g_dev_combobox,   "popup",   GDK_KEY_d);
    add_accelerator(agMain, g_install_button, "clicked", GDK_KEY_i);
    add_accelerator(agMain, g_update_button,  "clicked", GDK_KEY_u);
    add_accelerator(agMain, g_refresh_button, "clicked", GDK_KEY_r);
    gtk_check_menu_item_set_active(g_menu_item_secure_boot, 1 - g_secure_boot_support);
    fill_dev_list(NULL);
    return;
}
int on_exit_window(GtkWidget *widget, gpointer data) 
{
    vlog("on_exit_window ...\n");
    if (g_thread_run || ventoy_code_is_busy())
    {
        msgbox(GTK_MESSAGE_INFO, GTK_BUTTONS_OK, "STR_WAIT_PROCESS");
        return TRUE;
    }
    ventoy_code_save_cfg();
    return FALSE;
}
 | 32,525 | 
	C | 
	.c | 936 | 28.300214 | 132 | 0.619985 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 729 | 
	secure_icon_data.c | 
	ventoy_Ventoy/LinuxGUI/Ventoy2Disk/GTK/secure_icon_data.c | 
	/******************************************************************************
 * secure_icon_data.c
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
static unsigned char secure_icon_hexData[958] = {
    0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x0D, 0x10, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0xA8, 0x03,
    0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x0D, 0x00, 0x00, 0x00, 0x20, 0x00,
    0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x03, 0x00, 0x00, 0x46, 0x5C,
    0x00, 0x00, 0x46, 0x5C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8C,
    0xFB, 0x01, 0x00, 0x8C, 0xFB, 0x2E, 0x00, 0x8C, 0xFB, 0x52, 0x00, 0x8C, 0xFB, 0x53, 0x00, 0x8C,
    0xFB, 0x53, 0x00, 0x8C, 0xFB, 0x53, 0x00, 0x8C, 0xFB, 0x53, 0x00, 0x8C, 0xFB, 0x53, 0x00, 0x8C,
    0xFB, 0x53, 0x00, 0x8C, 0xFB, 0x53, 0x00, 0x8C, 0xFB, 0x52, 0x00, 0x8C, 0xFB, 0x2E, 0x00, 0x8C,
    0xFB, 0x01, 0x00, 0x8C, 0xFB, 0x3E, 0x00, 0x8C, 0xFB, 0xDA, 0x00, 0x8C, 0xFB, 0xF8, 0x00, 0x8C,
    0xFB, 0xF7, 0x00, 0x8C, 0xFB, 0xF7, 0x00, 0x8C, 0xFB, 0xF7, 0x00, 0x8C, 0xFB, 0xF7, 0x00, 0x8C,
    0xFB, 0xF7, 0x00, 0x8C, 0xFB, 0xF7, 0x00, 0x8C, 0xFB, 0xF7, 0x00, 0x8C, 0xFB, 0xF8, 0x00, 0x8C,
    0xFB, 0xDA, 0x00, 0x8C, 0xFB, 0x3E, 0x00, 0x8C, 0xFB, 0x78, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0x78, 0x00, 0x8C, 0xFB, 0x7B, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0x7B, 0x00, 0x8C,
    0xFB, 0x7A, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x86, 0xF1, 0xFF, 0x00, 0x7C, 0xDF, 0xFF, 0x00, 0x86, 0xF1, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0x7A, 0x00, 0x8C, 0xFB, 0x7A, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFC, 0xFF, 0x00, 0x7C, 0xDF, 0xFF, 0x00, 0x6C, 0xC4, 0xFF, 0x00, 0x7C,
    0xDF, 0xFF, 0x00, 0x8C, 0xFC, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0x7A, 0x00, 0x8C, 0xFB, 0x7A, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x87, 0xF2, 0xFF, 0x00, 0x7D,
    0xE1, 0xFF, 0x00, 0x87, 0xF2, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0x7A, 0x00, 0x8C, 0xFB, 0x7B, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFC, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0x7B, 0x00, 0x8C,
    0xFB, 0x77, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C, 0xFB, 0xFF, 0x00, 0x8C,
    0xFB, 0x77, 0x00, 0x8C, 0xFB, 0x3A, 0x00, 0x8C, 0xFB, 0xD4, 0x01, 0x8B, 0xF9, 0xF7, 0x03, 0x89,
    0xF3, 0xFF, 0x01, 0x8B, 0xF8, 0xF8, 0x00, 0x8C, 0xFB, 0xF4, 0x00, 0x8C, 0xFB, 0xF4, 0x00, 0x8C,
    0xFB, 0xF4, 0x01, 0x8B, 0xF8, 0xF8, 0x03, 0x89, 0xF3, 0xFF, 0x01, 0x8B, 0xF9, 0xF7, 0x00, 0x8C,
    0xFB, 0xD4, 0x00, 0x8C, 0xFB, 0x3A, 0x00, 0x8C, 0xFB, 0x00, 0x00, 0x93, 0xFF, 0x1E, 0x1D, 0x6B,
    0xA9, 0x6B, 0x32, 0x54, 0x6F, 0xF6, 0x22, 0x65, 0x9A, 0x7D, 0x00, 0x90, 0xFF, 0x39, 0x00, 0x8C,
    0xFB, 0x3C, 0x00, 0x90, 0xFF, 0x39, 0x22, 0x65, 0x9A, 0x7D, 0x32, 0x54, 0x6F, 0xF6, 0x1D, 0x6B,
    0xA9, 0x6B, 0x00, 0x93, 0xFF, 0x1E, 0x00, 0x8C, 0xFB, 0x00, 0x00, 0x8C, 0xFB, 0x00, 0x2A, 0x5D,
    0x85, 0x00, 0x46, 0x3D, 0x36, 0x3A, 0x43, 0x41, 0x3F, 0xF3, 0x45, 0x3F, 0x3A, 0x58, 0x26, 0x62,
    0x91, 0x00, 0x00, 0x8D, 0xFD, 0x00, 0x26, 0x62, 0x91, 0x00, 0x45, 0x3F, 0x3A, 0x58, 0x43, 0x41,
    0x3F, 0xF3, 0x46, 0x3D, 0x36, 0x3A, 0x2A, 0x5D, 0x85, 0x00, 0x00, 0x8C, 0xFB, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x42, 0x42, 0x42, 0x00, 0x42, 0x42, 0x42, 0x27, 0x42, 0x42, 0x42, 0xE9, 0x42, 0x42,
    0x42, 0x94, 0x42, 0x42, 0x42, 0x01, 0x42, 0x42, 0x42, 0x00, 0x42, 0x42, 0x42, 0x01, 0x42, 0x42,
    0x42, 0x94, 0x42, 0x42, 0x42, 0xE9, 0x42, 0x42, 0x42, 0x27, 0x42, 0x42, 0x42, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x42, 0x42, 0x00, 0x42, 0x42, 0x42, 0x04, 0x42, 0x42,
    0x42, 0x96, 0x42, 0x42, 0x42, 0xF5, 0x42, 0x42, 0x42, 0x8E, 0x42, 0x42, 0x42, 0x53, 0x42, 0x42,
    0x42, 0x8E, 0x42, 0x42, 0x42, 0xF5, 0x42, 0x42, 0x42, 0x96, 0x42, 0x42, 0x42, 0x04, 0x42, 0x42,
    0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x42, 0x42, 0x00, 0x42, 0x42,
    0x42, 0x00, 0x42, 0x42, 0x42, 0x16, 0x42, 0x42, 0x42, 0x96, 0x42, 0x42, 0x42, 0xE9, 0x42, 0x42,
    0x42, 0xF3, 0x42, 0x42, 0x42, 0xE9, 0x42, 0x42, 0x42, 0x96, 0x42, 0x42, 0x42, 0x16, 0x42, 0x42,
    0x42, 0x00, 0x42, 0x42, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x42, 0x42,
    0x42, 0x00, 0x42, 0x42, 0x42, 0x00, 0x42, 0x42, 0x42, 0x00, 0x42, 0x42, 0x42, 0x05, 0x42, 0x42,
    0x42, 0x31, 0x42, 0x42, 0x42, 0x4B, 0x42, 0x42, 0x42, 0x31, 0x42, 0x42, 0x42, 0x05, 0x42, 0x42,
    0x42, 0x00, 0x42, 0x42, 0x42, 0x00, 0x42, 0x42, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x08,
    0x00, 0x00, 0x80, 0x08, 0x00, 0x00, 0x80, 0x08, 0x00, 0x00, 0x80, 0x08, 0x00, 0x00 
};
void *get_secure_icon_raw_data(int *len)
{
    *len = (int)sizeof(secure_icon_hexData);
    return secure_icon_hexData;
}
 | 7,110 | 
	C | 
	.c | 88 | 75.670455 | 100 | 0.643814 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 731 | 
	refresh_icon_data.c | 
	ventoy_Ventoy/LinuxGUI/Ventoy2Disk/GTK/refresh_icon_data.c | 
	/******************************************************************************
 * refresh_icon_data.c
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
static unsigned char refresh_icon_hexData[4286] = {
    0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x20, 0x20, 0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0xA8, 0x10,
    0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x40, 0x00,
    0x00, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x10, 0x27,
    0x00, 0x00, 0x10, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x0C, 0xA6, 0xBE,
    0x32, 0x2D, 0xA6, 0xBE, 0x32, 0x54, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0x81, 0xA6, 0xBE,
    0x32, 0x81, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0x54, 0xA6, 0xBE, 0x32, 0x2D, 0xA6, 0xBE,
    0x32, 0x0C, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x21, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0xBF, 0xA6, 0xBE,
    0x32, 0xEB, 0xA6, 0xBE, 0x32, 0xFC, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFC, 0xA6, 0xBE, 0x32, 0xEB, 0xA6, 0xBE,
    0x32, 0xBF, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0x21, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x10, 0xA6, 0xBE,
    0x32, 0x71, 0xA6, 0xBE, 0x32, 0xD9, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xDA, 0xA6, 0xBE, 0x32, 0x71, 0xA6, 0xBE,
    0x32, 0x10, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x29, 0xA6, 0xBE, 0x32, 0xB2, 0xA6, 0xBE,
    0x32, 0xFE, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA5, 0xBD,
    0x2F, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA5, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFE, 0xA6, 0xBE,
    0x32, 0xB2, 0xA6, 0xBE, 0x32, 0x29, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x35, 0xA6, 0xBE, 0x32, 0xCF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xA5, 0xBE,
    0x31, 0xFF, 0xAC, 0xC3, 0x40, 0xFF, 0xB7, 0xCA, 0x59, 0xFF, 0xBF, 0xD0, 0x6B, 0xFF, 0xC0, 0xD1,
    0x6E, 0xFF, 0xBA, 0xCD, 0x60, 0xFF, 0xAF, 0xC5, 0x48, 0xFF, 0xA7, 0xBF, 0x34, 0xFF, 0xA5, 0xBD,
    0x2F, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xCF, 0xA6, 0xBE, 0x32, 0x35, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x29, 0xA6, 0xBE, 0x32, 0xCF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xB5, 0xC9, 0x54, 0xFF, 0xD4, 0xE0,
    0x9D, 0xFF, 0xED, 0xF2, 0xD6, 0xFF, 0xF9, 0xFB, 0xF1, 0xFF, 0xFD, 0xFD, 0xFA, 0xFF, 0xFD, 0xFE,
    0xFB, 0xFF, 0xFB, 0xFC, 0xF5, 0xFF, 0xF2, 0xF6, 0xE1, 0xFF, 0xDD, 0xE6, 0xB1, 0xFF, 0xBD, 0xCF,
    0x67, 0xFF, 0xA7, 0xBF, 0x35, 0xFF, 0xA5, 0xBE, 0x30, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xCF, 0xA6, 0xBE, 0x32, 0x29, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x10, 0xA6, 0xBE,
    0x32, 0xB2, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x31, 0xFF, 0xA8, 0xC0, 0x37, 0xFF, 0xCB, 0xD9, 0x87, 0xFF, 0xF4, 0xF7, 0xE6, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFA, 0xFB,
    0xF4, 0xFF, 0xD9, 0xE4, 0xA8, 0xFF, 0xAF, 0xC4, 0x46, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xB2, 0xA6, 0xBE,
    0x32, 0x10, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x71, 0xA6, 0xBE,
    0x32, 0xFE, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA9, 0xC0,
    0x38, 0xFF, 0xD5, 0xE0, 0x9D, 0xFF, 0xFD, 0xFE, 0xFA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFE,
    0xFD, 0xFF, 0xEE, 0xF3, 0xD9, 0xFF, 0xD9, 0xE3, 0xA8, 0xFF, 0xCC, 0xDA, 0x8A, 0xFF, 0xCA, 0xD8,
    0x85, 0xFF, 0xD3, 0xDF, 0x99, 0xFF, 0xE6, 0xEC, 0xC4, 0xFF, 0xFA, 0xFB, 0xF3, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE7, 0xED, 0xC7, 0xFF, 0xB1, 0xC6, 0x4C, 0xFF, 0xA5, 0xBD,
    0x30, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFE, 0xA6, 0xBE,
    0x32, 0x71, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x21, 0xA6, 0xBE, 0x32, 0xDA, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xCD, 0xDB,
    0x8C, 0xFF, 0xFD, 0xFE, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF4, 0xF7, 0xE7, 0xFF, 0xCB, 0xD9,
    0x87, 0xFF, 0xAE, 0xC3, 0x43, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA4, 0xBD, 0x2F, 0xFF, 0xA4, 0xBD,
    0x2E, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA9, 0xC0, 0x38, 0xFF, 0xBD, 0xCF, 0x66, 0xFF, 0xE8, 0xEE,
    0xC9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE4, 0xEB, 0xC1, 0xFF, 0xAD, 0xC3,
    0x41, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xDA, 0xA6, 0xBE, 0x32, 0x21, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBD,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA4, 0xBC, 0x2D, 0xFF, 0xB8, 0xCB, 0x5C, 0xFF, 0xF6, 0xF9,
    0xEB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF1, 0xF5, 0xDF, 0xFF, 0xBA, 0xCD, 0x60, 0xFF, 0xA4, 0xBD,
    0x2E, 0xFF, 0xA5, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xAE, 0xC4,
    0x44, 0xFF, 0xE2, 0xE9, 0xBB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC7, 0xD6,
    0x7E, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x0C, 0xA6, 0xBE, 0x32, 0xC0, 0xA6, 0xBE, 0x32, 0xFF, 0xA9, 0xC0,
    0x39, 0xFF, 0xC8, 0xD7, 0x80, 0xFF, 0xD0, 0xDC, 0x92, 0xFF, 0xE7, 0xEE, 0xC8, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE6, 0xED, 0xC5, 0xFF, 0xCC, 0xDA, 0x8A, 0xFF, 0xB0, 0xC5,
    0x49, 0xFF, 0xA5, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD,
    0x30, 0xFF, 0xB0, 0xC6, 0x4A, 0xFF, 0xE3, 0xEA, 0xBE, 0xFF, 0xEA, 0xEF, 0xCE, 0xFF, 0xB8, 0xCB,
    0x5C, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xBF, 0xA6, 0xBE, 0x32, 0x0C, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x2E, 0xA6, 0xBE, 0x32, 0xEB, 0xA6, 0xBE, 0x32, 0xFF, 0xA8, 0xC0,
    0x37, 0xFF, 0xE0, 0xE8, 0xB8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF3, 0xF6, 0xE3, 0xFF, 0xB3, 0xC7,
    0x4F, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xAA, 0xC1, 0x3A, 0xFF, 0xAB, 0xC1, 0x3D, 0xFF, 0xA6, 0xBE,
    0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xEB, 0xA6, 0xBE, 0x32, 0x2D, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x54, 0xA6, 0xBE, 0x32, 0xFC, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD,
    0x30, 0xFF, 0xB6, 0xCA, 0x58, 0xFF, 0xF4, 0xF7, 0xE6, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFD, 0xFE, 0xFB, 0xFF, 0xC9, 0xD8, 0x84, 0xFF, 0xA5, 0xBD,
    0x30, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBE, 0x31, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFC, 0xA6, 0xBE, 0x32, 0x54, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA5, 0xBE, 0x30, 0xFF, 0xCD, 0xDB, 0x8C, 0xFF, 0xFE, 0xFE, 0xFD, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE2, 0xEA, 0xBC, 0xFF, 0xAA, 0xC1, 0x3A, 0xFF, 0xA6, 0xBE,
    0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xAB, 0xC2, 0x3E, 0xFF, 0xBB, 0xCE, 0x63, 0xFF, 0xA7, 0xBF,
    0x35, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x81, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xAB, 0xC2, 0x3E, 0xFF, 0xE6, 0xED, 0xC5, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xF5, 0xF8, 0xE8, 0xFF, 0xB7, 0xCB, 0x5A, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA5, 0xBE, 0x31, 0xFF, 0xCE, 0xDB, 0x8F, 0xFF, 0xF7, 0xF9, 0xEC, 0xFF, 0xBD, 0xCF,
    0x67, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0x81, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x81, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xBB, 0xCD, 0x63, 0xFF, 0xF6, 0xF8,
    0xEA, 0xFF, 0xCE, 0xDB, 0x8F, 0xFF, 0xA5, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD,
    0x30, 0xFF, 0xB7, 0xCB, 0x5A, 0xFF, 0xF5, 0xF8, 0xE8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE8, 0xEE,
    0xC9, 0xFF, 0xAC, 0xC2, 0x40, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0x81, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA7, 0xBF, 0x34, 0xFF, 0xBA, 0xCD,
    0x60, 0xFF, 0xAB, 0xC2, 0x3E, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xAA, 0xC1,
    0x3A, 0xFF, 0xE2, 0xEA, 0xBC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFE, 0xFF, 0xCF, 0xDC, 0x90, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x54, 0xA6, 0xBE, 0x32, 0xFC, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD,
    0x2F, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xC9, 0xD8,
    0x84, 0xFF, 0xFD, 0xFE, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xF5, 0xF8, 0xE9, 0xFF, 0xB8, 0xCB, 0x5B, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFC, 0xA6, 0xBE, 0x32, 0x54, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x2E, 0xA6, 0xBE, 0x32, 0xEB, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA9, 0xC0,
    0x38, 0xFF, 0xA8, 0xBF, 0x37, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xB2, 0xC7, 0x4F, 0xFF, 0xF2, 0xF6,
    0xE2, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE2, 0xE9, 0xBB, 0xFF, 0xA9, 0xC0, 0x38, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xEB, 0xA6, 0xBE, 0x32, 0x2D, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x0C, 0xA6, 0xBE, 0x32, 0xC0, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xB5, 0xC9, 0x54, 0xFF, 0xE4, 0xEB,
    0xC1, 0xFF, 0xDF, 0xE8, 0xB5, 0xFF, 0xAF, 0xC5, 0x47, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBE, 0x31, 0xFF, 0xAF, 0xC5, 0x47, 0xFF, 0xCA, 0xD8,
    0x85, 0xFF, 0xE2, 0xE9, 0xBB, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE9, 0xEF,
    0xCD, 0xFF, 0xCE, 0xDB, 0x8F, 0xFF, 0xC7, 0xD6, 0x7E, 0xFF, 0xA9, 0xC0, 0x39, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xBF, 0xA6, 0xBE, 0x32, 0x0C, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBD,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x73, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xC6, 0xD6, 0x7C, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDF, 0xE8, 0xB5, 0xFF, 0xAC, 0xC3, 0x40, 0xFF, 0xA5, 0xBD,
    0x2F, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA4, 0xBD, 0x2E, 0xFF, 0xB5, 0xC9,
    0x55, 0xFF, 0xED, 0xF2, 0xD6, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF9, 0xFB, 0xF1, 0xFF, 0xBC, 0xCE,
    0x65, 0xFF, 0xA4, 0xBC, 0x2C, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x21, 0xA6, 0xBE, 0x32, 0xDA, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xAE, 0xC4, 0x44, 0xFF, 0xE6, 0xED,
    0xC6, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xE4, 0xEB, 0xC1, 0xFF, 0xB9, 0xCC,
    0x5E, 0xFF, 0xA7, 0xBF, 0x35, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA4, 0xBD, 0x2E, 0xFF, 0xA4, 0xBD,
    0x2E, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xAB, 0xC1, 0x3D, 0xFF, 0xC5, 0xD5, 0x79, 0xFF, 0xF1, 0xF5,
    0xDE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xD3, 0xDF, 0x99, 0xFF, 0xA7, 0xBE,
    0x33, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xDA, 0xA6, 0xBE, 0x32, 0x21, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00,
    0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE,
    0x32, 0xFE, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xB3, 0xC8,
    0x51, 0xFF, 0xE9, 0xEF, 0xCD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF8, 0xFA,
    0xEE, 0xFF, 0xE1, 0xE9, 0xBA, 0xFF, 0xCD, 0xDB, 0x8C, 0xFF, 0xC4, 0xD4, 0x78, 0xFF, 0xC6, 0xD6,
    0x7C, 0xFF, 0xD3, 0xDF, 0x9A, 0xFF, 0xE9, 0xEF, 0xCD, 0xFF, 0xFC, 0xFD, 0xF9, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xDB, 0xE4, 0xAB, 0xFF, 0xAA, 0xC1, 0x3C, 0xFF, 0xA6, 0xBE,
    0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFE, 0xA6, 0xBE,
    0x32, 0x71, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x10, 0xA6, 0xBE,
    0x32, 0xB3, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA5, 0xBD,
    0x30, 0xFF, 0xB1, 0xC6, 0x4B, 0xFF, 0xDD, 0xE6, 0xB2, 0xFF, 0xFC, 0xFD, 0xF8, 0xFF, 0xFF, 0xFF,
    0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF,
    0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xF8, 0xFA,
    0xEE, 0xFF, 0xD1, 0xDE, 0x96, 0xFF, 0xAA, 0xC1, 0x3C, 0xFF, 0xA5, 0xBE, 0x31, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xB2, 0xA6, 0xBE,
    0x32, 0x10, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x29, 0xA6, 0xBE, 0x32, 0xCF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xA9, 0xC0, 0x38, 0xFF, 0xC1, 0xD2, 0x71, 0xFF, 0xE2, 0xEA,
    0xBC, 0xFF, 0xF5, 0xF8, 0xE9, 0xFF, 0xFD, 0xFD, 0xFA, 0xFF, 0xFF, 0xFF, 0xFE, 0xFF, 0xFE, 0xFF,
    0xFE, 0xFF, 0xFB, 0xFC, 0xF7, 0xFF, 0xF2, 0xF5, 0xE1, 0xFF, 0xDB, 0xE5, 0xAC, 0xFF, 0xB9, 0xCC,
    0x5F, 0xFF, 0xA6, 0xBE, 0x33, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xCF, 0xA6, 0xBE, 0x32, 0x29, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x35, 0xA6, 0xBE, 0x32, 0xCF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x31, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA8, 0xBF,
    0x36, 0xFF, 0xB3, 0xC7, 0x4F, 0xFF, 0xBF, 0xD0, 0x6B, 0xFF, 0xC5, 0xD5, 0x7A, 0xFF, 0xC4, 0xD4,
    0x78, 0xFF, 0xBC, 0xCE, 0x64, 0xFF, 0xB0, 0xC5, 0x48, 0xFF, 0xA6, 0xBE, 0x33, 0xFF, 0xA5, 0xBD,
    0x30, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xCF, 0xA6, 0xBE, 0x32, 0x35, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x29, 0xA6, 0xBE, 0x32, 0xB2, 0xA6, 0xBE,
    0x32, 0xFE, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA5, 0xBD, 0x30, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA4, 0xBD, 0x2E, 0xFF, 0xA4, 0xBD,
    0x2E, 0xFF, 0xA5, 0xBD, 0x2F, 0xFF, 0xA5, 0xBE, 0x31, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFE, 0xA6, 0xBE,
    0x32, 0xB3, 0xA6, 0xBE, 0x32, 0x29, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x10, 0xA6, 0xBE,
    0x32, 0x71, 0xA6, 0xBE, 0x32, 0xDA, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xDA, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE,
    0x32, 0x10, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x21, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0xBF, 0xA6, 0xBE,
    0x32, 0xEB, 0xA6, 0xBE, 0x32, 0xFC, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE,
    0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFF, 0xA6, 0xBE, 0x32, 0xFC, 0xA6, 0xBE, 0x32, 0xEB, 0xA6, 0xBE,
    0x32, 0xC0, 0xA6, 0xBE, 0x32, 0x73, 0xA6, 0xBE, 0x32, 0x21, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x0C, 0xA6, 0xBE,
    0x32, 0x2D, 0xA6, 0xBE, 0x32, 0x54, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0x81, 0xA6, 0xBE,
    0x32, 0x81, 0xA6, 0xBE, 0x32, 0x72, 0xA6, 0xBE, 0x32, 0x54, 0xA6, 0xBE, 0x32, 0x2E, 0xA6, 0xBE,
    0x32, 0x0C, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBD, 0x31, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE,
    0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0xA6, 0xBE, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x80,
    0x01, 0xFF, 0xFE, 0x00, 0x00, 0x7F, 0xF8, 0x00, 0x00, 0x1F, 0xF0, 0x00, 0x00, 0x0F, 0xE0, 0x00,
    0x00, 0x07, 0xC0, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x03, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00,
    0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00,
    0x00, 0x01, 0xC0, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x03, 0xE0, 0x00, 0x00, 0x07, 0xF0, 0x00,
    0x00, 0x0F, 0xF8, 0x00, 0x00, 0x1F, 0xFE, 0x00, 0x00, 0x7F, 0xFF, 0x80, 0x01, 0xFF 
};
void *get_refresh_icon_raw_data(int *len)
{
    *len = (int)sizeof(refresh_icon_hexData);
    return refresh_icon_hexData;
}
 | 28,126 | 
	C | 
	.c | 296 | 89.273649 | 100 | 0.641039 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 732 | 
	ventoy_http.c | 
	ventoy_Ventoy/LinuxGUI/Ventoy2Disk/Web/ventoy_http.c | 
	/******************************************************************************
 * ventoy_http.c  ---- ventoy http
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mount.h>
#include <linux/fs.h>
#include <linux/limits.h>
#include <dirent.h>
#include <pthread.h>
#include <ventoy_define.h>
#include <ventoy_json.h>
#include <ventoy_util.h>
#include <ventoy_disk.h>
#include <ventoy_http.h>
#include "fat_filelib.h"
static char *g_pub_out_buf = NULL;
static int g_pub_out_max = 0;
static pthread_mutex_t g_api_mutex;
static char g_cur_language[128];
static int  g_cur_part_style = 0;
static int  g_cur_show_all = 0;
static char g_cur_server_token[64];
static struct mg_context *g_ventoy_http_ctx = NULL;
static uint32_t g_efi_part_offset = 0;
static uint8_t *g_efi_part_raw_img = NULL;
static uint8_t *g_grub_stg1_raw_img = NULL;
static char g_cur_process_diskname[64];
static char g_cur_process_type[64];
static volatile int g_cur_process_result = 0;
static volatile PROGRESS_POINT g_current_progress = PT_FINISH;
static int ventoy_load_mbr_template(void)
{
    FILE *fp = NULL;
    fp = fopen("boot/boot.img", "rb");
    if (fp == NULL)
    {
        vlog("Failed to open file boot/boot.img\n");
        return 1;
    }
    fread(g_mbr_template, 1, 512, fp);
    fclose(fp);
    
    ventoy_gen_preudo_uuid(g_mbr_template + 0x180);    
    return 0;
}
static int ventoy_disk_xz_flush(void *src, unsigned int size)
{
    memcpy(g_efi_part_raw_img + g_efi_part_offset, src, size);
    g_efi_part_offset += size;
    g_current_progress = PT_LOAD_DISK_IMG + (g_efi_part_offset / SIZE_1MB);
    return (int)size;
}
static int ventoy_unxz_efipart_img(void)
{
    int rc;
    int inlen;
    int xzlen;
    void *xzbuf = NULL;
    uint8_t *buf = NULL;
    rc = ventoy_read_file_to_buf(VENTOY_FILE_DISK_IMG, 0, &xzbuf, &xzlen);
    vdebug("read disk.img.xz rc:%d len:%d\n", rc, xzlen);
    if (g_efi_part_raw_img)
    {
        buf = g_efi_part_raw_img;
    }
    else
    {
        buf = malloc(VTOYEFI_PART_BYTES);
        if (!buf)
        {
            check_free(xzbuf);
            return 1;
        }
    }
    g_efi_part_offset = 0;
    g_efi_part_raw_img = buf;
    
    rc = unxz(xzbuf, xzlen, NULL, ventoy_disk_xz_flush, buf, &inlen, NULL);
    vdebug("ventoy_unxz_efipart_img len:%d rc:%d unxzlen:%u\n", inlen, rc, g_efi_part_offset);
    check_free(xzbuf);
    return 0;
}
static int ventoy_unxz_stg1_img(void)
{
    int rc;
    int inlen;
    int xzlen;
    void *xzbuf = NULL;
    uint8_t *buf = NULL;
    rc = ventoy_read_file_to_buf(VENTOY_FILE_STG1_IMG, 0, &xzbuf, &xzlen);
    vdebug("read core.img.xz rc:%d len:%d\n", rc, xzlen);
    if (g_grub_stg1_raw_img)
    {
        buf = g_grub_stg1_raw_img;
    }
    else
    {
        buf = zalloc(SIZE_1MB);
        if (!buf)
        {
            check_free(xzbuf);
            return 1;
        }
    }
    
    rc = unxz(xzbuf, xzlen, NULL, NULL, buf, &inlen, NULL);
    vdebug("ventoy_unxz_stg1_img len:%d rc:%d\n", inlen, rc);
    g_grub_stg1_raw_img = buf;
    check_free(xzbuf);
    return 0;
}
static int ventoy_http_save_cfg(void)
{
    FILE *fp;
    fp = fopen(g_ini_file, "w");
    if (!fp)
    {
        vlog("Failed to open %s code:%d\n", g_ini_file, errno);
        return 0;
    }
    fprintf(fp, "[Ventoy]\nLanguage=%s\nPartStyle=%d\nShowAllDevice=%d\n", 
        g_cur_language, g_cur_part_style, g_cur_show_all);
    fclose(fp);
    return 0;
}
static int ventoy_http_load_cfg(void)
{
    int i;
    int len;
    char line[256];
    FILE *fp;
    fp = fopen(g_ini_file, "r");
    if (!fp)
    {
        return 0;
    }
    while (fgets(line, sizeof(line), fp))
    {
        len = (int)strlen(line);
        for (i = len - 1; i >= 0; i--)
        {
            if (line[i] == ' ' || line[i] == '\t' || line[i] == '\r' || line[i] == '\n')
            {
                line[i] = 0;
            }
            else
            {
                break;
            }
        }
    
        len = (int)strlen("Language=");
        if (strncmp(line, "Language=", len) == 0)
        {
            scnprintf(g_cur_language, "%s", line + len);
        }
        else if (strncmp(line, "PartStyle=", strlen("PartStyle=")) == 0)
        {
            g_cur_part_style = (int)strtol(line + strlen("PartStyle="), NULL, 10);
        }
        else if (strncmp(line, "ShowAllDevice=", strlen("ShowAllDevice=")) == 0)
        {
            g_cur_show_all = (int)strtol(line + strlen("ShowAllDevice="), NULL, 10);
        }
    }
    fclose(fp);
    return 0;
}
static int ventoy_json_result(struct mg_connection *conn, const char *err)
{
    if (conn)
    {
        mg_printf(conn, 
                  "HTTP/1.1 200 OK \r\n"
                  "Content-Type: application/json\r\n"
                  "Content-Length: %d\r\n"
                  "\r\n%s",
                  (int)strlen(err), err);
    }
    else
    {
        memcpy(g_pub_out_buf, err, (int)strlen(err) + 1);
    }
    return 0;
}
static int ventoy_json_buffer(struct mg_connection *conn, const char *json_buf, int json_len)
{
    if (conn)
    {
        mg_printf(conn, 
                  "HTTP/1.1 200 OK \r\n"
                  "Content-Type: application/json\r\n"
                  "Content-Length: %d\r\n"
                  "\r\n%s",
                  json_len, json_buf);    
    }
    else
    {
        if (json_len >= g_pub_out_max)
        {
            vlog("json buffer overflow\n");
        }
        else
        {
            memcpy(g_pub_out_buf, json_buf, json_len);
            g_pub_out_buf[json_len] = 0;
        }
    }
    return 0;
}
static int ventoy_api_sysinfo(struct mg_connection *conn, VTOY_JSON *json)
{
    int busy = 0;
    int pos = 0;
    int buflen = 0;
    char buf[512];
    
    (void)json;
    busy = (g_current_progress == PT_FINISH) ? 0 : 1;
    buflen = sizeof(buf) - 1;
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_STRN("token", g_cur_server_token);
    VTOY_JSON_FMT_STRN("language", g_cur_language);
    VTOY_JSON_FMT_STRN("ventoy_ver", ventoy_get_local_version());
    VTOY_JSON_FMT_UINT("partstyle", g_cur_part_style);
    VTOY_JSON_FMT_BOOL("busy", busy);
    VTOY_JSON_FMT_STRN("process_disk", g_cur_process_diskname);
    VTOY_JSON_FMT_STRN("process_type", g_cur_process_type);
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    ventoy_json_buffer(conn, buf, pos);
    return 0;
}
static int ventoy_api_get_percent(struct mg_connection *conn, VTOY_JSON *json)
{
    int pos = 0;
    int buflen = 0;
    int percent = 0;
    char buf[128];
    
    (void)json;
    percent = g_current_progress * 100 / PT_FINISH;
    buflen = sizeof(buf) - 1;
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_STRN("result", g_cur_process_result ? "failed" : "success");
    VTOY_JSON_FMT_STRN("process_disk", g_cur_process_diskname);
    VTOY_JSON_FMT_STRN("process_type", g_cur_process_type);
    VTOY_JSON_FMT_UINT("percent", percent);
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    ventoy_json_buffer(conn, buf, pos);
    return 0;
}
static int ventoy_api_set_language(struct mg_connection *conn, VTOY_JSON *json)
{
    const char *lang = NULL;
    
    lang = vtoy_json_get_string_ex(json, "language");
    if (lang)
    {
        scnprintf(g_cur_language, "%s", lang);
        ventoy_http_save_cfg();
    }
    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;    
}
static int ventoy_api_set_partstyle(struct mg_connection *conn, VTOY_JSON *json)
{
    int ret;
    int style = 0;
    
    ret = vtoy_json_get_int(json, "partstyle", &style);
    if (JSON_SUCCESS == ret)
    {
        if ((style == 0) || (style == 1))
        {
            g_cur_part_style = style;
            ventoy_http_save_cfg();            
        }
    }
    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;    
}
static int ventoy_clean_disk(int fd, uint64_t size)
{
    int zerolen;
    ssize_t len;
    off_t offset;
    void *buf = NULL;
    
    vdebug("ventoy_clean_disk fd:%d size:%llu\n", fd, (_ull)size);
    zerolen = 64 * 1024;
    buf = zalloc(zerolen);
    if (!buf)
    {
        vlog("failed to alloc clean buffer\n");
        return 1;
    }
    offset = lseek(fd, 0, SEEK_SET);
    len = write(fd, buf, zerolen);
    vdebug("write disk at off:%llu writelen:%lld datalen:%d\n", (_ull)offset, (_ll)len, zerolen);
    offset = lseek(fd, size - zerolen, SEEK_SET);
    len = write(fd, buf, zerolen);
    vdebug("write disk at off:%llu writelen:%lld datalen:%d\n", (_ull)offset, (_ll)len, zerolen);
    fsync(fd);
    free(buf);
    return 0;
}
static int ventoy_write_legacy_grub(int fd, int partstyle)
{
    ssize_t len;
    off_t offset;
    
    if (partstyle)
    {
        vlog("Write GPT stage1 ...\n");
        offset = lseek(fd, 512 * 34, SEEK_SET);
        g_grub_stg1_raw_img[500] = 35;//update blocklist
        len = write(fd, g_grub_stg1_raw_img, SIZE_1MB - 512 * 34);
        vlog("lseek offset:%llu(%u) writelen:%llu(%u)\n", (_ull)offset, 512 * 34, (_ull)len, SIZE_1MB - 512 * 34);
        if (SIZE_1MB - 512 * 34 != len)
        {
            vlog("write length error\n");
            return 1;
        }
    }
    else
    {
        vlog("Write MBR stage1 ...\n");
        offset = lseek(fd, 512, SEEK_SET);
        len = write(fd, g_grub_stg1_raw_img, SIZE_1MB - 512);
        
        vlog("lseek offset:%llu(%u) writelen:%llu(%u)\n", (_ull)offset, 512, (_ull)len, SIZE_1MB - 512);
        if (SIZE_1MB - 512 != len)
        {
            vlog("write length error\n");
            return 1;
        }
    }
    return 0;
}
static int VentoyFatMemRead(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
{
	uint32 i;
	uint32 offset;
	for (i = 0; i < SectorCount; i++)
	{
		offset = (Sector + i) * 512;
        memcpy(Buffer + i * 512, g_efi_part_raw_img + offset, 512);
	}
	return 1;
}
static int VentoyFatMemWrite(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
{
	uint32 i;
	uint32 offset;
	for (i = 0; i < SectorCount; i++)
	{
		offset = (Sector + i) * 512;
        memcpy(g_efi_part_raw_img + offset, Buffer + i * 512, 512);
	}
	return 1;
}
static int VentoyProcSecureBoot(int SecureBoot)
{
	int rc = 0;
	int size;
	char *filebuf = NULL;
	void *file = NULL;
	vlog("VentoyProcSecureBoot %d ...\n", SecureBoot);
	
	if (SecureBoot)
	{
		vlog("Secure boot is enabled ...\n");
		return 0;
	}
	fl_init();
	if (0 == fl_attach_media(VentoyFatMemRead, VentoyFatMemWrite))
	{
		file = fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
		vlog("Open ventoy efi file %p \n", file);
		if (file)
		{
			fl_fseek(file, 0, SEEK_END);
			size = (int)fl_ftell(file);
			fl_fseek(file, 0, SEEK_SET);
			vlog("ventoy efi file size %d ...\n", size);
			filebuf = (char *)malloc(size);
			if (filebuf)
			{
				fl_fread(filebuf, 1, size, file);
			}
			fl_fclose(file);
			vlog("Now delete all efi files ...\n");
			fl_remove("/EFI/BOOT/BOOTX64.EFI");
			fl_remove("/EFI/BOOT/grubx64.efi");
			fl_remove("/EFI/BOOT/grubx64_real.efi");
			fl_remove("/EFI/BOOT/MokManager.efi");
			fl_remove("/EFI/BOOT/mmx64.efi");
            fl_remove("/ENROLL_THIS_KEY_IN_MOKMANAGER.cer");
			file = fl_fopen("/EFI/BOOT/BOOTX64.EFI", "wb");
			vlog("Open bootx64 efi file %p \n", file);
			if (file)
			{
				if (filebuf)
				{
					fl_fwrite(filebuf, 1, size, file);
				}
				
				fl_fflush(file);
				fl_fclose(file);
			}
			if (filebuf)
			{
				free(filebuf);
			}
		}
        file = fl_fopen("/EFI/BOOT/grubia32_real.efi", "rb");
        vlog("Open ventoy efi file %p\n", file);
        if (file)
        {
            fl_fseek(file, 0, SEEK_END);
            size = (int)fl_ftell(file);
            fl_fseek(file, 0, SEEK_SET);
            vlog("ventoy efi file size %d ...\n", size);
            filebuf = (char *)malloc(size);
            if (filebuf)
            {
                fl_fread(filebuf, 1, size, file);
            }
            fl_fclose(file);
            vlog("Now delete all efi files ...\n");
            fl_remove("/EFI/BOOT/BOOTIA32.EFI");
            fl_remove("/EFI/BOOT/grubia32.efi");
            fl_remove("/EFI/BOOT/grubia32_real.efi");
            fl_remove("/EFI/BOOT/mmia32.efi");            
            file = fl_fopen("/EFI/BOOT/BOOTIA32.EFI", "wb");
            vlog("Open bootia32 efi file %p\n", file);
            if (file)
            {
                if (filebuf)
                {
                    fl_fwrite(filebuf, 1, size, file);
                }
                fl_fflush(file);
                fl_fclose(file);
            }
            if (filebuf)
            {
                free(filebuf);
            }
        }
	}
	else
	{
		rc = 1;
	}
	fl_shutdown();
	return rc;
}
static int ventoy_check_efi_part_data(int fd, uint64_t offset)
{
    int i;
    ssize_t len;
    char *buf;
    buf = malloc(SIZE_1MB);
    if (!buf)
    {
        return 0;
    }
    
    lseek(fd, offset, SEEK_SET);
    for (i = 0; i < 32; i++)
    {
        len = read(fd, buf, SIZE_1MB);
        if (len != SIZE_1MB || memcmp(buf, g_efi_part_raw_img + i * SIZE_1MB, SIZE_1MB))
        {
            vlog("part2 data check failed i=%d len:%llu\n", i, (_ull)len);
            return 1;
        }
        g_current_progress = PT_CHECK_PART2 + (i / 4);
    }
    return 0;
}
static int ventoy_write_efipart(int fd, uint64_t offset, uint32_t secureboot)
{
    int i;
    ssize_t len;
    
    vlog("Formatting part2 EFI offset:%llu ...\n", (_ull)offset);
    lseek(fd, offset, SEEK_SET);
    VentoyProcSecureBoot((int)secureboot);
    g_current_progress = PT_WRITE_VENTOY_START;
    for (i = 0; i < 32; i++)
    {
        len = write(fd, g_efi_part_raw_img + i * SIZE_1MB, SIZE_1MB);
        vlog("write disk writelen:%lld datalen:%d [ %s ]\n", 
            (_ll)len, SIZE_1MB, (len == SIZE_1MB) ? "success" : "failed");
        
        if (len != SIZE_1MB)
        {
            vlog("failed to format part2 EFI\n");
            return 1;
        }
    
        g_current_progress = PT_WRITE_VENTOY_START + i / 4;
    }
    return 0;
}
static int VentoyFillBackupGptHead(VTOY_GPT_INFO *pInfo, VTOY_GPT_HDR *pHead)
{
    uint64_t LBA;
    uint64_t BackupLBA;
    memcpy(pHead, &pInfo->Head, sizeof(VTOY_GPT_HDR));
    LBA = pHead->EfiStartLBA;
    BackupLBA = pHead->EfiBackupLBA;
    
    pHead->EfiStartLBA = BackupLBA;
    pHead->EfiBackupLBA = LBA;
    pHead->PartTblStartLBA = BackupLBA + 1 - 33;
    pHead->Crc = 0;
    pHead->Crc = ventoy_crc32(pHead, pHead->Length);
    return 0;
}
static int ventoy_write_gpt_part_table(int fd, uint64_t disksize, VTOY_GPT_INFO *gpt)
{
    ssize_t len;
    off_t offset;
    VTOY_GPT_HDR BackupHead;
    
    VentoyFillBackupGptHead(gpt, &BackupHead);
    offset = lseek(fd, disksize - 512, SEEK_SET);
    len = write(fd, &BackupHead, sizeof(VTOY_GPT_HDR));
    vlog("write backup gpt part table off:%llu len:%llu\n", (_ull)offset, (_ull)len);
    if (offset != disksize - 512 || len != sizeof(VTOY_GPT_HDR))
    {
        return 1;
    }
    offset = lseek(fd, disksize - 512 * 33, SEEK_SET);
    len = write(fd, gpt->PartTbl, sizeof(gpt->PartTbl));
    vlog("write main gpt part table off:%llu len:%llu\n", (_ull)offset, (_ull)len);
    if (offset != disksize - 512 * 33 || len != sizeof(gpt->PartTbl))
    {
        return 1;
    }
    
    offset = lseek(fd, 0, SEEK_SET);
    len = write(fd, gpt, sizeof(VTOY_GPT_INFO));
    vlog("write gpt part head off:%llu len:%llu\n", (_ull)offset, (_ull)len);
    if (offset != 0 || len != sizeof(VTOY_GPT_INFO))
    {
        return 1;
    }
    
    return 0;
}
static int ventoy_mbr_need_update(ventoy_disk *disk, MBR_HEAD *mbr)
{
    int update = 0;
    int partition_style;
    MBR_HEAD LocalMBR;
    partition_style = disk->vtoydata.partition_style;
    memcpy(mbr, &(disk->vtoydata.gptinfo.MBR), 512);
    
    VentoyGetLocalBootImg(&LocalMBR);
    memcpy(LocalMBR.BootCode + 0x180, mbr->BootCode + 0x180, 16);
    if (partition_style)
    {
        LocalMBR.BootCode[92] = 0x22;        
    }
    if (memcmp(LocalMBR.BootCode, mbr->BootCode, 440))
    {
        memcpy(mbr->BootCode, LocalMBR.BootCode, 440);
        vlog("MBR boot code different, must update it.\n");
        update = 1;
    }
    if (partition_style == 0 && mbr->PartTbl[0].Active == 0)
    {
        mbr->PartTbl[0].Active = 0x80;
        mbr->PartTbl[1].Active = 0;
        mbr->PartTbl[2].Active = 0;
        mbr->PartTbl[3].Active = 0;
        vlog("set MBR partition 1 active flag enabled\n");
        update = 1;
    }
    return update;
}
static void * ventoy_update_thread(void *data)
{
    int fd;
    ssize_t len;
    off_t offset;
    MBR_HEAD MBR;
    ventoy_disk *disk = NULL;
    ventoy_thread_data *thread = (ventoy_thread_data *)data;
    vdebug("ventoy_update_thread run ...\n");
    fd = thread->diskfd;
    disk = thread->disk;
    g_current_progress = PT_PRAPARE_FOR_CLEAN;
    vdebug("check disk %s\n", disk->disk_name);
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("disk is mounted, now try to unmount it ...\n");
        ventoy_try_umount_disk(disk->disk_path);
    }
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("%s is mounted and can't umount!\n", disk->disk_path);
        goto err;
    }
    else
    {
        vlog("disk is not mounted now, we can do continue ...\n");
    }
    g_current_progress = PT_LOAD_CORE_IMG;
    ventoy_unxz_stg1_img();
    
    g_current_progress = PT_LOAD_DISK_IMG;
    ventoy_unxz_efipart_img();
    g_current_progress = PT_FORMAT_PART2;
    vlog("Formatting part2 EFI ...\n");
    if (0 != ventoy_write_efipart(fd, disk->vtoydata.part2_start_sector * 512, thread->secure_boot))
    {
        vlog("Failed to format part2 efi ...\n");
        goto err;
    }
    g_current_progress = PT_WRITE_STG1_IMG;
    vlog("Writing legacy grub ...\n");
    if (0 != ventoy_write_legacy_grub(fd, disk->vtoydata.partition_style))
    {
        vlog("ventoy_write_legacy_grub failed ...\n");
        goto err;
    }
    offset = lseek(fd, 512 * 2040, SEEK_SET);
    len = write(fd, disk->vtoydata.rsvdata, sizeof(disk->vtoydata.rsvdata));
    vlog("Writing reserve data offset:%llu len:%llu ...\n", (_ull)offset, (_ull)len);
    if (ventoy_mbr_need_update(disk, &MBR))
    {
        offset = lseek(fd, 0, SEEK_SET);
        len = write(fd, &MBR, 512);
        vlog("update MBR offset:%llu len:%llu\n", (_ull)offset, (_ull)len);
    }
    else
    {
        vlog("No need to update MBR\n");
    }
    g_current_progress = PT_SYNC_DATA1;
    vlog("fsync data1...\n");
    fsync(fd);
    vtoy_safe_close_fd(fd);
    g_current_progress = PT_SYNC_DATA2;
    vlog("====================================\n");
    vlog("====== ventoy update success ======\n");
    vlog("====================================\n");
    goto end;
err:
    g_cur_process_result = 1;
    vtoy_safe_close_fd(fd);        
end:
    g_current_progress = PT_FINISH;
    check_free(thread);
    
    return NULL;
}
static void * ventoy_install_thread(void *data)
{
    int fd;
    ssize_t len;
    off_t offset;
    MBR_HEAD MBR;
    ventoy_disk *disk = NULL;
    VTOY_GPT_INFO *gpt = NULL;
    ventoy_thread_data *thread = (ventoy_thread_data *)data;
    uint64_t Part1StartSector = 0;
    uint64_t Part1SectorCount = 0;
    uint64_t Part2StartSector = 0;
    vdebug("ventoy_install_thread run ...\n");
    fd = thread->diskfd;
    disk = thread->disk;
    g_current_progress = PT_PRAPARE_FOR_CLEAN;
    vdebug("check disk %s\n", disk->disk_name);
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("disk is mounted, now try to unmount it ...\n");
        ventoy_try_umount_disk(disk->disk_path);
    }
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("%s is mounted and can't umount!\n", disk->disk_path);
        goto err;
    }
    else
    {
        vlog("disk is not mounted now, we can do continue ...\n");
    }
    g_current_progress = PT_DEL_ALL_PART;
    ventoy_clean_disk(fd, disk->size_in_byte);
    
    g_current_progress = PT_LOAD_CORE_IMG;
    ventoy_unxz_stg1_img();
    
    g_current_progress = PT_LOAD_DISK_IMG;
    ventoy_unxz_efipart_img();
    if (thread->partstyle)
    {
        vdebug("Fill GPT part table\n");
        gpt = zalloc(sizeof(VTOY_GPT_INFO));
        ventoy_fill_gpt(disk->size_in_byte, thread->reserveBytes, thread->align4kb, gpt);
        Part1StartSector = gpt->PartTbl[0].StartLBA;
        Part1SectorCount = gpt->PartTbl[0].LastLBA - Part1StartSector + 1;
        Part2StartSector = gpt->PartTbl[1].StartLBA;
    }
    else
    {
        vdebug("Fill MBR part table\n");
        ventoy_fill_mbr(disk->size_in_byte, thread->reserveBytes, thread->align4kb, &MBR);
        Part1StartSector = MBR.PartTbl[0].StartSectorId;
        Part1SectorCount = MBR.PartTbl[0].SectorCount;
        Part2StartSector = MBR.PartTbl[1].StartSectorId;
    }
    vlog("Part1StartSector:%llu Part1SectorCount:%llu Part2StartSector:%llu\n", 
        (_ull)Part1StartSector, (_ull)Part1SectorCount, (_ull)Part2StartSector);
    if (thread->partstyle != disk->partstyle)
    {
        vlog("Wait for format part1 (partstyle changed) ...\n");
        sleep(1);
    }
    g_current_progress = PT_FORMAT_PART1;
    vlog("Formatting part1 exFAT %s ...\n", disk->disk_path);
    if (0 != mkexfat_main(disk->disk_path, fd, Part1SectorCount))
    {
        vlog("Failed to format exfat ...\n");
        goto err;
    }
    g_current_progress = PT_FORMAT_PART2;
    vlog("Formatting part2 EFI ...\n");
    if (0 != ventoy_write_efipart(fd, Part2StartSector * 512, thread->secure_boot))
    {
        vlog("Failed to format part2 efi ...\n");
        goto err;
    }
    g_current_progress = PT_WRITE_STG1_IMG;
    vlog("Writing legacy grub ...\n");
    if (0 != ventoy_write_legacy_grub(fd, thread->partstyle))
    {
        vlog("ventoy_write_legacy_grub failed ...\n");
        goto err;
    }
    g_current_progress = PT_SYNC_DATA1;
    vlog("fsync data1...\n");
    fsync(fd);
    vtoy_safe_close_fd(fd);
    /* reopen for check part2 data */
    vlog("Checking part2 efi data %s ...\n", disk->disk_path);
    g_current_progress = PT_CHECK_PART2;
    fd = open(disk->disk_path, O_RDONLY | O_BINARY);
    if (fd < 0)
    {
        vlog("failed to open %s for check fd:%d err:%d\n", disk->disk_path, fd, errno);
        goto err;
    }
    if (0 == ventoy_check_efi_part_data(fd, Part2StartSector * 512))
    {
        vlog("efi part data check success\n");
    }
    else
    {
        vlog("efi part data check failed\n");
        goto err;
    }
    vtoy_safe_close_fd(fd);
    
    /* reopen for write part table */
    g_current_progress = PT_WRITE_PART_TABLE;
    vlog("Writting Partition Table style:%d...\n", thread->partstyle);
    fd = open(disk->disk_path, O_RDWR | O_BINARY);
    if (fd < 0)
    {
        vlog("failed to open %s for part table fd:%d err:%d\n", disk->disk_path, fd, errno);
        goto err;
    }
    if (thread->partstyle)
    {
        ventoy_write_gpt_part_table(fd, disk->size_in_byte, gpt);
    }
    else
    {
        offset = lseek(fd, 0, SEEK_SET);
        len = write(fd, &MBR, 512);
        vlog("Writting MBR Partition Table %llu %llu\n", (_ull)offset, (_ull)len);
        if (offset != 0 || len != 512)
        {
            goto err;
        }
    }
    g_current_progress = PT_SYNC_DATA2;
    vlog("fsync data2...\n");
    fsync(fd);
    vtoy_safe_close_fd(fd);
    vlog("====================================\n");
    vlog("====== ventoy install success ======\n");
    vlog("====================================\n");
    goto end;
err:
    g_cur_process_result = 1;
    vtoy_safe_close_fd(fd);        
end:
    g_current_progress = PT_FINISH;
    check_free(gpt);
    check_free(thread);
    
    return NULL;
}
static int ventoy_api_clean(struct mg_connection *conn, VTOY_JSON *json)
{
    int i = 0;
    int fd = 0;
    ventoy_disk *disk = NULL;
    const char *diskname = NULL;
    char path[128];
    
    if (g_current_progress != PT_FINISH)
    {
        ventoy_json_result(conn, VTOY_JSON_BUSY_RET);
        return 0;  
    }
    
    diskname = vtoy_json_get_string_ex(json, "disk");
    if (diskname == NULL)
    {
        ventoy_json_result(conn, VTOY_JSON_INVALID_RET);
        return 0;
    }
    for (i = 0; i < g_disk_num; i++)
    {
        if (strcmp(g_disk_list[i].disk_name, diskname) == 0)
        {
            disk = g_disk_list + i;
            break;
        }
    }
    if (disk == NULL)
    {
        vlog("disk %s not found\n", diskname);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }
    scnprintf(path, "/sys/block/%s", diskname);
    if (access(path, F_OK) < 0)
    {
        vlog("File %s not exist anymore\n", path);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }
    vlog("==================================\n");
    vlog("===== ventoy clean %s =====\n", disk->disk_path);
    vlog("==================================\n");
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("disk is mounted, now try to unmount it ...\n");
        ventoy_try_umount_disk(disk->disk_path);
    }
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("%s is mounted and can't umount!\n", disk->disk_path);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    else
    {
        vlog("disk is not mounted now, we can do the clean ...\n");
    }
    fd = open(disk->disk_path, O_RDWR | O_BINARY);
    if (fd < 0)
    {
        vlog("failed to open %s fd:%d err:%d\n", disk->disk_path, fd, errno);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    vdebug("start clean %s ...\n", disk->disk_model);
    ventoy_clean_disk(fd, disk->size_in_byte);    
    vtoy_safe_close_fd(fd);
    
    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;    
}
static int ventoy_api_install(struct mg_connection *conn, VTOY_JSON *json)
{
    int i = 0;
    int ret = 0;
    int fd = 0;
    uint32_t align4kb = 0;
    uint32_t style = 0;
    uint32_t secure_boot = 0;
    uint64_t reserveBytes = 0;
    ventoy_disk *disk = NULL;
    const char *diskname = NULL;
    const char *reserve_space = NULL;
    ventoy_thread_data *thread = NULL;
    char path[128];
    
    if (g_current_progress != PT_FINISH)
    {
        ventoy_json_result(conn, VTOY_JSON_BUSY_RET);
        return 0;  
    }
    
    diskname = vtoy_json_get_string_ex(json, "disk");
    reserve_space = vtoy_json_get_string_ex(json, "reserve_space");
    ret += vtoy_json_get_uint(json, "partstyle", &style);
    ret += vtoy_json_get_uint(json, "secure_boot", &secure_boot);
    ret += vtoy_json_get_uint(json, "align_4kb", &align4kb);
    if (diskname == NULL || reserve_space == NULL || ret != JSON_SUCCESS)
    {
        ventoy_json_result(conn, VTOY_JSON_INVALID_RET);
        return 0;
    }
    reserveBytes = (uint64_t)strtoull(reserve_space, NULL, 10);
    for (i = 0; i < g_disk_num; i++)
    {
        if (strcmp(g_disk_list[i].disk_name, diskname) == 0)
        {
            disk = g_disk_list + i;
            break;
        }
    }
    if (disk == NULL)
    {
        vlog("disk %s not found\n", diskname);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }
    if (disk->is4kn)
    {
        vlog("disk %s is 4k native, not supported.\n", diskname);
        ventoy_json_result(conn, VTOY_JSON_4KN_RET);
        return 0;
    }
    scnprintf(path, "/sys/block/%s", diskname);
    if (access(path, F_OK) < 0)
    {
        vlog("File %s not exist anymore\n", path);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }
    if (disk->size_in_byte > 2199023255552ULL && style == 0)
    {
        vlog("disk %s is more than 2TB and GPT is needed\n", path);
        ventoy_json_result(conn, VTOY_JSON_MBR_2TB_RET);
        return 0;
    }
    if ((reserveBytes + VTOYEFI_PART_BYTES * 2) > disk->size_in_byte)
    {
        vlog("reserve space %llu is too big for disk %s %llu\n", (_ull)reserveBytes, path, (_ull)disk->size_in_byte);
        ventoy_json_result(conn, VTOY_JSON_INVALID_RSV_RET);
        return 0;
    }
    vlog("==================================================================================\n");
    vlog("===== ventoy install %s style:%s secureboot:%u align4K:%u reserve:%llu =========\n",
         disk->disk_path, (style ? "GPT" : "MBR"), secure_boot, align4kb, (_ull)reserveBytes);
    vlog("==================================================================================\n");
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("disk is mounted, now try to unmount it ...\n");
        ventoy_try_umount_disk(disk->disk_path);
    }
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("%s is mounted and can't umount!\n", disk->disk_path);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    else
    {
        vlog("disk is not mounted now, we can do the install ...\n");
    }
    fd = open(disk->disk_path, O_RDWR | O_BINARY);
    if (fd < 0)
    {
        vlog("failed to open %s fd:%d err:%d\n", disk->disk_path, fd, errno);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    vdebug("start install thread %s ...\n", disk->disk_model);
    thread = zalloc(sizeof(ventoy_thread_data));
    if (!thread)
    {
        vtoy_safe_close_fd(fd);
        vlog("failed to alloc thread data err:%d\n", errno);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    
    g_current_progress = PT_START;
    g_cur_process_result = 0;
    scnprintf(g_cur_process_type, "%s", "install");
    scnprintf(g_cur_process_diskname, "%s", disk->disk_name);
    thread->disk = disk;
    thread->diskfd = fd;
    thread->align4kb = align4kb;
    thread->partstyle = style;
    thread->secure_boot = secure_boot;
    thread->reserveBytes = reserveBytes;
    
    mg_start_thread(ventoy_install_thread, thread);
    
    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;    
}
static int ventoy_api_update(struct mg_connection *conn, VTOY_JSON *json)
{
    int i = 0;
    int ret = 0;
    int fd = 0;
    uint32_t secure_boot = 0;
    ventoy_disk *disk = NULL;
    const char *diskname = NULL;
    ventoy_thread_data *thread = NULL;
    char path[128];
    
    if (g_current_progress != PT_FINISH)
    {
        ventoy_json_result(conn, VTOY_JSON_BUSY_RET);
        return 0;  
    }
    
    diskname = vtoy_json_get_string_ex(json, "disk");
    ret += vtoy_json_get_uint(json, "secure_boot", &secure_boot);
    if (diskname == NULL || ret != JSON_SUCCESS)
    {
        ventoy_json_result(conn, VTOY_JSON_INVALID_RET);
        return 0;
    }
    for (i = 0; i < g_disk_num; i++)
    {
        if (strcmp(g_disk_list[i].disk_name, diskname) == 0)
        {
            disk = g_disk_list + i;
            break;
        }
    }
    if (disk == NULL)
    {
        vlog("disk %s not found\n", diskname);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }
    if (disk->vtoydata.ventoy_valid == 0)
    {
        vlog("disk %s is not ventoy disk\n", diskname);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    scnprintf(path, "/sys/block/%s", diskname);
    if (access(path, F_OK) < 0)
    {
        vlog("File %s not exist anymore\n", path);
        ventoy_json_result(conn, VTOY_JSON_NOTFOUND_RET);
        return 0;
    }
    vlog("==========================================================\n");
    vlog("===== ventoy update %s new_secureboot:%u =========\n", disk->disk_path, secure_boot);
    vlog("==========================================================\n");
    vlog("%s version:%s partstyle:%u oldsecureboot:%u reserve:%llu\n", 
        disk->disk_path, disk->vtoydata.ventoy_ver, 
        disk->vtoydata.partition_style,
        disk->vtoydata.secure_boot_flag,
        (_ull)(disk->vtoydata.preserved_space)
        );
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("disk is mounted, now try to unmount it ...\n");
        ventoy_try_umount_disk(disk->disk_path);
    }
    if (ventoy_is_disk_mounted(disk->disk_path))
    {
        vlog("%s is mounted and can't umount!\n", disk->disk_path);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    else
    {
        vlog("disk is not mounted now, we can do the update ...\n");
    }
    fd = open(disk->disk_path, O_RDWR | O_BINARY);
    if (fd < 0)
    {
        vlog("failed to open %s fd:%d err:%d\n", disk->disk_path, fd, errno);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    vdebug("start update thread %s ...\n", disk->disk_model);
    thread = zalloc(sizeof(ventoy_thread_data));
    if (!thread)
    {
        vtoy_safe_close_fd(fd);
        vlog("failed to alloc thread data err:%d\n", errno);
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    
    g_current_progress = PT_START;
    g_cur_process_result = 0;
    scnprintf(g_cur_process_type, "%s", "update");
    scnprintf(g_cur_process_diskname, "%s", disk->disk_name);
    thread->disk = disk;
    thread->diskfd = fd;
    thread->secure_boot = secure_boot;
    
    mg_start_thread(ventoy_update_thread, thread);
    
    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;    
}
static int ventoy_api_refresh_device(struct mg_connection *conn, VTOY_JSON *json)
{
    (void)json;
    if (g_current_progress == PT_FINISH)
    {
        g_disk_num = 0;
        ventoy_disk_enumerate_all();
    }
    ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
    return 0;
}
static int ventoy_api_get_dev_list(struct mg_connection *conn, VTOY_JSON *json)
{
    int i = 0;
    int rc = 0;
    int pos = 0;
    int buflen = 0;
    uint32_t alldev = 0;
    char *buf = NULL;
    ventoy_disk *cur = NULL;
    
    rc = vtoy_json_get_uint(json, "alldev", &alldev);
    if (JSON_SUCCESS != rc)
    {
        alldev = 0;
    }
    buflen = g_disk_num * 1024;
    buf = (char *)malloc(buflen + 1024);
    if (!buf)
    {
        ventoy_json_result(conn, VTOY_JSON_FAILED_RET);
        return 0;
    }
    VTOY_JSON_FMT_BEGIN(pos, buf, buflen);
    VTOY_JSON_FMT_OBJ_BEGIN();
    VTOY_JSON_FMT_KEY("list");
    VTOY_JSON_FMT_ARY_BEGIN();
    for (i = 0; i < g_disk_num; i++)
    {
        cur = g_disk_list + i;
        if (alldev == 0 && cur->type != VTOY_DEVICE_USB)
        {
            continue;
        }
        
        VTOY_JSON_FMT_OBJ_BEGIN();
        VTOY_JSON_FMT_STRN("name", cur->disk_name);
        VTOY_JSON_FMT_STRN("model", cur->disk_model);
        VTOY_JSON_FMT_STRN("size", cur->human_readable_size);
        VTOY_JSON_FMT_UINT("vtoy_valid", cur->vtoydata.ventoy_valid);
        VTOY_JSON_FMT_STRN("vtoy_ver", cur->vtoydata.ventoy_ver);
        VTOY_JSON_FMT_UINT("vtoy_secure_boot", cur->vtoydata.secure_boot_flag);
        VTOY_JSON_FMT_UINT("vtoy_partstyle", cur->vtoydata.partition_style);
        VTOY_JSON_FMT_OBJ_ENDEX();
    }
    
    VTOY_JSON_FMT_ARY_END();
    VTOY_JSON_FMT_OBJ_END();
    VTOY_JSON_FMT_END(pos);
    ventoy_json_buffer(conn, buf, pos);
    return 0;
}
static JSON_CB g_ventoy_json_cb[] = 
{
    { "sysinfo",        ventoy_api_sysinfo        },
    { "sel_language",   ventoy_api_set_language   },
    { "sel_partstyle",  ventoy_api_set_partstyle  },
    { "refresh_device", ventoy_api_refresh_device },
    { "get_dev_list",   ventoy_api_get_dev_list   },
    { "install",        ventoy_api_install        },
    { "update",         ventoy_api_update         },
    { "clean",          ventoy_api_clean          },
    { "get_percent",    ventoy_api_get_percent    },
};
static int ventoy_json_handler(struct mg_connection *conn, VTOY_JSON *json)
{
    int i;
    const char *token = NULL;
    const char *method = NULL;
    method = vtoy_json_get_string_ex(json, "method");
    if (!method)
    {
        ventoy_json_result(conn, VTOY_JSON_SUCCESS_RET);
        return 0;
    }
    if (strcmp(method, "sysinfo"))
    {
        token = vtoy_json_get_string_ex(json, "token");
        if (token == NULL || strcmp(token, g_cur_server_token))
        {
            ventoy_json_result(conn, VTOY_JSON_TOKEN_ERR_RET);
            return 0;
        }
    }
    for (i = 0; i < (int)(sizeof(g_ventoy_json_cb) / sizeof(g_ventoy_json_cb[0])); i++)
    {
        if (strcmp(method, g_ventoy_json_cb[i].method) == 0)
        {
            g_ventoy_json_cb[i].callback(conn, json);
            break;
        }
    }
    return 0;
}
int ventoy_func_handler(const char *jsonstr, char *jsonbuf, int buflen)
{
    int i;
    const char *method = NULL;
    VTOY_JSON *json = NULL;
    g_pub_out_buf = jsonbuf;
    g_pub_out_max = buflen;
    json = vtoy_json_create();
    if (JSON_SUCCESS == vtoy_json_parse(json, jsonstr))
    {
        pthread_mutex_lock(&g_api_mutex);
        method = vtoy_json_get_string_ex(json->pstChild, "method");
        for (i = 0; i < (int)(sizeof(g_ventoy_json_cb) / sizeof(g_ventoy_json_cb[0])); i++)
        {
            if (method && strcmp(method, g_ventoy_json_cb[i].method) == 0)
            {
                g_ventoy_json_cb[i].callback(NULL, json->pstChild);
                break;
            }
        }
        pthread_mutex_unlock(&g_api_mutex);
    }
    else
    {
        ventoy_json_result(NULL, VTOY_JSON_INVALID_RET);
    }
    vtoy_json_destroy(json);
    return 0;
}
static int ventoy_request_handler(struct mg_connection *conn)
{
    int post_data_len;
    int post_buf_len;
    VTOY_JSON *json = NULL;
    char *post_data_buf = NULL;
    const struct mg_request_info *ri = NULL;
    char stack_buf[512];
    
    ri = mg_get_request_info(conn);    
    if (strcmp(ri->uri, "/vtoy/json") == 0)
    {
        if (ri->content_length > 500)
        {
            post_data_buf = malloc(ri->content_length + 4);
            post_buf_len  = ri->content_length + 1;
        }
        else
        {
            post_data_buf = stack_buf;
            post_buf_len = sizeof(stack_buf);
        }
        
        post_data_len = mg_read(conn, post_data_buf, post_buf_len);
        post_data_buf[post_data_len] = 0;
        json = vtoy_json_create();
        if (JSON_SUCCESS == vtoy_json_parse(json, post_data_buf))
        {
            pthread_mutex_lock(&g_api_mutex);
            ventoy_json_handler(conn, json->pstChild);
            pthread_mutex_unlock(&g_api_mutex);
        }
        else
        {
            ventoy_json_result(conn, VTOY_JSON_INVALID_RET);
        }
        vtoy_json_destroy(json);
        if (post_data_buf != stack_buf)
        {
            free(post_data_buf);
        }
        return 1;
    }
    else
    {
        return 0;
    }
}
int ventoy_http_start(const char *ip, const char *port)
{
    uint8_t uuid[16];
    char addr[128];
    struct mg_callbacks callbacks;
    const char *options[] = 
    {
	    "listening_ports",    "24680",
        "document_root",      "WebUI",
        "error_log_file",     g_log_file,
	    "request_timeout_ms", "10000",
	     NULL
    };
    /* unique token */
    ventoy_gen_preudo_uuid(uuid);
    scnprintf(g_cur_server_token, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
        uuid[0], uuid[1], uuid[2], uuid[3], uuid[4], uuid[5], uuid[6], uuid[7],
        uuid[8], uuid[9], uuid[10], uuid[11], uuid[12], uuid[13], uuid[14], uuid[15]);
    /* option */
    scnprintf(addr, "%s:%s", ip, port);
    options[1] = addr;
    memset(&callbacks, 0, sizeof(callbacks));
    callbacks.begin_request = ventoy_request_handler;
    g_ventoy_http_ctx = mg_start(&callbacks, NULL, options);
    return g_ventoy_http_ctx ? 0 : 1;
}
int ventoy_http_stop(void)
{
    if (g_ventoy_http_ctx)
    {
        mg_stop(g_ventoy_http_ctx);        
    }
    return 0;
}
int ventoy_http_init(void)
{
    pthread_mutex_init(&g_api_mutex, NULL);
    ventoy_http_load_cfg();
    ventoy_load_mbr_template();
    
    return 0;
}
void ventoy_http_exit(void)
{
    pthread_mutex_destroy(&g_api_mutex);
    check_free(g_efi_part_raw_img);
    g_efi_part_raw_img = NULL;    
}
const char * ventoy_code_get_cur_language(void)
{
    return g_cur_language;
}
int ventoy_code_get_cur_part_style(void)
{
    return g_cur_part_style;
}
void ventoy_code_set_cur_part_style(int style)
{
    pthread_mutex_lock(&g_api_mutex);
    
    g_cur_part_style = style;
    ventoy_http_save_cfg();
    pthread_mutex_unlock(&g_api_mutex);
}
int ventoy_code_get_cur_show_all(void)
{
    return g_cur_show_all;
}
void ventoy_code_set_cur_show_all(int show_all)
{
    pthread_mutex_lock(&g_api_mutex);
    
    g_cur_show_all = show_all;
    ventoy_http_save_cfg();
    pthread_mutex_unlock(&g_api_mutex);
}
void ventoy_code_set_cur_language(const char *lang)
{
    pthread_mutex_lock(&g_api_mutex);
    
    scnprintf(g_cur_language, "%s", lang);
    ventoy_http_save_cfg();
    
    pthread_mutex_unlock(&g_api_mutex);
}
void ventoy_code_refresh_device(void)
{
    if (g_current_progress == PT_FINISH)
    {
        g_disk_num = 0;
        ventoy_disk_enumerate_all();
    }
}
int ventoy_code_is_busy(void)
{
    return (g_current_progress == PT_FINISH) ? 0 : 1;
}
int ventoy_code_get_percent(void)
{
    return g_current_progress * 100 / PT_FINISH;
}
int ventoy_code_get_result(void)
{
    return g_cur_process_result;
}
void ventoy_code_save_cfg(void)
{
    ventoy_http_save_cfg();
}
 | 42,561 | 
	C | 
	.c | 1,382 | 24.518813 | 117 | 0.578021 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 740 | 
	ventoy_qt_stub.c | 
	ventoy_Ventoy/LinuxGUI/Ventoy2Disk/QT/ventoy_qt_stub.c | 
	/******************************************************************************
 * ventoy_qt_stub.c
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <linux/limits.h>
#include <pthread.h>
#include <ventoy_define.h>
#include <ventoy_json.h>
#include <ventoy_util.h>
#include <ventoy_disk.h>
#include <ventoy_http.h>
struct mg_context *
mg_start(const struct mg_callbacks *callbacks,
         void *user_data,
         const char **options)
{
    (void)callbacks;
    (void)user_data;
    (void)options;
    
    return NULL;
}
void mg_stop(struct mg_context *ctx)
{
    (void)ctx;
}
int mg_read(struct mg_connection *conn, void *buf, size_t len)
{
    (void)conn;
    (void)buf;
    (void)len;
    return 0;
}
const struct mg_request_info * mg_get_request_info(const struct mg_connection *conn)
{
    (void)conn;
    return NULL;
}
int mg_start_thread(mg_thread_func_t func, void *param)
{
	pthread_t thread_id;
	pthread_attr_t attr;
	int result;
	(void)pthread_attr_init(&attr);
	(void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
#if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1)
	/* Compile-time option to control stack size,
	 * e.g. -DUSE_STACK_SIZE=16384 */
	(void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE);
#endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */
	result = pthread_create(&thread_id, &attr, func, param);
	pthread_attr_destroy(&attr);
	return result;
}
int mg_printf(struct mg_connection *conn, const char *fmt, ...)
{
	(void)conn;
	(void)fmt;
	return 0;
}
static unsigned char window_icon_hexData[] = {
    0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
    0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40, 0x08, 0x06, 0x00, 0x00, 0x00, 0xAA, 0x69, 0x71,
    0xDE, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41, 0x4D, 0x41, 0x00, 0x00, 0xAF, 0xC8, 0x37, 0x05, 0x8A,
    0xE9, 0x00, 0x00, 0x00, 0x20, 0x63, 0x48, 0x52, 0x4D, 0x00, 0x00, 0x7A, 0x26, 0x00, 0x00, 0x80,
    0x84, 0x00, 0x00, 0xFA, 0x00, 0x00, 0x00, 0x80, 0xE8, 0x00, 0x00, 0x75, 0x30, 0x00, 0x00, 0xEA,
    0x60, 0x00, 0x00, 0x3A, 0x98, 0x00, 0x00, 0x17, 0x70, 0x9C, 0xBA, 0x51, 0x3C, 0x00, 0x00, 0x00,
    0x06, 0x62, 0x4B, 0x47, 0x44, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0xFF, 0xA0, 0xBD, 0xA7, 0x93, 0x00,
    0x00, 0x00, 0x07, 0x74, 0x49, 0x4D, 0x45, 0x07, 0xE4, 0x03, 0x17, 0x04, 0x10, 0x05, 0xF6, 0xCE,
    0xA8, 0xC0, 0x00, 0x00, 0x1C, 0x68, 0x49, 0x44, 0x41, 0x54, 0x78, 0xDA, 0xCD, 0x9B, 0x79, 0x94,
    0x1D, 0x57, 0x7D, 0xE7, 0x3F, 0xF7, 0xDE, 0xAA, 0x7A, 0xFB, 0xEB, 0xD7, 0xBB, 0xA4, 0x56, 0xCB,
    0xDA, 0x6C, 0x59, 0xB6, 0x64, 0x83, 0x91, 0x17, 0xBC, 0xE1, 0x0D, 0x2F, 0x04, 0x1B, 0xB0, 0x43,
    0x3C, 0x40, 0x32, 0x43, 0x4E, 0x38, 0x19, 0x87, 0x43, 0x26, 0x03, 0x84, 0x98, 0xC9, 0x1C, 0x98,
    0x93, 0x70, 0x48, 0x72, 0x66, 0x58, 0x86, 0x81, 0x10, 0x0E, 0x06, 0xC6, 0x21, 0xC1, 0x83, 0xC1,
    0x36, 0x18, 0xDB, 0x6C, 0xC6, 0x60, 0xB0, 0x65, 0xBC, 0x1B, 0x5B, 0x8B, 0x6D, 0x59, 0x92, 0xB5,
    0x75, 0x5B, 0x52, 0xAB, 0xD7, 0xB7, 0x56, 0xD5, 0x5D, 0xE6, 0x8F, 0xAA, 0xF7, 0xF4, 0xBA, 0xD5,
    0xF2, 0xC2, 0x92, 0x99, 0x3A, 0xE7, 0xD7, 0xF5, 0x96, 0x7A, 0x75, 0x7F, 0xDF, 0xEF, 0x6F, 0xB9,
    0xBF, 0xFB, 0xBB, 0xD5, 0x82, 0xDF, 0xD1, 0x61, 0x8C, 0x45, 0x7D, 0x70, 0x9A, 0xFD, 0x7F, 0x57,
    0x61, 0x57, 0xD5, 0x31, 0x17, 0x39, 0x9C, 0x83, 0xD8, 0xC1, 0xEF, 0xAF, 0x1A, 0xE6, 0xC9, 0x23,
    0x13, 0x41, 0x55, 0xA3, 0xB4, 0x75, 0xD2, 0x93, 0xB8, 0xBC, 0x27, 0xCC, 0xA6, 0x7E, 0x19, 0xDD,
    0xBA, 0x5B, 0xBB, 0xBC, 0x07, 0x02, 0x28, 0x78, 0x82, 0xD1, 0xA2, 0x60, 0x6D, 0x59, 0x52, 0x8F,
    0x1D, 0xC5, 0x40, 0xFE, 0xD6, 0xF5, 0x14, 0xBF, 0xED, 0x1B, 0x3E, 0xBC, 0x67, 0x92, 0x3C, 0x9A,
    0x03, 0xAE, 0x44, 0x84, 0xC7, 0xDB, 0x56, 0xFA, 0x3C, 0x3A, 0x61, 0x7A, 0x26, 0x43, 0x96, 0x59,
    0xEB, 0xD6, 0x6A, 0xC7, 0x09, 0x16, 0x46, 0x05, 0xF4, 0x03, 0x79, 0x01, 0xBE, 0x03, 0x03, 0x34,
    0x81, 0x19, 0x21, 0x18, 0xF3, 0x05, 0x7B, 0x95, 0x10, 0xBB, 0x8A, 0x3E, 0xFB, 0xCE, 0x1B, 0x56,
    0xD3, 0x77, 0xEC, 0x89, 0x4D, 0x5E, 0x5A, 0xFA, 0x5C, 0x9D, 0x59, 0xF2, 0xAC, 0x72, 0x87, 0x39,
    0x71, 0xD5, 0x09, 0xFF, 0x7F, 0x11, 0xF0, 0xD3, 0x17, 0x67, 0xC9, 0xA1, 0x99, 0xB0, 0x39, 0xBE,
    0x19, 0xE6, 0x78, 0x5F, 0xA1, 0xD1, 0x17, 0x4B, 0xFF, 0x8C, 0x96, 0x11, 0x17, 0x59, 0xC7, 0xD9,
    0xC6, 0xB1, 0xCE, 0x41, 0x9F, 0x14, 0xE4, 0x3C, 0x89, 0x54, 0x02, 0x94, 0x48, 0x14, 0x70, 0x80,
    0x75, 0x60, 0x8E, 0x4A, 0x53, 0xC0, 0x9C, 0x27, 0xD8, 0x2D, 0x04, 0x8F, 0x67, 0x24, 0xF7, 0x07,
    0xE8, 0x47, 0x2E, 0x52, 0xDF, 0x19, 0xBF, 0x3B, 0xBC, 0xD6, 0x55, 0x44, 0xC8, 0x6E, 0xBF, 0xCC,
    0x99, 0xCD, 0x3D, 0x9C, 0xB2, 0x76, 0xD5, 0xFF, 0x5B, 0x02, 0x7E, 0xBE, 0x6B, 0x92, 0x3E, 0xD1,
    0x64, 0x8F, 0xA9, 0x70, 0xF5, 0x89, 0x05, 0xBE, 0xBF, 0xBB, 0xB1, 0xAA, 0xE5, 0xD4, 0xD5, 0x06,
    0xF1, 0x76, 0xE3, 0xC4, 0xEB, 0x8D, 0xA3, 0x22, 0x05, 0xE4, 0x3C, 0x41, 0xD1, 0x83, 0xAC, 0x27,
    0x08, 0x24, 0xC8, 0x14, 0x7C, 0x9B, 0x80, 0x36, 0x09, 0xDA, 0x41, 0x4B, 0x3B, 0xEA, 0x1A, 0x1A,
    0xDA, 0x61, 0x1C, 0x28, 0x41, 0xC3, 0x13, 0xEE, 0x79, 0x0F, 0xEE, 0xC9, 0x48, 0x73, 0xC7, 0x3A,
    0x6F, 0x66, 0xCB, 0x56, 0x3D, 0xA0, 0x4F, 0xC8, 0x69, 0xE6, 0xB4, 0xE4, 0xFC, 0x91, 0xEC, 0xBF,
    0x3D, 0x01, 0x8F, 0xFE, 0x6A, 0x2B, 0xBB, 0x4B, 0xEB, 0xA9, 0x98, 0x39, 0x76, 0xDB, 0x0A, 0xAB,
    0xBC, 0xEA, 0xB2, 0x3A, 0xFE, 0xBB, 0x0D, 0xF2, 0xDF, 0x6B, 0xCB, 0x29, 0x91, 0x75, 0x4A, 0x20,
    0xA8, 0x64, 0x04, 0xBD, 0x19, 0x41, 0xCE, 0x13, 0x2C, 0x16, 0xC1, 0xEE, 0x38, 0x8A, 0x38, 0x20,
    0x34, 0x30, 0x1B, 0x39, 0xA6, 0x42, 0x8B, 0x76, 0x90, 0x91, 0x10, 0x48, 0xF6, 0x79, 0xC2, 0xDD,
    0x9E, 0xF7, 0xF8, 0xCA, 0xE5, 0x37, 0xFB, 0xDB, 0xEF, 0x7B, 0x6F, 0xCC, 0x25, 0xA3, 0x9A, 0xA7,
    0x0E, 0x29, 0xCE, 0x58, 0x92, 0xFB, 0xB7, 0x21, 0xE0, 0x91, 0xFD, 0x73, 0x9C, 0x55, 0xAE, 0xF2,
    0x9D, 0xC3, 0x15, 0x86, 0x5D, 0x35, 0xFB, 0x12, 0xA5, 0xAB, 0x62, 0x27, 0x3F, 0xA8, 0x11, 0xE7,
    0xB6, 0x0C, 0x2A, 0x32, 0x8E, 0x9E, 0x40, 0xB0, 0xAC, 0xA0, 0x28, 0x78, 0xA2, 0x33, 0x8A, 0x7B,
    0x8D, 0xE3, 0xB4, 0x95, 0x0B, 0x8D, 0xE3, 0x50, 0xD3, 0x72, 0xA4, 0x65, 0x51, 0x42, 0x50, 0xF0,
    0xC0, 0x97, 0xE2, 0xD9, 0x8C, 0x74, 0xFF, 0x34, 0x98, 0x71, 0xDF, 0xD8, 0xDF, 0x10, 0x53, 0xEB,
    0x8A, 0x9A, 0x99, 0x58, 0x72, 0xD1, 0x8A, 0xFC, 0xEF, 0x96, 0x80, 0x7B, 0x76, 0xD6, 0xE9, 0x0F,
    0x0C, 0x4F, 0xCD, 0x78, 0xAC, 0xC8, 0x9B, 0xD1, 0xAA, 0x96, 0x1F, 0x8E, 0x91, 0xEF, 0x6D, 0x69,
    0xD7, 0x53, 0xD7, 0x09, 0xC4, 0xD1, 0xA2, 0x62, 0x28, 0x2F, 0x51, 0x42, 0xBC, 0x66, 0xD0, 0xC7,
    0x3F, 0x1C, 0xD3, 0xA1, 0x63, 0x6F, 0xD5, 0x10, 0x19, 0x47, 0xD1, 0x97, 0xE4, 0x7D, 0x11, 0x65,
    0x25, 0xDF, 0xCF, 0x7A, 0x7C, 0xE2, 0xA1, 0xC9, 0xE0, 0xC9, 0x2B, 0x07, 0x1A, 0xB4, 0x2C, 0xBC,
    0x79, 0x55, 0xF1, 0x77, 0x43, 0xC0, 0x3D, 0xCF, 0xCF, 0x90, 0x55, 0xF0, 0xAB, 0x39, 0x9F, 0x35,
    0x25, 0x77, 0x66, 0x4D, 0x8B, 0x7F, 0x88, 0x0C, 0x17, 0xD7, 0x62, 0x27, 0x1A, 0xDA, 0xE1, 0x2B,
    0xC1, 0xEA, 0x1E, 0x45, 0x7F, 0x4E, 0x26, 0xC0, 0x7F, 0x7B, 0xE8, 0x13, 0x65, 0x05, 0xD4, 0x63,
    0xC7, 0xAE, 0x19, 0x43, 0x2D, 0x76, 0xE4, 0x3D, 0x41, 0x29, 0x10, 0xE4, 0x3D, 0xB1, 0xBD, 0xA0,
    0xDC, 0xC7, 0x2E, 0xAC, 0x34, 0xEE, 0x7C, 0x6A, 0xCE, 0x37, 0xA1, 0x15, 0x5C, 0xBE, 0xA6, 0xFC,
    0xDB, 0x25, 0xE0, 0x7B, 0xCF, 0xCD, 0x90, 0x53, 0x8E, 0xB7, 0x6C, 0xAF, 0xF0, 0x8D, 0x75, 0xF5,
    0x37, 0x37, 0x0D, 0x9F, 0x69, 0x6A, 0xB7, 0xA1, 0x1A, 0x39, 0x5A, 0xC6, 0xE1, 0x29, 0xC1, 0x89,
    0x15, 0x8F, 0xFE, 0x9C, 0xE4, 0x77, 0x80, 0xBD, 0x73, 0x48, 0xA0, 0x16, 0x3B, 0x76, 0x4C, 0x6B,
    0xEA, 0xDA, 0x91, 0x51, 0x82, 0x1E, 0x5F, 0x52, 0x0A, 0xC4, 0xE1, 0x82, 0xE7, 0xFE, 0xE6, 0x94,
    0x5C, 0xFD, 0xA6, 0xFD, 0x61, 0x10, 0x87, 0x16, 0xAE, 0x5A, 0x5B, 0xF9, 0xED, 0x10, 0x70, 0xCF,
    0x73, 0x53, 0x64, 0x14, 0xFC, 0x7C, 0xAA, 0xC0, 0x86, 0x52, 0x78, 0x45, 0xC3, 0x88, 0x2F, 0xD4,
    0x22, 0xB7, 0x76, 0x2E, 0xB2, 0xC4, 0xD6, 0x81, 0x10, 0xAC, 0x2C, 0x7B, 0x8C, 0x94, 0xD4, 0xEF,
    0x08, 0xF6, 0x02, 0xA5, 0x05, 0x4C, 0xB5, 0x2C, 0x3B, 0xA6, 0x35, 0xDA, 0x3A, 0x7C, 0x29, 0x28,
    0x07, 0x92, 0xDE, 0xAC, 0x9C, 0x2B, 0x2A, 0xF7, 0xF1, 0x8D, 0xF9, 0xD9, 0x7F, 0xDC, 0xD3, 0xCA,
    0xE9, 0xD8, 0x49, 0xAE, 0x3C, 0xF1, 0xE5, 0x49, 0x78, 0x45, 0x02, 0x7E, 0xB6, 0x65, 0x0F, 0x85,
    0x5C, 0x86, 0x87, 0x66, 0x0A, 0x0C, 0xE7, 0x38, 0xAF, 0x1E, 0xBB, 0x9B, 0x6A, 0x91, 0x5D, 0x3F,
    0x1B, 0x3A, 0x62, 0xE7, 0x70, 0x40, 0x5F, 0xCE, 0x63, 0x5D, 0x9F, 0x8F, 0xFA, 0xED, 0x17, 0x6A,
    0xC7, 0x1C, 0xCE, 0xB9, 0x8E, 0xD2, 0x7B, 0xAB, 0x86, 0x03, 0x55, 0x8D, 0x00, 0x3C, 0x29, 0xE8,
    0xC9, 0x48, 0xFA, 0xB2, 0x72, 0xAA, 0xE8, 0xF1, 0x97, 0xEF, 0x28, 0xEF, 0xBB, 0xF9, 0xFE, 0xFA,
    0x52, 0x67, 0x10, 0x5C, 0xB6, 0xB6, 0xF7, 0xD7, 0x27, 0xC0, 0x39, 0xF8, 0xCA, 0xD3, 0x73, 0xF4,
    0xA8, 0xE8, 0xD4, 0xD9, 0xD8, 0xBB, 0xB9, 0x1A, 0xD9, 0x4D, 0x33, 0x2D, 0x43, 0xEC, 0x12, 0x37,
    0xF7, 0x94, 0xE0, 0xA4, 0xBE, 0x80, 0xBE, 0xAC, 0x24, 0x75, 0x86, 0xDF, 0x00, 0xDD, 0x02, 0x8D,
    0x1C, 0xB8, 0xF6, 0x24, 0xE2, 0xC0, 0x5A, 0x43, 0xD6, 0x4B, 0x94, 0x0A, 0x2D, 0x84, 0x56, 0xF2,
    0xEC, 0x64, 0x4C, 0x33, 0x76, 0x08, 0x01, 0x9E, 0x84, 0xDE, 0xAC, 0xA2, 0x3F, 0xA7, 0xC6, 0xCB,
    0x9E, 0xFD, 0x8F, 0x7B, 0x9B, 0xFE, 0xDD, 0x67, 0x97, 0xE6, 0x88, 0x1B, 0x35, 0x2E, 0x38, 0xED,
    0xC4, 0xD7, 0x4E, 0xC0, 0x37, 0x9F, 0x3C, 0x08, 0x52, 0x92, 0x51, 0xF4, 0x1F, 0x89, 0xBC, 0x2F,
    0x57, 0x43, 0x7B, 0xED, 0x54, 0xD3, 0x10, 0xA6, 0x48, 0x9D, 0x80, 0xBE, 0xAC, 0xE2, 0xA4, 0xBE,
    0x00, 0x29, 0x39, 0xFE, 0xA4, 0xFE, 0x5A, 0x80, 0x2F, 0x76, 0x0F, 0x07, 0xD6, 0x6A, 0x7A, 0x02,
    0x38, 0x7D, 0xB8, 0x40, 0x64, 0x0C, 0x4F, 0xBD, 0x54, 0x25, 0x72, 0x1E, 0xFB, 0xEB, 0x30, 0x56,
    0x35, 0x9D, 0xCB, 0x7D, 0x29, 0x18, 0xC8, 0x4B, 0x06, 0x72, 0xEA, 0xE9, 0x5E, 0xCF, 0xFC, 0x61,
    0x9D, 0xCC, 0xD6, 0xEB, 0x4F, 0x2E, 0x1C, 0xD7, 0x32, 0xC7, 0x55, 0xF5, 0xAE, 0x87, 0xB6, 0x60,
    0x72, 0x15, 0xCE, 0x29, 0x4F, 0xC9, 0x7B, 0xA6, 0x47, 0x6E, 0x9C, 0x0D, 0xED, 0xDF, 0x4E, 0x36,
    0xB4, 0xD7, 0xD0, 0xC9, 0xAF, 0x84, 0x4C, 0x7E, 0xBA, 0xB2, 0x12, 0xB0, 0xA4, 0xE8, 0xFD, 0x06,
    0x66, 0xEF, 0xC2, 0xED, 0x1C, 0xCE, 0x5A, 0x04, 0x0E, 0x87, 0x40, 0xC8, 0x34, 0xA1, 0x9A, 0x98,
    0xC1, 0xBC, 0xE4, 0x75, 0x4B, 0x0B, 0xE4, 0x14, 0x78, 0x4A, 0xB1, 0x7F, 0xA6, 0xC9, 0xD3, 0x2F,
    0x55, 0x99, 0x8C, 0x3C, 0x76, 0xCC, 0x58, 0x8C, 0x13, 0x1D, 0x40, 0x19, 0x4F, 0xB0, 0xA4, 0xE0,
    0x31, 0x90, 0x93, 0xB7, 0x0C, 0xFB, 0xD1, 0x0D, 0x4D, 0x2B, 0xAB, 0x9E, 0x89, 0xB8, 0x72, 0xE3,
    0xC8, 0x31, 0xE3, 0x1E, 0x37, 0x6A, 0xDF, 0xAA, 0x7F, 0xCA, 0x78, 0x5C, 0xE0, 0x47, 0x53, 0x43,
    0x6F, 0xAC, 0x85, 0xF6, 0xFD, 0xD3, 0xF5, 0xD8, 0xAB, 0xB6, 0x34, 0xDA, 0x18, 0x8C, 0xB5, 0x68,
    0x63, 0xC1, 0x39, 0x32, 0x0A, 0xB4, 0x71, 0xC4, 0xDA, 0xFE, 0x46, 0x12, 0x45, 0x31, 0x26, 0x0E,
    0x59, 0x5E, 0x70, 0x9C, 0x36, 0xE8, 0x51, 0x10, 0x21, 0xAD, 0x56, 0x83, 0x28, 0x6C, 0xB2, 0xB4,
    0x20, 0xD8, 0xB4, 0xAC, 0x40, 0xC9, 0x97, 0x6C, 0xDD, 0x77, 0x80, 0x7D, 0x13, 0x47, 0x58, 0x51,
    0xC9, 0xB1, 0x7E, 0x30, 0x4F, 0xC6, 0x85, 0x48, 0x13, 0xA1, 0xB5, 0xC6, 0x18, 0x83, 0x36, 0x86,
    0x46, 0xA8, 0x99, 0xA8, 0x45, 0xCC, 0xB6, 0xEC, 0x3B, 0x26, 0x63, 0x75, 0xFD, 0x77, 0xF4, 0x00,
    0x81, 0x6D, 0xBD, 0x7A, 0x0F, 0xF8, 0xC1, 0x63, 0xDB, 0x99, 0xB2, 0x25, 0xF2, 0x52, 0x17, 0xC7,
    0xE3, 0xDC, 0x57, 0x26, 0x6B, 0xFA, 0xFA, 0x89, 0xBA, 0x26, 0xC6, 0x21, 0xA4, 0x44, 0xC8, 0xA4,
    0xC0, 0xC9, 0xF9, 0x92, 0x93, 0x07, 0x32, 0x04, 0xF2, 0x37, 0x5B, 0x52, 0x58, 0x6B, 0xC8, 0x49,
    0xCD, 0xE9, 0x4B, 0x72, 0xAC, 0xEA, 0xCB, 0xE3, 0x49, 0xC1, 0x74, 0x23, 0xE2, 0xA9, 0x03, 0xD3,
    0x14, 0x32, 0x3E, 0xA7, 0x8F, 0x54, 0x08, 0x54, 0xB2, 0x72, 0x98, 0x6B, 0xB6, 0x70, 0xCE, 0x51,
    0x29, 0xE4, 0x70, 0x08, 0xB6, 0x1F, 0x9C, 0xE5, 0xB6, 0x2D, 0x87, 0x99, 0x8C, 0x33, 0x48, 0xCF,
    0x4F, 0x6D, 0xEA, 0xF0, 0x84, 0x60, 0xB0, 0xE0, 0x31, 0x52, 0xF2, 0x7F, 0x35, 0xE0, 0xC7, 0xD7,
    0xC5, 0x4E, 0xEE, 0x56, 0x71, 0x9D, 0xB7, 0x6F, 0x5A, 0xFD, 0xCA, 0x1E, 0x30, 0x68, 0x27, 0x19,
    0x0B, 0xB3, 0x4C, 0x84, 0xEA, 0xD2, 0x6A, 0x53, 0xBF, 0x65, 0xAA, 0x1E, 0xD2, 0x8C, 0x35, 0xDA,
    0xD8, 0x84, 0x65, 0x9D, 0x88, 0xB3, 0x16, 0x63, 0x1D, 0x91, 0xB1, 0xBF, 0xB6, 0xB4, 0xA2, 0x88,
    0x2C, 0x11, 0x67, 0x2E, 0xCD, 0xB1, 0xBA, 0x37, 0x07, 0xCE, 0x11, 0x6B, 0x43, 0x29, 0x50, 0x9C,
    0x73, 0x42, 0x1F, 0xA7, 0x2D, 0x2D, 0xA3, 0x70, 0x98, 0x74, 0xEC, 0x42, 0xE0, 0x53, 0xCA, 0x66,
    0x98, 0xAB, 0x37, 0xA9, 0x37, 0x5B, 0x9C, 0x3C, 0x54, 0xE2, 0xCC, 0x65, 0x79, 0x6C, 0x73, 0x96,
    0x38, 0x0C, 0xD1, 0x5A, 0xA3, 0xB5, 0x25, 0x8C, 0x0D, 0x93, 0xF5, 0x88, 0x99, 0xA6, 0x3E, 0xBD,
    0xAA, 0xE5, 0xBB, 0xAF, 0x7D, 0xF6, 0x1A, 0xA1, 0xCC, 0xB1, 0x5E, 0x70, 0x8C, 0xE9, 0xA6, 0x1B,
    0x31, 0xF7, 0x3E, 0x77, 0x84, 0xDE, 0x9C, 0x2A, 0x6E, 0x3B, 0x14, 0x7E, 0xFD, 0xE0, 0x5C, 0xF4,
    0x8E, 0x89, 0x5A, 0x8C, 0x41, 0x20, 0x94, 0x48, 0x62, 0x5F, 0x08, 0x1C, 0x82, 0x52, 0x46, 0x72,
    0x62, 0x7F, 0x8E, 0x5F, 0xCF, 0x01, 0x1C, 0xC6, 0x68, 0x7A, 0x7C, 0xC3, 0x79, 0x2B, 0x4A, 0x8C,
    0xF4, 0xE4, 0xB0, 0xCE, 0xE1, 0x52, 0xE9, 0x56, 0x31, 0x36, 0x1A, 0x29, 0x25, 0x9E, 0x94, 0x38,
    0xE7, 0x90, 0x52, 0x72, 0x60, 0x72, 0x8A, 0x17, 0xC6, 0x0E, 0x72, 0xEE, 0x29, 0xEB, 0x90, 0x42,
    0xF0, 0xBD, 0xAD, 0xE3, 0xDC, 0xFF, 0x62, 0x1D, 0x82, 0x22, 0x88, 0xA4, 0x1E, 0x51, 0x02, 0x06,
    0x0B, 0x3E, 0x2B, 0x2B, 0xC1, 0xF6, 0x01, 0x3F, 0xBE, 0x26, 0x76, 0x62, 0x97, 0x98, 0x1D, 0xE3,
    0x0F, 0x2E, 0x3D, 0xFB, 0xF8, 0x1E, 0xD0, 0x9B, 0xBF, 0x86, 0xC3, 0x35, 0xCD, 0x4B, 0x35, 0x73,
    0x66, 0xB5, 0x19, 0x5F, 0x38, 0x53, 0x0D, 0x09, 0x23, 0xDD, 0xB1, 0xBA, 0xD6, 0x36, 0x15, 0x43,
    0x14, 0x1B, 0xC2, 0x58, 0x13, 0xC5, 0xE6, 0x35, 0x8A, 0xA6, 0x15, 0x86, 0xE4, 0x08, 0x39, 0x67,
    0x24, 0xCF, 0xD2, 0x72, 0x06, 0x6D, 0x0C, 0xD6, 0xDA, 0x8E, 0x98, 0xF4, 0xBD, 0xB3, 0x06, 0x09,
    0x34, 0x5A, 0x2D, 0x9A, 0x61, 0x88, 0x73, 0x0E, 0xA3, 0x35, 0x4B, 0x2A, 0x3D, 0xAC, 0x18, 0x1A,
    0x24, 0xD6, 0x1A, 0xE1, 0x2C, 0x67, 0x8E, 0x56, 0x28, 0xAA, 0x98, 0x28, 0x6C, 0xA5, 0x5E, 0x60,
    0x08, 0x63, 0xC3, 0x54, 0x3D, 0x64, 0xBA, 0x19, 0xAF, 0x6B, 0x38, 0xEF, 0xF7, 0x0E, 0xAC, 0x18,
    0x81, 0xB0, 0x3E, 0x0F, 0xEF, 0x31, 0xA5, 0xDB, 0xE3, 0x7B, 0x9F, 0xE0, 0x6D, 0xA7, 0x0D, 0xCA,
    0x5F, 0xBC, 0x30, 0xF5, 0x81, 0xC3, 0x33, 0xAD, 0x4B, 0x27, 0x6B, 0x11, 0xB1, 0x4D, 0x0A, 0x1E,
    0xE7, 0x1C, 0xB6, 0x2D, 0xD6, 0x82, 0x75, 0x94, 0x32, 0x49, 0xCC, 0x69, 0x6B, 0x31, 0xAF, 0x52,
    0xE2, 0x58, 0x93, 0x17, 0x11, 0xE7, 0x9F, 0x50, 0x62, 0xB4, 0x92, 0xEF, 0x58, 0xBE, 0x9B, 0x80,
    0xB6, 0x27, 0xB4, 0xBF, 0x53, 0x42, 0xD2, 0x88, 0x22, 0xAC, 0x73, 0x28, 0x29, 0xB1, 0xC6, 0xD0,
    0x57, 0xCA, 0x03, 0x82, 0x5D, 0x07, 0x8F, 0xD0, 0x88, 0x2D, 0x4F, 0xEE, 0x9D, 0xA2, 0x6E, 0x14,
    0x4E, 0x48, 0xAC, 0x75, 0x29, 0x91, 0x16, 0x4F, 0x08, 0x59, 0x0C, 0x84, 0xBF, 0x7C, 0xF2, 0xC0,
    0x5D, 0x3A, 0xD7, 0xD7, 0x3A, 0xE3, 0xC4, 0xE5, 0xDC, 0xF7, 0x93, 0x9F, 0x00, 0x30, 0x6F, 0xFE,
    0xAA, 0xB6, 0x34, 0x77, 0x3E, 0x7D, 0x88, 0x83, 0x73, 0xE1, 0x92, 0x5A, 0x23, 0xBA, 0x64, 0xA6,
    0x16, 0xD2, 0x0A, 0x63, 0x9C, 0x92, 0x08, 0x27, 0x3B, 0x09, 0xB0, 0x3D, 0xA7, 0x5A, 0x63, 0xA9,
    0xB5, 0x62, 0x8A, 0x19, 0x85, 0x7B, 0x95, 0xC5, 0xBF, 0xB3, 0x86, 0x9C, 0x88, 0x79, 0xE3, 0xCA,
    0x32, 0x2B, 0x2A, 0x39, 0x8C, 0xB5, 0xC9, 0xE7, 0x29, 0x01, 0xC7, 0x86, 0x40, 0x5A, 0xFD, 0x09,
    0x41, 0xDE, 0x0F, 0x68, 0xE9, 0x98, 0x50, 0x08, 0x02, 0x25, 0xA9, 0xB7, 0x22, 0xB6, 0x1F, 0x38,
    0x48, 0x23, 0x76, 0x6C, 0xDE, 0x35, 0xC9, 0x44, 0xCD, 0x21, 0xB2, 0x60, 0xB5, 0x49, 0xA2, 0xDB,
    0x81, 0xC1, 0x31, 0x5D, 0x83, 0x5A, 0x5E, 0xBD, 0x3E, 0xEF, 0xAB, 0x0D, 0xDA, 0x8A, 0x07, 0x97,
    0xAE, 0xDF, 0xD4, 0xB9, 0xF7, 0x3C, 0x02, 0x4A, 0xD9, 0xA5, 0x7C, 0xFE, 0xBE, 0x47, 0x30, 0xC6,
    0x9E, 0x36, 0x5B, 0x0F, 0xD7, 0xD4, 0x1A, 0x21, 0x51, 0x6C, 0x91, 0x4E, 0x21, 0x9C, 0x03, 0xE9,
    0xD2, 0xF9, 0xBF, 0xDD, 0xC7, 0x11, 0xCC, 0xD4, 0x05, 0x81, 0x08, 0x5E, 0xD5, 0xE2, 0xC7, 0x59,
    0x43, 0x40, 0xC4, 0xD9, 0xAB, 0x4B, 0xAC, 0xEE, 0xCF, 0x77, 0x80, 0xB5, 0xDD, 0x5F, 0x00, 0xDA,
    0x18, 0x62, 0xAD, 0xF1, 0x3D, 0x6F, 0x1E, 0x78, 0x21, 0x04, 0xCE, 0x19, 0x7C, 0x21, 0xF0, 0x94,
    0x62, 0xA6, 0xD1, 0xE4, 0xC1, 0x67, 0x77, 0xD3, 0x34, 0x8A, 0xC7, 0xF6, 0xCE, 0xF2, 0x52, 0x1D,
    0xBC, 0x6C, 0x19, 0x61, 0x00, 0x6B, 0x8E, 0xA6, 0x37, 0xE7, 0xA8, 0x3A, 0xCB, 0x6C, 0xC3, 0xEF,
    0xAB, 0x54, 0x32, 0xE7, 0xE9, 0x33, 0x56, 0x3E, 0x68, 0x6F, 0x7F, 0x72, 0x71, 0x02, 0x76, 0x1E,
    0xDE, 0xC3, 0xDA, 0xB5, 0x9F, 0xE6, 0x33, 0xDF, 0x7E, 0xD7, 0x59, 0xD5, 0x7A, 0x58, 0x6A, 0x34,
    0x23, 0x34, 0x02, 0x89, 0x43, 0x38, 0x09, 0x52, 0x22, 0x84, 0x9C, 0xD7, 0xE0, 0x98, 0xAE, 0x59,
    0x8A, 0xBE, 0x40, 0xBD, 0x42, 0x26, 0x74, 0xD6, 0xA2, 0x6C, 0xC4, 0xA6, 0x55, 0x45, 0x4E, 0x19,
    0x2E, 0xE2, 0xAC, 0xE5, 0x70, 0xB5, 0xCE, 0xC1, 0xA9, 0x19, 0x96, 0x0F, 0xF6, 0x91, 0xF5, 0x3C,
    0xF6, 0x1F, 0x99, 0x62, 0xC7, 0xD8, 0x21, 0xF2, 0x19, 0x9F, 0xB3, 0xD7, 0xAD, 0x86, 0x2E, 0xF0,
    0x6D, 0x32, 0xA4, 0x94, 0x60, 0x0C, 0xB3, 0xF5, 0x26, 0xFB, 0xA7, 0x1A, 0xEC, 0x98, 0x74, 0x1C,
    0x6A, 0x2A, 0x94, 0x9F, 0xC7, 0x38, 0x0F, 0x8C, 0x65, 0xDE, 0x5A, 0xD4, 0x39, 0x9A, 0x06, 0x66,
    0x1A, 0xA1, 0x18, 0xCA, 0x8B, 0xB3, 0x46, 0x1E, 0xFE, 0x65, 0xBE, 0xB6, 0x6C, 0x6D, 0x63, 0xD1,
    0x24, 0xB8, 0xEB, 0x50, 0x95, 0xDD, 0xBB, 0x3F, 0x9C, 0x0B, 0xC3, 0xF8, 0xB4, 0x6A, 0xAD, 0x45,
    0x2B, 0x8C, 0x3A, 0x09, 0x25, 0x8E, 0x0D, 0x3A, 0xD6, 0xC9, 0xFB, 0x38, 0x11, 0x13, 0x6B, 0xAA,
    0x8D, 0x88, 0xC9, 0x6A, 0x8B, 0x28, 0xD6, 0x84, 0xD1, 0xF1, 0x24, 0x26, 0x6C, 0x35, 0xD8, 0x30,
    0xE4, 0xF3, 0xFA, 0x91, 0x12, 0xCE, 0x59, 0xB4, 0xB5, 0xFC, 0xEC, 0x99, 0xE7, 0xF8, 0x97, 0xFB,
    0x1F, 0xE7, 0xB1, 0x1D, 0xFB, 0x88, 0xB4, 0xE6, 0xBE, 0x67, 0x76, 0x72, 0xFF, 0x73, 0x63, 0x84,
    0x5A, 0xE0, 0x8C, 0xC1, 0xA6, 0x9E, 0x91, 0xE8, 0xA0, 0x3B, 0x7A, 0x5A, 0x6B, 0x29, 0xE7, 0x72,
    0x28, 0x95, 0xE1, 0x70, 0x55, 0x63, 0x45, 0x06, 0xE3, 0x64, 0x92, 0x9C, 0xDB, 0x7A, 0xB6, 0x45,
    0x27, 0x3A, 0xCC, 0xD5, 0x43, 0x42, 0xED, 0x4E, 0xCE, 0x0D, 0xAD, 0xEE, 0x0F, 0xCA, 0x83, 0x8B,
    0x7B, 0xC0, 0xBE, 0x23, 0x75, 0xE6, 0x9A, 0x71, 0xB9, 0xDE, 0x8C, 0x56, 0xD7, 0x9B, 0x11, 0x51,
    0xAC, 0xC1, 0x3A, 0xA4, 0x73, 0x08, 0xA5, 0x40, 0x0A, 0x84, 0xB4, 0x2C, 0x9C, 0x3D, 0x27, 0xE6,
    0x42, 0x3C, 0x01, 0xFE, 0x22, 0xCB, 0x41, 0xE7, 0x1C, 0x56, 0x87, 0x6C, 0x18, 0xF6, 0x39, 0x6F,
    0x55, 0x05, 0x81, 0xC3, 0x68, 0x8B, 0x13, 0x82, 0x6C, 0x90, 0x65, 0xC3, 0xAA, 0x13, 0x58, 0xBD,
    0x64, 0x80, 0x83, 0x33, 0x55, 0x7C, 0x3F, 0xE0, 0xCC, 0xB5, 0x2B, 0x58, 0xD6, 0x57, 0xC6, 0xA4,
    0x6E, 0xEC, 0x52, 0xE0, 0x5E, 0x1A, 0x12, 0x52, 0x0A, 0x0E, 0x4C, 0x4E, 0xF3, 0xC4, 0xCE, 0xFD,
    0xBC, 0xFE, 0x84, 0x11, 0x9E, 0x3A, 0xD0, 0xE0, 0x70, 0x2B, 0x46, 0xFA, 0x92, 0x45, 0xEB, 0xBA,
    0x34, 0xA7, 0xD4, 0x9A, 0x50, 0x6F, 0xC5, 0x4B, 0xAC, 0x63, 0xD4, 0x58, 0xB7, 0x3F, 0xD2, 0x86,
    0xC0, 0x53, 0xF3, 0x09, 0x68, 0x45, 0x31, 0x51, 0x20, 0x07, 0xEA, 0xAD, 0x78, 0xB8, 0xD1, 0x8C,
    0x88, 0x63, 0x8D, 0x74, 0x0E, 0x9B, 0xDE, 0xA8, 0x93, 0x04, 0x17, 0x0C, 0xA4, 0xB5, 0xE1, 0xB0,
    0x70, 0x0C, 0x14, 0x03, 0x04, 0xDD, 0x6D, 0x30, 0x87, 0xD1, 0x11, 0xAB, 0x7A, 0x04, 0x97, 0xAC,
    0xED, 0xC5, 0x17, 0x0E, 0xAD, 0x93, 0xE5, 0xAB, 0x76, 0x50, 0xCC, 0x7A, 0x5C, 0xBC, 0x71, 0x2D,
    0x47, 0xE6, 0x6A, 0xFC, 0x62, 0xEB, 0x6E, 0xCE, 0x5D, 0xB7, 0x92, 0x91, 0x4A, 0x21, 0x99, 0x51,
    0x8C, 0xED, 0xB8, 0xBC, 0x52, 0xAA, 0x13, 0x0A, 0x5B, 0x5F, 0x1C, 0xE3, 0xD1, 0x1D, 0xBB, 0x39,
    0xFF, 0xD4, 0x93, 0x18, 0x1D, 0x2A, 0x53, 0x50, 0x86, 0x28, 0x6C, 0xE1, 0x09, 0x6F, 0x71, 0x02,
    0x70, 0x38, 0xEB, 0x68, 0x86, 0x8E, 0x46, 0x18, 0xE7, 0x6B, 0xAD, 0x68, 0xB4, 0x15, 0xE9, 0x4E,
    0xD2, 0x9E, 0x47, 0x80, 0xB3, 0x0E, 0x9C, 0x1B, 0x6C, 0x85, 0x51, 0x3E, 0x0C, 0x23, 0x74, 0x6C,
    0x69, 0xF3, 0x2A, 0x9C, 0x4A, 0x92, 0xA0, 0x68, 0xCF, 0x02, 0xF3, 0xD3, 0xDE, 0x74, 0xD5, 0x60,
    0x8D, 0xA5, 0x27, 0xE7, 0xA7, 0x39, 0xD2, 0x61, 0x4D, 0xCC, 0x70, 0xCE, 0x72, 0xF9, 0xBA, 0x61,
    0x8A, 0x3E, 0x44, 0x71, 0xDC, 0x89, 0x67, 0x84, 0xC0, 0x13, 0x82, 0xF1, 0xA9, 0x59, 0x1E, 0x7A,
    0x76, 0x37, 0x67, 0x9D, 0x74, 0x02, 0x4B, 0x7A, 0x0A, 0x84, 0x5A, 0x23, 0x21, 0x99, 0xEE, 0x94,
    0x42, 0x4A, 0x89, 0x94, 0x02, 0x63, 0x2D, 0x0F, 0x6C, 0xDD, 0xC1, 0xF6, 0x7D, 0x2F, 0x71, 0xF9,
    0x1B, 0x36, 0xB0, 0x7A, 0xA8, 0x97, 0xF1, 0xD9, 0x1A, 0x47, 0x66, 0xAB, 0x18, 0x53, 0x80, 0xD8,
    0x2C, 0xA2, 0x97, 0xE8, 0x10, 0xD0, 0xC2, 0xD2, 0x0C, 0x75, 0x50, 0x6F, 0xE9, 0xC1, 0xBD, 0x13,
    0xB5, 0xCE, 0xE2, 0x70, 0x1E, 0x01, 0x49, 0xB9, 0xE9, 0x7A, 0x1A, 0xCD, 0xD8, 0x8F, 0xA2, 0x18,
    0x6D, 0xDC, 0xD1, 0xFE, 0xBD, 0x03, 0xA4, 0x4D, 0x93, 0xE0, 0xD1, 0x59, 0xA0, 0x9B, 0xE9, 0xC9,
    0xAA, 0x49, 0xCA, 0xD8, 0xAC, 0x87, 0xB3, 0x9A, 0xA2, 0x8C, 0xB8, 0xFC, 0xA4, 0x41, 0x86, 0xF2,
    0x8A, 0x28, 0xD6, 0x1D, 0xF0, 0xD6, 0x5A, 0x02, 0xDF, 0xA3, 0x11, 0xC5, 0xDC, 0xFD, 0xE8, 0x36,
    0xAE, 0xDA, 0x74, 0x2A, 0xFD, 0xA5, 0x1C, 0x5F, 0xFA, 0xE1, 0x66, 0x7A, 0xF3, 0x19, 0xAE, 0x3D,
    0xF7, 0x74, 0x02, 0xA5, 0x10, 0x29, 0xF8, 0x7A, 0x2B, 0xE2, 0x07, 0x8F, 0x6D, 0xE1, 0xF0, 0x4C,
    0x8D, 0xB7, 0x9D, 0xFB, 0x3A, 0x46, 0xFA, 0xCA, 0xEC, 0x99, 0x98, 0xE5, 0xAB, 0x3F, 0x7D, 0x9A,
    0xF1, 0x19, 0x8D, 0xCC, 0x95, 0x70, 0xC6, 0x1C, 0xA3, 0x4F, 0x32, 0x15, 0x3A, 0x9C, 0xB3, 0xC4,
    0x56, 0xD0, 0x0A, 0x63, 0xA9, 0xB5, 0xE9, 0xFD, 0xFB, 0x3B, 0xB7, 0xF2, 0xD7, 0xD7, 0x9C, 0x7A,
    0x2C, 0x01, 0x61, 0xA4, 0xD1, 0xC6, 0x64, 0xA7, 0xE7, 0x1A, 0xAA, 0x5E, 0x6F, 0xE1, 0x94, 0x4A,
    0x3C, 0xC0, 0x81, 0xB0, 0x0E, 0x94, 0x44, 0x08, 0x97, 0x8E, 0xB3, 0xB8, 0xBB, 0x4D, 0x6A, 0x4D,
    0xA3, 0x29, 0xE8, 0xCD, 0x68, 0x2E, 0xDE, 0xD8, 0xC7, 0xEA, 0xFE, 0x0C, 0xB1, 0x8E, 0x3B, 0xD7,
    0x0B, 0x21, 0xF0, 0x3C, 0x45, 0x23, 0xB6, 0x6C, 0xD9, 0x73, 0x08, 0x27, 0x3D, 0xEA, 0x51, 0xCC,
    0xB6, 0xAD, 0xE3, 0x4C, 0xD7, 0x22, 0x7A, 0x8B, 0x05, 0x3C, 0xCF, 0x47, 0x4A, 0x81, 0x92, 0x92,
    0xC3, 0xB3, 0x55, 0x6E, 0x7F, 0xE0, 0x71, 0x10, 0x8A, 0x3F, 0xB8, 0xF0, 0x0D, 0xF4, 0x17, 0xF3,
    0x3C, 0xB1, 0x73, 0x8C, 0xAF, 0xFD, 0xF4, 0x57, 0xEC, 0x99, 0x15, 0xF8, 0x85, 0x41, 0x9C, 0x93,
    0xA0, 0xCD, 0x22, 0x3A, 0x25, 0x5D, 0x1B, 0xE7, 0x2C, 0x42, 0xC0, 0x6C, 0x3D, 0xA4, 0x15, 0xE9,
    0x7C, 0xF4, 0xF5, 0x2F, 0xE3, 0xBE, 0x7A, 0xFD, 0xB1, 0x04, 0xE0, 0x2C, 0x38, 0x27, 0xC3, 0x48,
    0x73, 0x64, 0xA6, 0x4E, 0xA1, 0x90, 0x21, 0x48, 0xEF, 0x23, 0xAC, 0x43, 0xD8, 0xA4, 0x18, 0x7A,
    0xB9, 0xB6, 0x8F, 0x73, 0x96, 0xA8, 0xDE, 0xE4, 0xE2, 0x0D, 0x15, 0x36, 0xAD, 0x28, 0xA7, 0x45,
    0xCD, 0x51, 0xF0, 0x8D, 0x48, 0xF3, 0xE3, 0x87, 0xB7, 0x70, 0x70, 0xAE, 0xC5, 0x29, 0x2B, 0x47,
    0x58, 0xB3, 0x74, 0x80, 0x6A, 0xA3, 0xC9, 0x8A, 0xC1, 0x5E, 0xCE, 0x3B, 0x65, 0x35, 0xF9, 0xC0,
    0x43, 0x09, 0x90, 0x42, 0xB0, 0x63, 0xEC, 0x10, 0xB7, 0xFE, 0xEC, 0x51, 0x46, 0x06, 0xFB, 0xB8,
    0xEE, 0xFC, 0x33, 0x08, 0x3C, 0xC9, 0x77, 0x1F, 0xDE, 0xCA, 0x37, 0x1F, 0x7A, 0x9E, 0x19, 0x93,
    0xC7, 0xCF, 0xF7, 0x63, 0x44, 0x90, 0xEC, 0xA7, 0x61, 0x8E, 0xA7, 0x10, 0xCE, 0x5A, 0xEA, 0xA1,
    0xA6, 0x9A, 0xF7, 0xB0, 0xCE, 0x49, 0xD8, 0xDF, 0x89, 0x14, 0x6F, 0xE1, 0xC5, 0x02, 0x17, 0x49,
    0x9C, 0x0D, 0xC3, 0x88, 0x56, 0x6C, 0xE8, 0xED, 0x15, 0xF8, 0x90, 0x14, 0x42, 0x4E, 0x21, 0xE4,
    0xCB, 0xF4, 0xBD, 0x9C, 0xC5, 0xC4, 0x2D, 0xCE, 0x5D, 0x99, 0xE3, 0x9A, 0xD7, 0x2D, 0x45, 0x89,
    0x24, 0x61, 0x4A, 0x29, 0x13, 0xCB, 0x2B, 0xC5, 0x0B, 0x2F, 0x1D, 0xE1, 0xAE, 0x47, 0xB6, 0x93,
    0x2F, 0xF4, 0xF0, 0xEE, 0x8B, 0xCF, 0x66, 0x49, 0xC9, 0xC7, 0x51, 0x42, 0x2A, 0xD5, 0xF1, 0x5A,
    0x21, 0x24, 0x9B, 0xB7, 0xEE, 0xE0, 0xB6, 0x5F, 0x3C, 0xCE, 0xB9, 0xA7, 0x9E, 0xC4, 0x35, 0x6F,
    0x3C, 0x8D, 0xD9, 0x7A, 0x93, 0xAF, 0xFC, 0xE8, 0x49, 0xEE, 0xDD, 0x32, 0x86, 0x0E, 0xFA, 0xF0,
    0xB2, 0x3D, 0x18, 0x82, 0x14, 0xF7, 0xE2, 0xE0, 0x93, 0x54, 0xE4, 0xA8, 0x37, 0x23, 0xC2, 0x30,
    0x06, 0x5B, 0x40, 0x38, 0x17, 0x52, 0xBE, 0x36, 0x8D, 0xE9, 0x85, 0x04, 0xE0, 0x10, 0x82, 0x9A,
    0x12, 0x4E, 0x0B, 0x2C, 0xCD, 0x96, 0x66, 0x7A, 0x56, 0x50, 0x2E, 0x83, 0x9F, 0xF1, 0x93, 0x30,
    0x90, 0xB2, 0xD3, 0xA9, 0x59, 0xF8, 0x5B, 0x1D, 0x87, 0x9C, 0x3C, 0xA8, 0xF8, 0xE3, 0xF3, 0x57,
    0xD1, 0x5B, 0xCC, 0x62, 0xEC, 0xD1, 0x84, 0x24, 0x84, 0xC0, 0x5A, 0xCB, 0xCA, 0xE1, 0x01, 0xDE,
    0x79, 0xE1, 0x26, 0xF2, 0xF9, 0x1C, 0x7D, 0x85, 0x00, 0xEB, 0x1C, 0x52, 0x29, 0x84, 0x48, 0xE2,
    0x3D, 0xD2, 0x86, 0x6F, 0xDF, 0xFF, 0x4B, 0xEE, 0x7D, 0x62, 0x3B, 0xEF, 0xBA, 0xF4, 0x8D, 0x5C,
    0xF6, 0xFA, 0x93, 0xD9, 0xBA, 0x67, 0x9C, 0x2F, 0xFF, 0xF0, 0x31, 0x9E, 0x19, 0xAF, 0xA3, 0x72,
    0x03, 0x48, 0xBF, 0x84, 0xC1, 0x7B, 0x79, 0xCB, 0xA7, 0xE0, 0x9B, 0xA1, 0xA6, 0xDA, 0x08, 0xC9,
    0x28, 0xF0, 0xA4, 0x73, 0x52, 0x30, 0x77, 0xD5, 0x47, 0x2E, 0x46, 0xA4, 0x5E, 0x79, 0x8C, 0x07,
    0x38, 0xEB, 0x26, 0x03, 0x4F, 0x46, 0xCA, 0x39, 0x30, 0x9A, 0x30, 0x0C, 0x99, 0xAD, 0x42, 0xC1,
    0xE6, 0x08, 0x32, 0x3E, 0x42, 0x2A, 0x90, 0xB6, 0x8B, 0xE3, 0x24, 0x49, 0x58, 0x1D, 0x33, 0x98,
    0x33, 0xFC, 0xE9, 0xC5, 0xEB, 0x58, 0x31, 0x58, 0x46, 0x1B, 0x8B, 0x27, 0xE7, 0x13, 0x04, 0x82,
    0xA2, 0xE7, 0x71, 0xED, 0x79, 0x1B, 0xD3, 0x69, 0x2D, 0xB1, 0xB6, 0x10, 0x49, 0xBC, 0x4F, 0x57,
    0xEB, 0x7C, 0xE9, 0xCE, 0x9F, 0xF0, 0xFC, 0xFE, 0x43, 0xFC, 0xC5, 0x75, 0x57, 0xB0, 0x71, 0xF5,
    0x08, 0x77, 0x3F, 0xBC, 0x95, 0xFF, 0xFD, 0x93, 0xA7, 0x38, 0xD4, 0xF4, 0xF1, 0xF3, 0x43, 0x38,
    0x2F, 0x8F, 0x71, 0x32, 0xA9, 0xF8, 0xDC, 0xC2, 0x9A, 0x24, 0x19, 0x43, 0x08, 0xB0, 0xD6, 0xD1,
    0x8C, 0x74, 0xB2, 0x96, 0x31, 0x06, 0x25, 0x15, 0x81, 0x14, 0x71, 0xA0, 0xC4, 0x91, 0x37, 0x9D,
    0xBA, 0x94, 0xB6, 0x0D, 0xE7, 0x11, 0x90, 0xF1, 0x15, 0xD9, 0x40, 0x4D, 0xE4, 0x33, 0x6A, 0xCA,
    0x97, 0x0C, 0x38, 0xA3, 0x41, 0x0B, 0xE2, 0x50, 0x50, 0x75, 0x90, 0x33, 0x96, 0x20, 0xE3, 0x27,
    0xE5, 0x68, 0x57, 0x18, 0x58, 0x6B, 0xC8, 0x8A, 0x16, 0x7F, 0xF2, 0xA6, 0xF5, 0xBC, 0x61, 0xF5,
    0x10, 0xC6, 0x3A, 0x3C, 0x71, 0x14, 0xBD, 0x58, 0x10, 0x32, 0xF3, 0xE6, 0x76, 0x40, 0x29, 0xC5,
    0xCE, 0x03, 0x07, 0xF9, 0xEC, 0xAD, 0xF7, 0x20, 0xA4, 0xC7, 0x27, 0xDE, 0xF7, 0x4E, 0x0A, 0x19,
    0x9F, 0xCF, 0xDE, 0xFE, 0x33, 0xBE, 0xF7, 0xD8, 0x6E, 0x22, 0x59, 0xC6, 0xCB, 0x55, 0x30, 0x22,
    0x9B, 0xD4, 0xFA, 0x2F, 0x63, 0x75, 0x00, 0xE3, 0x1C, 0xAD, 0xC8, 0x10, 0xC7, 0x1A, 0x67, 0x1D,
    0xCE, 0x1A, 0x3C, 0x5F, 0x90, 0xF3, 0x65, 0xAB, 0xB7, 0x10, 0x8C, 0x6B, 0x63, 0x16, 0xAF, 0x03,
    0x86, 0x2B, 0x39, 0x56, 0x0E, 0xF7, 0xCC, 0x94, 0x72, 0xC1, 0xBE, 0x8C, 0x2F, 0x4F, 0x12, 0x46,
    0xE3, 0x84, 0xC0, 0x49, 0x81, 0x89, 0x05, 0x0D, 0xE7, 0x88, 0x8D, 0x21, 0x13, 0xF8, 0x48, 0x25,
    0x93, 0xA2, 0xC7, 0x59, 0x9C, 0x6E, 0xF2, 0xCE, 0x37, 0xAD, 0xE2, 0xF7, 0x36, 0xAD, 0x4A, 0x00,
    0x09, 0xD7, 0x01, 0xBD, 0x10, 0x7C, 0x1B, 0x78, 0xFB, 0x3B, 0x01, 0x6C, 0x7E, 0xE6, 0x59, 0x3E,
    0xFF, 0xED, 0x1F, 0xB2, 0x61, 0xCD, 0x4A, 0xDE, 0x7F, 0xED, 0x9B, 0xD9, 0x77, 0x68, 0x92, 0xBF,
    0xF9, 0xFA, 0x0F, 0x79, 0x62, 0xCF, 0x0C, 0x32, 0xDB, 0x87, 0x0C, 0x4A, 0x18, 0xFC, 0xE3, 0xBA,
    0x7C, 0x77, 0x43, 0x39, 0x36, 0x96, 0x58, 0x1B, 0xAC, 0x4D, 0x57, 0x95, 0xD6, 0x82, 0x31, 0x64,
    0x94, 0x4F, 0x39, 0xE7, 0xCF, 0x64, 0x7C, 0x6F, 0x6F, 0xE0, 0x29, 0x02, 0x4F, 0x1D, 0x4B, 0xC0,
    0x89, 0xCB, 0x7A, 0xD9, 0x74, 0xE2, 0x50, 0xF5, 0x8E, 0x9F, 0xFB, 0xCF, 0x16, 0x73, 0xFE, 0x65,
    0xC2, 0x59, 0xAC, 0x8E, 0x71, 0x32, 0x5D, 0x8D, 0x09, 0x88, 0xA3, 0xA4, 0x5E, 0xF0, 0x3C, 0x85,
    0xE7, 0x49, 0x4C, 0xDC, 0xE2, 0x8A, 0x8D, 0x43, 0xFC, 0xC9, 0x65, 0x1B, 0x08, 0x3C, 0x0F, 0xEB,
    0xE6, 0x83, 0x6F, 0x2F, 0x6D, 0x93, 0x82, 0xE6, 0xA8, 0x57, 0x48, 0x29, 0x89, 0xA2, 0x98, 0xDB,
    0xEE, 0xDB, 0xCC, 0x37, 0x7E, 0xFC, 0x20, 0xD7, 0x5D, 0xFC, 0x46, 0xAE, 0xBD, 0xF8, 0x2C, 0x7E,
    0xF4, 0xE8, 0x36, 0xBE, 0xF8, 0xBD, 0x87, 0x19, 0xAB, 0x82, 0x9F, 0x1B, 0xC4, 0x79, 0x79, 0x2C,
    0xAA, 0x03, 0xFE, 0x38, 0x5D, 0x73, 0xAC, 0x75, 0xC4, 0xC6, 0xA6, 0x79, 0xC7, 0xB5, 0xC3, 0x39,
    0x69, 0xA8, 0x58, 0x4B, 0x7F, 0x31, 0xA0, 0x9C, 0x95, 0x2F, 0xCE, 0x4E, 0x8C, 0x1F, 0x6E, 0x36,
    0x8F, 0x92, 0x38, 0x8F, 0x80, 0x4D, 0x27, 0x0E, 0xF1, 0xC7, 0xFF, 0xE3, 0xFB, 0x76, 0xDD, 0x8A,
    0xFE, 0xC7, 0x2B, 0xC5, 0x6C, 0xE4, 0x09, 0x02, 0xA3, 0x35, 0x4E, 0x26, 0xE0, 0x3B, 0x2E, 0xEF,
    0x1C, 0x91, 0xB5, 0xB4, 0x9A, 0x11, 0xA7, 0x8D, 0x16, 0xF9, 0xD0, 0x3B, 0x36, 0xD1, 0x5B, 0xCC,
    0x26, 0x71, 0xDF, 0x65, 0xF1, 0x76, 0x29, 0xDB, 0x9E, 0x05, 0x3A, 0x5E, 0x20, 0x25, 0xD3, 0xB3,
    0x73, 0x7C, 0xF1, 0xB6, 0xEF, 0xF3, 0xD0, 0x96, 0x17, 0xF8, 0x8B, 0xEB, 0xDF, 0xCA, 0xC6, 0x35,
    0xA3, 0xFC, 0xCF, 0x6F, 0xDD, 0xC7, 0xB7, 0x1F, 0x7C, 0x8E, 0x96, 0x28, 0xE2, 0x65, 0x2B, 0x58,
    0x99, 0x41, 0x58, 0x12, 0x2B, 0x2E, 0x38, 0x5C, 0x97, 0x2E, 0xD6, 0xBA, 0xA3, 0xC0, 0xA1, 0x33,
    0xF7, 0x63, 0x2D, 0xCE, 0x18, 0xF2, 0x81, 0x62, 0xA4, 0xBF, 0x40, 0x3E, 0x90, 0x4F, 0x7E, 0xEB,
    0x3F, 0x9F, 0x3B, 0xBB, 0xE6, 0xDD, 0x9F, 0x5A, 0x9C, 0x80, 0xC3, 0x33, 0x4D, 0x36, 0xAE, 0x1A,
    0x64, 0xA8, 0xAF, 0xF0, 0xC4, 0x40, 0x6F, 0xE1, 0x60, 0x36, 0x50, 0x2B, 0xC2, 0x30, 0xC2, 0xC5,
    0x02, 0x8B, 0x40, 0x72, 0x74, 0x1D, 0x60, 0x75, 0x4C, 0x7F, 0xC1, 0x71, 0xE3, 0x75, 0x67, 0xB2,
    0x7A, 0xA8, 0x27, 0xA9, 0xF1, 0x3B, 0xEB, 0xF6, 0xF9, 0x56, 0x5F, 0x08, 0x7E, 0xF7, 0x81, 0x71,
    0x3E, 0xFD, 0xF5, 0x3B, 0x98, 0x6D, 0x84, 0x7C, 0xF2, 0xCF, 0xDE, 0x4D, 0x6C, 0x1C, 0x1F, 0xFA,
    0xC7, 0x3B, 0xF8, 0xE5, 0x8E, 0x09, 0x44, 0xB6, 0x17, 0x15, 0x94, 0x92, 0x29, 0xCE, 0x42, 0xFA,
    0xE7, 0x18, 0xF4, 0x36, 0x2D, 0x71, 0xAD, 0x5B, 0xE4, 0xCB, 0xB6, 0xF5, 0x8D, 0xC1, 0x17, 0x8E,
    0x25, 0x3D, 0x39, 0xFA, 0x8B, 0x99, 0x66, 0x5F, 0xB9, 0xF8, 0xD0, 0x45, 0xFF, 0xF0, 0xA4, 0xDD,
    0xF7, 0xF0, 0x77, 0x17, 0x27, 0x60, 0xB8, 0x37, 0xCF, 0x77, 0x36, 0xEF, 0x60, 0xD3, 0xFA, 0xE5,
    0xBB, 0x1F, 0xDD, 0xBA, 0xFF, 0x91, 0x4A, 0x29, 0xB7, 0x62, 0x6E, 0xAE, 0x8E, 0xD5, 0x71, 0x52,
    0x55, 0x76, 0x7A, 0x0C, 0x86, 0x40, 0x69, 0xFE, 0xFC, 0xAD, 0x67, 0x73, 0xC1, 0xA9, 0xCB, 0x89,
    0xD3, 0x15, 0x5B, 0x27, 0xE6, 0x84, 0x40, 0x76, 0xAD, 0xE1, 0x9D, 0x4B, 0xAA, 0x47, 0x29, 0x04,
    0x8F, 0x3E, 0xB3, 0x9D, 0x4F, 0xFD, 0xEB, 0x77, 0x59, 0xB3, 0x7C, 0x29, 0x1F, 0x7C, 0xCF, 0xDB,
    0xF9, 0xE5, 0xB6, 0x17, 0xF9, 0x5F, 0xDF, 0xD9, 0xCC, 0xFE, 0x19, 0x83, 0x9F, 0x1B, 0x40, 0xB4,
    0x5D, 0x7E, 0xA1, 0xD5, 0xD3, 0xAD, 0x38, 0x97, 0xEE, 0x47, 0x1E, 0xFD, 0x23, 0xBA, 0x92, 0x80,
    0xEB, 0xAC, 0xFE, 0x9C, 0xB1, 0xF8, 0xD2, 0x31, 0x50, 0xCC, 0x30, 0x50, 0xCE, 0xD0, 0x5B, 0xCC,
    0xEC, 0x2A, 0x17, 0x82, 0x47, 0x85, 0x08, 0xF1, 0x8B, 0x95, 0xC5, 0x09, 0x00, 0xB8, 0xE2, 0x0D,
    0xAB, 0xB8, 0xEA, 0xC6, 0x5B, 0x9A, 0x97, 0x9F, 0xB9, 0xE6, 0x9E, 0xE1, 0x81, 0xD2, 0x35, 0x07,
    0x0F, 0x4E, 0x66, 0x9A, 0x51, 0x04, 0xC2, 0x75, 0xDC, 0xCE, 0xC4, 0x96, 0x6B, 0x2E, 0x58, 0xC3,
    0x1F, 0x5E, 0xB2, 0x01, 0x1D, 0xC7, 0xA9, 0x15, 0x5C, 0x7B, 0x12, 0x4A, 0x9E, 0x80, 0xEA, 0x02,
    0xDF, 0xF6, 0x8A, 0x1F, 0x3C, 0xF0, 0x18, 0x37, 0xDF, 0x79, 0x2F, 0x57, 0x5C, 0x70, 0x16, 0x6F,
    0x3A, 0x63, 0x03, 0x37, 0xDD, 0xFD, 0x10, 0xB7, 0xFE, 0x7C, 0x1B, 0x4D, 0x97, 0xC7, 0xCB, 0xF6,
    0x63, 0x65, 0x16, 0x61, 0x45, 0xE2, 0xBA, 0x8B, 0xB9, 0xFC, 0xF1, 0x1E, 0x3A, 0xE8, 0x5E, 0x03,
    0xB9, 0xD4, 0xF2, 0x0A, 0xFA, 0x0B, 0x19, 0xCA, 0x59, 0x45, 0x5F, 0x29, 0x4B, 0x4F, 0x21, 0xF3,
    0x93, 0xF7, 0x5C, 0xBC, 0x7E, 0xEC, 0xB6, 0x5F, 0xEC, 0xE0, 0xCF, 0xFE, 0xDB, 0x87, 0x8E, 0x4F,
    0xC0, 0xBE, 0xC3, 0x73, 0xFC, 0xFE, 0x9B, 0x4E, 0x61, 0xA0, 0x52, 0xB8, 0x6F, 0x74, 0xB8, 0xB2,
    0xED, 0xC5, 0x3D, 0xD9, 0x33, 0x5A, 0x47, 0x5A, 0x10, 0x77, 0x0F, 0x6D, 0x38, 0x30, 0x7E, 0x88,
    0xC3, 0xD3, 0x73, 0x0C, 0x57, 0x0A, 0x49, 0xB3, 0x22, 0xB5, 0xBA, 0x50, 0x2A, 0x59, 0x09, 0x76,
    0x85, 0x41, 0x18, 0xC5, 0xDC, 0x72, 0xCF, 0x7D, 0xFC, 0xE2, 0x89, 0xAD, 0xBC, 0xFF, 0xFA, 0xAB,
    0xC9, 0x64, 0x73, 0xFC, 0xD5, 0x97, 0xEE, 0xE4, 0xE1, 0xE7, 0x0F, 0x23, 0x32, 0x15, 0x54, 0xA6,
    0x88, 0x13, 0xFE, 0xD1, 0xD8, 0x7D, 0xAD, 0x47, 0x1A, 0x07, 0x6D, 0x0F, 0xCC, 0x7A, 0x92, 0xBE,
    0x62, 0x40, 0xCE, 0x13, 0x94, 0x32, 0x1E, 0x83, 0x3D, 0xB9, 0x89, 0x4A, 0x31, 0xFB, 0x9D, 0x4F,
    0x7F, 0xFB, 0x51, 0xF3, 0xF5, 0x9F, 0x1F, 0x9C, 0xF7, 0xD3, 0x63, 0x4A, 0xBA, 0x93, 0x57, 0xF4,
    0xB3, 0x62, 0xB8, 0xC2, 0xBB, 0x2E, 0x39, 0xE5, 0xC0, 0xC8, 0x50, 0xCF, 0xAD, 0x23, 0x4B, 0x7A,
    0x6D, 0xE0, 0x49, 0x9C, 0x8E, 0xB1, 0x71, 0x8C, 0x8B, 0x23, 0x84, 0x73, 0x3C, 0xBC, 0x65, 0x2F,
    0x9F, 0xFC, 0xDA, 0xF7, 0xA9, 0x35, 0x93, 0x56, 0xB5, 0x6B, 0x2B, 0x61, 0x8F, 0x6E, 0x62, 0x00,
    0xCC, 0x56, 0x6B, 0x7C, 0xE1, 0x5F, 0xEF, 0x60, 0xE7, 0xBE, 0x71, 0x3E, 0xFA, 0xBE, 0x7F, 0xC7,
    0xD8, 0x54, 0x9D, 0x0F, 0x7C, 0xEE, 0x76, 0x36, 0x3F, 0x37, 0x89, 0xCC, 0xF6, 0x23, 0xFD, 0x12,
    0x4E, 0x78, 0x09, 0x78, 0x6B, 0xE7, 0x09, 0xAF, 0x20, 0xDD, 0xD7, 0x38, 0x63, 0xC0, 0x18, 0x8A,
    0x81, 0x64, 0xB0, 0x14, 0x90, 0x55, 0xE0, 0x0B, 0x47, 0x7F, 0x4F, 0x8E, 0x81, 0x9E, 0xFC, 0x8F,
    0xD7, 0x2C, 0xEB, 0x7D, 0x6C, 0xB0, 0x27, 0xC7, 0x27, 0xDE, 0xB3, 0x7E, 0x1E, 0xDE, 0x45, 0x9F,
    0x68, 0x78, 0xDB, 0x7B, 0x6E, 0xE0, 0xEC, 0x2B, 0xDF, 0xC3, 0x60, 0x6F, 0x71, 0xAC, 0xD6, 0x08,
    0x2F, 0x9A, 0x98, 0x9C, 0x5D, 0x5A, 0xAF, 0x37, 0xD2, 0x8D, 0xCB, 0xA4, 0x06, 0x12, 0x52, 0xF2,
    0xC2, 0x9E, 0x71, 0xB0, 0x31, 0xE7, 0x9C, 0xB6, 0x16, 0x29, 0x8E, 0xBA, 0xBC, 0x73, 0x16, 0xA5,
    0x14, 0x63, 0x87, 0x27, 0xF9, 0xD2, 0xAD, 0x77, 0xB1, 0x6C, 0x68, 0x80, 0x6B, 0x2F, 0xBF, 0x88,
    0x7F, 0xFE, 0xFE, 0xC3, 0x7C, 0xEE, 0xF6, 0xCD, 0x4C, 0xB5, 0x02, 0xFC, 0x6C, 0x2F, 0x42, 0x65,
    0x93, 0x4D, 0x0C, 0x77, 0x34, 0x7E, 0x5F, 0xB3, 0xA4, 0x44, 0x28, 0x1C, 0xBD, 0x85, 0x80, 0xDE,
    0x82, 0x8F, 0x87, 0x45, 0x3A, 0x43, 0x4F, 0x21, 0x60, 0xF5, 0x48, 0xFF, 0xC4, 0xE8, 0x70, 0xE5,
    0xBF, 0xEE, 0x1A, 0x9B, 0x7A, 0xE1, 0x5D, 0x97, 0xAC, 0xE7, 0x8C, 0x13, 0x97, 0xBD, 0xBC, 0x07,
    0x00, 0xBC, 0xEB, 0xD2, 0x53, 0x39, 0x61, 0x49, 0x85, 0xF7, 0xFF, 0xF9, 0x97, 0xF7, 0xAC, 0x1C,
    0xE9, 0xFF, 0xA7, 0x55, 0xA3, 0x43, 0xAD, 0x5C, 0xC6, 0x07, 0x13, 0xE3, 0x74, 0x84, 0x8B, 0x63,
    0x30, 0x60, 0xC8, 0x72, 0xD3, 0x9D, 0x8F, 0x70, 0xF3, 0x5D, 0x9B, 0x41, 0xC8, 0xD4, 0xF2, 0x1A,
    0x29, 0x24, 0xDB, 0x76, 0xED, 0xE5, 0x96, 0xBB, 0x7F, 0xC2, 0x65, 0xE7, 0x9E, 0xC9, 0xC6, 0x53,
    0x4E, 0xE6, 0x23, 0x9F, 0xBF, 0x9D, 0xAF, 0xFE, 0xE0, 0x57, 0x84, 0xA2, 0x8C, 0x97, 0xE9, 0x01,
    0x19, 0x24, 0xC1, 0xFB, 0x2A, 0xAD, 0x8D, 0x4D, 0x4A, 0x5F, 0xD7, 0x65, 0x7D, 0x67, 0x4C, 0xD2,
    0x66, 0xF7, 0x04, 0xC3, 0x3D, 0x59, 0x2A, 0x39, 0x0F, 0x65, 0x0D, 0xC2, 0x18, 0xB2, 0x9E, 0x60,
    0x49, 0x5F, 0x89, 0xA1, 0x4A, 0xF1, 0xD6, 0xD3, 0x4F, 0x5C, 0xFA, 0xE0, 0xE8, 0x50, 0x99, 0x07,
    0xB6, 0x8C, 0x1D, 0x83, 0xF5, 0xB8, 0xCF, 0xB4, 0x5C, 0xF1, 0xCE, 0xF7, 0x71, 0xE9, 0xA5, 0x1B,
    0x59, 0x39, 0xD2, 0xBF, 0xAB, 0xD6, 0x08, 0xD7, 0xCF, 0xCC, 0xD5, 0x4F, 0x99, 0x9B, 0xAD, 0x61,
    0x8D, 0xE9, 0x2C, 0x71, 0x85, 0x90, 0xC4, 0x16, 0x1E, 0xDF, 0xF6, 0x02, 0xA5, 0xBC, 0xCF, 0xE9,
    0x27, 0xAD, 0x40, 0x08, 0xC1, 0xA3, 0x5B, 0x9F, 0x67, 0xDB, 0xCE, 0x3D, 0x5C, 0x7D, 0xE9, 0x05,
    0x3C, 0xBB, 0x77, 0x82, 0xBF, 0xFE, 0xE2, 0x77, 0xD9, 0xB6, 0x7F, 0x0E, 0x2F, 0xD7, 0x8B, 0xF4,
    0xF2, 0x20, 0xD5, 0xC2, 0xCC, 0xB6, 0xE0, 0x38, 0x4E, 0x93, 0xBD, 0x63, 0xF9, 0x84, 0x80, 0x40,
    0x0A, 0x7A, 0x0B, 0x01, 0x7D, 0xC5, 0x0C, 0x19, 0x05, 0xC2, 0x1A, 0xB0, 0x06, 0x5F, 0x3A, 0x06,
    0x7B, 0x0B, 0xAC, 0x5A, 0x3E, 0xF0, 0xCC, 0x09, 0x4B, 0x7B, 0xFF, 0x6A, 0xEF, 0x4B, 0xD3, 0x87,
    0x8E, 0xCC, 0x35, 0xF8, 0xD3, 0xAB, 0xDF, 0x70, 0xCC, 0x2D, 0x5F, 0xB6, 0x97, 0xED, 0x9C, 0xE3,
    0x23, 0x5F, 0xF8, 0x01, 0xC3, 0xFD, 0xE5, 0x33, 0x1E, 0x7B, 0x66, 0xF7, 0x2D, 0x0F, 0x3F, 0xF1,
    0xDC, 0xBA, 0x89, 0x89, 0x69, 0xAC, 0x13, 0xA0, 0x14, 0x42, 0x79, 0x08, 0x4F, 0x62, 0x6D, 0x4C,
    0xCE, 0x0B, 0xB9, 0xE1, 0xBA, 0xF3, 0x39, 0xF3, 0x94, 0x15, 0xF8, 0x9E, 0x60, 0x74, 0x64, 0x19,
    0x37, 0xDD, 0xFE, 0x33, 0x6E, 0xB9, 0xF7, 0x49, 0x42, 0x0A, 0xA8, 0x6C, 0x19, 0x21, 0x03, 0xE8,
    0xB4, 0xD5, 0x5F, 0xE5, 0x86, 0x62, 0x17, 0x49, 0xED, 0xFA, 0xC2, 0x93, 0x82, 0x62, 0xCE, 0xA7,
    0x9C, 0x0B, 0x08, 0x94, 0x40, 0xB8, 0xC4, 0x3B, 0x84, 0xB5, 0x28, 0x61, 0xA9, 0x14, 0x73, 0xAC,
    0x5D, 0xB9, 0x64, 0x76, 0xDD, 0xCA, 0xA1, 0x1B, 0x3E, 0xFD, 0xAD, 0x27, 0xBF, 0x79, 0xEB, 0xC7,
    0xAF, 0xE2, 0xE0, 0xAC, 0xE6, 0xDA, 0x0B, 0x4F, 0x7E, 0xF5, 0x1E, 0x00, 0xB0, 0xF6, 0xDC, 0x6B,
    0x19, 0x19, 0xAC, 0x70, 0xC3, 0xF5, 0x7F, 0xFB, 0xD2, 0x75, 0xEF, 0xB9, 0x6C, 0x3A, 0x36, 0xF6,
    0x92, 0xE9, 0xE9, 0x6A, 0x36, 0x6C, 0xB6, 0xDA, 0xFD, 0xC3, 0x64, 0xEA, 0x13, 0x8A, 0xD8, 0x08,
    0x1E, 0x79, 0x66, 0x27, 0xE3, 0x47, 0xA6, 0x59, 0x35, 0x3A, 0xC2, 0xA7, 0x6E, 0xBE, 0x9B, 0xEF,
    0x6D, 0x7E, 0x0E, 0xEB, 0xF5, 0x20, 0xFD, 0x22, 0x42, 0xFA, 0xB4, 0x5B, 0x54, 0x9D, 0x95, 0xC8,
    0xAB, 0x88, 0xEF, 0x76, 0x43, 0x03, 0xE7, 0xF0, 0xA4, 0xA0, 0x94, 0xF3, 0x18, 0x28, 0x65, 0x29,
    0x67, 0x3D, 0x3C, 0xE1, 0x10, 0x2E, 0xB1, 0xBA, 0xB0, 0x06, 0xE9, 0x0C, 0xA5, 0x5C, 0xC0, 0x8A,
    0x91, 0x7E, 0xBD, 0x72, 0xD9, 0xC0, 0x67, 0x2F, 0xD9, 0xB4, 0xE6, 0x4B, 0xAF, 0x5B, 0x3B, 0x60,
    0x9A, 0x91, 0xE6, 0xBA, 0x8B, 0x4E, 0x5D, 0x14, 0xE3, 0xCB, 0x12, 0xF0, 0x82, 0x38, 0x95, 0xB7,
    0x9F, 0xBF, 0x9E, 0xF3, 0xAF, 0x3C, 0x9B, 0x2B, 0xCE, 0x3B, 0xF5, 0xB9, 0x83, 0x93, 0x73, 0x26,
    0x36, 0xF6, 0xDC, 0xD9, 0xD9, 0xAA, 0x1F, 0x85, 0x61, 0x92, 0x14, 0xD3, 0x82, 0x45, 0x08, 0x09,
    0xD2, 0x63, 0xFF, 0xA1, 0x59, 0xEE, 0x7D, 0x78, 0x3B, 0x7B, 0x0F, 0xD7, 0xF1, 0x82, 0x12, 0xB2,
    0x93, 0xE8, 0x5C, 0x32, 0x5D, 0x39, 0x9B, 0x36, 0x57, 0xEC, 0xCB, 0x82, 0x4F, 0x4A, 0x59, 0x87,
    0xC4, 0x91, 0xF5, 0x25, 0x3D, 0xF9, 0xC4, 0xD5, 0x4B, 0x59, 0x2F, 0x59, 0x66, 0xBB, 0x04, 0xB4,
    0xE8, 0x80, 0xB7, 0x14, 0xB2, 0x3E, 0xA3, 0xCB, 0xFA, 0xDD, 0xE8, 0xB2, 0xFE, 0x7F, 0x1E, 0xEA,
    0x2F, 0xFF, 0x8D, 0xD1, 0xB6, 0xFE, 0xF4, 0xCE, 0x43, 0x7C, 0xF2, 0x5F, 0x1E, 0x60, 0xE4, 0x8C,
    0xB7, 0x52, 0x5C, 0x77, 0x19, 0xB3, 0xCF, 0xFE, 0xF8, 0xD5, 0x11, 0xD0, 0x73, 0xE5, 0x27, 0x31,
    0xD6, 0x32, 0x35, 0x53, 0xE7, 0xC7, 0x8F, 0xEF, 0xE2, 0xE3, 0xFF, 0xE1, 0x02, 0xBB, 0x7D, 0xFF,
    0xF4, 0x93, 0xBE, 0x92, 0xBE, 0xC5, 0x9D, 0x3D, 0x3B, 0x57, 0xF3, 0xA2, 0x56, 0x88, 0xB3, 0xA6,
    0xCB, 0xAA, 0x02, 0x21, 0x14, 0x0E, 0x0F, 0xA9, 0x32, 0x20, 0xD2, 0x32, 0xA3, 0x03, 0xD6, 0x76,
    0x48, 0xC0, 0x76, 0xC5, 0x73, 0x97, 0xE0, 0x2C, 0x12, 0x4B, 0xA0, 0x24, 0xC5, 0xAC, 0x47, 0x6F,
    0x21, 0xA0, 0x27, 0x1F, 0x90, 0x0B, 0x54, 0x62, 0x71, 0x6B, 0xBB, 0xC0, 0x5B, 0xB0, 0x1A, 0x89,
    0xA3, 0x90, 0xF5, 0x59, 0xBE, 0xB4, 0x8F, 0xE5, 0x4B, 0xFB, 0xEF, 0x40, 0x79, 0x37, 0x7E, 0xF4,
    0x8F, 0x2E, 0x3C, 0xFC, 0xC3, 0x83, 0x23, 0xF2, 0xF1, 0xE7, 0xC7, 0xC8, 0x67, 0x7C, 0x96, 0x0F,
    0x94, 0x78, 0xF1, 0xE0, 0x2C, 0x76, 0xF4, 0x42, 0xEC, 0x9E, 0xFB, 0x5F, 0x3E, 0x07, 0x8C, 0xBC,
    0xFD, 0xBF, 0x13, 0xC6, 0x86, 0xD8, 0x58, 0x02, 0x4F, 0x89, 0x30, 0xD2, 0x38, 0x10, 0xD5, 0x47,
    0x76, 0x8A, 0xF7, 0x7F, 0xFC, 0xBA, 0x12, 0x71, 0xF4, 0xD1, 0x67, 0x77, 0xEC, 0xFB, 0x4F, 0xDB,
    0x9F, 0x7B, 0x31, 0x37, 0x3B, 0x53, 0x4D, 0x16, 0x22, 0x52, 0xA5, 0x9B, 0x27, 0x5D, 0x67, 0xA9,
    0x40, 0x76, 0x6F, 0xA9, 0xB5, 0x5B, 0xEA, 0x47, 0x37, 0x58, 0x45, 0x5A, 0x40, 0x29, 0x25, 0xF1,
    0x3D, 0x45, 0x26, 0x50, 0x64, 0x03, 0x8F, 0xC0, 0x53, 0x28, 0x99, 0x36, 0x4D, 0xD2, 0x90, 0x11,
    0x38, 0x84, 0x73, 0x08, 0x12, 0x42, 0x85, 0xB3, 0x28, 0x01, 0xC5, 0x7C, 0x86, 0x91, 0xA5, 0x03,
    0x6E, 0xC9, 0x70, 0xDF, 0x9D, 0x73, 0x4D, 0x7D, 0xE3, 0x97, 0xBF, 0x76, 0xFF, 0xDE, 0xE2, 0x09,
    0x03, 0x90, 0x2C, 0x24, 0xAC, 0x00, 0x2B, 0xA5, 0x64, 0x76, 0xAE, 0xE1, 0xCE, 0x58, 0xBF, 0x9C,
    0xFE, 0x9E, 0x1C, 0xF7, 0x7E, 0xF6, 0xBD, 0xC7, 0xF7, 0x80, 0x81, 0x8D, 0x57, 0xB2, 0xB4, 0xAF,
    0xC8, 0x4C, 0x2D, 0x14, 0xAD, 0x48, 0x0B, 0x92, 0xE9, 0xD2, 0x0B, 0x46, 0xFA, 0x82, 0xCD, 0xCF,
    0xEC, 0xC5, 0xCF, 0x66, 0x9F, 0x3A, 0x69, 0xC5, 0x60, 0x54, 0x2C, 0x64, 0x4F, 0x0B, 0xC3, 0x28,
    0x17, 0xB6, 0x42, 0x9C, 0xD1, 0x47, 0x2D, 0x6B, 0xDB, 0x96, 0xB2, 0x88, 0xD4, 0xE5, 0x85, 0x4B,
    0xF6, 0x18, 0x14, 0xC9, 0xE3, 0x6C, 0x81, 0x92, 0xE4, 0x03, 0x45, 0x21, 0xA3, 0x28, 0xE5, 0x7C,
    0xCA, 0x39, 0x9F, 0x52, 0xC6, 0x23, 0xEB, 0x2B, 0x7C, 0x49, 0xBA, 0x1F, 0x69, 0x13, 0x4B, 0xBB,
    0x64, 0x5E, 0x17, 0xCE, 0x20, 0xAC, 0xEE, 0xC4, 0x7B, 0x20, 0x05, 0xBD, 0xE5, 0x02, 0xA3, 0xCB,
    0x06, 0xA3, 0x9E, 0x4A, 0xE9, 0xDB, 0x5B, 0xF6, 0x4C, 0xFE, 0xFD, 0x6D, 0x3F, 0x7F, 0xF6, 0x48,
    0x71, 0xA0, 0x94, 0xCE, 0xB1, 0x47, 0x0D, 0x6C, 0xAD, 0x25, 0x97, 0x0B, 0xB8, 0xEA, 0x9C, 0x93,
    0x68, 0x86, 0x9A, 0x0F, 0xDF, 0xF8, 0x5F, 0xB8, 0xEB, 0xFF, 0xDC, 0xB4, 0x88, 0x07, 0x9C, 0xFF,
    0x31, 0x0A, 0xD9, 0x00, 0x29, 0x05, 0xCE, 0x39, 0x91, 0xEA, 0xAC, 0x00, 0x1F, 0xC8, 0x00, 0x39,
    0x6D, 0x6C, 0xA6, 0x98, 0xCF, 0xE4, 0x2F, 0xDA, 0xB8, 0xFC, 0x2A, 0x11, 0x87, 0x37, 0xEC, 0xDD,
    0x3B, 0xBE, 0x6A, 0x7C, 0x7C, 0x82, 0x66, 0xB3, 0x99, 0xF6, 0x03, 0x12, 0xEB, 0x0B, 0x25, 0x91,
    0x4A, 0xCD, 0x93, 0xF6, 0x66, 0x87, 0x52, 0xE9, 0x76, 0x7B, 0xBB, 0x84, 0xEE, 0xB4, 0xC8, 0x44,
    0x47, 0x73, 0x21, 0xDA, 0x0F, 0x45, 0xBA, 0xA4, 0x35, 0x8F, 0x43, 0xE0, 0x50, 0x02, 0xB2, 0xD9,
    0x80, 0x81, 0xBE, 0x1E, 0x06, 0x06, 0x7B, 0xA7, 0x5B, 0x56, 0xDE, 0xF6, 0xC0, 0xD6, 0x03, 0xDF,
    0x7A, 0x69, 0xB2, 0x36, 0xE3, 0x7B, 0x32, 0x22, 0xF9, 0xEF, 0x93, 0x56, 0x7A, 0x0E, 0x81, 0x18,
    0xD0, 0x4A, 0x0A, 0x7B, 0xCE, 0xA9, 0xA3, 0xEE, 0x47, 0x9F, 0xF9, 0xA6, 0xBB, 0xEB, 0xA1, 0xCF,
    0x72, 0xF5, 0xB9, 0x27, 0x2F, 0xE2, 0x01, 0xA3, 0x17, 0x12, 0xCF, 0x35, 0x50, 0x59, 0x5F, 0xC8,
    0x64, 0x1D, 0xAB, 0x80, 0x00, 0xC8, 0x02, 0x45, 0xA0, 0x2C, 0xA5, 0xE8, 0x8D, 0xB5, 0xED, 0xDB,
    0x31, 0x36, 0x3D, 0xE3, 0x67, 0x33, 0x2F, 0xAE, 0x1C, 0x19, 0x2C, 0xF4, 0xF5, 0x14, 0x87, 0x04,
    0x78, 0xCE, 0x18, 0x04, 0x16, 0x25, 0x93, 0xAC, 0xED, 0x49, 0x50, 0x42, 0xA0, 0x64, 0xD2, 0x29,
    0x92, 0x24, 0x22, 0x52, 0x0B, 0xCB, 0xD4, 0xA5, 0x85, 0x33, 0xF3, 0x2C, 0x9E, 0x48, 0x12, 0xE7,
    0xC2, 0x26, 0xF7, 0x94, 0x58, 0xB2, 0xBE, 0x47, 0x6F, 0xA5, 0xC8, 0xB2, 0xA5, 0x03, 0xA6, 0x50,
    0x2E, 0xBD, 0xB0, 0xF3, 0x70, 0xED, 0xF6, 0x9F, 0x3D, 0xBD, 0xEF, 0xF1, 0x5A, 0x33, 0xCA, 0x78,
    0x4A, 0x16, 0x52, 0x23, 0xB5, 0x9F, 0x96, 0x4A, 0xD8, 0x4B, 0x43, 0xC1, 0x5A, 0xE7, 0xC2, 0x48,
    0xBB, 0xBF, 0xFC, 0xE8, 0x3B, 0xF9, 0xE5, 0x96, 0xFD, 0x3C, 0x75, 0xDF, 0xAD, 0xC7, 0x12, 0x50,
    0x38, 0xF9, 0xCD, 0x54, 0x7A, 0x8B, 0x44, 0xDA, 0x08, 0x29, 0x84, 0x24, 0x59, 0x30, 0x05, 0x40,
    0x1E, 0x28, 0x03, 0xBD, 0x40, 0xBF, 0x10, 0x0C, 0x48, 0x21, 0x06, 0x0F, 0x4D, 0x37, 0xBC, 0x03,
    0x53, 0x8D, 0x03, 0x95, 0x9E, 0xE2, 0xDC, 0x8A, 0x65, 0x03, 0xA5, 0x9E, 0x52, 0xBE, 0x20, 0x85,
    0x94, 0xAE, 0xAB, 0x7A, 0x4B, 0x2C, 0x67, 0x3B, 0xC0, 0x65, 0x1A, 0xCB, 0x12, 0xDB, 0x05, 0xD6,
    0xCE, 0x07, 0x9E, 0x82, 0x97, 0x24, 0x44, 0x66, 0x03, 0x9F, 0xDE, 0x9E, 0x22, 0x4B, 0x87, 0xFB,
    0xE9, 0x1B, 0xE8, 0x9D, 0x3E, 0xDC, 0x30, 0x8F, 0x6D, 0x7E, 0xEE, 0xE0, 0x43, 0xBB, 0xC6, 0x67,
    0x66, 0x85, 0xA0, 0x24, 0x84, 0x28, 0xA4, 0x46, 0x0A, 0xBA, 0x42, 0xDB, 0x92, 0xF4, 0xD0, 0x34,
    0x60, 0x85, 0x10, 0xB6, 0x15, 0x6A, 0xFA, 0x4A, 0x39, 0xB7, 0xEB, 0xC0, 0x24, 0xFB, 0x1E, 0xBF,
    0xEB, 0x58, 0x02, 0xD6, 0x5F, 0x70, 0x1D, 0x2B, 0x86, 0x7B, 0x38, 0x3C, 0x5D, 0x97, 0x2E, 0x8D,
    0xFD, 0x94, 0xD5, 0x36, 0x01, 0x15, 0xA0, 0xAF, 0x2D, 0x52, 0x88, 0x5E, 0xAD, 0x6D, 0x79, 0x7C,
    0xAA, 0xD6, 0x3C, 0x52, 0x8B, 0x0F, 0xF6, 0xF4, 0x94, 0x1A, 0xCB, 0x96, 0xF4, 0x65, 0x06, 0x7A,
    0xCB, 0x99, 0x6C, 0x36, 0x90, 0x2A, 0xDD, 0x5D, 0x92, 0x0B, 0xAC, 0xDF, 0x26, 0xA1, 0x9D, 0xD4,
    0xDA, 0x16, 0x4E, 0xBC, 0x24, 0x79, 0x04, 0x37, 0x1B, 0xF8, 0x14, 0x8B, 0x39, 0x06, 0xFA, 0x7A,
    0x18, 0x1E, 0xEE, 0xB7, 0xA5, 0x4A, 0xCF, 0xDC, 0x74, 0xC4, 0xCE, 0x27, 0x76, 0x4F, 0x3E, 0xB3,
    0x6D, 0xEF, 0xE4, 0xC1, 0x30, 0xD2, 0x9E, 0x94, 0x22, 0x9F, 0xEA, 0x17, 0xA4, 0xBA, 0xB6, 0x9F,
    0x59, 0x35, 0xA9, 0xEB, 0x47, 0xED, 0x10, 0x20, 0xE9, 0x9C, 0xB9, 0xB1, 0x23, 0x73, 0xEE, 0xE0,
    0x74, 0x83, 0xE6, 0x0B, 0xF7, 0x1D, 0xBB, 0x1C, 0x56, 0x69, 0x5C, 0x2E, 0xD8, 0x67, 0x6C, 0x27,
    0x42, 0x95, 0x0E, 0xE2, 0xA7, 0x03, 0x06, 0x40, 0x46, 0x08, 0x32, 0x02, 0x91, 0x99, 0xA9, 0x35,
    0x79, 0xF4, 0x85, 0xE6, 0xDE, 0x52, 0x3E, 0x33, 0x31, 0x3A, 0x50, 0x1C, 0x58, 0x32, 0xB4, 0x64,
    0xC9, 0xE0, 0x12, 0xD7, 0x6F, 0xA2, 0xB0, 0xD0, 0x6A, 0xB6, 0xBC, 0x56, 0x2B, 0x24, 0x8A, 0x22,
    0x74, 0x6C, 0xB0, 0xF6, 0x68, 0x67, 0x56, 0x4A, 0x81, 0x54, 0x12, 0xDF, 0xF3, 0x08, 0x02, 0x9F,
    0x4C, 0x26, 0x20, 0x9B, 0xCD, 0x90, 0xCB, 0x65, 0x8D, 0xF4, 0xFD, 0x56, 0xD3, 0x30, 0xB3, 0x6F,
    0xA6, 0x75, 0x68, 0xCF, 0xC4, 0xF4, 0x91, 0xA9, 0xB9, 0x56, 0xDD, 0xE1, 0xAC, 0x14, 0x22, 0x07,
    0x22, 0x4E, 0xC1, 0xB5, 0x5D, 0x3D, 0xEE, 0xD2, 0xCB, 0x4B, 0xF5, 0x95, 0xA9, 0x74, 0xF2, 0x9D,
    0x36, 0x4E, 0xD8, 0x74, 0xBD, 0x7E, 0x0C, 0x01, 0xA6, 0xF3, 0x9C, 0xCE, 0xBC, 0x8F, 0xDB, 0x71,
    0xD4, 0xCD, 0x6A, 0x98, 0x4A, 0x7B, 0x5F, 0xDA, 0x09, 0x21, 0xAC, 0x00, 0xAF, 0xD6, 0x88, 0xEC,
    0xB6, 0xBD, 0x93, 0x8D, 0xE7, 0x95, 0x1C, 0xAB, 0x14, 0x32, 0xB9, 0xC1, 0x9E, 0x5C, 0xB9, 0xBF,
    0x58, 0xAE, 0x94, 0xCB, 0xB2, 0xE4, 0x4B, 0xF2, 0x9E, 0x20, 0x27, 0x70, 0x7E, 0xB2, 0xA9, 0x97,
    0xF4, 0x4B, 0xA4, 0x94, 0x0E, 0x21, 0x63, 0xED, 0x68, 0xC5, 0x96, 0x66, 0x2B, 0xB6, 0xF5, 0xF1,
    0xE9, 0x70, 0xF6, 0xD0, 0xCC, 0xDC, 0xDC, 0x74, 0xAD, 0xD5, 0x88, 0x62, 0xA3, 0x11, 0x38, 0x29,
    0x84, 0x15, 0x49, 0x73, 0xBC, 0xAD, 0x4B, 0x9C, 0xEA, 0xD1, 0xEA, 0xD2, 0xA9, 0x93, 0xF8, 0xDA,
    0xF1, 0xDF, 0x6D, 0xCE, 0xC0, 0x57, 0xAE, 0xFD, 0xF6, 0x18, 0x02, 0x76, 0x8D, 0x4F, 0x93, 0xCF,
    0xD4, 0x88, 0x8D, 0x71, 0x4A, 0xCA, 0x36, 0x70, 0x9D, 0x82, 0x6E, 0x74, 0x25, 0x19, 0xD2, 0x41,
    0x9A, 0x69, 0xEC, 0x65, 0xD3, 0xCF, 0x93, 0xC7, 0x78, 0x84, 0xF0, 0x9C, 0x73, 0x72, 0xAA, 0xDA,
    0x94, 0x47, 0xE6, 0x9A, 0x07, 0x85, 0x40, 0x7A, 0x4A, 0xAA, 0x8C, 0xEF, 0x79, 0xB9, 0x8C, 0xE7,
    0x67, 0x7D, 0x15, 0x28, 0x21, 0x54, 0xBA, 0x45, 0xE3, 0xAC, 0xC5, 0x46, 0xDA, 0xE8, 0x46, 0x18,
    0xC7, 0xAD, 0xC8, 0xC4, 0xDA, 0x58, 0x6B, 0x9D, 0xB3, 0x49, 0x57, 0x5E, 0x38, 0x29, 0x85, 0x65,
    0x7E, 0x4C, 0xEB, 0x2E, 0xBD, 0xDA, 0x04, 0x34, 0x80, 0x2A, 0x30, 0x9B, 0x9E, 0x1B, 0xE9, 0x77,
    0x6D, 0x22, 0x9C, 0xA7, 0x04, 0x6F, 0x39, 0x7B, 0x2D, 0xBB, 0xC7, 0xA6, 0xF8, 0xE9, 0x62, 0x04,
    0xD4, 0x1B, 0x21, 0xF5, 0x23, 0x73, 0xE4, 0xFA, 0x8A, 0xDD, 0x96, 0x6F, 0x03, 0x6D, 0x67, 0x56,
    0x9D, 0xBE, 0xAF, 0x02, 0xB9, 0x14, 0x7C, 0x9B, 0x98, 0xB6, 0x78, 0x80, 0x12, 0x42, 0x28, 0x95,
    0xFC, 0xC3, 0x98, 0xB4, 0xD6, 0xC9, 0x46, 0x2B, 0x16, 0xF5, 0x56, 0x24, 0xE9, 0xD8, 0xE0, 0xA8,
    0x6B, 0x0A, 0x91, 0xB4, 0xD4, 0x84, 0x48, 0xB6, 0x23, 0x94, 0xE8, 0x80, 0xEE, 0x06, 0xDF, 0x4D,
    0x40, 0xDB, 0x1B, 0x23, 0x8E, 0x4E, 0x7B, 0x0D, 0xA0, 0x96, 0xEA, 0x56, 0x4D, 0x3F, 0x8B, 0x01,
    0xE3, 0x9C, 0x73, 0xC3, 0xBD, 0x25, 0xF7, 0xBA, 0x93, 0x96, 0x52, 0xC8, 0x07, 0x8B, 0x13, 0x80,
    0x10, 0xE4, 0xFB, 0x4B, 0x48, 0x21, 0x3A, 0x2D, 0xC0, 0x54, 0xC9, 0xB0, 0x2B, 0xB9, 0x84, 0xE9,
    0x20, 0x6D, 0xCB, 0xB7, 0xE3, 0xAE, 0x1B, 0x7C, 0x3B, 0x06, 0xDB, 0x71, 0xA8, 0x20, 0x9D, 0xF2,
    0x11, 0xB2, 0xB3, 0x39, 0x37, 0x9F, 0x04, 0xD7, 0x75, 0xB6, 0x5D, 0xE7, 0xE3, 0x59, 0x7F, 0x31,
    0x12, 0x42, 0xE6, 0xD7, 0x01, 0xED, 0x24, 0x68, 0x00, 0xE7, 0xFB, 0xCA, 0x7D, 0xE0, 0xBA, 0x73,
    0x78, 0x70, 0xCB, 0x5E, 0x3E, 0xB7, 0x28, 0x01, 0x0F, 0x7E, 0x02, 0xF9, 0xE6, 0x4F, 0x2C, 0x8C,
    0x7F, 0xDD, 0xA5, 0x8C, 0x4E, 0x6F, 0xEE, 0x2F, 0x22, 0x0B, 0x81, 0x77, 0x13, 0xD0, 0x9D, 0x8C,
    0xDA, 0x49, 0xF5, 0x78, 0xC7, 0xF1, 0x08, 0x68, 0x8F, 0x6F, 0xBA, 0xA4, 0x1D, 0xEB, 0x71, 0x97,
    0x44, 0x5D, 0x9F, 0xB5, 0xAF, 0x77, 0x80, 0xDB, 0xB6, 0x65, 0x3F, 0x1B, 0xFE, 0xE8, 0xF3, 0x8C,
    0x4D, 0xCC, 0xC1, 0xA2, 0x04, 0x1C, 0xAB, 0x48, 0xFB, 0xDC, 0x4D, 0x40, 0xDC, 0x65, 0xD5, 0xC5,
    0xC0, 0x76, 0xBF, 0x6E, 0x17, 0x53, 0x62, 0x81, 0xBC, 0x12, 0x01, 0xDD, 0x63, 0x2E, 0x46, 0x84,
    0x59, 0x40, 0x48, 0x77, 0x88, 0x98, 0x45, 0xAE, 0x47, 0x08, 0xE1, 0x0A, 0x03, 0x45, 0x76, 0x8D,
    0x4D, 0x71, 0xFD, 0x25, 0x1B, 0xE7, 0xB9, 0xDE, 0x31, 0x47, 0x71, 0xBE, 0x17, 0x74, 0x5F, 0xDB,
    0x0D, 0xA0, 0xFB, 0xB5, 0x5C, 0xE4, 0xBB, 0xEE, 0xCF, 0xBA, 0x85, 0x45, 0xCE, 0x0B, 0x09, 0x5F,
    0x48, 0xC4, 0x42, 0x42, 0x16, 0x92, 0xB3, 0xF0, 0xBC, 0xF0, 0xF7, 0x9D, 0xA3, 0x76, 0xEF, 0xC7,
    0x8E, 0x01, 0xF5, 0x6A, 0x49, 0x58, 0x4C, 0xF1, 0x85, 0xC4, 0x74, 0xBF, 0x7E, 0x25, 0xC0, 0xAF,
    0x74, 0x1C, 0x8F, 0x90, 0xC5, 0xC8, 0xE1, 0x65, 0xCE, 0x8B, 0x82, 0x07, 0xF8, 0xBF, 0xBC, 0x7A,
    0x38, 0x97, 0x7C, 0xD1, 0xFC, 0xA1, 0x00, 0x00, 0x00, 0x25, 0x74, 0x45, 0x58, 0x74, 0x64, 0x61,
    0x74, 0x65, 0x3A, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x00, 0x32, 0x30, 0x32, 0x30, 0x2D, 0x30,
    0x33, 0x2D, 0x31, 0x39, 0x54, 0x31, 0x30, 0x3A, 0x35, 0x30, 0x3A, 0x35, 0x38, 0x2B, 0x30, 0x30,
    0x3A, 0x30, 0x30, 0x62, 0x40, 0x28, 0xF1, 0x00, 0x00, 0x00, 0x25, 0x74, 0x45, 0x58, 0x74, 0x64,
    0x61, 0x74, 0x65, 0x3A, 0x6D, 0x6F, 0x64, 0x69, 0x66, 0x79, 0x00, 0x32, 0x30, 0x31, 0x39, 0x2D,
    0x30, 0x31, 0x2D, 0x30, 0x38, 0x54, 0x31, 0x35, 0x3A, 0x35, 0x34, 0x3A, 0x32, 0x33, 0x2B, 0x30,
    0x30, 0x3A, 0x30, 0x30, 0x8A, 0xEF, 0xF9, 0x19, 0x00, 0x00, 0x00, 0x20, 0x74, 0x45, 0x58, 0x74,
    0x73, 0x6F, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, 0x00, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3A, 0x2F,
    0x2F, 0x69, 0x6D, 0x61, 0x67, 0x65, 0x6D, 0x61, 0x67, 0x69, 0x63, 0x6B, 0x2E, 0x6F, 0x72, 0x67,
    0xBC, 0xCF, 0x1D, 0x9D, 0x00, 0x00, 0x00, 0x18, 0x74, 0x45, 0x58, 0x74, 0x54, 0x68, 0x75, 0x6D,
    0x62, 0x3A, 0x3A, 0x44, 0x6F, 0x63, 0x75, 0x6D, 0x65, 0x6E, 0x74, 0x3A, 0x3A, 0x50, 0x61, 0x67,
    0x65, 0x73, 0x00, 0x31, 0xA7, 0xFF, 0xBB, 0x2F, 0x00, 0x00, 0x00, 0x18, 0x74, 0x45, 0x58, 0x74,
    0x54, 0x68, 0x75, 0x6D, 0x62, 0x3A, 0x3A, 0x49, 0x6D, 0x61, 0x67, 0x65, 0x3A, 0x3A, 0x48, 0x65,
    0x69, 0x67, 0x68, 0x74, 0x00, 0x31, 0x32, 0x38, 0x43, 0x7C, 0x41, 0x80, 0x00, 0x00, 0x00, 0x17,
    0x74, 0x45, 0x58, 0x74, 0x54, 0x68, 0x75, 0x6D, 0x62, 0x3A, 0x3A, 0x49, 0x6D, 0x61, 0x67, 0x65,
    0x3A, 0x3A, 0x57, 0x69, 0x64, 0x74, 0x68, 0x00, 0x31, 0x32, 0x38, 0xD0, 0x8D, 0x11, 0xDD, 0x00,
    0x00, 0x00, 0x19, 0x74, 0x45, 0x58, 0x74, 0x54, 0x68, 0x75, 0x6D, 0x62, 0x3A, 0x3A, 0x4D, 0x69,
    0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x00, 0x69, 0x6D, 0x61, 0x67, 0x65, 0x2F, 0x70, 0x6E, 0x67,
    0x3F, 0xB2, 0x56, 0x4E, 0x00, 0x00, 0x00, 0x17, 0x74, 0x45, 0x58, 0x74, 0x54, 0x68, 0x75, 0x6D,
    0x62, 0x3A, 0x3A, 0x4D, 0x54, 0x69, 0x6D, 0x65, 0x00, 0x31, 0x35, 0x34, 0x36, 0x39, 0x36, 0x32,
    0x38, 0x36, 0x33, 0x1F, 0x1E, 0xB3, 0x01, 0x00, 0x00, 0x00, 0x12, 0x74, 0x45, 0x58, 0x74, 0x54,
    0x68, 0x75, 0x6D, 0x62, 0x3A, 0x3A, 0x53, 0x69, 0x7A, 0x65, 0x00, 0x31, 0x39, 0x32, 0x37, 0x34,
    0x42, 0x0A, 0x19, 0xAB, 0x42, 0x00, 0x00, 0x00, 0x56, 0x74, 0x45, 0x58, 0x74, 0x54, 0x68, 0x75,
    0x6D, 0x62, 0x3A, 0x3A, 0x55, 0x52, 0x49, 0x00, 0x66, 0x69, 0x6C, 0x65, 0x3A, 0x2F, 0x2F, 0x2F,
    0x64, 0x61, 0x74, 0x61, 0x2F, 0x77, 0x77, 0x77, 0x72, 0x6F, 0x6F, 0x74, 0x2F, 0x77, 0x77, 0x77,
    0x2E, 0x65, 0x61, 0x73, 0x79, 0x69, 0x63, 0x6F, 0x6E, 0x2E, 0x6E, 0x65, 0x74, 0x2F, 0x63, 0x64,
    0x6E, 0x2D, 0x69, 0x6D, 0x67, 0x2E, 0x65, 0x61, 0x73, 0x79, 0x69, 0x63, 0x6F, 0x6E, 0x2E, 0x63,
    0x6E, 0x2F, 0x66, 0x69, 0x6C, 0x65, 0x73, 0x2F, 0x32, 0x2F, 0x32, 0x39, 0x31, 0x36, 0x35, 0x2E,
    0x70, 0x6E, 0x67, 0xBF, 0x98, 0x5F, 0xE5, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE,
    0x42, 0x60, 0x82 
};
void *get_window_icon_raw_data(int *len)
{
    *len = (int)sizeof(window_icon_hexData);
    return window_icon_hexData;
}
 | 51,747 | 
	C | 
	.c | 582 | 84.304124 | 99 | 0.64875 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 745 | 
	ventoy_disk.c | 
	ventoy_Ventoy/LinuxGUI/Ventoy2Disk/Core/ventoy_disk.c | 
	/******************************************************************************
 * ventoy_disk.c  ---- ventoy disk
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/fs.h>
#include <dirent.h>
#include <time.h>
#include <ventoy_define.h>
#include <ventoy_disk.h>
#include <ventoy_util.h>
#include <fat_filelib.h>
int g_disk_num = 0;
static int g_fatlib_media_fd = 0;
static uint64_t g_fatlib_media_offset = 0;
ventoy_disk *g_disk_list = NULL;
static const char *g_ventoy_dev_type_str[VTOY_DEVICE_END] = 
{
    "unknown", "scsi", "USB", "ide", "dac960",
    "cpqarray", "file", "ataraid", "i2o",
    "ubd", "dasd", "viodasd", "sx8", "dm",
    "xvd", "sd/mmc", "virtblk", "aoe",
    "md", "loopback", "nvme", "brd", "pmem"
};
static const char * ventoy_get_dev_type_name(ventoy_dev_type type)
{
    return (type < VTOY_DEVICE_END) ? g_ventoy_dev_type_str[type] : "unknown";
}
static int ventoy_check_blk_major(int major, const char *type)
{
    int flag = 0;
    int valid = 0;
    int devnum = 0;
    int len = 0;
    char line[64];
    char *pos = NULL;
    FILE *fp = NULL;
    fp = fopen("/proc/devices", "r");
    if (!fp)
    {
        return 0;
    }
    len = (int)strlen(type);
    while (fgets(line, sizeof(line), fp))
    {
        if (flag)
        {
            pos = strchr(line, ' ');
            if (pos)
            {
                devnum = (int)strtol(line, NULL, 10);
                if (devnum == major)
                {
                    if (strncmp(pos + 1, type, len) == 0)
                    {
                        valid = 1;                        
                    }
                    break;
                }
            }
        }
        else if (strncmp(line, "Block devices:", 14) == 0)
        {
            flag = 1;
        }
    }
    fclose(fp);
    return valid;
}
static int ventoy_get_disk_devnum(const char *name, int *major, int* minor)
{
    int rc;
    char *pos;
    char devnum[16] = {0};
    
    rc = ventoy_get_sys_file_line(devnum, sizeof(devnum), "/sys/block/%s/dev", name);
    if (rc)
    {
        return 1;
    }
    pos = strstr(devnum, ":");
    if (!pos)
    {
        return 1;
    }
    *major = (int)strtol(devnum, NULL, 10);
    *minor = (int)strtol(pos + 1, NULL, 10);
    return 0;
}
static ventoy_dev_type ventoy_get_dev_type(const char *name, int major, int minor)
{
    int rc;
    char syspath[128];
    char dstpath[256];
    memset(syspath, 0, sizeof(syspath));
    memset(dstpath, 0, sizeof(dstpath));
    
    scnprintf(syspath, "/sys/block/%s", name);
    rc = readlink(syspath, dstpath, sizeof(dstpath) - 1);
    if (rc > 0 && strstr(dstpath, "/usb"))
    {
        return VTOY_DEVICE_USB;
    }
    
    if (SCSI_BLK_MAJOR(major) && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_SCSI;
    }
    else if (IDE_BLK_MAJOR(major) && (minor % 0x40 == 0)) 
    {
        return VTOY_DEVICE_IDE;
    }
    else if (major == DAC960_MAJOR && (minor % 0x8 == 0)) 
    {
        return VTOY_DEVICE_DAC960;
    }
    else if (major == ATARAID_MAJOR && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_ATARAID;
    }
    else if (major == AOE_MAJOR && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_AOE;
    }
    else if (major == DASD_MAJOR && (minor % 0x4 == 0)) 
    {
        return VTOY_DEVICE_DASD;
    }
    else if (major == VIODASD_MAJOR && (minor % 0x8 == 0)) 
    {
        return VTOY_DEVICE_VIODASD;
    }
    else if (SX8_BLK_MAJOR(major) && (minor % 0x20 == 0)) 
    {
        return VTOY_DEVICE_SX8;
    }
    else if (I2O_BLK_MAJOR(major) && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_I2O;
    }
    else if (CPQARRAY_BLK_MAJOR(major) && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_CPQARRAY;
    }
    else if (UBD_MAJOR == major && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_UBD;
    }
    else if (XVD_MAJOR == major && (minor % 0x10 == 0)) 
    {
        return VTOY_DEVICE_XVD;
    }
    else if (SDMMC_MAJOR == major && (minor % 0x8 == 0)) 
    {
        return VTOY_DEVICE_SDMMC;
    }
    else if (ventoy_check_blk_major(major, "virtblk"))
    {
        return VTOY_DEVICE_VIRTBLK;
    }
    else if (major == LOOP_MAJOR)
    {
        return VTOY_DEVICE_LOOP;
    }
    else if (major == MD_MAJOR)
    {
        return VTOY_DEVICE_MD;
    }
    else if (major == RAM_MAJOR)
    {
        return VTOY_DEVICE_RAM;
    }
    else if (strstr(name, "nvme") && ventoy_check_blk_major(major, "blkext"))
    {
        return VTOY_DEVICE_NVME;
    }
    else if (strstr(name, "pmem") && ventoy_check_blk_major(major, "blkext"))
    {
        return VTOY_DEVICE_PMEM;
    }
    
    return VTOY_DEVICE_END;
}
static int ventoy_is_possible_blkdev(const char *name)
{
    if (name[0] == '.')
    {
        return 0;
    }
    /* /dev/ramX */
    if (name[0] == 'r' && name[1] == 'a' && name[2] == 'm')
    {
        return 0;
    }
    
    /* /dev/zramX */
    if (name[0] == 'z' && name[1] == 'r' && name[2] == 'a' && name[3] == 'm')
    {
        return 0;
    }
    /* /dev/loopX */
    if (name[0] == 'l' && name[1] == 'o' && name[2] == 'o' && name[3] == 'p')
    {
        return 0;
    }
    /* /dev/dm-X */
    if (name[0] == 'd' && name[1] == 'm' && name[2] == '-' && isdigit(name[3]))
    {
        return 0;
    }
    /* /dev/srX */
    if (name[0] == 's' && name[1] == 'r' && isdigit(name[2]))
    {
        return 0;
    }
    
    return 1;
}
int ventoy_is_disk_4k_native(const char *disk)
{
    int fd;
    int rc = 0;
    int logsector = 0;
    int physector = 0;
    char diskpath[256] = {0};
    snprintf(diskpath, sizeof(diskpath) - 1, "/dev/%s", disk);
    fd = open(diskpath, O_RDONLY | O_BINARY);
    if (fd >= 0)
    {
        ioctl(fd, BLKSSZGET, &logsector);
        ioctl(fd, BLKPBSZGET, &physector);
        
        if (logsector == 4096 && physector == 4096)
        {
            rc = 1;
        }
        close(fd);
    }
    vdebug("is 4k native disk <%s> <%d>\n", disk, rc);    
    return rc;
}
uint64_t ventoy_get_disk_size_in_byte(const char *disk)
{
    int fd;
    int rc;
    unsigned long long size = 0;
    char diskpath[256] = {0};
    char sizebuf[64] = {0};
    // Try 1: get size from sysfs
    snprintf(diskpath, sizeof(diskpath) - 1, "/sys/block/%s/size", disk);
    if (access(diskpath, F_OK) >= 0)
    {
        vdebug("get disk size from sysfs for %s\n", disk);
        
        fd = open(diskpath, O_RDONLY | O_BINARY);
        if (fd >= 0)
        {
            read(fd, sizebuf, sizeof(sizebuf));
            size = strtoull(sizebuf, NULL, 10);
            close(fd);
            return (uint64_t)(size * 512);
        }
    }
    else
    {
        vdebug("%s not exist \n", diskpath);
    }
    // Try 2: get size from ioctl
    snprintf(diskpath, sizeof(diskpath) - 1, "/dev/%s", disk);
    fd = open(diskpath, O_RDONLY);
    if (fd >= 0)
    {
        vdebug("get disk size from ioctl for %s\n", disk);
        rc = ioctl(fd, BLKGETSIZE64, &size);
        if (rc == -1)
        {
            size = 0;
            vdebug("failed to ioctl %d\n", rc);
        }
        close(fd);
    }
    else
    {
        vdebug("failed to open %s %d\n", diskpath, errno);
    }
    vdebug("disk %s size %llu bytes\n", disk, size);
    return size;
}
int ventoy_get_disk_vendor(const char *name, char *vendorbuf, int bufsize)
{
    return ventoy_get_sys_file_line(vendorbuf, bufsize, "/sys/block/%s/device/vendor", name);
}
int ventoy_get_disk_model(const char *name, char *modelbuf, int bufsize)
{
    return ventoy_get_sys_file_line(modelbuf, bufsize, "/sys/block/%s/device/model", name);
}
static int fatlib_media_sector_read(uint32 sector, uint8 *buffer, uint32 sector_count)
{
    lseek(g_fatlib_media_fd, (sector + g_fatlib_media_offset) * 512ULL, SEEK_SET);
    read(g_fatlib_media_fd, buffer, sector_count * 512);
    
    return 1;
}
static int fatlib_is_secure_boot_enable(void)
{
    void *flfile = NULL;
    
    flfile = fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
    if (flfile)
    {
        vlog("/EFI/BOOT/grubx64_real.efi find, secure boot in enabled\n");
        fl_fclose(flfile);
        return 1;
    }
    else
    {
        vlog("/EFI/BOOT/grubx64_real.efi not exist\n");
    }
    
    return 0;
}
static int fatlib_get_ventoy_version(char *verbuf, int bufsize)
{
    int rc = 1;
    int size = 0;
    char *buf = NULL;
    char *pos = NULL;
    char *end = NULL;
    void *flfile = NULL;
    flfile = fl_fopen("/grub/grub.cfg", "rb");
    if (flfile)
    {
        fl_fseek(flfile, 0, SEEK_END);
        size = (int)fl_ftell(flfile);
        fl_fseek(flfile, 0, SEEK_SET);
        buf = malloc(size + 1);
        if (buf)
        {
            fl_fread(buf, 1, size, flfile);
            buf[size] = 0;
            pos = strstr(buf, "VENTOY_VERSION=");
            if (pos)
            {
                pos += strlen("VENTOY_VERSION=");
                if (*pos == '"')
                {
                    pos++;
                }
                end = pos;
                while (*end != 0 && *end != '"' && *end != '\r' && *end != '\n')
                {
                    end++;
                }
                *end = 0;
                snprintf(verbuf, bufsize - 1, "%s", pos);
                rc = 0;
            }
            free(buf);
        }
        fl_fclose(flfile);
    }
    else
    {
        vdebug("No grub.cfg found\n");
    }
    
    return rc;
}
int ventoy_get_vtoy_data(ventoy_disk *info, int *ppartstyle)
{
    int i;
    int fd;
    int len;
    int rc = 1;
    int ret = 1;
    int part_style;
    uint64_t part1_start_sector;
    uint64_t part1_sector_count;
    uint64_t part2_start_sector;
    uint64_t part2_sector_count;
    uint64_t preserved_space;
    char name[64] = {0};
    disk_ventoy_data *vtoy = NULL;    
    VTOY_GPT_INFO *gpt = NULL;
    
    vtoy = &(info->vtoydata);
    gpt = &(vtoy->gptinfo);
    memset(vtoy, 0, sizeof(disk_ventoy_data));
    vdebug("ventoy_get_vtoy_data %s\n", info->disk_path);
    if (info->size_in_byte < (2 * VTOYEFI_PART_BYTES))
    {
        vdebug("disk %s is too small %llu\n", info->disk_path, (_ull)info->size_in_byte);
        return 1;
    }
    fd = open(info->disk_path, O_RDONLY | O_BINARY);
    if (fd < 0)
    {
        vdebug("failed to open %s %d\n", info->disk_path, errno);
        return 1;
    }
    len = (int)read(fd, &(vtoy->gptinfo), sizeof(VTOY_GPT_INFO));
    if (len != sizeof(VTOY_GPT_INFO))
    {
        vdebug("failed to read %s %d\n", info->disk_path, errno);
        goto end;
    }
    if (gpt->MBR.Byte55 != 0x55 || gpt->MBR.ByteAA != 0xAA)
    {
        vdebug("Invalid mbr magic 0x%x 0x%x\n", gpt->MBR.Byte55, gpt->MBR.ByteAA);
        goto end;
    }
    if (gpt->MBR.PartTbl[0].FsFlag == 0xEE && strncmp(gpt->Head.Signature, "EFI PART", 8) == 0)
    {
        part_style = GPT_PART_STYLE;
        if (ppartstyle)
        {
            *ppartstyle = part_style;
        }
        if (gpt->PartTbl[0].StartLBA == 0 || gpt->PartTbl[1].StartLBA == 0)
        {
            vdebug("NO ventoy efi part layout <%llu %llu>\n", 
                (_ull)gpt->PartTbl[0].StartLBA,
                (_ull)gpt->PartTbl[1].StartLBA);
            goto end;
        }
        for (i = 0; i < 36; i++)
        {
            name[i] = (char)(gpt->PartTbl[1].Name[i]);
        }
        if (strcmp(name, "VTOYEFI"))
        {
            vdebug("Invalid efi part2 name <%s>\n", name);
            goto end;
        }
        part1_start_sector = gpt->PartTbl[0].StartLBA;
        part1_sector_count = gpt->PartTbl[0].LastLBA - part1_start_sector + 1;
        part2_start_sector = gpt->PartTbl[1].StartLBA;
        part2_sector_count = gpt->PartTbl[1].LastLBA - part2_start_sector + 1;
        preserved_space = info->size_in_byte - (part2_start_sector + part2_sector_count + 33) * 512;
    }
    else
    {
        part_style = MBR_PART_STYLE;
        if (ppartstyle)
        {
            *ppartstyle = part_style;
        }
        
        part1_start_sector = gpt->MBR.PartTbl[0].StartSectorId;
        part1_sector_count = gpt->MBR.PartTbl[0].SectorCount;
        part2_start_sector = gpt->MBR.PartTbl[1].StartSectorId;
        part2_sector_count = gpt->MBR.PartTbl[1].SectorCount;
        preserved_space = info->size_in_byte - (part2_start_sector + part2_sector_count) * 512;
    }
    if (part1_start_sector != VTOYIMG_PART_START_SECTOR ||
        part2_sector_count != VTOYEFI_PART_SECTORS ||
        (part1_start_sector + part1_sector_count) != part2_start_sector)
    {
        vdebug("Not valid ventoy partition layout [%llu %llu] [%llu %llu]\n", 
               part1_start_sector, part1_sector_count, part2_start_sector, part2_sector_count);
        goto end;
    }
    vdebug("ventoy partition layout check OK: [%llu %llu] [%llu %llu]\n", 
               part1_start_sector, part1_sector_count, part2_start_sector, part2_sector_count);
    vtoy->ventoy_valid = 1;
    vdebug("now check secure boot for %s ...\n", info->disk_path);
    g_fatlib_media_fd = fd;
    g_fatlib_media_offset = part2_start_sector;
    fl_init();
    if (0 == fl_attach_media(fatlib_media_sector_read, NULL))
    {
        ret = fatlib_get_ventoy_version(vtoy->ventoy_ver, sizeof(vtoy->ventoy_ver));
        if (ret == 0 && vtoy->ventoy_ver[0])
        {
            vtoy->secure_boot_flag = fatlib_is_secure_boot_enable();            
        }
        else
        {
            vdebug("fatlib_get_ventoy_version failed %d\n", ret);
        }
    }
    else
    {
        vdebug("fl_attach_media failed\n");
    }
    fl_shutdown();
    g_fatlib_media_fd = -1;
    g_fatlib_media_offset = 0;
    if (vtoy->ventoy_ver[0] == 0)
    {
        vtoy->ventoy_ver[0] = '?';
    }
    if (0 == vtoy->ventoy_valid)
    {
        goto end;
    }
    
    lseek(fd, 2040 * 512, SEEK_SET);
    read(fd, vtoy->rsvdata, sizeof(vtoy->rsvdata));
    vtoy->preserved_space = preserved_space;
    vtoy->partition_style = part_style;
    vtoy->part2_start_sector = part2_start_sector;
    rc = 0;
end:
    vtoy_safe_close_fd(fd);
    return rc;
}
int ventoy_get_disk_info(const char *name, ventoy_disk *info)
{
    char vendor[64] = {0};
    char model[128] = {0};
    vdebug("get disk info %s\n", name);
    strlcpy(info->disk_name, name);
    scnprintf(info->disk_path, "/dev/%s", name);
    if (strstr(name, "nvme") || strstr(name, "mmc") || strstr(name, "nbd"))
    {
        scnprintf(info->part1_name, "%sp1", name);
        scnprintf(info->part1_path, "/dev/%sp1", name);
        scnprintf(info->part2_name, "%sp2", name);
        scnprintf(info->part2_path, "/dev/%sp2", name);
    }
    else
    {
        scnprintf(info->part1_name, "%s1", name);
        scnprintf(info->part1_path, "/dev/%s1", name);
        scnprintf(info->part2_name, "%s2", name);
        scnprintf(info->part2_path, "/dev/%s2", name);
    }
    
    info->is4kn = ventoy_is_disk_4k_native(name);
    info->size_in_byte = ventoy_get_disk_size_in_byte(name);
    ventoy_get_disk_devnum(name, &info->major, &info->minor);
    info->type = ventoy_get_dev_type(name, info->major, info->minor);
    ventoy_get_disk_vendor(name, vendor, sizeof(vendor));
    ventoy_get_disk_model(name, model, sizeof(model));
    scnprintf(info->human_readable_size, "%llu GB", (_ull)ventoy_get_human_readable_gb(info->size_in_byte));
    scnprintf(info->disk_model, "%s %s (%s)", vendor, model, ventoy_get_dev_type_name(info->type));
    ventoy_get_vtoy_data(info, &(info->partstyle));
    
    vdebug("disk:<%s %d:%d> model:<%s> size:%llu (%s)\n", 
        info->disk_path, info->major, info->minor, info->disk_model, info->size_in_byte, info->human_readable_size);
    if (info->vtoydata.ventoy_valid)
    {
        vdebug("%s Ventoy:<%s> %s secureboot:%d preserve:%llu\n", info->disk_path, info->vtoydata.ventoy_ver, 
            info->vtoydata.partition_style == MBR_PART_STYLE ? "MBR" : "GPT",
            info->vtoydata.secure_boot_flag, (_ull)(info->vtoydata.preserved_space));
    }
    else
    {
        vdebug("%s NO Ventoy detected\n", info->disk_path);
    }
    return 0;
}
static int ventoy_disk_compare(const ventoy_disk *disk1, const ventoy_disk *disk2)
{
    if (disk1->type == VTOY_DEVICE_USB && disk2->type == VTOY_DEVICE_USB)
    {
        return strcmp(disk1->disk_name, disk2->disk_name);
    }
    else if (disk1->type == VTOY_DEVICE_USB)
    {
        return -1;
    }
    else if (disk2->type == VTOY_DEVICE_USB)
    {
        return 1;
    }
    else
    {
        return strcmp(disk1->disk_name, disk2->disk_name);
    }
}
static int ventoy_disk_sort(void)
{
    int i, j;
    ventoy_disk *tmp;
    tmp = malloc(sizeof(ventoy_disk));
    if (!tmp)
    {
        return 1;
    }
    for (i = 0; i < g_disk_num; i++)
    for (j = i + 1; j < g_disk_num; j++)
    {
        if (ventoy_disk_compare(g_disk_list + i, g_disk_list + j) > 0)
        {
            memcpy(tmp, g_disk_list + i, sizeof(ventoy_disk));
            memcpy(g_disk_list + i, g_disk_list + j, sizeof(ventoy_disk));
            memcpy(g_disk_list + j, tmp, sizeof(ventoy_disk));
        }
    }
    free(tmp);
    return 0;
}
int ventoy_disk_enumerate_all(void)
{
    int rc = 0;
    DIR* dir = NULL;
    struct dirent* p = NULL;
    vdebug("ventoy_disk_enumerate_all\n");
    dir = opendir("/sys/block");
    if (!dir)
    {
        vlog("Failed to open /sys/block %d\n", errno);
        return 1;
    }
    while (((p = readdir(dir)) != NULL) && (g_disk_num < MAX_DISK_NUM))
    {
        if (ventoy_is_possible_blkdev(p->d_name))
        {
            memset(g_disk_list + g_disk_num, 0, sizeof(ventoy_disk));
            if (0 == ventoy_get_disk_info(p->d_name, g_disk_list + g_disk_num))
            {
                g_disk_num++;                    
            }
        }
    }
    closedir(dir);
    ventoy_disk_sort();
    
    return rc;
}
void ventoy_disk_dump(ventoy_disk *cur)
{
    if (cur->vtoydata.ventoy_valid)
    {
        vdebug("%s [%s] %s\tVentoy: %s %s secureboot:%d preserve:%llu\n", 
            cur->disk_path, cur->human_readable_size, cur->disk_model,
            cur->vtoydata.ventoy_ver, cur->vtoydata.partition_style == MBR_PART_STYLE ? "MBR" : "GPT",
            cur->vtoydata.secure_boot_flag, (_ull)(cur->vtoydata.preserved_space));
    }
    else
    {
        vdebug("%s [%s] %s\tVentoy: NA\n", cur->disk_path, cur->human_readable_size, cur->disk_model); 
    }
}
void ventoy_disk_dump_all(void)
{
    int i;
    
    vdebug("============= DISK DUMP ============\n");
    for (i = 0; i < g_disk_num; i++)
    {
        ventoy_disk_dump(g_disk_list + i);
    }
}
int ventoy_disk_install(ventoy_disk *disk, void *efipartimg)
{
    return 0;
}
int ventoy_disk_init(void)
{
    g_disk_list = malloc(sizeof(ventoy_disk) * MAX_DISK_NUM);
    ventoy_disk_enumerate_all();
    ventoy_disk_dump_all();
    
    return 0;
}
void ventoy_disk_exit(void)
{
    check_free(g_disk_list);        
    g_disk_list = NULL;
    g_disk_num  = 0;
}
 | 19,911 | 
	C | 
	.c | 669 | 23.09417 | 116 | 0.551996 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
| 746 | 
	ventoy_log.c | 
	ventoy_Ventoy/LinuxGUI/Ventoy2Disk/Core/ventoy_log.c | 
	/******************************************************************************
 * ventoy_log.c  ---- ventoy log
 *
 * Copyright (c) 2021, longpanda <admin@ventoy.net>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#include <linux/limits.h>
#include <ventoy_define.h>
extern char g_log_file[PATH_MAX];
static int g_ventoy_log_level = VLOG_DEBUG;
static pthread_mutex_t g_log_mutex;
int ventoy_log_init(void)
{
    pthread_mutex_init(&g_log_mutex, NULL);
    return 0;
}
void ventoy_log_exit(void)
{
    pthread_mutex_destroy(&g_log_mutex);
}
void ventoy_set_loglevel(int level)
{
    g_ventoy_log_level = level;
}
void ventoy_syslog_newline(int level, const char *Fmt, ...)
{
    char log[512];
    va_list arg;
    time_t stamp;
    struct tm ttm;
    FILE *fp;
    
    if (level > g_ventoy_log_level)
    {
        return;
    }
    time(&stamp);
    localtime_r(&stamp, &ttm);
    va_start(arg, Fmt);
    vsnprintf(log, 512, Fmt, arg);
    va_end(arg);
    pthread_mutex_lock(&g_log_mutex);
    fp = fopen(g_log_file, "a+");
    if (fp)
    {
        fprintf(fp, "[%04u/%02u/%02u %02u:%02u:%02u] %s\n", 
           ttm.tm_year, ttm.tm_mon, ttm.tm_mday,
           ttm.tm_hour, ttm.tm_min, ttm.tm_sec,
           log);
        fclose(fp);
    }
    pthread_mutex_unlock(&g_log_mutex);
}
void ventoy_syslog_printf(const char *Fmt, ...)
{
    char log[512];
    va_list arg;
    time_t stamp;
    struct tm ttm;
    FILE *fp;
    
    time(&stamp);
    localtime_r(&stamp, &ttm);
    va_start(arg, Fmt);
    vsnprintf(log, 512, Fmt, arg);
    va_end(arg);
    pthread_mutex_lock(&g_log_mutex);
    fp = fopen(g_log_file, "a+");
    if (fp)
    {
        fprintf(fp, "[%04u/%02u/%02u %02u:%02u:%02u] %s", 
           ttm.tm_year, ttm.tm_mon, ttm.tm_mday,
           ttm.tm_hour, ttm.tm_min, ttm.tm_sec,
           log);
        fclose(fp);
    }
    pthread_mutex_unlock(&g_log_mutex);
}
void ventoy_syslog(int level, const char *Fmt, ...)
{
    char log[512];
    va_list arg;
    time_t stamp;
    struct tm ttm;
    FILE *fp;
    
    if (level > g_ventoy_log_level)
    {
        return;
    }
    time(&stamp);
    localtime_r(&stamp, &ttm);
    va_start(arg, Fmt);
    vsnprintf(log, 512, Fmt, arg);
    va_end(arg);
    pthread_mutex_lock(&g_log_mutex);
    fp = fopen(g_log_file, "a+");
    if (fp)
    {
        fprintf(fp, "[%04u/%02u/%02u %02u:%02u:%02u] %s", 
           ttm.tm_year + 1900, ttm.tm_mon, ttm.tm_mday,
           ttm.tm_hour, ttm.tm_min, ttm.tm_sec,
           log);
        fclose(fp);
    }
    pthread_mutex_unlock(&g_log_mutex);
}
 | 3,364 | 
	C | 
	.c | 126 | 22.134921 | 79 | 0.607733 | 
	ventoy/Ventoy | 61,575 | 4,002 | 755 | 
	GPL-3.0 | 
	9/7/2024, 9:40:14 AM (Europe/Amsterdam) | false | false | false | false | false | false | false | false | 
			Subsets and Splits
				
	
				
			
				
No community queries yet
The top public SQL queries from the community will appear here once available.
