Commit d8fbd79d authored by longpanda's avatar longpanda
Browse files

1.0.29 release

parent 8c192a18
...@@ -9,6 +9,7 @@ print_usage() { ...@@ -9,6 +9,7 @@ print_usage() {
echo ' -i install ventoy to sdX (fail if disk already installed with ventoy)' echo ' -i install ventoy to sdX (fail if disk already installed with ventoy)'
echo ' -I force install ventoy to sdX (no matter installed or not)' echo ' -I force install ventoy to sdX (no matter installed or not)'
echo ' -u update ventoy in sdX' echo ' -u update ventoy in sdX'
echo ' -l list Ventoy information in sdX'
echo '' echo ''
echo ' OPTION: (optional)' echo ' OPTION: (optional)'
echo ' -r SIZE_MB preserve some space at the bottom of the disk (only for install)' echo ' -r SIZE_MB preserve some space at the bottom of the disk (only for install)'
...@@ -29,6 +30,8 @@ while [ -n "$1" ]; do ...@@ -29,6 +30,8 @@ while [ -n "$1" ]; do
FORCE="Y" FORCE="Y"
elif [ "$1" = "-u" ]; then elif [ "$1" = "-u" ]; then
MODE="update" MODE="update"
elif [ "$1" = "-l" ]; then
MODE="list"
elif [ "$1" = "-s" ]; then elif [ "$1" = "-s" ]; then
SECUREBOOT="YES" SECUREBOOT="YES"
elif [ "$1" = "-g" ]; then elif [ "$1" = "-g" ]; then
...@@ -42,7 +45,7 @@ while [ -n "$1" ]; do ...@@ -42,7 +45,7 @@ while [ -n "$1" ]; do
RESERVE_SIZE_MB=$1 RESERVE_SIZE_MB=$1
elif [ "$1" = "-V" ] || [ "$1" = "--version" ]; then elif [ "$1" = "-V" ] || [ "$1" = "--version" ]; then
exit 0 exit 0
elif [ "$1" == "-h" ] || [ "$1" = "--help" ]; then elif [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
print_usage print_usage
exit 0 exit 0
else else
...@@ -76,7 +79,7 @@ if [ -e /sys/class/block/${DISK#/dev/}/start ]; then ...@@ -76,7 +79,7 @@ if [ -e /sys/class/block/${DISK#/dev/}/start ]; then
exit 1 exit 1
fi fi
if [ -n "$RESERVE_SPACE" ]; then if [ -n "$RESERVE_SPACE" -a "$MODE" = "install" ]; then
if echo $RESERVE_SIZE_MB | grep -q '^[0-9][0-9]*$'; then if echo $RESERVE_SIZE_MB | grep -q '^[0-9][0-9]*$'; then
vtdebug "User will reserve $RESERVE_SIZE_MB MB disk space" vtdebug "User will reserve $RESERVE_SIZE_MB MB disk space"
else else
...@@ -104,6 +107,36 @@ else ...@@ -104,6 +107,36 @@ else
exit 1 exit 1
fi fi
if [ "$MODE" = "list" ]; then
version=$(get_disk_ventoy_version $DISK)
if [ $? -eq 0 ]; then
echo "Ventoy Version in Disk: $version"
vtPart1Type=$(dd if=$DISK bs=1 count=1 skip=450 status=none | hexdump -n1 -e '1/1 "%02X"')
if [ "$vtPart1Type" = "EE" ]; then
echo "Disk Partition Style : GPT"
else
echo "Disk Partition Style : MBR"
fi
vtPART2=$(get_disk_part_name $DISK 2)
rm -rf ./tmpmntp2 && mkdir ./tmpmntp2
mount $vtPART2 ./tmpmntp2 > /dev/null 2>&1
if [ -e ./tmpmntp2/EFI/BOOT/MokManager.efi ]; then
echo "Secure Boot Support : YES"
else
echo "Secure Boot Support : NO"
fi
umount ./tmpmntp2 > /dev/null 2>&1
rm -rf ./tmpmntp2
else
echo "Ventoy Version: NA"
fi
echo ""
exit 0
fi
#check mountpoint #check mountpoint
grep "^$DISK" /proc/mounts | while read mtline; do grep "^$DISK" /proc/mounts | while read mtline; do
mtpnt=$(echo $mtline | awk '{print $2}') mtpnt=$(echo $mtline | awk '{print $2}')
...@@ -345,7 +378,7 @@ else ...@@ -345,7 +378,7 @@ else
SHORT_PART2=${PART2#/dev/} SHORT_PART2=${PART2#/dev/}
part2_start=$(cat /sys/class/block/$SHORT_PART2/start) part2_start=$(cat /sys/class/block/$SHORT_PART2/start)
PART1_TYPE=$(dd if=$DISK bs=1 count=1 skip=450 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"') PART1_TYPE=$(dd if=$DISK bs=1 count=1 skip=450 status=none | hexdump -n1 -e '1/1 "%02X"')
if [ "$PART1_TYPE" = "EE" ]; then if [ "$PART1_TYPE" = "EE" ]; then
vtdebug "This is GPT partition style ..." vtdebug "This is GPT partition style ..."
...@@ -355,8 +388,8 @@ else ...@@ -355,8 +388,8 @@ else
vtdebug "This is MBR partition style ..." vtdebug "This is MBR partition style ..."
dd status=none conv=fsync if=./boot/boot.img of=$DISK bs=1 count=440 dd status=none conv=fsync if=./boot/boot.img of=$DISK bs=1 count=440
PART1_ACTIVE=$(dd if=$DISK bs=1 count=1 skip=446 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"') PART1_ACTIVE=$(dd if=$DISK bs=1 count=1 skip=446 status=none | hexdump -n1 -e '1/1 "%02X"')
PART2_ACTIVE=$(dd if=$DISK bs=1 count=1 skip=462 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"') PART2_ACTIVE=$(dd if=$DISK bs=1 count=1 skip=462 status=none | hexdump -n1 -e '1/1 "%02X"')
vtdebug "PART1_ACTIVE=$PART1_ACTIVE PART2_ACTIVE=$PART2_ACTIVE" vtdebug "PART1_ACTIVE=$PART1_ACTIVE PART2_ACTIVE=$PART2_ACTIVE"
if [ "$PART1_ACTIVE" = "00" ] && [ "$PART2_ACTIVE" = "80" ]; then if [ "$PART1_ACTIVE" = "00" ] && [ "$PART2_ACTIVE" = "80" ]; then
......
...@@ -128,8 +128,8 @@ is_disk_contains_ventoy() { ...@@ -128,8 +128,8 @@ is_disk_contains_ventoy() {
return return
fi fi
PART1_TYPE=$(dd if=$DISK bs=1 count=1 skip=450 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"') PART1_TYPE=$(dd if=$DISK bs=1 count=1 skip=450 status=none | hexdump -n1 -e '1/1 "%02X"')
PART2_TYPE=$(dd if=$DISK bs=1 count=1 skip=466 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"') PART2_TYPE=$(dd if=$DISK bs=1 count=1 skip=466 status=none | hexdump -n1 -e '1/1 "%02X"')
# if [ "$PART1_TYPE" != "EE" ]; then # if [ "$PART1_TYPE" != "EE" ]; then
# if [ "$PART2_TYPE" != "EF" ]; then # if [ "$PART2_TYPE" != "EF" ]; then
...@@ -139,7 +139,7 @@ is_disk_contains_ventoy() { ...@@ -139,7 +139,7 @@ is_disk_contains_ventoy() {
# fi # fi
# fi # fi
# PART1_TYPE=$(dd if=$DISK bs=1 count=1 skip=450 status=none | ./tool/hexdump -n1 -e '1/1 "%02X"') # PART1_TYPE=$(dd if=$DISK bs=1 count=1 skip=450 status=none | hexdump -n1 -e '1/1 "%02X"')
# if [ "$PART1_TYPE" != "07" ]; then # if [ "$PART1_TYPE" != "07" ]; then
# vtdebug "part1 type is $PART2_TYPE not 07" # vtdebug "part1 type is $PART2_TYPE not 07"
# ventoy_false # ventoy_false
......
File suppressed by a .gitattributes entry or the file's encoding is unsupported.
/****************************************************************************** /******************************************************************************
* vtoyjump.c * vtoyjump.c
* *
* Copyright (c) 2020, longpanda <admin@ventoy.net> * Copyright (c) 2020, longpanda <admin@ventoy.net>
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as * modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 3 of the * published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version. * License, or (at your option) any later version.
* *
* This program is distributed in the hope that it will be useful, but * This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of * WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details. * General Public License for more details.
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>. * along with this program; if not, see <http://www.gnu.org/licenses/>.
* *
*/ */
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <Windows.h> #include <Windows.h>
#include <virtdisk.h> #include <virtdisk.h>
#include <winioctl.h> #include <winioctl.h>
#include <VersionHelpers.h> #include <VersionHelpers.h>
#include "vtoyjump.h" #include "vtoyjump.h"
#include "fat_filelib.h" #include "fat_filelib.h"
static ventoy_os_param g_os_param; static ventoy_os_param g_os_param;
static ventoy_windows_data g_windows_data; static ventoy_windows_data g_windows_data;
static UINT8 g_os_param_reserved[32]; static UINT8 g_os_param_reserved[32];
static BOOL g_64bit_system = FALSE; static BOOL g_64bit_system = FALSE;
static ventoy_guid g_ventoy_guid = VENTOY_GUID; static ventoy_guid g_ventoy_guid = VENTOY_GUID;
void Log(const char *Fmt, ...) void Log(const char *Fmt, ...)
{ {
va_list Arg; va_list Arg;
int Len = 0; int Len = 0;
FILE *File = NULL; FILE *File = NULL;
SYSTEMTIME Sys; SYSTEMTIME Sys;
char szBuf[1024]; char szBuf[1024];
GetLocalTime(&Sys); GetLocalTime(&Sys);
Len += sprintf_s(szBuf, sizeof(szBuf), Len += sprintf_s(szBuf, sizeof(szBuf),
"[%4d/%02d/%02d %02d:%02d:%02d.%03d] ", "[%4d/%02d/%02d %02d:%02d:%02d.%03d] ",
Sys.wYear, Sys.wMonth, Sys.wDay, Sys.wYear, Sys.wMonth, Sys.wDay,
Sys.wHour, Sys.wMinute, Sys.wSecond, Sys.wHour, Sys.wMinute, Sys.wSecond,
Sys.wMilliseconds); Sys.wMilliseconds);
va_start(Arg, Fmt); va_start(Arg, Fmt);
Len += vsnprintf_s(szBuf + Len, sizeof(szBuf)-Len, sizeof(szBuf)-Len, Fmt, Arg); Len += vsnprintf_s(szBuf + Len, sizeof(szBuf)-Len, sizeof(szBuf)-Len, Fmt, Arg);
va_end(Arg); va_end(Arg);
fopen_s(&File, "ventoy.log", "a+"); fopen_s(&File, "ventoy.log", "a+");
if (File) if (File)
{ {
fwrite(szBuf, 1, Len, File); fwrite(szBuf, 1, Len, File);
fwrite("\n", 1, 1, File); fwrite("\n", 1, 1, File);
fclose(File); fclose(File);
} }
} }
static int LoadNtDriver(const char *DrvBinPath) static int LoadNtDriver(const char *DrvBinPath)
{ {
int i; int i;
int rc = 0; int rc = 0;
BOOL Ret; BOOL Ret;
DWORD Status; DWORD Status;
SC_HANDLE hServiceMgr; SC_HANDLE hServiceMgr;
SC_HANDLE hService; SC_HANDLE hService;
char name[256] = { 0 }; char name[256] = { 0 };
for (i = (int)strlen(DrvBinPath) - 1; i >= 0; i--) for (i = (int)strlen(DrvBinPath) - 1; i >= 0; i--)
{ {
if (DrvBinPath[i] == '\\' || DrvBinPath[i] == '/') if (DrvBinPath[i] == '\\' || DrvBinPath[i] == '/')
{ {
sprintf_s(name, sizeof(name), "%s", DrvBinPath + i + 1); sprintf_s(name, sizeof(name), "%s", DrvBinPath + i + 1);
break; break;
} }
} }
Log("Load NT driver: %s %s", DrvBinPath, name); Log("Load NT driver: %s %s", DrvBinPath, name);
hServiceMgr = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS); hServiceMgr = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (hServiceMgr == NULL) if (hServiceMgr == NULL)
{ {
Log("OpenSCManager failed Error:%u", GetLastError()); Log("OpenSCManager failed Error:%u", GetLastError());
return 1; return 1;
} }
Log("OpenSCManager OK"); Log("OpenSCManager OK");
hService = CreateServiceA(hServiceMgr, hService = CreateServiceA(hServiceMgr,
name, name,
name, name,
SERVICE_ALL_ACCESS, SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER, SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START, SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL, SERVICE_ERROR_NORMAL,
DrvBinPath, DrvBinPath,
NULL, NULL, NULL, NULL, NULL); NULL, NULL, NULL, NULL, NULL);
if (hService == NULL) if (hService == NULL)
{ {
Status = GetLastError(); Status = GetLastError();
if (Status != ERROR_IO_PENDING && Status != ERROR_SERVICE_EXISTS) if (Status != ERROR_IO_PENDING && Status != ERROR_SERVICE_EXISTS)
{ {
Log("CreateService failed v %u", Status); Log("CreateService failed v %u", Status);
CloseServiceHandle(hServiceMgr); CloseServiceHandle(hServiceMgr);
return 1; return 1;
} }
hService = OpenServiceA(hServiceMgr, name, SERVICE_ALL_ACCESS); hService = OpenServiceA(hServiceMgr, name, SERVICE_ALL_ACCESS);
if (hService == NULL) if (hService == NULL)
{ {
Log("OpenService failed %u", Status); Log("OpenService failed %u", Status);
CloseServiceHandle(hServiceMgr); CloseServiceHandle(hServiceMgr);
return 1; return 1;
} }
} }
Log("CreateService imdisk OK"); Log("CreateService imdisk OK");
Ret = StartServiceA(hService, 0, NULL); Ret = StartServiceA(hService, 0, NULL);
if (Ret) if (Ret)
{ {
Log("StartService OK"); Log("StartService OK");
} }
else else
{ {
Status = GetLastError(); Status = GetLastError();
if (Status == ERROR_SERVICE_ALREADY_RUNNING) if (Status == ERROR_SERVICE_ALREADY_RUNNING)
{ {
rc = 0; rc = 0;
} }
else else
{ {
Log("StartService error %u", Status); Log("StartService error %u", Status);
rc = 1; rc = 1;
} }
} }
CloseServiceHandle(hService); CloseServiceHandle(hService);
CloseServiceHandle(hServiceMgr); CloseServiceHandle(hServiceMgr);
Log("Load NT driver %s", rc ? "failed" : "success"); Log("Load NT driver %s", rc ? "failed" : "success");
return rc; return rc;
} }
static int ReadWholeFile2Buf(const char *Fullpath, void **Data, DWORD *Size) static int ReadWholeFile2Buf(const char *Fullpath, void **Data, DWORD *Size)
{ {
int rc = 1; int rc = 1;
DWORD FileSize; DWORD FileSize;
DWORD dwSize; DWORD dwSize;
HANDLE Handle; HANDLE Handle;
BYTE *Buffer = NULL; BYTE *Buffer = NULL;
Log("ReadWholeFile2Buf <%s>", Fullpath); Log("ReadWholeFile2Buf <%s>", Fullpath);
Handle = CreateFileA(Fullpath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); Handle = CreateFileA(Fullpath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (Handle == INVALID_HANDLE_VALUE) if (Handle == INVALID_HANDLE_VALUE)
{ {
Log("Could not open the file<%s>, error:%u", Fullpath, GetLastError()); Log("Could not open the file<%s>, error:%u", Fullpath, GetLastError());
goto End; goto End;
} }
FileSize = SetFilePointer(Handle, 0, NULL, FILE_END); FileSize = SetFilePointer(Handle, 0, NULL, FILE_END);
Buffer = malloc(FileSize); Buffer = malloc(FileSize);
if (!Buffer) if (!Buffer)
{ {
Log("Failed to alloc memory size:%u", FileSize); Log("Failed to alloc memory size:%u", FileSize);
goto End; goto End;
} }
SetFilePointer(Handle, 0, NULL, FILE_BEGIN); SetFilePointer(Handle, 0, NULL, FILE_BEGIN);
if (!ReadFile(Handle, Buffer, FileSize, &dwSize, NULL)) if (!ReadFile(Handle, Buffer, FileSize, &dwSize, NULL))
{ {
Log("ReadFile failed, dwSize:%u error:%u", dwSize, GetLastError()); Log("ReadFile failed, dwSize:%u error:%u", dwSize, GetLastError());
goto End; goto End;
} }
*Data = Buffer; *Data = Buffer;
*Size = FileSize; *Size = FileSize;
Log("Success read file size:%u", FileSize); Log("Success read file size:%u", FileSize);
rc = 0; rc = 0;
End: End:
SAFE_CLOSE_HANDLE(Handle); SAFE_CLOSE_HANDLE(Handle);
return rc; return rc;
} }
static BOOL CheckPeHead(BYTE *Head) static BOOL CheckPeHead(BYTE *Head)
{ {
UINT32 PeOffset; UINT32 PeOffset;
if (Head[0] != 'M' || Head[1] != 'Z') if (Head[0] != 'M' || Head[1] != 'Z')
{ {
return FALSE; return FALSE;
} }
PeOffset = *(UINT32 *)(Head + 60); PeOffset = *(UINT32 *)(Head + 60);
if (*(UINT32 *)(Head + PeOffset) != 0x00004550) if (*(UINT32 *)(Head + PeOffset) != 0x00004550)
{ {
return FALSE; return FALSE;
} }
return TRUE; return TRUE;
} }
static BOOL IsPe64(BYTE *buffer) static BOOL IsPe64(BYTE *buffer)
{ {
DWORD pe_off; DWORD pe_off;
if (!CheckPeHead(buffer)) if (!CheckPeHead(buffer))
{ {
return FALSE; return FALSE;
} }
pe_off = *(UINT32 *)(buffer + 60); pe_off = *(UINT32 *)(buffer + 60);
if (*(UINT16 *)(buffer + pe_off + 24) == 0x020b) if (*(UINT16 *)(buffer + pe_off + 24) == 0x020b)
{ {
return TRUE; return TRUE;
} }
return FALSE; return FALSE;
} }
static BOOL CheckOsParam(ventoy_os_param *param) static BOOL CheckOsParam(ventoy_os_param *param)
{ {
UINT32 i; UINT32 i;
BYTE Sum = 0; BYTE Sum = 0;
if (memcmp(&param->guid, &g_ventoy_guid, sizeof(ventoy_guid))) if (memcmp(&param->guid, &g_ventoy_guid, sizeof(ventoy_guid)))
{ {
return FALSE; return FALSE;
} }
for (i = 0; i < sizeof(ventoy_os_param); i++) for (i = 0; i < sizeof(ventoy_os_param); i++)
{ {
Sum += *((BYTE *)param + i); Sum += *((BYTE *)param + i);
} }
if (Sum) if (Sum)
{ {
return FALSE; return FALSE;
} }
if (param->vtoy_img_location_addr % 4096) if (param->vtoy_img_location_addr % 4096)
{ {
return FALSE; return FALSE;
} }
return TRUE; return TRUE;
} }
static int SaveBuffer2File(const char *Fullpath, void *Buffer, DWORD Length) static int SaveBuffer2File(const char *Fullpath, void *Buffer, DWORD Length)
{ {
int rc = 1; int rc = 1;
DWORD dwSize; DWORD dwSize;
HANDLE Handle; HANDLE Handle;
Log("SaveBuffer2File <%s> len:%u", Fullpath, Length); Log("SaveBuffer2File <%s> len:%u", Fullpath, Length);
Handle = CreateFileA(Fullpath, GENERIC_READ | GENERIC_WRITE, Handle = CreateFileA(Fullpath, GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, 0, CREATE_NEW, 0, 0); FILE_SHARE_READ | FILE_SHARE_WRITE, 0, CREATE_NEW, 0, 0);
if (Handle == INVALID_HANDLE_VALUE) if (Handle == INVALID_HANDLE_VALUE)
{ {
Log("Could not create new file, error:%u", GetLastError()); Log("Could not create new file, error:%u", GetLastError());
goto End; goto End;
} }
WriteFile(Handle, Buffer, Length, &dwSize, NULL); WriteFile(Handle, Buffer, Length, &dwSize, NULL);
rc = 0; rc = 0;
End: End:
SAFE_CLOSE_HANDLE(Handle); SAFE_CLOSE_HANDLE(Handle);
return rc; return rc;
} }
static BOOL IsPathExist(BOOL Dir, const char *Fmt, ...) static int IsUTF8Encode(const char *src)
{ {
va_list Arg; int i;
HANDLE hFile; const UCHAR *Byte = (const UCHAR *)src;
DWORD Attr;
CHAR FilePath[MAX_PATH]; for (i = 0; i < MAX_PATH && Byte[i]; i++)
{
va_start(Arg, Fmt); if (Byte[i] > 127)
vsnprintf_s(FilePath, sizeof(FilePath), sizeof(FilePath), Fmt, Arg); {
va_end(Arg); return 1;
}
hFile = CreateFileA(FilePath, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0); }
if (INVALID_HANDLE_VALUE == hFile)
{ return 0;
return FALSE; }
}
static int Utf8ToUtf16(const char* src, WCHAR * dst)
CloseHandle(hFile); {
int size = MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, 0);
Attr = GetFileAttributesA(FilePath); return MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, size + 1);
}
if (Dir)
{ static BOOL IsPathExist(BOOL Dir, const char *Fmt, ...)
if ((Attr & FILE_ATTRIBUTE_DIRECTORY) == 0) {
{ va_list Arg;
return FALSE; HANDLE hFile;
} DWORD Attr;
} int UTF8 = 0;
else CHAR FilePathA[MAX_PATH];
{ WCHAR FilePathW[MAX_PATH];
if (Attr & FILE_ATTRIBUTE_DIRECTORY)
{ va_start(Arg, Fmt);
return FALSE; vsnprintf_s(FilePathA, sizeof(FilePathA), sizeof(FilePathA), Fmt, Arg);
} va_end(Arg);
}
UTF8 = IsUTF8Encode(FilePathA);
return TRUE;
} if (UTF8)
{
static int GetPhyDiskUUID(const char LogicalDrive, UINT8 *UUID, DISK_EXTENT *DiskExtent) Utf8ToUtf16(FilePathA, FilePathW);
{ hFile = CreateFileW(FilePathW, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
BOOL Ret; }
DWORD dwSize; else
HANDLE Handle; {
VOLUME_DISK_EXTENTS DiskExtents; hFile = CreateFileA(FilePathA, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
CHAR PhyPath[128]; }
UINT8 SectorBuf[512]; if (INVALID_HANDLE_VALUE == hFile)
{
Log("GetPhyDiskUUID %C", LogicalDrive); return FALSE;
}
sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\%C:", LogicalDrive);
Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); CloseHandle(hFile);
if (Handle == INVALID_HANDLE_VALUE)
{ if (UTF8)
Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError()); {
return 1; Attr = GetFileAttributesW(FilePathW);
} }
else
Ret = DeviceIoControl(Handle, {
IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, Attr = GetFileAttributesA(FilePathA);
NULL, }
0,
&DiskExtents, if (Dir)
(DWORD)(sizeof(DiskExtents)), {
(LPDWORD)&dwSize, if ((Attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
NULL); {
if (!Ret || DiskExtents.NumberOfDiskExtents == 0) return FALSE;
{ }
Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed, error:%u", GetLastError()); }
CloseHandle(Handle); else
return 1; {
} if (Attr & FILE_ATTRIBUTE_DIRECTORY)
CloseHandle(Handle); {
return FALSE;
memcpy(DiskExtent, DiskExtents.Extents, sizeof(DiskExtent)); }
Log("%C: is in PhysicalDrive%d ", LogicalDrive, DiskExtents.Extents[0].DiskNumber); }
sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\PhysicalDrive%d", DiskExtents.Extents[0].DiskNumber); return TRUE;
Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); }
if (Handle == INVALID_HANDLE_VALUE)
{ static int GetPhyDiskUUID(const char LogicalDrive, UINT8 *UUID, DISK_EXTENT *DiskExtent)
Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError()); {
return 1; BOOL Ret;
} DWORD dwSize;
HANDLE Handle;
if (!ReadFile(Handle, SectorBuf, sizeof(SectorBuf), &dwSize, NULL)) VOLUME_DISK_EXTENTS DiskExtents;
{ CHAR PhyPath[128];
Log("ReadFile failed, dwSize:%u error:%u", dwSize, GetLastError()); UINT8 SectorBuf[512];
CloseHandle(Handle);
return 1; Log("GetPhyDiskUUID %C", LogicalDrive);
}
sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\%C:", LogicalDrive);
memcpy(UUID, SectorBuf + 0x180, 16); Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
CloseHandle(Handle); if (Handle == INVALID_HANDLE_VALUE)
return 0; {
} Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError());
return 1;
int VentoyMountISOByAPI(const char *IsoPath) }
{
HANDLE Handle; Ret = DeviceIoControl(Handle,
DWORD Status; IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
WCHAR wFilePath[512] = { 0 }; NULL,
VIRTUAL_STORAGE_TYPE StorageType; 0,
OPEN_VIRTUAL_DISK_PARAMETERS OpenParameters; &DiskExtents,
ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters; (DWORD)(sizeof(DiskExtents)),
(LPDWORD)&dwSize,
Log("VentoyMountISOByAPI <%s>", IsoPath); NULL);
if (!Ret || DiskExtents.NumberOfDiskExtents == 0)
MultiByteToWideChar(CP_ACP, 0, IsoPath, (int)strlen(IsoPath), wFilePath, (int)(sizeof(wFilePath) / sizeof(WCHAR))); {
Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed, error:%u", GetLastError());
memset(&StorageType, 0, sizeof(StorageType)); CloseHandle(Handle);
memset(&OpenParameters, 0, sizeof(OpenParameters)); return 1;
memset(&AttachParameters, 0, sizeof(AttachParameters)); }
CloseHandle(Handle);
OpenParameters.Version = OPEN_VIRTUAL_DISK_VERSION_1;
AttachParameters.Version = ATTACH_VIRTUAL_DISK_VERSION_1; memcpy(DiskExtent, DiskExtents.Extents, sizeof(DiskExtent));
Log("%C: is in PhysicalDrive%d ", LogicalDrive, DiskExtents.Extents[0].DiskNumber);
Status = OpenVirtualDisk(&StorageType, wFilePath, VIRTUAL_DISK_ACCESS_READ, 0, &OpenParameters, &Handle);
if (Status != ERROR_SUCCESS) sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\PhysicalDrive%d", DiskExtents.Extents[0].DiskNumber);
{ Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (ERROR_VIRTDISK_PROVIDER_NOT_FOUND == Status) if (Handle == INVALID_HANDLE_VALUE)
{ {
Log("VirtualDisk for ISO file is not supported in current system"); Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError());
} return 1;
else }
{
Log("Failed to open virtual disk ErrorCode:%u", Status); if (!ReadFile(Handle, SectorBuf, sizeof(SectorBuf), &dwSize, NULL))
} {
return 1; Log("ReadFile failed, dwSize:%u error:%u", dwSize, GetLastError());
} CloseHandle(Handle);
return 1;
Log("OpenVirtualDisk success"); }
Status = AttachVirtualDisk(Handle, NULL, ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY | ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME, 0, &AttachParameters, NULL); memcpy(UUID, SectorBuf + 0x180, 16);
if (Status != ERROR_SUCCESS) CloseHandle(Handle);
{ return 0;
Log("Failed to attach virtual disk ErrorCode:%u", Status); }
CloseHandle(Handle);
return 1; int VentoyMountISOByAPI(const char *IsoPath)
} {
HANDLE Handle;
CloseHandle(Handle); DWORD Status;
return 0; WCHAR wFilePath[512] = { 0 };
} VIRTUAL_STORAGE_TYPE StorageType;
OPEN_VIRTUAL_DISK_PARAMETERS OpenParameters;
ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters;
static HANDLE g_FatPhyDrive;
static UINT64 g_Part2StartSec; Log("VentoyMountISOByAPI <%s>", IsoPath);
static int CopyFileFromFatDisk(const CHAR* SrcFile, const CHAR *DstFile) if (IsUTF8Encode(IsoPath))
{ {
int rc = 1; MultiByteToWideChar(CP_UTF8, 0, IsoPath, (int)strlen(IsoPath), wFilePath, (int)(sizeof(wFilePath) / sizeof(WCHAR)));
int size = 0; }
char *buf = NULL; else
void *flfile = NULL; {
MultiByteToWideChar(CP_ACP, 0, IsoPath, (int)strlen(IsoPath), wFilePath, (int)(sizeof(wFilePath) / sizeof(WCHAR)));
Log("CopyFileFromFatDisk (%s)==>(%s)", SrcFile, DstFile); }
flfile = fl_fopen(SrcFile, "rb"); memset(&StorageType, 0, sizeof(StorageType));
if (flfile) memset(&OpenParameters, 0, sizeof(OpenParameters));
{ memset(&AttachParameters, 0, sizeof(AttachParameters));
fl_fseek(flfile, 0, SEEK_END);
size = (int)fl_ftell(flfile); OpenParameters.Version = OPEN_VIRTUAL_DISK_VERSION_1;
fl_fseek(flfile, 0, SEEK_SET); AttachParameters.Version = ATTACH_VIRTUAL_DISK_VERSION_1;
buf = (char *)malloc(size); Status = OpenVirtualDisk(&StorageType, wFilePath, VIRTUAL_DISK_ACCESS_READ, 0, &OpenParameters, &Handle);
if (buf) if (Status != ERROR_SUCCESS)
{ {
fl_fread(buf, 1, size, flfile); if (ERROR_VIRTDISK_PROVIDER_NOT_FOUND == Status)
{
rc = 0; Log("VirtualDisk for ISO file is not supported in current system");
SaveBuffer2File(DstFile, buf, size); }
free(buf); else
} {
Log("Failed to open virtual disk ErrorCode:%u", Status);
fl_fclose(flfile); }
} return 1;
}
return rc;
} Log("OpenVirtualDisk success");
static int VentoyFatDiskRead(uint32 Sector, uint8 *Buffer, uint32 SectorCount) Status = AttachVirtualDisk(Handle, NULL, ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY | ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME, 0, &AttachParameters, NULL);
{ if (Status != ERROR_SUCCESS)
DWORD dwSize; {
BOOL bRet; Log("Failed to attach virtual disk ErrorCode:%u", Status);
DWORD ReadSize; CloseHandle(Handle);
LARGE_INTEGER liCurrentPosition; return 1;
}
liCurrentPosition.QuadPart = Sector + g_Part2StartSec;
liCurrentPosition.QuadPart *= 512; CloseHandle(Handle);
SetFilePointerEx(g_FatPhyDrive, liCurrentPosition, &liCurrentPosition, FILE_BEGIN); return 0;
}
ReadSize = (DWORD)(SectorCount * 512);
bRet = ReadFile(g_FatPhyDrive, Buffer, ReadSize, &dwSize, NULL); static HANDLE g_FatPhyDrive;
if (bRet == FALSE || dwSize != ReadSize) static UINT64 g_Part2StartSec;
{
Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u\n", bRet, ReadSize, dwSize, GetLastError()); static int CopyFileFromFatDisk(const CHAR* SrcFile, const CHAR *DstFile)
} {
int rc = 1;
return 1; int size = 0;
} char *buf = NULL;
void *flfile = NULL;
static CHAR GetMountLogicalDrive(void)
{ Log("CopyFileFromFatDisk (%s)==>(%s)", SrcFile, DstFile);
CHAR Letter = 'Y';
DWORD Drives; flfile = fl_fopen(SrcFile, "rb");
DWORD Mask = 0x1000000; if (flfile)
{
Drives = GetLogicalDrives(); fl_fseek(flfile, 0, SEEK_END);
Log("Drives=0x%x", Drives); size = (int)fl_ftell(flfile);
fl_fseek(flfile, 0, SEEK_SET);
while (Mask)
{ buf = (char *)malloc(size);
if ((Drives & Mask) == 0) if (buf)
{ {
break; fl_fread(buf, 1, size, flfile);
}
rc = 0;
Letter--; SaveBuffer2File(DstFile, buf, size);
Mask >>= 1; free(buf);
} }
return Letter; fl_fclose(flfile);
} }
UINT64 GetVentoyEfiPartStartSector(HANDLE hDrive) return rc;
{ }
BOOL bRet;
DWORD dwSize; static int VentoyFatDiskRead(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
MBR_HEAD MBR; {
VTOY_GPT_INFO *pGpt = NULL; DWORD dwSize;
UINT64 StartSector = 0; BOOL bRet;
DWORD ReadSize;
SetFilePointer(hDrive, 0, NULL, FILE_BEGIN); LARGE_INTEGER liCurrentPosition;
bRet = ReadFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL); liCurrentPosition.QuadPart = Sector + g_Part2StartSec;
Log("Read MBR Ret:%u Size:%u code:%u", bRet, dwSize, LASTERR); liCurrentPosition.QuadPart *= 512;
SetFilePointerEx(g_FatPhyDrive, liCurrentPosition, &liCurrentPosition, FILE_BEGIN);
if ((!bRet) || (dwSize != sizeof(MBR)))
{ ReadSize = (DWORD)(SectorCount * 512);
0;
} bRet = ReadFile(g_FatPhyDrive, Buffer, ReadSize, &dwSize, NULL);
if (bRet == FALSE || dwSize != ReadSize)
if (MBR.PartTbl[0].FsFlag == 0xEE) {
{ Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u\n", bRet, ReadSize, dwSize, GetLastError());
Log("GPT partition style"); }
pGpt = malloc(sizeof(VTOY_GPT_INFO)); return 1;
if (!pGpt) }
{
return 0; static CHAR GetMountLogicalDrive(void)
} {
CHAR Letter = 'Y';
SetFilePointer(hDrive, 0, NULL, FILE_BEGIN); DWORD Drives;
bRet = ReadFile(hDrive, pGpt, sizeof(VTOY_GPT_INFO), &dwSize, NULL); DWORD Mask = 0x1000000;
if ((!bRet) || (dwSize != sizeof(VTOY_GPT_INFO)))
{ Drives = GetLogicalDrives();
Log("Failed to read gpt info %d %u %d", bRet, dwSize, LASTERR); Log("Drives=0x%x", Drives);
return 0;
} while (Mask)
{
StartSector = pGpt->PartTbl[1].StartLBA; if ((Drives & Mask) == 0)
free(pGpt); {
} break;
else }
{
Log("MBR partition style"); Letter--;
StartSector = MBR.PartTbl[1].StartSectorId; Mask >>= 1;
} }
Log("GetVentoyEfiPart StartSector: %llu", StartSector); return Letter;
return StartSector; }
}
UINT64 GetVentoyEfiPartStartSector(HANDLE hDrive)
int VentoyMountISOByImdisk(const char *IsoPath, DWORD PhyDrive) {
{ BOOL bRet;
int rc = 1; DWORD dwSize;
BOOL bRet; MBR_HEAD MBR;
CHAR Letter; VTOY_GPT_INFO *pGpt = NULL;
DWORD dwBytes; UINT64 StartSector = 0;
HANDLE hDrive;
CHAR PhyPath[MAX_PATH]; SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
STARTUPINFOA Si;
PROCESS_INFORMATION Pi; bRet = ReadFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL);
GET_LENGTH_INFORMATION LengthInfo; Log("Read MBR Ret:%u Size:%u code:%u", bRet, dwSize, LASTERR);
Log("VentoyMountISOByImdisk %s", IsoPath); if ((!bRet) || (dwSize != sizeof(MBR)))
{
sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\PhysicalDrive%d", PhyDrive); 0;
hDrive = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); }
if (hDrive == INVALID_HANDLE_VALUE)
{ if (MBR.PartTbl[0].FsFlag == 0xEE)
Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError()); {
goto End; Log("GPT partition style");
}
pGpt = malloc(sizeof(VTOY_GPT_INFO));
bRet = DeviceIoControl(hDrive, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &LengthInfo, sizeof(LengthInfo), &dwBytes, NULL); if (!pGpt)
if (!bRet) {
{ return 0;
Log("Could not get phy disk %s size, error:%u", PhyPath, GetLastError()); }
goto End;
} SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
bRet = ReadFile(hDrive, pGpt, sizeof(VTOY_GPT_INFO), &dwSize, NULL);
g_FatPhyDrive = hDrive; if ((!bRet) || (dwSize != sizeof(VTOY_GPT_INFO)))
g_Part2StartSec = GetVentoyEfiPartStartSector(hDrive); {
Log("Failed to read gpt info %d %u %d", bRet, dwSize, LASTERR);
Log("Parse FAT fs..."); return 0;
}
fl_init();
StartSector = pGpt->PartTbl[1].StartLBA;
if (0 == fl_attach_media(VentoyFatDiskRead, NULL)) free(pGpt);
{ }
if (g_64bit_system) else
{ {
CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.sys", "ventoy\\imdisk.sys"); Log("MBR partition style");
CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.exe", "ventoy\\imdisk.exe"); StartSector = MBR.PartTbl[1].StartSectorId;
CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.cpl", "ventoy\\imdisk.cpl"); }
}
else Log("GetVentoyEfiPart StartSector: %llu", StartSector);
{ return StartSector;
CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.sys", "ventoy\\imdisk.sys"); }
CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.exe", "ventoy\\imdisk.exe");
CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.cpl", "ventoy\\imdisk.cpl"); int VentoyMountISOByImdisk(const char *IsoPath, DWORD PhyDrive)
} {
int rc = 1;
GetCurrentDirectoryA(sizeof(PhyPath), PhyPath); BOOL bRet;
strcat_s(PhyPath, sizeof(PhyPath), "\\ventoy\\imdisk.sys"); CHAR Letter;
DWORD dwBytes;
if (LoadNtDriver(PhyPath) == 0) HANDLE hDrive;
{ CHAR PhyPath[MAX_PATH];
rc = 0; WCHAR PhyPathW[MAX_PATH];
STARTUPINFOA Si;
Letter = GetMountLogicalDrive(); PROCESS_INFORMATION Pi;
sprintf_s(PhyPath, sizeof(PhyPath), "ventoy\\imdisk.exe -a -o ro -f %s -m %C:", IsoPath, Letter); GET_LENGTH_INFORMATION LengthInfo;
Log("mount iso to %C: use imdisk cmd <%s>", Letter, PhyPath); Log("VentoyMountISOByImdisk %s", IsoPath);
GetStartupInfoA(&Si); sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\PhysicalDrive%d", PhyDrive);
if (IsUTF8Encode(PhyPath))
Si.dwFlags |= STARTF_USESHOWWINDOW; {
Si.wShowWindow = SW_HIDE; Utf8ToUtf16(PhyPath, PhyPathW);
hDrive = CreateFileW(PhyPathW, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
CreateProcessA(NULL, PhyPath, NULL, NULL, FALSE, 0, NULL, NULL, &Si, &Pi); }
WaitForSingleObject(Pi.hProcess, INFINITE); else
} {
} hDrive = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
fl_shutdown(); }
End: if (hDrive == INVALID_HANDLE_VALUE)
{
SAFE_CLOSE_HANDLE(hDrive); Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError());
goto End;
return rc; }
}
bRet = DeviceIoControl(hDrive, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &LengthInfo, sizeof(LengthInfo), &dwBytes, NULL);
static int MountIsoFile(CONST CHAR *IsoPath, DWORD PhyDrive) if (!bRet)
{ {
if (IsWindows8OrGreater()) Log("Could not get phy disk %s size, error:%u", PhyPath, GetLastError());
{ goto End;
Log("This is Windows 8 or latter..."); }
if (VentoyMountISOByAPI(IsoPath) == 0)
{ g_FatPhyDrive = hDrive;
Log("Mount iso by API success"); g_Part2StartSec = GetVentoyEfiPartStartSector(hDrive);
return 0;
} Log("Parse FAT fs...");
else
{ fl_init();
Log("Mount iso by API failed, maybe not supported, try imdisk");
return VentoyMountISOByImdisk(IsoPath, PhyDrive); if (0 == fl_attach_media(VentoyFatDiskRead, NULL))
} {
} if (g_64bit_system)
else {
{ CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.sys", "ventoy\\imdisk.sys");
Log("This is before Windows 8 ..."); CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.exe", "ventoy\\imdisk.exe");
if (VentoyMountISOByImdisk(IsoPath, PhyDrive) == 0) CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.cpl", "ventoy\\imdisk.cpl");
{ }
Log("Mount iso by imdisk success"); else
return 0; {
} CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.sys", "ventoy\\imdisk.sys");
else CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.exe", "ventoy\\imdisk.exe");
{ CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.cpl", "ventoy\\imdisk.cpl");
return VentoyMountISOByAPI(IsoPath); }
}
} GetCurrentDirectoryA(sizeof(PhyPath), PhyPath);
} strcat_s(PhyPath, sizeof(PhyPath), "\\ventoy\\imdisk.sys");
static int GetPhyDriveByLogicalDrive(int DriveLetter) if (LoadNtDriver(PhyPath) == 0)
{ {
BOOL Ret; rc = 0;
DWORD dwSize;
HANDLE Handle; Letter = GetMountLogicalDrive();
VOLUME_DISK_EXTENTS DiskExtents; sprintf_s(PhyPath, sizeof(PhyPath), "ventoy\\imdisk.exe -a -o ro -f %s -m %C:", IsoPath, Letter);
CHAR PhyPath[128];
Log("mount iso to %C: use imdisk cmd <%s>", Letter, PhyPath);
sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\%C:", (CHAR)DriveLetter);
GetStartupInfoA(&Si);
Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
if (Handle == INVALID_HANDLE_VALUE) Si.dwFlags |= STARTF_USESHOWWINDOW;
{ Si.wShowWindow = SW_HIDE;
Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError());
return -1; CreateProcessA(NULL, PhyPath, NULL, NULL, FALSE, 0, NULL, NULL, &Si, &Pi);
} WaitForSingleObject(Pi.hProcess, INFINITE);
}
Ret = DeviceIoControl(Handle, }
IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, fl_shutdown();
NULL,
0, End:
&DiskExtents,
(DWORD)(sizeof(DiskExtents)), SAFE_CLOSE_HANDLE(hDrive);
(LPDWORD)&dwSize,
NULL); return rc;
}
if (!Ret || DiskExtents.NumberOfDiskExtents == 0)
{ static int MountIsoFile(CONST CHAR *IsoPath, DWORD PhyDrive)
Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath, GetLastError()); {
SAFE_CLOSE_HANDLE(Handle); if (IsWindows8OrGreater())
return -1; {
} Log("This is Windows 8 or latter...");
SAFE_CLOSE_HANDLE(Handle); if (VentoyMountISOByAPI(IsoPath) == 0)
{
Log("LogicalDrive:%s PhyDrive:%d Offset:%llu ExtentLength:%llu", Log("Mount iso by API success");
PhyPath, return 0;
DiskExtents.Extents[0].DiskNumber, }
DiskExtents.Extents[0].StartingOffset.QuadPart, else
DiskExtents.Extents[0].ExtentLength.QuadPart {
); Log("Mount iso by API failed, maybe not supported, try imdisk");
return VentoyMountISOByImdisk(IsoPath, PhyDrive);
return (int)DiskExtents.Extents[0].DiskNumber; }
} }
else
{
static int DeleteVentoyPart2MountPoint(DWORD PhyDrive) Log("This is before Windows 8 ...");
{ if (VentoyMountISOByImdisk(IsoPath, PhyDrive) == 0)
CHAR Letter = 'A'; {
DWORD Drives; Log("Mount iso by imdisk success");
DWORD PhyDisk; return 0;
CHAR DriveName[] = "?:\\"; }
else
Log("DeleteVentoyPart2MountPoint Phy%u ...", PhyDrive); {
return VentoyMountISOByAPI(IsoPath);
Drives = GetLogicalDrives(); }
while (Drives) }
{ }
if ((Drives & 0x01) && IsPathExist(FALSE, "%C:\\ventoy\\ventoy.cpio", Letter))
{ static int GetPhyDriveByLogicalDrive(int DriveLetter)
Log("File %C:\\ventoy\\ventoy.cpio exist", Letter); {
BOOL Ret;
PhyDisk = GetPhyDriveByLogicalDrive(Letter); DWORD dwSize;
Log("PhyDisk=%u for %C", PhyDisk, Letter); HANDLE Handle;
VOLUME_DISK_EXTENTS DiskExtents;
if (PhyDisk == PhyDrive) CHAR PhyPath[128];
{
DriveName[0] = Letter; sprintf_s(PhyPath, sizeof(PhyPath), "\\\\.\\%C:", (CHAR)DriveLetter);
DeleteVolumeMountPointA(DriveName);
return 0; Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
} if (Handle == INVALID_HANDLE_VALUE)
} {
Log("Could not open the disk<%s>, error:%u", PhyPath, GetLastError());
Letter++; return -1;
Drives >>= 1; }
}
Ret = DeviceIoControl(Handle,
return 1; IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
} NULL,
0,
static BOOL check_tar_archive(const char *archive, CHAR *tarName) &DiskExtents,
{ (DWORD)(sizeof(DiskExtents)),
int len; (LPDWORD)&dwSize,
int nameLen; NULL);
const char *pos = archive;
const char *slash = archive; if (!Ret || DiskExtents.NumberOfDiskExtents == 0)
{
while (*pos) Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath, GetLastError());
{ SAFE_CLOSE_HANDLE(Handle);
if (*pos == '\\' || *pos == '/') return -1;
{ }
slash = pos; SAFE_CLOSE_HANDLE(Handle);
}
pos++; Log("LogicalDrive:%s PhyDrive:%d Offset:%llu ExtentLength:%llu",
} PhyPath,
DiskExtents.Extents[0].DiskNumber,
len = (int)strlen(slash); DiskExtents.Extents[0].StartingOffset.QuadPart,
DiskExtents.Extents[0].ExtentLength.QuadPart
if (len > 7 && (strncmp(slash + len - 7, ".tar.gz", 7) == 0 || strncmp(slash + len - 7, ".tar.xz", 7) == 0)) );
{
nameLen = (int)sprintf_s(tarName, MAX_PATH, "X:%s", slash); return (int)DiskExtents.Extents[0].DiskNumber;
tarName[nameLen - 3] = 0; }
return TRUE;
}
else if (len > 8 && strncmp(slash + len - 8, ".tar.bz2", 8) == 0) static int DeleteVentoyPart2MountPoint(DWORD PhyDrive)
{ {
nameLen = (int)sprintf_s(tarName, MAX_PATH, "X:%s", slash); CHAR Letter = 'A';
tarName[nameLen - 4] = 0; DWORD Drives;
return TRUE; DWORD PhyDisk;
} CHAR DriveName[] = "?:\\";
else if (len > 9 && strncmp(slash + len - 9, ".tar.lzma", 9) == 0)
{ Log("DeleteVentoyPart2MountPoint Phy%u ...", PhyDrive);
nameLen = (int)sprintf_s(tarName, MAX_PATH, "X:%s", slash);
tarName[nameLen - 5] = 0; Drives = GetLogicalDrives();
return TRUE; while (Drives)
} {
if ((Drives & 0x01) && IsPathExist(FALSE, "%C:\\ventoy\\ventoy.cpio", Letter))
return FALSE; {
} Log("File %C:\\ventoy\\ventoy.cpio exist", Letter);
static int DecompressInjectionArchive(const char *archive, DWORD PhyDrive) PhyDisk = GetPhyDriveByLogicalDrive(Letter);
{ Log("PhyDisk=%u for %C", PhyDisk, Letter);
int rc = 1;
BOOL bRet; if (PhyDisk == PhyDrive)
DWORD dwBytes; {
HANDLE hDrive; DriveName[0] = Letter;
HANDLE hOut; DeleteVolumeMountPointA(DriveName);
DWORD flags = CREATE_NO_WINDOW; return 0;
CHAR StrBuf[MAX_PATH]; }
CHAR tarName[MAX_PATH]; }
STARTUPINFOA Si;
PROCESS_INFORMATION Pi; Letter++;
PROCESS_INFORMATION NewPi; Drives >>= 1;
GET_LENGTH_INFORMATION LengthInfo; }
SECURITY_ATTRIBUTES Sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
return 1;
Log("DecompressInjectionArchive %s", archive); }
sprintf_s(StrBuf, sizeof(StrBuf), "\\\\.\\PhysicalDrive%d", PhyDrive); static BOOL check_tar_archive(const char *archive, CHAR *tarName)
hDrive = CreateFileA(StrBuf, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0); {
if (hDrive == INVALID_HANDLE_VALUE) int len;
{ int nameLen;
Log("Could not open the disk<%s>, error:%u", StrBuf, GetLastError()); const char *pos = archive;
goto End; const char *slash = archive;
}
while (*pos)
bRet = DeviceIoControl(hDrive, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &LengthInfo, sizeof(LengthInfo), &dwBytes, NULL); {
if (!bRet) if (*pos == '\\' || *pos == '/')
{ {
Log("Could not get phy disk %s size, error:%u", StrBuf, GetLastError()); slash = pos;
goto End; }
} pos++;
}
g_FatPhyDrive = hDrive;
g_Part2StartSec = GetVentoyEfiPartStartSector(hDrive); len = (int)strlen(slash);
Log("Parse FAT fs..."); if (len > 7 && (strncmp(slash + len - 7, ".tar.gz", 7) == 0 || strncmp(slash + len - 7, ".tar.xz", 7) == 0))
{
fl_init(); nameLen = (int)sprintf_s(tarName, MAX_PATH, "X:%s", slash);
tarName[nameLen - 3] = 0;
if (0 == fl_attach_media(VentoyFatDiskRead, NULL)) return TRUE;
{ }
if (g_64bit_system) else if (len > 8 && strncmp(slash + len - 8, ".tar.bz2", 8) == 0)
{ {
CopyFileFromFatDisk("/ventoy/7z/64/7za.exe", "ventoy\\7za.exe"); nameLen = (int)sprintf_s(tarName, MAX_PATH, "X:%s", slash);
} tarName[nameLen - 4] = 0;
else return TRUE;
{ }
CopyFileFromFatDisk("/ventoy/7z/32/7za.exe", "ventoy\\7za.exe"); else if (len > 9 && strncmp(slash + len - 9, ".tar.lzma", 9) == 0)
} {
nameLen = (int)sprintf_s(tarName, MAX_PATH, "X:%s", slash);
sprintf_s(StrBuf, sizeof(StrBuf), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", archive); tarName[nameLen - 5] = 0;
return TRUE;
Log("extract inject to X:"); }
Log("cmdline:<%s>", StrBuf);
return FALSE;
GetStartupInfoA(&Si); }
hOut = CreateFileA("ventoy\\7z.log", static int DecompressInjectionArchive(const char *archive, DWORD PhyDrive)
FILE_APPEND_DATA, {
FILE_SHARE_WRITE | FILE_SHARE_READ, int rc = 1;
&Sa, BOOL bRet;
OPEN_ALWAYS, DWORD dwBytes;
FILE_ATTRIBUTE_NORMAL, HANDLE hDrive;
NULL); HANDLE hOut;
DWORD flags = CREATE_NO_WINDOW;
Si.dwFlags |= STARTF_USESTDHANDLES; CHAR StrBuf[MAX_PATH];
CHAR tarName[MAX_PATH];
if (hOut != INVALID_HANDLE_VALUE) STARTUPINFOA Si;
{ PROCESS_INFORMATION Pi;
Si.hStdError = hOut; PROCESS_INFORMATION NewPi;
Si.hStdOutput = hOut; GET_LENGTH_INFORMATION LengthInfo;
} SECURITY_ATTRIBUTES Sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
CreateProcessA(NULL, StrBuf, NULL, NULL, TRUE, flags, NULL, NULL, &Si, &Pi); Log("DecompressInjectionArchive %s", archive);
WaitForSingleObject(Pi.hProcess, INFINITE);
sprintf_s(StrBuf, sizeof(StrBuf), "\\\\.\\PhysicalDrive%d", PhyDrive);
// hDrive = CreateFileA(StrBuf, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
// decompress tar archive, for tar.gz/tar.xz/tar.bz2 if (hDrive == INVALID_HANDLE_VALUE)
// {
if (check_tar_archive(archive, tarName)) Log("Could not open the disk<%s>, error:%u", StrBuf, GetLastError());
{ goto End;
Log("Decompress tar archive...<%s>", tarName); }
sprintf_s(StrBuf, sizeof(StrBuf), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", tarName); bRet = DeviceIoControl(hDrive, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &LengthInfo, sizeof(LengthInfo), &dwBytes, NULL);
if (!bRet)
CreateProcessA(NULL, StrBuf, NULL, NULL, TRUE, flags, NULL, NULL, &Si, &NewPi); {
WaitForSingleObject(NewPi.hProcess, INFINITE); Log("Could not get phy disk %s size, error:%u", StrBuf, GetLastError());
goto End;
Log("Now delete %s", tarName); }
DeleteFileA(tarName);
} g_FatPhyDrive = hDrive;
g_Part2StartSec = GetVentoyEfiPartStartSector(hDrive);
SAFE_CLOSE_HANDLE(hOut);
} Log("Parse FAT fs...");
fl_shutdown();
fl_init();
End:
if (0 == fl_attach_media(VentoyFatDiskRead, NULL))
SAFE_CLOSE_HANDLE(hDrive); {
if (g_64bit_system)
return rc; {
} CopyFileFromFatDisk("/ventoy/7z/64/7za.exe", "ventoy\\7za.exe");
}
static int ProcessUnattendedInstallation(const char *script) else
{ {
DWORD dw; CopyFileFromFatDisk("/ventoy/7z/32/7za.exe", "ventoy\\7za.exe");
HKEY hKey; }
LSTATUS Ret;
CHAR Letter; sprintf_s(StrBuf, sizeof(StrBuf), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", archive);
CHAR CurDir[MAX_PATH];
Log("extract inject to X:");
Log("Copy unattended XML ..."); Log("cmdline:<%s>", StrBuf);
GetCurrentDirectory(sizeof(CurDir), CurDir); GetStartupInfoA(&Si);
Letter = CurDir[0];
if ((Letter >= 'A' && Letter <= 'Z') || (Letter >= 'a' && Letter <= 'z')) hOut = CreateFileA("ventoy\\7z.log",
{ FILE_APPEND_DATA,
Log("Current Drive Letter: %C", Letter); FILE_SHARE_WRITE | FILE_SHARE_READ,
} &Sa,
else OPEN_ALWAYS,
{ FILE_ATTRIBUTE_NORMAL,
Letter = 'X'; NULL);
}
Si.dwFlags |= STARTF_USESTDHANDLES;
sprintf_s(CurDir, sizeof(CurDir), "%C:\\Autounattend.xml", Letter);
Log("Copy file <%s> --> <%s>", script, CurDir); if (hOut != INVALID_HANDLE_VALUE)
CopyFile(script, CurDir, FALSE); {
Si.hStdError = hOut;
Ret = RegCreateKeyEx(HKEY_LOCAL_MACHINE, "System\\Setup", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dw); Si.hStdOutput = hOut;
if (ERROR_SUCCESS == Ret) }
{
Ret = RegSetValueEx(hKey, "UnattendFile", 0, REG_SZ, CurDir, (DWORD)(strlen(CurDir) + 1)); CreateProcessA(NULL, StrBuf, NULL, NULL, TRUE, flags, NULL, NULL, &Si, &Pi);
} WaitForSingleObject(Pi.hProcess, INFINITE);
return 0; //
} // decompress tar archive, for tar.gz/tar.xz/tar.bz2
//
static int VentoyHook(ventoy_os_param *param) if (check_tar_archive(archive, tarName))
{ {
int rc; Log("Decompress tar archive...<%s>", tarName);
CHAR Letter = 'A';
DISK_EXTENT DiskExtent; sprintf_s(StrBuf, sizeof(StrBuf), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", tarName);
DWORD Drives = GetLogicalDrives();
UINT8 UUID[16]; CreateProcessA(NULL, StrBuf, NULL, NULL, TRUE, flags, NULL, NULL, &Si, &NewPi);
CHAR IsoPath[MAX_PATH]; WaitForSingleObject(NewPi.hProcess, INFINITE);
Log("Logical Drives=0x%x Path:<%s>", Drives, param->vtoy_img_path); Log("Now delete %s", tarName);
DeleteFileA(tarName);
while (Drives) }
{
if (Drives & 0x01) SAFE_CLOSE_HANDLE(hOut);
{ }
sprintf_s(IsoPath, sizeof(IsoPath), "%C:\\%s", Letter, param->vtoy_img_path); fl_shutdown();
if (IsPathExist(FALSE, "%s", IsoPath))
{ End:
Log("File exist under %C:", Letter);
if (GetPhyDiskUUID(Letter, UUID, &DiskExtent) == 0) SAFE_CLOSE_HANDLE(hDrive);
{
if (memcmp(UUID, param->vtoy_disk_guid, 16) == 0) return rc;
{ }
Log("Disk UUID match");
break; static int ProcessUnattendedInstallation(const char *script)
} {
} DWORD dw;
} HKEY hKey;
else LSTATUS Ret;
{ CHAR Letter;
Log("File NOT exist under %C:", Letter); CHAR CurDir[MAX_PATH];
}
} Log("Copy unattended XML ...");
Drives >>= 1; GetCurrentDirectory(sizeof(CurDir), CurDir);
Letter++; Letter = CurDir[0];
} if ((Letter >= 'A' && Letter <= 'Z') || (Letter >= 'a' && Letter <= 'z'))
{
if (Drives == 0) Log("Current Drive Letter: %C", Letter);
{ }
Log("Failed to find ISO file"); else
return 1; {
} Letter = 'X';
}
Log("Find ISO file <%s>", IsoPath);
sprintf_s(CurDir, sizeof(CurDir), "%C:\\Autounattend.xml", Letter);
rc = MountIsoFile(IsoPath, DiskExtent.DiskNumber); Log("Copy file <%s> --> <%s>", script, CurDir);
Log("Mount ISO FILE: %s", rc == 0 ? "SUCCESS" : "FAILED"); CopyFile(script, CurDir, FALSE);
// for protect Ret = RegCreateKeyEx(HKEY_LOCAL_MACHINE, "System\\Setup", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &dw);
rc = DeleteVentoyPart2MountPoint(DiskExtent.DiskNumber); if (ERROR_SUCCESS == Ret)
Log("Delete ventoy mountpoint: %s", rc == 0 ? "SUCCESS" : "NO NEED"); {
Ret = RegSetValueEx(hKey, "UnattendFile", 0, REG_SZ, CurDir, (DWORD)(strlen(CurDir) + 1));
if (g_windows_data.auto_install_script[0]) }
{
sprintf_s(IsoPath, sizeof(IsoPath), "%C:%s", Letter, g_windows_data.auto_install_script); return 0;
if (IsPathExist(FALSE, "%s", IsoPath)) }
{
Log("use auto install script %s...", IsoPath); static int VentoyHook(ventoy_os_param *param)
ProcessUnattendedInstallation(IsoPath); {
} int rc;
else CHAR Letter = 'A';
{ DISK_EXTENT DiskExtent;
Log("auto install script %s not exist", IsoPath); DWORD Drives = GetLogicalDrives();
} UINT8 UUID[16];
} CHAR IsoPath[MAX_PATH];
else
{ Log("Logical Drives=0x%x Path:<%s>", Drives, param->vtoy_img_path);
Log("auto install no need");
} if (IsUTF8Encode(param->vtoy_img_path))
{
if (g_windows_data.injection_archive[0]) Log("This file is UTF8 encoding\n");
{ }
sprintf_s(IsoPath, sizeof(IsoPath), "%C:%s", Letter, g_windows_data.injection_archive);
if (IsPathExist(FALSE, "%s", IsoPath)) while (Drives)
{ {
Log("decompress injection archive %s...", IsoPath); if (Drives & 0x01)
DecompressInjectionArchive(IsoPath, DiskExtent.DiskNumber); {
} sprintf_s(IsoPath, sizeof(IsoPath), "%C:\\%s", Letter, param->vtoy_img_path);
else if (IsPathExist(FALSE, "%s", IsoPath))
{ {
Log("injection archive %s not exist", IsoPath); Log("File exist under %C:", Letter);
} if (GetPhyDiskUUID(Letter, UUID, &DiskExtent) == 0)
} {
else if (memcmp(UUID, param->vtoy_disk_guid, 16) == 0)
{ {
Log("no injection archive found"); Log("Disk UUID match");
} break;
}
return 0; }
} }
else
const char * GetFileNameInPath(const char *fullpath) {
{ Log("File NOT exist under %C:", Letter);
int i; }
const char *pos = NULL; }
if (strstr(fullpath, ":")) Drives >>= 1;
{ Letter++;
for (i = (int)strlen(fullpath); i > 0; i--) }
{
if (fullpath[i - 1] == '/' || fullpath[i - 1] == '\\') if (Drives == 0)
{ {
return fullpath + i; Log("Failed to find ISO file");
} return 1;
} }
}
Log("Find ISO file <%s>", IsoPath);
return fullpath;
} rc = MountIsoFile(IsoPath, DiskExtent.DiskNumber);
Log("Mount ISO FILE: %s", rc == 0 ? "SUCCESS" : "FAILED");
int VentoyJump(INT argc, CHAR **argv, CHAR *LunchFile)
{ // for protect
int rc = 1; rc = DeleteVentoyPart2MountPoint(DiskExtent.DiskNumber);
DWORD Pos; Log("Delete ventoy mountpoint: %s", rc == 0 ? "SUCCESS" : "NO NEED");
DWORD PeStart;
DWORD FileSize; if (g_windows_data.auto_install_script[0])
BYTE *Buffer = NULL; {
CHAR ExeFileName[MAX_PATH]; sprintf_s(IsoPath, sizeof(IsoPath), "%C:%s", Letter, g_windows_data.auto_install_script);
if (IsPathExist(FALSE, "%s", IsoPath))
sprintf_s(ExeFileName, sizeof(ExeFileName), "%s", argv[0]); {
if (!IsPathExist(FALSE, "%s", ExeFileName)) Log("use auto install script %s...", IsoPath);
{ ProcessUnattendedInstallation(IsoPath);
Log("File %s NOT exist, now try %s.exe", ExeFileName, ExeFileName); }
sprintf_s(ExeFileName, sizeof(ExeFileName), "%s.exe", argv[0]); else
{
Log("File %s exist ? %s", ExeFileName, IsPathExist(FALSE, "%s", ExeFileName) ? "YES" : "NO"); Log("auto install script %s not exist", IsoPath);
} }
}
if (ReadWholeFile2Buf(ExeFileName, (void **)&Buffer, &FileSize)) else
{ {
goto End; Log("auto install no need");
} }
g_64bit_system = IsPe64(Buffer); if (g_windows_data.injection_archive[0])
{
if (!IsPathExist(TRUE, "ventoy")) sprintf_s(IsoPath, sizeof(IsoPath), "%C:%s", Letter, g_windows_data.injection_archive);
{ if (IsPathExist(FALSE, "%s", IsoPath))
if (!CreateDirectoryA("ventoy", NULL)) {
{ Log("decompress injection archive %s...", IsoPath);
Log("Failed to create ventoy directory err:%u", GetLastError()); DecompressInjectionArchive(IsoPath, DiskExtent.DiskNumber);
goto End; }
} else
} {
Log("injection archive %s not exist", IsoPath);
for (PeStart = 0; PeStart < FileSize; PeStart += 16) }
{ }
if (CheckOsParam((ventoy_os_param *)(Buffer + PeStart)) && else
CheckPeHead(Buffer + PeStart + sizeof(ventoy_os_param) + sizeof(ventoy_windows_data))) {
{ Log("no injection archive found");
Log("Find os pararm at %u", PeStart); }
memcpy(&g_os_param, Buffer + PeStart, sizeof(ventoy_os_param)); return 0;
memcpy(&g_windows_data, Buffer + PeStart + sizeof(ventoy_os_param), sizeof(ventoy_windows_data)); }
memcpy(g_os_param_reserved, g_os_param.vtoy_reserved, sizeof(g_os_param_reserved));
const char * GetFileNameInPath(const char *fullpath)
if (g_os_param_reserved[0] == 1) {
{ int i;
Log("break here for debug ....."); const char *pos = NULL;
goto End;
} if (strstr(fullpath, ":"))
{
// convert / to \\ for (i = (int)strlen(fullpath); i > 0; i--)
for (Pos = 0; Pos < sizeof(g_os_param.vtoy_img_path) && g_os_param.vtoy_img_path[Pos]; Pos++) {
{ if (fullpath[i - 1] == '/' || fullpath[i - 1] == '\\')
if (g_os_param.vtoy_img_path[Pos] == '/') {
{ return fullpath + i;
g_os_param.vtoy_img_path[Pos] = '\\'; }
} }
} }
PeStart += sizeof(ventoy_os_param) + sizeof(ventoy_windows_data); return fullpath;
sprintf_s(LunchFile, MAX_PATH, "ventoy\\%s", GetFileNameInPath(ExeFileName)); }
SaveBuffer2File(LunchFile, Buffer + PeStart, FileSize - PeStart);
break; int VentoyJump(INT argc, CHAR **argv, CHAR *LunchFile)
} {
} int rc = 1;
DWORD Pos;
if (PeStart >= FileSize) DWORD PeStart;
{ DWORD FileSize;
Log("OS param not found"); BYTE *Buffer = NULL;
goto End; CHAR ExeFileName[MAX_PATH];
}
sprintf_s(ExeFileName, sizeof(ExeFileName), "%s", argv[0]);
if (g_os_param_reserved[0] == 2) if (!IsPathExist(FALSE, "%s", ExeFileName))
{ {
Log("skip hook for debug ....."); Log("File %s NOT exist, now try %s.exe", ExeFileName, ExeFileName);
rc = 0; sprintf_s(ExeFileName, sizeof(ExeFileName), "%s.exe", argv[0]);
goto End;
} Log("File %s exist ? %s", ExeFileName, IsPathExist(FALSE, "%s", ExeFileName) ? "YES" : "NO");
}
rc = VentoyHook(&g_os_param);
if (ReadWholeFile2Buf(ExeFileName, (void **)&Buffer, &FileSize))
End: {
goto End;
if (Buffer) }
{
free(Buffer); g_64bit_system = IsPe64(Buffer);
}
if (!IsPathExist(TRUE, "ventoy"))
return rc; {
} if (!CreateDirectoryA("ventoy", NULL))
{
int main(int argc, char **argv) Log("Failed to create ventoy directory err:%u", GetLastError());
{ goto End;
int i = 0; }
int rc = 0; }
CHAR *Pos = NULL;
CHAR CurDir[MAX_PATH]; for (PeStart = 0; PeStart < FileSize; PeStart += 16)
CHAR LunchFile[MAX_PATH]; {
STARTUPINFOA Si; if (CheckOsParam((ventoy_os_param *)(Buffer + PeStart)) &&
PROCESS_INFORMATION Pi; CheckPeHead(Buffer + PeStart + sizeof(ventoy_os_param) + sizeof(ventoy_windows_data)))
{
if (argv[0] && argv[0][0] && argv[0][1] == ':') Log("Find os pararm at %u", PeStart);
{
GetCurrentDirectoryA(sizeof(CurDir), CurDir); memcpy(&g_os_param, Buffer + PeStart, sizeof(ventoy_os_param));
memcpy(&g_windows_data, Buffer + PeStart + sizeof(ventoy_os_param), sizeof(ventoy_windows_data));
strcpy_s(LunchFile, sizeof(LunchFile), argv[0]); memcpy(g_os_param_reserved, g_os_param.vtoy_reserved, sizeof(g_os_param_reserved));
Pos = (char *)GetFileNameInPath(LunchFile);
if (g_os_param_reserved[0] == 1)
strcat_s(CurDir, sizeof(CurDir), "\\"); {
strcat_s(CurDir, sizeof(CurDir), Pos); Log("break here for debug .....");
goto End;
if (_stricmp(argv[0], CurDir) != 0) }
{
*Pos = 0; // convert / to \\
SetCurrentDirectoryA(LunchFile); for (Pos = 0; Pos < sizeof(g_os_param.vtoy_img_path) && g_os_param.vtoy_img_path[Pos]; Pos++)
} {
} if (g_os_param.vtoy_img_path[Pos] == '/')
{
Log("######## VentoyJump ##########"); g_os_param.vtoy_img_path[Pos] = '\\';
Log("argc = %d argv[0] = <%s>", argc, argv[0]); }
}
if (Pos && *Pos == 0)
{ PeStart += sizeof(ventoy_os_param) + sizeof(ventoy_windows_data);
Log("Old current directory = <%s>", CurDir); sprintf_s(LunchFile, MAX_PATH, "ventoy\\%s", GetFileNameInPath(ExeFileName));
Log("New current directory = <%s>", LunchFile); SaveBuffer2File(LunchFile, Buffer + PeStart, FileSize - PeStart);
} break;
else }
{ }
GetCurrentDirectoryA(sizeof(CurDir), CurDir);
Log("Current directory = <%s>", CurDir); if (PeStart >= FileSize)
} {
Log("OS param not found");
GetStartupInfoA(&Si); goto End;
}
memset(LunchFile, 0, sizeof(LunchFile));
rc = VentoyJump(argc, argv, LunchFile); if (g_os_param_reserved[0] == 2)
{
if (g_os_param_reserved[0] == 3) Log("skip hook for debug .....");
{ rc = 0;
Log("Open log for debug ..."); goto End;
sprintf_s(LunchFile, sizeof(LunchFile), "%s", "notepad.exe ventoy.log"); }
}
else rc = VentoyHook(&g_os_param);
{
Si.dwFlags |= STARTF_USESHOWWINDOW; End:
Si.wShowWindow = SW_HIDE;
Log("Ventoy jump %s ...", rc == 0 ? "success" : "failed"); if (Buffer)
} {
free(Buffer);
CreateProcessA(NULL, LunchFile, NULL, NULL, FALSE, 0, NULL, NULL, &Si, &Pi); }
while (rc) return rc;
{ }
Log("Ventoy hook failed, now wait and retry ...");
Sleep(1000); int main(int argc, char **argv)
{
rc = VentoyHook(&g_os_param); int i = 0;
} int rc = 0;
CHAR *Pos = NULL;
WaitForSingleObject(Pi.hProcess, INFINITE); CHAR CurDir[MAX_PATH];
CHAR LunchFile[MAX_PATH];
return 0; STARTUPINFOA Si;
} PROCESS_INFORMATION Pi;
if (argv[0] && argv[0][0] && argv[0][1] == ':')
{
GetCurrentDirectoryA(sizeof(CurDir), CurDir);
strcpy_s(LunchFile, sizeof(LunchFile), argv[0]);
Pos = (char *)GetFileNameInPath(LunchFile);
strcat_s(CurDir, sizeof(CurDir), "\\");
strcat_s(CurDir, sizeof(CurDir), Pos);
if (_stricmp(argv[0], CurDir) != 0)
{
*Pos = 0;
SetCurrentDirectoryA(LunchFile);
}
}
Log("######## VentoyJump ##########");
Log("argc = %d argv[0] = <%s>", argc, argv[0]);
if (Pos && *Pos == 0)
{
Log("Old current directory = <%s>", CurDir);
Log("New current directory = <%s>", LunchFile);
}
else
{
GetCurrentDirectoryA(sizeof(CurDir), CurDir);
Log("Current directory = <%s>", CurDir);
}
GetStartupInfoA(&Si);
memset(LunchFile, 0, sizeof(LunchFile));
rc = VentoyJump(argc, argv, LunchFile);
if (g_os_param_reserved[0] == 3)
{
Log("Open log for debug ...");
sprintf_s(LunchFile, sizeof(LunchFile), "%s", "notepad.exe ventoy.log");
}
else
{
Si.dwFlags |= STARTF_USESHOWWINDOW;
Si.wShowWindow = SW_HIDE;
Log("Ventoy jump %s ...", rc == 0 ? "success" : "failed");
}
CreateProcessA(NULL, LunchFile, NULL, NULL, FALSE, 0, NULL, NULL, &Si, &Pi);
while (rc)
{
Log("Ventoy hook failed, now wait and retry ...");
Sleep(1000);
rc = VentoyHook(&g_os_param);
}
WaitForSingleObject(Pi.hProcess, INFINITE);
return 0;
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment