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\\PECMD.EXE_BACK.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 static const char * GetFileNameInPath(const char *fullpath
)
67 if (strstr(fullpath
, ":"))
69 for (i
= (int)strlen(fullpath
); i
> 0; i
--)
71 if (fullpath
[i
- 1] == '/' || fullpath
[i
- 1] == '\\')
81 static int split_path_name(char *fullpath
, char *dir
, char *name
)
86 Pos
= (CHAR
*)GetFileNameInPath(fullpath
);
88 strcpy_s(name
, MAX_PATH
, Pos
);
92 strcpy_s(dir
, MAX_PATH
, fullpath
);
98 static void TrimString(CHAR
*String
, BOOL TrimLeft
)
102 size_t Len
= strlen(String
);
106 if (String
[Len
- 1] != ' ' && String
[Len
- 1] != '\t')
116 while (*Pos1
== ' ' || *Pos1
== '\t')
131 void Log(const char *Fmt
, ...)
138 DWORD LockStatus
= 0;
139 DWORD PID
= GetCurrentProcessId();
142 Len
+= sprintf_s(szBuf
, sizeof(szBuf
),
143 "[%4d/%02d/%02d %02d:%02d:%02d.%03d] [%u] ",
144 Sys
.wYear
, Sys
.wMonth
, Sys
.wDay
,
145 Sys
.wHour
, Sys
.wMinute
, Sys
.wSecond
,
146 Sys
.wMilliseconds
, PID
);
149 Len
+= vsnprintf_s(szBuf
+ Len
, sizeof(szBuf
)-Len
, sizeof(szBuf
)-Len
, Fmt
, Arg
);
152 MUTEX_LOCK(g_vtoylog_mutex
);
154 fopen_s(&File
, LOG_FILE
, "a+");
157 fwrite(szBuf
, 1, Len
, File
);
158 fwrite("\n", 1, 1, File
);
162 MUTEX_UNLOCK(g_vtoylog_mutex
);
166 static int LoadNtDriver(const char *DrvBinPath
)
172 SC_HANDLE hServiceMgr
;
174 char name
[256] = { 0 };
176 for (i
= (int)strlen(DrvBinPath
) - 1; i
>= 0; i
--)
178 if (DrvBinPath
[i
] == '\\' || DrvBinPath
[i
] == '/')
180 sprintf_s(name
, sizeof(name
), "%s", DrvBinPath
+ i
+ 1);
185 Log("Load NT driver: %s %s", DrvBinPath
, name
);
187 hServiceMgr
= OpenSCManagerA(NULL
, NULL
, SC_MANAGER_ALL_ACCESS
);
188 if (hServiceMgr
== NULL
)
190 Log("OpenSCManager failed Error:%u", GetLastError());
194 Log("OpenSCManager OK");
196 hService
= CreateServiceA(hServiceMgr
,
200 SERVICE_KERNEL_DRIVER
,
201 SERVICE_DEMAND_START
,
202 SERVICE_ERROR_NORMAL
,
204 NULL
, NULL
, NULL
, NULL
, NULL
);
205 if (hService
== NULL
)
207 Status
= GetLastError();
208 if (Status
!= ERROR_IO_PENDING
&& Status
!= ERROR_SERVICE_EXISTS
)
210 Log("CreateService failed v %u", Status
);
211 CloseServiceHandle(hServiceMgr
);
215 hService
= OpenServiceA(hServiceMgr
, name
, SERVICE_ALL_ACCESS
);
216 if (hService
== NULL
)
218 Log("OpenService failed %u", Status
);
219 CloseServiceHandle(hServiceMgr
);
224 Log("CreateService imdisk OK");
226 Ret
= StartServiceA(hService
, 0, NULL
);
229 Log("StartService OK");
233 Status
= GetLastError();
234 if (Status
== ERROR_SERVICE_ALREADY_RUNNING
)
240 Log("StartService error %u", Status
);
245 CloseServiceHandle(hService
);
246 CloseServiceHandle(hServiceMgr
);
248 Log("Load NT driver %s", rc
? "failed" : "success");
253 static int ReadWholeFile2Buf(const char *Fullpath
, void **Data
, DWORD
*Size
)
261 Log("ReadWholeFile2Buf <%s>", Fullpath
);
263 Handle
= CreateFileA(Fullpath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
264 if (Handle
== INVALID_HANDLE_VALUE
)
266 Log("Could not open the file<%s>, error:%u", Fullpath
, GetLastError());
270 FileSize
= SetFilePointer(Handle
, 0, NULL
, FILE_END
);
272 Buffer
= malloc(FileSize
);
275 Log("Failed to alloc memory size:%u", FileSize
);
279 SetFilePointer(Handle
, 0, NULL
, FILE_BEGIN
);
280 if (!ReadFile(Handle
, Buffer
, FileSize
, &dwSize
, NULL
))
282 Log("ReadFile failed, dwSize:%u error:%u", dwSize
, GetLastError());
289 Log("Success read file size:%u", FileSize
);
294 SAFE_CLOSE_HANDLE(Handle
);
299 static BOOL
CheckPeHead(BYTE
*Buffer
, DWORD Size
, DWORD Offset
)
304 ventoy_windows_data
*pdata
= NULL
;
306 Head
= Buffer
+ Offset
;
307 pdata
= (ventoy_windows_data
*)Head
;
308 Head
+= sizeof(ventoy_windows_data
);
310 if (pdata
->auto_install_script
[0] && pdata
->auto_install_len
> 0)
312 End
= Offset
+ sizeof(ventoy_windows_data
) + pdata
->auto_install_len
+ 60;
315 Head
+= pdata
->auto_install_len
;
319 if (Head
[0] != 'M' || Head
[1] != 'Z')
324 PeOffset
= *(UINT32
*)(Head
+ 60);
325 if (*(UINT32
*)(Head
+ PeOffset
) != 0x00004550)
334 static BOOL
CheckOsParam(ventoy_os_param
*param
)
339 if (memcmp(¶m
->guid
, &g_ventoy_guid
, sizeof(ventoy_guid
)))
344 for (i
= 0; i
< sizeof(ventoy_os_param
); i
++)
346 Sum
+= *((BYTE
*)param
+ i
);
354 if (param
->vtoy_img_location_addr
% 4096)
362 static int SaveBuffer2File(const char *Fullpath
, void *Buffer
, DWORD Length
)
368 Log("SaveBuffer2File <%s> len:%u", Fullpath
, Length
);
370 Handle
= CreateFileA(Fullpath
, GENERIC_READ
| GENERIC_WRITE
,
371 FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, CREATE_NEW
, 0, 0);
372 if (Handle
== INVALID_HANDLE_VALUE
)
374 Log("Could not create new file, error:%u", GetLastError());
378 WriteFile(Handle
, Buffer
, Length
, &dwSize
, NULL
);
383 SAFE_CLOSE_HANDLE(Handle
);
388 static int IsUTF8Encode(const char *src
)
391 const UCHAR
*Byte
= (const UCHAR
*)src
;
393 for (i
= 0; i
< MAX_PATH
&& Byte
[i
]; i
++)
404 static int Utf8ToUtf16(const char* src
, WCHAR
* dst
)
406 int size
= MultiByteToWideChar(CP_UTF8
, 0, src
, -1, dst
, 0);
407 return MultiByteToWideChar(CP_UTF8
, 0, src
, -1, dst
, size
+ 1);
410 static BOOL
IsDirExist(const char *Fmt
, ...)
415 CHAR FilePathA
[MAX_PATH
];
416 WCHAR FilePathW
[MAX_PATH
];
419 vsnprintf_s(FilePathA
, sizeof(FilePathA
), sizeof(FilePathA
), Fmt
, Arg
);
422 UTF8
= IsUTF8Encode(FilePathA
);
426 Utf8ToUtf16(FilePathA
, FilePathW
);
427 Attr
= GetFileAttributesW(FilePathW
);
431 Attr
= GetFileAttributesA(FilePathA
);
434 if (Attr
!= INVALID_FILE_ATTRIBUTES
&& (Attr
& FILE_ATTRIBUTE_DIRECTORY
))
442 static BOOL
IsFileExist(const char *Fmt
, ...)
449 CHAR FilePathA
[MAX_PATH
];
450 WCHAR FilePathW
[MAX_PATH
];
453 vsnprintf_s(FilePathA
, sizeof(FilePathA
), sizeof(FilePathA
), Fmt
, Arg
);
456 UTF8
= IsUTF8Encode(FilePathA
);
460 Utf8ToUtf16(FilePathA
, FilePathW
);
461 hFile
= CreateFileW(FilePathW
, FILE_READ_EA
, FILE_SHARE_READ
, 0, OPEN_EXISTING
, 0, 0);
465 hFile
= CreateFileA(FilePathA
, FILE_READ_EA
, FILE_SHARE_READ
, 0, OPEN_EXISTING
, 0, 0);
467 if (INVALID_HANDLE_VALUE
== hFile
)
476 Attr
= GetFileAttributesW(FilePathW
);
480 Attr
= GetFileAttributesA(FilePathA
);
483 if (Attr
& FILE_ATTRIBUTE_DIRECTORY
)
491 Log("File <%s> %s", FilePathA
, (bRet
? "exist" : "NOT exist"));
495 static int GetPhyDiskUUID(const char LogicalDrive
, UINT8
*UUID
, UINT32
*DiskSig
, DISK_EXTENT
*DiskExtent
)
500 VOLUME_DISK_EXTENTS DiskExtents
;
502 UINT8 SectorBuf
[512];
504 Log("GetPhyDiskUUID %C", LogicalDrive
);
506 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\%C:", LogicalDrive
);
507 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
508 if (Handle
== INVALID_HANDLE_VALUE
)
510 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
514 Ret
= DeviceIoControl(Handle
,
515 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
519 (DWORD
)(sizeof(DiskExtents
)),
522 if (!Ret
|| DiskExtents
.NumberOfDiskExtents
== 0)
524 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed, error:%u", GetLastError());
530 memcpy(DiskExtent
, DiskExtents
.Extents
, sizeof(DISK_EXTENT
));
531 Log("%C: is in PhysicalDrive%d Offset:%llu", LogicalDrive
, DiskExtents
.Extents
[0].DiskNumber
,
532 (ULONGLONG
)(DiskExtents
.Extents
[0].StartingOffset
.QuadPart
));
534 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\PhysicalDrive%d", DiskExtents
.Extents
[0].DiskNumber
);
535 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
536 if (Handle
== INVALID_HANDLE_VALUE
)
538 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
542 if (!ReadFile(Handle
, SectorBuf
, sizeof(SectorBuf
), &dwSize
, NULL
))
544 Log("ReadFile failed, dwSize:%u error:%u", dwSize
, GetLastError());
549 memcpy(UUID
, SectorBuf
+ 0x180, 16);
552 memcpy(DiskSig
, SectorBuf
+ 0x1B8, 4);
559 static int VentoyMountAnywhere(HANDLE Handle
)
562 ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters
;
564 Log("VentoyMountAnywhere");
566 memset(&AttachParameters
, 0, sizeof(AttachParameters
));
567 AttachParameters
.Version
= ATTACH_VIRTUAL_DISK_VERSION_1
;
569 Status
= AttachVirtualDisk(Handle
, NULL
, ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY
| ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME
, 0, &AttachParameters
, NULL
);
570 if (Status
!= ERROR_SUCCESS
)
572 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
579 int VentoyMountY(HANDLE Handle
)
584 DWORD physicalDriveNameSize
;
586 WCHAR physicalDriveName
[MAX_PATH
];
587 CHAR physicalDriveNameA
[MAX_PATH
];
588 CHAR cdromDriveName
[MAX_PATH
];
589 ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters
;
593 memset(&AttachParameters
, 0, sizeof(AttachParameters
));
594 AttachParameters
.Version
= ATTACH_VIRTUAL_DISK_VERSION_1
;
596 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
);
597 if (Status
!= ERROR_SUCCESS
)
599 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
603 memset(physicalDriveName
, 0, sizeof(physicalDriveName
));
604 memset(physicalDriveNameA
, 0, sizeof(physicalDriveNameA
));
606 physicalDriveNameSize
= MAX_PATH
;
607 Status
= GetVirtualDiskPhysicalPath(Handle
, &physicalDriveNameSize
, physicalDriveName
);
608 if (Status
!= ERROR_SUCCESS
)
610 Log("Failed GetVirtualDiskPhysicalPath ErrorCode:%u", Status
);
614 for (i
= 0; physicalDriveName
[i
]; i
++)
616 physicalDriveNameA
[i
] = (CHAR
)toupper((CHAR
)(physicalDriveName
[i
]));
619 Log("physicalDriveNameA=<%s>", physicalDriveNameA
);
621 Pos
= strstr(physicalDriveNameA
, "CDROM");
624 Log("Not cdrom phy drive");
628 sprintf_s(cdromDriveName
, sizeof(cdromDriveName
), "\\Device\\%s", Pos
);
629 Log("cdromDriveName=<%s>", cdromDriveName
);
631 for (i
= 0; i
< 3 && (bRet
== FALSE
); i
++)
634 bRet
= DefineDosDeviceA(DDD_RAW_TARGET_PATH
, "Y:", cdromDriveName
);
635 Log("DefineDosDeviceA %s", bRet
? "success" : "failed");
641 static BOOL
VentoyAPINeedMountY(const char *IsoPath
)
649 static int VentoyAttachVirtualDisk(HANDLE Handle
, const char *IsoPath
)
654 Drives
= GetLogicalDrives();
655 if ((1 << 24) & Drives
)
657 Log("Y: is occupied");
662 Log("Y: is free now");
666 if (DriveYFree
&& VentoyAPINeedMountY(IsoPath
))
668 return VentoyMountY(Handle
);
672 return VentoyMountAnywhere(Handle
);
676 int VentoyMountISOByAPI(const char *IsoPath
)
681 WCHAR wFilePath
[512] = { 0 };
682 VIRTUAL_STORAGE_TYPE StorageType
;
683 OPEN_VIRTUAL_DISK_PARAMETERS OpenParameters
;
685 Log("VentoyMountISOByAPI <%s>", IsoPath
);
687 if (IsUTF8Encode(IsoPath
))
689 Log("This is UTF8 encoding");
690 MultiByteToWideChar(CP_UTF8
, 0, IsoPath
, (int)strlen(IsoPath
), wFilePath
, (int)(sizeof(wFilePath
) / sizeof(WCHAR
)));
694 Log("This is ANSI encoding");
695 MultiByteToWideChar(CP_ACP
, 0, IsoPath
, (int)strlen(IsoPath
), wFilePath
, (int)(sizeof(wFilePath
) / sizeof(WCHAR
)));
698 memset(&StorageType
, 0, sizeof(StorageType
));
699 memset(&OpenParameters
, 0, sizeof(OpenParameters
));
701 OpenParameters
.Version
= OPEN_VIRTUAL_DISK_VERSION_1
;
703 for (i
= 0; i
< 10; i
++)
705 Status
= OpenVirtualDisk(&StorageType
, wFilePath
, VIRTUAL_DISK_ACCESS_READ
, 0, &OpenParameters
, &Handle
);
706 if (ERROR_FILE_NOT_FOUND
== Status
|| ERROR_PATH_NOT_FOUND
== Status
)
708 Log("OpenVirtualDisk ErrorCode:%u, now wait and retry...", Status
);
713 if (ERROR_SUCCESS
== Status
)
715 Log("OpenVirtualDisk success");
717 else if (ERROR_VIRTDISK_PROVIDER_NOT_FOUND
== Status
)
719 Log("VirtualDisk for ISO file is not supported in current system");
723 Log("Failed to open virtual disk ErrorCode:%u", Status
);
729 if (Status
!= ERROR_SUCCESS
)
734 Log("OpenVirtualDisk success");
736 Status
= VentoyAttachVirtualDisk(Handle
, IsoPath
);
737 if (Status
!= ERROR_SUCCESS
)
739 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
744 Log("VentoyAttachVirtualDisk success");
751 static HANDLE g_FatPhyDrive
;
752 static UINT64 g_Part2StartSec
;
754 static int CopyFileFromFatDisk(const CHAR
* SrcFile
, const CHAR
*DstFile
)
761 Log("CopyFileFromFatDisk (%s)==>(%s)", SrcFile
, DstFile
);
763 flfile
= fl_fopen(SrcFile
, "rb");
766 fl_fseek(flfile
, 0, SEEK_END
);
767 size
= (int)fl_ftell(flfile
);
768 fl_fseek(flfile
, 0, SEEK_SET
);
770 buf
= (char *)malloc(size
);
773 fl_fread(buf
, 1, size
, flfile
);
776 SaveBuffer2File(DstFile
, buf
, size
);
786 static int VentoyFatDiskRead(uint32 Sector
, uint8
*Buffer
, uint32 SectorCount
)
791 LARGE_INTEGER liCurrentPosition
;
793 liCurrentPosition
.QuadPart
= Sector
+ g_Part2StartSec
;
794 liCurrentPosition
.QuadPart
*= 512;
795 SetFilePointerEx(g_FatPhyDrive
, liCurrentPosition
, &liCurrentPosition
, FILE_BEGIN
);
797 ReadSize
= (DWORD
)(SectorCount
* 512);
799 bRet
= ReadFile(g_FatPhyDrive
, Buffer
, ReadSize
, &dwSize
, NULL
);
800 if (bRet
== FALSE
|| dwSize
!= ReadSize
)
802 Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u", bRet
, ReadSize
, dwSize
, GetLastError());
808 static BOOL
Is2K10PE(void)
814 fopen_s(&fp
, "X:\\Windows\\System32\\PECMD.INI", "r");
820 memset(szLine
, 0, sizeof(szLine
));
821 while (fgets(szLine
, sizeof(szLine
) - 1, fp
))
823 if (strstr(szLine
, "2k10\\"))
834 static CHAR
GetIMDiskMountLogicalDrive(void)
838 DWORD Mask
= 0x1000000;
840 // fixed use M as mountpoint for 2K10 PE
843 Log("Use M: for 2K10 PE");
847 Drives
= GetLogicalDrives();
848 Log("Drives=0x%x", Drives
);
852 if ((Drives
& Mask
) == 0)
864 UINT64
GetVentoyEfiPartStartSector(HANDLE hDrive
)
869 VTOY_GPT_INFO
*pGpt
= NULL
;
870 UINT64 StartSector
= 0;
872 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
874 bRet
= ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
875 Log("Read MBR Ret:%u Size:%u code:%u", bRet
, dwSize
, LASTERR
);
877 if ((!bRet
) || (dwSize
!= sizeof(MBR
)))
882 if (MBR
.PartTbl
[0].FsFlag
== 0xEE)
884 Log("GPT partition style");
886 pGpt
= malloc(sizeof(VTOY_GPT_INFO
));
892 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
893 bRet
= ReadFile(hDrive
, pGpt
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
);
894 if ((!bRet
) || (dwSize
!= sizeof(VTOY_GPT_INFO
)))
896 Log("Failed to read gpt info %d %u %d", bRet
, dwSize
, LASTERR
);
900 StartSector
= pGpt
->PartTbl
[1].StartLBA
;
905 Log("MBR partition style");
906 StartSector
= MBR
.PartTbl
[1].StartSectorId
;
909 Log("GetVentoyEfiPart StartSector: %llu", StartSector
);
913 static int VentoyRunImdisk(const char *IsoPath
, const char *imdiskexe
)
918 PROCESS_INFORMATION Pi
;
920 Log("VentoyRunImdisk <%s> <%s>", IsoPath
, imdiskexe
);
922 Letter
= GetIMDiskMountLogicalDrive();
923 sprintf_s(Cmdline
, sizeof(Cmdline
), "%s -a -o ro -f \"%s\" -m %C:", imdiskexe
, IsoPath
, Letter
);
924 Log("mount iso to %C: use imdisk cmd <%s>", Letter
, Cmdline
);
926 if (IsUTF8Encode(IsoPath
))
929 GetStartupInfoW(&Si
);
930 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
931 Si
.wShowWindow
= SW_HIDE
;
933 Utf8ToUtf16(Cmdline
, CmdlineW
);
934 CreateProcessW(NULL
, CmdlineW
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
936 Log("This is UTF8 encoding");
941 GetStartupInfoA(&Si
);
942 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
943 Si
.wShowWindow
= SW_HIDE
;
945 CreateProcessA(NULL
, Cmdline
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
947 Log("This is ANSI encoding");
950 Log("Wait for imdisk process ...");
951 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
952 Log("imdisk process finished");
957 int VentoyMountISOByImdisk(const char *IsoPath
, DWORD PhyDrive
)
963 CHAR PhyPath
[MAX_PATH
];
964 GET_LENGTH_INFORMATION LengthInfo
;
966 Log("VentoyMountISOByImdisk %s", IsoPath
);
968 if (IsFileExist("X:\\Windows\\System32\\imdisk.exe"))
970 Log("imdisk.exe exist, use it directly...");
971 VentoyRunImdisk(IsoPath
, "imdisk.exe");
975 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\PhysicalDrive%d", PhyDrive
);
976 hDrive
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
977 if (hDrive
== INVALID_HANDLE_VALUE
)
979 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
983 bRet
= DeviceIoControl(hDrive
, IOCTL_DISK_GET_LENGTH_INFO
, NULL
, 0, &LengthInfo
, sizeof(LengthInfo
), &dwBytes
, NULL
);
986 Log("Could not get phy disk %s size, error:%u", PhyPath
, GetLastError());
990 g_FatPhyDrive
= hDrive
;
991 g_Part2StartSec
= GetVentoyEfiPartStartSector(hDrive
);
993 Log("Parse FAT fs...");
997 if (0 == fl_attach_media(VentoyFatDiskRead
, NULL
))
999 if (g_system_bit
== 64)
1001 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.sys", "ventoy\\imdisk.sys");
1002 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.exe", "ventoy\\imdisk.exe");
1003 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.cpl", "ventoy\\imdisk.cpl");
1007 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.sys", "ventoy\\imdisk.sys");
1008 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.exe", "ventoy\\imdisk.exe");
1009 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.cpl", "ventoy\\imdisk.cpl");
1012 GetCurrentDirectoryA(sizeof(PhyPath
), PhyPath
);
1013 strcat_s(PhyPath
, sizeof(PhyPath
), "\\ventoy\\imdisk.sys");
1015 if (LoadNtDriver(PhyPath
) == 0)
1017 VentoyRunImdisk(IsoPath
, "ventoy\\imdisk.exe");
1025 SAFE_CLOSE_HANDLE(hDrive
);
1030 static int GetIsoId(CONST CHAR
*IsoPath
, IsoId
*ids
)
1038 hFile
= CreateFileA(IsoPath
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, NULL
);
1039 if (hFile
== INVALID_HANDLE_VALUE
)
1044 SetFilePointer(hFile
, 2048 * 16 + 8, NULL
, FILE_BEGIN
);
1045 bRet
[n
++] = ReadFile(hFile
, ids
->SystemId
, 32, &dwSize
, NULL
);
1047 SetFilePointer(hFile
, 2048 * 16 + 40, NULL
, FILE_BEGIN
);
1048 bRet
[n
++] = ReadFile(hFile
, ids
->VolumeId
, 32, &dwSize
, NULL
);
1050 SetFilePointer(hFile
, 2048 * 16 + 318, NULL
, FILE_BEGIN
);
1051 bRet
[n
++] = ReadFile(hFile
, ids
->PulisherId
, 128, &dwSize
, NULL
);
1053 SetFilePointer(hFile
, 2048 * 16 + 446, NULL
, FILE_BEGIN
);
1054 bRet
[n
++] = ReadFile(hFile
, ids
->PreparerId
, 128, &dwSize
, NULL
);
1059 for (i
= 0; i
< n
; i
++)
1061 if (bRet
[i
] == FALSE
)
1068 TrimString(ids
->SystemId
, FALSE
);
1069 TrimString(ids
->VolumeId
, FALSE
);
1070 TrimString(ids
->PulisherId
, FALSE
);
1071 TrimString(ids
->PreparerId
, FALSE
);
1073 Log("ISO ID: System<%s> Volume<%s> Pulisher<%s> Preparer<%s>",
1074 ids
->SystemId
, ids
->VolumeId
, ids
->PulisherId
, ids
->PreparerId
);
1079 static int CheckSkipMountIso(CONST CHAR
*IsoPath
)
1081 BOOL InRoot
= FALSE
;
1083 CONST CHAR
*p
= NULL
;
1087 for (p
= IsoPath
; *p
; p
++)
1089 if (*p
== '\\' || *p
== '/')
1100 memset(&ID
, 0, sizeof(ID
));
1101 if (GetIsoId(IsoPath
, &ID
))
1106 //Bob.Ombs.Modified.Win10PEx64.iso will auto find ISO file in root, so we can skip the mount
1107 if (InRoot
&& strcmp(ID
.VolumeId
, "Modified-Win10PEx64") == 0)
1115 static int MountIsoFile(CONST CHAR
*IsoPath
, DWORD PhyDrive
)
1117 if (CheckSkipMountIso(IsoPath
))
1119 Log("Skip mount ISO file for <%s>", IsoPath
);
1123 if (IsWindows8OrGreater())
1125 Log("This is Windows 8 or latter...");
1126 if (VentoyMountISOByAPI(IsoPath
) == 0)
1128 Log("Mount iso by API success");
1133 Log("Mount iso by API failed, maybe not supported, try imdisk");
1134 return VentoyMountISOByImdisk(IsoPath
, PhyDrive
);
1139 Log("This is before Windows 8 ...");
1140 if (VentoyMountISOByImdisk(IsoPath
, PhyDrive
) == 0)
1142 Log("Mount iso by imdisk success");
1147 return VentoyMountISOByAPI(IsoPath
);
1152 static int GetPhyDriveByLogicalDrive(int DriveLetter
)
1157 VOLUME_DISK_EXTENTS DiskExtents
;
1160 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\%C:", (CHAR
)DriveLetter
);
1162 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
1163 if (Handle
== INVALID_HANDLE_VALUE
)
1165 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
1169 Ret
= DeviceIoControl(Handle
,
1170 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
1174 (DWORD
)(sizeof(DiskExtents
)),
1178 if (!Ret
|| DiskExtents
.NumberOfDiskExtents
== 0)
1180 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath
, GetLastError());
1181 SAFE_CLOSE_HANDLE(Handle
);
1184 SAFE_CLOSE_HANDLE(Handle
);
1186 Log("LogicalDrive:%s PhyDrive:%d Offset:%llu ExtentLength:%llu",
1188 DiskExtents
.Extents
[0].DiskNumber
,
1189 DiskExtents
.Extents
[0].StartingOffset
.QuadPart
,
1190 DiskExtents
.Extents
[0].ExtentLength
.QuadPart
1193 return (int)DiskExtents
.Extents
[0].DiskNumber
;
1197 static int DeleteVentoyPart2MountPoint(DWORD PhyDrive
)
1202 CHAR DriveName
[] = "?:\\";
1204 Log("DeleteVentoyPart2MountPoint Phy%u ...", PhyDrive
);
1206 Drives
= GetLogicalDrives();
1209 if ((Drives
& 0x01) && IsFileExist("%C:\\ventoy\\ventoy.cpio", Letter
))
1211 Log("File %C:\\ventoy\\ventoy.cpio exist", Letter
);
1213 PhyDisk
= GetPhyDriveByLogicalDrive(Letter
);
1214 Log("PhyDisk=%u for %C", PhyDisk
, Letter
);
1216 if (PhyDisk
== PhyDrive
)
1218 DriveName
[0] = Letter
;
1219 DeleteVolumeMountPointA(DriveName
);
1231 static BOOL
check_tar_archive(const char *archive
, CHAR
*tarName
)
1235 const char *pos
= archive
;
1236 const char *slash
= archive
;
1240 if (*pos
== '\\' || *pos
== '/')
1247 len
= (int)strlen(slash
);
1249 if (len
> 7 && (strncmp(slash
+ len
- 7, ".tar.gz", 7) == 0 || strncmp(slash
+ len
- 7, ".tar.xz", 7) == 0))
1251 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
1252 tarName
[nameLen
- 3] = 0;
1255 else if (len
> 8 && strncmp(slash
+ len
- 8, ".tar.bz2", 8) == 0)
1257 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
1258 tarName
[nameLen
- 4] = 0;
1261 else if (len
> 9 && strncmp(slash
+ len
- 9, ".tar.lzma", 9) == 0)
1263 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
1264 tarName
[nameLen
- 5] = 0;
1271 static UCHAR
*g_unxz_buffer
= NULL
;
1272 static int g_unxz_len
= 0;
1274 static void unxz_error(char *x
)
1279 static int unxz_flush(void *src
, unsigned int size
)
1281 memcpy(g_unxz_buffer
+ g_unxz_len
, src
, size
);
1282 g_unxz_len
+= (int)size
;
1287 static int DecompressInjectionArchive(const char *archive
, DWORD PhyDrive
)
1291 UCHAR
*Buffer
= NULL
;
1292 UCHAR
*RawBuffer
= NULL
;
1298 DWORD flags
= CREATE_NO_WINDOW
;
1299 CHAR StrBuf
[MAX_PATH
];
1300 CHAR tarName
[MAX_PATH
];
1302 PROCESS_INFORMATION Pi
;
1303 PROCESS_INFORMATION NewPi
;
1304 GET_LENGTH_INFORMATION LengthInfo
;
1305 SECURITY_ATTRIBUTES Sa
= { sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
1307 Log("DecompressInjectionArchive %s", archive
);
1309 sprintf_s(StrBuf
, sizeof(StrBuf
), "\\\\.\\PhysicalDrive%d", PhyDrive
);
1310 hDrive
= CreateFileA(StrBuf
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
1311 if (hDrive
== INVALID_HANDLE_VALUE
)
1313 Log("Could not open the disk<%s>, error:%u", StrBuf
, GetLastError());
1317 bRet
= DeviceIoControl(hDrive
, IOCTL_DISK_GET_LENGTH_INFO
, NULL
, 0, &LengthInfo
, sizeof(LengthInfo
), &dwBytes
, NULL
);
1320 Log("Could not get phy disk %s size, error:%u", StrBuf
, GetLastError());
1324 g_FatPhyDrive
= hDrive
;
1325 g_Part2StartSec
= GetVentoyEfiPartStartSector(hDrive
);
1327 Log("Parse FAT fs...");
1331 if (0 == fl_attach_media(VentoyFatDiskRead
, NULL
))
1333 if (g_system_bit
== 64)
1335 CopyFileFromFatDisk("/ventoy/7z/64/7za.xz", "ventoy\\7za.xz");
1339 CopyFileFromFatDisk("/ventoy/7z/32/7za.xz", "ventoy\\7za.xz");
1342 ReadWholeFile2Buf("ventoy\\7za.xz", &Buffer
, &dwSize
);
1343 Log("7za.xz file size:%u", dwSize
);
1345 RawBuffer
= malloc(SIZE_1MB
* 4);
1348 g_unxz_buffer
= RawBuffer
;
1350 unxz(Buffer
, (int)dwSize
, NULL
, unxz_flush
, NULL
, &writelen
, unxz_error
);
1351 if (writelen
== (int)dwSize
)
1353 Log("Decompress success 7za.xz(%u) ---> 7za.exe(%d)", dwSize
, g_unxz_len
);
1357 Log("Decompress failed 7za.xz(%u) ---> 7za.exe(%u)", dwSize
, dwSize
);
1360 SaveBuffer2File("ventoy\\7za.exe", RawBuffer
, (DWORD
)g_unxz_len
);
1362 g_unxz_buffer
= NULL
;
1368 Log("Failed to alloc 4MB memory");
1371 sprintf_s(StrBuf
, sizeof(StrBuf
), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", archive
);
1373 Log("extract inject to X:");
1374 Log("cmdline:<%s>", StrBuf
);
1376 GetStartupInfoA(&Si
);
1378 hOut
= CreateFileA("ventoy\\7z.log",
1380 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
1383 FILE_ATTRIBUTE_NORMAL
,
1386 Si
.dwFlags
|= STARTF_USESTDHANDLES
;
1388 if (hOut
!= INVALID_HANDLE_VALUE
)
1390 Si
.hStdError
= hOut
;
1391 Si
.hStdOutput
= hOut
;
1394 CreateProcessA(NULL
, StrBuf
, NULL
, NULL
, TRUE
, flags
, NULL
, NULL
, &Si
, &Pi
);
1395 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
1398 // decompress tar archive, for tar.gz/tar.xz/tar.bz2
1400 if (check_tar_archive(archive
, tarName
))
1402 Log("Decompress tar archive...<%s>", tarName
);
1404 sprintf_s(StrBuf
, sizeof(StrBuf
), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", tarName
);
1406 CreateProcessA(NULL
, StrBuf
, NULL
, NULL
, TRUE
, flags
, NULL
, NULL
, &Si
, &NewPi
);
1407 WaitForSingleObject(NewPi
.hProcess
, INFINITE
);
1409 Log("Now delete %s", tarName
);
1410 DeleteFileA(tarName
);
1413 SAFE_CLOSE_HANDLE(hOut
);
1419 SAFE_CLOSE_HANDLE(hDrive
);
1424 static int UnattendNeedVarExpand(const char *script
)
1429 fopen_s(&fp
, script
, "r");
1435 szLine
[0] = szLine
[4095] = 0;
1437 while (fgets(szLine
, sizeof(szLine
) - 1, fp
))
1439 if (strstr(szLine
, "$$VT_"))
1445 szLine
[0] = szLine
[4095] = 0;
1452 static int ExpandSingleVar(VarDiskInfo
*pDiskInfo
, int DiskNum
, const char *var
, char *value
, int len
)
1458 UINT64 uiMaxSize
= 0;
1459 UINT64 uiMaxDelta
= ULLONG_MAX
;
1463 if (strcmp(var
, "VT_WINDOWS_DISK_1ST_NONVTOY") == 0)
1465 for (i
= 0; i
< DiskNum
; i
++)
1467 if (pDiskInfo
[i
].Capacity
> 0 && i
!= g_vtoy_disk_drive
)
1469 Log("%s=<PhyDrive%d>", var
, i
);
1470 sprintf_s(value
, len
, "%d", i
);
1475 else if (strcmp(var
, "VT_WINDOWS_DISK_1ST_NONUSB") == 0)
1477 for (i
= 0; i
< DiskNum
; i
++)
1479 if (pDiskInfo
[i
].Capacity
> 0 && pDiskInfo
[i
].BusType
!= BusTypeUsb
)
1481 Log("%s=<PhyDrive%d>", var
, i
);
1482 sprintf_s(value
, len
, "%d", i
);
1487 else if (strcmp(var
, "VT_WINDOWS_DISK_MAX_SIZE") == 0)
1489 for (i
= 0; i
< DiskNum
; i
++)
1491 if (pDiskInfo
[i
].Capacity
> 0 && pDiskInfo
[i
].Capacity
> uiMaxSize
)
1494 uiMaxSize
= pDiskInfo
[i
].Capacity
;
1498 Log("%s=<PhyDrive%d>", var
, index
);
1499 sprintf_s(value
, len
, "%d", index
);
1501 else if (strncmp(var
, "VT_WINDOWS_DISK_CLOSEST_", 24) == 0)
1503 uiDst
= strtoul(var
+ 24, NULL
, 10);
1504 uiDst
= uiDst
* (1024ULL * 1024ULL * 1024ULL);
1506 for (i
= 0; i
< DiskNum
; i
++)
1508 if (pDiskInfo
[i
].Capacity
== 0)
1513 if (pDiskInfo
[i
].Capacity
> uiDst
)
1515 uiDelta
= pDiskInfo
[i
].Capacity
- uiDst
;
1519 uiDelta
= uiDst
- pDiskInfo
[i
].Capacity
;
1522 if (uiDelta
< uiMaxDelta
)
1524 uiMaxDelta
= uiDelta
;
1529 Log("%s=<PhyDrive%d>", var
, index
);
1530 sprintf_s(value
, len
, "%d", index
);
1534 Log("Invalid var name <%s>", var
);
1535 sprintf_s(value
, len
, "$$%s$$", var
);
1540 sprintf_s(value
, len
, "$$%s$$", var
);
1546 static int GetRegDwordValue(HKEY Key
, LPCSTR SubKey
, LPCSTR ValueName
, DWORD
*pValue
)
1554 lRet
= RegOpenKeyExA(Key
, SubKey
, 0, KEY_QUERY_VALUE
, &hKey
);
1555 Log("RegOpenKeyExA <%s> Ret:%ld", SubKey
, lRet
);
1557 if (ERROR_SUCCESS
== lRet
)
1559 Size
= sizeof(Value
);
1560 lRet
= RegQueryValueExA(hKey
, ValueName
, NULL
, &Type
, (LPBYTE
)&Value
, &Size
);
1561 Log("RegQueryValueExA <%s> ret:%u Size:%u Value:%u", ValueName
, lRet
, Size
, Value
);
1574 static const CHAR
* GetBusTypeString(int Type
)
1578 case BusTypeUnknown
: return "unknown";
1579 case BusTypeScsi
: return "SCSI";
1580 case BusTypeAtapi
: return "Atapi";
1581 case BusTypeAta
: return "ATA";
1582 case BusType1394
: return "1394";
1583 case BusTypeSsa
: return "SSA";
1584 case BusTypeFibre
: return "Fibre";
1585 case BusTypeUsb
: return "USB";
1586 case BusTypeRAID
: return "RAID";
1587 case BusTypeiScsi
: return "iSCSI";
1588 case BusTypeSas
: return "SAS";
1589 case BusTypeSata
: return "SATA";
1590 case BusTypeSd
: return "SD";
1591 case BusTypeMmc
: return "MMC";
1592 case BusTypeVirtual
: return "Virtual";
1593 case BusTypeFileBackedVirtual
: return "FileBackedVirtual";
1594 case BusTypeSpaces
: return "Spaces";
1595 case BusTypeNvme
: return "Nvme";
1600 static int GetHumanReadableGBSize(UINT64 SizeBytes
)
1605 double GB
= SizeBytes
* 1.0 / 1000 / 1000 / 1000;
1607 if ((SizeBytes
% 1073741824) == 0)
1609 return (int)(SizeBytes
/ 1073741824);
1612 for (i
= 0; i
< 12; i
++)
1616 Delta
= (Pow2
- GB
) / Pow2
;
1620 Delta
= (GB
- Pow2
) / Pow2
;
1634 static int EnumerateAllDisk(VarDiskInfo
**ppDiskInfo
, int *pDiskNum
)
1641 VarDiskInfo
*pDiskInfo
= NULL
;
1642 HANDLE Handle
= INVALID_HANDLE_VALUE
;
1644 GET_LENGTH_INFORMATION LengthInfo
;
1645 STORAGE_PROPERTY_QUERY Query
;
1646 STORAGE_DESCRIPTOR_HEADER DevDescHeader
;
1647 STORAGE_DEVICE_DESCRIPTOR
*pDevDesc
;
1649 if (GetRegDwordValue(HKEY_LOCAL_MACHINE
, "SYSTEM\\CurrentControlSet\\Services\\disk\\Enum", "Count", &Value
) == 0)
1651 DiskNum
= (int)Value
;
1655 Log("Failed to read disk count");
1659 Log("Current phy disk count:%d", DiskNum
);
1665 pDiskInfo
= malloc(DiskNum
* sizeof(VarDiskInfo
));
1668 Log("Failed to alloc");
1671 memset(pDiskInfo
, 0, DiskNum
* sizeof(VarDiskInfo
));
1673 for (i
= 0; i
< DiskNum
; i
++)
1675 SAFE_CLOSE_HANDLE(Handle
);
1677 safe_sprintf(PhyDrive
, "\\\\.\\PhysicalDrive%d", i
);
1678 Handle
= CreateFileA(PhyDrive
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, NULL
);
1679 Log("Create file Handle:%p %s status:%u", Handle
, PhyDrive
, LASTERR
);
1681 if (Handle
== INVALID_HANDLE_VALUE
)
1686 bRet
= DeviceIoControl(Handle
,
1687 IOCTL_DISK_GET_LENGTH_INFO
, NULL
,
1695 Log("DeviceIoControl IOCTL_DISK_GET_LENGTH_INFO failed error:%u", LASTERR
);
1699 Log("PHYSICALDRIVE%d size %llu bytes", i
, (ULONGLONG
)LengthInfo
.Length
.QuadPart
);
1701 Query
.PropertyId
= StorageDeviceProperty
;
1702 Query
.QueryType
= PropertyStandardQuery
;
1704 bRet
= DeviceIoControl(Handle
,
1705 IOCTL_STORAGE_QUERY_PROPERTY
,
1709 sizeof(STORAGE_DESCRIPTOR_HEADER
),
1714 Log("DeviceIoControl1 error:%u dwBytes:%u", LASTERR
, dwBytes
);
1718 if (DevDescHeader
.Size
< sizeof(STORAGE_DEVICE_DESCRIPTOR
))
1720 Log("Invalid DevDescHeader.Size:%u", DevDescHeader
.Size
);
1724 pDevDesc
= (STORAGE_DEVICE_DESCRIPTOR
*)malloc(DevDescHeader
.Size
);
1727 Log("failed to malloc error:%u len:%u", LASTERR
, DevDescHeader
.Size
);
1731 bRet
= DeviceIoControl(Handle
,
1732 IOCTL_STORAGE_QUERY_PROPERTY
,
1741 Log("DeviceIoControl2 error:%u dwBytes:%u", LASTERR
, dwBytes
);
1746 pDiskInfo
[i
].RemovableMedia
= pDevDesc
->RemovableMedia
;
1747 pDiskInfo
[i
].BusType
= pDevDesc
->BusType
;
1748 pDiskInfo
[i
].DeviceType
= pDevDesc
->DeviceType
;
1749 pDiskInfo
[i
].Capacity
= LengthInfo
.Length
.QuadPart
;
1751 if (pDevDesc
->VendorIdOffset
)
1753 safe_strcpy(pDiskInfo
[i
].VendorId
, (char *)pDevDesc
+ pDevDesc
->VendorIdOffset
);
1754 TrimString(pDiskInfo
[i
].VendorId
, TRUE
);
1757 if (pDevDesc
->ProductIdOffset
)
1759 safe_strcpy(pDiskInfo
[i
].ProductId
, (char *)pDevDesc
+ pDevDesc
->ProductIdOffset
);
1760 TrimString(pDiskInfo
[i
].ProductId
, TRUE
);
1763 if (pDevDesc
->ProductRevisionOffset
)
1765 safe_strcpy(pDiskInfo
[i
].ProductRev
, (char *)pDevDesc
+ pDevDesc
->ProductRevisionOffset
);
1766 TrimString(pDiskInfo
[i
].ProductRev
, TRUE
);
1769 if (pDevDesc
->SerialNumberOffset
)
1771 safe_strcpy(pDiskInfo
[i
].SerialNumber
, (char *)pDevDesc
+ pDevDesc
->SerialNumberOffset
);
1772 TrimString(pDiskInfo
[i
].SerialNumber
, TRUE
);
1776 SAFE_CLOSE_HANDLE(Handle
);
1779 Log("########## DUMP DISK BEGIN ##########");
1780 for (i
= 0; i
< DiskNum
; i
++)
1782 Log("PhyDrv:%d BusType:%-4s Removable:%u Size:%dGB(%llu) Name:%s %s",
1783 i
, GetBusTypeString(pDiskInfo
[i
].BusType
), pDiskInfo
[i
].RemovableMedia
,
1784 GetHumanReadableGBSize(pDiskInfo
[i
].Capacity
), pDiskInfo
[i
].Capacity
,
1785 pDiskInfo
[i
].VendorId
, pDiskInfo
[i
].ProductId
);
1787 Log("Ventoy disk is PhyDvr%d", g_vtoy_disk_drive
);
1788 Log("########## DUMP DISK END ##########");
1790 *ppDiskInfo
= pDiskInfo
;
1791 *pDiskNum
= DiskNum
;
1795 static int UnattendVarExpand(const char *script
, const char *tmpfile
)
1804 VarDiskInfo
*pDiskInfo
= NULL
;
1806 Log("UnattendVarExpand ...");
1808 if (EnumerateAllDisk(&pDiskInfo
, &DiskNum
))
1810 Log("Failed to EnumerateAllDisk");
1814 fopen_s(&fp
, script
, "r");
1821 fopen_s(&fout
, tmpfile
, "w+");
1829 szLine
[0] = szLine
[4095] = 0;
1831 while (fgets(szLine
, sizeof(szLine
) - 1, fp
))
1833 start
= strstr(szLine
, "$$VT_");
1836 end
= strstr(start
+ 5, "$$");
1842 fprintf(fout
, "%s", szLine
);
1845 ExpandSingleVar(pDiskInfo
, DiskNum
, start
+ 2, szValue
, sizeof(szValue
) - 1);
1846 fprintf(fout
, "%s", szValue
);
1848 fprintf(fout
, "%s", end
+ 2);
1852 fprintf(fout
, "%s", szLine
);
1855 szLine
[0] = szLine
[4095] = 0;
1864 //#define VAR_DEBUG 1
1866 static int ProcessUnattendedInstallation(const char *script
)
1872 CHAR TmpFile
[MAX_PATH
];
1873 CHAR CurDir
[MAX_PATH
];
1875 Log("Copy unattended XML ...");
1877 GetCurrentDirectory(sizeof(CurDir
), CurDir
);
1879 if ((Letter
>= 'A' && Letter
<= 'Z') || (Letter
>= 'a' && Letter
<= 'z'))
1881 Log("Current Drive Letter: %C", Letter
);
1889 sprintf_s(CurDir
, sizeof(CurDir
), "%C:\\AutounattendXXX.xml", Letter
);
1891 sprintf_s(CurDir
, sizeof(CurDir
), "%C:\\Autounattend.xml", Letter
);
1894 if (UnattendNeedVarExpand(script
))
1896 sprintf_s(TmpFile
, sizeof(TmpFile
), "%C:\\__Autounattend", Letter
);
1897 UnattendVarExpand(script
, TmpFile
);
1899 Log("Expand Copy file <%s> --> <%s>", script
, CurDir
);
1900 CopyFile(TmpFile
, CurDir
, FALSE
);
1904 Log("No var expand copy file <%s> --> <%s>", script
, CurDir
);
1905 CopyFile(script
, CurDir
, FALSE
);
1909 Ret
= RegCreateKeyEx(HKEY_LOCAL_MACHINE
, "System\\Setup", 0, NULL
, REG_OPTION_NON_VOLATILE
, KEY_ALL_ACCESS
, NULL
, &hKey
, &dw
);
1910 if (ERROR_SUCCESS
== Ret
)
1912 Ret
= RegSetValueEx(hKey
, "UnattendFile", 0, REG_SZ
, CurDir
, (DWORD
)(strlen(CurDir
) + 1));
1919 static int Windows11BypassCheck(const char *isofile
, const char MntLetter
)
1926 CHAR
*Buffer
= NULL
;
1927 VS_FIXEDFILEINFO
* VerInfo
= NULL
;
1928 CHAR CheckFile
[MAX_PATH
];
1929 UINT16 Major
, Minor
, Build
, Revision
;
1931 Log("Windows11BypassCheck for <%s> %C:", isofile
, MntLetter
);
1933 if (FALSE
== IsFileExist("%C:\\sources\\boot.wim", MntLetter
) ||
1934 FALSE
== IsFileExist("%C:\\sources\\compatresources.dll", MntLetter
))
1936 Log("boot.wim/compatresources.dll not exist, this is not a windows install media.");
1940 if (FALSE
== IsFileExist("%C:\\sources\\install.wim", MntLetter
) &&
1941 FALSE
== IsFileExist("%C:\\sources\\install.esd", MntLetter
))
1943 Log("install.wim/install.esd not exist, this is not a windows install media.");
1947 sprintf_s(CheckFile
, sizeof(CheckFile
), "%C:\\sources\\compatresources.dll", MntLetter
);
1948 dwSize
= GetFileVersionInfoSizeA(CheckFile
, &dwHandle
);
1951 Log("Failed to get file version info size: %u", LASTERR
);
1955 Buffer
= malloc(dwSize
);
1961 if (FALSE
== GetFileVersionInfoA(CheckFile
, dwHandle
, dwSize
, Buffer
))
1963 Log("Failed to get file version info : %u", LASTERR
);
1967 if (VerQueryValueA(Buffer
, "\\", (LPVOID
)&VerInfo
, &VerLen
) && VerLen
!= 0)
1969 if (VerInfo
->dwSignature
== VS_FFI_SIGNATURE
)
1971 Major
= HIWORD(VerInfo
->dwFileVersionMS
);
1972 Minor
= LOWORD(VerInfo
->dwFileVersionMS
);
1973 Build
= HIWORD(VerInfo
->dwFileVersionLS
);
1974 Revision
= LOWORD(VerInfo
->dwFileVersionLS
);
1976 Log("FileVersionze: <%u %u %u %u>", Major
, Minor
, Build
, Revision
);
1978 if (Major
== 10 && Build
> 20000)
1985 Log("This is not Windows 11, not need to bypass.", Major
);
1991 //Now we really need to bypass windows 11 check. create registry
1993 HKEY hSubKey
= NULL
;
1996 Status
= RegCreateKeyExA(HKEY_LOCAL_MACHINE
, "System\\Setup", 0, NULL
, REG_OPTION_NON_VOLATILE
, KEY_ALL_ACCESS
, NULL
, &hKey
, &dwSize
);
1997 if (ERROR_SUCCESS
!= Status
)
1999 Log("Failed to create reg key System\\Setup %u %u", LASTERR
, Status
);
2003 Status
= RegCreateKeyExA(hKey
, "LabConfig", 0, NULL
, 0, KEY_SET_VALUE
| KEY_QUERY_VALUE
| KEY_CREATE_SUB_KEY
, NULL
, &hSubKey
, &dwSize
);
2004 if (ERROR_SUCCESS
!= Status
)
2006 Log("Failed to create LabConfig reg %u %u", LASTERR
, Status
);
2011 Status
+= RegSetValueExA(hSubKey
, "BypassRAMCheck", 0, REG_DWORD
, (LPBYTE
)&dwValue
, sizeof(DWORD
));
2012 Status
+= RegSetValueExA(hSubKey
, "BypassTPMCheck", 0, REG_DWORD
, (LPBYTE
)&dwValue
, sizeof(DWORD
));
2013 Status
+= RegSetValueExA(hSubKey
, "BypassSecureBootCheck", 0, REG_DWORD
, (LPBYTE
)&dwValue
, sizeof(DWORD
));
2014 Status
+= RegSetValueExA(hSubKey
, "BypassStorageCheck", 0, REG_DWORD
, (LPBYTE
)&dwValue
, sizeof(DWORD
));
2015 Status
+= RegSetValueExA(hSubKey
, "BypassCPUCheck", 0, REG_DWORD
, (LPBYTE
)&dwValue
, sizeof(DWORD
));
2017 Log("Create bypass registry %s %u", (Status
== ERROR_SUCCESS
) ? "SUCCESS" : "FAILED", Status
);
2030 static BOOL
CheckVentoyDisk(DWORD DiskNum
)
2034 UINT8 SectorBuf
[512];
2036 UINT8 check
[8] = { 0x56, 0x54, 0x00, 0x47, 0x65, 0x00, 0x48, 0x44 };
2038 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\PhysicalDrive%d", DiskNum
);
2039 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
2040 if (Handle
== INVALID_HANDLE_VALUE
)
2042 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
2046 if (!ReadFile(Handle
, SectorBuf
, sizeof(SectorBuf
), &dwSize
, NULL
))
2048 Log("ReadFile failed, dwSize:%u error:%u", dwSize
, GetLastError());
2049 CloseHandle(Handle
);
2053 CloseHandle(Handle
);
2055 if (memcmp(SectorBuf
+ 0x190, check
, 8) == 0)
2064 static int VentoyHook(ventoy_os_param
*param
)
2069 BOOL vtoyfind
= FALSE
;
2078 DISK_EXTENT DiskExtent
;
2079 DISK_EXTENT VtoyDiskExtent
;
2081 CHAR IsoPath
[MAX_PATH
];
2083 Log("VentoyHook Path:<%s>", param
->vtoy_img_path
);
2085 if (IsUTF8Encode(param
->vtoy_img_path
))
2087 Log("This file is UTF8 encoding");
2090 for (i
= 0; i
< 5; i
++)
2093 Drives
= GetLogicalDrives();
2094 Log("Logic Drives: 0x%x", Drives
);
2100 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:\\%s", Letter
, param
->vtoy_img_path
);
2101 if (IsFileExist("%s", IsoPath
))
2103 Log("File exist under %C:", Letter
);
2104 memset(UUID
, 0, sizeof(UUID
));
2105 memset(&DiskExtent
, 0, sizeof(DiskExtent
));
2106 if (GetPhyDiskUUID(Letter
, UUID
, NULL
, &DiskExtent
) == 0)
2108 if (memcmp(UUID
, param
->vtoy_disk_guid
, 16) == 0)
2110 Log("Disk UUID match");
2118 Log("File NOT exist under %C:", Letter
);
2132 Log("Now wait and retry ...");
2139 Log("Failed to find ISO file");
2143 Log("Find ISO file <%s>", IsoPath
);
2145 //Find VtoyLetter in Vlnk Mode
2146 if (g_os_param_reserved
[6] == 1)
2148 memcpy(&VtoySig
, g_os_param_reserved
+ 7, 4);
2149 for (i
= 0; i
< 5; i
++)
2152 Drives
= GetLogicalDrives();
2153 Log("Logic Drives: 0x%x VentoySig:%08X", Drives
, VtoySig
);
2159 memset(UUID
, 0, sizeof(UUID
));
2160 memset(&VtoyDiskExtent
, 0, sizeof(VtoyDiskExtent
));
2162 if (GetPhyDiskUUID(VtoyLetter
, UUID
, &DiskSig
, &VtoyDiskExtent
) == 0)
2164 Log("DiskSig=%08X PartStart=%lld", DiskSig
, VtoyDiskExtent
.StartingOffset
.QuadPart
);
2165 if (DiskSig
== VtoySig
&& VtoyDiskExtent
.StartingOffset
.QuadPart
== SIZE_1MB
)
2167 Log("Ventoy Disk Sig match");
2180 Log("Find Ventoy Letter: %C", VtoyLetter
);
2185 Log("Now wait and retry ...");
2190 if (vtoyfind
== FALSE
)
2192 Log("Failed to find ventoy disk");
2196 VtoyDiskNum
= VtoyDiskExtent
.DiskNumber
;
2200 VtoyLetter
= Letter
;
2201 Log("No vlnk mode %C", Letter
);
2203 VtoyDiskNum
= DiskExtent
.DiskNumber
;
2206 if (CheckVentoyDisk(VtoyDiskNum
))
2208 Log("Disk check OK %C: %u", VtoyLetter
, VtoyDiskNum
);
2212 Log("Failed to check ventoy disk %u", VtoyDiskNum
);
2216 g_vtoy_disk_drive
= VtoyDiskNum
;
2218 Drives
= GetLogicalDrives();
2219 Log("Drives before mount: 0x%x", Drives
);
2221 rc
= MountIsoFile(IsoPath
, VtoyDiskNum
);
2223 NewDrives
= GetLogicalDrives();
2224 Log("Drives after mount: 0x%x (0x%x)", NewDrives
, (NewDrives
^ Drives
));
2227 NewDrives
= (NewDrives
^ Drives
);
2230 if (NewDrives
& 0x01)
2232 if ((NewDrives
>> 1) == 0)
2234 Log("The ISO file is mounted at %C:", MntLetter
);
2238 Log("Maybe the ISO file is mounted at %C:", MntLetter
);
2247 Log("Mount ISO FILE: %s", rc
== 0 ? "SUCCESS" : "FAILED");
2249 //Windows 11 bypass check
2250 if (g_windows_data
.windows11_bypass_check
== 1)
2252 Windows11BypassCheck(IsoPath
, MntLetter
);
2256 rc
= DeleteVentoyPart2MountPoint(VtoyDiskNum
);
2257 Log("Delete ventoy mountpoint: %s", rc
== 0 ? "SUCCESS" : "NO NEED");
2259 if (g_windows_data
.auto_install_script
[0])
2261 if (IsFileExist("%s", VTOY_AUTO_FILE
))
2263 Log("use auto install script %s...", VTOY_AUTO_FILE
);
2264 ProcessUnattendedInstallation(VTOY_AUTO_FILE
);
2268 Log("auto install script %s not exist", IsoPath
);
2273 Log("auto install no need");
2276 if (g_windows_data
.injection_archive
[0])
2278 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:%s", VtoyLetter
, g_windows_data
.injection_archive
);
2279 if (IsFileExist("%s", IsoPath
))
2281 Log("decompress injection archive %s...", IsoPath
);
2282 DecompressInjectionArchive(IsoPath
, VtoyDiskNum
);
2284 if (IsFileExist("%s", AUTO_RUN_BAT
))
2287 DWORD flags
= CREATE_NO_WINDOW
;
2290 PROCESS_INFORMATION Pi
;
2291 SECURITY_ATTRIBUTES Sa
= { sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
2293 Log("%s exist, now run it...", AUTO_RUN_BAT
);
2295 GetStartupInfoA(&Si
);
2297 hOut
= CreateFileA(AUTO_RUN_LOG
,
2299 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
2302 FILE_ATTRIBUTE_NORMAL
,
2305 Si
.dwFlags
|= STARTF_USESTDHANDLES
;
2306 if (hOut
!= INVALID_HANDLE_VALUE
)
2308 Si
.hStdError
= hOut
;
2309 Si
.hStdOutput
= hOut
;
2312 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:\\%s", Letter
, param
->vtoy_img_path
);
2313 sprintf_s(StrBuf
, sizeof(StrBuf
), "cmd.exe /c %s \"%s\" %C", AUTO_RUN_BAT
, IsoPath
, MntLetter
);
2314 CreateProcessA(NULL
, StrBuf
, NULL
, NULL
, TRUE
, flags
, NULL
, NULL
, &Si
, &Pi
);
2315 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
2317 SAFE_CLOSE_HANDLE(hOut
);
2321 Log("%s not exist...", AUTO_RUN_BAT
);
2326 Log("injection archive %s not exist", IsoPath
);
2331 Log("no injection archive found");
2337 static int ExtractWindowsDataFile(char *databuf
)
2340 char *filedata
= NULL
;
2341 ventoy_windows_data
*pdata
= (ventoy_windows_data
*)databuf
;
2343 Log("ExtractWindowsDataFile: auto install <%s:%d>", pdata
->auto_install_script
, pdata
->auto_install_len
);
2345 filedata
= databuf
+ sizeof(ventoy_windows_data
);
2347 if (pdata
->auto_install_script
[0] && pdata
->auto_install_len
> 0)
2349 SaveBuffer2File(VTOY_AUTO_FILE
, filedata
, pdata
->auto_install_len
);
2350 filedata
+= pdata
->auto_install_len
;
2351 len
= pdata
->auto_install_len
;
2357 static int ventoy_check_create_directory(void)
2359 if (IsDirExist("ventoy"))
2361 Log("ventoy directory already exist");
2365 Log("ventoy directory not exist, now create it.");
2366 if (!CreateDirectoryA("ventoy", NULL
))
2368 Log("Failed to create ventoy directory err:%u", GetLastError());
2376 int VentoyJump(INT argc
, CHAR
**argv
, CHAR
*LunchFile
)
2384 DWORD LockStatus
= 0;
2385 BYTE
*Buffer
= NULL
;
2386 CHAR ExeFileName
[MAX_PATH
];
2388 sprintf_s(ExeFileName
, sizeof(ExeFileName
), "%s", argv
[0]);
2389 if (!IsFileExist("%s", ExeFileName
))
2391 Log("File %s NOT exist, now try %s.exe", ExeFileName
, ExeFileName
);
2392 sprintf_s(ExeFileName
, sizeof(ExeFileName
), "%s.exe", argv
[0]);
2394 Log("File %s exist ? %s", ExeFileName
, IsFileExist("%s", ExeFileName
) ? "YES" : "NO");
2397 if (ReadWholeFile2Buf(ExeFileName
, (void **)&Buffer
, &FileSize
))
2402 Log("VentoyJump %dbit", g_system_bit
);
2404 MUTEX_LOCK(g_vtoyins_mutex
);
2405 stat
= ventoy_check_create_directory();
2406 MUTEX_UNLOCK(g_vtoyins_mutex
);
2413 for (PeStart
= 0; PeStart
< FileSize
; PeStart
+= 16)
2415 if (CheckOsParam((ventoy_os_param
*)(Buffer
+ PeStart
)) &&
2416 CheckPeHead(Buffer
, FileSize
, PeStart
+ sizeof(ventoy_os_param
)))
2418 Log("Find os pararm at %u", PeStart
);
2420 memcpy(&g_os_param
, Buffer
+ PeStart
, sizeof(ventoy_os_param
));
2421 memcpy(&g_windows_data
, Buffer
+ PeStart
+ sizeof(ventoy_os_param
), sizeof(ventoy_windows_data
));
2422 exlen
= ExtractWindowsDataFile(Buffer
+ PeStart
+ sizeof(ventoy_os_param
));
2423 memcpy(g_os_param_reserved
, g_os_param
.vtoy_reserved
, sizeof(g_os_param_reserved
));
2425 if (g_os_param_reserved
[0] == 1)
2427 Log("break here for debug .....");
2432 for (Pos
= 0; Pos
< sizeof(g_os_param
.vtoy_img_path
) && g_os_param
.vtoy_img_path
[Pos
]; Pos
++)
2434 if (g_os_param
.vtoy_img_path
[Pos
] == '/')
2436 g_os_param
.vtoy_img_path
[Pos
] = '\\';
2440 PeStart
+= sizeof(ventoy_os_param
) + sizeof(ventoy_windows_data
) + exlen
;
2441 sprintf_s(LunchFile
, MAX_PATH
, "ventoy\\%s", GetFileNameInPath(ExeFileName
));
2443 MUTEX_LOCK(g_vtoyins_mutex
);
2444 if (IsFileExist("%s", LunchFile
))
2446 Log("vtoyjump multiple call ...");
2448 MUTEX_UNLOCK(g_vtoyins_mutex
);
2452 SaveBuffer2File(LunchFile
, Buffer
+ PeStart
, FileSize
- PeStart
);
2453 MUTEX_UNLOCK(g_vtoyins_mutex
);
2459 if (PeStart
>= FileSize
)
2461 Log("OS param not found");
2465 if (g_os_param_reserved
[0] == 2)
2467 Log("skip hook for debug .....");
2472 rc
= VentoyHook(&g_os_param
);
2485 static int vtoy_cmd_delete_file(char *File
)
2487 CHAR szCmd
[MAX_PATH
];
2489 PROCESS_INFORMATION Pi
;
2491 GetStartupInfoA(&Si
);
2492 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
2493 Si
.wShowWindow
= SW_HIDE
;
2494 sprintf_s(szCmd
, sizeof(szCmd
), "cmd.exe /c del /F /Q %s", File
);
2495 CreateProcessA(NULL
, szCmd
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
2496 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
2501 int real_main(int argc
, char **argv
)
2505 CHAR NewFile
[MAX_PATH
];
2506 CHAR LunchFile
[MAX_PATH
];
2507 CHAR CallParam
[1024] = { 0 };
2509 PROCESS_INFORMATION Pi
;
2511 Log("#### real_main #### argc = %d", argc
);
2512 Log("program full path: <%s>", g_prog_full_path
);
2513 Log("program dir: <%s>", g_prog_dir
);
2514 Log("program name: <%s>", g_prog_name
);
2516 Log("argc = %d", argc
);
2517 for (i
= 0; i
< argc
; i
++)
2519 Log("argv[%d]=<%s>", i
, argv
[i
]);
2522 strcat_s(CallParam
, sizeof(CallParam
), " ");
2523 strcat_s(CallParam
, sizeof(CallParam
), argv
[i
]);
2527 GetStartupInfoA(&Si
);
2528 memset(LunchFile
, 0, sizeof(LunchFile
));
2530 rc
= VentoyJump(argc
, argv
, LunchFile
);
2532 Log("LunchFile=<%s> CallParam=<%s>", LunchFile
, CallParam
);
2534 if (_stricmp(g_prog_name
, "winpeshl.exe") != 0 && IsFileExist("ventoy\\%s", g_prog_name
))
2536 sprintf_s(NewFile
, sizeof(NewFile
), "%s_BACK.EXE", g_prog_full_path
);
2537 MoveFileA(g_prog_full_path
, NewFile
);
2538 Log("Move <%s> to <%s>", g_prog_full_path
, NewFile
);
2540 sprintf_s(NewFile
, sizeof(NewFile
), "ventoy\\%s", g_prog_name
);
2541 CopyFileA(NewFile
, g_prog_full_path
, TRUE
);
2542 Log("Copy <%s> to <%s>", NewFile
, g_prog_full_path
);
2544 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", g_prog_full_path
);
2545 Log("Final lunchFile is <%s>", LunchFile
);
2549 Log("We don't need to recover original <%s>", g_prog_name
);
2552 if (g_os_param_reserved
[0] == 3)
2554 Log("Open log for debug ...");
2555 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", "notepad.exe ventoy.log");
2561 strcat_s(LunchFile
, sizeof(LunchFile
), CallParam
);
2563 else if (NULL
== strstr(LunchFile
, "setup.exe"))
2565 Log("Not setup.exe, hide windows.");
2566 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
2567 Si
.wShowWindow
= SW_HIDE
;
2570 Log("Ventoy jump %s ...", rc
== 0 ? "success" : "failed");
2573 Log("Now launch <%s> ...", LunchFile
);
2575 if (g_os_param_reserved
[0] == 4)
2577 Log("Open cmd for debug ...");
2578 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", "cmd.exe");
2581 if (IsFileExist(ORG_PECMD_BK_PATH
))
2583 Log("Delete backup file <%s>", ORG_PECMD_BK_PATH
);
2584 vtoy_cmd_delete_file(ORG_PECMD_BK_PATH
);
2587 Log("Backup log at this point");
2588 CopyFileA(LOG_FILE
, "X:\\Windows\\ventoy.backup", TRUE
);
2590 CreateProcessA(NULL
, LunchFile
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
2592 for (i
= 0; rc
&& i
< 1800; i
++)
2594 Log("Ventoy hook failed, now wait and retry ...");
2596 rc
= VentoyHook(&g_os_param
);
2599 Log("Wait process...");
2600 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
2602 Log("vtoyjump finished");
2606 static void VentoyToUpper(CHAR
*str
)
2609 for (i
= 0; str
[i
]; i
++)
2611 str
[i
] = (CHAR
)toupper(str
[i
]);
2615 static int vtoy_remove_duplicate_file(char *File
)
2617 CHAR szCmd
[MAX_PATH
];
2618 CHAR NewFile
[MAX_PATH
];
2620 PROCESS_INFORMATION Pi
;
2622 Log("<1> Copy New file", File
);
2623 sprintf_s(NewFile
, sizeof(NewFile
), "%s_NEW", File
);
2624 CopyFileA(File
, NewFile
, FALSE
);
2626 Log("<2> Remove file <%s>", File
);
2627 GetStartupInfoA(&Si
);
2628 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
2629 Si
.wShowWindow
= SW_HIDE
;
2630 sprintf_s(szCmd
, sizeof(szCmd
), "cmd.exe /c del /F /Q %s", File
);
2631 CreateProcessA(NULL
, szCmd
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
2632 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
2634 Log("<3> Copy back file <%s>", File
);
2635 MoveFileA(NewFile
, File
);
2640 int main(int argc
, char **argv
)
2644 PROCESS_INFORMATION Pi
;
2645 CHAR CurDir
[MAX_PATH
];
2646 CHAR NewArgv0
[MAX_PATH
];
2647 CHAR CallParam
[1024] = { 0 };
2649 g_vtoylog_mutex
= CreateMutexA(NULL
, FALSE
, "VTOYLOG_LOCK");
2650 g_vtoyins_mutex
= CreateMutexA(NULL
, FALSE
, "VTOYINS_LOCK");
2652 Log("######## VentoyJump %dbit ##########", g_system_bit
);
2654 GetCurrentDirectoryA(sizeof(CurDir
), CurDir
);
2655 Log("Current directory is <%s>", CurDir
);
2657 GetModuleFileNameA(NULL
, g_prog_full_path
, MAX_PATH
);
2658 split_path_name(g_prog_full_path
, g_prog_dir
, g_prog_name
);
2660 Log("EXE path: <%s> dir:<%s> name:<%s>", g_prog_full_path
, g_prog_dir
, g_prog_name
);
2662 if (IsFileExist(WIMBOOT_FILE
))
2664 Log("This is wimboot mode ...");
2665 g_wimboot_mode
= TRUE
;
2667 if (!IsFileExist(WIMBOOT_DONE
))
2669 vtoy_remove_duplicate_file(g_prog_full_path
);
2670 SaveBuffer2File(WIMBOOT_DONE
, g_prog_full_path
, 1);
2675 Log("This is normal mode ...");
2678 if (_stricmp(g_prog_name
, "WinLogon.exe") == 0)
2680 Log("This time is rejump back ...");
2682 strcpy_s(g_prog_full_path
, sizeof(g_prog_full_path
), argv
[1]);
2683 split_path_name(g_prog_full_path
, g_prog_dir
, g_prog_name
);
2685 return real_main(argc
- 1, argv
+ 1);
2687 else if (_stricmp(g_prog_name
, "PECMD.exe") == 0)
2689 strcpy_s(NewArgv0
, sizeof(NewArgv0
), g_prog_dir
);
2690 VentoyToUpper(NewArgv0
);
2692 if (NULL
== strstr(NewArgv0
, "SYSTEM32") && IsFileExist(ORG_PECMD_BK_PATH
))
2694 Log("Just call original pecmd.exe");
2695 strcpy_s(CallParam
, sizeof(CallParam
), ORG_PECMD_PATH
);
2699 Log("We need to rejump for pecmd ...");
2701 ventoy_check_create_directory();
2702 CopyFileA(g_prog_full_path
, "ventoy\\WinLogon.exe", TRUE
);
2704 sprintf_s(CallParam
, sizeof(CallParam
), "ventoy\\WinLogon.exe %s", g_prog_full_path
);
2707 for (i
= 1; i
< argc
; i
++)
2709 strcat_s(CallParam
, sizeof(CallParam
), " ");
2710 strcat_s(CallParam
, sizeof(CallParam
), argv
[i
]);
2713 Log("Now rejump to <%s> ...", CallParam
);
2714 GetStartupInfoA(&Si
);
2715 CreateProcessA(NULL
, CallParam
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
2717 Log("Wait rejump process...");
2718 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
2719 Log("rejump finished");
2724 Log("We don't need to rejump ...");
2726 ventoy_check_create_directory();
2727 strcpy_s(NewArgv0
, sizeof(NewArgv0
), g_prog_full_path
);
2730 return real_main(argc
, argv
);