1 /******************************************************************************
4 * Copyright (c) 2020, 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 BOOL g_64bit_system
= FALSE
;
35 static ventoy_guid g_ventoy_guid
= VENTOY_GUID
;
37 void Log(const char *Fmt
, ...)
44 DWORD PID
= GetCurrentProcessId();
47 Len
+= sprintf_s(szBuf
, sizeof(szBuf
),
48 "[%4d/%02d/%02d %02d:%02d:%02d.%03d] [%u] ",
49 Sys
.wYear
, Sys
.wMonth
, Sys
.wDay
,
50 Sys
.wHour
, Sys
.wMinute
, Sys
.wSecond
,
51 Sys
.wMilliseconds
, PID
);
54 Len
+= vsnprintf_s(szBuf
+ Len
, sizeof(szBuf
)-Len
, sizeof(szBuf
)-Len
, Fmt
, Arg
);
57 fopen_s(&File
, "ventoy.log", "a+");
60 fwrite(szBuf
, 1, Len
, File
);
61 fwrite("\n", 1, 1, File
);
67 static int LoadNtDriver(const char *DrvBinPath
)
73 SC_HANDLE hServiceMgr
;
75 char name
[256] = { 0 };
77 for (i
= (int)strlen(DrvBinPath
) - 1; i
>= 0; i
--)
79 if (DrvBinPath
[i
] == '\\' || DrvBinPath
[i
] == '/')
81 sprintf_s(name
, sizeof(name
), "%s", DrvBinPath
+ i
+ 1);
86 Log("Load NT driver: %s %s", DrvBinPath
, name
);
88 hServiceMgr
= OpenSCManagerA(NULL
, NULL
, SC_MANAGER_ALL_ACCESS
);
89 if (hServiceMgr
== NULL
)
91 Log("OpenSCManager failed Error:%u", GetLastError());
95 Log("OpenSCManager OK");
97 hService
= CreateServiceA(hServiceMgr
,
101 SERVICE_KERNEL_DRIVER
,
102 SERVICE_DEMAND_START
,
103 SERVICE_ERROR_NORMAL
,
105 NULL
, NULL
, NULL
, NULL
, NULL
);
106 if (hService
== NULL
)
108 Status
= GetLastError();
109 if (Status
!= ERROR_IO_PENDING
&& Status
!= ERROR_SERVICE_EXISTS
)
111 Log("CreateService failed v %u", Status
);
112 CloseServiceHandle(hServiceMgr
);
116 hService
= OpenServiceA(hServiceMgr
, name
, SERVICE_ALL_ACCESS
);
117 if (hService
== NULL
)
119 Log("OpenService failed %u", Status
);
120 CloseServiceHandle(hServiceMgr
);
125 Log("CreateService imdisk OK");
127 Ret
= StartServiceA(hService
, 0, NULL
);
130 Log("StartService OK");
134 Status
= GetLastError();
135 if (Status
== ERROR_SERVICE_ALREADY_RUNNING
)
141 Log("StartService error %u", Status
);
146 CloseServiceHandle(hService
);
147 CloseServiceHandle(hServiceMgr
);
149 Log("Load NT driver %s", rc
? "failed" : "success");
154 static int ReadWholeFile2Buf(const char *Fullpath
, void **Data
, DWORD
*Size
)
162 Log("ReadWholeFile2Buf <%s>", Fullpath
);
164 Handle
= CreateFileA(Fullpath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
165 if (Handle
== INVALID_HANDLE_VALUE
)
167 Log("Could not open the file<%s>, error:%u", Fullpath
, GetLastError());
171 FileSize
= SetFilePointer(Handle
, 0, NULL
, FILE_END
);
173 Buffer
= malloc(FileSize
);
176 Log("Failed to alloc memory size:%u", FileSize
);
180 SetFilePointer(Handle
, 0, NULL
, FILE_BEGIN
);
181 if (!ReadFile(Handle
, Buffer
, FileSize
, &dwSize
, NULL
))
183 Log("ReadFile failed, dwSize:%u error:%u", dwSize
, GetLastError());
190 Log("Success read file size:%u", FileSize
);
195 SAFE_CLOSE_HANDLE(Handle
);
200 static BOOL
CheckPeHead(BYTE
*Head
)
204 if (Head
[0] != 'M' || Head
[1] != 'Z')
209 PeOffset
= *(UINT32
*)(Head
+ 60);
210 if (*(UINT32
*)(Head
+ PeOffset
) != 0x00004550)
218 static BOOL
IsPe64(BYTE
*buffer
)
222 if (!CheckPeHead(buffer
))
227 pe_off
= *(UINT32
*)(buffer
+ 60);
228 if (*(UINT16
*)(buffer
+ pe_off
+ 24) == 0x020b)
237 static BOOL
CheckOsParam(ventoy_os_param
*param
)
242 if (memcmp(¶m
->guid
, &g_ventoy_guid
, sizeof(ventoy_guid
)))
247 for (i
= 0; i
< sizeof(ventoy_os_param
); i
++)
249 Sum
+= *((BYTE
*)param
+ i
);
257 if (param
->vtoy_img_location_addr
% 4096)
265 static int SaveBuffer2File(const char *Fullpath
, void *Buffer
, DWORD Length
)
271 Log("SaveBuffer2File <%s> len:%u", Fullpath
, Length
);
273 Handle
= CreateFileA(Fullpath
, GENERIC_READ
| GENERIC_WRITE
,
274 FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, CREATE_NEW
, 0, 0);
275 if (Handle
== INVALID_HANDLE_VALUE
)
277 Log("Could not create new file, error:%u", GetLastError());
281 WriteFile(Handle
, Buffer
, Length
, &dwSize
, NULL
);
286 SAFE_CLOSE_HANDLE(Handle
);
291 static int IsUTF8Encode(const char *src
)
294 const UCHAR
*Byte
= (const UCHAR
*)src
;
296 for (i
= 0; i
< MAX_PATH
&& Byte
[i
]; i
++)
307 static int Utf8ToUtf16(const char* src
, WCHAR
* dst
)
309 int size
= MultiByteToWideChar(CP_UTF8
, 0, src
, -1, dst
, 0);
310 return MultiByteToWideChar(CP_UTF8
, 0, src
, -1, dst
, size
+ 1);
313 static BOOL
IsDirExist(const char *Fmt
, ...)
318 CHAR FilePathA
[MAX_PATH
];
319 WCHAR FilePathW
[MAX_PATH
];
322 vsnprintf_s(FilePathA
, sizeof(FilePathA
), sizeof(FilePathA
), Fmt
, Arg
);
325 UTF8
= IsUTF8Encode(FilePathA
);
329 Utf8ToUtf16(FilePathA
, FilePathW
);
330 Attr
= GetFileAttributesW(FilePathW
);
334 Attr
= GetFileAttributesA(FilePathA
);
337 if (Attr
!= INVALID_FILE_ATTRIBUTES
&& (Attr
& FILE_ATTRIBUTE_DIRECTORY
))
345 static BOOL
IsFileExist(const char *Fmt
, ...)
352 CHAR FilePathA
[MAX_PATH
];
353 WCHAR FilePathW
[MAX_PATH
];
356 vsnprintf_s(FilePathA
, sizeof(FilePathA
), sizeof(FilePathA
), Fmt
, Arg
);
359 UTF8
= IsUTF8Encode(FilePathA
);
363 Utf8ToUtf16(FilePathA
, FilePathW
);
364 hFile
= CreateFileW(FilePathW
, FILE_READ_EA
, FILE_SHARE_READ
, 0, OPEN_EXISTING
, 0, 0);
368 hFile
= CreateFileA(FilePathA
, FILE_READ_EA
, FILE_SHARE_READ
, 0, OPEN_EXISTING
, 0, 0);
370 if (INVALID_HANDLE_VALUE
== hFile
)
379 Attr
= GetFileAttributesW(FilePathW
);
383 Attr
= GetFileAttributesA(FilePathA
);
386 if (Attr
& FILE_ATTRIBUTE_DIRECTORY
)
394 Log("File <%s> %s", FilePathA
, (bRet
? "exist" : "NOT exist"));
398 static int GetPhyDiskUUID(const char LogicalDrive
, UINT8
*UUID
, DISK_EXTENT
*DiskExtent
)
403 VOLUME_DISK_EXTENTS DiskExtents
;
405 UINT8 SectorBuf
[512];
407 Log("GetPhyDiskUUID %C", LogicalDrive
);
409 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\%C:", LogicalDrive
);
410 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
411 if (Handle
== INVALID_HANDLE_VALUE
)
413 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
417 Ret
= DeviceIoControl(Handle
,
418 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
422 (DWORD
)(sizeof(DiskExtents
)),
425 if (!Ret
|| DiskExtents
.NumberOfDiskExtents
== 0)
427 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed, error:%u", GetLastError());
433 memcpy(DiskExtent
, DiskExtents
.Extents
, sizeof(DiskExtent
));
434 Log("%C: is in PhysicalDrive%d ", LogicalDrive
, DiskExtents
.Extents
[0].DiskNumber
);
436 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\PhysicalDrive%d", DiskExtents
.Extents
[0].DiskNumber
);
437 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
438 if (Handle
== INVALID_HANDLE_VALUE
)
440 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
444 if (!ReadFile(Handle
, SectorBuf
, sizeof(SectorBuf
), &dwSize
, NULL
))
446 Log("ReadFile failed, dwSize:%u error:%u", dwSize
, GetLastError());
451 memcpy(UUID
, SectorBuf
+ 0x180, 16);
456 static int VentoyMountAnywhere(HANDLE Handle
)
459 ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters
;
461 Log("VentoyMountAnywhere");
463 memset(&AttachParameters
, 0, sizeof(AttachParameters
));
464 AttachParameters
.Version
= ATTACH_VIRTUAL_DISK_VERSION_1
;
466 Status
= AttachVirtualDisk(Handle
, NULL
, ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY
| ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME
, 0, &AttachParameters
, NULL
);
467 if (Status
!= ERROR_SUCCESS
)
469 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
476 int VentoyMountY(HANDLE Handle
)
481 DWORD physicalDriveNameSize
;
483 WCHAR physicalDriveName
[MAX_PATH
];
484 CHAR physicalDriveNameA
[MAX_PATH
];
485 CHAR cdromDriveName
[MAX_PATH
];
486 ATTACH_VIRTUAL_DISK_PARAMETERS AttachParameters
;
490 memset(&AttachParameters
, 0, sizeof(AttachParameters
));
491 AttachParameters
.Version
= ATTACH_VIRTUAL_DISK_VERSION_1
;
493 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
);
494 if (Status
!= ERROR_SUCCESS
)
496 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
500 memset(physicalDriveName
, 0, sizeof(physicalDriveName
));
501 memset(physicalDriveNameA
, 0, sizeof(physicalDriveNameA
));
503 physicalDriveNameSize
= MAX_PATH
;
504 Status
= GetVirtualDiskPhysicalPath(Handle
, &physicalDriveNameSize
, physicalDriveName
);
505 if (Status
!= ERROR_SUCCESS
)
507 Log("Failed GetVirtualDiskPhysicalPath ErrorCode:%u", Status
);
511 for (i
= 0; physicalDriveName
[i
]; i
++)
513 physicalDriveNameA
[i
] = toupper((CHAR
)(physicalDriveName
[i
]));
516 Log("physicalDriveNameA=<%s>", physicalDriveNameA
);
518 Pos
= strstr(physicalDriveNameA
, "CDROM");
521 Log("Not cdrom phy drive");
525 sprintf_s(cdromDriveName
, sizeof(cdromDriveName
), "\\Device\\%s", Pos
);
526 Log("cdromDriveName=<%s>", cdromDriveName
);
528 for (i
= 0; i
< 3 && (bRet
== FALSE
); i
++)
531 bRet
= DefineDosDeviceA(DDD_RAW_TARGET_PATH
, "Y:", cdromDriveName
);
532 Log("DefineDosDeviceA %s", bRet
? "success" : "failed");
538 static BOOL
VentoyNeedMountY(const char *IsoPath
)
544 static int VentoyAttachVirtualDisk(HANDLE Handle
, const char *IsoPath
)
549 Drives
= GetLogicalDrives();
550 if ((1 << 24) & Drives
)
552 Log("Y: is occupied");
557 Log("Y: is free now");
561 if (DriveYFree
&& VentoyNeedMountY(IsoPath
))
563 return VentoyMountY(Handle
);
567 return VentoyMountAnywhere(Handle
);
571 int VentoyMountISOByAPI(const char *IsoPath
)
575 WCHAR wFilePath
[512] = { 0 };
576 VIRTUAL_STORAGE_TYPE StorageType
;
577 OPEN_VIRTUAL_DISK_PARAMETERS OpenParameters
;
579 Log("VentoyMountISOByAPI <%s>", IsoPath
);
581 if (IsUTF8Encode(IsoPath
))
583 MultiByteToWideChar(CP_UTF8
, 0, IsoPath
, (int)strlen(IsoPath
), wFilePath
, (int)(sizeof(wFilePath
) / sizeof(WCHAR
)));
587 MultiByteToWideChar(CP_ACP
, 0, IsoPath
, (int)strlen(IsoPath
), wFilePath
, (int)(sizeof(wFilePath
) / sizeof(WCHAR
)));
590 memset(&StorageType
, 0, sizeof(StorageType
));
591 memset(&OpenParameters
, 0, sizeof(OpenParameters
));
593 OpenParameters
.Version
= OPEN_VIRTUAL_DISK_VERSION_1
;
595 Status
= OpenVirtualDisk(&StorageType
, wFilePath
, VIRTUAL_DISK_ACCESS_READ
, 0, &OpenParameters
, &Handle
);
596 if (Status
!= ERROR_SUCCESS
)
598 if (ERROR_VIRTDISK_PROVIDER_NOT_FOUND
== Status
)
600 Log("VirtualDisk for ISO file is not supported in current system");
604 Log("Failed to open virtual disk ErrorCode:%u", Status
);
609 Log("OpenVirtualDisk success");
611 Status
= VentoyAttachVirtualDisk(Handle
, IsoPath
);
612 if (Status
!= ERROR_SUCCESS
)
614 Log("Failed to attach virtual disk ErrorCode:%u", Status
);
619 Log("VentoyAttachVirtualDisk success");
626 static HANDLE g_FatPhyDrive
;
627 static UINT64 g_Part2StartSec
;
629 static int CopyFileFromFatDisk(const CHAR
* SrcFile
, const CHAR
*DstFile
)
636 Log("CopyFileFromFatDisk (%s)==>(%s)", SrcFile
, DstFile
);
638 flfile
= fl_fopen(SrcFile
, "rb");
641 fl_fseek(flfile
, 0, SEEK_END
);
642 size
= (int)fl_ftell(flfile
);
643 fl_fseek(flfile
, 0, SEEK_SET
);
645 buf
= (char *)malloc(size
);
648 fl_fread(buf
, 1, size
, flfile
);
651 SaveBuffer2File(DstFile
, buf
, size
);
661 static int VentoyFatDiskRead(uint32 Sector
, uint8
*Buffer
, uint32 SectorCount
)
666 LARGE_INTEGER liCurrentPosition
;
668 liCurrentPosition
.QuadPart
= Sector
+ g_Part2StartSec
;
669 liCurrentPosition
.QuadPart
*= 512;
670 SetFilePointerEx(g_FatPhyDrive
, liCurrentPosition
, &liCurrentPosition
, FILE_BEGIN
);
672 ReadSize
= (DWORD
)(SectorCount
* 512);
674 bRet
= ReadFile(g_FatPhyDrive
, Buffer
, ReadSize
, &dwSize
, NULL
);
675 if (bRet
== FALSE
|| dwSize
!= ReadSize
)
677 Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u\n", bRet
, ReadSize
, dwSize
, GetLastError());
683 static CHAR
GetMountLogicalDrive(void)
687 DWORD Mask
= 0x1000000;
689 Drives
= GetLogicalDrives();
690 Log("Drives=0x%x", Drives
);
694 if ((Drives
& Mask
) == 0)
706 UINT64
GetVentoyEfiPartStartSector(HANDLE hDrive
)
711 VTOY_GPT_INFO
*pGpt
= NULL
;
712 UINT64 StartSector
= 0;
714 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
716 bRet
= ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
717 Log("Read MBR Ret:%u Size:%u code:%u", bRet
, dwSize
, LASTERR
);
719 if ((!bRet
) || (dwSize
!= sizeof(MBR
)))
724 if (MBR
.PartTbl
[0].FsFlag
== 0xEE)
726 Log("GPT partition style");
728 pGpt
= malloc(sizeof(VTOY_GPT_INFO
));
734 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
735 bRet
= ReadFile(hDrive
, pGpt
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
);
736 if ((!bRet
) || (dwSize
!= sizeof(VTOY_GPT_INFO
)))
738 Log("Failed to read gpt info %d %u %d", bRet
, dwSize
, LASTERR
);
742 StartSector
= pGpt
->PartTbl
[1].StartLBA
;
747 Log("MBR partition style");
748 StartSector
= MBR
.PartTbl
[1].StartSectorId
;
751 Log("GetVentoyEfiPart StartSector: %llu", StartSector
);
755 int VentoyMountISOByImdisk(const char *IsoPath
, DWORD PhyDrive
)
762 CHAR PhyPath
[MAX_PATH
];
763 WCHAR PhyPathW
[MAX_PATH
];
765 PROCESS_INFORMATION Pi
;
766 GET_LENGTH_INFORMATION LengthInfo
;
768 Log("VentoyMountISOByImdisk %s", IsoPath
);
770 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\PhysicalDrive%d", PhyDrive
);
771 if (IsUTF8Encode(PhyPath
))
773 Utf8ToUtf16(PhyPath
, PhyPathW
);
774 hDrive
= CreateFileW(PhyPathW
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
778 hDrive
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
781 if (hDrive
== INVALID_HANDLE_VALUE
)
783 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
787 bRet
= DeviceIoControl(hDrive
, IOCTL_DISK_GET_LENGTH_INFO
, NULL
, 0, &LengthInfo
, sizeof(LengthInfo
), &dwBytes
, NULL
);
790 Log("Could not get phy disk %s size, error:%u", PhyPath
, GetLastError());
794 g_FatPhyDrive
= hDrive
;
795 g_Part2StartSec
= GetVentoyEfiPartStartSector(hDrive
);
797 Log("Parse FAT fs...");
801 if (0 == fl_attach_media(VentoyFatDiskRead
, NULL
))
805 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.sys", "ventoy\\imdisk.sys");
806 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.exe", "ventoy\\imdisk.exe");
807 CopyFileFromFatDisk("/ventoy/imdisk/64/imdisk.cpl", "ventoy\\imdisk.cpl");
811 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.sys", "ventoy\\imdisk.sys");
812 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.exe", "ventoy\\imdisk.exe");
813 CopyFileFromFatDisk("/ventoy/imdisk/32/imdisk.cpl", "ventoy\\imdisk.cpl");
816 GetCurrentDirectoryA(sizeof(PhyPath
), PhyPath
);
817 strcat_s(PhyPath
, sizeof(PhyPath
), "\\ventoy\\imdisk.sys");
819 if (LoadNtDriver(PhyPath
) == 0)
823 Letter
= GetMountLogicalDrive();
824 sprintf_s(PhyPath
, sizeof(PhyPath
), "ventoy\\imdisk.exe -a -o ro -f %s -m %C:", IsoPath
, Letter
);
826 Log("mount iso to %C: use imdisk cmd <%s>", Letter
, PhyPath
);
828 GetStartupInfoA(&Si
);
830 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
831 Si
.wShowWindow
= SW_HIDE
;
833 CreateProcessA(NULL
, PhyPath
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
834 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
841 SAFE_CLOSE_HANDLE(hDrive
);
846 static int MountIsoFile(CONST CHAR
*IsoPath
, DWORD PhyDrive
)
848 if (IsWindows8OrGreater())
850 Log("This is Windows 8 or latter...");
851 if (VentoyMountISOByAPI(IsoPath
) == 0)
853 Log("Mount iso by API success");
858 Log("Mount iso by API failed, maybe not supported, try imdisk");
859 return VentoyMountISOByImdisk(IsoPath
, PhyDrive
);
864 Log("This is before Windows 8 ...");
865 if (VentoyMountISOByImdisk(IsoPath
, PhyDrive
) == 0)
867 Log("Mount iso by imdisk success");
872 return VentoyMountISOByAPI(IsoPath
);
877 static int GetPhyDriveByLogicalDrive(int DriveLetter
)
882 VOLUME_DISK_EXTENTS DiskExtents
;
885 sprintf_s(PhyPath
, sizeof(PhyPath
), "\\\\.\\%C:", (CHAR
)DriveLetter
);
887 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
888 if (Handle
== INVALID_HANDLE_VALUE
)
890 Log("Could not open the disk<%s>, error:%u", PhyPath
, GetLastError());
894 Ret
= DeviceIoControl(Handle
,
895 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
899 (DWORD
)(sizeof(DiskExtents
)),
903 if (!Ret
|| DiskExtents
.NumberOfDiskExtents
== 0)
905 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath
, GetLastError());
906 SAFE_CLOSE_HANDLE(Handle
);
909 SAFE_CLOSE_HANDLE(Handle
);
911 Log("LogicalDrive:%s PhyDrive:%d Offset:%llu ExtentLength:%llu",
913 DiskExtents
.Extents
[0].DiskNumber
,
914 DiskExtents
.Extents
[0].StartingOffset
.QuadPart
,
915 DiskExtents
.Extents
[0].ExtentLength
.QuadPart
918 return (int)DiskExtents
.Extents
[0].DiskNumber
;
922 static int DeleteVentoyPart2MountPoint(DWORD PhyDrive
)
927 CHAR DriveName
[] = "?:\\";
929 Log("DeleteVentoyPart2MountPoint Phy%u ...", PhyDrive
);
931 Drives
= GetLogicalDrives();
934 if ((Drives
& 0x01) && IsFileExist("%C:\\ventoy\\ventoy.cpio", Letter
))
936 Log("File %C:\\ventoy\\ventoy.cpio exist", Letter
);
938 PhyDisk
= GetPhyDriveByLogicalDrive(Letter
);
939 Log("PhyDisk=%u for %C", PhyDisk
, Letter
);
941 if (PhyDisk
== PhyDrive
)
943 DriveName
[0] = Letter
;
944 DeleteVolumeMountPointA(DriveName
);
956 static BOOL
check_tar_archive(const char *archive
, CHAR
*tarName
)
960 const char *pos
= archive
;
961 const char *slash
= archive
;
965 if (*pos
== '\\' || *pos
== '/')
972 len
= (int)strlen(slash
);
974 if (len
> 7 && (strncmp(slash
+ len
- 7, ".tar.gz", 7) == 0 || strncmp(slash
+ len
- 7, ".tar.xz", 7) == 0))
976 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
977 tarName
[nameLen
- 3] = 0;
980 else if (len
> 8 && strncmp(slash
+ len
- 8, ".tar.bz2", 8) == 0)
982 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
983 tarName
[nameLen
- 4] = 0;
986 else if (len
> 9 && strncmp(slash
+ len
- 9, ".tar.lzma", 9) == 0)
988 nameLen
= (int)sprintf_s(tarName
, MAX_PATH
, "X:%s", slash
);
989 tarName
[nameLen
- 5] = 0;
996 static int DecompressInjectionArchive(const char *archive
, DWORD PhyDrive
)
1003 DWORD flags
= CREATE_NO_WINDOW
;
1004 CHAR StrBuf
[MAX_PATH
];
1005 CHAR tarName
[MAX_PATH
];
1007 PROCESS_INFORMATION Pi
;
1008 PROCESS_INFORMATION NewPi
;
1009 GET_LENGTH_INFORMATION LengthInfo
;
1010 SECURITY_ATTRIBUTES Sa
= { sizeof(SECURITY_ATTRIBUTES
), NULL
, TRUE
};
1012 Log("DecompressInjectionArchive %s", archive
);
1014 sprintf_s(StrBuf
, sizeof(StrBuf
), "\\\\.\\PhysicalDrive%d", PhyDrive
);
1015 hDrive
= CreateFileA(StrBuf
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
1016 if (hDrive
== INVALID_HANDLE_VALUE
)
1018 Log("Could not open the disk<%s>, error:%u", StrBuf
, GetLastError());
1022 bRet
= DeviceIoControl(hDrive
, IOCTL_DISK_GET_LENGTH_INFO
, NULL
, 0, &LengthInfo
, sizeof(LengthInfo
), &dwBytes
, NULL
);
1025 Log("Could not get phy disk %s size, error:%u", StrBuf
, GetLastError());
1029 g_FatPhyDrive
= hDrive
;
1030 g_Part2StartSec
= GetVentoyEfiPartStartSector(hDrive
);
1032 Log("Parse FAT fs...");
1036 if (0 == fl_attach_media(VentoyFatDiskRead
, NULL
))
1040 CopyFileFromFatDisk("/ventoy/7z/64/7za.exe", "ventoy\\7za.exe");
1044 CopyFileFromFatDisk("/ventoy/7z/32/7za.exe", "ventoy\\7za.exe");
1047 sprintf_s(StrBuf
, sizeof(StrBuf
), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", archive
);
1049 Log("extract inject to X:");
1050 Log("cmdline:<%s>", StrBuf
);
1052 GetStartupInfoA(&Si
);
1054 hOut
= CreateFileA("ventoy\\7z.log",
1056 FILE_SHARE_WRITE
| FILE_SHARE_READ
,
1059 FILE_ATTRIBUTE_NORMAL
,
1062 Si
.dwFlags
|= STARTF_USESTDHANDLES
;
1064 if (hOut
!= INVALID_HANDLE_VALUE
)
1066 Si
.hStdError
= hOut
;
1067 Si
.hStdOutput
= hOut
;
1070 CreateProcessA(NULL
, StrBuf
, NULL
, NULL
, TRUE
, flags
, NULL
, NULL
, &Si
, &Pi
);
1071 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
1074 // decompress tar archive, for tar.gz/tar.xz/tar.bz2
1076 if (check_tar_archive(archive
, tarName
))
1078 Log("Decompress tar archive...<%s>", tarName
);
1080 sprintf_s(StrBuf
, sizeof(StrBuf
), "ventoy\\7za.exe x -y -aoa -oX:\\ %s", tarName
);
1082 CreateProcessA(NULL
, StrBuf
, NULL
, NULL
, TRUE
, flags
, NULL
, NULL
, &Si
, &NewPi
);
1083 WaitForSingleObject(NewPi
.hProcess
, INFINITE
);
1085 Log("Now delete %s", tarName
);
1086 DeleteFileA(tarName
);
1089 SAFE_CLOSE_HANDLE(hOut
);
1095 SAFE_CLOSE_HANDLE(hDrive
);
1100 static int ProcessUnattendedInstallation(const char *script
)
1106 CHAR CurDir
[MAX_PATH
];
1108 Log("Copy unattended XML ...");
1110 GetCurrentDirectory(sizeof(CurDir
), CurDir
);
1112 if ((Letter
>= 'A' && Letter
<= 'Z') || (Letter
>= 'a' && Letter
<= 'z'))
1114 Log("Current Drive Letter: %C", Letter
);
1121 sprintf_s(CurDir
, sizeof(CurDir
), "%C:\\Autounattend.xml", Letter
);
1122 Log("Copy file <%s> --> <%s>", script
, CurDir
);
1123 CopyFile(script
, CurDir
, FALSE
);
1125 Ret
= RegCreateKeyEx(HKEY_LOCAL_MACHINE
, "System\\Setup", 0, NULL
, REG_OPTION_NON_VOLATILE
, KEY_ALL_ACCESS
, NULL
, &hKey
, &dw
);
1126 if (ERROR_SUCCESS
== Ret
)
1128 Ret
= RegSetValueEx(hKey
, "UnattendFile", 0, REG_SZ
, CurDir
, (DWORD
)(strlen(CurDir
) + 1));
1134 static int VentoyHook(ventoy_os_param
*param
)
1138 DISK_EXTENT DiskExtent
;
1139 DWORD Drives
= GetLogicalDrives();
1141 CHAR IsoPath
[MAX_PATH
];
1143 Log("Logical Drives=0x%x Path:<%s>", Drives
, param
->vtoy_img_path
);
1145 if (IsUTF8Encode(param
->vtoy_img_path
))
1147 Log("This file is UTF8 encoding\n");
1154 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:\\%s", Letter
, param
->vtoy_img_path
);
1155 if (IsFileExist("%s", IsoPath
))
1157 Log("File exist under %C:", Letter
);
1158 if (GetPhyDiskUUID(Letter
, UUID
, &DiskExtent
) == 0)
1160 if (memcmp(UUID
, param
->vtoy_disk_guid
, 16) == 0)
1162 Log("Disk UUID match");
1169 Log("File NOT exist under %C:", Letter
);
1179 Log("Failed to find ISO file");
1183 Log("Find ISO file <%s>", IsoPath
);
1185 rc
= MountIsoFile(IsoPath
, DiskExtent
.DiskNumber
);
1186 Log("Mount ISO FILE: %s", rc
== 0 ? "SUCCESS" : "FAILED");
1189 rc
= DeleteVentoyPart2MountPoint(DiskExtent
.DiskNumber
);
1190 Log("Delete ventoy mountpoint: %s", rc
== 0 ? "SUCCESS" : "NO NEED");
1192 if (g_windows_data
.auto_install_script
[0])
1194 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:%s", Letter
, g_windows_data
.auto_install_script
);
1195 if (IsFileExist("%s", IsoPath
))
1197 Log("use auto install script %s...", IsoPath
);
1198 ProcessUnattendedInstallation(IsoPath
);
1202 Log("auto install script %s not exist", IsoPath
);
1207 Log("auto install no need");
1210 if (g_windows_data
.injection_archive
[0])
1212 sprintf_s(IsoPath
, sizeof(IsoPath
), "%C:%s", Letter
, g_windows_data
.injection_archive
);
1213 if (IsFileExist("%s", IsoPath
))
1215 Log("decompress injection archive %s...", IsoPath
);
1216 DecompressInjectionArchive(IsoPath
, DiskExtent
.DiskNumber
);
1220 Log("injection archive %s not exist", IsoPath
);
1225 Log("no injection archive found");
1231 const char * GetFileNameInPath(const char *fullpath
)
1234 const char *pos
= NULL
;
1236 if (strstr(fullpath
, ":"))
1238 for (i
= (int)strlen(fullpath
); i
> 0; i
--)
1240 if (fullpath
[i
- 1] == '/' || fullpath
[i
- 1] == '\\')
1242 return fullpath
+ i
;
1250 int VentoyJumpWimboot(INT argc
, CHAR
**argv
, CHAR
*LunchFile
)
1258 g_64bit_system
= FALSE
;
1260 g_64bit_system
= TRUE
;
1263 Log("VentoyJumpWimboot %dbit", g_64bit_system
? 64 : 32);
1265 sprintf_s(LunchFile
, MAX_PATH
, "X:\\setup.exe");
1267 ReadWholeFile2Buf("wimboot.data", &buf
, &size
);
1268 Log("wimboot.data size:%d", size
);
1270 memcpy(&g_os_param
, buf
, sizeof(ventoy_os_param
));
1271 memcpy(&g_windows_data
, buf
+ sizeof(ventoy_os_param
), sizeof(ventoy_windows_data
));
1272 memcpy(g_os_param_reserved
, g_os_param
.vtoy_reserved
, sizeof(g_os_param_reserved
));
1274 if (g_os_param_reserved
[0] == 1)
1276 Log("break here for debug .....");
1281 for (Pos
= 0; Pos
< sizeof(g_os_param
.vtoy_img_path
) && g_os_param
.vtoy_img_path
[Pos
]; Pos
++)
1283 if (g_os_param
.vtoy_img_path
[Pos
] == '/')
1285 g_os_param
.vtoy_img_path
[Pos
] = '\\';
1289 if (g_os_param_reserved
[0] == 2)
1291 Log("skip hook for debug .....");
1296 rc
= VentoyHook(&g_os_param
);
1308 int VentoyJump(INT argc
, CHAR
**argv
, CHAR
*LunchFile
)
1314 BYTE
*Buffer
= NULL
;
1315 CHAR ExeFileName
[MAX_PATH
];
1317 sprintf_s(ExeFileName
, sizeof(ExeFileName
), "%s", argv
[0]);
1318 if (!IsFileExist("%s", ExeFileName
))
1320 Log("File %s NOT exist, now try %s.exe", ExeFileName
, ExeFileName
);
1321 sprintf_s(ExeFileName
, sizeof(ExeFileName
), "%s.exe", argv
[0]);
1323 Log("File %s exist ? %s", ExeFileName
, IsFileExist("%s", ExeFileName
) ? "YES" : "NO");
1326 if (ReadWholeFile2Buf(ExeFileName
, (void **)&Buffer
, &FileSize
))
1331 g_64bit_system
= IsPe64(Buffer
);
1332 Log("VentoyJump %dbit", g_64bit_system
? 64 : 32);
1334 if (IsDirExist("ventoy"))
1336 Log("ventoy directory already exist");
1340 Log("ventoy directory not exist, now create it.");
1341 if (!CreateDirectoryA("ventoy", NULL
))
1343 Log("Failed to create ventoy directory err:%u", GetLastError());
1348 for (PeStart
= 0; PeStart
< FileSize
; PeStart
+= 16)
1350 if (CheckOsParam((ventoy_os_param
*)(Buffer
+ PeStart
)) &&
1351 CheckPeHead(Buffer
+ PeStart
+ sizeof(ventoy_os_param
) + sizeof(ventoy_windows_data
)))
1353 Log("Find os pararm at %u", PeStart
);
1355 memcpy(&g_os_param
, Buffer
+ PeStart
, sizeof(ventoy_os_param
));
1356 memcpy(&g_windows_data
, Buffer
+ PeStart
+ sizeof(ventoy_os_param
), sizeof(ventoy_windows_data
));
1357 memcpy(g_os_param_reserved
, g_os_param
.vtoy_reserved
, sizeof(g_os_param_reserved
));
1359 if (g_os_param_reserved
[0] == 1)
1361 Log("break here for debug .....");
1366 for (Pos
= 0; Pos
< sizeof(g_os_param
.vtoy_img_path
) && g_os_param
.vtoy_img_path
[Pos
]; Pos
++)
1368 if (g_os_param
.vtoy_img_path
[Pos
] == '/')
1370 g_os_param
.vtoy_img_path
[Pos
] = '\\';
1374 PeStart
+= sizeof(ventoy_os_param
) + sizeof(ventoy_windows_data
);
1375 sprintf_s(LunchFile
, MAX_PATH
, "ventoy\\%s", GetFileNameInPath(ExeFileName
));
1377 if (IsFileExist("%s", LunchFile
))
1379 Log("vtoyjump multiple call...");
1384 SaveBuffer2File(LunchFile
, Buffer
+ PeStart
, FileSize
- PeStart
);
1389 if (PeStart
>= FileSize
)
1391 Log("OS param not found");
1395 if (g_os_param_reserved
[0] == 2)
1397 Log("skip hook for debug .....");
1402 rc
= VentoyHook(&g_os_param
);
1414 int main(int argc
, char **argv
)
1419 CHAR CurDir
[MAX_PATH
];
1420 CHAR LunchFile
[MAX_PATH
];
1421 CHAR CallParam
[1024] = { 0 };
1423 PROCESS_INFORMATION Pi
;
1425 if (argv
[0] && argv
[0][0] && argv
[0][1] == ':')
1427 GetCurrentDirectoryA(sizeof(CurDir
), CurDir
);
1429 strcpy_s(LunchFile
, sizeof(LunchFile
), argv
[0]);
1430 Pos
= (char *)GetFileNameInPath(LunchFile
);
1432 strcat_s(CurDir
, sizeof(CurDir
), "\\");
1433 strcat_s(CurDir
, sizeof(CurDir
), Pos
);
1435 if (_stricmp(argv
[0], CurDir
) != 0)
1438 SetCurrentDirectoryA(LunchFile
);
1442 Log("######## VentoyJump ##########");
1443 Log("argc = %d", argc
);
1444 for (i
= 0; i
< argc
; i
++)
1446 Log("argv[%d]=<%s>", i
, argv
[i
]);
1449 strcat_s(CallParam
, sizeof(CallParam
), " ");
1450 strcat_s(CallParam
, sizeof(CallParam
), argv
[i
]);
1454 if (Pos
&& *Pos
== 0)
1456 Log("Old current directory = <%s>", CurDir
);
1457 Log("New current directory = <%s>", LunchFile
);
1461 GetCurrentDirectoryA(sizeof(CurDir
), CurDir
);
1462 Log("Current directory = <%s>", CurDir
);
1465 GetStartupInfoA(&Si
);
1467 memset(LunchFile
, 0, sizeof(LunchFile
));
1469 if (strstr(argv
[0], "vtoyjump.exe"))
1471 rc
= VentoyJumpWimboot(argc
, argv
, LunchFile
);
1475 rc
= VentoyJump(argc
, argv
, LunchFile
);
1478 Log("LunchFile=<%s> CallParam=<%s>", LunchFile
, CallParam
);
1480 if (_stricmp(argv
[0], "PECMD.EXE") == 0 && _stricmp(LunchFile
, "ventoy\\PECMD.EXE") == 0)
1482 MoveFileA("PECMD.EXE", "PECMD_BACK.EXE");
1483 MoveFileA("ventoy\\PECMD.EXE", "PECMD.EXE");
1484 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", "PECMD.EXE");
1485 Log("Move original PECMD.EXE <%s>", LunchFile
);
1488 if (g_os_param_reserved
[0] == 3)
1490 Log("Open log for debug ...");
1491 sprintf_s(LunchFile
, sizeof(LunchFile
), "%s", "notepad.exe ventoy.log");
1497 strcat_s(LunchFile
, sizeof(LunchFile
), CallParam
);
1499 else if (NULL
== strstr(LunchFile
, "setup.exe"))
1501 Log("Not setup.exe, hide windows.");
1502 Si
.dwFlags
|= STARTF_USESHOWWINDOW
;
1503 Si
.wShowWindow
= SW_HIDE
;
1506 Log("Ventoy jump %s ...", rc
== 0 ? "success" : "failed");
1509 Log("Now launch <%s> ...", LunchFile
);
1511 //sprintf_s(LunchFile, sizeof(LunchFile), "%s", "cmd.exe");
1512 CreateProcessA(NULL
, LunchFile
, NULL
, NULL
, FALSE
, 0, NULL
, NULL
, &Si
, &Pi
);
1514 for (i
= 0; rc
&& i
< 1800; i
++)
1516 Log("Ventoy hook failed, now wait and retry ...");
1518 rc
= VentoyHook(&g_os_param
);
1521 Log("Wait process...");
1522 WaitForSingleObject(Pi
.hProcess
, INFINITE
);
1524 Log("vtoyjump finished");