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");
1230 int ClearVentoyFromPhyDrive(HWND hWnd
, PHY_DRIVE_INFO
*pPhyDrive
, char *pDrvLetter
)
1239 CHAR DriveName
[] = "?:\\";
1240 CHAR DriveLetters
[MAX_PATH
] = { 0 };
1241 LARGE_INTEGER liCurrentPosition
;
1242 char *pTmpBuf
= NULL
;
1247 Log("ClearVentoyFromPhyDrive PhyDrive%d <<%s %s %dGB>>",
1248 pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1249 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1251 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1253 Log("Lock disk for clean ............................. ");
1255 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
1256 if (hDrive
== INVALID_HANDLE_VALUE
)
1258 Log("Failed to open physical disk");
1262 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1264 if (DriveLetters
[0] == 0)
1266 Log("No drive letter was assigned...");
1267 DriveName
[0] = GetFirstUnusedDriveLetter();
1268 Log("GetFirstUnusedDriveLetter %C: ...", DriveName
[0]);
1272 // Unmount all mounted volumes that belong to this drive
1273 // Do it in reverse so that we always end on the first volume letter
1274 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
1276 DriveName
[0] = DriveLetters
[i
- 1];
1277 bRet
= DeleteVolumeMountPointA(DriveName
);
1278 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, GetLastError());
1282 MountDrive
= DriveName
[0];
1283 Log("Will use '%C:' as volume mountpoint", DriveName
[0]);
1285 // It kind of blows, but we have to relinquish access to the physical drive
1286 // for VDS to be able to delete the partitions that reside on it...
1287 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1288 CHECK_CLOSE_HANDLE(hDrive
);
1290 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
1292 if (!VDS_DeleteAllPartitions(pPhyDrive
->PhyDrive
))
1294 Log("Notice: Could not delete partitions: %u", GetLastError());
1297 Log("Deleting all partitions ......................... OK");
1299 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
1301 Log("Lock disk for write ............................. ");
1302 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1303 if (hDrive
== INVALID_HANDLE_VALUE
)
1305 Log("Failed to GetPhysicalHandle for write.");
1310 // clear first and last 2MB space
1311 pTmpBuf
= malloc(SIZE_2MB
);
1314 Log("Failed to alloc memory.");
1318 memset(pTmpBuf
, 0, SIZE_2MB
);
1321 bRet
= WriteFile(hDrive
, pTmpBuf
, SIZE_2MB
- 512, &dwSize
, NULL
);
1322 Log("Write fisrt 1MB ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1329 SET_FILE_POS(pPhyDrive
->SizeInBytes
- SIZE_2MB
);
1330 bRet
= WriteFile(hDrive
, pTmpBuf
, SIZE_2MB
, &dwSize
, NULL
);
1331 Log("Write 2nd 1MB ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1340 if (pPhyDrive
->SizeInBytes
> 2199023255552ULL)
1342 VTOY_GPT_INFO
*pGptInfo
;
1343 VTOY_GPT_HDR BackupHead
;
1344 LARGE_INTEGER liCurrentPosition
;
1346 pGptInfo
= (VTOY_GPT_INFO
*)pTmpBuf
;
1348 VentoyFillWholeGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1350 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512);
1351 VentoyFillBackupGptHead(pGptInfo
, &BackupHead
);
1352 if (!WriteFile(hDrive
, &BackupHead
, sizeof(VTOY_GPT_HDR
), &dwSize
, NULL
))
1355 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1359 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512 * 33);
1360 if (!WriteFile(hDrive
, pGptInfo
->PartTbl
, sizeof(pGptInfo
->PartTbl
), &dwSize
, NULL
))
1363 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1368 if (!WriteFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
))
1371 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1375 Log("Write GPT Info OK ...");
1379 bRet
= ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
1380 Log("Read MBR ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1387 //clear boot code and partition table (reserved disk signature)
1388 memset(MBR
.BootCode
, 0, 440);
1389 memset(MBR
.PartTbl
, 0, sizeof(MBR
.PartTbl
));
1391 VentoyFillMBRLocation(pPhyDrive
->SizeInBytes
, 2048, (UINT32
)(pPhyDrive
->SizeInBytes
/ 512 - 2048), MBR
.PartTbl
);
1393 MBR
.PartTbl
[0].Active
= 0x00; // bootable
1394 MBR
.PartTbl
[0].FsFlag
= 0x07; // exFAT/NTFS/HPFS
1397 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
1398 Log("Write MBR ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1406 Log("Clear Ventoy successfully finished");
1408 //Refresh Drive Layout
1409 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1413 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1414 PROGRESS_BAR_SET_POS(PT_REFORMAT_FINISH
);
1423 Log("Mounting Ventoy Partition ....................... ");
1427 memset(DriveLetters
, 0, sizeof(DriveLetters
));
1428 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1429 Log("Logical drive letter after write ventoy: <%s>", DriveLetters
);
1431 for (i
= 0; i
< sizeof(DriveLetters
) && DriveLetters
[i
]; i
++)
1433 DriveName
[0] = DriveLetters
[i
];
1434 Log("%s is ventoy part1, already mounted", DriveName
);
1440 Log("need to mount ventoy part1...");
1441 if (0 == GetVentoyVolumeName(pPhyDrive
->PhyDrive
, 2048, DriveLetters
, sizeof(DriveLetters
), FALSE
))
1443 DriveName
[0] = MountDrive
;
1444 bRet
= SetVolumeMountPointA(DriveName
, DriveLetters
);
1445 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName
, DriveLetters
, bRet
, GetLastError());
1447 *pDrvLetter
= MountDrive
;
1451 Log("Failed to find ventoy volume");
1459 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
1462 CHECK_CLOSE_HANDLE(hDrive
);
1466 int InstallVentoy2FileImage(PHY_DRIVE_INFO
*pPhyDrive
, int PartStyle
)
1475 UINT64 data_offset
= 0;
1476 UINT64 Part2StartSector
= 0;
1477 UINT64 Part1StartSector
= 0;
1478 UINT64 Part1SectorCount
= 0;
1479 UINT8
*pData
= NULL
;
1480 UINT8
*pBkGptPartTbl
= NULL
;
1481 BYTE
*ImgBuf
= NULL
;
1482 MBR_HEAD
*pMBR
= NULL
;
1483 VTSI_FOOTER
*pImgFooter
= NULL
;
1484 VTSI_SEGMENT
*pSegment
= NULL
;
1485 VTOY_GPT_INFO
*pGptInfo
= NULL
;
1486 VTOY_GPT_HDR
*pBkGptHdr
= NULL
;
1489 Log("InstallVentoy2FileImage %s PhyDrive%d <<%s %s %dGB>>",
1490 PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1491 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1493 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1495 size
= SIZE_1MB
+ VENTOY_EFI_PART_SIZE
+ 33 * 512 + VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
) + sizeof(VTSI_FOOTER
);
1497 pData
= (UINT8
*)malloc(size
);
1500 Log("malloc image buffer failed %d.", size
);
1504 pImgFooter
= (VTSI_FOOTER
*)(pData
+ size
- sizeof(VTSI_FOOTER
));
1505 pSegment
= (VTSI_SEGMENT
*)((UINT8
*)pImgFooter
- VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
));
1506 memset(pImgFooter
, 0, sizeof(VTSI_FOOTER
));
1507 memset(pSegment
, 0, VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
));
1509 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START
);
1511 Log("Writing Boot Image ............................. ");
1512 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG
, 0, (void **)&ImgBuf
, &Len
))
1514 Log("Failed to read stage1 img");
1518 unxz(ImgBuf
, Len
, NULL
, NULL
, pData
, &dataLen
, unxz_error
);
1521 Log("decompress %s len:%d", VENTOY_FILE_STG1_IMG
, dataLen
);
1525 pData
[500] = 35;//update blocklist
1526 memmove(pData
+ 34 * 512, pData
, SIZE_1MB
- 512 * 34);
1527 memset(pData
, 0, 34 * 512);
1529 pGptInfo
= (VTOY_GPT_INFO
*)pData
;
1530 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
1531 VentoyFillGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1533 pBkGptPartTbl
= pData
+ SIZE_1MB
+ VENTOY_EFI_PART_SIZE
;
1534 memset(pBkGptPartTbl
, 0, 33 * 512);
1536 memcpy(pBkGptPartTbl
, pGptInfo
->PartTbl
, 32 * 512);
1537 pBkGptHdr
= (VTOY_GPT_HDR
*)(pBkGptPartTbl
+ 32 * 512);
1538 VentoyFillBackupGptHead(pGptInfo
, pBkGptHdr
);
1540 Part1StartSector
= pGptInfo
->PartTbl
[0].StartLBA
;
1541 Part1SectorCount
= pGptInfo
->PartTbl
[0].LastLBA
- Part1StartSector
+ 1;
1542 Part2StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
1544 Log("Write GPT Info OK ...");
1548 memmove(pData
+ 512, pData
, SIZE_1MB
- 512);
1549 memset(pData
, 0, 512);
1551 pMBR
= (MBR_HEAD
*)pData
;
1552 VentoyFillMBR(pPhyDrive
->SizeInBytes
, pMBR
, PartStyle
);
1553 Part1StartSector
= pMBR
->PartTbl
[0].StartSectorId
;
1554 Part1SectorCount
= pMBR
->PartTbl
[0].SectorCount
;
1555 Part2StartSector
= pMBR
->PartTbl
[1].StartSectorId
;
1557 Log("Write MBR OK ...");
1560 Log("Writing EFI part Image ............................. ");
1561 rc
= ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG
, 0, (void **)&ImgBuf
, &Len
);
1564 Log("Failed to read img file %p %u", ImgBuf
, Len
);
1568 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START
+ 28);
1569 memset(g_part_img_buf
, 0, sizeof(g_part_img_buf
));
1570 unxz(ImgBuf
, Len
, NULL
, NULL
, pData
+ SIZE_1MB
, &dataLen
, unxz_error
);
1573 Log("decompress finished success");
1574 g_part_img_buf
[0] = pData
+ SIZE_1MB
;
1576 VentoyProcSecureBoot(g_SecureBoot
);
1580 Log("decompress finished failed");
1584 fopen_s(&fp
, "VentoySparseImg.vtsi", "wb+");
1587 Log("Failed to create Ventoy img file");
1591 Log("Writing stage1 data ............................. ");
1593 fwrite(pData
, 1, SIZE_1MB
, fp
);
1595 pSegment
[0].disk_start_sector
= 0;
1596 pSegment
[0].sector_num
= SIZE_1MB
/ 512;
1597 pSegment
[0].data_offset
= data_offset
;
1598 data_offset
+= pSegment
[0].sector_num
* 512;
1600 disk_io_set_param(INVALID_HANDLE_VALUE
, Part1StartSector
+ Part1SectorCount
);// include the 2048 sector gap
1601 disk_io_set_imghook(fp
, pSegment
+ 1, VTSI_IMG_MAX_SEG
- 1, data_offset
);
1603 Log("Formatting part1 exFAT ...");
1604 if (0 != FormatPart1exFAT(pPhyDrive
->SizeInBytes
))
1606 Log("FormatPart1exFAT failed.");
1607 disk_io_reset_imghook(&segnum
, &data_offset
);
1611 disk_io_reset_imghook(&segnum
, &data_offset
);
1614 Log("current segment number:%d dataoff:%ld", segnum
, (long)data_offset
);
1617 Log("Writing part2 data ............................. ");
1618 fwrite(pData
+ SIZE_1MB
, 1, VENTOY_EFI_PART_SIZE
, fp
);
1619 pSegment
[segnum
].disk_start_sector
= Part2StartSector
;
1620 pSegment
[segnum
].sector_num
= VENTOY_EFI_PART_SIZE
/ 512;
1621 pSegment
[segnum
].data_offset
= data_offset
;
1622 data_offset
+= pSegment
[segnum
].sector_num
* 512;
1627 Log("Writing backup gpt table ............................. ");
1628 fwrite(pBkGptPartTbl
, 1, 33 * 512, fp
);
1629 pSegment
[segnum
].disk_start_sector
= pPhyDrive
->SizeInBytes
/ 512 - 33;
1630 pSegment
[segnum
].sector_num
= 33;
1631 pSegment
[segnum
].data_offset
= data_offset
;
1632 data_offset
+= pSegment
[segnum
].sector_num
* 512;
1636 Log("Writing segment metadata ............................. ");
1638 for (i
= 0; i
< (int)segnum
; i
++)
1640 Log("SEG[%d]: PhySector:%llu SectorNum:%llu DataOffset:%llu(sector:%llu)", i
, pSegment
[i
].disk_start_sector
, pSegment
[i
].sector_num
,
1641 pSegment
[i
].data_offset
, pSegment
[i
].data_offset
/ 512);
1644 dataLen
= segnum
* sizeof(VTSI_SEGMENT
);
1645 fwrite(pSegment
, 1, dataLen
, fp
);
1649 //pData + SIZE_1MB - 8192 is a temp data buffer with zero
1650 fwrite(pData
+ SIZE_1MB
- 8192, 1, 512 - (dataLen
% 512), fp
);
1654 pImgFooter
->magic
= VTSI_IMG_MAGIC
;
1655 pImgFooter
->version
= 1;
1656 pImgFooter
->disk_size
= pPhyDrive
->SizeInBytes
;
1657 memcpy(&pImgFooter
->disk_signature
, pPhyDrive
->MBR
.BootCode
+ 0x1b8, 4);
1658 pImgFooter
->segment_num
= segnum
;
1659 pImgFooter
->segment_offset
= data_offset
;
1661 for (i
= 0, chksum
= 0; i
< (int)(segnum
* sizeof(VTSI_SEGMENT
)); i
++)
1663 chksum
+= *((UINT8
*)pSegment
+ i
);
1665 pImgFooter
->segment_chksum
= ~chksum
;
1667 for (i
= 0, chksum
= 0; i
< sizeof(VTSI_FOOTER
); i
++)
1669 chksum
+= *((UINT8
*)pImgFooter
+ i
);
1671 pImgFooter
->foot_chksum
= ~chksum
;
1673 Log("Writing footer segnum(%u) segoffset(%llu) ......................", segnum
, data_offset
);
1674 Log("disk_size=%llu disk_signature=%lx segment_offset=%llu", pImgFooter
->disk_size
, pImgFooter
->disk_signature
, pImgFooter
->segment_offset
);
1676 fwrite(pImgFooter
, 1, sizeof(VTSI_FOOTER
), fp
);
1679 Log("Writing Ventoy image file finished, the file size should be %llu .", data_offset
+ 512 + ((dataLen
+ 511) / 512 * 512));
1685 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1686 PROGRESS_BAR_SET_POS(PT_REFORMAT_FINISH
);
1688 Log("retcode:%d\n", rc
);
1697 int InstallVentoy2PhyDrive(PHY_DRIVE_INFO
*pPhyDrive
, int PartStyle
, int TryId
)
1707 CHAR DriveName
[] = "?:\\";
1708 CHAR DriveLetters
[MAX_PATH
] = { 0 };
1710 VTOY_GPT_INFO
*pGptInfo
= NULL
;
1711 UINT64 Part1StartSector
= 0;
1712 UINT64 Part1SectorCount
= 0;
1713 UINT64 Part2StartSector
= 0;
1714 BOOL LargeFAT32
= FALSE
;
1716 Log("#####################################################");
1717 Log("InstallVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId
,
1718 PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1719 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1720 Log("#####################################################");
1724 pGptInfo
= malloc(sizeof(VTOY_GPT_INFO
));
1725 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
1728 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1732 VentoyFillGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1733 Part1StartSector
= pGptInfo
->PartTbl
[0].StartLBA
;
1734 Part1SectorCount
= pGptInfo
->PartTbl
[0].LastLBA
- Part1StartSector
+ 1;
1735 Part2StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
1739 VentoyFillMBR(pPhyDrive
->SizeInBytes
, &MBR
, PartStyle
);
1740 Part1StartSector
= MBR
.PartTbl
[0].StartSectorId
;
1741 Part1SectorCount
= MBR
.PartTbl
[0].SectorCount
;
1742 Part2StartSector
= MBR
.PartTbl
[1].StartSectorId
;
1745 Log("Lock disk for clean ............................. ");
1747 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
1748 if (hDrive
== INVALID_HANDLE_VALUE
)
1750 Log("Failed to open physical disk");
1755 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1757 if (DriveLetters
[0] == 0)
1759 Log("No drive letter was assigned...");
1760 DriveName
[0] = GetFirstUnusedDriveLetter();
1761 Log("GetFirstUnusedDriveLetter %C: ...", DriveName
[0]);
1765 // Unmount all mounted volumes that belong to this drive
1766 // Do it in reverse so that we always end on the first volume letter
1767 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
1769 DriveName
[0] = DriveLetters
[i
- 1];
1770 bRet
= DeleteVolumeMountPointA(DriveName
);
1771 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, GetLastError());
1775 MountDrive
= DriveName
[0];
1776 Log("Will use '%C:' as volume mountpoint", DriveName
[0]);
1778 // It kind of blows, but we have to relinquish access to the physical drive
1779 // for VDS to be able to delete the partitions that reside on it...
1780 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1781 CHECK_CLOSE_HANDLE(hDrive
);
1783 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
1785 if (!VDS_DeleteAllPartitions(pPhyDrive
->PhyDrive
))
1787 Log("Notice: Could not delete partitions: 0x%x, but we continue.", GetLastError());
1790 Log("Deleting all partitions ......................... OK");
1792 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
1794 Log("Lock disk for write ............................. ");
1795 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1796 if (hDrive
== INVALID_HANDLE_VALUE
)
1798 Log("Failed to GetPhysicalHandle for write.");
1803 //Refresh Drive Layout
1804 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1806 disk_io_set_param(hDrive
, Part1StartSector
+ Part1SectorCount
);// include the 2048 sector gap
1808 PROGRESS_BAR_SET_POS(PT_FORMAT_PART1
);
1810 if (PartStyle
== 1 && pPhyDrive
->PartStyle
== 0)
1812 Log("Wait for format part1 ...");
1816 if (GetVentoyFsType() == VTOY_FS_FAT32
&& (Part1SectorCount
* 512 >= FAT32_MAX_LIMIT
))
1818 Log("Formatting part1 large FAT32 ...");
1820 if (0 != FormatPart1LargeFAT32(pPhyDrive
->SizeInBytes
, GetClusterSize()))
1822 Log("FormatPart1LargeFAT32 failed.");
1829 CHAR TmpBuffer
[512] = { 0 };
1831 Log("Zero part1 file system ...");
1832 SetFilePointer(hDrive
, VENTOY_PART1_START_SECTOR
* 512, NULL
, FILE_BEGIN
);
1833 for (i
= 0; i
< 32; i
++)
1835 WriteFile(hDrive
, TmpBuffer
, 512, &dwSize
, NULL
);
1839 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
1840 Log("Writing part2 FAT img ...");
1842 if (0 != FormatPart2Fat(hDrive
, Part2StartSector
))
1844 Log("FormatPart2Fat failed.");
1849 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG
);
1850 Log("Writing Boot Image ............................. ");
1851 if (WriteGrubStage1ToPhyDrive(hDrive
, PartStyle
) != 0)
1853 Log("WriteGrubStage1ToPhyDrive failed.");
1858 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE
);
1859 Log("Writing Partition Table ........................ ");
1860 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
1864 VTOY_GPT_HDR BackupHead
;
1865 LARGE_INTEGER liCurrentPosition
;
1867 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512);
1868 VentoyFillBackupGptHead(pGptInfo
, &BackupHead
);
1869 if (!WriteFile(hDrive
, &BackupHead
, sizeof(VTOY_GPT_HDR
), &dwSize
, NULL
))
1872 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1876 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512 * 33);
1877 if (!WriteFile(hDrive
, pGptInfo
->PartTbl
, sizeof(pGptInfo
->PartTbl
), &dwSize
, NULL
))
1880 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1885 if (!WriteFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
))
1888 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1892 Log("Write GPT Info OK ...");
1893 memcpy(&(pPhyDrive
->MBR
), &(pGptInfo
->MBR
), 512);
1897 if (!WriteFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
))
1900 Log("Write MBR Failed, dwSize:%u ErrCode:%u", dwSize
, GetLastError());
1903 Log("Write MBR OK ...");
1904 memcpy(&(pPhyDrive
->MBR
), &MBR
, 512);
1907 //Refresh Drive Layout
1908 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1912 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1916 Log("Mounting Ventoy Partition ....................... ");
1920 memset(DriveLetters
, 0, sizeof(DriveLetters
));
1921 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1922 Log("Logical drive letter after write ventoy: <%s>", DriveLetters
);
1924 for (i
= 0; i
< sizeof(DriveLetters
) && DriveLetters
[i
]; i
++)
1926 DriveName
[0] = DriveLetters
[i
];
1927 if (IsVentoyLogicalDrive(DriveName
[0]))
1929 Log("%s is ventoy part2, delete mountpoint", DriveName
);
1930 DeleteVolumeMountPointA(DriveName
);
1934 Log("%s is ventoy part1, already mounted", DriveName
);
1935 MountDrive
= DriveName
[0];
1942 Log("need to mount ventoy part1...");
1944 if (0 == GetVentoyVolumeName(pPhyDrive
->PhyDrive
, Part1StartSector
, DriveLetters
, sizeof(DriveLetters
), FALSE
))
1946 DriveName
[0] = MountDrive
;
1947 bRet
= SetVolumeMountPointA(DriveName
, DriveLetters
);
1948 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName
, DriveLetters
, bRet
, GetLastError());
1957 Log("Failed to find ventoy volume");
1961 // close handle, or it will deny reformat
1962 Log("Close handle ...");
1963 CHECK_CLOSE_HANDLE(hDrive
);
1971 Log("No need to reformat for large FAT32");
1972 pPhyDrive
->VentoyFsClusterSize
= GetVolumeClusterSize(MountDrive
);
1976 bRet
= DISK_FormatVolume(MountDrive
, GetVentoyFsType(), Part1SectorCount
* 512);
1977 for (i
= 0; bRet
== FALSE
&& i
< 2; i
++)
1979 Log("Wait and retry reformat ...");
1981 bRet
= DISK_FormatVolume(MountDrive
, GetVentoyFsType(), Part1SectorCount
* 512);
1987 Log("Reformat %C:\\ to %s SUCCESS", MountDrive
, GetVentoyFsName());
1988 pPhyDrive
->VentoyFsClusterSize
= GetVolumeClusterSize(MountDrive
);
1990 if ((GetVentoyFsType() != VTOY_FS_UDF
) && (pPhyDrive
->VentoyFsClusterSize
< 2048))
1992 for (i
= 0; i
< 10; i
++)
1994 Log("### Invalid cluster size %d ###", pPhyDrive
->VentoyFsClusterSize
);
2000 Log("Reformat %C:\\ to %s FAILED", MountDrive
, GetVentoyFsName());
2006 Log("Can not reformat %s to %s", DriveName
, GetVentoyFsName());
2011 Log("Format to exfat with built-in algorithm");
2013 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2014 if (hDrive
== INVALID_HANDLE_VALUE
)
2016 Log("Failed to GetPhysicalHandle for write.");
2020 if (0 != FormatPart1exFAT(pPhyDrive
->SizeInBytes
))
2022 Log("FormatPart1exFAT SUCCESS.");
2026 Log("FormatPart1exFAT FAILED.");
2029 CHECK_CLOSE_HANDLE(hDrive
);
2037 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2039 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
2041 if (!VDS_IsLastAvaliable())
2043 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2044 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2045 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2046 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2047 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2050 CHECK_CLOSE_HANDLE(hDrive
);
2062 int PartitionResizeForVentoy(PHY_DRIVE_INFO
*pPhyDrive
)
2068 INT64 ReservedValue
;
2072 VTOY_GPT_INFO
*pGPT
;
2075 VTOY_GPT_HDR BackupHead
;
2076 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
2077 GUID ZeroGuid
= { 0 };
2078 static GUID WindowsDataPartType
= { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
2079 static GUID EspPartType
= { 0xc12a7328, 0xf81f, 0x11d2, { 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b } };
2080 static GUID BiosGrubPartType
= { 0x21686148, 0x6449, 0x6e6f, { 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46, 0x49 } };
2082 Log("#####################################################");
2083 Log("PartitionResizeForVentoy PhyDrive%d <<%s %s %dGB>>",
2084 pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
2085 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
2086 Log("#####################################################");
2088 pGPT
= &(pPhyDrive
->Gpt
);
2089 pMBR
= &(pPhyDrive
->Gpt
.MBR
);
2090 Log("Disksize:%llu Part2Start:%llu", pPhyDrive
->SizeInBytes
, pPhyDrive
->ResizePart2StartSector
* 512);
2092 if (pMBR
->PartTbl
[0].FsFlag
== 0xEE && memcmp(pGPT
->Head
.Signature
, "EFI PART", 8) == 0)
2101 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2103 RecudeBytes
= VENTOY_EFI_PART_SIZE
;
2104 ReservedValue
= GetReservedSpaceInMB();
2105 if (ReservedValue
> 0)
2107 Log("Reduce add reserved space %lldMB", (LONGLONG
)ReservedValue
);
2108 RecudeBytes
+= (UINT64
)(ReservedValue
* SIZE_1MB
);
2112 if (pPhyDrive
->ResizeNoShrink
== FALSE
)
2114 Log("Need to shrink the volume");
2115 if (DISK_ShrinkVolume(pPhyDrive
->PhyDrive
, pPhyDrive
->ResizeVolumeGuid
, pPhyDrive
->Part1DriveLetter
, pPhyDrive
->ResizeOldPart1Size
, RecudeBytes
))
2117 Log("Shrink volume success, now check again");
2119 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2120 if (hDrive
== INVALID_HANDLE_VALUE
)
2122 Log("Failed to GetPhysicalHandle for update.");
2126 //Refresh Drive Layout
2127 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2129 CHECK_CLOSE_HANDLE(hDrive
);
2132 if (PartResizePreCheck(NULL
) && pPhyDrive
->ResizeNoShrink
)
2134 Log("Recheck after Shrink volume success");
2135 Log("After shrink Disksize:%llu Part2Start:%llu", pPhyDrive
->SizeInBytes
, pPhyDrive
->ResizePart2StartSector
* 512);
2139 Log("Recheck after Shrink volume failed %u", pPhyDrive
->ResizeNoShrink
);
2145 Log("Shrink volume failed");
2151 //Now try write data
2152 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2153 if (hDrive
== INVALID_HANDLE_VALUE
)
2155 Log("Failed to GetPhysicalHandle for update.");
2160 //Write partition 2 data
2161 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
2162 if (0 != FormatPart2Fat(hDrive
, pPhyDrive
->ResizePart2StartSector
))
2164 Log("FormatPart2Fat failed.");
2168 //Write grub stage2 gap
2169 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG
);
2170 Log("Writing Boot Image ............................. ");
2171 if (WriteGrubStage1ToPhyDrive(hDrive
, PartStyle
) != 0)
2173 Log("WriteGrubStage1ToPhyDrive failed.");
2178 //Write partition table
2179 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE
);
2180 Log("Writing partition table ............................. ");
2182 VentoyGetLocalBootImg(&MBR
);
2183 CoCreateGuid(&Guid
);
2184 memcpy(MBR
.BootCode
+ 0x180, &Guid
, 16);
2185 memcpy(pMBR
->BootCode
, MBR
.BootCode
, 440);
2189 for (i
= 1; i
< 4; i
++)
2191 if (pMBR
->PartTbl
[i
].SectorCount
== 0)
2199 Log("Can not find MBR free partition table");
2203 for (j
= i
- 1; j
> 0; j
--)
2205 Log("Move MBR partition table %d --> %d", j
+ 1, j
+ 2);
2206 memcpy(pMBR
->PartTbl
+ (j
+ 1), pMBR
->PartTbl
+ j
, sizeof(PART_TABLE
));
2209 memset(pMBR
->PartTbl
+ 1, 0, sizeof(PART_TABLE
));
2210 VentoyFillMBRLocation(pPhyDrive
->SizeInBytes
, (UINT32
)pPhyDrive
->ResizePart2StartSector
, VENTOY_EFI_PART_SIZE
/ 512, pMBR
->PartTbl
+ 1);
2211 pMBR
->PartTbl
[0].Active
= 0x80; // bootable
2212 pMBR
->PartTbl
[1].Active
= 0x00;
2213 pMBR
->PartTbl
[1].FsFlag
= 0xEF; // EFI System Partition
2215 if (!WriteDataToPhyDisk(hDrive
, 0, pMBR
, 512))
2217 Log("Legacy BIOS write MBR failed");
2223 for (i
= 1; i
< 128; i
++)
2225 if (memcmp(&(pGPT
->PartTbl
[i
].PartGuid
), &ZeroGuid
, sizeof(GUID
)) == 0)
2233 Log("Can not find GPT free partition table");
2237 for (j
= i
- 1; j
> 0; j
--)
2239 Log("Move GPT partition table %d --> %d", j
+ 1, j
+ 2);
2240 memcpy(pGPT
->PartTbl
+ (j
+ 1), pGPT
->PartTbl
+ j
, sizeof(VTOY_GPT_PART_TBL
));
2244 pMBR
->BootCode
[92] = 0x22;
2246 // to fix windows issue
2247 memset(pGPT
->PartTbl
+ 1, 0, sizeof(VTOY_GPT_PART_TBL
));
2248 memcpy(&(pGPT
->PartTbl
[1].PartType
), &WindowsDataPartType
, sizeof(GUID
));
2249 CoCreateGuid(&(pGPT
->PartTbl
[1].PartGuid
));
2251 pGPT
->PartTbl
[1].StartLBA
= pGPT
->PartTbl
[0].LastLBA
+ 1;
2252 pGPT
->PartTbl
[1].LastLBA
= pGPT
->PartTbl
[1].StartLBA
+ VENTOY_EFI_PART_SIZE
/ 512 - 1;
2253 pGPT
->PartTbl
[1].Attr
= 0xC000000000000001ULL
;
2254 memcpy(pGPT
->PartTbl
[1].Name
, L
"VTOYEFI", 7 * 2);
2257 pGPT
->Head
.PartTblCrc
= VentoyCrc32(pGPT
->PartTbl
, sizeof(pGPT
->PartTbl
));
2259 pGPT
->Head
.Crc
= VentoyCrc32(&(pGPT
->Head
), pGPT
->Head
.Length
);
2261 Log("pGPT->Head.EfiStartLBA=%llu", (ULONGLONG
)pGPT
->Head
.EfiStartLBA
);
2262 Log("pGPT->Head.EfiBackupLBA=%llu", (ULONGLONG
)pGPT
->Head
.EfiBackupLBA
);
2264 VentoyFillBackupGptHead(pGPT
, &BackupHead
);
2265 if (!WriteDataToPhyDisk(hDrive
, pGPT
->Head
.EfiBackupLBA
* 512, &BackupHead
, 512))
2267 Log("UEFI write backup head failed");
2271 if (!WriteDataToPhyDisk(hDrive
, (pGPT
->Head
.EfiBackupLBA
- 32) * 512, pGPT
->PartTbl
, 512 * 32))
2273 Log("UEFI write backup partition table failed");
2277 if (!WriteDataToPhyDisk(hDrive
, 0, pGPT
, 512 * 34))
2279 Log("UEFI write MBR & Main partition table failed");
2286 //Refresh Drive Layout
2287 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2289 //We must close handle here, because it will block the refresh bellow
2290 CHECK_CLOSE_HANDLE(hDrive
);
2295 PhyDrive
= pPhyDrive
->PhyDrive
;
2297 Log("#### Now Refresh PhyDrive ####");
2298 Ventoy2DiskDestroy();
2301 pPhyDrive
= GetPhyDriveInfoByPhyDrive(PhyDrive
);
2304 if (pPhyDrive
->VentoyVersion
[0] == 0)
2306 Log("After process the Ventoy version is still invalid");
2310 Log("### Ventoy non-destructive installation successfully finished <%s>", pPhyDrive
->VentoyVersion
);
2314 Log("### Ventoy non-destructive installation successfully finished <not found>");
2317 InitComboxCtrl(g_DialogHwnd
, PhyDrive
);
2322 CHECK_CLOSE_HANDLE(hDrive
);
2327 static BOOL
DiskCheckWriteAccess(HANDLE hDrive
)
2333 LARGE_INTEGER liCurPosition
;
2334 LARGE_INTEGER liNewPosition
;
2336 liCurPosition
.QuadPart
= 2039 * 512;
2337 liNewPosition
.QuadPart
= 0;
2338 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2339 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2341 Log("SetFilePointer1 Failed %u", LASTERR
);
2347 ret
= ReadFile(hDrive
, Buffer
, 512, &dwSize
, NULL
);
2348 if ((!ret
) || (dwSize
!= 512))
2350 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2355 liCurPosition
.QuadPart
= 2039 * 512;
2356 liNewPosition
.QuadPart
= 0;
2357 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2358 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2360 Log("SetFilePointer2 Failed %u", LASTERR
);
2365 ret
= WriteFile(hDrive
, Buffer
, 512, &dwSize
, NULL
);
2366 if ((!ret
) || dwSize
!= 512)
2368 Log("Failed to write %d %u %u", ret
, dwSize
, LASTERR
);
2379 static BOOL
BackupDataBeforeCleanDisk(int PhyDrive
, UINT64 DiskSize
, BYTE
**pBackup
)
2383 BOOL Return
= FALSE
;
2385 BYTE
*backup
= NULL
;
2387 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
2388 LARGE_INTEGER liCurPosition
;
2389 LARGE_INTEGER liNewPosition
;
2390 VTOY_GPT_INFO
*pGPT
= NULL
;
2392 Log("BackupDataBeforeCleanDisk %d", PhyDrive
);
2394 // step1: check write access
2395 hDrive
= GetPhysicalHandle(PhyDrive
, TRUE
, TRUE
, FALSE
);
2396 if (hDrive
== INVALID_HANDLE_VALUE
)
2398 Log("Failed to GetPhysicalHandle for write.");
2402 if (DiskCheckWriteAccess(hDrive
))
2404 Log("DiskCheckWriteAccess success");
2405 CHECK_CLOSE_HANDLE(hDrive
);
2409 Log("DiskCheckWriteAccess failed");
2413 //step2 backup 4MB data
2414 backup
= malloc(SIZE_1MB
* 4);
2420 hDrive
= GetPhysicalHandle(PhyDrive
, FALSE
, FALSE
, FALSE
);
2421 if (hDrive
== INVALID_HANDLE_VALUE
)
2427 dwStatus
= SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2434 ret
= ReadFile(hDrive
, backup
, SIZE_2MB
, &dwSize
, NULL
);
2435 if ((!ret
) || (dwSize
!= SIZE_2MB
))
2437 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2441 pGPT
= (VTOY_GPT_INFO
*)backup
;
2442 offset
= pGPT
->Head
.EfiBackupLBA
* 512;
2443 if (offset
>= (DiskSize
- SIZE_2MB
) && offset
< DiskSize
)
2445 Log("EFI partition table check success");
2449 Log("Backup EFI LBA not in last 2MB range: %llu", pGPT
->Head
.EfiBackupLBA
);
2454 liCurPosition
.QuadPart
= DiskSize
- SIZE_2MB
;
2455 liNewPosition
.QuadPart
= 0;
2456 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2457 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2463 ret
= ReadFile(hDrive
, backup
+ SIZE_2MB
, SIZE_2MB
, &dwSize
, NULL
);
2464 if ((!ret
) || (dwSize
!= SIZE_2MB
))
2466 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2471 backup
= NULL
; //For don't free later
2475 CHECK_CLOSE_HANDLE(hDrive
);
2483 static BOOL
WriteBackupDataToDisk(HANDLE hDrive
, UINT64 Offset
, BYTE
*Data
, DWORD Length
)
2487 LARGE_INTEGER liCurPosition
;
2488 LARGE_INTEGER liNewPosition
;
2490 Log("WriteBackupDataToDisk %llu %p %u", Offset
, Data
, Length
);
2492 liCurPosition
.QuadPart
= Offset
;
2493 liNewPosition
.QuadPart
= 0;
2494 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2495 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2500 ret
= WriteFile(hDrive
, Data
, Length
, &dwSize
, NULL
);
2501 if ((!ret
) || dwSize
!= Length
)
2503 Log("Failed to write %d %u %u", ret
, dwSize
, LASTERR
);
2507 Log("WriteBackupDataToDisk %llu %p %u success", Offset
, Data
, Length
);
2512 int UpdateVentoy2PhyDrive(PHY_DRIVE_INFO
*pPhyDrive
, int TryId
)
2517 BOOL ForceMBR
= FALSE
;
2518 BOOL Esp2Basic
= FALSE
;
2519 BOOL ChangeAttr
= FALSE
;
2520 BOOL CleanDisk
= FALSE
;
2521 BOOL DelEFI
= FALSE
;
2522 BOOL bWriteBack
= TRUE
;
2528 CHAR DriveName
[] = "?:\\";
2529 CHAR DriveLetters
[MAX_PATH
] = { 0 };
2530 CHAR BackBinFile
[MAX_PATH
];
2532 UINT64 ReservedMB
= 0;
2535 BYTE
*pBackup
= NULL
;
2536 VTOY_GPT_INFO
*pGptInfo
= NULL
;
2537 VTOY_GPT_INFO
*pGptBkup
= NULL
;
2538 UINT8 ReservedData
[4096];
2540 Log("#####################################################");
2541 Log("UpdateVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId
,
2542 pPhyDrive
->PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
2543 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
2544 Log("#####################################################");
2546 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2548 Log("Lock disk for umount ............................ ");
2550 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
2551 if (hDrive
== INVALID_HANDLE_VALUE
)
2553 Log("Failed to open physical disk");
2557 if (pPhyDrive
->PartStyle
)
2559 pGptInfo
= malloc(2 * sizeof(VTOY_GPT_INFO
));
2565 memset(pGptInfo
, 0, 2 * sizeof(VTOY_GPT_INFO
));
2566 pGptBkup
= pGptInfo
+ 1;
2569 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2570 ReadFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
);
2571 memcpy(pGptBkup
, pGptInfo
, sizeof(VTOY_GPT_INFO
));
2573 //MBR will be used to compare with local boot image
2574 memcpy(&MBR
, &pGptInfo
->MBR
, sizeof(MBR_HEAD
));
2576 StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
2577 Log("GPT StartSector in PartTbl:%llu", (ULONGLONG
)StartSector
);
2579 ReservedMB
= (pPhyDrive
->SizeInBytes
/ 512 - (StartSector
+ VENTOY_EFI_PART_SIZE
/ 512) - 33) / 2048;
2580 Log("GPT Reserved Disk Space:%llu MB", (ULONGLONG
)ReservedMB
);
2585 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2586 ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
2588 StartSector
= MBR
.PartTbl
[1].StartSectorId
;
2589 Log("MBR StartSector in PartTbl:%llu", (ULONGLONG
)StartSector
);
2591 ReservedMB
= (pPhyDrive
->SizeInBytes
/ 512 - (StartSector
+ VENTOY_EFI_PART_SIZE
/ 512)) / 2048;
2592 Log("MBR Reserved Disk Space:%llu MB", (ULONGLONG
)ReservedMB
);
2595 //Read Reserved Data
2596 SetFilePointer(hDrive
, 512 * 2040, NULL
, FILE_BEGIN
);
2597 ReadFile(hDrive
, ReservedData
, sizeof(ReservedData
), &dwSize
, NULL
);
2599 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
2601 if (DriveLetters
[0] == 0)
2603 Log("No drive letter was assigned...");
2607 // Unmount all mounted volumes that belong to this drive
2608 // Do it in reverse so that we always end on the first volume letter
2609 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
2611 DriveName
[0] = DriveLetters
[i
- 1];
2612 if (IsVentoyLogicalDrive(DriveName
[0]))
2614 Log("%s is ventoy logical drive", DriveName
);
2615 bRet
= DeleteVolumeMountPointA(DriveName
);
2616 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, LASTERR
);
2622 // It kind of blows, but we have to relinquish access to the physical drive
2623 // for VDS to be able to delete the partitions that reside on it...
2624 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2625 CHECK_CLOSE_HANDLE(hDrive
);
2627 if (pPhyDrive
->PartStyle
== 1)
2629 Log("TryId=%d EFI GPT partition type is 0x%llx", TryId
, pPhyDrive
->Part2GPTAttr
);
2630 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
2634 Log("Change GPT partition type to ESP");
2635 if (DISK_ChangeVtoyEFI2ESP(pPhyDrive
->PhyDrive
, StartSector
* 512ULL))
2641 else if (TryId
== 2)
2643 Log("Change GPT partition attribute");
2644 if (DISK_ChangeVtoyEFIAttr(pPhyDrive
->PhyDrive
, StartSector
* 512ULL, 0x8000000000000001))
2650 else if (TryId
== 3)
2652 DISK_DeleteVtoyEFIPartition(pPhyDrive
->PhyDrive
, StartSector
* 512ULL);
2655 else if (TryId
== 4)
2657 Log("Clean disk GPT partition table");
2658 if (BackupDataBeforeCleanDisk(pPhyDrive
->PhyDrive
, pPhyDrive
->SizeInBytes
, &pBackup
))
2660 sprintf_s(BackBinFile
, sizeof(BackBinFile
), ".\\ventoy\\phydrive%d_%u_%d.bin",
2661 pPhyDrive
->PhyDrive
, GetCurrentProcessId(), g_backup_bin_index
++);
2662 SaveBufToFile(BackBinFile
, pBackup
, 4 * SIZE_1MB
);
2663 Log("Save backup data to %s", BackBinFile
);
2665 Log("Success to backup data before clean");
2667 DISK_CleanDisk(pPhyDrive
->PhyDrive
);
2672 Log("Failed to backup data before clean");
2677 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
2679 Log("Lock disk for update ............................ ");
2680 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2681 if (hDrive
== INVALID_HANDLE_VALUE
)
2683 Log("Failed to GetPhysicalHandle for write.");
2688 PROGRESS_BAR_SET_POS(PT_LOCK_VOLUME
);
2690 Log("Lock volume for update .......................... ");
2691 hVolume
= INVALID_HANDLE_VALUE
;
2693 //If we change VTOYEFI to ESP, it can not have s volume name, so don't try to get it.
2696 //writeback the last 2MB
2697 if (!WriteBackupDataToDisk(hDrive
, pPhyDrive
->SizeInBytes
- SIZE_2MB
, pBackup
+ SIZE_2MB
, SIZE_2MB
))
2702 //write the first 2MB except parttable
2703 if (!WriteBackupDataToDisk(hDrive
, 34 * 512, pBackup
+ 34 * 512, SIZE_2MB
- 34 * 512))
2708 Status
= ERROR_NOT_FOUND
;
2712 Status
= ERROR_NOT_FOUND
;
2716 Status
= ERROR_NOT_FOUND
;
2720 for (i
= 0; i
< MaxRetry
; i
++)
2722 Status
= GetVentoyVolumeName(pPhyDrive
->PhyDrive
, StartSector
, DriveLetters
, sizeof(DriveLetters
), TRUE
);
2723 if (ERROR_SUCCESS
== Status
)
2729 Log("==== Volume not found, wait and retry %d... ====", i
);
2735 if (ERROR_SUCCESS
== Status
)
2737 Log("Now lock and dismount volume <%s>", DriveLetters
);
2739 for (i
= 0; i
< MaxRetry
; i
++)
2741 hVolume
= CreateFileA(DriveLetters
,
2742 GENERIC_READ
| GENERIC_WRITE
,
2746 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_NO_BUFFERING
| FILE_FLAG_WRITE_THROUGH
,
2749 if (hVolume
== INVALID_HANDLE_VALUE
)
2751 Log("Failed to create file volume, errcode:%u, wait and retry ...", LASTERR
);
2760 if (hVolume
== INVALID_HANDLE_VALUE
)
2762 Log("Failed to create file volume, errcode:%u", LASTERR
);
2766 bRet
= DeviceIoControl(hVolume
, FSCTL_LOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2767 Log("FSCTL_LOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2769 bRet
= DeviceIoControl(hVolume
, FSCTL_DISMOUNT_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2770 Log("FSCTL_DISMOUNT_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2773 else if (ERROR_NOT_FOUND
== Status
)
2775 Log("Volume not found, maybe not supported");
2783 bRet
= TryWritePart2(hDrive
, StartSector
);
2784 if (FALSE
== bRet
&& Esp2Basic
)
2786 Log("TryWritePart2 agagin ...");
2788 bRet
= TryWritePart2(hDrive
, StartSector
);
2793 if (pPhyDrive
->PartStyle
== 0)
2795 if (DiskCheckWriteAccess(hDrive
))
2797 Log("MBR DiskCheckWriteAccess success");
2801 Log("Try write failed, now delete partition 2 for MBR...");
2802 CHECK_CLOSE_HANDLE(hDrive
);
2804 Log("Now delete partition 2...");
2805 DISK_DeleteVtoyEFIPartition(pPhyDrive
->PhyDrive
, StartSector
* 512ULL);
2807 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2808 if (hDrive
== INVALID_HANDLE_VALUE
)
2810 Log("Failed to GetPhysicalHandle for write.");
2817 Log("MBR DiskCheckWriteAccess failed");
2822 Log("TryWritePart2 failed ....");
2828 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
2830 Log("Write Ventoy to disk ............................ ");
2831 if (0 != FormatPart2Fat(hDrive
, StartSector
))
2837 if (hVolume
!= INVALID_HANDLE_VALUE
)
2839 bRet
= DeviceIoControl(hVolume
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2840 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2841 CHECK_CLOSE_HANDLE(hVolume
);
2844 Log("Updating Boot Image ............................. ");
2845 if (WriteGrubStage1ToPhyDrive(hDrive
, pPhyDrive
->PartStyle
) != 0)
2851 //write reserved data
2852 SetFilePointer(hDrive
, 512 * 2040, NULL
, FILE_BEGIN
);
2853 bRet
= WriteFile(hDrive
, ReservedData
, sizeof(ReservedData
), &dwSize
, NULL
);
2854 Log("Write resv data ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2857 VentoyGetLocalBootImg(&BootImg
);
2860 memcpy(BootImg
.BootCode
+ 0x180, MBR
.BootCode
+ 0x180, 16);
2861 if (pPhyDrive
->PartStyle
)
2863 BootImg
.BootCode
[92] = 0x22;
2866 if (ForceMBR
== FALSE
&& memcmp(BootImg
.BootCode
, MBR
.BootCode
, 440) == 0)
2868 Log("Boot image has no difference, no need to write.");
2872 Log("Boot image need to write %u.", ForceMBR
);
2874 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2876 memcpy(MBR
.BootCode
, BootImg
.BootCode
, 440);
2877 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
2878 Log("Write Boot Image ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2881 if (pPhyDrive
->PartStyle
== 0)
2883 if (0x00 == MBR
.PartTbl
[0].Active
&& 0x80 == MBR
.PartTbl
[1].Active
)
2885 Log("Need to chage 1st partition active and 2nd partition inactive.");
2887 MBR
.PartTbl
[0].Active
= 0x80;
2888 MBR
.PartTbl
[1].Active
= 0x00;
2890 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2891 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
2892 Log("Write NEW MBR ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2898 if (!WriteBackupDataToDisk(hDrive
, 0, pBackup
, 34 * 512))
2907 Log("Write backup data success, now delete %s", BackBinFile
);
2908 DeleteFileA(BackBinFile
);
2912 Log("Write backup data failed");
2919 VTOY_GPT_HDR BackupHdr
;
2921 VentoyFillBackupGptHead(pGptBkup
, &BackupHdr
);
2922 if (!WriteBackupDataToDisk(hDrive
, 512 * pGptBkup
->Head
.EfiBackupLBA
, (BYTE
*)(&BackupHdr
), 512))
2927 if (!WriteBackupDataToDisk(hDrive
, 512 * (pGptBkup
->Head
.EfiBackupLBA
- 32), (BYTE
*)(pGptBkup
->PartTbl
), 32 * 512))
2932 if (!WriteBackupDataToDisk(hDrive
, 512, (BYTE
*)pGptBkup
+ 512, 33 * 512))
2939 Log("Write backup partition table success");
2943 Log("Write backup partition table failed");
2949 //Refresh Drive Layout
2950 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2954 if (hVolume
!= INVALID_HANDLE_VALUE
)
2956 bRet
= DeviceIoControl(hVolume
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2957 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2958 CHECK_CLOSE_HANDLE(hVolume
);
2967 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2968 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
2971 CHECK_CLOSE_HANDLE(hDrive
);
2975 Log("Recover GPT partition type to basic");
2976 DISK_ChangeVtoyEFI2Basic(pPhyDrive
->PhyDrive
, StartSector
* 512);
2979 if (pPhyDrive
->PartStyle
== 1)
2981 if (ChangeAttr
|| ((pPhyDrive
->Part2GPTAttr
>> 56) != 0xC0))
2983 Log("Change EFI partition attr %u <0x%llx> to <0x%llx>", ChangeAttr
, pPhyDrive
->Part2GPTAttr
, 0xC000000000000001ULL
);
2984 if (DISK_ChangeVtoyEFIAttr(pPhyDrive
->PhyDrive
, StartSector
* 512ULL, 0xC000000000000001ULL
))
2986 Log("Change EFI partition attr success");
2987 pPhyDrive
->Part2GPTAttr
= 0xC000000000000001ULL
;
2991 Log("Change EFI partition attr failed");