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 CHAR g_prog_full_path
[MAX_PATH
];
40 static CHAR g_prog_dir
[MAX_PATH
];
41 static CHAR g_prog_name
[MAX_PATH
];
43 #define LOG_FILE "X:\\Windows\\system32\\ventoy.log"
44 #define MUTEX_LOCK(hmutex) if (hmutex != NULL) LockStatus = WaitForSingleObject(hmutex, INFINITE)
45 #define MUTEX_UNLOCK(hmutex) if (hmutex != NULL && WAIT_OBJECT_0 == LockStatus) ReleaseMutex(hmutex)
47 static const char * GetFileNameInPath(const char *fullpath
)
51 if (strstr(fullpath
, ":"))
53 for (i
= (int)strlen(fullpath
); i
> 0; i
--)
55 if (fullpath
[i
- 1] == '/' || fullpath
[i
- 1] == '\\')
65 static int split_path_name(char *fullpath
, char *dir
, char *name
)
70 Pos
= (CHAR
*)GetFileNameInPath(fullpath
);
72 strcpy_s(name
, MAX_PATH
, Pos
);
76 strcpy_s(dir
, MAX_PATH
, fullpath
);
83 void Log(const char *Fmt
, ...)
91 DWORD PID
= GetCurrentProcessId();
94 Len
+= sprintf_s(szBuf
, sizeof(szBuf
),
95 "[%4d/%02d/%02d %02d:%02d:%02d.%03d] [%u] ",
96 Sys
.wYear
, Sys
.wMonth
, Sys
.wDay
,
97 Sys
.wHour
, Sys
.wMinute
, Sys
.wSecond
,
98 Sys
.wMilliseconds
, PID
);
101 Len
+= vsnprintf_s(szBuf
+ Len
, sizeof(szBuf
)-Len
, sizeof(szBuf
)-Len
, Fmt
, Arg
);
104 MUTEX_LOCK(g_vtoylog_mutex
);
106 fopen_s(&File
, LOG_FILE
, "a+");
109 fwrite(szBuf
, 1, Len
, File
);
110 fwrite("\n", 1, 1, File
);
114 MUTEX_UNLOCK(g_vtoylog_mutex
);
118 static int LoadNtDriver(const char *DrvBinPath
)
124 SC_HANDLE hServiceMgr
;
126 char name
[256] = { 0 };
128 for (i
= (int)strlen(DrvBinPath
) - 1; i
>= 0; i
--)
130 if (DrvBinPath
[i
] == '\\' || DrvBinPath
[i
] == '/')
132 sprintf_s(name
, sizeof(name
), "%s", DrvBinPath
+ i
+ 1);
137 Log("Load NT driver: %s %s", DrvBinPath
, name
);
139 hServiceMgr
= OpenSCManagerA(NULL
, NULL
, SC_MANAGER_ALL_ACCESS
);
140 if (hServiceMgr
== NULL
)
142 Log("OpenSCManager failed Error:%u", GetLastError());
146 Log("OpenSCManager OK");
148 hService
= CreateServiceA(hServiceMgr
,
152 SERVICE_KERNEL_DRIVER
,
153 SERVICE_DEMAND_START
,
154 SERVICE_ERROR_NORMAL
,
156 NULL
, NULL
, NULL
, NULL
, NULL
);
157 if (hService
== NULL
)
159 Status
= GetLastError();
160 if (Status
!= ERROR_IO_PENDING
&& Status
!= ERROR_SERVICE_EXISTS
)
162 Log("CreateService failed v %u", Status
);
163 CloseServiceHandle(hServiceMgr
);
167 hService
= OpenServiceA(hServiceMgr
, name
, SERVICE_ALL_ACCESS
);
168 if (hService
== NULL
)
170 Log("OpenService failed %u", Status
);
171 CloseServiceHandle(hServiceMgr
);
176 Log("CreateService imdisk OK");
178 Ret
= StartServiceA(hService
, 0, NULL
);
181 Log("StartService OK");
185 Status
= GetLastError();
186 if (Status
== ERROR_SERVICE_ALREADY_RUNNING
)
192 Log("StartService error %u", Status
);
197 CloseServiceHandle(hService
);
198 CloseServiceHandle(hServiceMgr
);
200 Log("Load NT driver %s", rc
? "failed" : "success");
205 static int ReadWholeFile2Buf(const char *Fullpath
, void **Data
, DWORD
*Size
)
213 Log("ReadWholeFile2Buf <%s>", Fullpath
);
215 Handle
= CreateFileA(Fullpath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
216 if (Handle
== INVALID_HANDLE_VALUE
)
218 Log("Could not open the file<%s>, error:%u", Fullpath
, GetLastError());
222 FileSize
= SetFilePointer(Handle
, 0, NULL
, FILE_END
);
224 Buffer
= malloc(FileSize
);
227 Log("Failed to alloc memory size:%u", FileSize
);
231 SetFilePointer(Handle
, 0, NULL
, FILE_BEGIN
);
232 if (!ReadFile(Handle
, Buffer
, FileSize
, &dwSize
, NULL
))
234 Log("ReadFile failed, dwSize:%u error:%u", dwSize
, GetLastError());
241 Log("Success read file size:%u", FileSize
);
246 SAFE_CLOSE_HANDLE(Handle
);
251 static BOOL
CheckPeHead(BYTE
*Head
)
255 if (Head
[0] != 'M' || Head
[1] != 'Z')
260 PeOffset
= *(UINT32
*)(Head
+ 60);
261 if (*(UINT32
*)(Head
+ PeOffset
) != 0x00004550)
270 static BOOL
CheckOsParam(ventoy_os_param
*param
)
275 if (memcmp(¶m
->guid
, &g_ventoy_guid
, sizeof(ventoy_guid
)))
280 for (i
= 0; i
< sizeof(ventoy_os_param
); i
++)
282 Sum
+= *((BYTE
*)param
+ i
);
290 if (param
->vtoy_img_location_addr
% 4096)
298 static int SaveBuffer2File(const char *Fullpath
, void *Buffer
, DWORD Length
)
304 Log("SaveBuffer2File <%s> len:%u", Fullpath
, Length
);
306 Handle
= CreateFileA(Fullpath
, GENERIC_READ
| GENERIC_WRITE
,
307 FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, CREATE_NEW
, 0, 0);
308 if (Handle
== INVALID_HANDLE_VALUE
)
310 Log("Could not create new file, error:%u", GetLastError());
314 WriteFile(Handle
, Buffer
, Length
, &dwSize
, NULL
);
319 SAFE_CLOSE_HANDLE(Handle
);
324 static int IsUTF8Encode(const char *src
)
327 const UCHAR
*Byte
= (const UCHAR
*)src
;
329 for (i
= 0; i
< MAX_PATH
&& Byte
[i
]; i
++)
340 static int Utf8ToUtf16(const char* src
, WCHAR
* dst
)
342 int size
= MultiByteToWideChar(CP_UTF8
, 0, src
, -1, dst
, 0);
343 return MultiByteToWideChar(CP_UTF8
, 0, src
, -1, dst
, size
+ 1);
346 static BOOL
IsDirExist(const char *Fmt
, ...)
351 CHAR FilePathA
[MAX_PATH
];
352 WCHAR FilePathW
[MAX_PATH
];
355 vsnprintf_s(FilePathA
, sizeof(FilePathA
), sizeof(FilePathA
), Fmt
, Arg
);
358 UTF8
= IsUTF8Encode(FilePathA
);
362 Utf8ToUtf16(FilePathA
, FilePathW
);
363 Attr
= GetFileAttributesW(FilePathW
);
367 Attr
= GetFileAttributesA(FilePathA
);
370 if (Attr
!= INVALID_FILE_ATTRIBUTES
&& (Attr
& FILE_ATTRIBUTE_DIRECTORY
))
378 static BOOL
IsFileExist(const char *Fmt
, ...)
385 CHAR FilePathA
[MAX_PATH
];
386 WCHAR FilePathW
[MAX_PATH
];
389 vsnprintf_s(FilePathA
, sizeof(FilePathA
), sizeof(FilePathA
), Fmt
, Arg
);
392 UTF8
= IsUTF8Encode(FilePathA
);
396 Utf8ToUtf16(FilePathA
, FilePathW
);
397 hFile
= CreateFileW(FilePathW
, FILE_READ_EA
, FILE_SHARE_READ
, 0, OPEN_EXISTING
, 0, 0);
401 hFile
= CreateFileA(FilePathA
, FILE_READ_EA
, FILE_SHARE_READ
, 0, OPEN_EXISTING
, 0, 0);
403 if (INVALID_HANDLE_VALUE
== hFile
)
412 Attr
= GetFileAttributesW(FilePathW
);
416 Attr
= GetFileAttributesA(FilePathA
);
419 if (Attr
& FILE_ATTRIBUTE_DIRECTORY
)
427 Log("File <%s> %s", FilePathA
, (bRet
? "exist" : "NOT exist"));
431 static int GetPhyDiskUUID(const char LogicalDrive
, UINT8
*UUID
, DISK_EXTENT
*DiskExtent
)
436 VOLUME_DISK_EXTENTS DiskExtents
;
438 UINT8 SectorBuf
[512];
440 Log("GetPhyDiskUUID %C", LogicalDrive
);
442 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\%C:", LogicalDrive
);
443 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
444 if (Handle
== INVALID_HANDLE_VALUE
)
446 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
450 Ret
= DeviceIoControl(Handle
,
451 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
455 (DWORD
)(sizeof(DiskExtents
)),
458 if (!Ret
|| DiskExtents
.NumberOfDiskExtents
== 0)
460 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed, error:%u", GetLastError());
466 memcpy(DiskExtent
, DiskExtents
.Extents
, sizeof(DiskExtent
));
467 Log("%C: is in PhysicalDrive%d ", LogicalDrive
, DiskExtents
.Extents
[0].DiskNumber
);
469 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\PhysicalDrive%d", DiskExtents
.Extents
[0].DiskNumber
);
470 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
471 if (Handle
== INVALID_HANDLE_VALUE
)
473 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
477 if (!ReadFile(Handle
, SectorBuf
, sizeof(SectorBuf
), &dwSize
, NULL
))
479 Log("ReadFile failed, dwSize:%u error:%u", dwSize
, GetLastError());
484 memcpy(UUID
, SectorBuf
+ 0x180, 16);
489 static int VentoyMountAnywhere(HANDLE Handle
)
492 ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters
;
494 Log("VentoyMountAnywhere");
496 memset(&AttachParameters
, 0, sizeof(AttachParameters
));
497 AttachParameters
.Version
= ATTACH_VIRTUAL_DISK_VERSION_1
;
499 Status
= AttachVirtualDisk(Handle
, NULL
, ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY
| ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME
, 0, &AttachParameters
, NULL
);
500 if (Status
!= ERROR_SUCCESS
)
502 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
509 int VentoyMountY(HANDLE Handle
)
514 DWORD physicalDriveNameSize
;
516 WCHAR physicalDriveName
[MAX_PATH
];
517 CHAR physicalDriveNameA
[MAX_PATH
];
518 CHAR cdromDriveName
[MAX_PATH
];
519 ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters
;
523 memset(&AttachParameters
, 0, sizeof(AttachParameters
));
524 AttachParameters
.Version
= ATTACH_VIRTUAL_DISK_VERSION_1
;
526 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
);
527 if (Status
!= ERROR_SUCCESS
)
529 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
533 memset(physicalDriveName
, 0, sizeof(physicalDriveName
));
534 memset(physicalDriveNameA
, 0, sizeof(physicalDriveNameA
));
536 physicalDriveNameSize
= MAX_PATH
;
537 Status
= GetVirtualDiskPhysicalPath(Handle
, &physicalDriveNameSize
, physicalDriveName
);
538 if (Status
!= ERROR_SUCCESS
)
540 Log("Failed GetVirtualDiskPhysicalPath ErrorCode:%u", Status
);
544 for (i
= 0; physicalDriveName
[i
]; i
++)
546 physicalDriveNameA
[i
] = (CHAR
)toupper((CHAR
)(physicalDriveName
[i
]));
549 Log("physicalDriveNameA=<%s>", physicalDriveNameA
);
551 Pos
= strstr(physicalDriveNameA
, "CDROM");
554 Log("Not cdrom phy drive");
558 sprintf_s(cdromDriveName
, sizeof(cdromDriveName
), "\\Device\\%s", Pos
);
559 Log("cdromDriveName=<%s>", cdromDriveName
);
561 for (i
= 0; i
< 3 && (bRet
== FALSE
); i
++)
564 bRet
= DefineDosDeviceA(DDD_RAW_TARGET_PATH
, "Y:", cdromDriveName
);
565 Log("DefineDosDeviceA %s", bRet
? "success" : "failed");
571 static BOOL
VentoyAPINeedMountY(const char *IsoPath
)
579 static int VentoyAttachVirtualDisk(HANDLE Handle
, const char *IsoPath
)
584 Drives
= GetLogicalDrives();
585 if ((1 << 24) & Drives
)
587 Log("Y: is occupied");
592 Log("Y: is free now");
596 if (DriveYFree
&& VentoyAPINeedMountY(IsoPath
))
598 return VentoyMountY(Handle
);
602 return VentoyMountAnywhere(Handle
);
606 int VentoyMountISOByAPI(const char *IsoPath
)
611 WCHAR wFilePath
[512] = { 0 };
612 VIRTUAL_STORAGE_TYPE StorageType
;
613 OPEN_VIRTUAL_DISK_PARAMETERS OpenParameters
;
615 Log("VentoyMountISOByAPI <%s>", IsoPath
);
617 if (IsUTF8Encode(IsoPath
))
619 Log("This is UTF8 encoding");
620 MultiByteToWideChar(CP_UTF8
, 0, IsoPath
, (int)strlen(IsoPath
), wFilePath
, (int)(sizeof(wFilePath
) / sizeof(WCHAR
)));
624 Log("This is ANSI encoding");
625 MultiByteToWideChar(CP_ACP
, 0, IsoPath
, (int)strlen(IsoPath
), wFilePath
, (int)(sizeof(wFilePath
) / sizeof(WCHAR
)));
628 memset(&StorageType
, 0, sizeof(StorageType
));
629 memset(&OpenParameters
, 0, sizeof(OpenParameters
));
631 OpenParameters
.Version
= OPEN_VIRTUAL_DISK_VERSION_1
;
633 for (i
= 0; i
< 10; i
++)
635 Status
= OpenVirtualDisk(&StorageType
, wFilePath
, VIRTUAL_DISK_ACCESS_READ
, 0, &OpenParameters
, &Handle
);
636 if (ERROR_FILE_NOT_FOUND
== Status
|| ERROR_PATH_NOT_FOUND
== Status
)
638 Log("OpenVirtualDisk ErrorCode:%u, now wait and retry...", Status
);
643 if (ERROR_SUCCESS
== Status
)
645 Log("OpenVirtualDisk success");
647 else if (ERROR_VIRTDISK_PROVIDER_NOT_FOUND
== Status
)
649 Log("VirtualDisk for ISO file is not supported in current system");
653 Log("Failed to open virtual disk ErrorCode:%u", Status
);
659 if (Status
!= ERROR_SUCCESS
)
664 Log("OpenVirtualDisk success");
666 Status
= VentoyAttachVirtualDisk(Handle
, IsoPath
);
667 if (Status
!= ERROR_SUCCESS
)
669 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
674 Log("VentoyAttachVirtualDisk success");
681 static HANDLE g_FatPhyDrive
;
682 static UINT64 g_Part2StartSec
;
684 static int CopyFileFromFatDisk(const CHAR
* SrcFile
, const CHAR
*DstFile
)
691 Log("CopyFileFromFatDisk (%s)==>(%s)", SrcFile
, DstFile
);
693 flfile
= fl_fopen(SrcFile
, "rb");
696 fl_fseek(flfile
, 0, SEEK_END
);
697 size
= (int)fl_ftell(flfile
);
698 fl_fseek(flfile
, 0, SEEK_SET
);
700 buf
= (char *)malloc(size
);
703 fl_fread(buf
, 1, size
, flfile
);
706 SaveBuffer2File(DstFile
, buf
, size
);
716 static int VentoyFatDiskRead(uint32 Sector
, uint8
*Buffer
, uint32 SectorCount
)
721 LARGE_INTEGER liCurrentPosition
;
723 liCurrentPosition
.QuadPart
= Sector
+ g_Part2StartSec
;
724 liCurrentPosition
.QuadPart
*= 512;
725 SetFilePointerEx(g_FatPhyDrive
, liCurrentPosition
, &liCurrentPosition
, FILE_BEGIN
);
727 ReadSize
= (DWORD
)(SectorCount
* 512);
729 bRet
= ReadFile(g_FatPhyDrive
, Buffer
, ReadSize
, &dwSize
, NULL
);
730 if (bRet
== FALSE
|| dwSize
!= ReadSize
)
732 Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u\n", bRet
, ReadSize
, dwSize
, GetLastError());
738 static BOOL
Is2K10PE(void)
744 fopen_s(&fp
, "X:\\Windows\\System32\\PECMD.INI", "r");
750 memset(szLine
, 0, sizeof(szLine
));
751 while (fgets(szLine
, sizeof(szLine
) - 1, fp
))
753 if (strstr(szLine
, "2k10\\"))
764 static CHAR
GetIMDiskMountLogicalDrive(void)
768 DWORD Mask
= 0x1000000;
770 // fixed use M as mountpoint for 2K10 PE
773 Log("Use M: for 2K10 PE");
777 Drives
= GetLogicalDrives();
778 Log("Drives=0x%x", Drives
);
782 if ((Drives
& Mask
) == 0)
794 UINT64
GetVentoyEfiPartStartSector(HANDLE hDrive
)
799 VTOY_GPT_INFO
*pGpt
= NULL
;
800 UINT64 StartSector
= 0;
802 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
804 bRet
= ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
805 Log("Read MBR Ret:%u Size:%u code:%u", bRet
, dwSize
, LASTERR
);
807 if ((!bRet
) || (dwSize
!= sizeof(MBR
)))
812 if (MBR
.PartTbl
[0].FsFlag
== 0xEE)
814 Log("GPT partition style");
816 pGpt
= malloc(sizeof(VTOY_GPT_INFO
));
822 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
823 bRet
= ReadFile(hDrive
, pGpt
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
);
824 if ((!bRet
) || (dwSize
!= sizeof(VTOY_GPT_INFO
)))
826 Log("Failed to read gpt info %d %u %d", bRet
, dwSize
, LASTERR
);
830 StartSector
= pGpt
->PartTbl
[1].StartLBA
;
835 Log("MBR partition style");
836 StartSector
= MBR
.PartTbl
[1].StartSectorId
;
839 Log("GetVentoyEfiPart StartSector: %llu", StartSector
);
843 static int VentoyRunImdisk(const char *IsoPath
, const char *imdiskexe
)
848 PROCESS_INFORMATION Pi
;
850 Log("VentoyRunImdisk <%s> <%s>", IsoPath
, imdiskexe
);
852 Letter
= GetIMDiskMountLogicalDrive();
853 sprintf_s(Cmdline
, sizeof(Cmdline
), "%s -a -o ro -f \"%s\" -m %C:", imdiskexe
, IsoPath
, Letter
);
854 Log("mount iso to %C: use imdisk cmd <%s>", Letter
, Cmdline
);
856 if (IsUTF8Encode(IsoPath
))
859 GetStartupInfoW(&Si
);
860 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
861 Si
.wShowWindow
= SW_HIDE
;
863 Utf8ToUtf16(Cmdline
, CmdlineW
);
864 CreateProcessW(NULL
, CmdlineW
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
866 Log("This is UTF8 encoding");
871 GetStartupInfoA(&Si
);
872 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
873 Si
.wShowWindow
= SW_HIDE
;
875 CreateProcessA(NULL
, Cmdline
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
877 Log("This is ANSI encoding");
880 Log("Wait for imdisk process ...");
881 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
882 Log("imdisk process finished");
887 int VentoyMountISOByImdisk(const char *IsoPath
, DWORD PhyDrive
)
893 CHAR PhyPath
[MAX_PATH
];
894 GET_LENGTH_INFORMATION LengthInfo
;
896 Log("VentoyMountISOByImdisk %s", IsoPath
);
898 if (IsFileExist("X:\\Windows\\System32\\imdisk.exe"))
900 Log("imdisk.exe exist, use it directly...");
901 VentoyRunImdisk(IsoPath
, "imdisk.exe");
905 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\PhysicalDrive%d", PhyDrive
);
906 hDrive
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
907 if (hDrive
== INVALID_HANDLE_VALUE
)
909 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
913 bRet
= DeviceIoControl(hDrive
, IOCTL_DISK_GET_LENGTH_INFO
, NULL
, 0, &LengthInfo
, sizeof(LengthInfo
), &dwBytes
, NULL
);
916 Log("Could not get phy disk %s size, error:%u", PhyPath
, GetLastError());
920 g_FatPhyDrive
= hDrive
;
921 g_Part2StartSec
= GetVentoyEfiPartStartSector(hDrive
);
923 Log("Parse FAT fs...");
927 if (0 == fl_attach_media(VentoyFatDiskRead
, NULL
))
929 if (g_system_bit
== 64)
931 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.sys", "ventoy\\imdisk.sys");
932 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.exe", "ventoy\\imdisk.exe");
933 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.cpl", "ventoy\\imdisk.cpl");
937 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.sys", "ventoy\\imdisk.sys");
938 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.exe", "ventoy\\imdisk.exe");
939 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.cpl", "ventoy\\imdisk.cpl");
942 GetCurrentDirectoryA(sizeof(PhyPath
), PhyPath
);
943 strcat_s(PhyPath
, sizeof(PhyPath
), "\\ventoy\\imdisk.sys");
945 if (LoadNtDriver(PhyPath
) == 0)
947 VentoyRunImdisk(IsoPath
, "ventoy\\imdisk.exe");
955 SAFE_CLOSE_HANDLE(hDrive
);
960 static int MountIsoFile(CONST CHAR
*IsoPath
, DWORD PhyDrive
)
962 if (IsWindows8OrGreater())
964 Log("This is Windows 8 or latter...");
965 if (VentoyMountISOByAPI(IsoPath
) == 0)
967 Log("Mount iso by API success");
972 Log("Mount iso by API failed, maybe not supported, try imdisk");
973 return VentoyMountISOByImdisk(IsoPath
, PhyDrive
);
978 Log("This is before Windows 8 ...");
979 if (VentoyMountISOByImdisk(IsoPath
, PhyDrive
) == 0)
981 Log("Mount iso by imdisk success");
986 return VentoyMountISOByAPI(IsoPath
);
991 static int GetPhyDriveByLogicalDrive(int DriveLetter
)
996 VOLUME_DISK_EXTENTS DiskExtents
;
999 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\%C:", (CHAR
)DriveLetter
);
1001 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
1002 if (Handle
== INVALID_HANDLE_VALUE
)
1004 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
1008 Ret
= DeviceIoControl(Handle
,
1009 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
1013 (DWORD
)(sizeof(DiskExtents
)),
1017 if (!Ret
|| DiskExtents
.NumberOfDiskExtents
== 0)
1019 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath
, GetLastError());
1020 SAFE_CLOSE_HANDLE(Handle
);
1023 SAFE_CLOSE_HANDLE(Handle
);
1025 Log("LogicalDrive:%s PhyDrive:%d Offset:%llu ExtentLength:%llu",
1027 DiskExtents
.Extents
[0].DiskNumber
,
1028 DiskExtents
.Extents
[0].StartingOffset
.QuadPart
,
1029 DiskExtents
.Extents
[0].ExtentLength
.QuadPart
1032 return (int)DiskExtents
.Extents
[0].DiskNumber
;
1036 static int DeleteVentoyPart2MountPoint(DWORD PhyDrive
)
1041 CHAR DriveName
[] = "?:\\";
1043 Log("DeleteVentoyPart2MountPoint Phy%u ...", PhyDrive
);
1045 Drives
= GetLogicalDrives();
1048 if ((Drives
& 0x01) && IsFileExist("%C:\\ventoy\\ventoy.cpio", Letter
))
1050 Log("File %C:\\ventoy\\ventoy.cpio exist", Letter
);
1052 PhyDisk
= GetPhyDriveByLogicalDrive(Letter
);
1053 Log("PhyDisk=%u for %C", PhyDisk
, Letter
);
1055 if (PhyDisk
== PhyDrive
)
1057 DriveName
[0] = Letter
;
1058 DeleteVolumeMountPointA(DriveName
);
1070 static BOOL
check_tar_archive(const char *archive
, CHAR
*tarName
)
1074 const char *pos
= archive
;
1075 const char *slash
= archive
;
1079 if (*pos
== '\\' || *pos
== '/')
1086 len
= (int)strlen(slash
);
1088 if (len
> 7 && (strncmp(slash
+ len
- 7, ".tar.gz", 7) == 0 || strncmp(slash
+ len
- 7, ".tar.xz", 7) == 0))
1090 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
1091 tarName
[nameLen
- 3] = 0;
1094 else if (len
> 8 && strncmp(slash
+ len
- 8, ".tar.bz2", 8) == 0)
1096 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
1097 tarName
[nameLen
- 4] = 0;
1100 else if (len
> 9 && strncmp(slash
+ len
- 9, ".tar.lzma", 9) == 0)
1102 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
1103 tarName
[nameLen
- 5] = 0;
1110 static int DecompressInjectionArchive(const char *archive
, DWORD PhyDrive
)
1117 DWORD flags
= CREATE_NO_WINDOW
;
1118 CHAR StrBuf
[MAX_PATH
];
1119 CHAR tarName
[MAX_PATH
];
1121 PROCESS_INFORMATION Pi
;
1122 PROCESS_INFORMATION NewPi
;
1123 GET_LENGTH_INFORMATION LengthInfo
;
1124 SECURITY_ATTRIBUTES Sa
= { sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
1126 Log("DecompressInjectionArchive %s", archive
);
1128 sprintf_s(StrBuf
, sizeof(StrBuf
), "\\\\.\\PhysicalDrive%d", PhyDrive
);
1129 hDrive
= CreateFileA(StrBuf
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
1130 if (hDrive
== INVALID_HANDLE_VALUE
)
1132 Log("Could not open the disk<%s>, error:%u", StrBuf
, GetLastError());
1136 bRet
= DeviceIoControl(hDrive
, IOCTL_DISK_GET_LENGTH_INFO
, NULL
, 0, &LengthInfo
, sizeof(LengthInfo
), &dwBytes
, NULL
);
1139 Log("Could not get phy disk %s size, error:%u", StrBuf
, GetLastError());
1143 g_FatPhyDrive
= hDrive
;
1144 g_Part2StartSec
= GetVentoyEfiPartStartSector(hDrive
);
1146 Log("Parse FAT fs...");
1150 if (0 == fl_attach_media(VentoyFatDiskRead
, NULL
))
1152 if (g_system_bit
== 64)
1154 CopyFileFromFatDisk("/ventoy/7z/64/7za.exe", "ventoy\\7za.exe");
1158 CopyFileFromFatDisk("/ventoy/7z/32/7za.exe", "ventoy\\7za.exe");
1161 sprintf_s(StrBuf
, sizeof(StrBuf
), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", archive
);
1163 Log("extract inject to X:");
1164 Log("cmdline:<%s>", StrBuf
);
1166 GetStartupInfoA(&Si
);
1168 hOut
= CreateFileA("ventoy\\7z.log",
1170 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
1173 FILE_ATTRIBUTE_NORMAL
,
1176 Si
.dwFlags
|= STARTF_USESTDHANDLES
;
1178 if (hOut
!= INVALID_HANDLE_VALUE
)
1180 Si
.hStdError
= hOut
;
1181 Si
.hStdOutput
= hOut
;
1184 CreateProcessA(NULL
, StrBuf
, NULL
, NULL
, TRUE
, flags
, NULL
, NULL
, &Si
, &Pi
);
1185 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
1188 // decompress tar archive, for tar.gz/tar.xz/tar.bz2
1190 if (check_tar_archive(archive
, tarName
))
1192 Log("Decompress tar archive...<%s>", tarName
);
1194 sprintf_s(StrBuf
, sizeof(StrBuf
), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", tarName
);
1196 CreateProcessA(NULL
, StrBuf
, NULL
, NULL
, TRUE
, flags
, NULL
, NULL
, &Si
, &NewPi
);
1197 WaitForSingleObject(NewPi
.hProcess
, INFINITE
);
1199 Log("Now delete %s", tarName
);
1200 DeleteFileA(tarName
);
1203 SAFE_CLOSE_HANDLE(hOut
);
1209 SAFE_CLOSE_HANDLE(hDrive
);
1214 static int ProcessUnattendedInstallation(const char *script
)
1220 CHAR CurDir
[MAX_PATH
];
1222 Log("Copy unattended XML ...");
1224 GetCurrentDirectory(sizeof(CurDir
), CurDir
);
1226 if ((Letter
>= 'A' && Letter
<= 'Z') || (Letter
>= 'a' && Letter
<= 'z'))
1228 Log("Current Drive Letter: %C", Letter
);
1235 sprintf_s(CurDir
, sizeof(CurDir
), "%C:\\Autounattend.xml", Letter
);
1236 Log("Copy file <%s> --> <%s>", script
, CurDir
);
1237 CopyFile(script
, CurDir
, FALSE
);
1239 Ret
= RegCreateKeyEx(HKEY_LOCAL_MACHINE
, "System\\Setup", 0, NULL
, REG_OPTION_NON_VOLATILE
, KEY_ALL_ACCESS
, NULL
, &hKey
, &dw
);
1240 if (ERROR_SUCCESS
== Ret
)
1242 Ret
= RegSetValueEx(hKey
, "UnattendFile", 0, REG_SZ
, CurDir
, (DWORD
)(strlen(CurDir
) + 1));
1248 static int VentoyHook(ventoy_os_param
*param
)
1255 DISK_EXTENT DiskExtent
;
1257 CHAR IsoPath
[MAX_PATH
];
1259 Log("VentoyHook Path:<%s>", param
->vtoy_img_path
);
1261 if (IsUTF8Encode(param
->vtoy_img_path
))
1263 Log("This file is UTF8 encoding\n");
1266 for (i
= 0; i
< 5; i
++)
1269 Drives
= GetLogicalDrives();
1270 Log("Logic Drives: 0x%x", Drives
);
1276 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:\\%s", Letter
, param
->vtoy_img_path
);
1277 if (IsFileExist("%s", IsoPath
))
1279 Log("File exist under %C:", Letter
);
1280 if (GetPhyDiskUUID(Letter
, UUID
, &DiskExtent
) == 0)
1282 if (memcmp(UUID
, param
->vtoy_disk_guid
, 16) == 0)
1284 Log("Disk UUID match");
1292 Log("File NOT exist under %C:", Letter
);
1306 Log("Now wait and retry ...");
1313 Log("Failed to find ISO file");
1317 Log("Find ISO file <%s>", IsoPath
);
1319 rc
= MountIsoFile(IsoPath
, DiskExtent
.DiskNumber
);
1320 Log("Mount ISO FILE: %s", rc
== 0 ? "SUCCESS" : "FAILED");
1323 rc
= DeleteVentoyPart2MountPoint(DiskExtent
.DiskNumber
);
1324 Log("Delete ventoy mountpoint: %s", rc
== 0 ? "SUCCESS" : "NO NEED");
1326 if (g_windows_data
.auto_install_script
[0])
1328 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:%s", Letter
, g_windows_data
.auto_install_script
);
1329 if (IsFileExist("%s", IsoPath
))
1331 Log("use auto install script %s...", IsoPath
);
1332 ProcessUnattendedInstallation(IsoPath
);
1336 Log("auto install script %s not exist", IsoPath
);
1341 Log("auto install no need");
1344 if (g_windows_data
.injection_archive
[0])
1346 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:%s", Letter
, g_windows_data
.injection_archive
);
1347 if (IsFileExist("%s", IsoPath
))
1349 Log("decompress injection archive %s...", IsoPath
);
1350 DecompressInjectionArchive(IsoPath
, DiskExtent
.DiskNumber
);
1354 Log("injection archive %s not exist", IsoPath
);
1359 Log("no injection archive found");
1366 int VentoyJumpWimboot(INT argc
, CHAR
**argv
, CHAR
*LunchFile
)
1373 Log("VentoyJumpWimboot %dbit", g_system_bit
);
1375 sprintf_s(LunchFile
, MAX_PATH
, "X:\\setup.exe");
1377 ReadWholeFile2Buf("wimboot.data", &buf
, &size
);
1378 Log("wimboot.data size:%d", size
);
1380 memcpy(&g_os_param
, buf
, sizeof(ventoy_os_param
));
1381 memcpy(&g_windows_data
, buf
+ sizeof(ventoy_os_param
), sizeof(ventoy_windows_data
));
1382 memcpy(g_os_param_reserved
, g_os_param
.vtoy_reserved
, sizeof(g_os_param_reserved
));
1384 if (g_os_param_reserved
[0] == 1)
1386 Log("break here for debug .....");
1391 for (Pos
= 0; Pos
< sizeof(g_os_param
.vtoy_img_path
) && g_os_param
.vtoy_img_path
[Pos
]; Pos
++)
1393 if (g_os_param
.vtoy_img_path
[Pos
] == '/')
1395 g_os_param
.vtoy_img_path
[Pos
] = '\\';
1399 if (g_os_param_reserved
[0] == 2)
1401 Log("skip hook for debug .....");
1406 rc
= VentoyHook(&g_os_param
);
1418 static int ventoy_check_create_directory(void)
1420 if (IsDirExist("ventoy"))
1422 Log("ventoy directory already exist");
1426 Log("ventoy directory not exist, now create it.");
1427 if (!CreateDirectoryA("ventoy", NULL
))
1429 Log("Failed to create ventoy directory err:%u", GetLastError());
1437 int VentoyJump(INT argc
, CHAR
**argv
, CHAR
*LunchFile
)
1444 DWORD LockStatus
= 0;
1445 BYTE
*Buffer
= NULL
;
1446 CHAR ExeFileName
[MAX_PATH
];
1448 sprintf_s(ExeFileName
, sizeof(ExeFileName
), "%s", argv
[0]);
1449 if (!IsFileExist("%s", ExeFileName
))
1451 Log("File %s NOT exist, now try %s.exe", ExeFileName
, ExeFileName
);
1452 sprintf_s(ExeFileName
, sizeof(ExeFileName
), "%s.exe", argv
[0]);
1454 Log("File %s exist ? %s", ExeFileName
, IsFileExist("%s", ExeFileName
) ? "YES" : "NO");
1457 if (ReadWholeFile2Buf(ExeFileName
, (void **)&Buffer
, &FileSize
))
1462 Log("VentoyJump %dbit", g_system_bit
);
1464 MUTEX_LOCK(g_vtoyins_mutex
);
1465 stat
= ventoy_check_create_directory();
1466 MUTEX_UNLOCK(g_vtoyins_mutex
);
1473 for (PeStart
= 0; PeStart
< FileSize
; PeStart
+= 16)
1475 if (CheckOsParam((ventoy_os_param
*)(Buffer
+ PeStart
)) &&
1476 CheckPeHead(Buffer
+ PeStart
+ sizeof(ventoy_os_param
) + sizeof(ventoy_windows_data
)))
1478 Log("Find os pararm at %u", PeStart
);
1480 memcpy(&g_os_param
, Buffer
+ PeStart
, sizeof(ventoy_os_param
));
1481 memcpy(&g_windows_data
, Buffer
+ PeStart
+ sizeof(ventoy_os_param
), sizeof(ventoy_windows_data
));
1482 memcpy(g_os_param_reserved
, g_os_param
.vtoy_reserved
, sizeof(g_os_param_reserved
));
1484 if (g_os_param_reserved
[0] == 1)
1486 Log("break here for debug .....");
1491 for (Pos
= 0; Pos
< sizeof(g_os_param
.vtoy_img_path
) && g_os_param
.vtoy_img_path
[Pos
]; Pos
++)
1493 if (g_os_param
.vtoy_img_path
[Pos
] == '/')
1495 g_os_param
.vtoy_img_path
[Pos
] = '\\';
1499 PeStart
+= sizeof(ventoy_os_param
) + sizeof(ventoy_windows_data
);
1500 sprintf_s(LunchFile
, MAX_PATH
, "ventoy\\%s", GetFileNameInPath(ExeFileName
));
1502 MUTEX_LOCK(g_vtoyins_mutex
);
1503 if (IsFileExist("%s", LunchFile
))
1505 Log("vtoyjump multiple call ...");
1507 MUTEX_UNLOCK(g_vtoyins_mutex
);
1511 SaveBuffer2File(LunchFile
, Buffer
+ PeStart
, FileSize
- PeStart
);
1512 MUTEX_UNLOCK(g_vtoyins_mutex
);
1518 if (PeStart
>= FileSize
)
1520 Log("OS param not found");
1524 if (g_os_param_reserved
[0] == 2)
1526 Log("skip hook for debug .....");
1531 rc
= VentoyHook(&g_os_param
);
1544 int real_main(int argc
, char **argv
)
1548 CHAR NewFile
[MAX_PATH
];
1549 CHAR LunchFile
[MAX_PATH
];
1550 CHAR CallParam
[1024] = { 0 };
1552 PROCESS_INFORMATION Pi
;
1554 Log("#### real_main #### argc = %d", argc
);
1555 Log("program full path: <%s>", g_prog_full_path
);
1556 Log("program dir: <%s>", g_prog_dir
);
1557 Log("program name:: <%s>", g_prog_name
);
1559 Log("argc = %d", argc
);
1560 for (i
= 0; i
< argc
; i
++)
1562 Log("argv[%d]=<%s>", i
, argv
[i
]);
1565 strcat_s(CallParam
, sizeof(CallParam
), " ");
1566 strcat_s(CallParam
, sizeof(CallParam
), argv
[i
]);
1570 GetStartupInfoA(&Si
);
1571 memset(LunchFile
, 0, sizeof(LunchFile
));
1573 if (strstr(argv
[0], "vtoyjump.exe"))
1575 rc
= VentoyJumpWimboot(argc
, argv
, LunchFile
);
1579 rc
= VentoyJump(argc
, argv
, LunchFile
);
1582 Log("LunchFile=<%s> CallParam=<%s>", LunchFile
, CallParam
);
1584 if (_stricmp(g_prog_name
, "winpeshl.exe") != 0 && IsFileExist("ventoy\\%s", g_prog_name
))
1586 sprintf_s(NewFile
, sizeof(NewFile
), "%s_BACK.EXE", g_prog_full_path
);
1587 MoveFileA(g_prog_full_path
, NewFile
);
1588 Log("Move <%s> to <%s>", g_prog_full_path
, NewFile
);
1590 sprintf_s(NewFile
, sizeof(NewFile
), "ventoy\\%s", g_prog_name
);
1591 CopyFileA(NewFile
, g_prog_full_path
, TRUE
);
1592 Log("Copy <%s> to <%s>", NewFile
, g_prog_full_path
);
1594 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", g_prog_full_path
);
1595 Log("Final lunchFile is <%s>", LunchFile
);
1599 Log("We don't need to recover original <%s>", g_prog_name
);
1602 if (g_os_param_reserved
[0] == 3)
1604 Log("Open log for debug ...");
1605 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", "notepad.exe ventoy.log");
1611 strcat_s(LunchFile
, sizeof(LunchFile
), CallParam
);
1613 else if (NULL
== strstr(LunchFile
, "setup.exe"))
1615 Log("Not setup.exe, hide windows.");
1616 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
1617 Si
.wShowWindow
= SW_HIDE
;
1620 Log("Ventoy jump %s ...", rc
== 0 ? "success" : "failed");
1623 Log("Now launch <%s> ...", LunchFile
);
1625 if (g_os_param_reserved
[0] == 4)
1627 Log("Open cmd for debug ...");
1628 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", "cmd.exe");
1631 Log("Backup log at this point");
1632 CopyFileA(LOG_FILE
, "X:\\Windows\\ventoy.backup", TRUE
);
1634 CreateProcessA(NULL
, LunchFile
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
1636 for (i
= 0; rc
&& i
< 1800; i
++)
1638 Log("Ventoy hook failed, now wait and retry ...");
1640 rc
= VentoyHook(&g_os_param
);
1643 Log("Wait process...");
1644 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
1646 Log("vtoyjump finished");
1651 int main(int argc
, char **argv
)
1655 PROCESS_INFORMATION Pi
;
1656 CHAR CurDir
[MAX_PATH
];
1657 CHAR NewArgv0
[MAX_PATH
];
1658 CHAR CallParam
[1024] = { 0 };
1660 g_vtoylog_mutex
= CreateMutexA(NULL
, FALSE
, "VTOYLOG_LOCK");
1661 g_vtoyins_mutex
= CreateMutexA(NULL
, FALSE
, "VTOYINS_LOCK");
1663 Log("######## VentoyJump %dbit ##########", g_system_bit
);
1665 GetCurrentDirectoryA(sizeof(CurDir
), CurDir
);
1666 Log("Current directory is <%s>", CurDir
);
1668 GetModuleFileNameA(NULL
, g_prog_full_path
, MAX_PATH
);
1669 split_path_name(g_prog_full_path
, g_prog_dir
, g_prog_name
);
1671 Log("EXE path: <%s> dir:<%s> name:<%s>", g_prog_full_path
, g_prog_dir
, g_prog_name
);
1673 if (_stricmp(g_prog_name
, "WinLogon.exe") == 0)
1675 Log("This time is rejump back ...");
1677 strcpy_s(g_prog_full_path
, sizeof(g_prog_full_path
), argv
[1]);
1678 split_path_name(g_prog_full_path
, g_prog_dir
, g_prog_name
);
1680 return real_main(argc
- 1, argv
+ 1);
1682 else if (_stricmp(g_prog_name
, "PECMD.exe") == 0)
1684 Log("We need to rejump for pecmd ...");
1686 ventoy_check_create_directory();
1687 CopyFileA(g_prog_full_path
, "ventoy\\WinLogon.exe", TRUE
);
1689 sprintf_s(CallParam
, sizeof(CallParam
), "ventoy\\WinLogon.exe %s", g_prog_full_path
);
1690 for (i
= 1; i
< argc
; i
++)
1692 strcat_s(CallParam
, sizeof(CallParam
), " ");
1693 strcat_s(CallParam
, sizeof(CallParam
), argv
[i
]);
1696 Log("Now rejump to <%s> ...", CallParam
);
1697 GetStartupInfoA(&Si
);
1698 CreateProcessA(NULL
, CallParam
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
1700 Log("Wait rejump process...");
1701 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
1702 Log("rejump finished");
1707 Log("We don't need to rejump ...");
1709 strcpy_s(NewArgv0
, sizeof(NewArgv0
), g_prog_full_path
);
1712 return real_main(argc
, argv
);