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
)
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 Ret
= DeviceIoControl(Handle
,
309 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
,
313 (DWORD
)(sizeof(DiskExtents
)),
317 if (!Ret
|| DiskExtents
.NumberOfDiskExtents
== 0)
319 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath
, LASTERR
);
320 CHECK_CLOSE_HANDLE(Handle
);
323 CHECK_CLOSE_HANDLE(Handle
);
325 Log("LogicalDrive:%s PhyDrive:%d Offset:%llu ExtentLength:%llu",
327 DiskExtents
.Extents
[0].DiskNumber
,
328 DiskExtents
.Extents
[0].StartingOffset
.QuadPart
,
329 DiskExtents
.Extents
[0].ExtentLength
.QuadPart
334 *Offset
= (UINT64
)(DiskExtents
.Extents
[0].StartingOffset
.QuadPart
);
337 return (int)DiskExtents
.Extents
[0].DiskNumber
;
340 int GetAllPhysicalDriveInfo(PHY_DRIVE_INFO
*pDriveList
, DWORD
*pDriveCount
)
348 DWORD DriveCount
= 0;
349 HANDLE Handle
= INVALID_HANDLE_VALUE
;
351 PHY_DRIVE_INFO
*CurDrive
= pDriveList
;
352 GET_LENGTH_INFORMATION LengthInfo
;
353 STORAGE_PROPERTY_QUERY Query
;
354 STORAGE_DESCRIPTOR_HEADER DevDescHeader
;
355 STORAGE_DEVICE_DESCRIPTOR
*pDevDesc
;
356 int PhyDriveId
[VENTOY_MAX_PHY_DRIVE
];
358 Count
= GetPhysicalDriveCount();
360 for (i
= 0; i
< Count
&& i
< VENTOY_MAX_PHY_DRIVE
; i
++)
365 dwBytes
= GetLogicalDrives();
366 Log("Logical Drives: 0x%x", dwBytes
);
371 id
= GetPhyDriveByLogicalDrive(Letter
, NULL
);
372 Log("%C --> %d", Letter
, id
);
375 for (i
= 0; i
< Count
; i
++)
377 if (PhyDriveId
[i
] == id
)
385 Log("Add phy%d to list", i
);
386 PhyDriveId
[Count
] = id
;
396 for (i
= 0; i
< Count
&& DriveCount
< VENTOY_MAX_PHY_DRIVE
; i
++)
398 CHECK_CLOSE_HANDLE(Handle
);
400 safe_sprintf(PhyDrive
, "\\\\.\\PhysicalDrive%d", PhyDriveId
[i
]);
401 Handle
= CreateFileA(PhyDrive
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, NULL
);
402 Log("Create file Handle:%p %s status:%u", Handle
, PhyDrive
, LASTERR
);
404 if (Handle
== INVALID_HANDLE_VALUE
)
409 bRet
= DeviceIoControl(Handle
,
410 IOCTL_DISK_GET_LENGTH_INFO
, NULL
,
418 Log("DeviceIoControl IOCTL_DISK_GET_LENGTH_INFO failed error:%u", LASTERR
);
422 Log("PHYSICALDRIVE%d size %llu bytes", i
, (ULONGLONG
)LengthInfo
.Length
.QuadPart
);
424 Query
.PropertyId
= StorageDeviceProperty
;
425 Query
.QueryType
= PropertyStandardQuery
;
427 bRet
= DeviceIoControl(Handle
,
428 IOCTL_STORAGE_QUERY_PROPERTY
,
432 sizeof(STORAGE_DESCRIPTOR_HEADER
),
437 Log("DeviceIoControl1 error:%u dwBytes:%u", LASTERR
, dwBytes
);
441 if (DevDescHeader
.Size
< sizeof(STORAGE_DEVICE_DESCRIPTOR
))
443 Log("Invalid DevDescHeader.Size:%u", DevDescHeader
.Size
);
447 pDevDesc
= (STORAGE_DEVICE_DESCRIPTOR
*)malloc(DevDescHeader
.Size
);
450 Log("failed to malloc error:%u len:%u", LASTERR
, DevDescHeader
.Size
);
454 bRet
= DeviceIoControl(Handle
,
455 IOCTL_STORAGE_QUERY_PROPERTY
,
464 Log("DeviceIoControl2 error:%u dwBytes:%u", LASTERR
, dwBytes
);
469 CurDrive
->PhyDrive
= i
;
470 CurDrive
->SizeInBytes
= LengthInfo
.Length
.QuadPart
;
471 CurDrive
->DeviceType
= pDevDesc
->DeviceType
;
472 CurDrive
->RemovableMedia
= pDevDesc
->RemovableMedia
;
473 CurDrive
->BusType
= pDevDesc
->BusType
;
475 if (pDevDesc
->VendorIdOffset
)
477 safe_strcpy(CurDrive
->VendorId
, (char *)pDevDesc
+ pDevDesc
->VendorIdOffset
);
478 TrimString(CurDrive
->VendorId
);
481 if (pDevDesc
->ProductIdOffset
)
483 safe_strcpy(CurDrive
->ProductId
, (char *)pDevDesc
+ pDevDesc
->ProductIdOffset
);
484 TrimString(CurDrive
->ProductId
);
487 if (pDevDesc
->ProductRevisionOffset
)
489 safe_strcpy(CurDrive
->ProductRev
, (char *)pDevDesc
+ pDevDesc
->ProductRevisionOffset
);
490 TrimString(CurDrive
->ProductRev
);
493 if (pDevDesc
->SerialNumberOffset
)
495 safe_strcpy(CurDrive
->SerialNumber
, (char *)pDevDesc
+ pDevDesc
->SerialNumberOffset
);
496 TrimString(CurDrive
->SerialNumber
);
504 CHECK_CLOSE_HANDLE(Handle
);
507 for (i
= 0, CurDrive
= pDriveList
; i
< (int)DriveCount
; i
++, CurDrive
++)
509 Log("PhyDrv:%d BusType:%-4s Removable:%u Size:%dGB(%llu) Name:%s %s",
510 CurDrive
->PhyDrive
, GetBusTypeString(CurDrive
->BusType
), CurDrive
->RemovableMedia
,
511 GetHumanReadableGBSize(CurDrive
->SizeInBytes
), CurDrive
->SizeInBytes
,
512 CurDrive
->VendorId
, CurDrive
->ProductId
);
515 *pDriveCount
= DriveCount
;
521 static HANDLE g_FatPhyDrive
;
522 static UINT64 g_Part2StartSec
;
523 static int GetVentoyVersionFromFatFile(CHAR
*VerBuf
, size_t BufLen
)
530 flfile
= fl_fopen("/grub/grub.cfg", "rb");
533 fl_fseek(flfile
, 0, SEEK_END
);
534 size
= (int)fl_ftell(flfile
);
536 fl_fseek(flfile
, 0, SEEK_SET
);
538 buf
= (char *)malloc(size
+ 1);
541 fl_fread(buf
, 1, size
, flfile
);
545 sprintf_s(VerBuf
, BufLen
, "%s", ParseVentoyVersionFromString(buf
));
555 static int VentoyFatDiskRead(uint32 Sector
, uint8
*Buffer
, uint32 SectorCount
)
560 LARGE_INTEGER liCurrentPosition
;
562 liCurrentPosition
.QuadPart
= Sector
+ g_Part2StartSec
;
563 liCurrentPosition
.QuadPart
*= 512;
564 SetFilePointerEx(g_FatPhyDrive
, liCurrentPosition
, &liCurrentPosition
, FILE_BEGIN
);
566 ReadSize
= (DWORD
)(SectorCount
* 512);
568 bRet
= ReadFile(g_FatPhyDrive
, Buffer
, ReadSize
, &dwSize
, NULL
);
569 if (bRet
== FALSE
|| dwSize
!= ReadSize
)
571 Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u\n", bRet
, ReadSize
, dwSize
, LASTERR
);
578 int GetVentoyVerInPhyDrive(const PHY_DRIVE_INFO
*pDriveInfo
, UINT64 Part2StartSector
, CHAR
*VerBuf
, size_t BufLen
, BOOL
*pSecureBoot
)
584 hDrive
= GetPhysicalHandle(pDriveInfo
->PhyDrive
, FALSE
, FALSE
, FALSE
);
585 if (hDrive
== INVALID_HANDLE_VALUE
)
590 g_FatPhyDrive
= hDrive
;
591 g_Part2StartSec
= Part2StartSector
;
593 Log("Parse FAT fs...");
597 if (0 == fl_attach_media(VentoyFatDiskRead
, NULL
))
599 Log("attach media success...");
600 rc
= GetVentoyVersionFromFatFile(VerBuf
, BufLen
);
604 Log("attach media failed...");
608 Log("GetVentoyVerInPhyDrive rc=%d...", rc
);
611 Log("VentoyVerInPhyDrive %d is <%s>...", pDriveInfo
->PhyDrive
, VerBuf
);
613 flfile
= fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
623 CHECK_CLOSE_HANDLE(hDrive
);
632 static unsigned int g_disk_unxz_len
= 0;
633 static BYTE
*g_part_img_pos
= NULL
;
634 static BYTE
*g_part_img_buf
[VENTOY_EFI_PART_SIZE
/ SIZE_1MB
];
637 static int VentoyFatMemRead(uint32 Sector
, uint8
*Buffer
, uint32 SectorCount
)
643 for (i
= 0; i
< SectorCount
; i
++)
645 offset
= (Sector
+ i
) * 512;
647 if (g_part_img_buf
[1] == NULL
)
649 MbBuf
= g_part_img_buf
[0] + offset
;
650 memcpy(Buffer
+ i
* 512, MbBuf
, 512);
654 MbBuf
= g_part_img_buf
[offset
/ SIZE_1MB
];
655 memcpy(Buffer
+ i
* 512, MbBuf
+ (offset
% SIZE_1MB
), 512);
663 static int VentoyFatMemWrite(uint32 Sector
, uint8
*Buffer
, uint32 SectorCount
)
669 for (i
= 0; i
< SectorCount
; i
++)
671 offset
= (Sector
+ i
) * 512;
673 if (g_part_img_buf
[1] == NULL
)
675 MbBuf
= g_part_img_buf
[0] + offset
;
676 memcpy(MbBuf
, Buffer
+ i
* 512, 512);
680 MbBuf
= g_part_img_buf
[offset
/ SIZE_1MB
];
681 memcpy(MbBuf
+ (offset
% SIZE_1MB
), Buffer
+ i
* 512, 512);
688 int VentoyProcSecureBoot(BOOL SecureBoot
)
692 char *filebuf
= NULL
;
695 Log("VentoyProcSecureBoot %d ...", SecureBoot
);
699 Log("Secure boot is enabled ...");
705 if (0 == fl_attach_media(VentoyFatMemRead
, VentoyFatMemWrite
))
707 file
= fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
708 Log("Open ventoy efi file %p ", file
);
711 fl_fseek(file
, 0, SEEK_END
);
712 size
= (int)fl_ftell(file
);
713 fl_fseek(file
, 0, SEEK_SET
);
715 Log("ventoy efi file size %d ...", size
);
717 filebuf
= (char *)malloc(size
);
720 fl_fread(filebuf
, 1, size
, file
);
725 Log("Now delete all efi files ...");
726 fl_remove("/EFI/BOOT/BOOTX64.EFI");
727 fl_remove("/EFI/BOOT/grubx64.efi");
728 fl_remove("/EFI/BOOT/grubx64_real.efi");
729 fl_remove("/EFI/BOOT/MokManager.efi");
730 fl_remove("/ENROLL_THIS_KEY_IN_MOKMANAGER.cer");
732 file
= fl_fopen("/EFI/BOOT/BOOTX64.EFI", "wb");
733 Log("Open bootx64 efi file %p ", file
);
738 fl_fwrite(filebuf
, 1, size
, file
);
751 file
= fl_fopen("/EFI/BOOT/grubia32_real.efi", "rb");
752 Log("Open ventoy efi file %p ", file
);
755 fl_fseek(file
, 0, SEEK_END
);
756 size
= (int)fl_ftell(file
);
757 fl_fseek(file
, 0, SEEK_SET
);
759 Log("ventoy efi file size %d ...", size
);
761 filebuf
= (char *)malloc(size
);
764 fl_fread(filebuf
, 1, size
, file
);
769 Log("Now delete all efi files ...");
770 fl_remove("/EFI/BOOT/BOOTIA32.EFI");
771 fl_remove("/EFI/BOOT/grubia32.efi");
772 fl_remove("/EFI/BOOT/grubia32_real.efi");
773 fl_remove("/EFI/BOOT/mmia32.efi");
775 file
= fl_fopen("/EFI/BOOT/BOOTIA32.EFI", "wb");
776 Log("Open bootia32 efi file %p ", file
);
781 fl_fwrite(filebuf
, 1, size
, file
);
807 static int disk_xz_flush(void *src
, unsigned int size
)
810 BYTE
*buf
= (BYTE
*)src
;
812 for (i
= 0; i
< size
; i
++)
814 *g_part_img_pos
= *buf
++;
817 if ((g_disk_unxz_len
% SIZE_1MB
) == 0)
819 g_part_img_pos
= g_part_img_buf
[g_disk_unxz_len
/ SIZE_1MB
];
830 static void unxz_error(char *x
)
835 static BOOL
TryWritePart2(HANDLE hDrive
, UINT64 StartSectorId
)
838 DWORD TrySize
= 16 * 1024;
841 unsigned char *data
= NULL
;
842 LARGE_INTEGER liCurrentPosition
;
844 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
845 SetFilePointerEx(hDrive
, liCurrentPosition
, &liCurrentPosition
, FILE_BEGIN
);
847 Buffer
= malloc(TrySize
);
849 bRet
= WriteFile(hDrive
, Buffer
, TrySize
, &dwSize
, NULL
);
853 Log("Try write part2 bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
855 if (bRet
&& dwSize
== TrySize
)
863 static int FormatPart2Fat(HANDLE hDrive
, UINT64 StartSectorId
)
870 int Pos
= PT_WRITE_VENTOY_START
;
873 unsigned char *data
= NULL
;
874 LARGE_INTEGER liCurrentPosition
;
875 LARGE_INTEGER liNewPosition
;
876 BYTE
*CheckBuf
= NULL
;
878 Log("FormatPart2Fat %llu...", (ULONGLONG
)StartSectorId
);
880 CheckBuf
= malloc(SIZE_1MB
);
883 Log("Failed to malloc check buf");
887 rc
= ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG
, 0, (void **)&data
, &len
);
890 Log("Failed to read img file %p %u", data
, len
);
895 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
896 SetFilePointerEx(hDrive
, liCurrentPosition
, &liNewPosition
, FILE_BEGIN
);
898 memset(g_part_img_buf
, 0, sizeof(g_part_img_buf
));
900 g_part_img_buf
[0] = (BYTE
*)malloc(VENTOY_EFI_PART_SIZE
);
901 if (g_part_img_buf
[0])
903 Log("Malloc whole img buffer success, now decompress ...");
904 unxz(data
, len
, NULL
, NULL
, g_part_img_buf
[0], &writelen
, unxz_error
);
908 Log("decompress finished success");
910 VentoyProcSecureBoot(g_SecureBoot
);
912 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
915 bRet
= WriteFile(hDrive
, g_part_img_buf
[0] + i
* SIZE_1MB
, SIZE_1MB
, &dwSize
, NULL
);
916 Log("Write part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
924 PROGRESS_BAR_SET_POS(Pos
);
931 //Read and check the data
932 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
933 SetFilePointerEx(hDrive
, liCurrentPosition
, &liNewPosition
, FILE_BEGIN
);
935 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
937 bRet
= ReadFile(hDrive
, CheckBuf
, SIZE_1MB
, &dwSize
, NULL
);
938 Log("Read part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
940 if (!bRet
|| memcmp(CheckBuf
, g_part_img_buf
[0] + i
* SIZE_1MB
, SIZE_1MB
))
942 Log("### [Check Fail] The data write and read does not match");
947 PROGRESS_BAR_SET_POS(Pos
);
957 Log("decompress finished failed");
963 Log("Failed to malloc whole img size %u, now split it", VENTOY_EFI_PART_SIZE
);
966 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
968 g_part_img_buf
[i
] = (BYTE
*)malloc(SIZE_1MB
);
969 if (g_part_img_buf
[i
] == NULL
)
976 Log("Malloc part img buffer success, now decompress ...");
978 g_part_img_pos
= g_part_img_buf
[0];
980 unxz(data
, len
, NULL
, disk_xz_flush
, NULL
, NULL
, unxz_error
);
982 if (g_disk_unxz_len
== VENTOY_EFI_PART_SIZE
)
984 Log("decompress finished success");
986 VentoyProcSecureBoot(g_SecureBoot
);
988 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
991 bRet
= WriteFile(hDrive
, g_part_img_buf
[i
], SIZE_1MB
, &dwSize
, NULL
);
992 Log("Write part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
1000 PROGRESS_BAR_SET_POS(Pos
);
1007 //Read and check the data
1008 liCurrentPosition
.QuadPart
= StartSectorId
* 512;
1009 SetFilePointerEx(hDrive
, liCurrentPosition
, &liNewPosition
, FILE_BEGIN
);
1011 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
1013 bRet
= ReadFile(hDrive
, CheckBuf
, SIZE_1MB
, &dwSize
, NULL
);
1014 Log("Read part data bRet:%u dwSize:%u code:%u", bRet
, dwSize
, LASTERR
);
1016 if (!bRet
|| memcmp(CheckBuf
, g_part_img_buf
[i
], SIZE_1MB
))
1018 Log("### [Check Fail] The data write and read does not match");
1023 PROGRESS_BAR_SET_POS(Pos
);
1033 Log("decompress finished failed");
1040 if (data
) free(data
);
1041 if (CheckBuf
)free(CheckBuf
);
1045 for (i
= 0; i
< VENTOY_EFI_PART_SIZE
/ SIZE_1MB
; i
++)
1047 if (g_part_img_buf
[i
]) free(g_part_img_buf
[i
]);
1052 if (g_part_img_buf
[0]) free(g_part_img_buf
[0]);
1058 static int WriteGrubStage1ToPhyDrive(HANDLE hDrive
, int PartStyle
)
1064 BYTE
*ImgBuf
= NULL
;
1065 BYTE
*RawBuf
= NULL
;
1067 Log("WriteGrubStage1ToPhyDrive ...");
1069 RawBuf
= (BYTE
*)malloc(SIZE_1MB
);
1075 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG
, 0, (void **)&ImgBuf
, &Len
))
1077 Log("Failed to read stage1 img");
1082 unxz(ImgBuf
, Len
, NULL
, NULL
, RawBuf
, &readLen
, unxz_error
);
1086 Log("Write GPT stage1 ...");
1087 RawBuf
[500] = 35;//update blocklist
1088 SetFilePointer(hDrive
, 512 * 34, NULL
, FILE_BEGIN
);
1089 bRet
= WriteFile(hDrive
, RawBuf
, SIZE_1MB
- 512 * 34, &dwSize
, NULL
);
1093 Log("Write MBR stage1 ...");
1094 SetFilePointer(hDrive
, 512, NULL
, FILE_BEGIN
);
1095 bRet
= WriteFile(hDrive
, RawBuf
, SIZE_1MB
- 512, &dwSize
, NULL
);
1098 Log("WriteFile Ret:%u dwSize:%u ErrCode:%u", bRet
, dwSize
, GetLastError());
1107 static int FormatPart1exFAT(UINT64 DiskSizeBytes
)
1112 Option
.fmt
= FM_EXFAT
;
1117 // < 32GB select 32KB as cluster size
1118 // > 32GB select 128KB as cluster size
1119 if (DiskSizeBytes
/ 1024 / 1024 / 1024 <= 32)
1121 Option
.au_size
= 32768;
1125 Option
.au_size
= 131072;
1128 Log("Formatting Part1 exFAT ...");
1130 Ret
= f_mkfs(TEXT("0:"), &Option
, 0, 8 * 1024 * 1024);
1133 Log("Formatting Part1 exFAT success");
1138 Log("Formatting Part1 exFAT failed");
1145 int ClearVentoyFromPhyDrive(HWND hWnd
, PHY_DRIVE_INFO
*pPhyDrive
, char *pDrvLetter
)
1154 CHAR DriveName
[] = "?:\\";
1155 CHAR DriveLetters
[MAX_PATH
] = { 0 };
1156 LARGE_INTEGER liCurrentPosition
;
1157 char *pTmpBuf
= NULL
;
1162 Log("ClearVentoyFromPhyDrive PhyDrive%d <<%s %s %dGB>>",
1163 pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1164 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1166 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1168 Log("Lock disk for clean ............................. ");
1170 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
1171 if (hDrive
== INVALID_HANDLE_VALUE
)
1173 Log("Failed to open physical disk");
1177 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1179 if (DriveLetters
[0] == 0)
1181 Log("No drive letter was assigned...");
1182 DriveName
[0] = GetFirstUnusedDriveLetter();
1183 Log("GetFirstUnusedDriveLetter %C: ...", DriveName
[0]);
1187 // Unmount all mounted volumes that belong to this drive
1188 // Do it in reverse so that we always end on the first volume letter
1189 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
1191 DriveName
[0] = DriveLetters
[i
- 1];
1192 bRet
= DeleteVolumeMountPointA(DriveName
);
1193 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, GetLastError());
1197 MountDrive
= DriveName
[0];
1198 Log("Will use '%C:' as volume mountpoint", DriveName
[0]);
1200 // It kind of blows, but we have to relinquish access to the physical drive
1201 // for VDS to be able to delete the partitions that reside on it...
1202 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1203 CHECK_CLOSE_HANDLE(hDrive
);
1205 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
1207 if (!VDS_DeleteAllPartitions(pPhyDrive
->PhyDrive
))
1209 Log("Notice: Could not delete partitions: %u", GetLastError());
1212 Log("Deleting all partitions ......................... OK");
1214 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
1216 Log("Lock disk for write ............................. ");
1217 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1218 if (hDrive
== INVALID_HANDLE_VALUE
)
1220 Log("Failed to GetPhysicalHandle for write.");
1225 // clear first and last 2MB space
1226 pTmpBuf
= malloc(SIZE_2MB
);
1229 Log("Failed to alloc memory.");
1233 memset(pTmpBuf
, 0, SIZE_2MB
);
1236 bRet
= WriteFile(hDrive
, pTmpBuf
, SIZE_2MB
- 512, &dwSize
, NULL
);
1237 Log("Write fisrt 1MB ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1244 SET_FILE_POS(pPhyDrive
->SizeInBytes
- SIZE_2MB
);
1245 bRet
= WriteFile(hDrive
, pTmpBuf
, SIZE_2MB
, &dwSize
, NULL
);
1246 Log("Write 2nd 1MB ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1255 if (pPhyDrive
->SizeInBytes
> 2199023255552ULL)
1257 VTOY_GPT_INFO
*pGptInfo
;
1258 VTOY_GPT_HDR BackupHead
;
1259 LARGE_INTEGER liCurrentPosition
;
1261 pGptInfo
= (VTOY_GPT_INFO
*)pTmpBuf
;
1263 VentoyFillWholeGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1265 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512);
1266 VentoyFillBackupGptHead(pGptInfo
, &BackupHead
);
1267 if (!WriteFile(hDrive
, &BackupHead
, sizeof(VTOY_GPT_HDR
), &dwSize
, NULL
))
1270 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1274 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512 * 33);
1275 if (!WriteFile(hDrive
, pGptInfo
->PartTbl
, sizeof(pGptInfo
->PartTbl
), &dwSize
, NULL
))
1278 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1283 if (!WriteFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
))
1286 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1290 Log("Write GPT Info OK ...");
1294 bRet
= ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
1295 Log("Read MBR ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1302 //clear boot code and partition table (reserved disk signature)
1303 memset(MBR
.BootCode
, 0, 440);
1304 memset(MBR
.PartTbl
, 0, sizeof(MBR
.PartTbl
));
1306 VentoyFillMBRLocation(pPhyDrive
->SizeInBytes
, 2048, (UINT32
)(pPhyDrive
->SizeInBytes
/ 512 - 2048), MBR
.PartTbl
);
1308 MBR
.PartTbl
[0].Active
= 0x00; // bootable
1309 MBR
.PartTbl
[0].FsFlag
= 0x07; // exFAT/NTFS/HPFS
1312 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
1313 Log("Write MBR ret:%d size:%u err:%d", bRet
, dwSize
, LASTERR
);
1321 Log("Clear Ventoy successfully finished");
1323 //Refresh Drive Layout
1324 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1328 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1337 Log("Mounting Ventoy Partition ....................... ");
1341 memset(DriveLetters
, 0, sizeof(DriveLetters
));
1342 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1343 Log("Logical drive letter after write ventoy: <%s>", DriveLetters
);
1345 for (i
= 0; i
< sizeof(DriveLetters
) && DriveLetters
[i
]; i
++)
1347 DriveName
[0] = DriveLetters
[i
];
1348 Log("%s is ventoy part1, already mounted", DriveName
);
1354 Log("need to mount ventoy part1...");
1355 if (0 == GetVentoyVolumeName(pPhyDrive
->PhyDrive
, 2048, DriveLetters
, sizeof(DriveLetters
), FALSE
))
1357 DriveName
[0] = MountDrive
;
1358 bRet
= SetVolumeMountPointA(DriveName
, DriveLetters
);
1359 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName
, DriveLetters
, bRet
, GetLastError());
1361 *pDrvLetter
= MountDrive
;
1365 Log("Failed to find ventoy volume");
1373 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
1376 CHECK_CLOSE_HANDLE(hDrive
);
1380 int InstallVentoy2FileImage(PHY_DRIVE_INFO
*pPhyDrive
, int PartStyle
)
1389 UINT64 data_offset
= 0;
1390 UINT64 Part2StartSector
= 0;
1391 UINT64 Part1StartSector
= 0;
1392 UINT64 Part1SectorCount
= 0;
1393 UINT8
*pData
= NULL
;
1394 UINT8
*pBkGptPartTbl
= NULL
;
1395 BYTE
*ImgBuf
= NULL
;
1396 MBR_HEAD
*pMBR
= NULL
;
1397 VTSI_FOOTER
*pImgFooter
= NULL
;
1398 VTSI_SEGMENT
*pSegment
= NULL
;
1399 VTOY_GPT_INFO
*pGptInfo
= NULL
;
1400 VTOY_GPT_HDR
*pBkGptHdr
= NULL
;
1403 Log("InstallVentoy2FileImage %s PhyDrive%d <<%s %s %dGB>>",
1404 PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1405 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1407 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1409 size
= SIZE_1MB
+ VENTOY_EFI_PART_SIZE
+ 33 * 512 + VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
) + sizeof(VTSI_FOOTER
);
1411 pData
= (UINT8
*)malloc(size
);
1414 Log("malloc image buffer failed %d.", size
);
1418 pImgFooter
= (VTSI_FOOTER
*)(pData
+ size
- sizeof(VTSI_FOOTER
));
1419 pSegment
= (VTSI_SEGMENT
*)((UINT8
*)pImgFooter
- VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
));
1420 memset(pImgFooter
, 0, sizeof(VTSI_FOOTER
));
1421 memset(pSegment
, 0, VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
));
1423 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START
);
1425 Log("Writing Boot Image ............................. ");
1426 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG
, 0, (void **)&ImgBuf
, &Len
))
1428 Log("Failed to read stage1 img");
1432 unxz(ImgBuf
, Len
, NULL
, NULL
, pData
, &dataLen
, unxz_error
);
1435 Log("decompress %s len:%d", VENTOY_FILE_STG1_IMG
, dataLen
);
1439 pData
[500] = 35;//update blocklist
1440 memmove(pData
+ 34 * 512, pData
, SIZE_1MB
- 512 * 34);
1441 memset(pData
, 0, 34 * 512);
1443 pGptInfo
= (VTOY_GPT_INFO
*)pData
;
1444 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
1445 VentoyFillGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1447 pBkGptPartTbl
= pData
+ SIZE_1MB
+ VENTOY_EFI_PART_SIZE
;
1448 memset(pBkGptPartTbl
, 0, 33 * 512);
1450 memcpy(pBkGptPartTbl
, pGptInfo
->PartTbl
, 32 * 512);
1451 pBkGptHdr
= (VTOY_GPT_HDR
*)(pBkGptPartTbl
+ 32 * 512);
1452 VentoyFillBackupGptHead(pGptInfo
, pBkGptHdr
);
1454 Part1StartSector
= pGptInfo
->PartTbl
[0].StartLBA
;
1455 Part1SectorCount
= pGptInfo
->PartTbl
[0].LastLBA
- Part1StartSector
+ 1;
1456 Part2StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
1458 Log("Write GPT Info OK ...");
1462 memmove(pData
+ 512, pData
, SIZE_1MB
- 512);
1463 memset(pData
, 0, 512);
1465 pMBR
= (MBR_HEAD
*)pData
;
1466 VentoyFillMBR(pPhyDrive
->SizeInBytes
, pMBR
, PartStyle
);
1467 Part1StartSector
= pMBR
->PartTbl
[0].StartSectorId
;
1468 Part1SectorCount
= pMBR
->PartTbl
[0].SectorCount
;
1469 Part2StartSector
= pMBR
->PartTbl
[1].StartSectorId
;
1471 Log("Write MBR OK ...");
1474 Log("Writing EFI part Image ............................. ");
1475 rc
= ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG
, 0, (void **)&ImgBuf
, &Len
);
1478 Log("Failed to read img file %p %u", ImgBuf
, Len
);
1482 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START
+ 28);
1483 memset(g_part_img_buf
, 0, sizeof(g_part_img_buf
));
1484 unxz(ImgBuf
, Len
, NULL
, NULL
, pData
+ SIZE_1MB
, &dataLen
, unxz_error
);
1487 Log("decompress finished success");
1488 g_part_img_buf
[0] = pData
+ SIZE_1MB
;
1490 VentoyProcSecureBoot(g_SecureBoot
);
1494 Log("decompress finished failed");
1498 fopen_s(&fp
, "VentoySparseImg.vtsi", "wb+");
1501 Log("Failed to create Ventoy img file");
1505 Log("Writing stage1 data ............................. ");
1507 fwrite(pData
, 1, SIZE_1MB
, fp
);
1509 pSegment
[0].disk_start_sector
= 0;
1510 pSegment
[0].sector_num
= SIZE_1MB
/ 512;
1511 pSegment
[0].data_offset
= data_offset
;
1512 data_offset
+= pSegment
[0].sector_num
* 512;
1514 disk_io_set_param(INVALID_HANDLE_VALUE
, Part1StartSector
+ Part1SectorCount
);// include the 2048 sector gap
1515 disk_io_set_imghook(fp
, pSegment
+ 1, VTSI_IMG_MAX_SEG
- 1, data_offset
);
1517 Log("Formatting part1 exFAT ...");
1518 if (0 != FormatPart1exFAT(pPhyDrive
->SizeInBytes
))
1520 Log("FormatPart1exFAT failed.");
1521 disk_io_reset_imghook(&segnum
, &data_offset
);
1525 disk_io_reset_imghook(&segnum
, &data_offset
);
1528 Log("current segment number:%d dataoff:%ld", segnum
, (long)data_offset
);
1531 Log("Writing part2 data ............................. ");
1532 fwrite(pData
+ SIZE_1MB
, 1, VENTOY_EFI_PART_SIZE
, fp
);
1533 pSegment
[segnum
].disk_start_sector
= Part2StartSector
;
1534 pSegment
[segnum
].sector_num
= VENTOY_EFI_PART_SIZE
/ 512;
1535 pSegment
[segnum
].data_offset
= data_offset
;
1536 data_offset
+= pSegment
[segnum
].sector_num
* 512;
1541 Log("Writing backup gpt table ............................. ");
1542 fwrite(pBkGptPartTbl
, 1, 33 * 512, fp
);
1543 pSegment
[segnum
].disk_start_sector
= pPhyDrive
->SizeInBytes
/ 512 - 33;
1544 pSegment
[segnum
].sector_num
= 33;
1545 pSegment
[segnum
].data_offset
= data_offset
;
1546 data_offset
+= pSegment
[segnum
].sector_num
* 512;
1550 Log("Writing segment metadata ............................. ");
1552 for (i
= 0; i
< (int)segnum
; i
++)
1554 Log("SEG[%d]: PhySector:%llu SectorNum:%llu DataOffset:%llu(sector:%llu)", i
, pSegment
[i
].disk_start_sector
, pSegment
[i
].sector_num
,
1555 pSegment
[i
].data_offset
, pSegment
[i
].data_offset
/ 512);
1558 dataLen
= segnum
* sizeof(VTSI_SEGMENT
);
1559 fwrite(pSegment
, 1, dataLen
, fp
);
1563 //pData + SIZE_1MB - 8192 is a temp data buffer with zero
1564 fwrite(pData
+ SIZE_1MB
- 8192, 1, 512 - (dataLen
% 512), fp
);
1568 pImgFooter
->magic
= VTSI_IMG_MAGIC
;
1569 pImgFooter
->version
= 1;
1570 pImgFooter
->disk_size
= pPhyDrive
->SizeInBytes
;
1571 memcpy(&pImgFooter
->disk_signature
, pPhyDrive
->MBR
.BootCode
+ 0x1b8, 4);
1572 pImgFooter
->segment_num
= segnum
;
1573 pImgFooter
->segment_offset
= data_offset
;
1575 for (i
= 0, chksum
= 0; i
< (int)(segnum
* sizeof(VTSI_SEGMENT
)); i
++)
1577 chksum
+= *((UINT8
*)pSegment
+ i
);
1579 pImgFooter
->segment_chksum
= ~chksum
;
1581 for (i
= 0, chksum
= 0; i
< sizeof(VTSI_FOOTER
); i
++)
1583 chksum
+= *((UINT8
*)pImgFooter
+ i
);
1585 pImgFooter
->foot_chksum
= ~chksum
;
1587 Log("Writing footer segnum(%u) segoffset(%llu) ......................", segnum
, data_offset
);
1588 Log("disk_size=%llu disk_signature=%lx segment_offset=%llu", pImgFooter
->disk_size
, pImgFooter
->disk_signature
, pImgFooter
->segment_offset
);
1590 fwrite(pImgFooter
, 1, sizeof(VTSI_FOOTER
), fp
);
1593 Log("Writing Ventoy image file finished, the file size should be %llu .", data_offset
+ 512 + ((dataLen
+ 511) / 512 * 512));
1599 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1601 Log("retcode:%d\n", rc
);
1610 int InstallVentoy2PhyDrive(PHY_DRIVE_INFO
*pPhyDrive
, int PartStyle
, int TryId
)
1619 CHAR DriveName
[] = "?:\\";
1620 CHAR DriveLetters
[MAX_PATH
] = { 0 };
1622 VTOY_GPT_INFO
*pGptInfo
= NULL
;
1623 UINT64 Part1StartSector
= 0;
1624 UINT64 Part1SectorCount
= 0;
1625 UINT64 Part2StartSector
= 0;
1627 Log("#####################################################");
1628 Log("InstallVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId
,
1629 PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1630 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1631 Log("#####################################################");
1635 pGptInfo
= malloc(sizeof(VTOY_GPT_INFO
));
1636 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
1639 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1643 VentoyFillGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1644 Part1StartSector
= pGptInfo
->PartTbl
[0].StartLBA
;
1645 Part1SectorCount
= pGptInfo
->PartTbl
[0].LastLBA
- Part1StartSector
+ 1;
1646 Part2StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
1650 VentoyFillMBR(pPhyDrive
->SizeInBytes
, &MBR
, PartStyle
);
1651 Part1StartSector
= MBR
.PartTbl
[0].StartSectorId
;
1652 Part1SectorCount
= MBR
.PartTbl
[0].SectorCount
;
1653 Part2StartSector
= MBR
.PartTbl
[1].StartSectorId
;
1656 Log("Lock disk for clean ............................. ");
1658 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
1659 if (hDrive
== INVALID_HANDLE_VALUE
)
1661 Log("Failed to open physical disk");
1666 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1668 if (DriveLetters
[0] == 0)
1670 Log("No drive letter was assigned...");
1671 DriveName
[0] = GetFirstUnusedDriveLetter();
1672 Log("GetFirstUnusedDriveLetter %C: ...", DriveName
[0]);
1676 // Unmount all mounted volumes that belong to this drive
1677 // Do it in reverse so that we always end on the first volume letter
1678 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
1680 DriveName
[0] = DriveLetters
[i
- 1];
1681 bRet
= DeleteVolumeMountPointA(DriveName
);
1682 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, GetLastError());
1686 MountDrive
= DriveName
[0];
1687 Log("Will use '%C:' as volume mountpoint", DriveName
[0]);
1689 // It kind of blows, but we have to relinquish access to the physical drive
1690 // for VDS to be able to delete the partitions that reside on it...
1691 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1692 CHECK_CLOSE_HANDLE(hDrive
);
1694 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
1696 if (!VDS_DeleteAllPartitions(pPhyDrive
->PhyDrive
))
1698 Log("Notice: Could not delete partitions: 0x%x, but we continue.", GetLastError());
1701 Log("Deleting all partitions ......................... OK");
1703 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
1705 Log("Lock disk for write ............................. ");
1706 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1707 if (hDrive
== INVALID_HANDLE_VALUE
)
1709 Log("Failed to GetPhysicalHandle for write.");
1714 //Refresh Drive Layout
1715 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1717 disk_io_set_param(hDrive
, Part1StartSector
+ Part1SectorCount
);// include the 2048 sector gap
1719 PROGRESS_BAR_SET_POS(PT_FORMAT_PART1
);
1721 if (PartStyle
== 1 && pPhyDrive
->PartStyle
== 0)
1723 Log("Wait for format part1 ...");
1727 Log("Formatting part1 exFAT ...");
1728 if (0 != FormatPart1exFAT(pPhyDrive
->SizeInBytes
))
1730 Log("FormatPart1exFAT failed.");
1735 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
1736 Log("Writing part2 FAT img ...");
1738 if (0 != FormatPart2Fat(hDrive
, Part2StartSector
))
1740 Log("FormatPart2Fat failed.");
1745 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG
);
1746 Log("Writing Boot Image ............................. ");
1747 if (WriteGrubStage1ToPhyDrive(hDrive
, PartStyle
) != 0)
1749 Log("WriteGrubStage1ToPhyDrive failed.");
1754 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE
);
1755 Log("Writing Partition Table ........................ ");
1756 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
1760 VTOY_GPT_HDR BackupHead
;
1761 LARGE_INTEGER liCurrentPosition
;
1763 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512);
1764 VentoyFillBackupGptHead(pGptInfo
, &BackupHead
);
1765 if (!WriteFile(hDrive
, &BackupHead
, sizeof(VTOY_GPT_HDR
), &dwSize
, NULL
))
1768 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1772 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512 * 33);
1773 if (!WriteFile(hDrive
, pGptInfo
->PartTbl
, sizeof(pGptInfo
->PartTbl
), &dwSize
, NULL
))
1776 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1781 if (!WriteFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
))
1784 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1788 Log("Write GPT Info OK ...");
1789 memcpy(&(pPhyDrive
->MBR
), &(pGptInfo
->MBR
), 512);
1793 if (!WriteFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
))
1796 Log("Write MBR Failed, dwSize:%u ErrCode:%u", dwSize
, GetLastError());
1799 Log("Write MBR OK ...");
1800 memcpy(&(pPhyDrive
->MBR
), &MBR
, 512);
1803 //Refresh Drive Layout
1804 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1808 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1812 Log("Mounting Ventoy Partition ....................... ");
1816 memset(DriveLetters
, 0, sizeof(DriveLetters
));
1817 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1818 Log("Logical drive letter after write ventoy: <%s>", DriveLetters
);
1820 for (i
= 0; i
< sizeof(DriveLetters
) && DriveLetters
[i
]; i
++)
1822 DriveName
[0] = DriveLetters
[i
];
1823 if (IsVentoyLogicalDrive(DriveName
[0]))
1825 Log("%s is ventoy part2, delete mountpoint", DriveName
);
1826 DeleteVolumeMountPointA(DriveName
);
1830 Log("%s is ventoy part1, already mounted", DriveName
);
1837 Log("need to mount ventoy part1...");
1839 if (0 == GetVentoyVolumeName(pPhyDrive
->PhyDrive
, Part1StartSector
, DriveLetters
, sizeof(DriveLetters
), FALSE
))
1841 DriveName
[0] = MountDrive
;
1842 bRet
= SetVolumeMountPointA(DriveName
, DriveLetters
);
1843 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName
, DriveLetters
, bRet
, GetLastError());
1847 Log("Failed to find ventoy volume");
1854 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
1862 CHECK_CLOSE_HANDLE(hDrive
);
1867 int PartitionResizeForVentoy(PHY_DRIVE_INFO
*pPhyDrive
)
1873 INT64 ReservedValue
;
1877 VTOY_GPT_INFO
*pGPT
;
1880 VTOY_GPT_HDR BackupHead
;
1881 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
1882 GUID ZeroGuid
= { 0 };
1883 static GUID WindowsDataPartType
= { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
1884 static GUID EspPartType
= { 0xc12a7328, 0xf81f, 0x11d2, { 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b } };
1885 static GUID BiosGrubPartType
= { 0x21686148, 0x6449, 0x6e6f, { 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46, 0x49 } };
1887 Log("#####################################################");
1888 Log("PartitionResizeForVentoy PhyDrive%d <<%s %s %dGB>>",
1889 pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1890 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1891 Log("#####################################################");
1893 pGPT
= &(pPhyDrive
->Gpt
);
1894 pMBR
= &(pPhyDrive
->Gpt
.MBR
);
1895 Log("Disksize:%llu Part2Start:%llu", pPhyDrive
->SizeInBytes
, pPhyDrive
->ResizePart2StartSector
* 512);
1897 if (pMBR
->PartTbl
[0].FsFlag
== 0xEE && memcmp(pGPT
->Head
.Signature
, "EFI PART", 8) == 0)
1906 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1908 RecudeBytes
= VENTOY_EFI_PART_SIZE
;
1909 ReservedValue
= GetReservedSpaceInMB();
1910 if (ReservedValue
> 0)
1912 Log("Reduce add reserved space %lldMB", (LONGLONG
)ReservedValue
);
1913 RecudeBytes
+= (UINT64
)(ReservedValue
* SIZE_1MB
);
1917 if (pPhyDrive
->ResizeNoShrink
== FALSE
)
1919 Log("Need to shrink the volume");
1920 if (VDS_ShrinkVolume(pPhyDrive
->ResizeVolumeGuid
, RecudeBytes
))
1922 Log("Shrink volume success, now check again");
1924 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1925 if (hDrive
== INVALID_HANDLE_VALUE
)
1927 Log("Failed to GetPhysicalHandle for update.");
1931 //Refresh Drive Layout
1932 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1934 CHECK_CLOSE_HANDLE(hDrive
);
1937 if (PartResizePreCheck(NULL
) && pPhyDrive
->ResizeNoShrink
)
1939 Log("Recheck after Shrink volume success");
1940 Log("After shrink Disksize:%llu Part2Start:%llu", pPhyDrive
->SizeInBytes
, pPhyDrive
->ResizePart2StartSector
* 512);
1944 Log("Recheck after Shrink volume failed %u", pPhyDrive
->ResizeNoShrink
);
1950 Log("Shrink volume failed");
1956 //Now try write data
1957 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1958 if (hDrive
== INVALID_HANDLE_VALUE
)
1960 Log("Failed to GetPhysicalHandle for update.");
1965 //Write partition 2 data
1966 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
1967 if (0 != FormatPart2Fat(hDrive
, pPhyDrive
->ResizePart2StartSector
))
1969 Log("FormatPart2Fat failed.");
1973 //Write grub stage2 gap
1974 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG
);
1975 Log("Writing Boot Image ............................. ");
1976 if (WriteGrubStage1ToPhyDrive(hDrive
, PartStyle
) != 0)
1978 Log("WriteGrubStage1ToPhyDrive failed.");
1983 //Write partition table
1984 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE
);
1985 Log("Writing partition table ............................. ");
1987 VentoyGetLocalBootImg(&MBR
);
1988 CoCreateGuid(&Guid
);
1989 memcpy(MBR
.BootCode
+ 0x180, &Guid
, 16);
1990 memcpy(pMBR
->BootCode
, MBR
.BootCode
, 440);
1994 for (i
= 1; i
< 4; i
++)
1996 if (pMBR
->PartTbl
[i
].SectorCount
== 0)
2004 Log("Can not find MBR free partition table");
2008 for (j
= i
- 1; j
> 0; j
--)
2010 Log("Move MBR partition table %d --> %d", j
+ 1, j
+ 2);
2011 memcpy(pMBR
->PartTbl
+ (j
+ 1), pMBR
->PartTbl
+ j
, sizeof(PART_TABLE
));
2014 VentoyFillMBRLocation(pPhyDrive
->SizeInBytes
, (UINT32
)pPhyDrive
->ResizePart2StartSector
, VENTOY_EFI_PART_SIZE
/ 512, pMBR
->PartTbl
+ 1);
2015 pMBR
->PartTbl
[0].Active
= 0x80; // bootable
2016 pMBR
->PartTbl
[1].Active
= 0x00;
2017 pMBR
->PartTbl
[1].FsFlag
= 0xEF; // EFI System Partition
2019 if (!WriteDataToPhyDisk(hDrive
, 0, pMBR
, 512))
2021 Log("Legacy BIOS write MBR failed");
2027 for (i
= 1; i
< 128; i
++)
2029 if (memcmp(&(pGPT
->PartTbl
[i
].PartGuid
), &ZeroGuid
, sizeof(GUID
)) == 0)
2037 Log("Can not find GPT free partition table");
2041 for (j
= i
- 1; j
> 0; j
--)
2043 Log("Move GPT partition table %d --> %d", j
+ 1, j
+ 2);
2044 memcpy(pGPT
->PartTbl
+ (j
+ 1), pGPT
->PartTbl
+ j
, sizeof(VTOY_GPT_PART_TBL
));
2048 pMBR
->BootCode
[92] = 0x22;
2050 // to fix windows issue
2051 memcpy(&(pGPT
->PartTbl
[1].PartType
), &WindowsDataPartType
, sizeof(GUID
));
2052 CoCreateGuid(&(pGPT
->PartTbl
[1].PartGuid
));
2054 pGPT
->PartTbl
[1].StartLBA
= pGPT
->PartTbl
[0].LastLBA
+ 1;
2055 pGPT
->PartTbl
[1].LastLBA
= pGPT
->PartTbl
[1].StartLBA
+ VENTOY_EFI_PART_SIZE
/ 512 - 1;
2056 pGPT
->PartTbl
[1].Attr
= 0xC000000000000001ULL
;
2057 memcpy(pGPT
->PartTbl
[1].Name
, L
"VTOYEFI", 7 * 2);
2060 pGPT
->Head
.PartTblCrc
= VentoyCrc32(pGPT
->PartTbl
, sizeof(pGPT
->PartTbl
));
2061 pGPT
->Head
.Crc
= VentoyCrc32(&(pGPT
->Head
), pGPT
->Head
.Length
);
2063 Log("pGPT->Head.EfiStartLBA=%llu", (ULONGLONG
)pGPT
->Head
.EfiStartLBA
);
2064 Log("pGPT->Head.EfiBackupLBA=%llu", (ULONGLONG
)pGPT
->Head
.EfiBackupLBA
);
2066 VentoyFillBackupGptHead(pGPT
, &BackupHead
);
2067 if (!WriteDataToPhyDisk(hDrive
, pGPT
->Head
.EfiBackupLBA
* 512, &BackupHead
, 512))
2069 Log("UEFI write backup head failed");
2073 if (!WriteDataToPhyDisk(hDrive
, (pGPT
->Head
.EfiBackupLBA
- 32) * 512, pGPT
->PartTbl
, 512 * 32))
2075 Log("UEFI write backup partition table failed");
2079 if (!WriteDataToPhyDisk(hDrive
, 0, pGPT
, 512 * 34))
2081 Log("UEFI write MBR & Main partition table failed");
2088 //Refresh Drive Layout
2089 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2091 //We must close handle here, because it will block the refresh bellow
2092 CHECK_CLOSE_HANDLE(hDrive
);
2097 PhyDrive
= pPhyDrive
->PhyDrive
;
2099 Log("#### Now Refresh PhyDrive ####");
2100 Ventoy2DiskDestroy();
2103 pPhyDrive
= GetPhyDriveInfoByPhyDrive(PhyDrive
);
2106 if (pPhyDrive
->VentoyVersion
[0] == 0)
2108 Log("After process the Ventoy version is still invalid");
2112 Log("### Ventoy non-destructive installation successfully finished <%s>", pPhyDrive
->VentoyVersion
);
2116 Log("### Ventoy non-destructive installation successfully finished <not found>");
2119 InitComboxCtrl(g_DialogHwnd
, PhyDrive
);
2124 CHECK_CLOSE_HANDLE(hDrive
);
2129 static BOOL
DiskCheckWriteAccess(HANDLE hDrive
)
2135 LARGE_INTEGER liCurPosition
;
2136 LARGE_INTEGER liNewPosition
;
2138 liCurPosition
.QuadPart
= 2039 * 512;
2139 liNewPosition
.QuadPart
= 0;
2140 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2141 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2143 Log("SetFilePointer1 Failed %u", LASTERR
);
2149 ret
= ReadFile(hDrive
, Buffer
, 512, &dwSize
, NULL
);
2150 if ((!ret
) || (dwSize
!= 512))
2152 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2157 liCurPosition
.QuadPart
= 2039 * 512;
2158 liNewPosition
.QuadPart
= 0;
2159 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2160 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2162 Log("SetFilePointer2 Failed %u", LASTERR
);
2167 ret
= WriteFile(hDrive
, Buffer
, 512, &dwSize
, NULL
);
2168 if ((!ret
) || dwSize
!= 512)
2170 Log("Failed to write %d %u %u", ret
, dwSize
, LASTERR
);
2181 static BOOL
BackupDataBeforeCleanDisk(int PhyDrive
, UINT64 DiskSize
, BYTE
**pBackup
)
2185 BOOL Return
= FALSE
;
2187 BYTE
*backup
= NULL
;
2189 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
2190 LARGE_INTEGER liCurPosition
;
2191 LARGE_INTEGER liNewPosition
;
2192 VTOY_GPT_INFO
*pGPT
= NULL
;
2194 Log("BackupDataBeforeCleanDisk %d", PhyDrive
);
2196 // step1: check write access
2197 hDrive
= GetPhysicalHandle(PhyDrive
, TRUE
, TRUE
, FALSE
);
2198 if (hDrive
== INVALID_HANDLE_VALUE
)
2200 Log("Failed to GetPhysicalHandle for write.");
2204 if (DiskCheckWriteAccess(hDrive
))
2206 Log("DiskCheckWriteAccess success");
2207 CHECK_CLOSE_HANDLE(hDrive
);
2211 Log("DiskCheckWriteAccess failed");
2215 //step2 backup 4MB data
2216 backup
= malloc(SIZE_1MB
* 4);
2222 hDrive
= GetPhysicalHandle(PhyDrive
, FALSE
, FALSE
, FALSE
);
2223 if (hDrive
== INVALID_HANDLE_VALUE
)
2229 dwStatus
= SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2236 ret
= ReadFile(hDrive
, backup
, SIZE_2MB
, &dwSize
, NULL
);
2237 if ((!ret
) || (dwSize
!= SIZE_2MB
))
2239 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2243 pGPT
= (VTOY_GPT_INFO
*)backup
;
2244 offset
= pGPT
->Head
.EfiBackupLBA
* 512;
2245 if (offset
>= (DiskSize
- SIZE_2MB
) && offset
< DiskSize
)
2247 Log("EFI partition table check success");
2251 Log("Backup EFI LBA not in last 2MB range: %llu", pGPT
->Head
.EfiBackupLBA
);
2256 liCurPosition
.QuadPart
= DiskSize
- SIZE_2MB
;
2257 liNewPosition
.QuadPart
= 0;
2258 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2259 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2265 ret
= ReadFile(hDrive
, backup
+ SIZE_2MB
, SIZE_2MB
, &dwSize
, NULL
);
2266 if ((!ret
) || (dwSize
!= SIZE_2MB
))
2268 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2273 backup
= NULL
; //For don't free later
2277 CHECK_CLOSE_HANDLE(hDrive
);
2285 static BOOL
WriteBackupDataToDisk(HANDLE hDrive
, UINT64 Offset
, BYTE
*Data
, DWORD Length
)
2289 LARGE_INTEGER liCurPosition
;
2290 LARGE_INTEGER liNewPosition
;
2292 Log("WriteBackupDataToDisk %llu %p %u", Offset
, Data
, Length
);
2294 liCurPosition
.QuadPart
= Offset
;
2295 liNewPosition
.QuadPart
= 0;
2296 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2297 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2302 ret
= WriteFile(hDrive
, Data
, Length
, &dwSize
, NULL
);
2303 if ((!ret
) || dwSize
!= Length
)
2305 Log("Failed to write %d %u %u", ret
, dwSize
, LASTERR
);
2309 Log("WriteBackupDataToDisk %llu %p %u success", Offset
, Data
, Length
);
2314 int UpdateVentoy2PhyDrive(PHY_DRIVE_INFO
*pPhyDrive
, int TryId
)
2319 BOOL ForceMBR
= FALSE
;
2320 BOOL Esp2Basic
= FALSE
;
2321 BOOL ChangeAttr
= FALSE
;
2322 BOOL CleanDisk
= FALSE
;
2323 BOOL bWriteBack
= TRUE
;
2329 CHAR DriveName
[] = "?:\\";
2330 CHAR DriveLetters
[MAX_PATH
] = { 0 };
2331 CHAR BackBinFile
[MAX_PATH
];
2333 UINT64 ReservedMB
= 0;
2336 BYTE
*pBackup
= NULL
;
2337 VTOY_GPT_INFO
*pGptInfo
= NULL
;
2338 UINT8 ReservedData
[4096];
2340 Log("#####################################################");
2341 Log("UpdateVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId
,
2342 pPhyDrive
->PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
2343 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
2344 Log("#####################################################");
2346 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2348 Log("Lock disk for umount ............................ ");
2350 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
2351 if (hDrive
== INVALID_HANDLE_VALUE
)
2353 Log("Failed to open physical disk");
2357 if (pPhyDrive
->PartStyle
)
2359 pGptInfo
= malloc(sizeof(VTOY_GPT_INFO
));
2365 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
2368 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2369 ReadFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
);
2371 //MBR will be used to compare with local boot image
2372 memcpy(&MBR
, &pGptInfo
->MBR
, sizeof(MBR_HEAD
));
2374 StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
2375 Log("GPT StartSector in PartTbl:%llu", (ULONGLONG
)StartSector
);
2377 ReservedMB
= (pPhyDrive
->SizeInBytes
/ 512 - (StartSector
+ VENTOY_EFI_PART_SIZE
/ 512) - 33) / 2048;
2378 Log("GPT Reserved Disk Space:%llu MB", (ULONGLONG
)ReservedMB
);
2383 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2384 ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
2386 StartSector
= MBR
.PartTbl
[1].StartSectorId
;
2387 Log("MBR StartSector in PartTbl:%llu", (ULONGLONG
)StartSector
);
2389 ReservedMB
= (pPhyDrive
->SizeInBytes
/ 512 - (StartSector
+ VENTOY_EFI_PART_SIZE
/ 512)) / 2048;
2390 Log("MBR Reserved Disk Space:%llu MB", (ULONGLONG
)ReservedMB
);
2393 //Read Reserved Data
2394 SetFilePointer(hDrive
, 512 * 2040, NULL
, FILE_BEGIN
);
2395 ReadFile(hDrive
, ReservedData
, sizeof(ReservedData
), &dwSize
, NULL
);
2397 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
2399 if (DriveLetters
[0] == 0)
2401 Log("No drive letter was assigned...");
2405 // Unmount all mounted volumes that belong to this drive
2406 // Do it in reverse so that we always end on the first volume letter
2407 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
2409 DriveName
[0] = DriveLetters
[i
- 1];
2410 if (IsVentoyLogicalDrive(DriveName
[0]))
2412 Log("%s is ventoy logical drive", DriveName
);
2413 bRet
= DeleteVolumeMountPointA(DriveName
);
2414 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, LASTERR
);
2420 // It kind of blows, but we have to relinquish access to the physical drive
2421 // for VDS to be able to delete the partitions that reside on it...
2422 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2423 CHECK_CLOSE_HANDLE(hDrive
);
2425 if (pPhyDrive
->PartStyle
== 1)
2427 Log("TryId=%d EFI GPT partition type is 0x%llx", TryId
, pPhyDrive
->Part2GPTAttr
);
2428 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
2432 Log("Change GPT partition type to ESP");
2433 if (VDS_ChangeVtoyEFI2ESP(pPhyDrive
->PhyDrive
, StartSector
* 512))
2439 else if (TryId
== 2)
2441 Log("Change GPT partition attribute");
2442 if (VDS_ChangeVtoyEFIAttr(pPhyDrive
->PhyDrive
, 0x8000000000000001))
2448 else if (TryId
== 3)
2450 Log("Clean disk GPT partition table");
2451 if (BackupDataBeforeCleanDisk(pPhyDrive
->PhyDrive
, pPhyDrive
->SizeInBytes
, &pBackup
))
2453 sprintf_s(BackBinFile
, sizeof(BackBinFile
), ".\\ventoy\\phydrive%d_%u_%d.bin",
2454 pPhyDrive
->PhyDrive
, GetCurrentProcessId(), g_backup_bin_index
++);
2455 SaveBufToFile(BackBinFile
, pBackup
, 4 * SIZE_1MB
);
2456 Log("Save backup data to %s", BackBinFile
);
2458 Log("Success to backup data before clean");
2460 if (!VDS_CleanDisk(pPhyDrive
->PhyDrive
))
2463 DSPT_CleanDisk(pPhyDrive
->PhyDrive
);
2469 Log("Failed to backup data before clean");
2474 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
2476 Log("Lock disk for update ............................ ");
2477 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2478 if (hDrive
== INVALID_HANDLE_VALUE
)
2480 Log("Failed to GetPhysicalHandle for write.");
2485 PROGRESS_BAR_SET_POS(PT_LOCK_VOLUME
);
2487 Log("Lock volume for update .......................... ");
2488 hVolume
= INVALID_HANDLE_VALUE
;
2490 //If we change VTOYEFI to ESP, it can not have s volume name, so don't try to get it.
2493 //writeback the last 2MB
2494 if (!WriteBackupDataToDisk(hDrive
, pPhyDrive
->SizeInBytes
- SIZE_2MB
, pBackup
+ SIZE_2MB
, SIZE_2MB
))
2499 //write the first 2MB except parttable
2500 if (!WriteBackupDataToDisk(hDrive
, 34 * 512, pBackup
+ 34 * 512, SIZE_2MB
- 34 * 512))
2505 Status
= ERROR_NOT_FOUND
;
2509 Status
= ERROR_NOT_FOUND
;
2513 for (i
= 0; i
< MaxRetry
; i
++)
2515 Status
= GetVentoyVolumeName(pPhyDrive
->PhyDrive
, StartSector
, DriveLetters
, sizeof(DriveLetters
), TRUE
);
2516 if (ERROR_SUCCESS
== Status
)
2522 Log("==== Volume not found, wait and retry %d... ====", i
);
2528 if (ERROR_SUCCESS
== Status
)
2530 Log("Now lock and dismount volume <%s>", DriveLetters
);
2532 for (i
= 0; i
< MaxRetry
; i
++)
2534 hVolume
= CreateFileA(DriveLetters
,
2535 GENERIC_READ
| GENERIC_WRITE
,
2539 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_NO_BUFFERING
| FILE_FLAG_WRITE_THROUGH
,
2542 if (hVolume
== INVALID_HANDLE_VALUE
)
2544 Log("Failed to create file volume, errcode:%u, wait and retry ...", LASTERR
);
2553 if (hVolume
== INVALID_HANDLE_VALUE
)
2555 Log("Failed to create file volume, errcode:%u", LASTERR
);
2559 bRet
= DeviceIoControl(hVolume
, FSCTL_LOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2560 Log("FSCTL_LOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2562 bRet
= DeviceIoControl(hVolume
, FSCTL_DISMOUNT_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2563 Log("FSCTL_DISMOUNT_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2566 else if (ERROR_NOT_FOUND
== Status
)
2568 Log("Volume not found, maybe not supported");
2576 bRet
= TryWritePart2(hDrive
, StartSector
);
2577 if (FALSE
== bRet
&& Esp2Basic
)
2579 Log("TryWritePart2 agagin ...");
2581 bRet
= TryWritePart2(hDrive
, StartSector
);
2586 if (pPhyDrive
->PartStyle
== 0)
2588 if (DiskCheckWriteAccess(hDrive
))
2590 Log("MBR DiskCheckWriteAccess success");
2594 Log("Try write failed, now delete partition 2 for MBR...");
2595 CHECK_CLOSE_HANDLE(hDrive
);
2597 Log("Now delete partition 2...");
2598 VDS_DeleteVtoyEFIPartition(pPhyDrive
->PhyDrive
);
2600 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2601 if (hDrive
== INVALID_HANDLE_VALUE
)
2603 Log("Failed to GetPhysicalHandle for write.");
2610 Log("MBR DiskCheckWriteAccess failed");
2615 Log("TryWritePart2 failed ....");
2621 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
2623 Log("Write Ventoy to disk ............................ ");
2624 if (0 != FormatPart2Fat(hDrive
, StartSector
))
2630 if (hVolume
!= INVALID_HANDLE_VALUE
)
2632 bRet
= DeviceIoControl(hVolume
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2633 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2634 CHECK_CLOSE_HANDLE(hVolume
);
2637 Log("Updating Boot Image ............................. ");
2638 if (WriteGrubStage1ToPhyDrive(hDrive
, pPhyDrive
->PartStyle
) != 0)
2644 //write reserved data
2645 SetFilePointer(hDrive
, 512 * 2040, NULL
, FILE_BEGIN
);
2646 bRet
= WriteFile(hDrive
, ReservedData
, sizeof(ReservedData
), &dwSize
, NULL
);
2647 Log("Write resv data ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2650 VentoyGetLocalBootImg(&BootImg
);
2653 memcpy(BootImg
.BootCode
+ 0x180, MBR
.BootCode
+ 0x180, 16);
2654 if (pPhyDrive
->PartStyle
)
2656 BootImg
.BootCode
[92] = 0x22;
2659 if (ForceMBR
== FALSE
&& memcmp(BootImg
.BootCode
, MBR
.BootCode
, 440) == 0)
2661 Log("Boot image has no difference, no need to write.");
2665 Log("Boot image need to write %u.", ForceMBR
);
2667 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2669 memcpy(MBR
.BootCode
, BootImg
.BootCode
, 440);
2670 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
2671 Log("Write Boot Image ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2674 if (pPhyDrive
->PartStyle
== 0)
2676 if (0x00 == MBR
.PartTbl
[0].Active
&& 0x80 == MBR
.PartTbl
[1].Active
)
2678 Log("Need to chage 1st partition active and 2nd partition inactive.");
2680 MBR
.PartTbl
[0].Active
= 0x80;
2681 MBR
.PartTbl
[1].Active
= 0x00;
2683 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2684 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
2685 Log("Write NEW MBR ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2691 if (!WriteBackupDataToDisk(hDrive
, 0, pBackup
, 34 * 512))
2700 Log("Write backup data success, now delete %s", BackBinFile
);
2701 DeleteFileA(BackBinFile
);
2705 Log("Write backup data failed");
2711 //Refresh Drive Layout
2712 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2716 if (hVolume
!= INVALID_HANDLE_VALUE
)
2718 bRet
= DeviceIoControl(hVolume
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2719 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2720 CHECK_CLOSE_HANDLE(hVolume
);
2729 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
2732 CHECK_CLOSE_HANDLE(hDrive
);
2736 Log("Recover GPT partition type to basic");
2737 VDS_ChangeVtoyEFI2Basic(pPhyDrive
->PhyDrive
, StartSector
* 512);
2740 if (pPhyDrive
->PartStyle
== 1)
2742 if (ChangeAttr
|| ((pPhyDrive
->Part2GPTAttr
>> 56) != 0xC0))
2744 Log("Change EFI partition attr %u <0x%llx> to <0x%llx>", ChangeAttr
, pPhyDrive
->Part2GPTAttr
, 0xC000000000000001ULL
);
2745 if (VDS_ChangeVtoyEFIAttr(pPhyDrive
->PhyDrive
, 0xC000000000000001ULL
))
2747 Log("Change EFI partition attr success");
2748 pPhyDrive
->Part2GPTAttr
= 0xC000000000000001ULL
;
2752 Log("Change EFI partition attr failed");