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");
735 file
= fl_fopen("/EFI/BOOT/BOOTX64.EFI", "wb");
736 Log("Open bootx64 efi file %p ", file
);
741 fl_fwrite(filebuf
, 1, size
, file
);
754 file
= fl_fopen("/EFI/BOOT/grubia32_real.efi", "rb");
755 Log("Open ventoy efi file %p ", file
);
758 fl_fseek(file
, 0, SEEK_END
);
759 size
= (int)fl_ftell(file
);
760 fl_fseek(file
, 0, SEEK_SET
);
762 Log("ventoy efi file size %d ...", size
);
764 filebuf
= (char *)malloc(size
);
767 fl_fread(filebuf
, 1, size
, file
);
772 Log("Now delete all efi files ...");
773 fl_remove("/EFI/BOOT/BOOTIA32.EFI");
774 fl_remove("/EFI/BOOT/grubia32.efi");
775 fl_remove("/EFI/BOOT/grubia32_real.efi");
776 fl_remove("/EFI/BOOT/mmia32.efi");
778 file
= fl_fopen("/EFI/BOOT/BOOTIA32.EFI", "wb");
779 Log("Open bootia32 efi file %p ", file
);
784 fl_fwrite(filebuf
, 1, size
, file
);
810 static int disk_xz_flush(void *src
, unsigned int size
)
813 BYTE
*buf
= (BYTE
*)src
;
815 for (i
= 0; i
< size
; i
++)
817 *g_part_img_pos
= *buf
++;
820 if ((g_disk_unxz_len
% SIZE_1MB
) == 0)
822 g_part_img_pos
= g_part_img_buf
[g_disk_unxz_len
/ SIZE_1MB
];
833 static void unxz_error(char *x
)
838 static BOOL
TryWritePart2(HANDLE hDrive
, UINT64 StartSectorId
)
841 DWORD TrySize
= 16 * 1024;
844 unsigned char *data
= NULL
;
845 LARGE_INTEGER liCurrentPosition
;
847 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
848 SetFilePointerEx(hDrive
, liCurrentPosition
, &liCurrentPosition
, FILE_BEGIN
);
850 Buffer
= malloc(TrySize
);
852 bRet
= WriteFile(hDrive
, Buffer
, TrySize
, &dwSize
, NULL
);
856 Log("Try write part2 bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
858 if (bRet
&& dwSize
== TrySize
)
866 static int FormatPart2Fat(HANDLE hDrive
, UINT64 StartSectorId
)
873 int Pos
= PT_WRITE_VENTOY_START
;
876 unsigned char *data
= NULL
;
877 LARGE_INTEGER liCurrentPosition
;
878 LARGE_INTEGER liNewPosition
;
879 BYTE
*CheckBuf
= NULL
;
881 Log("FormatPart2Fat %llu...", (ULONGLONG
)StartSectorId
);
883 CheckBuf
= malloc(SIZE_1MB
);
886 Log("Failed to malloc check buf");
890 rc
= ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG
, 0, (void **)&data
, &len
);
893 Log("Failed to read img file %p %u", data
, len
);
898 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
899 SetFilePointerEx(hDrive
, liCurrentPosition
, &liNewPosition
, FILE_BEGIN
);
901 memset(g_part_img_buf
, 0, sizeof(g_part_img_buf
));
903 g_part_img_buf
[0] = (BYTE
*)malloc(VENTOY_EFI_PART_SIZE
);
904 if (g_part_img_buf
[0])
906 Log("Malloc whole img buffer success, now decompress ...");
907 unxz(data
, len
, NULL
, NULL
, g_part_img_buf
[0], &writelen
, unxz_error
);
911 Log("decompress finished success");
913 VentoyProcSecureBoot(g_SecureBoot
);
915 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
918 bRet
= WriteFile(hDrive
, g_part_img_buf
[0] + i
* SIZE_1MB
, SIZE_1MB
, &dwSize
, NULL
);
919 Log("Write part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
927 PROGRESS_BAR_SET_POS(Pos
);
934 //Read and check the data
935 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
936 SetFilePointerEx(hDrive
, liCurrentPosition
, &liNewPosition
, FILE_BEGIN
);
938 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
940 bRet
= ReadFile(hDrive
, CheckBuf
, SIZE_1MB
, &dwSize
, NULL
);
941 Log("Read part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
943 if (!bRet
|| memcmp(CheckBuf
, g_part_img_buf
[0] + i
* SIZE_1MB
, SIZE_1MB
))
945 Log("### [Check Fail] The data write and read does not match");
950 PROGRESS_BAR_SET_POS(Pos
);
960 Log("decompress finished failed");
966 Log("Failed to malloc whole img size %u, now split it", VENTOY_EFI_PART_SIZE
);
969 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
971 g_part_img_buf
[i
] = (BYTE
*)malloc(SIZE_1MB
);
972 if (g_part_img_buf
[i
] == NULL
)
979 Log("Malloc part img buffer success, now decompress ...");
981 g_part_img_pos
= g_part_img_buf
[0];
983 unxz(data
, len
, NULL
, disk_xz_flush
, NULL
, NULL
, unxz_error
);
985 if (g_disk_unxz_len
== VENTOY_EFI_PART_SIZE
)
987 Log("decompress finished success");
989 VentoyProcSecureBoot(g_SecureBoot
);
991 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
994 bRet
= WriteFile(hDrive
, g_part_img_buf
[i
], SIZE_1MB
, &dwSize
, NULL
);
995 Log("Write part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
1003 PROGRESS_BAR_SET_POS(Pos
);
1010 //Read and check the data
1011 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
1012 SetFilePointerEx(hDrive
, liCurrentPosition
, &liNewPosition
, FILE_BEGIN
);
1014 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
1016 bRet
= ReadFile(hDrive
, CheckBuf
, SIZE_1MB
, &dwSize
, NULL
);
1017 Log("Read part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
1019 if (!bRet
|| memcmp(CheckBuf
, g_part_img_buf
[i
], SIZE_1MB
))
1021 Log("### [Check Fail] The data write and read does not match");
1026 PROGRESS_BAR_SET_POS(Pos
);
1036 Log("decompress finished failed");
1043 if (data
) free(data
);
1044 if (CheckBuf
)free(CheckBuf
);
1048 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
1050 if (g_part_img_buf
[i
]) free(g_part_img_buf
[i
]);
1055 if (g_part_img_buf
[0]) free(g_part_img_buf
[0]);
1061 static int WriteGrubStage1ToPhyDrive(HANDLE hDrive
, int PartStyle
)
1067 BYTE
*ImgBuf
= NULL
;
1068 BYTE
*RawBuf
= NULL
;
1070 Log("WriteGrubStage1ToPhyDrive ...");
1072 RawBuf
= (BYTE
*)malloc(SIZE_1MB
);
1078 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG
, 0, (void **)&ImgBuf
, &Len
))
1080 Log("Failed to read stage1 img");
1085 unxz(ImgBuf
, Len
, NULL
, NULL
, RawBuf
, &readLen
, unxz_error
);
1089 Log("Write GPT stage1 ...");
1090 RawBuf
[500] = 35;//update blocklist
1091 SetFilePointer(hDrive
, 512 * 34, NULL
, FILE_BEGIN
);
1092 bRet
= WriteFile(hDrive
, RawBuf
, SIZE_1MB
- 512 * 34, &dwSize
, NULL
);
1096 Log("Write MBR stage1 ...");
1097 SetFilePointer(hDrive
, 512, NULL
, FILE_BEGIN
);
1098 bRet
= WriteFile(hDrive
, RawBuf
, SIZE_1MB
- 512, &dwSize
, NULL
);
1101 Log("WriteFile Ret:%u dwSize:%u ErrCode:%u", bRet
, dwSize
, GetLastError());
1110 static int FormatPart1exFAT(UINT64 DiskSizeBytes
)
1115 Option
.fmt
= FM_EXFAT
;
1120 // < 32GB select 32KB as cluster size
1121 // > 32GB select 128KB as cluster size
1122 if (DiskSizeBytes
/ 1024 / 1024 / 1024 <= 32)
1124 Option
.au_size
= 32768;
1128 Option
.au_size
= 131072;
1131 Log("Formatting Part1 exFAT ...");
1133 disk_io_reset_write_error();
1135 Ret
= f_mkfs(TEXT("0:"), &Option
, 0, 8 * 1024 * 1024);
1138 if (disk_io_is_write_error())
1140 Log("Formatting Part1 exFAT failed, write error.");
1144 Log("Formatting Part1 exFAT success");
1149 Log("Formatting Part1 exFAT failed");
1156 int ClearVentoyFromPhyDrive(HWND hWnd
, PHY_DRIVE_INFO
*pPhyDrive
, char *pDrvLetter
)
1165 CHAR DriveName
[] = "?:\\";
1166 CHAR DriveLetters
[MAX_PATH
] = { 0 };
1167 LARGE_INTEGER liCurrentPosition
;
1168 char *pTmpBuf
= NULL
;
1173 Log("ClearVentoyFromPhyDrive PhyDrive%d <<%s %s %dGB>>",
1174 pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1175 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1177 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1179 Log("Lock disk for clean ............................. ");
1181 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
1182 if (hDrive
== INVALID_HANDLE_VALUE
)
1184 Log("Failed to open physical disk");
1188 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1190 if (DriveLetters
[0] == 0)
1192 Log("No drive letter was assigned...");
1193 DriveName
[0] = GetFirstUnusedDriveLetter();
1194 Log("GetFirstUnusedDriveLetter %C: ...", DriveName
[0]);
1198 // Unmount all mounted volumes that belong to this drive
1199 // Do it in reverse so that we always end on the first volume letter
1200 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
1202 DriveName
[0] = DriveLetters
[i
- 1];
1203 bRet
= DeleteVolumeMountPointA(DriveName
);
1204 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, GetLastError());
1208 MountDrive
= DriveName
[0];
1209 Log("Will use '%C:' as volume mountpoint", DriveName
[0]);
1211 // It kind of blows, but we have to relinquish access to the physical drive
1212 // for VDS to be able to delete the partitions that reside on it...
1213 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1214 CHECK_CLOSE_HANDLE(hDrive
);
1216 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
1218 if (!VDS_DeleteAllPartitions(pPhyDrive
->PhyDrive
))
1220 Log("Notice: Could not delete partitions: %u", GetLastError());
1223 Log("Deleting all partitions ......................... OK");
1225 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
1227 Log("Lock disk for write ............................. ");
1228 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1229 if (hDrive
== INVALID_HANDLE_VALUE
)
1231 Log("Failed to GetPhysicalHandle for write.");
1236 // clear first and last 2MB space
1237 pTmpBuf
= malloc(SIZE_2MB
);
1240 Log("Failed to alloc memory.");
1244 memset(pTmpBuf
, 0, SIZE_2MB
);
1247 bRet
= WriteFile(hDrive
, pTmpBuf
, SIZE_2MB
- 512, &dwSize
, NULL
);
1248 Log("Write fisrt 1MB ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1255 SET_FILE_POS(pPhyDrive
->SizeInBytes
- SIZE_2MB
);
1256 bRet
= WriteFile(hDrive
, pTmpBuf
, SIZE_2MB
, &dwSize
, NULL
);
1257 Log("Write 2nd 1MB ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1266 if (pPhyDrive
->SizeInBytes
> 2199023255552ULL)
1268 VTOY_GPT_INFO
*pGptInfo
;
1269 VTOY_GPT_HDR BackupHead
;
1270 LARGE_INTEGER liCurrentPosition
;
1272 pGptInfo
= (VTOY_GPT_INFO
*)pTmpBuf
;
1274 VentoyFillWholeGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1276 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512);
1277 VentoyFillBackupGptHead(pGptInfo
, &BackupHead
);
1278 if (!WriteFile(hDrive
, &BackupHead
, sizeof(VTOY_GPT_HDR
), &dwSize
, NULL
))
1281 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1285 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512 * 33);
1286 if (!WriteFile(hDrive
, pGptInfo
->PartTbl
, sizeof(pGptInfo
->PartTbl
), &dwSize
, NULL
))
1289 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1294 if (!WriteFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
))
1297 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1301 Log("Write GPT Info OK ...");
1305 bRet
= ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
1306 Log("Read MBR ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1313 //clear boot code and partition table (reserved disk signature)
1314 memset(MBR
.BootCode
, 0, 440);
1315 memset(MBR
.PartTbl
, 0, sizeof(MBR
.PartTbl
));
1317 VentoyFillMBRLocation(pPhyDrive
->SizeInBytes
, 2048, (UINT32
)(pPhyDrive
->SizeInBytes
/ 512 - 2048), MBR
.PartTbl
);
1319 MBR
.PartTbl
[0].Active
= 0x00; // bootable
1320 MBR
.PartTbl
[0].FsFlag
= 0x07; // exFAT/NTFS/HPFS
1323 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
1324 Log("Write MBR ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1332 Log("Clear Ventoy successfully finished");
1334 //Refresh Drive Layout
1335 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1339 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1348 Log("Mounting Ventoy Partition ....................... ");
1352 memset(DriveLetters
, 0, sizeof(DriveLetters
));
1353 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1354 Log("Logical drive letter after write ventoy: <%s>", DriveLetters
);
1356 for (i
= 0; i
< sizeof(DriveLetters
) && DriveLetters
[i
]; i
++)
1358 DriveName
[0] = DriveLetters
[i
];
1359 Log("%s is ventoy part1, already mounted", DriveName
);
1365 Log("need to mount ventoy part1...");
1366 if (0 == GetVentoyVolumeName(pPhyDrive
->PhyDrive
, 2048, DriveLetters
, sizeof(DriveLetters
), FALSE
))
1368 DriveName
[0] = MountDrive
;
1369 bRet
= SetVolumeMountPointA(DriveName
, DriveLetters
);
1370 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName
, DriveLetters
, bRet
, GetLastError());
1372 *pDrvLetter
= MountDrive
;
1376 Log("Failed to find ventoy volume");
1384 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
1387 CHECK_CLOSE_HANDLE(hDrive
);
1391 int InstallVentoy2FileImage(PHY_DRIVE_INFO
*pPhyDrive
, int PartStyle
)
1400 UINT64 data_offset
= 0;
1401 UINT64 Part2StartSector
= 0;
1402 UINT64 Part1StartSector
= 0;
1403 UINT64 Part1SectorCount
= 0;
1404 UINT8
*pData
= NULL
;
1405 UINT8
*pBkGptPartTbl
= NULL
;
1406 BYTE
*ImgBuf
= NULL
;
1407 MBR_HEAD
*pMBR
= NULL
;
1408 VTSI_FOOTER
*pImgFooter
= NULL
;
1409 VTSI_SEGMENT
*pSegment
= NULL
;
1410 VTOY_GPT_INFO
*pGptInfo
= NULL
;
1411 VTOY_GPT_HDR
*pBkGptHdr
= NULL
;
1414 Log("InstallVentoy2FileImage %s PhyDrive%d <<%s %s %dGB>>",
1415 PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1416 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1418 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1420 size
= SIZE_1MB
+ VENTOY_EFI_PART_SIZE
+ 33 * 512 + VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
) + sizeof(VTSI_FOOTER
);
1422 pData
= (UINT8
*)malloc(size
);
1425 Log("malloc image buffer failed %d.", size
);
1429 pImgFooter
= (VTSI_FOOTER
*)(pData
+ size
- sizeof(VTSI_FOOTER
));
1430 pSegment
= (VTSI_SEGMENT
*)((UINT8
*)pImgFooter
- VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
));
1431 memset(pImgFooter
, 0, sizeof(VTSI_FOOTER
));
1432 memset(pSegment
, 0, VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
));
1434 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START
);
1436 Log("Writing Boot Image ............................. ");
1437 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG
, 0, (void **)&ImgBuf
, &Len
))
1439 Log("Failed to read stage1 img");
1443 unxz(ImgBuf
, Len
, NULL
, NULL
, pData
, &dataLen
, unxz_error
);
1446 Log("decompress %s len:%d", VENTOY_FILE_STG1_IMG
, dataLen
);
1450 pData
[500] = 35;//update blocklist
1451 memmove(pData
+ 34 * 512, pData
, SIZE_1MB
- 512 * 34);
1452 memset(pData
, 0, 34 * 512);
1454 pGptInfo
= (VTOY_GPT_INFO
*)pData
;
1455 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
1456 VentoyFillGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1458 pBkGptPartTbl
= pData
+ SIZE_1MB
+ VENTOY_EFI_PART_SIZE
;
1459 memset(pBkGptPartTbl
, 0, 33 * 512);
1461 memcpy(pBkGptPartTbl
, pGptInfo
->PartTbl
, 32 * 512);
1462 pBkGptHdr
= (VTOY_GPT_HDR
*)(pBkGptPartTbl
+ 32 * 512);
1463 VentoyFillBackupGptHead(pGptInfo
, pBkGptHdr
);
1465 Part1StartSector
= pGptInfo
->PartTbl
[0].StartLBA
;
1466 Part1SectorCount
= pGptInfo
->PartTbl
[0].LastLBA
- Part1StartSector
+ 1;
1467 Part2StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
1469 Log("Write GPT Info OK ...");
1473 memmove(pData
+ 512, pData
, SIZE_1MB
- 512);
1474 memset(pData
, 0, 512);
1476 pMBR
= (MBR_HEAD
*)pData
;
1477 VentoyFillMBR(pPhyDrive
->SizeInBytes
, pMBR
, PartStyle
);
1478 Part1StartSector
= pMBR
->PartTbl
[0].StartSectorId
;
1479 Part1SectorCount
= pMBR
->PartTbl
[0].SectorCount
;
1480 Part2StartSector
= pMBR
->PartTbl
[1].StartSectorId
;
1482 Log("Write MBR OK ...");
1485 Log("Writing EFI part Image ............................. ");
1486 rc
= ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG
, 0, (void **)&ImgBuf
, &Len
);
1489 Log("Failed to read img file %p %u", ImgBuf
, Len
);
1493 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START
+ 28);
1494 memset(g_part_img_buf
, 0, sizeof(g_part_img_buf
));
1495 unxz(ImgBuf
, Len
, NULL
, NULL
, pData
+ SIZE_1MB
, &dataLen
, unxz_error
);
1498 Log("decompress finished success");
1499 g_part_img_buf
[0] = pData
+ SIZE_1MB
;
1501 VentoyProcSecureBoot(g_SecureBoot
);
1505 Log("decompress finished failed");
1509 fopen_s(&fp
, "VentoySparseImg.vtsi", "wb+");
1512 Log("Failed to create Ventoy img file");
1516 Log("Writing stage1 data ............................. ");
1518 fwrite(pData
, 1, SIZE_1MB
, fp
);
1520 pSegment
[0].disk_start_sector
= 0;
1521 pSegment
[0].sector_num
= SIZE_1MB
/ 512;
1522 pSegment
[0].data_offset
= data_offset
;
1523 data_offset
+= pSegment
[0].sector_num
* 512;
1525 disk_io_set_param(INVALID_HANDLE_VALUE
, Part1StartSector
+ Part1SectorCount
);// include the 2048 sector gap
1526 disk_io_set_imghook(fp
, pSegment
+ 1, VTSI_IMG_MAX_SEG
- 1, data_offset
);
1528 Log("Formatting part1 exFAT ...");
1529 if (0 != FormatPart1exFAT(pPhyDrive
->SizeInBytes
))
1531 Log("FormatPart1exFAT failed.");
1532 disk_io_reset_imghook(&segnum
, &data_offset
);
1536 disk_io_reset_imghook(&segnum
, &data_offset
);
1539 Log("current segment number:%d dataoff:%ld", segnum
, (long)data_offset
);
1542 Log("Writing part2 data ............................. ");
1543 fwrite(pData
+ SIZE_1MB
, 1, VENTOY_EFI_PART_SIZE
, fp
);
1544 pSegment
[segnum
].disk_start_sector
= Part2StartSector
;
1545 pSegment
[segnum
].sector_num
= VENTOY_EFI_PART_SIZE
/ 512;
1546 pSegment
[segnum
].data_offset
= data_offset
;
1547 data_offset
+= pSegment
[segnum
].sector_num
* 512;
1552 Log("Writing backup gpt table ............................. ");
1553 fwrite(pBkGptPartTbl
, 1, 33 * 512, fp
);
1554 pSegment
[segnum
].disk_start_sector
= pPhyDrive
->SizeInBytes
/ 512 - 33;
1555 pSegment
[segnum
].sector_num
= 33;
1556 pSegment
[segnum
].data_offset
= data_offset
;
1557 data_offset
+= pSegment
[segnum
].sector_num
* 512;
1561 Log("Writing segment metadata ............................. ");
1563 for (i
= 0; i
< (int)segnum
; i
++)
1565 Log("SEG[%d]: PhySector:%llu SectorNum:%llu DataOffset:%llu(sector:%llu)", i
, pSegment
[i
].disk_start_sector
, pSegment
[i
].sector_num
,
1566 pSegment
[i
].data_offset
, pSegment
[i
].data_offset
/ 512);
1569 dataLen
= segnum
* sizeof(VTSI_SEGMENT
);
1570 fwrite(pSegment
, 1, dataLen
, fp
);
1574 //pData + SIZE_1MB - 8192 is a temp data buffer with zero
1575 fwrite(pData
+ SIZE_1MB
- 8192, 1, 512 - (dataLen
% 512), fp
);
1579 pImgFooter
->magic
= VTSI_IMG_MAGIC
;
1580 pImgFooter
->version
= 1;
1581 pImgFooter
->disk_size
= pPhyDrive
->SizeInBytes
;
1582 memcpy(&pImgFooter
->disk_signature
, pPhyDrive
->MBR
.BootCode
+ 0x1b8, 4);
1583 pImgFooter
->segment_num
= segnum
;
1584 pImgFooter
->segment_offset
= data_offset
;
1586 for (i
= 0, chksum
= 0; i
< (int)(segnum
* sizeof(VTSI_SEGMENT
)); i
++)
1588 chksum
+= *((UINT8
*)pSegment
+ i
);
1590 pImgFooter
->segment_chksum
= ~chksum
;
1592 for (i
= 0, chksum
= 0; i
< sizeof(VTSI_FOOTER
); i
++)
1594 chksum
+= *((UINT8
*)pImgFooter
+ i
);
1596 pImgFooter
->foot_chksum
= ~chksum
;
1598 Log("Writing footer segnum(%u) segoffset(%llu) ......................", segnum
, data_offset
);
1599 Log("disk_size=%llu disk_signature=%lx segment_offset=%llu", pImgFooter
->disk_size
, pImgFooter
->disk_signature
, pImgFooter
->segment_offset
);
1601 fwrite(pImgFooter
, 1, sizeof(VTSI_FOOTER
), fp
);
1604 Log("Writing Ventoy image file finished, the file size should be %llu .", data_offset
+ 512 + ((dataLen
+ 511) / 512 * 512));
1610 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1612 Log("retcode:%d\n", rc
);
1621 int InstallVentoy2PhyDrive(PHY_DRIVE_INFO
*pPhyDrive
, int PartStyle
, int TryId
)
1630 CHAR DriveName
[] = "?:\\";
1631 CHAR DriveLetters
[MAX_PATH
] = { 0 };
1633 VTOY_GPT_INFO
*pGptInfo
= NULL
;
1634 UINT64 Part1StartSector
= 0;
1635 UINT64 Part1SectorCount
= 0;
1636 UINT64 Part2StartSector
= 0;
1638 Log("#####################################################");
1639 Log("InstallVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId
,
1640 PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1641 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1642 Log("#####################################################");
1646 pGptInfo
= malloc(sizeof(VTOY_GPT_INFO
));
1647 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
1650 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1654 VentoyFillGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1655 Part1StartSector
= pGptInfo
->PartTbl
[0].StartLBA
;
1656 Part1SectorCount
= pGptInfo
->PartTbl
[0].LastLBA
- Part1StartSector
+ 1;
1657 Part2StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
1661 VentoyFillMBR(pPhyDrive
->SizeInBytes
, &MBR
, PartStyle
);
1662 Part1StartSector
= MBR
.PartTbl
[0].StartSectorId
;
1663 Part1SectorCount
= MBR
.PartTbl
[0].SectorCount
;
1664 Part2StartSector
= MBR
.PartTbl
[1].StartSectorId
;
1667 Log("Lock disk for clean ............................. ");
1669 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
1670 if (hDrive
== INVALID_HANDLE_VALUE
)
1672 Log("Failed to open physical disk");
1677 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1679 if (DriveLetters
[0] == 0)
1681 Log("No drive letter was assigned...");
1682 DriveName
[0] = GetFirstUnusedDriveLetter();
1683 Log("GetFirstUnusedDriveLetter %C: ...", DriveName
[0]);
1687 // Unmount all mounted volumes that belong to this drive
1688 // Do it in reverse so that we always end on the first volume letter
1689 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
1691 DriveName
[0] = DriveLetters
[i
- 1];
1692 bRet
= DeleteVolumeMountPointA(DriveName
);
1693 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, GetLastError());
1697 MountDrive
= DriveName
[0];
1698 Log("Will use '%C:' as volume mountpoint", DriveName
[0]);
1700 // It kind of blows, but we have to relinquish access to the physical drive
1701 // for VDS to be able to delete the partitions that reside on it...
1702 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1703 CHECK_CLOSE_HANDLE(hDrive
);
1705 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
1707 if (!VDS_DeleteAllPartitions(pPhyDrive
->PhyDrive
))
1709 Log("Notice: Could not delete partitions: 0x%x, but we continue.", GetLastError());
1712 Log("Deleting all partitions ......................... OK");
1714 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
1716 Log("Lock disk for write ............................. ");
1717 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1718 if (hDrive
== INVALID_HANDLE_VALUE
)
1720 Log("Failed to GetPhysicalHandle for write.");
1725 //Refresh Drive Layout
1726 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1728 disk_io_set_param(hDrive
, Part1StartSector
+ Part1SectorCount
);// include the 2048 sector gap
1730 PROGRESS_BAR_SET_POS(PT_FORMAT_PART1
);
1732 if (PartStyle
== 1 && pPhyDrive
->PartStyle
== 0)
1734 Log("Wait for format part1 ...");
1738 Log("Formatting part1 exFAT ...");
1739 if (0 != FormatPart1exFAT(pPhyDrive
->SizeInBytes
))
1741 Log("FormatPart1exFAT failed.");
1746 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
1747 Log("Writing part2 FAT img ...");
1749 if (0 != FormatPart2Fat(hDrive
, Part2StartSector
))
1751 Log("FormatPart2Fat failed.");
1756 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG
);
1757 Log("Writing Boot Image ............................. ");
1758 if (WriteGrubStage1ToPhyDrive(hDrive
, PartStyle
) != 0)
1760 Log("WriteGrubStage1ToPhyDrive failed.");
1765 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE
);
1766 Log("Writing Partition Table ........................ ");
1767 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
1771 VTOY_GPT_HDR BackupHead
;
1772 LARGE_INTEGER liCurrentPosition
;
1774 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512);
1775 VentoyFillBackupGptHead(pGptInfo
, &BackupHead
);
1776 if (!WriteFile(hDrive
, &BackupHead
, sizeof(VTOY_GPT_HDR
), &dwSize
, NULL
))
1779 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1783 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512 * 33);
1784 if (!WriteFile(hDrive
, pGptInfo
->PartTbl
, sizeof(pGptInfo
->PartTbl
), &dwSize
, NULL
))
1787 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1792 if (!WriteFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
))
1795 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1799 Log("Write GPT Info OK ...");
1800 memcpy(&(pPhyDrive
->MBR
), &(pGptInfo
->MBR
), 512);
1804 if (!WriteFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
))
1807 Log("Write MBR Failed, dwSize:%u ErrCode:%u", dwSize
, GetLastError());
1810 Log("Write MBR OK ...");
1811 memcpy(&(pPhyDrive
->MBR
), &MBR
, 512);
1814 //Refresh Drive Layout
1815 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1819 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1823 Log("Mounting Ventoy Partition ....................... ");
1827 memset(DriveLetters
, 0, sizeof(DriveLetters
));
1828 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1829 Log("Logical drive letter after write ventoy: <%s>", DriveLetters
);
1831 for (i
= 0; i
< sizeof(DriveLetters
) && DriveLetters
[i
]; i
++)
1833 DriveName
[0] = DriveLetters
[i
];
1834 if (IsVentoyLogicalDrive(DriveName
[0]))
1836 Log("%s is ventoy part2, delete mountpoint", DriveName
);
1837 DeleteVolumeMountPointA(DriveName
);
1841 Log("%s is ventoy part1, already mounted", DriveName
);
1848 Log("need to mount ventoy part1...");
1850 if (0 == GetVentoyVolumeName(pPhyDrive
->PhyDrive
, Part1StartSector
, DriveLetters
, sizeof(DriveLetters
), FALSE
))
1852 DriveName
[0] = MountDrive
;
1853 bRet
= SetVolumeMountPointA(DriveName
, DriveLetters
);
1854 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName
, DriveLetters
, bRet
, GetLastError());
1858 Log("Failed to find ventoy volume");
1865 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1867 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
1869 if (!VDS_IsLastAvaliable())
1871 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
1872 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
1873 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
1874 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
1875 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
1884 CHECK_CLOSE_HANDLE(hDrive
);
1889 int PartitionResizeForVentoy(PHY_DRIVE_INFO
*pPhyDrive
)
1895 INT64 ReservedValue
;
1899 VTOY_GPT_INFO
*pGPT
;
1902 VTOY_GPT_HDR BackupHead
;
1903 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
1904 GUID ZeroGuid
= { 0 };
1905 static GUID WindowsDataPartType
= { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
1906 static GUID EspPartType
= { 0xc12a7328, 0xf81f, 0x11d2, { 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b } };
1907 static GUID BiosGrubPartType
= { 0x21686148, 0x6449, 0x6e6f, { 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46, 0x49 } };
1909 Log("#####################################################");
1910 Log("PartitionResizeForVentoy PhyDrive%d <<%s %s %dGB>>",
1911 pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1912 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1913 Log("#####################################################");
1915 pGPT
= &(pPhyDrive
->Gpt
);
1916 pMBR
= &(pPhyDrive
->Gpt
.MBR
);
1917 Log("Disksize:%llu Part2Start:%llu", pPhyDrive
->SizeInBytes
, pPhyDrive
->ResizePart2StartSector
* 512);
1919 if (pMBR
->PartTbl
[0].FsFlag
== 0xEE && memcmp(pGPT
->Head
.Signature
, "EFI PART", 8) == 0)
1928 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1930 RecudeBytes
= VENTOY_EFI_PART_SIZE
;
1931 ReservedValue
= GetReservedSpaceInMB();
1932 if (ReservedValue
> 0)
1934 Log("Reduce add reserved space %lldMB", (LONGLONG
)ReservedValue
);
1935 RecudeBytes
+= (UINT64
)(ReservedValue
* SIZE_1MB
);
1939 if (pPhyDrive
->ResizeNoShrink
== FALSE
)
1941 Log("Need to shrink the volume");
1942 if (DISK_ShrinkVolume(pPhyDrive
->PhyDrive
, pPhyDrive
->ResizeVolumeGuid
, pPhyDrive
->Part1DriveLetter
, pPhyDrive
->ResizeOldPart1Size
, RecudeBytes
))
1944 Log("Shrink volume success, now check again");
1946 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1947 if (hDrive
== INVALID_HANDLE_VALUE
)
1949 Log("Failed to GetPhysicalHandle for update.");
1953 //Refresh Drive Layout
1954 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1956 CHECK_CLOSE_HANDLE(hDrive
);
1959 if (PartResizePreCheck(NULL
) && pPhyDrive
->ResizeNoShrink
)
1961 Log("Recheck after Shrink volume success");
1962 Log("After shrink Disksize:%llu Part2Start:%llu", pPhyDrive
->SizeInBytes
, pPhyDrive
->ResizePart2StartSector
* 512);
1966 Log("Recheck after Shrink volume failed %u", pPhyDrive
->ResizeNoShrink
);
1972 Log("Shrink volume failed");
1978 //Now try write data
1979 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1980 if (hDrive
== INVALID_HANDLE_VALUE
)
1982 Log("Failed to GetPhysicalHandle for update.");
1987 //Write partition 2 data
1988 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
1989 if (0 != FormatPart2Fat(hDrive
, pPhyDrive
->ResizePart2StartSector
))
1991 Log("FormatPart2Fat failed.");
1995 //Write grub stage2 gap
1996 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG
);
1997 Log("Writing Boot Image ............................. ");
1998 if (WriteGrubStage1ToPhyDrive(hDrive
, PartStyle
) != 0)
2000 Log("WriteGrubStage1ToPhyDrive failed.");
2005 //Write partition table
2006 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE
);
2007 Log("Writing partition table ............................. ");
2009 VentoyGetLocalBootImg(&MBR
);
2010 CoCreateGuid(&Guid
);
2011 memcpy(MBR
.BootCode
+ 0x180, &Guid
, 16);
2012 memcpy(pMBR
->BootCode
, MBR
.BootCode
, 440);
2016 for (i
= 1; i
< 4; i
++)
2018 if (pMBR
->PartTbl
[i
].SectorCount
== 0)
2026 Log("Can not find MBR free partition table");
2030 for (j
= i
- 1; j
> 0; j
--)
2032 Log("Move MBR partition table %d --> %d", j
+ 1, j
+ 2);
2033 memcpy(pMBR
->PartTbl
+ (j
+ 1), pMBR
->PartTbl
+ j
, sizeof(PART_TABLE
));
2036 memset(pMBR
->PartTbl
+ 1, 0, sizeof(PART_TABLE
));
2037 VentoyFillMBRLocation(pPhyDrive
->SizeInBytes
, (UINT32
)pPhyDrive
->ResizePart2StartSector
, VENTOY_EFI_PART_SIZE
/ 512, pMBR
->PartTbl
+ 1);
2038 pMBR
->PartTbl
[0].Active
= 0x80; // bootable
2039 pMBR
->PartTbl
[1].Active
= 0x00;
2040 pMBR
->PartTbl
[1].FsFlag
= 0xEF; // EFI System Partition
2042 if (!WriteDataToPhyDisk(hDrive
, 0, pMBR
, 512))
2044 Log("Legacy BIOS write MBR failed");
2050 for (i
= 1; i
< 128; i
++)
2052 if (memcmp(&(pGPT
->PartTbl
[i
].PartGuid
), &ZeroGuid
, sizeof(GUID
)) == 0)
2060 Log("Can not find GPT free partition table");
2064 for (j
= i
- 1; j
> 0; j
--)
2066 Log("Move GPT partition table %d --> %d", j
+ 1, j
+ 2);
2067 memcpy(pGPT
->PartTbl
+ (j
+ 1), pGPT
->PartTbl
+ j
, sizeof(VTOY_GPT_PART_TBL
));
2071 pMBR
->BootCode
[92] = 0x22;
2073 // to fix windows issue
2074 memset(pGPT
->PartTbl
+ 1, 0, sizeof(VTOY_GPT_PART_TBL
));
2075 memcpy(&(pGPT
->PartTbl
[1].PartType
), &WindowsDataPartType
, sizeof(GUID
));
2076 CoCreateGuid(&(pGPT
->PartTbl
[1].PartGuid
));
2078 pGPT
->PartTbl
[1].StartLBA
= pGPT
->PartTbl
[0].LastLBA
+ 1;
2079 pGPT
->PartTbl
[1].LastLBA
= pGPT
->PartTbl
[1].StartLBA
+ VENTOY_EFI_PART_SIZE
/ 512 - 1;
2080 pGPT
->PartTbl
[1].Attr
= 0xC000000000000001ULL
;
2081 memcpy(pGPT
->PartTbl
[1].Name
, L
"VTOYEFI", 7 * 2);
2084 pGPT
->Head
.PartTblCrc
= VentoyCrc32(pGPT
->PartTbl
, sizeof(pGPT
->PartTbl
));
2086 pGPT
->Head
.Crc
= VentoyCrc32(&(pGPT
->Head
), pGPT
->Head
.Length
);
2088 Log("pGPT->Head.EfiStartLBA=%llu", (ULONGLONG
)pGPT
->Head
.EfiStartLBA
);
2089 Log("pGPT->Head.EfiBackupLBA=%llu", (ULONGLONG
)pGPT
->Head
.EfiBackupLBA
);
2091 VentoyFillBackupGptHead(pGPT
, &BackupHead
);
2092 if (!WriteDataToPhyDisk(hDrive
, pGPT
->Head
.EfiBackupLBA
* 512, &BackupHead
, 512))
2094 Log("UEFI write backup head failed");
2098 if (!WriteDataToPhyDisk(hDrive
, (pGPT
->Head
.EfiBackupLBA
- 32) * 512, pGPT
->PartTbl
, 512 * 32))
2100 Log("UEFI write backup partition table failed");
2104 if (!WriteDataToPhyDisk(hDrive
, 0, pGPT
, 512 * 34))
2106 Log("UEFI write MBR & Main partition table failed");
2113 //Refresh Drive Layout
2114 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2116 //We must close handle here, because it will block the refresh bellow
2117 CHECK_CLOSE_HANDLE(hDrive
);
2122 PhyDrive
= pPhyDrive
->PhyDrive
;
2124 Log("#### Now Refresh PhyDrive ####");
2125 Ventoy2DiskDestroy();
2128 pPhyDrive
= GetPhyDriveInfoByPhyDrive(PhyDrive
);
2131 if (pPhyDrive
->VentoyVersion
[0] == 0)
2133 Log("After process the Ventoy version is still invalid");
2137 Log("### Ventoy non-destructive installation successfully finished <%s>", pPhyDrive
->VentoyVersion
);
2141 Log("### Ventoy non-destructive installation successfully finished <not found>");
2144 InitComboxCtrl(g_DialogHwnd
, PhyDrive
);
2149 CHECK_CLOSE_HANDLE(hDrive
);
2154 static BOOL
DiskCheckWriteAccess(HANDLE hDrive
)
2160 LARGE_INTEGER liCurPosition
;
2161 LARGE_INTEGER liNewPosition
;
2163 liCurPosition
.QuadPart
= 2039 * 512;
2164 liNewPosition
.QuadPart
= 0;
2165 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2166 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2168 Log("SetFilePointer1 Failed %u", LASTERR
);
2174 ret
= ReadFile(hDrive
, Buffer
, 512, &dwSize
, NULL
);
2175 if ((!ret
) || (dwSize
!= 512))
2177 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2182 liCurPosition
.QuadPart
= 2039 * 512;
2183 liNewPosition
.QuadPart
= 0;
2184 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2185 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2187 Log("SetFilePointer2 Failed %u", LASTERR
);
2192 ret
= WriteFile(hDrive
, Buffer
, 512, &dwSize
, NULL
);
2193 if ((!ret
) || dwSize
!= 512)
2195 Log("Failed to write %d %u %u", ret
, dwSize
, LASTERR
);
2206 static BOOL
BackupDataBeforeCleanDisk(int PhyDrive
, UINT64 DiskSize
, BYTE
**pBackup
)
2210 BOOL Return
= FALSE
;
2212 BYTE
*backup
= NULL
;
2214 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
2215 LARGE_INTEGER liCurPosition
;
2216 LARGE_INTEGER liNewPosition
;
2217 VTOY_GPT_INFO
*pGPT
= NULL
;
2219 Log("BackupDataBeforeCleanDisk %d", PhyDrive
);
2221 // step1: check write access
2222 hDrive
= GetPhysicalHandle(PhyDrive
, TRUE
, TRUE
, FALSE
);
2223 if (hDrive
== INVALID_HANDLE_VALUE
)
2225 Log("Failed to GetPhysicalHandle for write.");
2229 if (DiskCheckWriteAccess(hDrive
))
2231 Log("DiskCheckWriteAccess success");
2232 CHECK_CLOSE_HANDLE(hDrive
);
2236 Log("DiskCheckWriteAccess failed");
2240 //step2 backup 4MB data
2241 backup
= malloc(SIZE_1MB
* 4);
2247 hDrive
= GetPhysicalHandle(PhyDrive
, FALSE
, FALSE
, FALSE
);
2248 if (hDrive
== INVALID_HANDLE_VALUE
)
2254 dwStatus
= SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2261 ret
= ReadFile(hDrive
, backup
, SIZE_2MB
, &dwSize
, NULL
);
2262 if ((!ret
) || (dwSize
!= SIZE_2MB
))
2264 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2268 pGPT
= (VTOY_GPT_INFO
*)backup
;
2269 offset
= pGPT
->Head
.EfiBackupLBA
* 512;
2270 if (offset
>= (DiskSize
- SIZE_2MB
) && offset
< DiskSize
)
2272 Log("EFI partition table check success");
2276 Log("Backup EFI LBA not in last 2MB range: %llu", pGPT
->Head
.EfiBackupLBA
);
2281 liCurPosition
.QuadPart
= DiskSize
- SIZE_2MB
;
2282 liNewPosition
.QuadPart
= 0;
2283 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2284 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2290 ret
= ReadFile(hDrive
, backup
+ SIZE_2MB
, SIZE_2MB
, &dwSize
, NULL
);
2291 if ((!ret
) || (dwSize
!= SIZE_2MB
))
2293 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2298 backup
= NULL
; //For don't free later
2302 CHECK_CLOSE_HANDLE(hDrive
);
2310 static BOOL
WriteBackupDataToDisk(HANDLE hDrive
, UINT64 Offset
, BYTE
*Data
, DWORD Length
)
2314 LARGE_INTEGER liCurPosition
;
2315 LARGE_INTEGER liNewPosition
;
2317 Log("WriteBackupDataToDisk %llu %p %u", Offset
, Data
, Length
);
2319 liCurPosition
.QuadPart
= Offset
;
2320 liNewPosition
.QuadPart
= 0;
2321 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2322 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2327 ret
= WriteFile(hDrive
, Data
, Length
, &dwSize
, NULL
);
2328 if ((!ret
) || dwSize
!= Length
)
2330 Log("Failed to write %d %u %u", ret
, dwSize
, LASTERR
);
2334 Log("WriteBackupDataToDisk %llu %p %u success", Offset
, Data
, Length
);
2339 int UpdateVentoy2PhyDrive(PHY_DRIVE_INFO
*pPhyDrive
, int TryId
)
2344 BOOL ForceMBR
= FALSE
;
2345 BOOL Esp2Basic
= FALSE
;
2346 BOOL ChangeAttr
= FALSE
;
2347 BOOL CleanDisk
= FALSE
;
2348 BOOL DelEFI
= FALSE
;
2349 BOOL bWriteBack
= TRUE
;
2355 CHAR DriveName
[] = "?:\\";
2356 CHAR DriveLetters
[MAX_PATH
] = { 0 };
2357 CHAR BackBinFile
[MAX_PATH
];
2359 UINT64 ReservedMB
= 0;
2362 BYTE
*pBackup
= NULL
;
2363 VTOY_GPT_INFO
*pGptInfo
= NULL
;
2364 VTOY_GPT_INFO
*pGptBkup
= NULL
;
2365 UINT8 ReservedData
[4096];
2367 Log("#####################################################");
2368 Log("UpdateVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId
,
2369 pPhyDrive
->PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
2370 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
2371 Log("#####################################################");
2373 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2375 Log("Lock disk for umount ............................ ");
2377 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
2378 if (hDrive
== INVALID_HANDLE_VALUE
)
2380 Log("Failed to open physical disk");
2384 if (pPhyDrive
->PartStyle
)
2386 pGptInfo
= malloc(2 * sizeof(VTOY_GPT_INFO
));
2392 memset(pGptInfo
, 0, 2 * sizeof(VTOY_GPT_INFO
));
2393 pGptBkup
= pGptInfo
+ 1;
2396 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2397 ReadFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
);
2398 memcpy(pGptBkup
, pGptInfo
, sizeof(VTOY_GPT_INFO
));
2400 //MBR will be used to compare with local boot image
2401 memcpy(&MBR
, &pGptInfo
->MBR
, sizeof(MBR_HEAD
));
2403 StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
2404 Log("GPT StartSector in PartTbl:%llu", (ULONGLONG
)StartSector
);
2406 ReservedMB
= (pPhyDrive
->SizeInBytes
/ 512 - (StartSector
+ VENTOY_EFI_PART_SIZE
/ 512) - 33) / 2048;
2407 Log("GPT Reserved Disk Space:%llu MB", (ULONGLONG
)ReservedMB
);
2412 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2413 ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
2415 StartSector
= MBR
.PartTbl
[1].StartSectorId
;
2416 Log("MBR StartSector in PartTbl:%llu", (ULONGLONG
)StartSector
);
2418 ReservedMB
= (pPhyDrive
->SizeInBytes
/ 512 - (StartSector
+ VENTOY_EFI_PART_SIZE
/ 512)) / 2048;
2419 Log("MBR Reserved Disk Space:%llu MB", (ULONGLONG
)ReservedMB
);
2422 //Read Reserved Data
2423 SetFilePointer(hDrive
, 512 * 2040, NULL
, FILE_BEGIN
);
2424 ReadFile(hDrive
, ReservedData
, sizeof(ReservedData
), &dwSize
, NULL
);
2426 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
2428 if (DriveLetters
[0] == 0)
2430 Log("No drive letter was assigned...");
2434 // Unmount all mounted volumes that belong to this drive
2435 // Do it in reverse so that we always end on the first volume letter
2436 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
2438 DriveName
[0] = DriveLetters
[i
- 1];
2439 if (IsVentoyLogicalDrive(DriveName
[0]))
2441 Log("%s is ventoy logical drive", DriveName
);
2442 bRet
= DeleteVolumeMountPointA(DriveName
);
2443 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, LASTERR
);
2449 // It kind of blows, but we have to relinquish access to the physical drive
2450 // for VDS to be able to delete the partitions that reside on it...
2451 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2452 CHECK_CLOSE_HANDLE(hDrive
);
2454 if (pPhyDrive
->PartStyle
== 1)
2456 Log("TryId=%d EFI GPT partition type is 0x%llx", TryId
, pPhyDrive
->Part2GPTAttr
);
2457 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
2461 Log("Change GPT partition type to ESP");
2462 if (DISK_ChangeVtoyEFI2ESP(pPhyDrive
->PhyDrive
, StartSector
* 512ULL))
2468 else if (TryId
== 2)
2470 Log("Change GPT partition attribute");
2471 if (DISK_ChangeVtoyEFIAttr(pPhyDrive
->PhyDrive
, StartSector
* 512ULL, 0x8000000000000001))
2477 else if (TryId
== 3)
2479 DISK_DeleteVtoyEFIPartition(pPhyDrive
->PhyDrive
, StartSector
* 512ULL);
2482 else if (TryId
== 4)
2484 Log("Clean disk GPT partition table");
2485 if (BackupDataBeforeCleanDisk(pPhyDrive
->PhyDrive
, pPhyDrive
->SizeInBytes
, &pBackup
))
2487 sprintf_s(BackBinFile
, sizeof(BackBinFile
), ".\\ventoy\\phydrive%d_%u_%d.bin",
2488 pPhyDrive
->PhyDrive
, GetCurrentProcessId(), g_backup_bin_index
++);
2489 SaveBufToFile(BackBinFile
, pBackup
, 4 * SIZE_1MB
);
2490 Log("Save backup data to %s", BackBinFile
);
2492 Log("Success to backup data before clean");
2494 DISK_CleanDisk(pPhyDrive
->PhyDrive
);
2499 Log("Failed to backup data before clean");
2504 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
2506 Log("Lock disk for update ............................ ");
2507 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2508 if (hDrive
== INVALID_HANDLE_VALUE
)
2510 Log("Failed to GetPhysicalHandle for write.");
2515 PROGRESS_BAR_SET_POS(PT_LOCK_VOLUME
);
2517 Log("Lock volume for update .......................... ");
2518 hVolume
= INVALID_HANDLE_VALUE
;
2520 //If we change VTOYEFI to ESP, it can not have s volume name, so don't try to get it.
2523 //writeback the last 2MB
2524 if (!WriteBackupDataToDisk(hDrive
, pPhyDrive
->SizeInBytes
- SIZE_2MB
, pBackup
+ SIZE_2MB
, SIZE_2MB
))
2529 //write the first 2MB except parttable
2530 if (!WriteBackupDataToDisk(hDrive
, 34 * 512, pBackup
+ 34 * 512, SIZE_2MB
- 34 * 512))
2535 Status
= ERROR_NOT_FOUND
;
2539 Status
= ERROR_NOT_FOUND
;
2543 Status
= ERROR_NOT_FOUND
;
2547 for (i
= 0; i
< MaxRetry
; i
++)
2549 Status
= GetVentoyVolumeName(pPhyDrive
->PhyDrive
, StartSector
, DriveLetters
, sizeof(DriveLetters
), TRUE
);
2550 if (ERROR_SUCCESS
== Status
)
2556 Log("==== Volume not found, wait and retry %d... ====", i
);
2562 if (ERROR_SUCCESS
== Status
)
2564 Log("Now lock and dismount volume <%s>", DriveLetters
);
2566 for (i
= 0; i
< MaxRetry
; i
++)
2568 hVolume
= CreateFileA(DriveLetters
,
2569 GENERIC_READ
| GENERIC_WRITE
,
2573 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_NO_BUFFERING
| FILE_FLAG_WRITE_THROUGH
,
2576 if (hVolume
== INVALID_HANDLE_VALUE
)
2578 Log("Failed to create file volume, errcode:%u, wait and retry ...", LASTERR
);
2587 if (hVolume
== INVALID_HANDLE_VALUE
)
2589 Log("Failed to create file volume, errcode:%u", LASTERR
);
2593 bRet
= DeviceIoControl(hVolume
, FSCTL_LOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2594 Log("FSCTL_LOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2596 bRet
= DeviceIoControl(hVolume
, FSCTL_DISMOUNT_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2597 Log("FSCTL_DISMOUNT_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2600 else if (ERROR_NOT_FOUND
== Status
)
2602 Log("Volume not found, maybe not supported");
2610 bRet
= TryWritePart2(hDrive
, StartSector
);
2611 if (FALSE
== bRet
&& Esp2Basic
)
2613 Log("TryWritePart2 agagin ...");
2615 bRet
= TryWritePart2(hDrive
, StartSector
);
2620 if (pPhyDrive
->PartStyle
== 0)
2622 if (DiskCheckWriteAccess(hDrive
))
2624 Log("MBR DiskCheckWriteAccess success");
2628 Log("Try write failed, now delete partition 2 for MBR...");
2629 CHECK_CLOSE_HANDLE(hDrive
);
2631 Log("Now delete partition 2...");
2632 DISK_DeleteVtoyEFIPartition(pPhyDrive
->PhyDrive
, StartSector
* 512ULL);
2634 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2635 if (hDrive
== INVALID_HANDLE_VALUE
)
2637 Log("Failed to GetPhysicalHandle for write.");
2644 Log("MBR DiskCheckWriteAccess failed");
2649 Log("TryWritePart2 failed ....");
2655 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
2657 Log("Write Ventoy to disk ............................ ");
2658 if (0 != FormatPart2Fat(hDrive
, StartSector
))
2664 if (hVolume
!= INVALID_HANDLE_VALUE
)
2666 bRet
= DeviceIoControl(hVolume
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2667 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2668 CHECK_CLOSE_HANDLE(hVolume
);
2671 Log("Updating Boot Image ............................. ");
2672 if (WriteGrubStage1ToPhyDrive(hDrive
, pPhyDrive
->PartStyle
) != 0)
2678 //write reserved data
2679 SetFilePointer(hDrive
, 512 * 2040, NULL
, FILE_BEGIN
);
2680 bRet
= WriteFile(hDrive
, ReservedData
, sizeof(ReservedData
), &dwSize
, NULL
);
2681 Log("Write resv data ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2684 VentoyGetLocalBootImg(&BootImg
);
2687 memcpy(BootImg
.BootCode
+ 0x180, MBR
.BootCode
+ 0x180, 16);
2688 if (pPhyDrive
->PartStyle
)
2690 BootImg
.BootCode
[92] = 0x22;
2693 if (ForceMBR
== FALSE
&& memcmp(BootImg
.BootCode
, MBR
.BootCode
, 440) == 0)
2695 Log("Boot image has no difference, no need to write.");
2699 Log("Boot image need to write %u.", ForceMBR
);
2701 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2703 memcpy(MBR
.BootCode
, BootImg
.BootCode
, 440);
2704 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
2705 Log("Write Boot Image ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2708 if (pPhyDrive
->PartStyle
== 0)
2710 if (0x00 == MBR
.PartTbl
[0].Active
&& 0x80 == MBR
.PartTbl
[1].Active
)
2712 Log("Need to chage 1st partition active and 2nd partition inactive.");
2714 MBR
.PartTbl
[0].Active
= 0x80;
2715 MBR
.PartTbl
[1].Active
= 0x00;
2717 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2718 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
2719 Log("Write NEW MBR ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2725 if (!WriteBackupDataToDisk(hDrive
, 0, pBackup
, 34 * 512))
2734 Log("Write backup data success, now delete %s", BackBinFile
);
2735 DeleteFileA(BackBinFile
);
2739 Log("Write backup data failed");
2746 VTOY_GPT_HDR BackupHdr
;
2748 VentoyFillBackupGptHead(pGptBkup
, &BackupHdr
);
2749 if (!WriteBackupDataToDisk(hDrive
, 512 * pGptBkup
->Head
.EfiBackupLBA
, (BYTE
*)(&BackupHdr
), 512))
2754 if (!WriteBackupDataToDisk(hDrive
, 512 * (pGptBkup
->Head
.EfiBackupLBA
- 32), (BYTE
*)(pGptBkup
->PartTbl
), 32 * 512))
2759 if (!WriteBackupDataToDisk(hDrive
, 512, (BYTE
*)pGptBkup
+ 512, 33 * 512))
2766 Log("Write backup partition table success");
2770 Log("Write backup partition table failed");
2776 //Refresh Drive Layout
2777 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2781 if (hVolume
!= INVALID_HANDLE_VALUE
)
2783 bRet
= DeviceIoControl(hVolume
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2784 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2785 CHECK_CLOSE_HANDLE(hVolume
);
2794 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2795 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
2798 CHECK_CLOSE_HANDLE(hDrive
);
2802 Log("Recover GPT partition type to basic");
2803 DISK_ChangeVtoyEFI2Basic(pPhyDrive
->PhyDrive
, StartSector
* 512);
2806 if (pPhyDrive
->PartStyle
== 1)
2808 if (ChangeAttr
|| ((pPhyDrive
->Part2GPTAttr
>> 56) != 0xC0))
2810 Log("Change EFI partition attr %u <0x%llx> to <0x%llx>", ChangeAttr
, pPhyDrive
->Part2GPTAttr
, 0xC000000000000001ULL
);
2811 if (DISK_ChangeVtoyEFIAttr(pPhyDrive
->PhyDrive
, StartSector
* 512ULL, 0xC000000000000001ULL
))
2813 Log("Change EFI partition attr success");
2814 pPhyDrive
->Part2GPTAttr
= 0xC000000000000001ULL
;
2818 Log("Change EFI partition attr failed");