1 /******************************************************************************
4 * Copyright (c) 2021, longpanda <admin@ventoy.net>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as
8 * published by the Free Software Foundation; either version 3 of the
9 * License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
27 #include <VersionHelpers.h>
29 #include "fat_filelib.h"
31 static ventoy_os_param g_os_param
;
32 static ventoy_windows_data g_windows_data
;
33 static UINT8 g_os_param_reserved
[32];
34 static INT g_system_bit
= VTOY_BIT
;
35 static ventoy_guid g_ventoy_guid
= VENTOY_GUID
;
36 static HANDLE g_vtoylog_mutex
= NULL
;
37 static HANDLE g_vtoyins_mutex
= NULL
;
39 static BOOL g_wimboot_mode
= FALSE
;
41 static DWORD g_vtoy_disk_drive
;
43 static CHAR g_prog_full_path
[MAX_PATH
];
44 static CHAR g_prog_dir
[MAX_PATH
];
45 static CHAR g_prog_name
[MAX_PATH
];
47 #define VTOY_PECMD_PATH "X:\\Windows\\system32\\ventoy\\PECMD.EXE"
48 #define ORG_PECMD_PATH "X:\\Windows\\system32\\PECMD.EXE"
49 #define ORG_PECMD_BK_PATH "X:\\Windows\\system32\\VTOYJUMP.EXE"
51 #define WIMBOOT_FILE "X:\\Windows\\system32\\vtoy_wimboot"
52 #define WIMBOOT_DONE "X:\\Windows\\system32\\vtoy_wimboot_done"
54 #define AUTO_RUN_BAT "X:\\VentoyAutoRun.bat"
55 #define AUTO_RUN_LOG "X:\\VentoyAutoRun.log"
57 #define VTOY_AUTO_FILE "X:\\_vtoy_auto_install"
59 #define LOG_FILE "X:\\Windows\\system32\\ventoy.log"
60 #define MUTEX_LOCK(hmutex) if (hmutex != NULL) LockStatus = WaitForSingleObject(hmutex, INFINITE)
61 #define MUTEX_UNLOCK(hmutex) if (hmutex != NULL && WAIT_OBJECT_0 == LockStatus) ReleaseMutex(hmutex)
63 #define BREAK() BreakAndLaunchCmd(__LINE__)
65 static void BreakAndLaunchCmd(int line
)
68 PROCESS_INFORMATION Pi
;
70 Log("Break at line:%d", line
);
73 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
74 Si
.wShowWindow
= SW_NORMAL
;
76 CreateProcessA(NULL
, "cmd.exe", NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
77 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
80 static const char * GetFileNameInPath(const char *fullpath
)
84 if (strstr(fullpath
, ":"))
86 for (i
= (int)strlen(fullpath
); i
> 0; i
--)
88 if (fullpath
[i
- 1] == '/' || fullpath
[i
- 1] == '\\')
98 static int split_path_name(char *fullpath
, char *dir
, char *name
)
103 Pos
= (CHAR
*)GetFileNameInPath(fullpath
);
105 strcpy_s(name
, MAX_PATH
, Pos
);
109 strcpy_s(dir
, MAX_PATH
, fullpath
);
115 static void TrimString(CHAR
*String
, BOOL TrimLeft
)
119 size_t Len
= strlen(String
);
123 if (String
[Len
- 1] != ' ' && String
[Len
- 1] != '\t')
133 while (*Pos1
== ' ' || *Pos1
== '\t')
148 static int VentoyProcessRunCmd(const char *Fmt
, ...)
153 PROCESS_INFORMATION Pi
;
154 char szBuf
[1024] = { 0 };
157 Len
+= vsnprintf_s(szBuf
+ Len
, sizeof(szBuf
)-Len
, sizeof(szBuf
)-Len
, Fmt
, Arg
);
160 GetStartupInfoA(&Si
);
161 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
162 Si
.wShowWindow
= SW_HIDE
;
164 Log("Process Run: <%s>", szBuf
);
165 CreateProcessA(NULL
, szBuf
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
166 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
171 static CHAR
VentoyGetFirstFreeDriveLetter(BOOL Reverse
)
177 Drives
= GetLogicalDrives();
181 for (i
= 25; i
>= 2; i
--)
183 if (0 == (Drives
& (1 << i
)))
192 for (i
= 2; i
< 26; i
++)
194 if (0 == (Drives
& (1 << i
)))
202 Log("FirstFreeDriveLetter %u %C:", Reverse
, Letter
);
206 void Log(const char *Fmt
, ...)
213 DWORD LockStatus
= 0;
214 DWORD PID
= GetCurrentProcessId();
217 Len
+= sprintf_s(szBuf
, sizeof(szBuf
),
218 "[%4d/%02d/%02d %02d:%02d:%02d.%03d] [%u] ",
219 Sys
.wYear
, Sys
.wMonth
, Sys
.wDay
,
220 Sys
.wHour
, Sys
.wMinute
, Sys
.wSecond
,
221 Sys
.wMilliseconds
, PID
);
224 Len
+= vsnprintf_s(szBuf
+ Len
, sizeof(szBuf
)-Len
, sizeof(szBuf
)-Len
, Fmt
, Arg
);
227 MUTEX_LOCK(g_vtoylog_mutex
);
229 fopen_s(&File
, LOG_FILE
, "a+");
232 fwrite(szBuf
, 1, Len
, File
);
233 fwrite("\n", 1, 1, File
);
237 MUTEX_UNLOCK(g_vtoylog_mutex
);
241 static int LoadNtDriver(const char *DrvBinPath
)
247 SC_HANDLE hServiceMgr
;
249 char name
[256] = { 0 };
251 for (i
= (int)strlen(DrvBinPath
) - 1; i
>= 0; i
--)
253 if (DrvBinPath
[i
] == '\\' || DrvBinPath
[i
] == '/')
255 sprintf_s(name
, sizeof(name
), "%s", DrvBinPath
+ i
+ 1);
260 Log("Load NT driver: %s %s", DrvBinPath
, name
);
262 hServiceMgr
= OpenSCManagerA(NULL
, NULL
, SC_MANAGER_ALL_ACCESS
);
263 if (hServiceMgr
== NULL
)
265 Log("OpenSCManager failed Error:%u", GetLastError());
269 Log("OpenSCManager OK");
271 hService
= CreateServiceA(hServiceMgr
,
275 SERVICE_KERNEL_DRIVER
,
276 SERVICE_DEMAND_START
,
277 SERVICE_ERROR_NORMAL
,
279 NULL
, NULL
, NULL
, NULL
, NULL
);
280 if (hService
== NULL
)
282 Status
= GetLastError();
283 if (Status
!= ERROR_IO_PENDING
&& Status
!= ERROR_SERVICE_EXISTS
)
285 Log("CreateService failed v %u", Status
);
286 CloseServiceHandle(hServiceMgr
);
290 hService
= OpenServiceA(hServiceMgr
, name
, SERVICE_ALL_ACCESS
);
291 if (hService
== NULL
)
293 Log("OpenService failed %u", Status
);
294 CloseServiceHandle(hServiceMgr
);
299 Log("CreateService imdisk OK");
301 Ret
= StartServiceA(hService
, 0, NULL
);
304 Log("StartService OK");
308 Status
= GetLastError();
309 if (Status
== ERROR_SERVICE_ALREADY_RUNNING
)
315 Log("StartService error %u", Status
);
320 CloseServiceHandle(hService
);
321 CloseServiceHandle(hServiceMgr
);
323 Log("Load NT driver %s", rc
? "failed" : "success");
328 static int ReadWholeFile2Buf(const char *Fullpath
, void **Data
, DWORD
*Size
)
336 Log("ReadWholeFile2Buf <%s>", Fullpath
);
338 Handle
= CreateFileA(Fullpath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
339 if (Handle
== INVALID_HANDLE_VALUE
)
341 Log("Could not open the file<%s>, error:%u", Fullpath
, GetLastError());
345 FileSize
= SetFilePointer(Handle
, 0, NULL
, FILE_END
);
347 Buffer
= malloc(FileSize
);
350 Log("Failed to alloc memory size:%u", FileSize
);
354 SetFilePointer(Handle
, 0, NULL
, FILE_BEGIN
);
355 if (!ReadFile(Handle
, Buffer
, FileSize
, &dwSize
, NULL
))
357 Log("ReadFile failed, dwSize:%u error:%u", dwSize
, GetLastError());
364 Log("Success read file size:%u", FileSize
);
369 SAFE_CLOSE_HANDLE(Handle
);
374 static BOOL
CheckPeHead(BYTE
*Buffer
, DWORD Size
, DWORD Offset
)
379 ventoy_windows_data
*pdata
= NULL
;
381 Head
= Buffer
+ Offset
;
382 pdata
= (ventoy_windows_data
*)Head
;
383 Head
+= sizeof(ventoy_windows_data
);
385 if (pdata
->auto_install_script
[0] && pdata
->auto_install_len
> 0)
387 End
= Offset
+ sizeof(ventoy_windows_data
) + pdata
->auto_install_len
+ 60;
390 Head
+= pdata
->auto_install_len
;
394 if (Head
[0] != 'M' || Head
[1] != 'Z')
399 PeOffset
= *(UINT32
*)(Head
+ 60);
400 if (*(UINT32
*)(Head
+ PeOffset
) != 0x00004550)
409 static BOOL
CheckOsParam(ventoy_os_param
*param
)
414 if (memcmp(¶m
->guid
, &g_ventoy_guid
, sizeof(ventoy_guid
)))
419 for (i
= 0; i
< sizeof(ventoy_os_param
); i
++)
421 Sum
+= *((BYTE
*)param
+ i
);
429 if (param
->vtoy_img_location_addr
% 4096)
437 static int SaveBuffer2File(const char *Fullpath
, void *Buffer
, DWORD Length
)
443 Log("SaveBuffer2File <%s> len:%u", Fullpath
, Length
);
445 Handle
= CreateFileA(Fullpath
, GENERIC_READ
| GENERIC_WRITE
,
446 FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, CREATE_NEW
, 0, 0);
447 if (Handle
== INVALID_HANDLE_VALUE
)
449 Log("Could not create new file, error:%u", GetLastError());
453 WriteFile(Handle
, Buffer
, Length
, &dwSize
, NULL
);
458 SAFE_CLOSE_HANDLE(Handle
);
463 static int IsUTF8Encode(const char *src
)
466 const UCHAR
*Byte
= (const UCHAR
*)src
;
468 for (i
= 0; i
< MAX_PATH
&& Byte
[i
]; i
++)
479 static int Utf16ToUtf8(const WCHAR
*src
, char *dst
)
484 len
= (int)wcslen(src
) + 1;
485 size
= WideCharToMultiByte(CP_UTF8
, 0, src
, len
, NULL
, 0, NULL
, NULL
);
486 return WideCharToMultiByte(CP_UTF8
, 0, src
, len
, dst
, size
, NULL
, NULL
);
489 static int Utf8ToUtf16(const char* src
, WCHAR
* dst
)
491 int size
= MultiByteToWideChar(CP_UTF8
, 0, src
, -1, dst
, 0);
492 return MultiByteToWideChar(CP_UTF8
, 0, src
, -1, dst
, size
+ 1);
495 static BOOL
IsDirExist(const char *Fmt
, ...)
500 CHAR FilePathA
[MAX_PATH
];
501 WCHAR FilePathW
[MAX_PATH
];
504 vsnprintf_s(FilePathA
, sizeof(FilePathA
), sizeof(FilePathA
), Fmt
, Arg
);
507 UTF8
= IsUTF8Encode(FilePathA
);
511 Utf8ToUtf16(FilePathA
, FilePathW
);
512 Attr
= GetFileAttributesW(FilePathW
);
516 Attr
= GetFileAttributesA(FilePathA
);
519 if (Attr
!= INVALID_FILE_ATTRIBUTES
&& (Attr
& FILE_ATTRIBUTE_DIRECTORY
))
527 static BOOL
IsFileExist(const char *Fmt
, ...)
534 CHAR FilePathA
[MAX_PATH
];
535 WCHAR FilePathW
[MAX_PATH
];
538 vsnprintf_s(FilePathA
, sizeof(FilePathA
), sizeof(FilePathA
), Fmt
, Arg
);
541 UTF8
= IsUTF8Encode(FilePathA
);
545 Utf8ToUtf16(FilePathA
, FilePathW
);
546 hFile
= CreateFileW(FilePathW
, FILE_READ_EA
, FILE_SHARE_READ
, 0, OPEN_EXISTING
, 0, 0);
550 hFile
= CreateFileA(FilePathA
, FILE_READ_EA
, FILE_SHARE_READ
, 0, OPEN_EXISTING
, 0, 0);
552 if (INVALID_HANDLE_VALUE
== hFile
)
561 Attr
= GetFileAttributesW(FilePathW
);
565 Attr
= GetFileAttributesA(FilePathA
);
568 if (Attr
& FILE_ATTRIBUTE_DIRECTORY
)
576 Log("File <%s> %s", FilePathA
, (bRet
? "exist" : "NOT exist"));
580 static int GetPhyDiskUUID(const char LogicalDrive
, UINT8
*UUID
, UINT32
*DiskSig
, DISK_EXTENT
*DiskExtent
)
585 VOLUME_DISK_EXTENTS DiskExtents
;
587 UINT8 SectorBuf
[512];
589 Log("GetPhyDiskUUID %C", LogicalDrive
);
591 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\%C:", LogicalDrive
);
592 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
593 if (Handle
== INVALID_HANDLE_VALUE
)
595 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
599 Ret
= DeviceIoControl(Handle
,
600 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
604 (DWORD
)(sizeof(DiskExtents
)),
607 if (!Ret
|| DiskExtents
.NumberOfDiskExtents
== 0)
609 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed, error:%u", GetLastError());
615 memcpy(DiskExtent
, DiskExtents
.Extents
, sizeof(DISK_EXTENT
));
616 Log("%C: is in PhysicalDrive%d Offset:%llu", LogicalDrive
, DiskExtents
.Extents
[0].DiskNumber
,
617 (ULONGLONG
)(DiskExtents
.Extents
[0].StartingOffset
.QuadPart
));
619 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\PhysicalDrive%d", DiskExtents
.Extents
[0].DiskNumber
);
620 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
621 if (Handle
== INVALID_HANDLE_VALUE
)
623 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
627 if (!ReadFile(Handle
, SectorBuf
, sizeof(SectorBuf
), &dwSize
, NULL
))
629 Log("ReadFile failed, dwSize:%u error:%u", dwSize
, GetLastError());
634 memcpy(UUID
, SectorBuf
+ 0x180, 16);
637 memcpy(DiskSig
, SectorBuf
+ 0x1B8, 4);
644 static int VentoyMountAnywhere(HANDLE Handle
)
647 ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters
;
649 Log("VentoyMountAnywhere");
651 memset(&AttachParameters
, 0, sizeof(AttachParameters
));
652 AttachParameters
.Version
= ATTACH_VIRTUAL_DISK_VERSION_1
;
654 Status
= AttachVirtualDisk(Handle
, NULL
, ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY
| ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME
, 0, &AttachParameters
, NULL
);
655 if (Status
!= ERROR_SUCCESS
)
657 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
664 int VentoyMountY(HANDLE Handle
)
669 DWORD physicalDriveNameSize
;
671 WCHAR physicalDriveName
[MAX_PATH
];
672 CHAR physicalDriveNameA
[MAX_PATH
];
673 CHAR cdromDriveName
[MAX_PATH
];
674 ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters
;
678 memset(&AttachParameters
, 0, sizeof(AttachParameters
));
679 AttachParameters
.Version
= ATTACH_VIRTUAL_DISK_VERSION_1
;
681 Status
= AttachVirtualDisk(Handle
, NULL
, ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY
| ATTACH_VIRTUAL_DISK_FLAG_NO_DRIVE_LETTER
| ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME
, 0, &AttachParameters
, NULL
);
682 if (Status
!= ERROR_SUCCESS
)
684 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
688 memset(physicalDriveName
, 0, sizeof(physicalDriveName
));
689 memset(physicalDriveNameA
, 0, sizeof(physicalDriveNameA
));
691 physicalDriveNameSize
= MAX_PATH
;
692 Status
= GetVirtualDiskPhysicalPath(Handle
, &physicalDriveNameSize
, physicalDriveName
);
693 if (Status
!= ERROR_SUCCESS
)
695 Log("Failed GetVirtualDiskPhysicalPath ErrorCode:%u", Status
);
699 for (i
= 0; physicalDriveName
[i
]; i
++)
701 physicalDriveNameA
[i
] = (CHAR
)toupper((CHAR
)(physicalDriveName
[i
]));
704 Log("physicalDriveNameA=<%s>", physicalDriveNameA
);
706 Pos
= strstr(physicalDriveNameA
, "CDROM");
709 Log("Not cdrom phy drive");
713 sprintf_s(cdromDriveName
, sizeof(cdromDriveName
), "\\Device\\%s", Pos
);
714 Log("cdromDriveName=<%s>", cdromDriveName
);
716 for (i
= 0; i
< 3 && (bRet
== FALSE
); i
++)
719 bRet
= DefineDosDeviceA(DDD_RAW_TARGET_PATH
, "Y:", cdromDriveName
);
720 Log("DefineDosDeviceA %s", bRet
? "success" : "failed");
726 static BOOL
VentoyAPINeedMountY(const char *IsoPath
)
734 static int VentoyAttachVirtualDisk(HANDLE Handle
, const char *IsoPath
)
739 Drives
= GetLogicalDrives();
740 if ((1 << 24) & Drives
)
742 Log("Y: is occupied");
747 Log("Y: is free now");
751 if (DriveYFree
&& VentoyAPINeedMountY(IsoPath
))
753 return VentoyMountY(Handle
);
757 return VentoyMountAnywhere(Handle
);
761 int VentoyMountISOByAPI(const char *IsoPath
)
766 WCHAR wFilePath
[512] = { 0 };
767 VIRTUAL_STORAGE_TYPE StorageType
;
768 OPEN_VIRTUAL_DISK_PARAMETERS OpenParameters
;
770 Log("VentoyMountISOByAPI <%s>", IsoPath
);
772 if (IsUTF8Encode(IsoPath
))
774 Log("This is UTF8 encoding");
775 MultiByteToWideChar(CP_UTF8
, 0, IsoPath
, (int)strlen(IsoPath
), wFilePath
, (int)(sizeof(wFilePath
) / sizeof(WCHAR
)));
779 Log("This is ANSI encoding");
780 MultiByteToWideChar(CP_ACP
, 0, IsoPath
, (int)strlen(IsoPath
), wFilePath
, (int)(sizeof(wFilePath
) / sizeof(WCHAR
)));
783 memset(&StorageType
, 0, sizeof(StorageType
));
784 memset(&OpenParameters
, 0, sizeof(OpenParameters
));
786 OpenParameters
.Version
= OPEN_VIRTUAL_DISK_VERSION_1
;
788 for (i
= 0; i
< 10; i
++)
790 Status
= OpenVirtualDisk(&StorageType
, wFilePath
, VIRTUAL_DISK_ACCESS_READ
, 0, &OpenParameters
, &Handle
);
791 if (ERROR_FILE_NOT_FOUND
== Status
|| ERROR_PATH_NOT_FOUND
== Status
)
793 Log("OpenVirtualDisk ErrorCode:%u, now wait and retry...", Status
);
798 if (ERROR_SUCCESS
== Status
)
800 Log("OpenVirtualDisk success");
802 else if (ERROR_VIRTDISK_PROVIDER_NOT_FOUND
== Status
)
804 Log("VirtualDisk for ISO file is not supported in current system");
808 Log("Failed to open virtual disk ErrorCode:%u", Status
);
814 if (Status
!= ERROR_SUCCESS
)
819 Log("OpenVirtualDisk success");
821 Status
= VentoyAttachVirtualDisk(Handle
, IsoPath
);
822 if (Status
!= ERROR_SUCCESS
)
824 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
829 Log("VentoyAttachVirtualDisk success");
836 static HANDLE g_FatPhyDrive
;
837 static UINT64 g_Part2StartSec
;
839 static int CopyFileFromFatDisk(const CHAR
* SrcFile
, const CHAR
*DstFile
)
846 Log("CopyFileFromFatDisk (%s)==>(%s)", SrcFile
, DstFile
);
848 flfile
= fl_fopen(SrcFile
, "rb");
851 fl_fseek(flfile
, 0, SEEK_END
);
852 size
= (int)fl_ftell(flfile
);
853 fl_fseek(flfile
, 0, SEEK_SET
);
855 buf
= (char *)malloc(size
);
858 fl_fread(buf
, 1, size
, flfile
);
861 SaveBuffer2File(DstFile
, buf
, size
);
871 static int VentoyFatDiskRead(uint32 Sector
, uint8
*Buffer
, uint32 SectorCount
)
876 LARGE_INTEGER liCurrentPosition
;
878 liCurrentPosition
.QuadPart
= Sector
+ g_Part2StartSec
;
879 liCurrentPosition
.QuadPart
*= 512;
880 SetFilePointerEx(g_FatPhyDrive
, liCurrentPosition
, &liCurrentPosition
, FILE_BEGIN
);
882 ReadSize
= (DWORD
)(SectorCount
* 512);
884 bRet
= ReadFile(g_FatPhyDrive
, Buffer
, ReadSize
, &dwSize
, NULL
);
885 if (bRet
== FALSE
|| dwSize
!= ReadSize
)
887 Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u", bRet
, ReadSize
, dwSize
, GetLastError());
893 static BOOL
Is2K10PE(void)
899 fopen_s(&fp
, "X:\\Windows\\System32\\PECMD.INI", "r");
905 memset(szLine
, 0, sizeof(szLine
));
906 while (fgets(szLine
, sizeof(szLine
) - 1, fp
))
908 if (strstr(szLine
, "2k10\\"))
919 static CHAR
GetIMDiskMountLogicalDrive(void)
923 DWORD Mask
= 0x1000000;
925 // fixed use M as mountpoint for 2K10 PE
928 Log("Use M: for 2K10 PE");
932 Drives
= GetLogicalDrives();
933 Log("Drives=0x%x", Drives
);
937 if ((Drives
& Mask
) == 0)
949 UINT64
GetVentoyEfiPartStartSector(HANDLE hDrive
)
954 VTOY_GPT_INFO
*pGpt
= NULL
;
955 UINT64 StartSector
= 0;
957 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
959 bRet
= ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
960 Log("Read MBR Ret:%u Size:%u code:%u", bRet
, dwSize
, LASTERR
);
962 if ((!bRet
) || (dwSize
!= sizeof(MBR
)))
967 if (MBR
.PartTbl
[0].FsFlag
== 0xEE)
969 Log("GPT partition style");
971 pGpt
= malloc(sizeof(VTOY_GPT_INFO
));
977 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
978 bRet
= ReadFile(hDrive
, pGpt
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
);
979 if ((!bRet
) || (dwSize
!= sizeof(VTOY_GPT_INFO
)))
981 Log("Failed to read gpt info %d %u %d", bRet
, dwSize
, LASTERR
);
985 StartSector
= pGpt
->PartTbl
[1].StartLBA
;
990 Log("MBR partition style");
991 StartSector
= MBR
.PartTbl
[1].StartSectorId
;
994 Log("GetVentoyEfiPart StartSector: %llu", StartSector
);
998 static int VentoyCopyImdisk(DWORD PhyDrive
, CHAR
*ImPath
)
1004 CHAR PhyPath
[MAX_PATH
];
1005 GET_LENGTH_INFORMATION LengthInfo
;
1007 if (IsFileExist("X:\\Windows\\System32\\imdisk.exe"))
1009 Log("imdisk.exe already exist, no need to copy...");
1010 strcpy_s(ImPath
, MAX_PATH
, "imdisk.exe");
1014 if (IsFileExist("X:\\Windows\\System32\\ventoy\\imdisk.exe"))
1016 Log("imdisk.exe already copied, no need to copy...");
1017 strcpy_s(ImPath
, MAX_PATH
, "ventoy\\imdisk.exe");
1021 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\PhysicalDrive%d", PhyDrive
);
1022 hDrive
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
1023 if (hDrive
== INVALID_HANDLE_VALUE
)
1025 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
1029 bRet
= DeviceIoControl(hDrive
, IOCTL_DISK_GET_LENGTH_INFO
, NULL
, 0, &LengthInfo
, sizeof(LengthInfo
), &dwBytes
, NULL
);
1032 Log("Could not get phy disk %s size, error:%u", PhyPath
, GetLastError());
1036 g_FatPhyDrive
= hDrive
;
1037 g_Part2StartSec
= GetVentoyEfiPartStartSector(hDrive
);
1039 Log("Parse FAT fs...");
1043 if (0 == fl_attach_media(VentoyFatDiskRead
, NULL
))
1045 if (g_system_bit
== 64)
1047 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.sys", "ventoy\\imdisk.sys");
1048 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.exe", "ventoy\\imdisk.exe");
1049 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.cpl", "ventoy\\imdisk.cpl");
1053 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.sys", "ventoy\\imdisk.sys");
1054 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.exe", "ventoy\\imdisk.exe");
1055 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.cpl", "ventoy\\imdisk.cpl");
1058 GetCurrentDirectoryA(sizeof(PhyPath
), PhyPath
);
1059 strcat_s(PhyPath
, sizeof(PhyPath
), "\\ventoy\\imdisk.sys");
1061 if (LoadNtDriver(PhyPath
) == 0)
1063 strcpy_s(ImPath
, MAX_PATH
, "ventoy\\imdisk.exe");
1071 SAFE_CLOSE_HANDLE(hDrive
);
1076 static int VentoyRunImdisk(const char *IsoPath
, const char *imdiskexe
, const char *opt
)
1080 WCHAR CmdlineW
[512];
1081 PROCESS_INFORMATION Pi
;
1083 Log("VentoyRunImdisk <%s> <%s> <%s>", IsoPath
, imdiskexe
, opt
);
1085 Letter
= GetIMDiskMountLogicalDrive();
1089 sprintf_s(Cmdline
, sizeof(Cmdline
), "%s -a -o %s -f \"%s\" -m %C:", imdiskexe
, opt
, IsoPath
, Letter
);
1093 sprintf_s(Cmdline
, sizeof(Cmdline
), "%s -a -f \"%s\" -m %C:", imdiskexe
, IsoPath
, Letter
);
1096 Log("mount iso to %C: use imdisk cmd <%s>", Letter
, Cmdline
);
1098 if (IsUTF8Encode(IsoPath
))
1101 GetStartupInfoW(&Si
);
1102 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
1103 Si
.wShowWindow
= SW_HIDE
;
1105 Utf8ToUtf16(Cmdline
, CmdlineW
);
1106 CreateProcessW(NULL
, CmdlineW
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
1108 Log("This is UTF8 encoding");
1113 GetStartupInfoA(&Si
);
1114 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
1115 Si
.wShowWindow
= SW_HIDE
;
1117 CreateProcessA(NULL
, Cmdline
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
1119 Log("This is ANSI encoding");
1122 Log("Wait for imdisk process ...");
1123 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
1124 Log("imdisk process finished");
1129 int VentoyMountISOByImdisk(const char *IsoPath
, DWORD PhyDrive
)
1132 CHAR ImPath
[MAX_PATH
];
1134 Log("VentoyMountISOByImdisk %s", IsoPath
);
1136 if (0 == VentoyCopyImdisk(PhyDrive
, ImPath
))
1138 VentoyRunImdisk(IsoPath
, ImPath
, "ro");
1145 static int GetIsoId(CONST CHAR
*IsoPath
, IsoId
*ids
)
1153 hFile
= CreateFileA(IsoPath
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, NULL
);
1154 if (hFile
== INVALID_HANDLE_VALUE
)
1159 SetFilePointer(hFile
, 2048 * 16 + 8, NULL
, FILE_BEGIN
);
1160 bRet
[n
++] = ReadFile(hFile
, ids
->SystemId
, 32, &dwSize
, NULL
);
1162 SetFilePointer(hFile
, 2048 * 16 + 40, NULL
, FILE_BEGIN
);
1163 bRet
[n
++] = ReadFile(hFile
, ids
->VolumeId
, 32, &dwSize
, NULL
);
1165 SetFilePointer(hFile
, 2048 * 16 + 318, NULL
, FILE_BEGIN
);
1166 bRet
[n
++] = ReadFile(hFile
, ids
->PulisherId
, 128, &dwSize
, NULL
);
1168 SetFilePointer(hFile
, 2048 * 16 + 446, NULL
, FILE_BEGIN
);
1169 bRet
[n
++] = ReadFile(hFile
, ids
->PreparerId
, 128, &dwSize
, NULL
);
1174 for (i
= 0; i
< n
; i
++)
1176 if (bRet
[i
] == FALSE
)
1183 TrimString(ids
->SystemId
, FALSE
);
1184 TrimString(ids
->VolumeId
, FALSE
);
1185 TrimString(ids
->PulisherId
, FALSE
);
1186 TrimString(ids
->PreparerId
, FALSE
);
1188 Log("ISO ID: System<%s> Volume<%s> Pulisher<%s> Preparer<%s>",
1189 ids
->SystemId
, ids
->VolumeId
, ids
->PulisherId
, ids
->PreparerId
);
1194 static int CheckSkipMountIso(CONST CHAR
*IsoPath
)
1196 BOOL InRoot
= FALSE
;
1198 CONST CHAR
*p
= NULL
;
1202 for (p
= IsoPath
; *p
; p
++)
1204 if (*p
== '\\' || *p
== '/')
1215 memset(&ID
, 0, sizeof(ID
));
1216 if (GetIsoId(IsoPath
, &ID
))
1221 //Bob.Ombs.Modified.Win10PEx64.iso will auto find ISO file in root, so we can skip the mount
1222 if (InRoot
&& strcmp(ID
.VolumeId
, "Modified-Win10PEx64") == 0)
1230 static int MountIsoFile(CONST CHAR
*IsoPath
, DWORD PhyDrive
)
1232 if (CheckSkipMountIso(IsoPath
))
1234 Log("Skip mount ISO file for <%s>", IsoPath
);
1238 if (IsWindows8OrGreater())
1240 Log("This is Windows 8 or latter...");
1241 if (VentoyMountISOByAPI(IsoPath
) == 0)
1243 Log("Mount iso by API success");
1248 Log("Mount iso by API failed, maybe not supported, try imdisk");
1249 return VentoyMountISOByImdisk(IsoPath
, PhyDrive
);
1254 Log("This is before Windows 8 ...");
1255 if (VentoyMountISOByImdisk(IsoPath
, PhyDrive
) == 0)
1257 Log("Mount iso by imdisk success");
1262 return VentoyMountISOByAPI(IsoPath
);
1267 static int GetPhyDriveByLogicalDrive(int DriveLetter
)
1272 VOLUME_DISK_EXTENTS DiskExtents
;
1275 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\%C:", (CHAR
)DriveLetter
);
1277 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
1278 if (Handle
== INVALID_HANDLE_VALUE
)
1280 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
1284 Ret
= DeviceIoControl(Handle
,
1285 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
1289 (DWORD
)(sizeof(DiskExtents
)),
1293 if (!Ret
|| DiskExtents
.NumberOfDiskExtents
== 0)
1295 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath
, GetLastError());
1296 SAFE_CLOSE_HANDLE(Handle
);
1299 SAFE_CLOSE_HANDLE(Handle
);
1301 Log("LogicalDrive:%s PhyDrive:%d Offset:%llu ExtentLength:%llu",
1303 DiskExtents
.Extents
[0].DiskNumber
,
1304 DiskExtents
.Extents
[0].StartingOffset
.QuadPart
,
1305 DiskExtents
.Extents
[0].ExtentLength
.QuadPart
1308 return (int)DiskExtents
.Extents
[0].DiskNumber
;
1312 static int DeleteVentoyPart2MountPoint(DWORD PhyDrive
)
1317 CHAR DriveName
[] = "?:\\";
1319 Log("DeleteVentoyPart2MountPoint Phy%u ...", PhyDrive
);
1321 Drives
= GetLogicalDrives();
1324 if ((Drives
& 0x01) && IsFileExist("%C:\\ventoy\\ventoy.cpio", Letter
))
1326 Log("File %C:\\ventoy\\ventoy.cpio exist", Letter
);
1328 PhyDisk
= GetPhyDriveByLogicalDrive(Letter
);
1329 Log("PhyDisk=%u for %C", PhyDisk
, Letter
);
1331 if (PhyDisk
== PhyDrive
)
1333 DriveName
[0] = Letter
;
1334 DeleteVolumeMountPointA(DriveName
);
1346 static BOOL
check_tar_archive(const char *archive
, CHAR
*tarName
)
1350 const char *pos
= archive
;
1351 const char *slash
= archive
;
1355 if (*pos
== '\\' || *pos
== '/')
1362 len
= (int)strlen(slash
);
1364 if (len
> 7 && (strncmp(slash
+ len
- 7, ".tar.gz", 7) == 0 || strncmp(slash
+ len
- 7, ".tar.xz", 7) == 0))
1366 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
1367 tarName
[nameLen
- 3] = 0;
1370 else if (len
> 8 && strncmp(slash
+ len
- 8, ".tar.bz2", 8) == 0)
1372 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
1373 tarName
[nameLen
- 4] = 0;
1376 else if (len
> 9 && strncmp(slash
+ len
- 9, ".tar.lzma", 9) == 0)
1378 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
1379 tarName
[nameLen
- 5] = 0;
1386 static UCHAR
*g_unxz_buffer
= NULL
;
1387 static int g_unxz_len
= 0;
1389 static void unxz_error(char *x
)
1394 static int unxz_flush(void *src
, unsigned int size
)
1396 memcpy(g_unxz_buffer
+ g_unxz_len
, src
, size
);
1397 g_unxz_len
+= (int)size
;
1402 static int DecompressInjectionArchive(const char *archive
, DWORD PhyDrive
)
1406 UCHAR
*Buffer
= NULL
;
1407 UCHAR
*RawBuffer
= NULL
;
1413 DWORD flags
= CREATE_NO_WINDOW
;
1414 CHAR StrBuf
[MAX_PATH
];
1415 CHAR tarName
[MAX_PATH
];
1417 PROCESS_INFORMATION Pi
;
1418 PROCESS_INFORMATION NewPi
;
1419 GET_LENGTH_INFORMATION LengthInfo
;
1420 SECURITY_ATTRIBUTES Sa
= { sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
1422 Log("DecompressInjectionArchive %s", archive
);
1424 sprintf_s(StrBuf
, sizeof(StrBuf
), "\\\\.\\PhysicalDrive%d", PhyDrive
);
1425 hDrive
= CreateFileA(StrBuf
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
1426 if (hDrive
== INVALID_HANDLE_VALUE
)
1428 Log("Could not open the disk<%s>, error:%u", StrBuf
, GetLastError());
1432 bRet
= DeviceIoControl(hDrive
, IOCTL_DISK_GET_LENGTH_INFO
, NULL
, 0, &LengthInfo
, sizeof(LengthInfo
), &dwBytes
, NULL
);
1435 Log("Could not get phy disk %s size, error:%u", StrBuf
, GetLastError());
1439 g_FatPhyDrive
= hDrive
;
1440 g_Part2StartSec
= GetVentoyEfiPartStartSector(hDrive
);
1442 Log("Parse FAT fs...");
1446 if (0 == fl_attach_media(VentoyFatDiskRead
, NULL
))
1448 if (g_system_bit
== 64)
1450 CopyFileFromFatDisk("/ventoy/7z/64/7za.xz", "ventoy\\7za.xz");
1454 CopyFileFromFatDisk("/ventoy/7z/32/7za.xz", "ventoy\\7za.xz");
1457 ReadWholeFile2Buf("ventoy\\7za.xz", &Buffer
, &dwSize
);
1458 Log("7za.xz file size:%u", dwSize
);
1460 RawBuffer
= malloc(SIZE_1MB
* 4);
1463 g_unxz_buffer
= RawBuffer
;
1465 unxz(Buffer
, (int)dwSize
, NULL
, unxz_flush
, NULL
, &writelen
, unxz_error
);
1466 if (writelen
== (int)dwSize
)
1468 Log("Decompress success 7za.xz(%u) ---> 7za.exe(%d)", dwSize
, g_unxz_len
);
1472 Log("Decompress failed 7za.xz(%u) ---> 7za.exe(%u)", dwSize
, dwSize
);
1475 SaveBuffer2File("ventoy\\7za.exe", RawBuffer
, (DWORD
)g_unxz_len
);
1477 g_unxz_buffer
= NULL
;
1483 Log("Failed to alloc 4MB memory");
1486 sprintf_s(StrBuf
, sizeof(StrBuf
), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", archive
);
1488 Log("extract inject to X:");
1489 Log("cmdline:<%s>", StrBuf
);
1491 GetStartupInfoA(&Si
);
1493 hOut
= CreateFileA("ventoy\\7z.log",
1495 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
1498 FILE_ATTRIBUTE_NORMAL
,
1501 Si
.dwFlags
|= STARTF_USESTDHANDLES
;
1503 if (hOut
!= INVALID_HANDLE_VALUE
)
1505 Si
.hStdError
= hOut
;
1506 Si
.hStdOutput
= hOut
;
1509 CreateProcessA(NULL
, StrBuf
, NULL
, NULL
, TRUE
, flags
, NULL
, NULL
, &Si
, &Pi
);
1510 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
1513 // decompress tar archive, for tar.gz/tar.xz/tar.bz2
1515 if (check_tar_archive(archive
, tarName
))
1517 Log("Decompress tar archive...<%s>", tarName
);
1519 sprintf_s(StrBuf
, sizeof(StrBuf
), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", tarName
);
1521 CreateProcessA(NULL
, StrBuf
, NULL
, NULL
, TRUE
, flags
, NULL
, NULL
, &Si
, &NewPi
);
1522 WaitForSingleObject(NewPi
.hProcess
, INFINITE
);
1524 Log("Now delete %s", tarName
);
1525 DeleteFileA(tarName
);
1528 SAFE_CLOSE_HANDLE(hOut
);
1534 SAFE_CLOSE_HANDLE(hDrive
);
1539 static int UnattendNeedVarExpand(const char *script
)
1544 fopen_s(&fp
, script
, "r");
1550 szLine
[0] = szLine
[4095] = 0;
1552 while (fgets(szLine
, sizeof(szLine
) - 1, fp
))
1554 if (strstr(szLine
, "$$VT_"))
1560 szLine
[0] = szLine
[4095] = 0;
1567 static int ExpandSingleVar(VarDiskInfo
*pDiskInfo
, int DiskNum
, const char *var
, char *value
, int len
)
1573 UINT64 uiMaxSize
= 0;
1574 UINT64 uiMaxDelta
= ULLONG_MAX
;
1578 if (strcmp(var
, "VT_WINDOWS_DISK_1ST_NONVTOY") == 0)
1580 for (i
= 0; i
< DiskNum
; i
++)
1582 if (pDiskInfo
[i
].Capacity
> 0 && i
!= g_vtoy_disk_drive
)
1584 Log("%s=<PhyDrive%d>", var
, i
);
1585 sprintf_s(value
, len
, "%d", i
);
1590 else if (strcmp(var
, "VT_WINDOWS_DISK_1ST_NONUSB") == 0)
1592 for (i
= 0; i
< DiskNum
; i
++)
1594 if (pDiskInfo
[i
].Capacity
> 0 && pDiskInfo
[i
].BusType
!= BusTypeUsb
)
1596 Log("%s=<PhyDrive%d>", var
, i
);
1597 sprintf_s(value
, len
, "%d", i
);
1602 else if (strcmp(var
, "VT_WINDOWS_DISK_MAX_SIZE") == 0)
1604 for (i
= 0; i
< DiskNum
; i
++)
1606 if (pDiskInfo
[i
].Capacity
> 0 && pDiskInfo
[i
].Capacity
> uiMaxSize
)
1609 uiMaxSize
= pDiskInfo
[i
].Capacity
;
1613 Log("%s=<PhyDrive%d>", var
, index
);
1614 sprintf_s(value
, len
, "%d", index
);
1616 else if (strncmp(var
, "VT_WINDOWS_DISK_CLOSEST_", 24) == 0)
1618 uiDst
= strtoul(var
+ 24, NULL
, 10);
1619 uiDst
= uiDst
* (1024ULL * 1024ULL * 1024ULL);
1621 for (i
= 0; i
< DiskNum
; i
++)
1623 if (pDiskInfo
[i
].Capacity
== 0)
1628 if (pDiskInfo
[i
].Capacity
> uiDst
)
1630 uiDelta
= pDiskInfo
[i
].Capacity
- uiDst
;
1634 uiDelta
= uiDst
- pDiskInfo
[i
].Capacity
;
1637 if (uiDelta
< uiMaxDelta
)
1639 uiMaxDelta
= uiDelta
;
1644 Log("%s=<PhyDrive%d>", var
, index
);
1645 sprintf_s(value
, len
, "%d", index
);
1649 Log("Invalid var name <%s>", var
);
1650 sprintf_s(value
, len
, "$$%s$$", var
);
1655 sprintf_s(value
, len
, "$$%s$$", var
);
1661 static int GetRegDwordValue(HKEY Key
, LPCSTR SubKey
, LPCSTR ValueName
, DWORD
*pValue
)
1669 lRet
= RegOpenKeyExA(Key
, SubKey
, 0, KEY_QUERY_VALUE
, &hKey
);
1670 Log("RegOpenKeyExA <%s> Ret:%ld", SubKey
, lRet
);
1672 if (ERROR_SUCCESS
== lRet
)
1674 Size
= sizeof(Value
);
1675 lRet
= RegQueryValueExA(hKey
, ValueName
, NULL
, &Type
, (LPBYTE
)&Value
, &Size
);
1676 Log("RegQueryValueExA <%s> ret:%u Size:%u Value:%u", ValueName
, lRet
, Size
, Value
);
1689 static const CHAR
* GetBusTypeString(int Type
)
1693 case BusTypeUnknown
: return "unknown";
1694 case BusTypeScsi
: return "SCSI";
1695 case BusTypeAtapi
: return "Atapi";
1696 case BusTypeAta
: return "ATA";
1697 case BusType1394
: return "1394";
1698 case BusTypeSsa
: return "SSA";
1699 case BusTypeFibre
: return "Fibre";
1700 case BusTypeUsb
: return "USB";
1701 case BusTypeRAID
: return "RAID";
1702 case BusTypeiScsi
: return "iSCSI";
1703 case BusTypeSas
: return "SAS";
1704 case BusTypeSata
: return "SATA";
1705 case BusTypeSd
: return "SD";
1706 case BusTypeMmc
: return "MMC";
1707 case BusTypeVirtual
: return "Virtual";
1708 case BusTypeFileBackedVirtual
: return "FileBackedVirtual";
1709 case BusTypeSpaces
: return "Spaces";
1710 case BusTypeNvme
: return "Nvme";
1715 static int GetHumanReadableGBSize(UINT64 SizeBytes
)
1720 double GB
= SizeBytes
* 1.0 / 1000 / 1000 / 1000;
1722 if ((SizeBytes
% 1073741824) == 0)
1724 return (int)(SizeBytes
/ 1073741824);
1727 for (i
= 0; i
< 12; i
++)
1731 Delta
= (Pow2
- GB
) / Pow2
;
1735 Delta
= (GB
- Pow2
) / Pow2
;
1749 static int EnumerateAllDisk(VarDiskInfo
**ppDiskInfo
, int *pDiskNum
)
1756 VarDiskInfo
*pDiskInfo
= NULL
;
1757 HANDLE Handle
= INVALID_HANDLE_VALUE
;
1759 GET_LENGTH_INFORMATION LengthInfo
;
1760 STORAGE_PROPERTY_QUERY Query
;
1761 STORAGE_DESCRIPTOR_HEADER DevDescHeader
;
1762 STORAGE_DEVICE_DESCRIPTOR
*pDevDesc
;
1764 if (GetRegDwordValue(HKEY_LOCAL_MACHINE
, "SYSTEM\\CurrentControlSet\\Services\\disk\\Enum", "Count", &Value
) == 0)
1766 DiskNum
= (int)Value
;
1770 Log("Failed to read disk count");
1774 Log("Current phy disk count:%d", DiskNum
);
1780 pDiskInfo
= malloc(DiskNum
* sizeof(VarDiskInfo
));
1783 Log("Failed to alloc");
1786 memset(pDiskInfo
, 0, DiskNum
* sizeof(VarDiskInfo
));
1788 for (i
= 0; i
< DiskNum
; i
++)
1790 SAFE_CLOSE_HANDLE(Handle
);
1792 safe_sprintf(PhyDrive
, "\\\\.\\PhysicalDrive%d", i
);
1793 Handle
= CreateFileA(PhyDrive
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, NULL
);
1794 Log("Create file Handle:%p %s status:%u", Handle
, PhyDrive
, LASTERR
);
1796 if (Handle
== INVALID_HANDLE_VALUE
)
1801 bRet
= DeviceIoControl(Handle
,
1802 IOCTL_DISK_GET_LENGTH_INFO
, NULL
,
1810 Log("DeviceIoControl IOCTL_DISK_GET_LENGTH_INFO failed error:%u", LASTERR
);
1814 Log("PHYSICALDRIVE%d size %llu bytes", i
, (ULONGLONG
)LengthInfo
.Length
.QuadPart
);
1816 Query
.PropertyId
= StorageDeviceProperty
;
1817 Query
.QueryType
= PropertyStandardQuery
;
1819 bRet
= DeviceIoControl(Handle
,
1820 IOCTL_STORAGE_QUERY_PROPERTY
,
1824 sizeof(STORAGE_DESCRIPTOR_HEADER
),
1829 Log("DeviceIoControl1 error:%u dwBytes:%u", LASTERR
, dwBytes
);
1833 if (DevDescHeader
.Size
< sizeof(STORAGE_DEVICE_DESCRIPTOR
))
1835 Log("Invalid DevDescHeader.Size:%u", DevDescHeader
.Size
);
1839 pDevDesc
= (STORAGE_DEVICE_DESCRIPTOR
*)malloc(DevDescHeader
.Size
);
1842 Log("failed to malloc error:%u len:%u", LASTERR
, DevDescHeader
.Size
);
1846 bRet
= DeviceIoControl(Handle
,
1847 IOCTL_STORAGE_QUERY_PROPERTY
,
1856 Log("DeviceIoControl2 error:%u dwBytes:%u", LASTERR
, dwBytes
);
1861 pDiskInfo
[i
].RemovableMedia
= pDevDesc
->RemovableMedia
;
1862 pDiskInfo
[i
].BusType
= pDevDesc
->BusType
;
1863 pDiskInfo
[i
].DeviceType
= pDevDesc
->DeviceType
;
1864 pDiskInfo
[i
].Capacity
= LengthInfo
.Length
.QuadPart
;
1866 if (pDevDesc
->VendorIdOffset
)
1868 safe_strcpy(pDiskInfo
[i
].VendorId
, (char *)pDevDesc
+ pDevDesc
->VendorIdOffset
);
1869 TrimString(pDiskInfo
[i
].VendorId
, TRUE
);
1872 if (pDevDesc
->ProductIdOffset
)
1874 safe_strcpy(pDiskInfo
[i
].ProductId
, (char *)pDevDesc
+ pDevDesc
->ProductIdOffset
);
1875 TrimString(pDiskInfo
[i
].ProductId
, TRUE
);
1878 if (pDevDesc
->ProductRevisionOffset
)
1880 safe_strcpy(pDiskInfo
[i
].ProductRev
, (char *)pDevDesc
+ pDevDesc
->ProductRevisionOffset
);
1881 TrimString(pDiskInfo
[i
].ProductRev
, TRUE
);
1884 if (pDevDesc
->SerialNumberOffset
)
1886 safe_strcpy(pDiskInfo
[i
].SerialNumber
, (char *)pDevDesc
+ pDevDesc
->SerialNumberOffset
);
1887 TrimString(pDiskInfo
[i
].SerialNumber
, TRUE
);
1891 SAFE_CLOSE_HANDLE(Handle
);
1894 Log("########## DUMP DISK BEGIN ##########");
1895 for (i
= 0; i
< DiskNum
; i
++)
1897 Log("PhyDrv:%d BusType:%-4s Removable:%u Size:%dGB(%llu) Name:%s %s",
1898 i
, GetBusTypeString(pDiskInfo
[i
].BusType
), pDiskInfo
[i
].RemovableMedia
,
1899 GetHumanReadableGBSize(pDiskInfo
[i
].Capacity
), pDiskInfo
[i
].Capacity
,
1900 pDiskInfo
[i
].VendorId
, pDiskInfo
[i
].ProductId
);
1902 Log("Ventoy disk is PhyDvr%d", g_vtoy_disk_drive
);
1903 Log("########## DUMP DISK END ##########");
1905 *ppDiskInfo
= pDiskInfo
;
1906 *pDiskNum
= DiskNum
;
1910 static int UnattendVarExpand(const char *script
, const char *tmpfile
)
1919 VarDiskInfo
*pDiskInfo
= NULL
;
1921 Log("UnattendVarExpand ...");
1923 if (EnumerateAllDisk(&pDiskInfo
, &DiskNum
))
1925 Log("Failed to EnumerateAllDisk");
1929 fopen_s(&fp
, script
, "r");
1936 fopen_s(&fout
, tmpfile
, "w+");
1944 szLine
[0] = szLine
[4095] = 0;
1946 while (fgets(szLine
, sizeof(szLine
) - 1, fp
))
1948 start
= strstr(szLine
, "$$VT_");
1951 end
= strstr(start
+ 5, "$$");
1957 fprintf(fout
, "%s", szLine
);
1960 ExpandSingleVar(pDiskInfo
, DiskNum
, start
+ 2, szValue
, sizeof(szValue
) - 1);
1961 fprintf(fout
, "%s", szValue
);
1963 fprintf(fout
, "%s", end
+ 2);
1967 fprintf(fout
, "%s", szLine
);
1970 szLine
[0] = szLine
[4095] = 0;
1979 //#define VAR_DEBUG 1
1981 static int CreateUnattendRegKey(const char *file
)
1988 Ret
= RegCreateKeyEx(HKEY_LOCAL_MACHINE
, "System\\Setup", 0, NULL
, REG_OPTION_NON_VOLATILE
, KEY_ALL_ACCESS
, NULL
, &hKey
, &dw
);
1989 if (ERROR_SUCCESS
== Ret
)
1991 Ret
= RegSetValueEx(hKey
, "UnattendFile", 0, REG_SZ
, file
, (DWORD
)(strlen(file
) + 1));
1998 static int ProcessUnattendedInstallation(const char *script
, DWORD PhyDrive
)
2002 CHAR TmpFile
[MAX_PATH
];
2003 CHAR CurDir
[MAX_PATH
];
2004 CHAR ImPath
[MAX_PATH
];
2006 Log("Copy unattended XML ...");
2008 GetCurrentDirectory(sizeof(CurDir
), CurDir
);
2010 if ((Letter
>= 'A' && Letter
<= 'Z') || (Letter
>= 'a' && Letter
<= 'z'))
2012 Log("Current Drive Letter: %C", Letter
);
2020 sprintf_s(CurDir
, sizeof(CurDir
), "%C:\\AutounattendXXX.xml", Letter
);
2022 sprintf_s(CurDir
, sizeof(CurDir
), "%C:\\Unattend.xml", Letter
);
2025 if (UnattendNeedVarExpand(script
))
2027 sprintf_s(TmpFile
, sizeof(TmpFile
), "%C:\\__Autounattend", Letter
);
2028 UnattendVarExpand(script
, TmpFile
);
2030 Log("Expand Copy file <%s> --> <%s>", script
, CurDir
);
2031 CopyFileA(TmpFile
, CurDir
, FALSE
);
2035 Log("No var expand copy file <%s> --> <%s>", script
, CurDir
);
2036 CopyFileA(script
, CurDir
, FALSE
);
2039 VentoyCopyImdisk(PhyDrive
, ImPath
);
2040 DrvLetter
= VentoyGetFirstFreeDriveLetter(FALSE
);
2041 VentoyProcessRunCmd("%s -a -s 64M -m %C: -p \"/fs:FAT32 /q /y\"", ImPath
, DrvLetter
);
2045 sprintf_s(TmpFile
, sizeof(TmpFile
), "%C:\\Unattend.xml", DrvLetter
);
2046 if (CopyFileA(CurDir
, TmpFile
, FALSE
))
2048 DeleteFileA(CurDir
);
2049 Log("Move file <%s> ==> <%s>, use the later as unattend XML", CurDir
, TmpFile
);
2050 CreateUnattendRegKey(TmpFile
);
2054 Log("Failed to copy file <%s> ==> <%s>, use OLD", CurDir
, TmpFile
);
2055 CreateUnattendRegKey(CurDir
);
2061 static int VentoyGetFileVersion(const CHAR
*FilePath
, UINT16
*pMajor
, UINT16
*pMinor
, UINT16
*pBuild
, UINT16
*pRevision
)
2067 CHAR
*Buffer
= NULL
;
2068 VS_FIXEDFILEINFO
* VerInfo
= NULL
;
2069 UINT16 Major
, Minor
, Build
, Revision
;
2071 Log("Get file version for <%s>", FilePath
);
2073 dwSize
= GetFileVersionInfoSizeA(FilePath
, &dwHandle
);
2076 Log("Failed to get file version info size: %u", LASTERR
);
2080 Buffer
= malloc(dwSize
);
2083 Log("malloc failed %u", dwSize
);
2087 if (FALSE
== GetFileVersionInfoA(FilePath
, dwHandle
, dwSize
, Buffer
))
2089 Log("Failed to get file version info : %u", LASTERR
);
2093 if (VerQueryValueA(Buffer
, "\\", (LPVOID
)&VerInfo
, &VerLen
) && VerLen
!= 0)
2095 if (VerInfo
->dwSignature
== VS_FFI_SIGNATURE
)
2097 Major
= HIWORD(VerInfo
->dwFileVersionMS
);
2098 Minor
= LOWORD(VerInfo
->dwFileVersionMS
);
2099 Build
= HIWORD(VerInfo
->dwFileVersionLS
);
2100 Revision
= LOWORD(VerInfo
->dwFileVersionLS
);
2102 Log("FileVersionze: <%u %u %u %u>", Major
, Minor
, Build
, Revision
);
2104 if (Major
== 10 && Build
> 20000)
2123 *pRevision
= Revision
;
2130 Log("Invalid verinfo signature 0x%x", VerInfo
->dwSignature
);
2135 Log("VerQueryValueA failed %u", LASTERR
);
2147 static BOOL
VentoyIsNeedBypass(const char *isofile
, const char MntLetter
)
2151 CHAR CheckFile
[MAX_PATH
];
2153 if (FALSE
== IsFileExist("%C:\\sources\\install.wim", MntLetter
) &&
2154 FALSE
== IsFileExist("%C:\\sources\\install.esd", MntLetter
))
2156 Log("install.wim/install.esd not exist, this is not a windows install media.");
2160 if (FALSE
== IsFileExist("%C:\\sources\\boot.wim", MntLetter
))
2162 Log("boot.wim not exist, this is not a windows install media.");
2166 if (IsFileExist("%C:\\sources\\compatresources.dll", MntLetter
))
2168 sprintf_s(CheckFile
, sizeof(CheckFile
), "%C:\\sources\\compatresources.dll", MntLetter
);
2170 else if (IsFileExist("%C:\\setup.exe", MntLetter
))
2172 sprintf_s(CheckFile
, sizeof(CheckFile
), "%C:\\setup.exe", MntLetter
);
2174 else if (IsFileExist("X:\\setup.exe"))
2176 sprintf_s(CheckFile
, sizeof(CheckFile
), "X:\\setup.exe");
2180 Log("No Check file found");
2184 if (VentoyGetFileVersion(CheckFile
, &Major
, NULL
, NULL
, NULL
))
2191 Log("Enable for Windows 11 %u", Major
);
2196 Log("This is not Windows 11, not need to bypass.", Major
);
2203 static int Windows11Bypass(const char *isofile
, const char MntLetter
, UINT8 Check
, UINT8 NRO
)
2207 HKEY hSubKey
= NULL
;
2212 Log("Windows11Bypass for <%s> %C: Check:%u NRO:%u", isofile
, MntLetter
, Check
, NRO
);
2214 if (!VentoyIsNeedBypass(isofile
, MntLetter
))
2219 //Now we really need to bypass windows 11 check. create registry
2223 Status
= RegCreateKeyExA(HKEY_LOCAL_MACHINE
, "System\\Setup", 0, NULL
, REG_OPTION_NON_VOLATILE
, KEY_ALL_ACCESS
, NULL
, &hKey
, &dwSize
);
2224 if (ERROR_SUCCESS
!= Status
)
2226 Log("Failed to create reg key System\\Setup %u %u", LASTERR
, Status
);
2230 Status
= RegCreateKeyExA(hKey
, "LabConfig", 0, NULL
, 0, KEY_SET_VALUE
| KEY_QUERY_VALUE
| KEY_CREATE_SUB_KEY
, NULL
, &hSubKey
, &dwSize
);
2231 if (ERROR_SUCCESS
!= Status
)
2233 Log("Failed to create LabConfig reg %u %u", LASTERR
, Status
);
2238 Status
+= RegSetValueExA(hSubKey
, "BypassRAMCheck", 0, REG_DWORD
, (LPBYTE
)&dwValue
, sizeof(DWORD
));
2239 Status
+= RegSetValueExA(hSubKey
, "BypassTPMCheck", 0, REG_DWORD
, (LPBYTE
)&dwValue
, sizeof(DWORD
));
2240 Status
+= RegSetValueExA(hSubKey
, "BypassSecureBootCheck", 0, REG_DWORD
, (LPBYTE
)&dwValue
, sizeof(DWORD
));
2241 Status
+= RegSetValueExA(hSubKey
, "BypassCPUCheck", 0, REG_DWORD
, (LPBYTE
)&dwValue
, sizeof(DWORD
));
2243 Log("Create bypass check registry %s %u", (Status
== ERROR_SUCCESS
) ? "SUCCESS" : "FAILED", Status
);
2249 Status
= RegCreateKeyExA(HKEY_LOCAL_MACHINE
, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion", 0, NULL
, REG_OPTION_NON_VOLATILE
, KEY_ALL_ACCESS
, NULL
, &hKey
, &dwSize
);
2250 if (ERROR_SUCCESS
!= Status
)
2252 Log("Failed to create reg key SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\OOBE %u %u", LASTERR
, Status
);
2256 Status
= RegCreateKeyExA(hKey
, "OOBE", 0, NULL
, 0, KEY_SET_VALUE
| KEY_QUERY_VALUE
| KEY_CREATE_SUB_KEY
, NULL
, &hSubKey
, &dwSize
);
2257 if (ERROR_SUCCESS
!= Status
)
2259 Log("Failed to create OOBE reg %u %u", LASTERR
, Status
);
2263 Status
+= RegSetValueExA(hSubKey
, "BypassNRO", 0, REG_DWORD
, (LPBYTE
)&dwValue
, sizeof(DWORD
));
2264 Log("Create BypassNRO registry %s %u", (Status
== ERROR_SUCCESS
) ? "SUCCESS" : "FAILED", Status
);
2275 static BOOL
CheckVentoyDisk(DWORD DiskNum
)
2279 UINT8 SectorBuf
[512];
2281 UINT8 check
[8] = { 0x56, 0x54, 0x00, 0x47, 0x65, 0x00, 0x48, 0x44 };
2283 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\PhysicalDrive%d", DiskNum
);
2284 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
2285 if (Handle
== INVALID_HANDLE_VALUE
)
2287 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
2291 if (!ReadFile(Handle
, SectorBuf
, sizeof(SectorBuf
), &dwSize
, NULL
))
2293 Log("ReadFile failed, dwSize:%u error:%u", dwSize
, GetLastError());
2294 CloseHandle(Handle
);
2298 CloseHandle(Handle
);
2300 if (memcmp(SectorBuf
+ 0x190, check
, 8) == 0)
2308 static BOOL
VentoyIsLenovoRecovery(CHAR
*IsoPath
, CHAR
*VTLRIPath
)
2314 WCHAR FilePathW
[MAX_PATH
];
2316 UTF8
= IsUTF8Encode(IsoPath
);
2320 Utf8ToUtf16(IsoPath
, FilePathW
);
2322 n
= (int)wcslen(FilePathW
);
2323 if (n
> 4 && _wcsicmp(FilePathW
+ n
- 4, L
".iso") == 0)
2325 FilePathW
[n
- 3] = L
'V';
2326 FilePathW
[n
- 2] = L
'T';
2327 FilePathW
[n
- 1] = L
'L';
2328 FilePathW
[n
- 0] = L
'R';
2329 FilePathW
[n
+ 1] = L
'I';
2330 FilePathW
[n
+ 2] = 0;
2332 hFile
= CreateFileW(FilePathW
, FILE_READ_EA
, FILE_SHARE_READ
, 0, OPEN_EXISTING
, 0, 0);
2333 if (hFile
!= INVALID_HANDLE_VALUE
)
2336 Attr
= GetFileAttributesW(FilePathW
);
2338 if ((Attr
& FILE_ATTRIBUTE_DIRECTORY
) == 0)
2340 Utf16ToUtf8(FilePathW
, VTLRIPath
);
2348 n
= (int)strlen(IsoPath
);
2349 if (n
> 4 && _stricmp(IsoPath
+ n
- 4, ".iso") == 0)
2352 sprintf_s(VTLRIPath
, MAX_PATH
, "%s.VTLRI", IsoPath
);
2353 IsoPath
[n
- 4] = '.';
2355 if (IsFileExist(VTLRIPath
))
2365 static int MountVTLRI(CHAR
*ImgPath
, DWORD PhyDrive
)
2367 CHAR ImDiskPath
[256];
2369 Log("MountVTLRI <%s> %u", ImgPath
, PhyDrive
);
2371 VentoyCopyImdisk(PhyDrive
, ImDiskPath
);
2373 VentoyRunImdisk(ImgPath
, ImDiskPath
, "rem");
2378 static int VentoyHook(ventoy_os_param
*param
)
2383 BOOL vtoyfind
= FALSE
;
2392 DISK_EXTENT DiskExtent
;
2393 DISK_EXTENT VtoyDiskExtent
;
2395 CHAR IsoPath
[MAX_PATH
];
2396 CHAR VTLRIPath
[MAX_PATH
];
2398 Log("VentoyHook Path:<%s>", param
->vtoy_img_path
);
2400 if (IsUTF8Encode(param
->vtoy_img_path
))
2402 Log("This file is UTF8 encoding");
2405 for (i
= 0; i
< 5; i
++)
2408 Drives
= GetLogicalDrives();
2409 Log("Logic Drives: 0x%x", Drives
);
2415 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:\\%s", Letter
, param
->vtoy_img_path
);
2416 if (IsFileExist("%s", IsoPath
))
2418 Log("File exist under %C:", Letter
);
2419 memset(UUID
, 0, sizeof(UUID
));
2420 memset(&DiskExtent
, 0, sizeof(DiskExtent
));
2421 if (GetPhyDiskUUID(Letter
, UUID
, NULL
, &DiskExtent
) == 0)
2423 if (memcmp(UUID
, param
->vtoy_disk_guid
, 16) == 0)
2425 Log("Disk UUID match");
2433 Log("File NOT exist under %C:", Letter
);
2447 Log("Now wait and retry ...");
2454 Log("Failed to find ISO file");
2458 Log("Find ISO file <%s>", IsoPath
);
2460 //Find VtoyLetter in Vlnk Mode
2461 if (g_os_param_reserved
[6] == 1)
2463 memcpy(&VtoySig
, g_os_param_reserved
+ 7, 4);
2464 for (i
= 0; i
< 5; i
++)
2467 Drives
= GetLogicalDrives();
2468 Log("Logic Drives: 0x%x VentoySig:%08X", Drives
, VtoySig
);
2474 memset(UUID
, 0, sizeof(UUID
));
2475 memset(&VtoyDiskExtent
, 0, sizeof(VtoyDiskExtent
));
2477 if (GetPhyDiskUUID(VtoyLetter
, UUID
, &DiskSig
, &VtoyDiskExtent
) == 0)
2479 Log("DiskSig=%08X PartStart=%lld", DiskSig
, VtoyDiskExtent
.StartingOffset
.QuadPart
);
2480 if (DiskSig
== VtoySig
&& VtoyDiskExtent
.StartingOffset
.QuadPart
== SIZE_1MB
)
2482 Log("Ventoy Disk Sig match");
2495 Log("Find Ventoy Letter: %C", VtoyLetter
);
2500 Log("Now wait and retry ...");
2505 if (vtoyfind
== FALSE
)
2507 Log("Failed to find ventoy disk");
2511 VtoyDiskNum
= VtoyDiskExtent
.DiskNumber
;
2515 VtoyLetter
= Letter
;
2516 Log("No vlnk mode %C", Letter
);
2518 VtoyDiskNum
= DiskExtent
.DiskNumber
;
2521 if (CheckVentoyDisk(VtoyDiskNum
))
2523 Log("Disk check OK %C: %u", VtoyLetter
, VtoyDiskNum
);
2527 Log("Failed to check ventoy disk %u", VtoyDiskNum
);
2531 g_vtoy_disk_drive
= VtoyDiskNum
;
2533 Drives
= GetLogicalDrives();
2534 Log("Drives before mount: 0x%x", Drives
);
2536 if (VentoyIsLenovoRecovery(IsoPath
, VTLRIPath
))
2538 Log("This is lenovo recovery image, mount VTLRI file.");
2539 rc
= MountVTLRI(VTLRIPath
, VtoyDiskNum
);
2543 Log("This is normal image, mount ISO file.");
2544 rc
= MountIsoFile(IsoPath
, VtoyDiskNum
);
2547 NewDrives
= GetLogicalDrives();
2548 Log("Drives after mount: 0x%x (0x%x)", NewDrives
, (NewDrives
^ Drives
));
2551 NewDrives
= (NewDrives
^ Drives
);
2554 if (NewDrives
& 0x01)
2556 if ((NewDrives
>> 1) == 0)
2558 Log("The ISO file is mounted at %C:", MntLetter
);
2562 Log("Maybe the ISO file is mounted at %C:", MntLetter
);
2571 Log("Mount ISO FILE: %s", rc
== 0 ? "SUCCESS" : "FAILED");
2573 //Windows 11 bypass check
2574 if (g_windows_data
.windows11_bypass_check
== 1 || g_windows_data
.windows11_bypass_nro
== 1)
2576 Windows11Bypass(IsoPath
, MntLetter
, g_windows_data
.windows11_bypass_check
, g_windows_data
.windows11_bypass_nro
);
2580 rc
= DeleteVentoyPart2MountPoint(VtoyDiskNum
);
2581 Log("Delete ventoy mountpoint: %s", rc
== 0 ? "SUCCESS" : "NO NEED");
2583 if (g_windows_data
.auto_install_script
[0])
2585 if (IsFileExist("%s", VTOY_AUTO_FILE
))
2587 Log("use auto install script %s...", VTOY_AUTO_FILE
);
2588 ProcessUnattendedInstallation(VTOY_AUTO_FILE
, VtoyDiskNum
);
2592 Log("auto install script %s not exist", IsoPath
);
2597 Log("auto install no need");
2600 if (g_windows_data
.injection_archive
[0])
2602 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:%s", VtoyLetter
, g_windows_data
.injection_archive
);
2603 if (IsFileExist("%s", IsoPath
))
2605 Log("decompress injection archive %s...", IsoPath
);
2606 DecompressInjectionArchive(IsoPath
, VtoyDiskNum
);
2608 if (IsFileExist("%s", AUTO_RUN_BAT
))
2611 DWORD flags
= CREATE_NO_WINDOW
;
2614 PROCESS_INFORMATION Pi
;
2615 SECURITY_ATTRIBUTES Sa
= { sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
2617 Log("%s exist, now run it...", AUTO_RUN_BAT
);
2619 GetStartupInfoA(&Si
);
2621 hOut
= CreateFileA(AUTO_RUN_LOG
,
2623 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
2626 FILE_ATTRIBUTE_NORMAL
,
2629 Si
.dwFlags
|= STARTF_USESTDHANDLES
;
2630 if (hOut
!= INVALID_HANDLE_VALUE
)
2632 Si
.hStdError
= hOut
;
2633 Si
.hStdOutput
= hOut
;
2636 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:\\%s", Letter
, param
->vtoy_img_path
);
2637 sprintf_s(StrBuf
, sizeof(StrBuf
), "cmd.exe /c %s \"%s\" %C", AUTO_RUN_BAT
, IsoPath
, MntLetter
);
2638 CreateProcessA(NULL
, StrBuf
, NULL
, NULL
, TRUE
, flags
, NULL
, NULL
, &Si
, &Pi
);
2639 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
2641 SAFE_CLOSE_HANDLE(hOut
);
2645 Log("%s not exist...", AUTO_RUN_BAT
);
2650 Log("injection archive %s not exist", IsoPath
);
2655 Log("no injection archive found");
2661 static int ExtractWindowsDataFile(char *databuf
)
2664 char *filedata
= NULL
;
2665 ventoy_windows_data
*pdata
= (ventoy_windows_data
*)databuf
;
2667 Log("ExtractWindowsDataFile: auto install <%s:%d>", pdata
->auto_install_script
, pdata
->auto_install_len
);
2669 filedata
= databuf
+ sizeof(ventoy_windows_data
);
2671 if (pdata
->auto_install_script
[0] && pdata
->auto_install_len
> 0)
2673 SaveBuffer2File(VTOY_AUTO_FILE
, filedata
, pdata
->auto_install_len
);
2674 filedata
+= pdata
->auto_install_len
;
2675 len
= pdata
->auto_install_len
;
2681 static int ventoy_check_create_directory(void)
2683 if (IsDirExist("ventoy"))
2685 Log("ventoy directory already exist");
2689 Log("ventoy directory not exist, now create it.");
2690 if (!CreateDirectoryA("ventoy", NULL
))
2692 Log("Failed to create ventoy directory err:%u", GetLastError());
2700 int VentoyJump(INT argc
, CHAR
**argv
, CHAR
*LunchFile
)
2708 DWORD LockStatus
= 0;
2709 BYTE
*Buffer
= NULL
;
2710 CHAR ExeFileName
[MAX_PATH
];
2712 sprintf_s(ExeFileName
, sizeof(ExeFileName
), "%s", argv
[0]);
2713 if (!IsFileExist("%s", ExeFileName
))
2715 Log("File %s NOT exist, now try %s.exe", ExeFileName
, ExeFileName
);
2716 sprintf_s(ExeFileName
, sizeof(ExeFileName
), "%s.exe", argv
[0]);
2718 Log("File %s exist ? %s", ExeFileName
, IsFileExist("%s", ExeFileName
) ? "YES" : "NO");
2721 if (ReadWholeFile2Buf(ExeFileName
, (void **)&Buffer
, &FileSize
))
2726 Log("VentoyJump %dbit", g_system_bit
);
2728 MUTEX_LOCK(g_vtoyins_mutex
);
2729 stat
= ventoy_check_create_directory();
2730 MUTEX_UNLOCK(g_vtoyins_mutex
);
2737 for (PeStart
= 0; PeStart
< FileSize
; PeStart
+= 16)
2739 if (CheckOsParam((ventoy_os_param
*)(Buffer
+ PeStart
)) &&
2740 CheckPeHead(Buffer
, FileSize
, PeStart
+ sizeof(ventoy_os_param
)))
2742 Log("Find os pararm at %u", PeStart
);
2744 memcpy(&g_os_param
, Buffer
+ PeStart
, sizeof(ventoy_os_param
));
2745 memcpy(&g_windows_data
, Buffer
+ PeStart
+ sizeof(ventoy_os_param
), sizeof(ventoy_windows_data
));
2746 exlen
= ExtractWindowsDataFile(Buffer
+ PeStart
+ sizeof(ventoy_os_param
));
2747 memcpy(g_os_param_reserved
, g_os_param
.vtoy_reserved
, sizeof(g_os_param_reserved
));
2749 if (g_os_param_reserved
[0] == 1)
2751 Log("break here for debug .....");
2756 for (Pos
= 0; Pos
< sizeof(g_os_param
.vtoy_img_path
) && g_os_param
.vtoy_img_path
[Pos
]; Pos
++)
2758 if (g_os_param
.vtoy_img_path
[Pos
] == '/')
2760 g_os_param
.vtoy_img_path
[Pos
] = '\\';
2764 PeStart
+= sizeof(ventoy_os_param
) + sizeof(ventoy_windows_data
) + exlen
;
2765 sprintf_s(LunchFile
, MAX_PATH
, "ventoy\\%s", GetFileNameInPath(ExeFileName
));
2767 MUTEX_LOCK(g_vtoyins_mutex
);
2768 if (IsFileExist("%s", LunchFile
))
2770 Log("vtoyjump multiple call ...");
2772 MUTEX_UNLOCK(g_vtoyins_mutex
);
2776 SaveBuffer2File(LunchFile
, Buffer
+ PeStart
, FileSize
- PeStart
);
2777 MUTEX_UNLOCK(g_vtoyins_mutex
);
2783 if (PeStart
>= FileSize
)
2785 Log("OS param not found");
2789 if (g_os_param_reserved
[0] == 2)
2791 Log("skip hook for debug .....");
2796 rc
= VentoyHook(&g_os_param
);
2809 int real_main(int argc
, char **argv
)
2813 CHAR NewFile
[MAX_PATH
];
2814 CHAR LunchFile
[MAX_PATH
];
2815 CHAR CallParam
[1024] = { 0 };
2817 PROCESS_INFORMATION Pi
;
2819 Log("#### real_main #### argc = %d", argc
);
2820 Log("program full path: <%s>", g_prog_full_path
);
2821 Log("program dir: <%s>", g_prog_dir
);
2822 Log("program name: <%s>", g_prog_name
);
2824 Log("argc = %d", argc
);
2825 for (i
= 0; i
< argc
; i
++)
2827 Log("argv[%d]=<%s>", i
, argv
[i
]);
2830 strcat_s(CallParam
, sizeof(CallParam
), " ");
2831 strcat_s(CallParam
, sizeof(CallParam
), argv
[i
]);
2835 GetStartupInfoA(&Si
);
2836 memset(LunchFile
, 0, sizeof(LunchFile
));
2838 rc
= VentoyJump(argc
, argv
, LunchFile
);
2840 Log("LunchFile=<%s> CallParam=<%s>", LunchFile
, CallParam
);
2842 if (_stricmp(g_prog_name
, "winpeshl.exe") != 0 && IsFileExist("ventoy\\%s", g_prog_name
))
2844 sprintf_s(NewFile
, sizeof(NewFile
), "%s\\VTOYJUMP.EXE", g_prog_dir
);
2845 MoveFileA(g_prog_full_path
, NewFile
);
2846 Log("Move <%s> to <%s>", g_prog_full_path
, NewFile
);
2848 sprintf_s(NewFile
, sizeof(NewFile
), "ventoy\\%s", g_prog_name
);
2849 CopyFileA(NewFile
, g_prog_full_path
, TRUE
);
2850 Log("Copy <%s> to <%s>", NewFile
, g_prog_full_path
);
2852 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", g_prog_full_path
);
2853 Log("Final lunchFile is <%s>", LunchFile
);
2857 Log("We don't need to recover original <%s>", g_prog_name
);
2860 if (g_os_param_reserved
[0] == 3)
2862 Log("Open log for debug ...");
2863 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", "notepad.exe ventoy.log");
2869 strcat_s(LunchFile
, sizeof(LunchFile
), CallParam
);
2871 else if (NULL
== strstr(LunchFile
, "setup.exe"))
2873 Log("Not setup.exe, hide windows.");
2874 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
2875 Si
.wShowWindow
= SW_HIDE
;
2878 Log("Ventoy jump %s ...", rc
== 0 ? "success" : "failed");
2881 Log("Now launch <%s> ...", LunchFile
);
2883 if (g_os_param_reserved
[0] == 4)
2885 Log("Open cmd for debug ...");
2886 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
2887 Si
.wShowWindow
= SW_NORMAL
;
2888 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", "cmd.exe");
2891 Log("Backup log at this point");
2892 CopyFileA(LOG_FILE
, "X:\\Windows\\ventoy.backup", TRUE
);
2894 CreateProcessA(NULL
, LunchFile
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
2896 for (i
= 0; rc
&& i
< 1800; i
++)
2898 Log("Ventoy hook failed, now wait and retry ...");
2900 rc
= VentoyHook(&g_os_param
);
2903 Log("Wait process...");
2904 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
2906 Log("vtoyjump finished");
2910 static void VentoyToUpper(CHAR
*str
)
2913 for (i
= 0; str
[i
]; i
++)
2915 str
[i
] = (CHAR
)toupper(str
[i
]);
2919 static int vtoy_remove_duplicate_file(char *File
)
2921 CHAR szCmd
[MAX_PATH
];
2922 CHAR NewFile
[MAX_PATH
];
2924 PROCESS_INFORMATION Pi
;
2926 Log("<1> Copy New file", File
);
2927 sprintf_s(NewFile
, sizeof(NewFile
), "%s_NEW", File
);
2928 CopyFileA(File
, NewFile
, FALSE
);
2930 Log("<2> Remove file <%s>", File
);
2931 GetStartupInfoA(&Si
);
2932 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
2933 Si
.wShowWindow
= SW_HIDE
;
2934 sprintf_s(szCmd
, sizeof(szCmd
), "cmd.exe /c del /F /Q %s", File
);
2935 CreateProcessA(NULL
, szCmd
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
2936 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
2938 Log("<3> Copy back file <%s>", File
);
2939 MoveFileA(NewFile
, File
);
2944 int main(int argc
, char **argv
)
2948 PROCESS_INFORMATION Pi
;
2949 CHAR CurDir
[MAX_PATH
];
2950 CHAR NewArgv0
[MAX_PATH
];
2951 CHAR CallParam
[1024] = { 0 };
2953 g_vtoylog_mutex
= CreateMutexA(NULL
, FALSE
, "VTOYLOG_LOCK");
2954 g_vtoyins_mutex
= CreateMutexA(NULL
, FALSE
, "VTOYINS_LOCK");
2956 Log("######## VentoyJump %dbit ##########", g_system_bit
);
2958 GetCurrentDirectoryA(sizeof(CurDir
), CurDir
);
2959 Log("Current directory is <%s>", CurDir
);
2961 GetModuleFileNameA(NULL
, g_prog_full_path
, MAX_PATH
);
2962 split_path_name(g_prog_full_path
, g_prog_dir
, g_prog_name
);
2964 Log("EXE path: <%s> dir:<%s> name:<%s>", g_prog_full_path
, g_prog_dir
, g_prog_name
);
2966 if (IsFileExist(WIMBOOT_FILE
))
2968 Log("This is wimboot mode ...");
2969 g_wimboot_mode
= TRUE
;
2971 if (!IsFileExist(WIMBOOT_DONE
))
2973 vtoy_remove_duplicate_file(g_prog_full_path
);
2974 SaveBuffer2File(WIMBOOT_DONE
, g_prog_full_path
, 1);
2979 Log("This is normal mode ...");
2982 if (_stricmp(g_prog_name
, "WinLogon.exe") == 0)
2984 Log("This time is rejump back ...");
2986 strcpy_s(g_prog_full_path
, sizeof(g_prog_full_path
), argv
[1]);
2987 split_path_name(g_prog_full_path
, g_prog_dir
, g_prog_name
);
2989 return real_main(argc
- 1, argv
+ 1);
2991 else if (_stricmp(g_prog_name
, "PECMD.exe") == 0)
2993 strcpy_s(NewArgv0
, sizeof(NewArgv0
), g_prog_dir
);
2994 VentoyToUpper(NewArgv0
);
2996 if (NULL
== strstr(NewArgv0
, "SYSTEM32") && IsFileExist(ORG_PECMD_BK_PATH
))
2998 Log("Just call original pecmd.exe");
2999 strcpy_s(CallParam
, sizeof(CallParam
), ORG_PECMD_PATH
);
3003 Log("We need to rejump for pecmd ...");
3005 ventoy_check_create_directory();
3006 CopyFileA(g_prog_full_path
, "ventoy\\WinLogon.exe", TRUE
);
3008 sprintf_s(CallParam
, sizeof(CallParam
), "ventoy\\WinLogon.exe %s", g_prog_full_path
);
3011 for (i
= 1; i
< argc
; i
++)
3013 strcat_s(CallParam
, sizeof(CallParam
), " ");
3014 strcat_s(CallParam
, sizeof(CallParam
), argv
[i
]);
3017 Log("Now rejump to <%s> ...", CallParam
);
3018 GetStartupInfoA(&Si
);
3019 CreateProcessA(NULL
, CallParam
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
3021 Log("Wait rejump process...");
3022 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
3023 Log("rejump finished");
3028 Log("We don't need to rejump ...");
3030 ventoy_check_create_directory();
3031 strcpy_s(NewArgv0
, sizeof(NewArgv0
), g_prog_full_path
);
3034 return real_main(argc
, argv
);