1 /******************************************************************************
4 * Copyright (c) 2020, longpanda <admin@ventoy.net>
5 * Copyright (c) 2011-2020, Pete Batard <pete@akeo.ie>
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation; either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, see <http://www.gnu.org/licenses/>.
29 #include "Ventoy2Disk.h"
30 #include "fat_filelib.h"
32 #include "DiskService.h"
34 static int g_backup_bin_index
= 0;
37 static BOOL
WriteDataToPhyDisk(HANDLE hDrive
, UINT64 Offset
, VOID
*buffer
, DWORD len
)
41 LARGE_INTEGER liCurPosition
;
42 LARGE_INTEGER liNewPosition
;
44 liCurPosition
.QuadPart
= (LONGLONG
)Offset
;
45 liNewPosition
.QuadPart
= 0;
46 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
47 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
49 Log("SetFilePointerEx Failed %u", LASTERR
);
53 bRet
= WriteFile(hDrive
, buffer
, len
, &dwSize
, NULL
);
54 if (bRet
== FALSE
|| dwSize
!= len
)
56 Log("Write file error %u %u", dwSize
, LASTERR
);
64 static DWORD
GetVentoyVolumeName(int PhyDrive
, UINT64 StartSectorId
, CHAR
*NameBuf
, UINT32 BufLen
, BOOL DelSlash
)
72 DWORD Status
= ERROR_NOT_FOUND
;
73 DISK_EXTENT
*pExtents
= NULL
;
74 CHAR VolumeName
[MAX_PATH
] = { 0 };
75 VOLUME_DISK_EXTENTS DiskExtents
;
77 PartOffset
= 512ULL * StartSectorId
;
79 Log("GetVentoyVolumeName PhyDrive %d SectorStart:%llu PartOffset:%llu", PhyDrive
, (ULONGLONG
)StartSectorId
, (ULONGLONG
)PartOffset
);
81 hVolume
= FindFirstVolumeA(VolumeName
, sizeof(VolumeName
));
82 if (hVolume
== INVALID_HANDLE_VALUE
)
89 len
= strlen(VolumeName
);
90 Log("Find volume:%s", VolumeName
);
92 VolumeName
[len
- 1] = 0;
94 hDrive
= CreateFileA(VolumeName
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, NULL
);
95 if (hDrive
== INVALID_HANDLE_VALUE
)
100 bRet
= DeviceIoControl(hDrive
,
101 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
105 (DWORD
)(sizeof(DiskExtents
)),
109 Log("IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS bRet:%u code:%u", bRet
, LASTERR
);
110 Log("NumberOfDiskExtents:%u DiskNumber:%u", DiskExtents
.NumberOfDiskExtents
, DiskExtents
.Extents
[0].DiskNumber
);
112 if (bRet
&& DiskExtents
.NumberOfDiskExtents
== 1)
114 pExtents
= DiskExtents
.Extents
;
116 Log("This volume DiskNumber:%u offset:%llu", pExtents
->DiskNumber
, (ULONGLONG
)pExtents
->StartingOffset
.QuadPart
);
117 if ((int)pExtents
->DiskNumber
== PhyDrive
&& pExtents
->StartingOffset
.QuadPart
== PartOffset
)
119 Log("This volume match");
123 VolumeName
[len
- 1] = '\\';
126 sprintf_s(NameBuf
, BufLen
, "%s", VolumeName
);
127 Status
= ERROR_SUCCESS
;
134 } while (FindNextVolumeA(hVolume
, VolumeName
, sizeof(VolumeName
)));
136 FindVolumeClose(hVolume
);
138 Log("GetVentoyVolumeName return %u", Status
);
142 static int GetLettersBelongPhyDrive(int PhyDrive
, char *DriveLetters
, size_t Length
)
147 CHAR
*StringBuf
= NULL
;
149 DataSize
= GetLogicalDriveStringsA(0, NULL
);
150 StringBuf
= (CHAR
*)malloc(DataSize
+ 1);
151 if (StringBuf
== NULL
)
156 GetLogicalDriveStringsA(DataSize
, StringBuf
);
158 for (Pos
= StringBuf
; *Pos
; Pos
+= strlen(Pos
) + 1)
160 if (n
< (int)Length
&& PhyDrive
== GetPhyDriveByLogicalDrive(Pos
[0], NULL
))
162 Log("%C: is belong to phydrive%d", Pos
[0], PhyDrive
);
163 DriveLetters
[n
++] = Pos
[0];
171 HANDLE
GetPhysicalHandle(int Drive
, BOOLEAN bLockDrive
, BOOLEAN bWriteAccess
, BOOLEAN bWriteShare
)
177 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
179 CHAR DevPath
[MAX_PATH
] = { 0 };
181 safe_sprintf(PhyDrive
, "\\\\.\\PhysicalDrive%d", Drive
);
183 if (0 == QueryDosDeviceA(PhyDrive
+ 4, DevPath
, sizeof(DevPath
)))
185 Log("QueryDosDeviceA failed error:%u", GetLastError());
186 strcpy_s(DevPath
, sizeof(DevPath
), "???");
190 Log("QueryDosDeviceA success %s", DevPath
);
193 for (i
= 0; i
< DRIVE_ACCESS_RETRIES
; i
++)
195 // Try without FILE_SHARE_WRITE (unless specifically requested) so that
196 // we won't be bothered by the OS or other apps when we set up our data.
197 // However this means we might have to wait for an access gap...
198 // We keep FILE_SHARE_READ though, as this shouldn't hurt us any, and is
199 // required for enumeration.
200 hDrive
= CreateFileA(PhyDrive
,
201 GENERIC_READ
| (bWriteAccess
? GENERIC_WRITE
: 0),
202 FILE_SHARE_READ
| (bWriteShare
? FILE_SHARE_WRITE
: 0),
205 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_NO_BUFFERING
| FILE_FLAG_WRITE_THROUGH
,
208 LastError
= GetLastError();
209 Log("[%d] CreateFileA %s code:%u %p", i
, PhyDrive
, LastError
, hDrive
);
211 if (hDrive
!= INVALID_HANDLE_VALUE
)
216 if ((LastError
!= ERROR_SHARING_VIOLATION
) && (LastError
!= ERROR_ACCESS_DENIED
))
223 Log("Waiting for access on %s [%s]...", PhyDrive
, DevPath
);
225 else if (!bWriteShare
&& (i
> DRIVE_ACCESS_RETRIES
/ 3))
227 // If we can't seem to get a hold of the drive for some time, try to enable FILE_SHARE_WRITE...
228 Log("Warning: Could not obtain exclusive rights. Retrying with write sharing enabled...");
231 // Try to report the process that is locking the drive
232 // We also use bit 6 as a flag to indicate that SearchProcess was called.
233 //access_mask = SearchProcess(DevPath, SEARCH_PROCESS_TIMEOUT, TRUE, TRUE, FALSE) | 0x40;
236 Sleep(DRIVE_ACCESS_TIMEOUT
/ DRIVE_ACCESS_RETRIES
);
239 if (hDrive
== INVALID_HANDLE_VALUE
)
241 Log("Could not open %s %u", PhyDrive
, LASTERR
);
247 Log("Opened %s for %s write access", PhyDrive
, bWriteShare
? "shared" : "exclusive");
252 if (DeviceIoControl(hDrive
, FSCTL_ALLOW_EXTENDED_DASD_IO
, NULL
, 0, NULL
, 0, &dwSize
, NULL
))
254 Log("I/O boundary checks disabled");
257 EndTime
= GetTickCount64() + DRIVE_ACCESS_TIMEOUT
;
260 if (DeviceIoControl(hDrive
, FSCTL_LOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
))
262 Log("FSCTL_LOCK_VOLUME success");
265 Sleep(DRIVE_ACCESS_TIMEOUT
/ DRIVE_ACCESS_RETRIES
);
266 } while (GetTickCount64() < EndTime
);
268 // If we reached this section, either we didn't manage to get a lock or the user cancelled
269 Log("Could not lock access to %s %u", PhyDrive
, LASTERR
);
271 // See if we can report the processes are accessing the drive
272 //if (!IS_ERROR(FormatStatus) && (access_mask == 0))
273 // access_mask = SearchProcess(DevPath, SEARCH_PROCESS_TIMEOUT, TRUE, TRUE, FALSE);
274 // Try to continue if the only access rights we saw were for read-only
275 //if ((access_mask & 0x07) != 0x01)
276 // safe_closehandle(hDrive);
278 CHECK_CLOSE_HANDLE(hDrive
);
283 if (hDrive
== INVALID_HANDLE_VALUE
)
285 Log("Can get handle of %s, maybe some process control it.", DevPath
);
291 int GetPhyDriveByLogicalDrive(int DriveLetter
, UINT64
*Offset
)
295 HANDLE Handle
= INVALID_HANDLE_VALUE
;
296 VOLUME_DISK_EXTENTS DiskExtents
;
299 safe_sprintf(PhyPath
, "\\\\.\\%C:", (CHAR
)DriveLetter
);
301 Handle
= CreateFileA(PhyPath
, GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, 0, OPEN_EXISTING
, 0, 0);
302 if (Handle
== INVALID_HANDLE_VALUE
)
304 Log("Could not open the disk<%s>, error:%u", PhyPath
, LASTERR
);
308 memset(&DiskExtents
, 0, sizeof(DiskExtents
));
309 Ret
= DeviceIoControl(Handle
,
310 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
314 (DWORD
)(sizeof(DiskExtents
)),
318 if (!Ret
|| DiskExtents
.NumberOfDiskExtents
== 0)
320 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath
, LASTERR
);
321 CHECK_CLOSE_HANDLE(Handle
);
324 CHECK_CLOSE_HANDLE(Handle
);
326 Log("LogicalDrive:%s PhyDrive:%d Num:%d Offset:%llu ExtentLength:%llu",
328 DiskExtents
.Extents
[0].DiskNumber
,
329 DiskExtents
.NumberOfDiskExtents
,
330 DiskExtents
.Extents
[0].StartingOffset
.QuadPart
,
331 DiskExtents
.Extents
[0].ExtentLength
.QuadPart
336 *Offset
= (UINT64
)(DiskExtents
.Extents
[0].StartingOffset
.QuadPart
);
339 return (int)DiskExtents
.Extents
[0].DiskNumber
;
342 int GetAllPhysicalDriveInfo(PHY_DRIVE_INFO
*pDriveList
, DWORD
*pDriveCount
)
350 DWORD DriveCount
= 0;
351 HANDLE Handle
= INVALID_HANDLE_VALUE
;
353 PHY_DRIVE_INFO
*CurDrive
= pDriveList
;
354 GET_LENGTH_INFORMATION LengthInfo
;
355 STORAGE_PROPERTY_QUERY Query
;
356 STORAGE_DESCRIPTOR_HEADER DevDescHeader
;
357 STORAGE_DEVICE_DESCRIPTOR
*pDevDesc
;
358 int PhyDriveId
[VENTOY_MAX_PHY_DRIVE
];
360 Count
= GetPhysicalDriveCount();
362 for (i
= 0; i
< Count
&& i
< VENTOY_MAX_PHY_DRIVE
; i
++)
367 dwBytes
= GetLogicalDrives();
368 Log("Logical Drives: 0x%x", dwBytes
);
373 id
= GetPhyDriveByLogicalDrive(Letter
, NULL
);
374 Log("%C --> %d", Letter
, id
);
377 for (i
= 0; i
< Count
; i
++)
379 if (PhyDriveId
[i
] == id
)
387 Log("Add phy%d to list", i
);
388 PhyDriveId
[Count
] = id
;
398 for (i
= 0; i
< Count
&& DriveCount
< VENTOY_MAX_PHY_DRIVE
; i
++)
400 CHECK_CLOSE_HANDLE(Handle
);
402 safe_sprintf(PhyDrive
, "\\\\.\\PhysicalDrive%d", PhyDriveId
[i
]);
403 Handle
= CreateFileA(PhyDrive
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, NULL
);
404 Log("Create file Handle:%p %s status:%u", Handle
, PhyDrive
, LASTERR
);
406 if (Handle
== INVALID_HANDLE_VALUE
)
411 bRet
= DeviceIoControl(Handle
,
412 IOCTL_DISK_GET_LENGTH_INFO
, NULL
,
420 Log("DeviceIoControl IOCTL_DISK_GET_LENGTH_INFO failed error:%u", LASTERR
);
424 Log("PHYSICALDRIVE%d size %llu bytes", i
, (ULONGLONG
)LengthInfo
.Length
.QuadPart
);
426 Query
.PropertyId
= StorageDeviceProperty
;
427 Query
.QueryType
= PropertyStandardQuery
;
429 bRet
= DeviceIoControl(Handle
,
430 IOCTL_STORAGE_QUERY_PROPERTY
,
434 sizeof(STORAGE_DESCRIPTOR_HEADER
),
439 Log("DeviceIoControl1 error:%u dwBytes:%u", LASTERR
, dwBytes
);
443 if (DevDescHeader
.Size
< sizeof(STORAGE_DEVICE_DESCRIPTOR
))
445 Log("Invalid DevDescHeader.Size:%u", DevDescHeader
.Size
);
449 pDevDesc
= (STORAGE_DEVICE_DESCRIPTOR
*)malloc(DevDescHeader
.Size
);
452 Log("failed to malloc error:%u len:%u", LASTERR
, DevDescHeader
.Size
);
456 bRet
= DeviceIoControl(Handle
,
457 IOCTL_STORAGE_QUERY_PROPERTY
,
466 Log("DeviceIoControl2 error:%u dwBytes:%u", LASTERR
, dwBytes
);
471 CurDrive
->PhyDrive
= i
;
472 CurDrive
->SizeInBytes
= LengthInfo
.Length
.QuadPart
;
473 CurDrive
->DeviceType
= pDevDesc
->DeviceType
;
474 CurDrive
->RemovableMedia
= pDevDesc
->RemovableMedia
;
475 CurDrive
->BusType
= pDevDesc
->BusType
;
477 if (pDevDesc
->VendorIdOffset
)
479 safe_strcpy(CurDrive
->VendorId
, (char *)pDevDesc
+ pDevDesc
->VendorIdOffset
);
480 TrimString(CurDrive
->VendorId
);
483 if (pDevDesc
->ProductIdOffset
)
485 safe_strcpy(CurDrive
->ProductId
, (char *)pDevDesc
+ pDevDesc
->ProductIdOffset
);
486 TrimString(CurDrive
->ProductId
);
489 if (pDevDesc
->ProductRevisionOffset
)
491 safe_strcpy(CurDrive
->ProductRev
, (char *)pDevDesc
+ pDevDesc
->ProductRevisionOffset
);
492 TrimString(CurDrive
->ProductRev
);
495 if (pDevDesc
->SerialNumberOffset
)
497 safe_strcpy(CurDrive
->SerialNumber
, (char *)pDevDesc
+ pDevDesc
->SerialNumberOffset
);
498 TrimString(CurDrive
->SerialNumber
);
506 CHECK_CLOSE_HANDLE(Handle
);
509 for (i
= 0, CurDrive
= pDriveList
; i
< (int)DriveCount
; i
++, CurDrive
++)
511 Log("PhyDrv:%d BusType:%-4s Removable:%u Size:%dGB(%llu) Name:%s %s",
512 CurDrive
->PhyDrive
, GetBusTypeString(CurDrive
->BusType
), CurDrive
->RemovableMedia
,
513 GetHumanReadableGBSize(CurDrive
->SizeInBytes
), CurDrive
->SizeInBytes
,
514 CurDrive
->VendorId
, CurDrive
->ProductId
);
517 *pDriveCount
= DriveCount
;
523 static HANDLE g_FatPhyDrive
;
524 static UINT64 g_Part2StartSec
;
525 static int GetVentoyVersionFromFatFile(CHAR
*VerBuf
, size_t BufLen
)
532 flfile
= fl_fopen("/grub/grub.cfg", "rb");
535 fl_fseek(flfile
, 0, SEEK_END
);
536 size
= (int)fl_ftell(flfile
);
538 fl_fseek(flfile
, 0, SEEK_SET
);
540 buf
= (char *)malloc(size
+ 1);
543 fl_fread(buf
, 1, size
, flfile
);
547 sprintf_s(VerBuf
, BufLen
, "%s", ParseVentoyVersionFromString(buf
));
557 static int VentoyFatDiskRead(uint32 Sector
, uint8
*Buffer
, uint32 SectorCount
)
562 LARGE_INTEGER liCurrentPosition
;
564 liCurrentPosition
.QuadPart
= Sector
+ g_Part2StartSec
;
565 liCurrentPosition
.QuadPart
*= 512;
566 SetFilePointerEx(g_FatPhyDrive
, liCurrentPosition
, &liCurrentPosition
, FILE_BEGIN
);
568 ReadSize
= (DWORD
)(SectorCount
* 512);
570 bRet
= ReadFile(g_FatPhyDrive
, Buffer
, ReadSize
, &dwSize
, NULL
);
571 if (bRet
== FALSE
|| dwSize
!= ReadSize
)
573 Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u\n", bRet
, ReadSize
, dwSize
, LASTERR
);
580 int GetVentoyVerInPhyDrive(const PHY_DRIVE_INFO
*pDriveInfo
, UINT64 Part2StartSector
, CHAR
*VerBuf
, size_t BufLen
, BOOL
*pSecureBoot
)
586 hDrive
= GetPhysicalHandle(pDriveInfo
->PhyDrive
, FALSE
, FALSE
, FALSE
);
587 if (hDrive
== INVALID_HANDLE_VALUE
)
592 g_FatPhyDrive
= hDrive
;
593 g_Part2StartSec
= Part2StartSector
;
595 Log("Parse FAT fs...");
599 if (0 == fl_attach_media(VentoyFatDiskRead
, NULL
))
601 Log("attach media success...");
602 rc
= GetVentoyVersionFromFatFile(VerBuf
, BufLen
);
606 Log("attach media failed...");
610 Log("GetVentoyVerInPhyDrive rc=%d...", rc
);
613 Log("VentoyVerInPhyDrive %d is <%s>...", pDriveInfo
->PhyDrive
, VerBuf
);
615 flfile
= fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
625 CHECK_CLOSE_HANDLE(hDrive
);
634 static unsigned int g_disk_unxz_len
= 0;
635 static BYTE
*g_part_img_pos
= NULL
;
636 static BYTE
*g_part_img_buf
[VENTOY_EFI_PART_SIZE
/ SIZE_1MB
];
639 static int VentoyFatMemRead(uint32 Sector
, uint8
*Buffer
, uint32 SectorCount
)
645 for (i
= 0; i
< SectorCount
; i
++)
647 offset
= (Sector
+ i
) * 512;
649 if (g_part_img_buf
[1] == NULL
)
651 MbBuf
= g_part_img_buf
[0] + offset
;
652 memcpy(Buffer
+ i
* 512, MbBuf
, 512);
656 MbBuf
= g_part_img_buf
[offset
/ SIZE_1MB
];
657 memcpy(Buffer
+ i
* 512, MbBuf
+ (offset
% SIZE_1MB
), 512);
665 static int VentoyFatMemWrite(uint32 Sector
, uint8
*Buffer
, uint32 SectorCount
)
671 for (i
= 0; i
< SectorCount
; i
++)
673 offset
= (Sector
+ i
) * 512;
675 if (g_part_img_buf
[1] == NULL
)
677 MbBuf
= g_part_img_buf
[0] + offset
;
678 memcpy(MbBuf
, Buffer
+ i
* 512, 512);
682 MbBuf
= g_part_img_buf
[offset
/ SIZE_1MB
];
683 memcpy(MbBuf
+ (offset
% SIZE_1MB
), Buffer
+ i
* 512, 512);
690 int VentoyProcSecureBoot(BOOL SecureBoot
)
694 char *filebuf
= NULL
;
697 Log("VentoyProcSecureBoot %d ...", SecureBoot
);
701 Log("Secure boot is enabled ...");
707 if (0 == fl_attach_media(VentoyFatMemRead
, VentoyFatMemWrite
))
709 file
= fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
710 Log("Open ventoy efi file %p ", file
);
713 fl_fseek(file
, 0, SEEK_END
);
714 size
= (int)fl_ftell(file
);
715 fl_fseek(file
, 0, SEEK_SET
);
717 Log("ventoy efi file size %d ...", size
);
719 filebuf
= (char *)malloc(size
);
722 fl_fread(filebuf
, 1, size
, file
);
727 Log("Now delete all efi files ...");
728 fl_remove("/EFI/BOOT/BOOTX64.EFI");
729 fl_remove("/EFI/BOOT/grubx64.efi");
730 fl_remove("/EFI/BOOT/grubx64_real.efi");
731 fl_remove("/EFI/BOOT/MokManager.efi");
732 fl_remove("/EFI/BOOT/mmx64.efi");
733 fl_remove("/ENROLL_THIS_KEY_IN_MOKMANAGER.cer");
734 fl_remove("/EFI/BOOT/grub.efi");
736 file
= fl_fopen("/EFI/BOOT/BOOTX64.EFI", "wb");
737 Log("Open bootx64 efi file %p ", file
);
742 fl_fwrite(filebuf
, 1, size
, file
);
755 file
= fl_fopen("/EFI/BOOT/grubia32_real.efi", "rb");
756 Log("Open ventoy efi file %p ", file
);
759 fl_fseek(file
, 0, SEEK_END
);
760 size
= (int)fl_ftell(file
);
761 fl_fseek(file
, 0, SEEK_SET
);
763 Log("ventoy efi file size %d ...", size
);
765 filebuf
= (char *)malloc(size
);
768 fl_fread(filebuf
, 1, size
, file
);
773 Log("Now delete all efi files ...");
774 fl_remove("/EFI/BOOT/BOOTIA32.EFI");
775 fl_remove("/EFI/BOOT/grubia32.efi");
776 fl_remove("/EFI/BOOT/grubia32_real.efi");
777 fl_remove("/EFI/BOOT/mmia32.efi");
779 file
= fl_fopen("/EFI/BOOT/BOOTIA32.EFI", "wb");
780 Log("Open bootia32 efi file %p ", file
);
785 fl_fwrite(filebuf
, 1, size
, file
);
811 static int disk_xz_flush(void *src
, unsigned int size
)
814 BYTE
*buf
= (BYTE
*)src
;
816 for (i
= 0; i
< size
; i
++)
818 *g_part_img_pos
= *buf
++;
821 if ((g_disk_unxz_len
% SIZE_1MB
) == 0)
823 g_part_img_pos
= g_part_img_buf
[g_disk_unxz_len
/ SIZE_1MB
];
834 static void unxz_error(char *x
)
839 static BOOL
TryWritePart2(HANDLE hDrive
, UINT64 StartSectorId
)
842 DWORD TrySize
= 16 * 1024;
845 unsigned char *data
= NULL
;
846 LARGE_INTEGER liCurrentPosition
;
848 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
849 SetFilePointerEx(hDrive
, liCurrentPosition
, &liCurrentPosition
, FILE_BEGIN
);
851 Buffer
= malloc(TrySize
);
853 bRet
= WriteFile(hDrive
, Buffer
, TrySize
, &dwSize
, NULL
);
857 Log("Try write part2 bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
859 if (bRet
&& dwSize
== TrySize
)
867 static int FormatPart2Fat(HANDLE hDrive
, UINT64 StartSectorId
)
874 int Pos
= PT_WRITE_VENTOY_START
;
877 unsigned char *data
= NULL
;
878 LARGE_INTEGER liCurrentPosition
;
879 LARGE_INTEGER liNewPosition
;
880 BYTE
*CheckBuf
= NULL
;
882 Log("FormatPart2Fat %llu...", (ULONGLONG
)StartSectorId
);
884 CheckBuf
= malloc(SIZE_1MB
);
887 Log("Failed to malloc check buf");
891 rc
= ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG
, 0, (void **)&data
, &len
);
894 Log("Failed to read img file %p %u", data
, len
);
899 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
900 SetFilePointerEx(hDrive
, liCurrentPosition
, &liNewPosition
, FILE_BEGIN
);
902 memset(g_part_img_buf
, 0, sizeof(g_part_img_buf
));
904 g_part_img_buf
[0] = (BYTE
*)malloc(VENTOY_EFI_PART_SIZE
);
905 if (g_part_img_buf
[0])
907 Log("Malloc whole img buffer success, now decompress ...");
908 unxz(data
, len
, NULL
, NULL
, g_part_img_buf
[0], &writelen
, unxz_error
);
912 Log("decompress finished success");
914 VentoyProcSecureBoot(g_SecureBoot
);
916 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
919 bRet
= WriteFile(hDrive
, g_part_img_buf
[0] + i
* SIZE_1MB
, SIZE_1MB
, &dwSize
, NULL
);
920 Log("Write part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
928 PROGRESS_BAR_SET_POS(Pos
);
935 //Read and check the data
936 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
937 SetFilePointerEx(hDrive
, liCurrentPosition
, &liNewPosition
, FILE_BEGIN
);
939 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
941 bRet
= ReadFile(hDrive
, CheckBuf
, SIZE_1MB
, &dwSize
, NULL
);
942 Log("Read part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
944 if (!bRet
|| memcmp(CheckBuf
, g_part_img_buf
[0] + i
* SIZE_1MB
, SIZE_1MB
))
946 Log("### [Check Fail] The data write and read does not match");
951 PROGRESS_BAR_SET_POS(Pos
);
961 Log("decompress finished failed");
967 Log("Failed to malloc whole img size %u, now split it", VENTOY_EFI_PART_SIZE
);
970 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
972 g_part_img_buf
[i
] = (BYTE
*)malloc(SIZE_1MB
);
973 if (g_part_img_buf
[i
] == NULL
)
980 Log("Malloc part img buffer success, now decompress ...");
982 g_part_img_pos
= g_part_img_buf
[0];
984 unxz(data
, len
, NULL
, disk_xz_flush
, NULL
, NULL
, unxz_error
);
986 if (g_disk_unxz_len
== VENTOY_EFI_PART_SIZE
)
988 Log("decompress finished success");
990 VentoyProcSecureBoot(g_SecureBoot
);
992 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
995 bRet
= WriteFile(hDrive
, g_part_img_buf
[i
], SIZE_1MB
, &dwSize
, NULL
);
996 Log("Write part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
1004 PROGRESS_BAR_SET_POS(Pos
);
1011 //Read and check the data
1012 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
1013 SetFilePointerEx(hDrive
, liCurrentPosition
, &liNewPosition
, FILE_BEGIN
);
1015 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
1017 bRet
= ReadFile(hDrive
, CheckBuf
, SIZE_1MB
, &dwSize
, NULL
);
1018 Log("Read part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
1020 if (!bRet
|| memcmp(CheckBuf
, g_part_img_buf
[i
], SIZE_1MB
))
1022 Log("### [Check Fail] The data write and read does not match");
1027 PROGRESS_BAR_SET_POS(Pos
);
1037 Log("decompress finished failed");
1044 if (data
) free(data
);
1045 if (CheckBuf
)free(CheckBuf
);
1049 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
1051 if (g_part_img_buf
[i
]) free(g_part_img_buf
[i
]);
1056 if (g_part_img_buf
[0]) free(g_part_img_buf
[0]);
1062 static int WriteGrubStage1ToPhyDrive(HANDLE hDrive
, int PartStyle
)
1068 BYTE
*ImgBuf
= NULL
;
1069 BYTE
*RawBuf
= NULL
;
1071 Log("WriteGrubStage1ToPhyDrive ...");
1073 RawBuf
= (BYTE
*)malloc(SIZE_1MB
);
1079 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG
, 0, (void **)&ImgBuf
, &Len
))
1081 Log("Failed to read stage1 img");
1086 unxz(ImgBuf
, Len
, NULL
, NULL
, RawBuf
, &readLen
, unxz_error
);
1090 Log("Write GPT stage1 ...");
1091 RawBuf
[500] = 35;//update blocklist
1092 SetFilePointer(hDrive
, 512 * 34, NULL
, FILE_BEGIN
);
1093 bRet
= WriteFile(hDrive
, RawBuf
, SIZE_1MB
- 512 * 34, &dwSize
, NULL
);
1097 Log("Write MBR stage1 ...");
1098 SetFilePointer(hDrive
, 512, NULL
, FILE_BEGIN
);
1099 bRet
= WriteFile(hDrive
, RawBuf
, SIZE_1MB
- 512, &dwSize
, NULL
);
1102 Log("WriteFile Ret:%u dwSize:%u ErrCode:%u", bRet
, dwSize
, GetLastError());
1110 static int FormatPart1LargeFAT32(UINT64 DiskSizeBytes
, int CluserSize
)
1116 Option
.fmt
= FM_FAT32
;
1121 if (CluserSize
== 0)
1123 // < 32GB select 32KB as cluster size
1124 // > 32GB select 128KB as cluster size
1125 if (DiskSizeBytes
/ 1024 / 1024 / 1024 <= 32)
1127 Option
.au_size
= 32768;
1131 Option
.au_size
= 131072;
1136 Option
.au_size
= CluserSize
;
1139 Log("Formatting Part1 large FAT32 ClusterSize:%u(%uKB) ...", CluserSize
, CluserSize
/ 1024);
1141 disk_io_reset_write_error();
1143 Ret
= f_mkfs(TEXT("0:"), &Option
, 0, 8 * 1024 * 1024);
1146 if (disk_io_is_write_error())
1148 Log("Formatting Part1 large FAT32 failed, write error.");
1152 Log("Formatting Part1 large FAT32 success, now set label");
1154 Ret
= f_mount(&FS
, TEXT("0:"), 1);
1157 Log("f_mount SUCCESS");
1158 Ret
= f_setlabel(TEXT("0:Ventoy"));
1161 Log("f_setlabel SUCCESS");
1162 Ret
= f_unmount(TEXT("0:"));
1163 Log("f_unmount %d %s", Ret
, (FR_OK
== Ret
) ? "SUCCESS" : "FAILED");
1167 Log("f_setlabel failed %d", Ret
);
1172 Log("f_mount failed %d", Ret
);
1179 Log("Formatting Part1 large FAT32 failed");
1184 static int FormatPart1exFAT(UINT64 DiskSizeBytes
)
1189 Option
.fmt
= FM_EXFAT
;
1194 // < 32GB select 32KB as cluster size
1195 // > 32GB select 128KB as cluster size
1196 if (DiskSizeBytes
/ 1024 / 1024 / 1024 <= 32)
1198 Option
.au_size
= 32768;
1202 Option
.au_size
= 131072;
1205 Log("Formatting Part1 exFAT ...");
1207 disk_io_reset_write_error();
1209 Ret
= f_mkfs(TEXT("0:"), &Option
, 0, 8 * 1024 * 1024);
1212 if (disk_io_is_write_error())
1214 Log("Formatting Part1 exFAT failed, write error.");
1218 Log("Formatting Part1 exFAT success");
1223 Log("Formatting Part1 exFAT failed");
1228 static int ZeroPart1FileSystem(HANDLE hDrive
, UINT64 Part2StartSector
)
1232 LARGE_INTEGER liCurPos
;
1233 LARGE_INTEGER liNewPos
;
1234 CHAR TmpBuffer
[1024] = { 0 };
1236 liCurPos
.QuadPart
= VENTOY_PART1_START_SECTOR
* 512;
1237 liNewPos
.QuadPart
= 0;
1238 if (0 == SetFilePointerEx(hDrive
, liCurPos
, &liNewPos
, FILE_BEGIN
) ||
1239 liNewPos
.QuadPart
!= liCurPos
.QuadPart
)
1241 Log("SetFilePointerEx Failed %u %llu %llu", LASTERR
, (ULONGLONG
)liCurPos
.QuadPart
, (ULONGLONG
)liNewPos
.QuadPart
);
1245 for (i
= 0; i
< 1024; i
++)
1247 WriteFile(hDrive
, TmpBuffer
, 1024, &dwSize
, NULL
);
1250 liCurPos
.QuadPart
= (Part2StartSector
* 512) - (1024 * 1024);
1251 liNewPos
.QuadPart
= 0;
1252 if (0 == SetFilePointerEx(hDrive
, liCurPos
, &liNewPos
, FILE_BEGIN
) ||
1253 liNewPos
.QuadPart
!= liCurPos
.QuadPart
)
1255 Log("SetFilePointerEx Failed %u %llu %llu", LASTERR
, (ULONGLONG
)liCurPos
.QuadPart
, (ULONGLONG
)liNewPos
.QuadPart
);
1259 for (i
= 0; i
< 1024; i
++)
1261 WriteFile(hDrive
, TmpBuffer
, 1024, &dwSize
, NULL
);
1264 Log("Zero Part1 SUCCESS");
1268 int ClearVentoyFromPhyDrive(HWND hWnd
, PHY_DRIVE_INFO
*pPhyDrive
, char *pDrvLetter
)
1277 CHAR DriveName
[] = "?:\\";
1278 CHAR DriveLetters
[MAX_PATH
] = { 0 };
1279 LARGE_INTEGER liCurrentPosition
;
1280 char *pTmpBuf
= NULL
;
1285 Log("ClearVentoyFromPhyDrive PhyDrive%d <<%s %s %dGB>>",
1286 pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1287 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1289 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1291 Log("Lock disk for clean ............................. ");
1293 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
1294 if (hDrive
== INVALID_HANDLE_VALUE
)
1296 Log("Failed to open physical disk");
1300 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1302 if (DriveLetters
[0] == 0)
1304 Log("No drive letter was assigned...");
1305 DriveName
[0] = GetFirstUnusedDriveLetter();
1306 Log("GetFirstUnusedDriveLetter %C: ...", DriveName
[0]);
1310 // Unmount all mounted volumes that belong to this drive
1311 // Do it in reverse so that we always end on the first volume letter
1312 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
1314 DriveName
[0] = DriveLetters
[i
- 1];
1315 bRet
= DeleteVolumeMountPointA(DriveName
);
1316 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, GetLastError());
1320 MountDrive
= DriveName
[0];
1321 Log("Will use '%C:' as volume mountpoint", DriveName
[0]);
1323 // It kind of blows, but we have to relinquish access to the physical drive
1324 // for VDS to be able to delete the partitions that reside on it...
1325 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1326 CHECK_CLOSE_HANDLE(hDrive
);
1328 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
1330 if (!VDS_DeleteAllPartitions(pPhyDrive
->PhyDrive
))
1332 Log("Notice: Could not delete partitions: %u", GetLastError());
1335 Log("Deleting all partitions ......................... OK");
1337 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
1339 Log("Lock disk for write ............................. ");
1340 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1341 if (hDrive
== INVALID_HANDLE_VALUE
)
1343 Log("Failed to GetPhysicalHandle for write.");
1348 // clear first and last 2MB space
1349 pTmpBuf
= malloc(SIZE_2MB
);
1352 Log("Failed to alloc memory.");
1356 memset(pTmpBuf
, 0, SIZE_2MB
);
1359 bRet
= WriteFile(hDrive
, pTmpBuf
, SIZE_2MB
- 512, &dwSize
, NULL
);
1360 Log("Write fisrt 1MB ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1367 SET_FILE_POS(pPhyDrive
->SizeInBytes
- SIZE_2MB
);
1368 bRet
= WriteFile(hDrive
, pTmpBuf
, SIZE_2MB
, &dwSize
, NULL
);
1369 Log("Write 2nd 1MB ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1378 if (pPhyDrive
->SizeInBytes
> 2199023255552ULL)
1380 VTOY_GPT_INFO
*pGptInfo
;
1381 VTOY_GPT_HDR BackupHead
;
1382 LARGE_INTEGER liCurrentPosition
;
1384 pGptInfo
= (VTOY_GPT_INFO
*)pTmpBuf
;
1386 VentoyFillWholeGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1388 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512);
1389 VentoyFillBackupGptHead(pGptInfo
, &BackupHead
);
1390 if (!WriteFile(hDrive
, &BackupHead
, sizeof(VTOY_GPT_HDR
), &dwSize
, NULL
))
1393 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1397 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512 * 33);
1398 if (!WriteFile(hDrive
, pGptInfo
->PartTbl
, sizeof(pGptInfo
->PartTbl
), &dwSize
, NULL
))
1401 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1406 if (!WriteFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
))
1409 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1413 Log("Write GPT Info OK ...");
1417 bRet
= ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
1418 Log("Read MBR ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1425 //clear boot code and partition table (reserved disk signature)
1426 memset(MBR
.BootCode
, 0, 440);
1427 memset(MBR
.PartTbl
, 0, sizeof(MBR
.PartTbl
));
1429 VentoyFillMBRLocation(pPhyDrive
->SizeInBytes
, 2048, (UINT32
)(pPhyDrive
->SizeInBytes
/ 512 - 2048), MBR
.PartTbl
);
1431 MBR
.PartTbl
[0].Active
= 0x00; // bootable
1432 MBR
.PartTbl
[0].FsFlag
= 0x07; // exFAT/NTFS/HPFS
1435 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
1436 Log("Write MBR ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1444 Log("Clear Ventoy successfully finished");
1446 //Refresh Drive Layout
1447 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1451 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1452 PROGRESS_BAR_SET_POS(PT_REFORMAT_FINISH
);
1461 Log("Mounting Ventoy Partition ....................... ");
1465 memset(DriveLetters
, 0, sizeof(DriveLetters
));
1466 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1467 Log("Logical drive letter after write ventoy: <%s>", DriveLetters
);
1469 for (i
= 0; i
< sizeof(DriveLetters
) && DriveLetters
[i
]; i
++)
1471 DriveName
[0] = DriveLetters
[i
];
1472 Log("%s is ventoy part1, already mounted", DriveName
);
1478 Log("need to mount ventoy part1...");
1479 if (0 == GetVentoyVolumeName(pPhyDrive
->PhyDrive
, 2048, DriveLetters
, sizeof(DriveLetters
), FALSE
))
1481 DriveName
[0] = MountDrive
;
1482 bRet
= SetVolumeMountPointA(DriveName
, DriveLetters
);
1483 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName
, DriveLetters
, bRet
, GetLastError());
1485 *pDrvLetter
= MountDrive
;
1489 Log("Failed to find ventoy volume");
1497 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
1500 CHECK_CLOSE_HANDLE(hDrive
);
1504 int InstallVentoy2FileImage(PHY_DRIVE_INFO
*pPhyDrive
, int PartStyle
)
1513 UINT64 data_offset
= 0;
1514 UINT64 Part2StartSector
= 0;
1515 UINT64 Part1StartSector
= 0;
1516 UINT64 Part1SectorCount
= 0;
1517 UINT8
*pData
= NULL
;
1518 UINT8
*pBkGptPartTbl
= NULL
;
1519 BYTE
*ImgBuf
= NULL
;
1520 MBR_HEAD
*pMBR
= NULL
;
1521 VTSI_FOOTER
*pImgFooter
= NULL
;
1522 VTSI_SEGMENT
*pSegment
= NULL
;
1523 VTOY_GPT_INFO
*pGptInfo
= NULL
;
1524 VTOY_GPT_HDR
*pBkGptHdr
= NULL
;
1527 Log("InstallVentoy2FileImage %s PhyDrive%d <<%s %s %dGB>>",
1528 PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1529 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1531 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1533 size
= SIZE_1MB
+ VENTOY_EFI_PART_SIZE
+ 33 * 512 + VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
) + sizeof(VTSI_FOOTER
);
1535 pData
= (UINT8
*)malloc(size
);
1538 Log("malloc image buffer failed %d.", size
);
1542 pImgFooter
= (VTSI_FOOTER
*)(pData
+ size
- sizeof(VTSI_FOOTER
));
1543 pSegment
= (VTSI_SEGMENT
*)((UINT8
*)pImgFooter
- VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
));
1544 memset(pImgFooter
, 0, sizeof(VTSI_FOOTER
));
1545 memset(pSegment
, 0, VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
));
1547 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START
);
1549 Log("Writing Boot Image ............................. ");
1550 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG
, 0, (void **)&ImgBuf
, &Len
))
1552 Log("Failed to read stage1 img");
1556 unxz(ImgBuf
, Len
, NULL
, NULL
, pData
, &dataLen
, unxz_error
);
1559 Log("decompress %s len:%d", VENTOY_FILE_STG1_IMG
, dataLen
);
1563 pData
[500] = 35;//update blocklist
1564 memmove(pData
+ 34 * 512, pData
, SIZE_1MB
- 512 * 34);
1565 memset(pData
, 0, 34 * 512);
1567 pGptInfo
= (VTOY_GPT_INFO
*)pData
;
1568 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
1569 VentoyFillGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1571 pBkGptPartTbl
= pData
+ SIZE_1MB
+ VENTOY_EFI_PART_SIZE
;
1572 memset(pBkGptPartTbl
, 0, 33 * 512);
1574 memcpy(pBkGptPartTbl
, pGptInfo
->PartTbl
, 32 * 512);
1575 pBkGptHdr
= (VTOY_GPT_HDR
*)(pBkGptPartTbl
+ 32 * 512);
1576 VentoyFillBackupGptHead(pGptInfo
, pBkGptHdr
);
1578 Part1StartSector
= pGptInfo
->PartTbl
[0].StartLBA
;
1579 Part1SectorCount
= pGptInfo
->PartTbl
[0].LastLBA
- Part1StartSector
+ 1;
1580 Part2StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
1582 Log("Write GPT Info OK ...");
1586 memmove(pData
+ 512, pData
, SIZE_1MB
- 512);
1587 memset(pData
, 0, 512);
1589 pMBR
= (MBR_HEAD
*)pData
;
1590 VentoyFillMBR(pPhyDrive
->SizeInBytes
, pMBR
, PartStyle
);
1591 Part1StartSector
= pMBR
->PartTbl
[0].StartSectorId
;
1592 Part1SectorCount
= pMBR
->PartTbl
[0].SectorCount
;
1593 Part2StartSector
= pMBR
->PartTbl
[1].StartSectorId
;
1595 Log("Write MBR OK ...");
1598 Log("Writing EFI part Image ............................. ");
1599 rc
= ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG
, 0, (void **)&ImgBuf
, &Len
);
1602 Log("Failed to read img file %p %u", ImgBuf
, Len
);
1606 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START
+ 28);
1607 memset(g_part_img_buf
, 0, sizeof(g_part_img_buf
));
1608 unxz(ImgBuf
, Len
, NULL
, NULL
, pData
+ SIZE_1MB
, &dataLen
, unxz_error
);
1611 Log("decompress finished success");
1612 g_part_img_buf
[0] = pData
+ SIZE_1MB
;
1614 VentoyProcSecureBoot(g_SecureBoot
);
1618 Log("decompress finished failed");
1622 fopen_s(&fp
, "VentoySparseImg.vtsi", "wb+");
1625 Log("Failed to create Ventoy img file");
1629 Log("Writing stage1 data ............................. ");
1631 fwrite(pData
, 1, SIZE_1MB
, fp
);
1633 pSegment
[0].disk_start_sector
= 0;
1634 pSegment
[0].sector_num
= SIZE_1MB
/ 512;
1635 pSegment
[0].data_offset
= data_offset
;
1636 data_offset
+= pSegment
[0].sector_num
* 512;
1638 disk_io_set_param(INVALID_HANDLE_VALUE
, Part1StartSector
+ Part1SectorCount
);// include the 2048 sector gap
1639 disk_io_set_imghook(fp
, pSegment
+ 1, VTSI_IMG_MAX_SEG
- 1, data_offset
);
1641 Log("Formatting part1 exFAT ...");
1642 if (0 != FormatPart1exFAT(pPhyDrive
->SizeInBytes
))
1644 Log("FormatPart1exFAT failed.");
1645 disk_io_reset_imghook(&segnum
, &data_offset
);
1649 disk_io_reset_imghook(&segnum
, &data_offset
);
1652 Log("current segment number:%d dataoff:%ld", segnum
, (long)data_offset
);
1655 Log("Writing part2 data ............................. ");
1656 fwrite(pData
+ SIZE_1MB
, 1, VENTOY_EFI_PART_SIZE
, fp
);
1657 pSegment
[segnum
].disk_start_sector
= Part2StartSector
;
1658 pSegment
[segnum
].sector_num
= VENTOY_EFI_PART_SIZE
/ 512;
1659 pSegment
[segnum
].data_offset
= data_offset
;
1660 data_offset
+= pSegment
[segnum
].sector_num
* 512;
1665 Log("Writing backup gpt table ............................. ");
1666 fwrite(pBkGptPartTbl
, 1, 33 * 512, fp
);
1667 pSegment
[segnum
].disk_start_sector
= pPhyDrive
->SizeInBytes
/ 512 - 33;
1668 pSegment
[segnum
].sector_num
= 33;
1669 pSegment
[segnum
].data_offset
= data_offset
;
1670 data_offset
+= pSegment
[segnum
].sector_num
* 512;
1674 Log("Writing segment metadata ............................. ");
1676 for (i
= 0; i
< (int)segnum
; i
++)
1678 Log("SEG[%d]: PhySector:%llu SectorNum:%llu DataOffset:%llu(sector:%llu)", i
, pSegment
[i
].disk_start_sector
, pSegment
[i
].sector_num
,
1679 pSegment
[i
].data_offset
, pSegment
[i
].data_offset
/ 512);
1682 dataLen
= segnum
* sizeof(VTSI_SEGMENT
);
1683 fwrite(pSegment
, 1, dataLen
, fp
);
1687 //pData + SIZE_1MB - 8192 is a temp data buffer with zero
1688 fwrite(pData
+ SIZE_1MB
- 8192, 1, 512 - (dataLen
% 512), fp
);
1692 pImgFooter
->magic
= VTSI_IMG_MAGIC
;
1693 pImgFooter
->version
= 1;
1694 pImgFooter
->disk_size
= pPhyDrive
->SizeInBytes
;
1695 memcpy(&pImgFooter
->disk_signature
, pPhyDrive
->MBR
.BootCode
+ 0x1b8, 4);
1696 pImgFooter
->segment_num
= segnum
;
1697 pImgFooter
->segment_offset
= data_offset
;
1699 for (i
= 0, chksum
= 0; i
< (int)(segnum
* sizeof(VTSI_SEGMENT
)); i
++)
1701 chksum
+= *((UINT8
*)pSegment
+ i
);
1703 pImgFooter
->segment_chksum
= ~chksum
;
1705 for (i
= 0, chksum
= 0; i
< sizeof(VTSI_FOOTER
); i
++)
1707 chksum
+= *((UINT8
*)pImgFooter
+ i
);
1709 pImgFooter
->foot_chksum
= ~chksum
;
1711 Log("Writing footer segnum(%u) segoffset(%llu) ......................", segnum
, data_offset
);
1712 Log("disk_size=%llu disk_signature=%lx segment_offset=%llu", pImgFooter
->disk_size
, pImgFooter
->disk_signature
, pImgFooter
->segment_offset
);
1714 fwrite(pImgFooter
, 1, sizeof(VTSI_FOOTER
), fp
);
1717 Log("Writing Ventoy image file finished, the file size should be %llu .", data_offset
+ 512 + ((dataLen
+ 511) / 512 * 512));
1723 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1724 PROGRESS_BAR_SET_POS(PT_REFORMAT_FINISH
);
1726 Log("retcode:%d\n", rc
);
1735 int InstallVentoy2PhyDrive(PHY_DRIVE_INFO
*pPhyDrive
, int PartStyle
, int TryId
)
1745 CHAR DriveName
[] = "?:\\";
1746 CHAR DriveLetters
[MAX_PATH
] = { 0 };
1748 VTOY_GPT_INFO
*pGptInfo
= NULL
;
1749 UINT64 Part1StartSector
= 0;
1750 UINT64 Part1SectorCount
= 0;
1751 UINT64 Part2StartSector
= 0;
1752 BOOL LargeFAT32
= FALSE
;
1754 Log("#####################################################");
1755 Log("InstallVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId
,
1756 PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1757 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1758 Log("#####################################################");
1762 pGptInfo
= malloc(sizeof(VTOY_GPT_INFO
));
1763 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
1766 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1770 VentoyFillGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1771 Part1StartSector
= pGptInfo
->PartTbl
[0].StartLBA
;
1772 Part1SectorCount
= pGptInfo
->PartTbl
[0].LastLBA
- Part1StartSector
+ 1;
1773 Part2StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
1777 VentoyFillMBR(pPhyDrive
->SizeInBytes
, &MBR
, PartStyle
);
1778 Part1StartSector
= MBR
.PartTbl
[0].StartSectorId
;
1779 Part1SectorCount
= MBR
.PartTbl
[0].SectorCount
;
1780 Part2StartSector
= MBR
.PartTbl
[1].StartSectorId
;
1783 Log("Lock disk for clean ............................. ");
1785 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
1786 if (hDrive
== INVALID_HANDLE_VALUE
)
1788 Log("Failed to open physical disk");
1793 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1795 if (DriveLetters
[0] == 0)
1797 Log("No drive letter was assigned...");
1798 DriveName
[0] = GetFirstUnusedDriveLetter();
1799 Log("GetFirstUnusedDriveLetter %C: ...", DriveName
[0]);
1803 // Unmount all mounted volumes that belong to this drive
1804 // Do it in reverse so that we always end on the first volume letter
1805 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
1807 DriveName
[0] = DriveLetters
[i
- 1];
1808 bRet
= DeleteVolumeMountPointA(DriveName
);
1809 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, GetLastError());
1813 MountDrive
= DriveName
[0];
1814 Log("Will use '%C:' as volume mountpoint", DriveName
[0]);
1816 // It kind of blows, but we have to relinquish access to the physical drive
1817 // for VDS to be able to delete the partitions that reside on it...
1818 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1819 CHECK_CLOSE_HANDLE(hDrive
);
1821 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
1823 if (!VDS_DeleteAllPartitions(pPhyDrive
->PhyDrive
))
1825 Log("Notice: Could not delete partitions: 0x%x, but we continue.", GetLastError());
1828 Log("Deleting all partitions ......................... OK");
1830 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
1832 Log("Lock disk for write ............................. ");
1833 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1834 if (hDrive
== INVALID_HANDLE_VALUE
)
1836 Log("Failed to GetPhysicalHandle for write.");
1841 //Refresh Drive Layout
1842 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1844 disk_io_set_param(hDrive
, Part1StartSector
+ Part1SectorCount
);// include the 2048 sector gap
1846 PROGRESS_BAR_SET_POS(PT_FORMAT_PART1
);
1848 if (PartStyle
== 1 && pPhyDrive
->PartStyle
== 0)
1850 Log("Wait for format part1 ...");
1854 if (GetVentoyFsType() == VTOY_FS_FAT32
&& (Part1SectorCount
* 512 >= FAT32_MAX_LIMIT
))
1856 Log("Formatting part1 large FAT32 ...");
1858 if (0 != FormatPart1LargeFAT32(pPhyDrive
->SizeInBytes
, GetClusterSize()))
1860 Log("FormatPart1LargeFAT32 failed.");
1867 Log("Zero part1 file system ...");
1868 if (0 != ZeroPart1FileSystem(hDrive
, Part2StartSector
))
1870 Log("ZeroPart1FileSystem failed.");
1876 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
1877 Log("Writing part2 FAT img ...");
1879 if (0 != FormatPart2Fat(hDrive
, Part2StartSector
))
1881 Log("FormatPart2Fat failed.");
1886 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG
);
1887 Log("Writing Boot Image ............................. ");
1888 if (WriteGrubStage1ToPhyDrive(hDrive
, PartStyle
) != 0)
1890 Log("WriteGrubStage1ToPhyDrive failed.");
1895 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE
);
1896 Log("Writing Partition Table ........................ ");
1897 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
1901 VTOY_GPT_HDR BackupHead
;
1902 LARGE_INTEGER liCurrentPosition
;
1904 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512);
1905 VentoyFillBackupGptHead(pGptInfo
, &BackupHead
);
1906 if (!WriteFile(hDrive
, &BackupHead
, sizeof(VTOY_GPT_HDR
), &dwSize
, NULL
))
1909 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1913 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512 * 33);
1914 if (!WriteFile(hDrive
, pGptInfo
->PartTbl
, sizeof(pGptInfo
->PartTbl
), &dwSize
, NULL
))
1917 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1922 if (!WriteFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
))
1925 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1929 Log("Write GPT Info OK ...");
1930 memcpy(&(pPhyDrive
->MBR
), &(pGptInfo
->MBR
), 512);
1934 if (!WriteFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
))
1937 Log("Write MBR Failed, dwSize:%u ErrCode:%u", dwSize
, GetLastError());
1940 Log("Write MBR OK ...");
1941 memcpy(&(pPhyDrive
->MBR
), &MBR
, 512);
1944 //Refresh Drive Layout
1945 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1949 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1953 Log("Mounting Ventoy Partition ....................... ");
1957 memset(DriveLetters
, 0, sizeof(DriveLetters
));
1958 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1959 Log("Logical drive letter after write ventoy: <%s>", DriveLetters
);
1961 for (i
= 0; i
< sizeof(DriveLetters
) && DriveLetters
[i
]; i
++)
1963 DriveName
[0] = DriveLetters
[i
];
1964 if (IsVentoyLogicalDrive(DriveName
[0]))
1966 Log("%s is ventoy part2, delete mountpoint", DriveName
);
1967 DeleteVolumeMountPointA(DriveName
);
1971 Log("%s is ventoy part1, already mounted", DriveName
);
1972 MountDrive
= DriveName
[0];
1979 Log("need to mount ventoy part1...");
1981 if (0 == GetVentoyVolumeName(pPhyDrive
->PhyDrive
, Part1StartSector
, DriveLetters
, sizeof(DriveLetters
), FALSE
))
1983 DriveName
[0] = MountDrive
;
1984 bRet
= SetVolumeMountPointA(DriveName
, DriveLetters
);
1985 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName
, DriveLetters
, bRet
, GetLastError());
1994 Log("Failed to find ventoy volume");
1998 // close handle, or it will deny reformat
1999 Log("Close handle ...");
2000 CHECK_CLOSE_HANDLE(hDrive
);
2008 Log("No need to reformat for large FAT32");
2009 pPhyDrive
->VentoyFsClusterSize
= GetVolumeClusterSize(MountDrive
);
2013 bRet
= DISK_FormatVolume(MountDrive
, GetVentoyFsType(), Part1SectorCount
* 512);
2014 for (i
= 0; bRet
== FALSE
&& i
< 2; i
++)
2016 Log("Wait and retry reformat ...");
2018 bRet
= DISK_FormatVolume(MountDrive
, GetVentoyFsType(), Part1SectorCount
* 512);
2023 Log("Reformat %C:\\ to %s SUCCESS", MountDrive
, GetVentoyFsName());
2024 pPhyDrive
->VentoyFsClusterSize
= GetVolumeClusterSize(MountDrive
);
2026 if ((GetVentoyFsType() != VTOY_FS_UDF
) && (pPhyDrive
->VentoyFsClusterSize
< 2048))
2028 for (i
= 0; i
< 10; i
++)
2030 Log("### Invalid cluster size %d ###", pPhyDrive
->VentoyFsClusterSize
);
2037 Log("Reformat %C:\\ to %s FAILED", MountDrive
, GetVentoyFsName());
2043 Log("Can not reformat %s to %s", DriveName
, GetVentoyFsName());
2048 Log("Format to exfat with built-in algorithm");
2050 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2051 if (hDrive
== INVALID_HANDLE_VALUE
)
2053 Log("Failed to GetPhysicalHandle for write.");
2057 if (0 != FormatPart1exFAT(pPhyDrive
->SizeInBytes
))
2059 Log("FormatPart1exFAT SUCCESS.");
2063 Log("FormatPart1exFAT FAILED.");
2066 CHECK_CLOSE_HANDLE(hDrive
);
2074 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2076 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
2078 if (!VDS_IsLastAvaliable())
2080 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2081 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2082 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2083 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2084 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2087 CHECK_CLOSE_HANDLE(hDrive
);
2099 int PartitionResizeForVentoy(PHY_DRIVE_INFO
*pPhyDrive
)
2105 INT64 ReservedValue
;
2109 VTOY_GPT_INFO
*pGPT
;
2112 VTOY_GPT_HDR BackupHead
;
2113 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
2114 GUID ZeroGuid
= { 0 };
2115 static GUID WindowsDataPartType
= { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
2116 static GUID EspPartType
= { 0xc12a7328, 0xf81f, 0x11d2, { 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b } };
2117 static GUID BiosGrubPartType
= { 0x21686148, 0x6449, 0x6e6f, { 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46, 0x49 } };
2119 Log("#####################################################");
2120 Log("PartitionResizeForVentoy PhyDrive%d <<%s %s %dGB>>",
2121 pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
2122 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
2123 Log("#####################################################");
2125 pGPT
= &(pPhyDrive
->Gpt
);
2126 pMBR
= &(pPhyDrive
->Gpt
.MBR
);
2127 Log("Disksize:%llu Part2Start:%llu", pPhyDrive
->SizeInBytes
, pPhyDrive
->ResizePart2StartSector
* 512);
2129 if (pMBR
->PartTbl
[0].FsFlag
== 0xEE && memcmp(pGPT
->Head
.Signature
, "EFI PART", 8) == 0)
2138 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2140 RecudeBytes
= VENTOY_EFI_PART_SIZE
;
2141 ReservedValue
= GetReservedSpaceInMB();
2142 if (ReservedValue
> 0)
2144 Log("Reduce add reserved space %lldMB", (LONGLONG
)ReservedValue
);
2145 RecudeBytes
+= (UINT64
)(ReservedValue
* SIZE_1MB
);
2149 if (pPhyDrive
->ResizeNoShrink
== FALSE
)
2151 Log("Need to shrink the volume");
2152 if (DISK_ShrinkVolume(pPhyDrive
->PhyDrive
, pPhyDrive
->ResizeVolumeGuid
, pPhyDrive
->Part1DriveLetter
, pPhyDrive
->ResizeOldPart1Size
, RecudeBytes
))
2154 Log("Shrink volume success, now check again");
2156 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2157 if (hDrive
== INVALID_HANDLE_VALUE
)
2159 Log("Failed to GetPhysicalHandle for update.");
2163 //Refresh Drive Layout
2164 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2166 CHECK_CLOSE_HANDLE(hDrive
);
2169 if (PartResizePreCheck(NULL
) && pPhyDrive
->ResizeNoShrink
)
2171 Log("Recheck after Shrink volume success");
2172 Log("After shrink Disksize:%llu Part2Start:%llu", pPhyDrive
->SizeInBytes
, pPhyDrive
->ResizePart2StartSector
* 512);
2176 Log("Recheck after Shrink volume failed %u", pPhyDrive
->ResizeNoShrink
);
2182 Log("Shrink volume failed");
2188 //Now try write data
2189 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2190 if (hDrive
== INVALID_HANDLE_VALUE
)
2192 Log("Failed to GetPhysicalHandle for update.");
2197 //Write partition 2 data
2198 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
2199 if (0 != FormatPart2Fat(hDrive
, pPhyDrive
->ResizePart2StartSector
))
2201 Log("FormatPart2Fat failed.");
2205 //Write grub stage2 gap
2206 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG
);
2207 Log("Writing Boot Image ............................. ");
2208 if (WriteGrubStage1ToPhyDrive(hDrive
, PartStyle
) != 0)
2210 Log("WriteGrubStage1ToPhyDrive failed.");
2215 //Write partition table
2216 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE
);
2217 Log("Writing partition table ............................. ");
2219 VentoyGetLocalBootImg(&MBR
);
2220 CoCreateGuid(&Guid
);
2221 memcpy(MBR
.BootCode
+ 0x180, &Guid
, 16);
2222 memcpy(pMBR
->BootCode
, MBR
.BootCode
, 440);
2226 for (i
= 1; i
< 4; i
++)
2228 if (pMBR
->PartTbl
[i
].SectorCount
== 0)
2236 Log("Can not find MBR free partition table");
2240 for (j
= i
- 1; j
> 0; j
--)
2242 Log("Move MBR partition table %d --> %d", j
+ 1, j
+ 2);
2243 memcpy(pMBR
->PartTbl
+ (j
+ 1), pMBR
->PartTbl
+ j
, sizeof(PART_TABLE
));
2246 memset(pMBR
->PartTbl
+ 1, 0, sizeof(PART_TABLE
));
2247 VentoyFillMBRLocation(pPhyDrive
->SizeInBytes
, (UINT32
)pPhyDrive
->ResizePart2StartSector
, VENTOY_EFI_PART_SIZE
/ 512, pMBR
->PartTbl
+ 1);
2248 pMBR
->PartTbl
[0].Active
= 0x80; // bootable
2249 pMBR
->PartTbl
[1].Active
= 0x00;
2250 pMBR
->PartTbl
[1].FsFlag
= 0xEF; // EFI System Partition
2252 if (!WriteDataToPhyDisk(hDrive
, 0, pMBR
, 512))
2254 Log("Legacy BIOS write MBR failed");
2260 for (i
= 1; i
< 128; i
++)
2262 if (memcmp(&(pGPT
->PartTbl
[i
].PartGuid
), &ZeroGuid
, sizeof(GUID
)) == 0)
2270 Log("Can not find GPT free partition table");
2274 for (j
= i
- 1; j
> 0; j
--)
2276 Log("Move GPT partition table %d --> %d", j
+ 1, j
+ 2);
2277 memcpy(pGPT
->PartTbl
+ (j
+ 1), pGPT
->PartTbl
+ j
, sizeof(VTOY_GPT_PART_TBL
));
2281 pMBR
->BootCode
[92] = 0x22;
2283 // to fix windows issue
2284 memset(pGPT
->PartTbl
+ 1, 0, sizeof(VTOY_GPT_PART_TBL
));
2285 memcpy(&(pGPT
->PartTbl
[1].PartType
), &WindowsDataPartType
, sizeof(GUID
));
2286 CoCreateGuid(&(pGPT
->PartTbl
[1].PartGuid
));
2288 pGPT
->PartTbl
[1].StartLBA
= pGPT
->PartTbl
[0].LastLBA
+ 1;
2289 pGPT
->PartTbl
[1].LastLBA
= pGPT
->PartTbl
[1].StartLBA
+ VENTOY_EFI_PART_SIZE
/ 512 - 1;
2290 pGPT
->PartTbl
[1].Attr
= 0xC000000000000001ULL
;
2291 memcpy(pGPT
->PartTbl
[1].Name
, L
"VTOYEFI", 7 * 2);
2294 pGPT
->Head
.PartTblCrc
= VentoyCrc32(pGPT
->PartTbl
, sizeof(pGPT
->PartTbl
));
2296 pGPT
->Head
.Crc
= VentoyCrc32(&(pGPT
->Head
), pGPT
->Head
.Length
);
2298 Log("pGPT->Head.EfiStartLBA=%llu", (ULONGLONG
)pGPT
->Head
.EfiStartLBA
);
2299 Log("pGPT->Head.EfiBackupLBA=%llu", (ULONGLONG
)pGPT
->Head
.EfiBackupLBA
);
2301 VentoyFillBackupGptHead(pGPT
, &BackupHead
);
2302 if (!WriteDataToPhyDisk(hDrive
, pGPT
->Head
.EfiBackupLBA
* 512, &BackupHead
, 512))
2304 Log("UEFI write backup head failed");
2308 if (!WriteDataToPhyDisk(hDrive
, (pGPT
->Head
.EfiBackupLBA
- 32) * 512, pGPT
->PartTbl
, 512 * 32))
2310 Log("UEFI write backup partition table failed");
2314 if (!WriteDataToPhyDisk(hDrive
, 0, pGPT
, 512 * 34))
2316 Log("UEFI write MBR & Main partition table failed");
2323 //Refresh Drive Layout
2324 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2326 //We must close handle here, because it will block the refresh bellow
2327 CHECK_CLOSE_HANDLE(hDrive
);
2332 PhyDrive
= pPhyDrive
->PhyDrive
;
2334 Log("#### Now Refresh PhyDrive ####");
2335 Ventoy2DiskDestroy();
2338 pPhyDrive
= GetPhyDriveInfoByPhyDrive(PhyDrive
);
2341 if (pPhyDrive
->VentoyVersion
[0] == 0)
2343 Log("After process the Ventoy version is still invalid");
2347 Log("### Ventoy non-destructive installation successfully finished <%s>", pPhyDrive
->VentoyVersion
);
2351 Log("### Ventoy non-destructive installation successfully finished <not found>");
2354 InitComboxCtrl(g_DialogHwnd
, PhyDrive
);
2359 CHECK_CLOSE_HANDLE(hDrive
);
2364 static BOOL
DiskCheckWriteAccess(HANDLE hDrive
)
2370 LARGE_INTEGER liCurPosition
;
2371 LARGE_INTEGER liNewPosition
;
2373 liCurPosition
.QuadPart
= 2039 * 512;
2374 liNewPosition
.QuadPart
= 0;
2375 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2376 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2378 Log("SetFilePointer1 Failed %u", LASTERR
);
2384 ret
= ReadFile(hDrive
, Buffer
, 512, &dwSize
, NULL
);
2385 if ((!ret
) || (dwSize
!= 512))
2387 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2392 liCurPosition
.QuadPart
= 2039 * 512;
2393 liNewPosition
.QuadPart
= 0;
2394 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2395 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2397 Log("SetFilePointer2 Failed %u", LASTERR
);
2402 ret
= WriteFile(hDrive
, Buffer
, 512, &dwSize
, NULL
);
2403 if ((!ret
) || dwSize
!= 512)
2405 Log("Failed to write %d %u %u", ret
, dwSize
, LASTERR
);
2416 static BOOL
BackupDataBeforeCleanDisk(int PhyDrive
, UINT64 DiskSize
, BYTE
**pBackup
)
2420 BOOL Return
= FALSE
;
2422 BYTE
*backup
= NULL
;
2424 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
2425 LARGE_INTEGER liCurPosition
;
2426 LARGE_INTEGER liNewPosition
;
2427 VTOY_GPT_INFO
*pGPT
= NULL
;
2429 Log("BackupDataBeforeCleanDisk %d", PhyDrive
);
2431 // step1: check write access
2432 hDrive
= GetPhysicalHandle(PhyDrive
, TRUE
, TRUE
, FALSE
);
2433 if (hDrive
== INVALID_HANDLE_VALUE
)
2435 Log("Failed to GetPhysicalHandle for write.");
2439 if (DiskCheckWriteAccess(hDrive
))
2441 Log("DiskCheckWriteAccess success");
2442 CHECK_CLOSE_HANDLE(hDrive
);
2446 Log("DiskCheckWriteAccess failed");
2450 //step2 backup 4MB data
2451 backup
= malloc(SIZE_1MB
* 4);
2457 hDrive
= GetPhysicalHandle(PhyDrive
, FALSE
, FALSE
, FALSE
);
2458 if (hDrive
== INVALID_HANDLE_VALUE
)
2464 dwStatus
= SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2471 ret
= ReadFile(hDrive
, backup
, SIZE_2MB
, &dwSize
, NULL
);
2472 if ((!ret
) || (dwSize
!= SIZE_2MB
))
2474 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2478 pGPT
= (VTOY_GPT_INFO
*)backup
;
2479 offset
= pGPT
->Head
.EfiBackupLBA
* 512;
2480 if (offset
>= (DiskSize
- SIZE_2MB
) && offset
< DiskSize
)
2482 Log("EFI partition table check success");
2486 Log("Backup EFI LBA not in last 2MB range: %llu", pGPT
->Head
.EfiBackupLBA
);
2491 liCurPosition
.QuadPart
= DiskSize
- SIZE_2MB
;
2492 liNewPosition
.QuadPart
= 0;
2493 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2494 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2500 ret
= ReadFile(hDrive
, backup
+ SIZE_2MB
, SIZE_2MB
, &dwSize
, NULL
);
2501 if ((!ret
) || (dwSize
!= SIZE_2MB
))
2503 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2508 backup
= NULL
; //For don't free later
2512 CHECK_CLOSE_HANDLE(hDrive
);
2520 static BOOL
WriteBackupDataToDisk(HANDLE hDrive
, UINT64 Offset
, BYTE
*Data
, DWORD Length
)
2524 LARGE_INTEGER liCurPosition
;
2525 LARGE_INTEGER liNewPosition
;
2527 Log("WriteBackupDataToDisk %llu %p %u", Offset
, Data
, Length
);
2529 liCurPosition
.QuadPart
= Offset
;
2530 liNewPosition
.QuadPart
= 0;
2531 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2532 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2537 ret
= WriteFile(hDrive
, Data
, Length
, &dwSize
, NULL
);
2538 if ((!ret
) || dwSize
!= Length
)
2540 Log("Failed to write %d %u %u", ret
, dwSize
, LASTERR
);
2544 Log("WriteBackupDataToDisk %llu %p %u success", Offset
, Data
, Length
);
2549 int UpdateVentoy2PhyDrive(PHY_DRIVE_INFO
*pPhyDrive
, int TryId
)
2554 BOOL ForceMBR
= FALSE
;
2555 BOOL Esp2Basic
= FALSE
;
2556 BOOL ChangeAttr
= FALSE
;
2557 BOOL CleanDisk
= FALSE
;
2558 BOOL DelEFI
= FALSE
;
2559 BOOL bWriteBack
= TRUE
;
2565 CHAR DriveName
[] = "?:\\";
2566 CHAR DriveLetters
[MAX_PATH
] = { 0 };
2567 CHAR BackBinFile
[MAX_PATH
];
2569 UINT64 ReservedMB
= 0;
2572 BYTE
*pBackup
= NULL
;
2573 VTOY_GPT_INFO
*pGptInfo
= NULL
;
2574 VTOY_GPT_INFO
*pGptBkup
= NULL
;
2575 UINT8 ReservedData
[4096];
2577 Log("#####################################################");
2578 Log("UpdateVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId
,
2579 pPhyDrive
->PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
2580 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
2581 Log("#####################################################");
2583 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2585 Log("Lock disk for umount ............................ ");
2587 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
2588 if (hDrive
== INVALID_HANDLE_VALUE
)
2590 Log("Failed to open physical disk");
2594 if (pPhyDrive
->PartStyle
)
2596 pGptInfo
= malloc(2 * sizeof(VTOY_GPT_INFO
));
2602 memset(pGptInfo
, 0, 2 * sizeof(VTOY_GPT_INFO
));
2603 pGptBkup
= pGptInfo
+ 1;
2606 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2607 ReadFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
);
2608 memcpy(pGptBkup
, pGptInfo
, sizeof(VTOY_GPT_INFO
));
2610 //MBR will be used to compare with local boot image
2611 memcpy(&MBR
, &pGptInfo
->MBR
, sizeof(MBR_HEAD
));
2613 StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
2614 Log("GPT StartSector in PartTbl:%llu", (ULONGLONG
)StartSector
);
2616 ReservedMB
= (pPhyDrive
->SizeInBytes
/ 512 - (StartSector
+ VENTOY_EFI_PART_SIZE
/ 512) - 33) / 2048;
2617 Log("GPT Reserved Disk Space:%llu MB", (ULONGLONG
)ReservedMB
);
2622 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2623 ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
2625 StartSector
= MBR
.PartTbl
[1].StartSectorId
;
2626 Log("MBR StartSector in PartTbl:%llu", (ULONGLONG
)StartSector
);
2628 ReservedMB
= (pPhyDrive
->SizeInBytes
/ 512 - (StartSector
+ VENTOY_EFI_PART_SIZE
/ 512)) / 2048;
2629 Log("MBR Reserved Disk Space:%llu MB", (ULONGLONG
)ReservedMB
);
2632 //Read Reserved Data
2633 SetFilePointer(hDrive
, 512 * 2040, NULL
, FILE_BEGIN
);
2634 ReadFile(hDrive
, ReservedData
, sizeof(ReservedData
), &dwSize
, NULL
);
2636 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
2638 if (DriveLetters
[0] == 0)
2640 Log("No drive letter was assigned...");
2644 // Unmount all mounted volumes that belong to this drive
2645 // Do it in reverse so that we always end on the first volume letter
2646 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
2648 DriveName
[0] = DriveLetters
[i
- 1];
2649 if (IsVentoyLogicalDrive(DriveName
[0]))
2651 Log("%s is ventoy logical drive", DriveName
);
2652 bRet
= DeleteVolumeMountPointA(DriveName
);
2653 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, LASTERR
);
2659 // It kind of blows, but we have to relinquish access to the physical drive
2660 // for VDS to be able to delete the partitions that reside on it...
2661 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2662 CHECK_CLOSE_HANDLE(hDrive
);
2664 if (pPhyDrive
->PartStyle
== 1)
2666 Log("TryId=%d EFI GPT partition type is 0x%llx", TryId
, pPhyDrive
->Part2GPTAttr
);
2667 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
2671 Log("Change GPT partition type to ESP");
2672 if (DISK_ChangeVtoyEFI2ESP(pPhyDrive
->PhyDrive
, StartSector
* 512ULL))
2678 else if (TryId
== 2)
2680 Log("Change GPT partition attribute");
2681 if (DISK_ChangeVtoyEFIAttr(pPhyDrive
->PhyDrive
, StartSector
* 512ULL, 0x8000000000000001))
2687 else if (TryId
== 3)
2689 DISK_DeleteVtoyEFIPartition(pPhyDrive
->PhyDrive
, StartSector
* 512ULL);
2692 else if (TryId
== 4)
2694 Log("Clean disk GPT partition table");
2695 if (BackupDataBeforeCleanDisk(pPhyDrive
->PhyDrive
, pPhyDrive
->SizeInBytes
, &pBackup
))
2697 sprintf_s(BackBinFile
, sizeof(BackBinFile
), ".\\ventoy\\phydrive%d_%u_%d.bin",
2698 pPhyDrive
->PhyDrive
, GetCurrentProcessId(), g_backup_bin_index
++);
2699 SaveBufToFile(BackBinFile
, pBackup
, 4 * SIZE_1MB
);
2700 Log("Save backup data to %s", BackBinFile
);
2702 Log("Success to backup data before clean");
2704 DISK_CleanDisk(pPhyDrive
->PhyDrive
);
2709 Log("Failed to backup data before clean");
2714 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
2716 Log("Lock disk for update ............................ ");
2717 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2718 if (hDrive
== INVALID_HANDLE_VALUE
)
2720 Log("Failed to GetPhysicalHandle for write.");
2725 PROGRESS_BAR_SET_POS(PT_LOCK_VOLUME
);
2727 Log("Lock volume for update .......................... ");
2728 hVolume
= INVALID_HANDLE_VALUE
;
2730 //If we change VTOYEFI to ESP, it can not have s volume name, so don't try to get it.
2733 //writeback the last 2MB
2734 if (!WriteBackupDataToDisk(hDrive
, pPhyDrive
->SizeInBytes
- SIZE_2MB
, pBackup
+ SIZE_2MB
, SIZE_2MB
))
2739 //write the first 2MB except parttable
2740 if (!WriteBackupDataToDisk(hDrive
, 34 * 512, pBackup
+ 34 * 512, SIZE_2MB
- 34 * 512))
2745 Status
= ERROR_NOT_FOUND
;
2749 Status
= ERROR_NOT_FOUND
;
2753 Status
= ERROR_NOT_FOUND
;
2757 for (i
= 0; i
< MaxRetry
; i
++)
2759 Status
= GetVentoyVolumeName(pPhyDrive
->PhyDrive
, StartSector
, DriveLetters
, sizeof(DriveLetters
), TRUE
);
2760 if (ERROR_SUCCESS
== Status
)
2766 Log("==== Volume not found, wait and retry %d... ====", i
);
2772 if (ERROR_SUCCESS
== Status
)
2774 Log("Now lock and dismount volume <%s>", DriveLetters
);
2776 for (i
= 0; i
< MaxRetry
; i
++)
2778 hVolume
= CreateFileA(DriveLetters
,
2779 GENERIC_READ
| GENERIC_WRITE
,
2783 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_NO_BUFFERING
| FILE_FLAG_WRITE_THROUGH
,
2786 if (hVolume
== INVALID_HANDLE_VALUE
)
2788 Log("Failed to create file volume, errcode:%u, wait and retry ...", LASTERR
);
2797 if (hVolume
== INVALID_HANDLE_VALUE
)
2799 Log("Failed to create file volume, errcode:%u", LASTERR
);
2803 bRet
= DeviceIoControl(hVolume
, FSCTL_LOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2804 Log("FSCTL_LOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2806 bRet
= DeviceIoControl(hVolume
, FSCTL_DISMOUNT_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2807 Log("FSCTL_DISMOUNT_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2810 else if (ERROR_NOT_FOUND
== Status
)
2812 Log("Volume not found, maybe not supported");
2820 bRet
= TryWritePart2(hDrive
, StartSector
);
2821 if (FALSE
== bRet
&& Esp2Basic
)
2823 Log("TryWritePart2 agagin ...");
2825 bRet
= TryWritePart2(hDrive
, StartSector
);
2830 if (pPhyDrive
->PartStyle
== 0)
2832 if (DiskCheckWriteAccess(hDrive
))
2834 Log("MBR DiskCheckWriteAccess success");
2838 Log("Try write failed, now delete partition 2 for MBR...");
2839 CHECK_CLOSE_HANDLE(hDrive
);
2841 Log("Now delete partition 2...");
2842 DISK_DeleteVtoyEFIPartition(pPhyDrive
->PhyDrive
, StartSector
* 512ULL);
2844 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2845 if (hDrive
== INVALID_HANDLE_VALUE
)
2847 Log("Failed to GetPhysicalHandle for write.");
2854 Log("MBR DiskCheckWriteAccess failed");
2859 Log("TryWritePart2 failed ....");
2865 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
2867 Log("Write Ventoy to disk ............................ ");
2868 if (0 != FormatPart2Fat(hDrive
, StartSector
))
2874 if (hVolume
!= INVALID_HANDLE_VALUE
)
2876 bRet
= DeviceIoControl(hVolume
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2877 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2878 CHECK_CLOSE_HANDLE(hVolume
);
2881 Log("Updating Boot Image ............................. ");
2882 if (WriteGrubStage1ToPhyDrive(hDrive
, pPhyDrive
->PartStyle
) != 0)
2888 //write reserved data
2889 SetFilePointer(hDrive
, 512 * 2040, NULL
, FILE_BEGIN
);
2890 bRet
= WriteFile(hDrive
, ReservedData
, sizeof(ReservedData
), &dwSize
, NULL
);
2891 Log("Write resv data ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2894 VentoyGetLocalBootImg(&BootImg
);
2897 memcpy(BootImg
.BootCode
+ 0x180, MBR
.BootCode
+ 0x180, 16);
2898 if (pPhyDrive
->PartStyle
)
2900 BootImg
.BootCode
[92] = 0x22;
2903 if (ForceMBR
== FALSE
&& memcmp(BootImg
.BootCode
, MBR
.BootCode
, 440) == 0)
2905 Log("Boot image has no difference, no need to write.");
2909 Log("Boot image need to write %u.", ForceMBR
);
2911 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2913 memcpy(MBR
.BootCode
, BootImg
.BootCode
, 440);
2914 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
2915 Log("Write Boot Image ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2918 if (pPhyDrive
->PartStyle
== 0)
2920 if (0x00 == MBR
.PartTbl
[0].Active
&& 0x80 == MBR
.PartTbl
[1].Active
)
2922 Log("Need to chage 1st partition active and 2nd partition inactive.");
2924 MBR
.PartTbl
[0].Active
= 0x80;
2925 MBR
.PartTbl
[1].Active
= 0x00;
2927 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2928 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
2929 Log("Write NEW MBR ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2935 if (!WriteBackupDataToDisk(hDrive
, 0, pBackup
, 34 * 512))
2944 Log("Write backup data success, now delete %s", BackBinFile
);
2945 DeleteFileA(BackBinFile
);
2949 Log("Write backup data failed");
2956 VTOY_GPT_HDR BackupHdr
;
2958 VentoyFillBackupGptHead(pGptBkup
, &BackupHdr
);
2959 if (!WriteBackupDataToDisk(hDrive
, 512 * pGptBkup
->Head
.EfiBackupLBA
, (BYTE
*)(&BackupHdr
), 512))
2964 if (!WriteBackupDataToDisk(hDrive
, 512 * (pGptBkup
->Head
.EfiBackupLBA
- 32), (BYTE
*)(pGptBkup
->PartTbl
), 32 * 512))
2969 if (!WriteBackupDataToDisk(hDrive
, 512, (BYTE
*)pGptBkup
+ 512, 33 * 512))
2976 Log("Write backup partition table success");
2980 Log("Write backup partition table failed");
2986 //Refresh Drive Layout
2987 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2991 if (hVolume
!= INVALID_HANDLE_VALUE
)
2993 bRet
= DeviceIoControl(hVolume
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2994 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2995 CHECK_CLOSE_HANDLE(hVolume
);
3004 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
3005 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
3008 CHECK_CLOSE_HANDLE(hDrive
);
3012 Log("Recover GPT partition type to basic");
3013 DISK_ChangeVtoyEFI2Basic(pPhyDrive
->PhyDrive
, StartSector
* 512);
3016 if (pPhyDrive
->PartStyle
== 1)
3018 if (ChangeAttr
|| ((pPhyDrive
->Part2GPTAttr
>> 56) != 0xC0))
3020 Log("Change EFI partition attr %u <0x%llx> to <0x%llx>", ChangeAttr
, pPhyDrive
->Part2GPTAttr
, 0xC000000000000001ULL
);
3021 if (DISK_ChangeVtoyEFIAttr(pPhyDrive
->PhyDrive
, StartSector
* 512ULL, 0xC000000000000001ULL
))
3023 Log("Change EFI partition attr success");
3024 pPhyDrive
->Part2GPTAttr
= 0xC000000000000001ULL
;
3028 Log("Change EFI partition attr failed");