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
);
1340 PROGRESS_BAR_SET_POS(PT_REFORMAT_FINISH
);
1349 Log("Mounting Ventoy Partition ....................... ");
1353 memset(DriveLetters
, 0, sizeof(DriveLetters
));
1354 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1355 Log("Logical drive letter after write ventoy: <%s>", DriveLetters
);
1357 for (i
= 0; i
< sizeof(DriveLetters
) && DriveLetters
[i
]; i
++)
1359 DriveName
[0] = DriveLetters
[i
];
1360 Log("%s is ventoy part1, already mounted", DriveName
);
1366 Log("need to mount ventoy part1...");
1367 if (0 == GetVentoyVolumeName(pPhyDrive
->PhyDrive
, 2048, DriveLetters
, sizeof(DriveLetters
), FALSE
))
1369 DriveName
[0] = MountDrive
;
1370 bRet
= SetVolumeMountPointA(DriveName
, DriveLetters
);
1371 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName
, DriveLetters
, bRet
, GetLastError());
1373 *pDrvLetter
= MountDrive
;
1377 Log("Failed to find ventoy volume");
1385 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
1388 CHECK_CLOSE_HANDLE(hDrive
);
1392 int InstallVentoy2FileImage(PHY_DRIVE_INFO
*pPhyDrive
, int PartStyle
)
1401 UINT64 data_offset
= 0;
1402 UINT64 Part2StartSector
= 0;
1403 UINT64 Part1StartSector
= 0;
1404 UINT64 Part1SectorCount
= 0;
1405 UINT8
*pData
= NULL
;
1406 UINT8
*pBkGptPartTbl
= NULL
;
1407 BYTE
*ImgBuf
= NULL
;
1408 MBR_HEAD
*pMBR
= NULL
;
1409 VTSI_FOOTER
*pImgFooter
= NULL
;
1410 VTSI_SEGMENT
*pSegment
= NULL
;
1411 VTOY_GPT_INFO
*pGptInfo
= NULL
;
1412 VTOY_GPT_HDR
*pBkGptHdr
= NULL
;
1415 Log("InstallVentoy2FileImage %s PhyDrive%d <<%s %s %dGB>>",
1416 PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1417 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1419 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1421 size
= SIZE_1MB
+ VENTOY_EFI_PART_SIZE
+ 33 * 512 + VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
) + sizeof(VTSI_FOOTER
);
1423 pData
= (UINT8
*)malloc(size
);
1426 Log("malloc image buffer failed %d.", size
);
1430 pImgFooter
= (VTSI_FOOTER
*)(pData
+ size
- sizeof(VTSI_FOOTER
));
1431 pSegment
= (VTSI_SEGMENT
*)((UINT8
*)pImgFooter
- VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
));
1432 memset(pImgFooter
, 0, sizeof(VTSI_FOOTER
));
1433 memset(pSegment
, 0, VTSI_IMG_MAX_SEG
* sizeof(VTSI_SEGMENT
));
1435 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START
);
1437 Log("Writing Boot Image ............................. ");
1438 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG
, 0, (void **)&ImgBuf
, &Len
))
1440 Log("Failed to read stage1 img");
1444 unxz(ImgBuf
, Len
, NULL
, NULL
, pData
, &dataLen
, unxz_error
);
1447 Log("decompress %s len:%d", VENTOY_FILE_STG1_IMG
, dataLen
);
1451 pData
[500] = 35;//update blocklist
1452 memmove(pData
+ 34 * 512, pData
, SIZE_1MB
- 512 * 34);
1453 memset(pData
, 0, 34 * 512);
1455 pGptInfo
= (VTOY_GPT_INFO
*)pData
;
1456 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
1457 VentoyFillGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1459 pBkGptPartTbl
= pData
+ SIZE_1MB
+ VENTOY_EFI_PART_SIZE
;
1460 memset(pBkGptPartTbl
, 0, 33 * 512);
1462 memcpy(pBkGptPartTbl
, pGptInfo
->PartTbl
, 32 * 512);
1463 pBkGptHdr
= (VTOY_GPT_HDR
*)(pBkGptPartTbl
+ 32 * 512);
1464 VentoyFillBackupGptHead(pGptInfo
, pBkGptHdr
);
1466 Part1StartSector
= pGptInfo
->PartTbl
[0].StartLBA
;
1467 Part1SectorCount
= pGptInfo
->PartTbl
[0].LastLBA
- Part1StartSector
+ 1;
1468 Part2StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
1470 Log("Write GPT Info OK ...");
1474 memmove(pData
+ 512, pData
, SIZE_1MB
- 512);
1475 memset(pData
, 0, 512);
1477 pMBR
= (MBR_HEAD
*)pData
;
1478 VentoyFillMBR(pPhyDrive
->SizeInBytes
, pMBR
, PartStyle
);
1479 Part1StartSector
= pMBR
->PartTbl
[0].StartSectorId
;
1480 Part1SectorCount
= pMBR
->PartTbl
[0].SectorCount
;
1481 Part2StartSector
= pMBR
->PartTbl
[1].StartSectorId
;
1483 Log("Write MBR OK ...");
1486 Log("Writing EFI part Image ............................. ");
1487 rc
= ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG
, 0, (void **)&ImgBuf
, &Len
);
1490 Log("Failed to read img file %p %u", ImgBuf
, Len
);
1494 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START
+ 28);
1495 memset(g_part_img_buf
, 0, sizeof(g_part_img_buf
));
1496 unxz(ImgBuf
, Len
, NULL
, NULL
, pData
+ SIZE_1MB
, &dataLen
, unxz_error
);
1499 Log("decompress finished success");
1500 g_part_img_buf
[0] = pData
+ SIZE_1MB
;
1502 VentoyProcSecureBoot(g_SecureBoot
);
1506 Log("decompress finished failed");
1510 fopen_s(&fp
, "VentoySparseImg.vtsi", "wb+");
1513 Log("Failed to create Ventoy img file");
1517 Log("Writing stage1 data ............................. ");
1519 fwrite(pData
, 1, SIZE_1MB
, fp
);
1521 pSegment
[0].disk_start_sector
= 0;
1522 pSegment
[0].sector_num
= SIZE_1MB
/ 512;
1523 pSegment
[0].data_offset
= data_offset
;
1524 data_offset
+= pSegment
[0].sector_num
* 512;
1526 disk_io_set_param(INVALID_HANDLE_VALUE
, Part1StartSector
+ Part1SectorCount
);// include the 2048 sector gap
1527 disk_io_set_imghook(fp
, pSegment
+ 1, VTSI_IMG_MAX_SEG
- 1, data_offset
);
1529 Log("Formatting part1 exFAT ...");
1530 if (0 != FormatPart1exFAT(pPhyDrive
->SizeInBytes
))
1532 Log("FormatPart1exFAT failed.");
1533 disk_io_reset_imghook(&segnum
, &data_offset
);
1537 disk_io_reset_imghook(&segnum
, &data_offset
);
1540 Log("current segment number:%d dataoff:%ld", segnum
, (long)data_offset
);
1543 Log("Writing part2 data ............................. ");
1544 fwrite(pData
+ SIZE_1MB
, 1, VENTOY_EFI_PART_SIZE
, fp
);
1545 pSegment
[segnum
].disk_start_sector
= Part2StartSector
;
1546 pSegment
[segnum
].sector_num
= VENTOY_EFI_PART_SIZE
/ 512;
1547 pSegment
[segnum
].data_offset
= data_offset
;
1548 data_offset
+= pSegment
[segnum
].sector_num
* 512;
1553 Log("Writing backup gpt table ............................. ");
1554 fwrite(pBkGptPartTbl
, 1, 33 * 512, fp
);
1555 pSegment
[segnum
].disk_start_sector
= pPhyDrive
->SizeInBytes
/ 512 - 33;
1556 pSegment
[segnum
].sector_num
= 33;
1557 pSegment
[segnum
].data_offset
= data_offset
;
1558 data_offset
+= pSegment
[segnum
].sector_num
* 512;
1562 Log("Writing segment metadata ............................. ");
1564 for (i
= 0; i
< (int)segnum
; i
++)
1566 Log("SEG[%d]: PhySector:%llu SectorNum:%llu DataOffset:%llu(sector:%llu)", i
, pSegment
[i
].disk_start_sector
, pSegment
[i
].sector_num
,
1567 pSegment
[i
].data_offset
, pSegment
[i
].data_offset
/ 512);
1570 dataLen
= segnum
* sizeof(VTSI_SEGMENT
);
1571 fwrite(pSegment
, 1, dataLen
, fp
);
1575 //pData + SIZE_1MB - 8192 is a temp data buffer with zero
1576 fwrite(pData
+ SIZE_1MB
- 8192, 1, 512 - (dataLen
% 512), fp
);
1580 pImgFooter
->magic
= VTSI_IMG_MAGIC
;
1581 pImgFooter
->version
= 1;
1582 pImgFooter
->disk_size
= pPhyDrive
->SizeInBytes
;
1583 memcpy(&pImgFooter
->disk_signature
, pPhyDrive
->MBR
.BootCode
+ 0x1b8, 4);
1584 pImgFooter
->segment_num
= segnum
;
1585 pImgFooter
->segment_offset
= data_offset
;
1587 for (i
= 0, chksum
= 0; i
< (int)(segnum
* sizeof(VTSI_SEGMENT
)); i
++)
1589 chksum
+= *((UINT8
*)pSegment
+ i
);
1591 pImgFooter
->segment_chksum
= ~chksum
;
1593 for (i
= 0, chksum
= 0; i
< sizeof(VTSI_FOOTER
); i
++)
1595 chksum
+= *((UINT8
*)pImgFooter
+ i
);
1597 pImgFooter
->foot_chksum
= ~chksum
;
1599 Log("Writing footer segnum(%u) segoffset(%llu) ......................", segnum
, data_offset
);
1600 Log("disk_size=%llu disk_signature=%lx segment_offset=%llu", pImgFooter
->disk_size
, pImgFooter
->disk_signature
, pImgFooter
->segment_offset
);
1602 fwrite(pImgFooter
, 1, sizeof(VTSI_FOOTER
), fp
);
1605 Log("Writing Ventoy image file finished, the file size should be %llu .", data_offset
+ 512 + ((dataLen
+ 511) / 512 * 512));
1611 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1612 PROGRESS_BAR_SET_POS(PT_REFORMAT_FINISH
);
1614 Log("retcode:%d\n", rc
);
1623 int InstallVentoy2PhyDrive(PHY_DRIVE_INFO
*pPhyDrive
, int PartStyle
, int TryId
)
1632 CHAR DriveName
[] = "?:\\";
1633 CHAR DriveLetters
[MAX_PATH
] = { 0 };
1635 VTOY_GPT_INFO
*pGptInfo
= NULL
;
1636 UINT64 Part1StartSector
= 0;
1637 UINT64 Part1SectorCount
= 0;
1638 UINT64 Part2StartSector
= 0;
1640 Log("#####################################################");
1641 Log("InstallVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId
,
1642 PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1643 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1644 Log("#####################################################");
1648 pGptInfo
= malloc(sizeof(VTOY_GPT_INFO
));
1649 memset(pGptInfo
, 0, sizeof(VTOY_GPT_INFO
));
1652 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1656 VentoyFillGpt(pPhyDrive
->SizeInBytes
, pGptInfo
);
1657 Part1StartSector
= pGptInfo
->PartTbl
[0].StartLBA
;
1658 Part1SectorCount
= pGptInfo
->PartTbl
[0].LastLBA
- Part1StartSector
+ 1;
1659 Part2StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
1663 VentoyFillMBR(pPhyDrive
->SizeInBytes
, &MBR
, PartStyle
);
1664 Part1StartSector
= MBR
.PartTbl
[0].StartSectorId
;
1665 Part1SectorCount
= MBR
.PartTbl
[0].SectorCount
;
1666 Part2StartSector
= MBR
.PartTbl
[1].StartSectorId
;
1669 Log("Lock disk for clean ............................. ");
1671 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
1672 if (hDrive
== INVALID_HANDLE_VALUE
)
1674 Log("Failed to open physical disk");
1679 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1681 if (DriveLetters
[0] == 0)
1683 Log("No drive letter was assigned...");
1684 DriveName
[0] = GetFirstUnusedDriveLetter();
1685 Log("GetFirstUnusedDriveLetter %C: ...", DriveName
[0]);
1689 // Unmount all mounted volumes that belong to this drive
1690 // Do it in reverse so that we always end on the first volume letter
1691 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
1693 DriveName
[0] = DriveLetters
[i
- 1];
1694 bRet
= DeleteVolumeMountPointA(DriveName
);
1695 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, GetLastError());
1699 MountDrive
= DriveName
[0];
1700 Log("Will use '%C:' as volume mountpoint", DriveName
[0]);
1702 // It kind of blows, but we have to relinquish access to the physical drive
1703 // for VDS to be able to delete the partitions that reside on it...
1704 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1705 CHECK_CLOSE_HANDLE(hDrive
);
1707 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
1709 if (!VDS_DeleteAllPartitions(pPhyDrive
->PhyDrive
))
1711 Log("Notice: Could not delete partitions: 0x%x, but we continue.", GetLastError());
1714 Log("Deleting all partitions ......................... OK");
1716 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
1718 Log("Lock disk for write ............................. ");
1719 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1720 if (hDrive
== INVALID_HANDLE_VALUE
)
1722 Log("Failed to GetPhysicalHandle for write.");
1727 //Refresh Drive Layout
1728 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1730 disk_io_set_param(hDrive
, Part1StartSector
+ Part1SectorCount
);// include the 2048 sector gap
1732 PROGRESS_BAR_SET_POS(PT_FORMAT_PART1
);
1734 if (PartStyle
== 1 && pPhyDrive
->PartStyle
== 0)
1736 Log("Wait for format part1 ...");
1740 Log("Formatting part1 exFAT ...");
1741 if (0 != FormatPart1exFAT(pPhyDrive
->SizeInBytes
))
1743 Log("FormatPart1exFAT failed.");
1748 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
1749 Log("Writing part2 FAT img ...");
1751 if (0 != FormatPart2Fat(hDrive
, Part2StartSector
))
1753 Log("FormatPart2Fat failed.");
1758 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG
);
1759 Log("Writing Boot Image ............................. ");
1760 if (WriteGrubStage1ToPhyDrive(hDrive
, PartStyle
) != 0)
1762 Log("WriteGrubStage1ToPhyDrive failed.");
1767 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE
);
1768 Log("Writing Partition Table ........................ ");
1769 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
1773 VTOY_GPT_HDR BackupHead
;
1774 LARGE_INTEGER liCurrentPosition
;
1776 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512);
1777 VentoyFillBackupGptHead(pGptInfo
, &BackupHead
);
1778 if (!WriteFile(hDrive
, &BackupHead
, sizeof(VTOY_GPT_HDR
), &dwSize
, NULL
))
1781 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1785 SET_FILE_POS(pPhyDrive
->SizeInBytes
- 512 * 33);
1786 if (!WriteFile(hDrive
, pGptInfo
->PartTbl
, sizeof(pGptInfo
->PartTbl
), &dwSize
, NULL
))
1789 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1794 if (!WriteFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
))
1797 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize
, sizeof(VTOY_GPT_INFO
), GetLastError());
1801 Log("Write GPT Info OK ...");
1802 memcpy(&(pPhyDrive
->MBR
), &(pGptInfo
->MBR
), 512);
1806 if (!WriteFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
))
1809 Log("Write MBR Failed, dwSize:%u ErrCode:%u", dwSize
, GetLastError());
1812 Log("Write MBR OK ...");
1813 memcpy(&(pPhyDrive
->MBR
), &MBR
, 512);
1816 //Refresh Drive Layout
1817 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1821 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME
);
1825 Log("Mounting Ventoy Partition ....................... ");
1829 memset(DriveLetters
, 0, sizeof(DriveLetters
));
1830 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
1831 Log("Logical drive letter after write ventoy: <%s>", DriveLetters
);
1833 for (i
= 0; i
< sizeof(DriveLetters
) && DriveLetters
[i
]; i
++)
1835 DriveName
[0] = DriveLetters
[i
];
1836 if (IsVentoyLogicalDrive(DriveName
[0]))
1838 Log("%s is ventoy part2, delete mountpoint", DriveName
);
1839 DeleteVolumeMountPointA(DriveName
);
1843 Log("%s is ventoy part1, already mounted", DriveName
);
1844 MountDrive
= DriveName
[0];
1851 Log("need to mount ventoy part1...");
1853 if (0 == GetVentoyVolumeName(pPhyDrive
->PhyDrive
, Part1StartSector
, DriveLetters
, sizeof(DriveLetters
), FALSE
))
1855 DriveName
[0] = MountDrive
;
1856 bRet
= SetVolumeMountPointA(DriveName
, DriveLetters
);
1857 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName
, DriveLetters
, bRet
, GetLastError());
1866 Log("Failed to find ventoy volume");
1870 if (GetVentoyFsType() > 0)
1874 Log("Reformat %C:\\ to %s", MountDrive
, GetVentoyFsName());
1875 DISK_FormatVolume(MountDrive
, GetVentoyFsType());
1879 Log("Can not reformat %s to %s", DriveName
, GetVentoyFsName());
1884 Log("No need to reformat ventoy partition");
1891 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1893 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
1895 if (!VDS_IsLastAvaliable())
1897 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
1898 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
1899 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
1900 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
1901 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
1910 CHECK_CLOSE_HANDLE(hDrive
);
1915 int PartitionResizeForVentoy(PHY_DRIVE_INFO
*pPhyDrive
)
1921 INT64 ReservedValue
;
1925 VTOY_GPT_INFO
*pGPT
;
1928 VTOY_GPT_HDR BackupHead
;
1929 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
1930 GUID ZeroGuid
= { 0 };
1931 static GUID WindowsDataPartType
= { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
1932 static GUID EspPartType
= { 0xc12a7328, 0xf81f, 0x11d2, { 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b } };
1933 static GUID BiosGrubPartType
= { 0x21686148, 0x6449, 0x6e6f, { 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46, 0x49 } };
1935 Log("#####################################################");
1936 Log("PartitionResizeForVentoy PhyDrive%d <<%s %s %dGB>>",
1937 pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
1938 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
1939 Log("#####################################################");
1941 pGPT
= &(pPhyDrive
->Gpt
);
1942 pMBR
= &(pPhyDrive
->Gpt
.MBR
);
1943 Log("Disksize:%llu Part2Start:%llu", pPhyDrive
->SizeInBytes
, pPhyDrive
->ResizePart2StartSector
* 512);
1945 if (pMBR
->PartTbl
[0].FsFlag
== 0xEE && memcmp(pGPT
->Head
.Signature
, "EFI PART", 8) == 0)
1954 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
1956 RecudeBytes
= VENTOY_EFI_PART_SIZE
;
1957 ReservedValue
= GetReservedSpaceInMB();
1958 if (ReservedValue
> 0)
1960 Log("Reduce add reserved space %lldMB", (LONGLONG
)ReservedValue
);
1961 RecudeBytes
+= (UINT64
)(ReservedValue
* SIZE_1MB
);
1965 if (pPhyDrive
->ResizeNoShrink
== FALSE
)
1967 Log("Need to shrink the volume");
1968 if (DISK_ShrinkVolume(pPhyDrive
->PhyDrive
, pPhyDrive
->ResizeVolumeGuid
, pPhyDrive
->Part1DriveLetter
, pPhyDrive
->ResizeOldPart1Size
, RecudeBytes
))
1970 Log("Shrink volume success, now check again");
1972 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
1973 if (hDrive
== INVALID_HANDLE_VALUE
)
1975 Log("Failed to GetPhysicalHandle for update.");
1979 //Refresh Drive Layout
1980 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
1982 CHECK_CLOSE_HANDLE(hDrive
);
1985 if (PartResizePreCheck(NULL
) && pPhyDrive
->ResizeNoShrink
)
1987 Log("Recheck after Shrink volume success");
1988 Log("After shrink Disksize:%llu Part2Start:%llu", pPhyDrive
->SizeInBytes
, pPhyDrive
->ResizePart2StartSector
* 512);
1992 Log("Recheck after Shrink volume failed %u", pPhyDrive
->ResizeNoShrink
);
1998 Log("Shrink volume failed");
2004 //Now try write data
2005 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2006 if (hDrive
== INVALID_HANDLE_VALUE
)
2008 Log("Failed to GetPhysicalHandle for update.");
2013 //Write partition 2 data
2014 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
2015 if (0 != FormatPart2Fat(hDrive
, pPhyDrive
->ResizePart2StartSector
))
2017 Log("FormatPart2Fat failed.");
2021 //Write grub stage2 gap
2022 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG
);
2023 Log("Writing Boot Image ............................. ");
2024 if (WriteGrubStage1ToPhyDrive(hDrive
, PartStyle
) != 0)
2026 Log("WriteGrubStage1ToPhyDrive failed.");
2031 //Write partition table
2032 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE
);
2033 Log("Writing partition table ............................. ");
2035 VentoyGetLocalBootImg(&MBR
);
2036 CoCreateGuid(&Guid
);
2037 memcpy(MBR
.BootCode
+ 0x180, &Guid
, 16);
2038 memcpy(pMBR
->BootCode
, MBR
.BootCode
, 440);
2042 for (i
= 1; i
< 4; i
++)
2044 if (pMBR
->PartTbl
[i
].SectorCount
== 0)
2052 Log("Can not find MBR free partition table");
2056 for (j
= i
- 1; j
> 0; j
--)
2058 Log("Move MBR partition table %d --> %d", j
+ 1, j
+ 2);
2059 memcpy(pMBR
->PartTbl
+ (j
+ 1), pMBR
->PartTbl
+ j
, sizeof(PART_TABLE
));
2062 memset(pMBR
->PartTbl
+ 1, 0, sizeof(PART_TABLE
));
2063 VentoyFillMBRLocation(pPhyDrive
->SizeInBytes
, (UINT32
)pPhyDrive
->ResizePart2StartSector
, VENTOY_EFI_PART_SIZE
/ 512, pMBR
->PartTbl
+ 1);
2064 pMBR
->PartTbl
[0].Active
= 0x80; // bootable
2065 pMBR
->PartTbl
[1].Active
= 0x00;
2066 pMBR
->PartTbl
[1].FsFlag
= 0xEF; // EFI System Partition
2068 if (!WriteDataToPhyDisk(hDrive
, 0, pMBR
, 512))
2070 Log("Legacy BIOS write MBR failed");
2076 for (i
= 1; i
< 128; i
++)
2078 if (memcmp(&(pGPT
->PartTbl
[i
].PartGuid
), &ZeroGuid
, sizeof(GUID
)) == 0)
2086 Log("Can not find GPT free partition table");
2090 for (j
= i
- 1; j
> 0; j
--)
2092 Log("Move GPT partition table %d --> %d", j
+ 1, j
+ 2);
2093 memcpy(pGPT
->PartTbl
+ (j
+ 1), pGPT
->PartTbl
+ j
, sizeof(VTOY_GPT_PART_TBL
));
2097 pMBR
->BootCode
[92] = 0x22;
2099 // to fix windows issue
2100 memset(pGPT
->PartTbl
+ 1, 0, sizeof(VTOY_GPT_PART_TBL
));
2101 memcpy(&(pGPT
->PartTbl
[1].PartType
), &WindowsDataPartType
, sizeof(GUID
));
2102 CoCreateGuid(&(pGPT
->PartTbl
[1].PartGuid
));
2104 pGPT
->PartTbl
[1].StartLBA
= pGPT
->PartTbl
[0].LastLBA
+ 1;
2105 pGPT
->PartTbl
[1].LastLBA
= pGPT
->PartTbl
[1].StartLBA
+ VENTOY_EFI_PART_SIZE
/ 512 - 1;
2106 pGPT
->PartTbl
[1].Attr
= 0xC000000000000001ULL
;
2107 memcpy(pGPT
->PartTbl
[1].Name
, L
"VTOYEFI", 7 * 2);
2110 pGPT
->Head
.PartTblCrc
= VentoyCrc32(pGPT
->PartTbl
, sizeof(pGPT
->PartTbl
));
2112 pGPT
->Head
.Crc
= VentoyCrc32(&(pGPT
->Head
), pGPT
->Head
.Length
);
2114 Log("pGPT->Head.EfiStartLBA=%llu", (ULONGLONG
)pGPT
->Head
.EfiStartLBA
);
2115 Log("pGPT->Head.EfiBackupLBA=%llu", (ULONGLONG
)pGPT
->Head
.EfiBackupLBA
);
2117 VentoyFillBackupGptHead(pGPT
, &BackupHead
);
2118 if (!WriteDataToPhyDisk(hDrive
, pGPT
->Head
.EfiBackupLBA
* 512, &BackupHead
, 512))
2120 Log("UEFI write backup head failed");
2124 if (!WriteDataToPhyDisk(hDrive
, (pGPT
->Head
.EfiBackupLBA
- 32) * 512, pGPT
->PartTbl
, 512 * 32))
2126 Log("UEFI write backup partition table failed");
2130 if (!WriteDataToPhyDisk(hDrive
, 0, pGPT
, 512 * 34))
2132 Log("UEFI write MBR & Main partition table failed");
2139 //Refresh Drive Layout
2140 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2142 //We must close handle here, because it will block the refresh bellow
2143 CHECK_CLOSE_HANDLE(hDrive
);
2148 PhyDrive
= pPhyDrive
->PhyDrive
;
2150 Log("#### Now Refresh PhyDrive ####");
2151 Ventoy2DiskDestroy();
2154 pPhyDrive
= GetPhyDriveInfoByPhyDrive(PhyDrive
);
2157 if (pPhyDrive
->VentoyVersion
[0] == 0)
2159 Log("After process the Ventoy version is still invalid");
2163 Log("### Ventoy non-destructive installation successfully finished <%s>", pPhyDrive
->VentoyVersion
);
2167 Log("### Ventoy non-destructive installation successfully finished <not found>");
2170 InitComboxCtrl(g_DialogHwnd
, PhyDrive
);
2175 CHECK_CLOSE_HANDLE(hDrive
);
2180 static BOOL
DiskCheckWriteAccess(HANDLE hDrive
)
2186 LARGE_INTEGER liCurPosition
;
2187 LARGE_INTEGER liNewPosition
;
2189 liCurPosition
.QuadPart
= 2039 * 512;
2190 liNewPosition
.QuadPart
= 0;
2191 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2192 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2194 Log("SetFilePointer1 Failed %u", LASTERR
);
2200 ret
= ReadFile(hDrive
, Buffer
, 512, &dwSize
, NULL
);
2201 if ((!ret
) || (dwSize
!= 512))
2203 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2208 liCurPosition
.QuadPart
= 2039 * 512;
2209 liNewPosition
.QuadPart
= 0;
2210 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2211 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2213 Log("SetFilePointer2 Failed %u", LASTERR
);
2218 ret
= WriteFile(hDrive
, Buffer
, 512, &dwSize
, NULL
);
2219 if ((!ret
) || dwSize
!= 512)
2221 Log("Failed to write %d %u %u", ret
, dwSize
, LASTERR
);
2232 static BOOL
BackupDataBeforeCleanDisk(int PhyDrive
, UINT64 DiskSize
, BYTE
**pBackup
)
2236 BOOL Return
= FALSE
;
2238 BYTE
*backup
= NULL
;
2240 HANDLE hDrive
= INVALID_HANDLE_VALUE
;
2241 LARGE_INTEGER liCurPosition
;
2242 LARGE_INTEGER liNewPosition
;
2243 VTOY_GPT_INFO
*pGPT
= NULL
;
2245 Log("BackupDataBeforeCleanDisk %d", PhyDrive
);
2247 // step1: check write access
2248 hDrive
= GetPhysicalHandle(PhyDrive
, TRUE
, TRUE
, FALSE
);
2249 if (hDrive
== INVALID_HANDLE_VALUE
)
2251 Log("Failed to GetPhysicalHandle for write.");
2255 if (DiskCheckWriteAccess(hDrive
))
2257 Log("DiskCheckWriteAccess success");
2258 CHECK_CLOSE_HANDLE(hDrive
);
2262 Log("DiskCheckWriteAccess failed");
2266 //step2 backup 4MB data
2267 backup
= malloc(SIZE_1MB
* 4);
2273 hDrive
= GetPhysicalHandle(PhyDrive
, FALSE
, FALSE
, FALSE
);
2274 if (hDrive
== INVALID_HANDLE_VALUE
)
2280 dwStatus
= SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2287 ret
= ReadFile(hDrive
, backup
, SIZE_2MB
, &dwSize
, NULL
);
2288 if ((!ret
) || (dwSize
!= SIZE_2MB
))
2290 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2294 pGPT
= (VTOY_GPT_INFO
*)backup
;
2295 offset
= pGPT
->Head
.EfiBackupLBA
* 512;
2296 if (offset
>= (DiskSize
- SIZE_2MB
) && offset
< DiskSize
)
2298 Log("EFI partition table check success");
2302 Log("Backup EFI LBA not in last 2MB range: %llu", pGPT
->Head
.EfiBackupLBA
);
2307 liCurPosition
.QuadPart
= DiskSize
- SIZE_2MB
;
2308 liNewPosition
.QuadPart
= 0;
2309 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2310 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2316 ret
= ReadFile(hDrive
, backup
+ SIZE_2MB
, SIZE_2MB
, &dwSize
, NULL
);
2317 if ((!ret
) || (dwSize
!= SIZE_2MB
))
2319 Log("Failed to read %d %u 0x%x", ret
, dwSize
, LASTERR
);
2324 backup
= NULL
; //For don't free later
2328 CHECK_CLOSE_HANDLE(hDrive
);
2336 static BOOL
WriteBackupDataToDisk(HANDLE hDrive
, UINT64 Offset
, BYTE
*Data
, DWORD Length
)
2340 LARGE_INTEGER liCurPosition
;
2341 LARGE_INTEGER liNewPosition
;
2343 Log("WriteBackupDataToDisk %llu %p %u", Offset
, Data
, Length
);
2345 liCurPosition
.QuadPart
= Offset
;
2346 liNewPosition
.QuadPart
= 0;
2347 if (0 == SetFilePointerEx(hDrive
, liCurPosition
, &liNewPosition
, FILE_BEGIN
) ||
2348 liNewPosition
.QuadPart
!= liCurPosition
.QuadPart
)
2353 ret
= WriteFile(hDrive
, Data
, Length
, &dwSize
, NULL
);
2354 if ((!ret
) || dwSize
!= Length
)
2356 Log("Failed to write %d %u %u", ret
, dwSize
, LASTERR
);
2360 Log("WriteBackupDataToDisk %llu %p %u success", Offset
, Data
, Length
);
2365 int UpdateVentoy2PhyDrive(PHY_DRIVE_INFO
*pPhyDrive
, int TryId
)
2370 BOOL ForceMBR
= FALSE
;
2371 BOOL Esp2Basic
= FALSE
;
2372 BOOL ChangeAttr
= FALSE
;
2373 BOOL CleanDisk
= FALSE
;
2374 BOOL DelEFI
= FALSE
;
2375 BOOL bWriteBack
= TRUE
;
2381 CHAR DriveName
[] = "?:\\";
2382 CHAR DriveLetters
[MAX_PATH
] = { 0 };
2383 CHAR BackBinFile
[MAX_PATH
];
2385 UINT64 ReservedMB
= 0;
2388 BYTE
*pBackup
= NULL
;
2389 VTOY_GPT_INFO
*pGptInfo
= NULL
;
2390 VTOY_GPT_INFO
*pGptBkup
= NULL
;
2391 UINT8 ReservedData
[4096];
2393 Log("#####################################################");
2394 Log("UpdateVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId
,
2395 pPhyDrive
->PartStyle
? "GPT" : "MBR", pPhyDrive
->PhyDrive
, pPhyDrive
->VendorId
, pPhyDrive
->ProductId
,
2396 GetHumanReadableGBSize(pPhyDrive
->SizeInBytes
));
2397 Log("#####################################################");
2399 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2401 Log("Lock disk for umount ............................ ");
2403 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, FALSE
, FALSE
);
2404 if (hDrive
== INVALID_HANDLE_VALUE
)
2406 Log("Failed to open physical disk");
2410 if (pPhyDrive
->PartStyle
)
2412 pGptInfo
= malloc(2 * sizeof(VTOY_GPT_INFO
));
2418 memset(pGptInfo
, 0, 2 * sizeof(VTOY_GPT_INFO
));
2419 pGptBkup
= pGptInfo
+ 1;
2422 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2423 ReadFile(hDrive
, pGptInfo
, sizeof(VTOY_GPT_INFO
), &dwSize
, NULL
);
2424 memcpy(pGptBkup
, pGptInfo
, sizeof(VTOY_GPT_INFO
));
2426 //MBR will be used to compare with local boot image
2427 memcpy(&MBR
, &pGptInfo
->MBR
, sizeof(MBR_HEAD
));
2429 StartSector
= pGptInfo
->PartTbl
[1].StartLBA
;
2430 Log("GPT StartSector in PartTbl:%llu", (ULONGLONG
)StartSector
);
2432 ReservedMB
= (pPhyDrive
->SizeInBytes
/ 512 - (StartSector
+ VENTOY_EFI_PART_SIZE
/ 512) - 33) / 2048;
2433 Log("GPT Reserved Disk Space:%llu MB", (ULONGLONG
)ReservedMB
);
2438 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2439 ReadFile(hDrive
, &MBR
, sizeof(MBR
), &dwSize
, NULL
);
2441 StartSector
= MBR
.PartTbl
[1].StartSectorId
;
2442 Log("MBR StartSector in PartTbl:%llu", (ULONGLONG
)StartSector
);
2444 ReservedMB
= (pPhyDrive
->SizeInBytes
/ 512 - (StartSector
+ VENTOY_EFI_PART_SIZE
/ 512)) / 2048;
2445 Log("MBR Reserved Disk Space:%llu MB", (ULONGLONG
)ReservedMB
);
2448 //Read Reserved Data
2449 SetFilePointer(hDrive
, 512 * 2040, NULL
, FILE_BEGIN
);
2450 ReadFile(hDrive
, ReservedData
, sizeof(ReservedData
), &dwSize
, NULL
);
2452 GetLettersBelongPhyDrive(pPhyDrive
->PhyDrive
, DriveLetters
, sizeof(DriveLetters
));
2454 if (DriveLetters
[0] == 0)
2456 Log("No drive letter was assigned...");
2460 // Unmount all mounted volumes that belong to this drive
2461 // Do it in reverse so that we always end on the first volume letter
2462 for (i
= (int)strlen(DriveLetters
); i
> 0; i
--)
2464 DriveName
[0] = DriveLetters
[i
- 1];
2465 if (IsVentoyLogicalDrive(DriveName
[0]))
2467 Log("%s is ventoy logical drive", DriveName
);
2468 bRet
= DeleteVolumeMountPointA(DriveName
);
2469 Log("Delete mountpoint %s ret:%u code:%u", DriveName
, bRet
, LASTERR
);
2475 // It kind of blows, but we have to relinquish access to the physical drive
2476 // for VDS to be able to delete the partitions that reside on it...
2477 DeviceIoControl(hDrive
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2478 CHECK_CLOSE_HANDLE(hDrive
);
2480 if (pPhyDrive
->PartStyle
== 1)
2482 Log("TryId=%d EFI GPT partition type is 0x%llx", TryId
, pPhyDrive
->Part2GPTAttr
);
2483 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART
);
2487 Log("Change GPT partition type to ESP");
2488 if (DISK_ChangeVtoyEFI2ESP(pPhyDrive
->PhyDrive
, StartSector
* 512ULL))
2494 else if (TryId
== 2)
2496 Log("Change GPT partition attribute");
2497 if (DISK_ChangeVtoyEFIAttr(pPhyDrive
->PhyDrive
, StartSector
* 512ULL, 0x8000000000000001))
2503 else if (TryId
== 3)
2505 DISK_DeleteVtoyEFIPartition(pPhyDrive
->PhyDrive
, StartSector
* 512ULL);
2508 else if (TryId
== 4)
2510 Log("Clean disk GPT partition table");
2511 if (BackupDataBeforeCleanDisk(pPhyDrive
->PhyDrive
, pPhyDrive
->SizeInBytes
, &pBackup
))
2513 sprintf_s(BackBinFile
, sizeof(BackBinFile
), ".\\ventoy\\phydrive%d_%u_%d.bin",
2514 pPhyDrive
->PhyDrive
, GetCurrentProcessId(), g_backup_bin_index
++);
2515 SaveBufToFile(BackBinFile
, pBackup
, 4 * SIZE_1MB
);
2516 Log("Save backup data to %s", BackBinFile
);
2518 Log("Success to backup data before clean");
2520 DISK_CleanDisk(pPhyDrive
->PhyDrive
);
2525 Log("Failed to backup data before clean");
2530 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE
);
2532 Log("Lock disk for update ............................ ");
2533 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2534 if (hDrive
== INVALID_HANDLE_VALUE
)
2536 Log("Failed to GetPhysicalHandle for write.");
2541 PROGRESS_BAR_SET_POS(PT_LOCK_VOLUME
);
2543 Log("Lock volume for update .......................... ");
2544 hVolume
= INVALID_HANDLE_VALUE
;
2546 //If we change VTOYEFI to ESP, it can not have s volume name, so don't try to get it.
2549 //writeback the last 2MB
2550 if (!WriteBackupDataToDisk(hDrive
, pPhyDrive
->SizeInBytes
- SIZE_2MB
, pBackup
+ SIZE_2MB
, SIZE_2MB
))
2555 //write the first 2MB except parttable
2556 if (!WriteBackupDataToDisk(hDrive
, 34 * 512, pBackup
+ 34 * 512, SIZE_2MB
- 34 * 512))
2561 Status
= ERROR_NOT_FOUND
;
2565 Status
= ERROR_NOT_FOUND
;
2569 Status
= ERROR_NOT_FOUND
;
2573 for (i
= 0; i
< MaxRetry
; i
++)
2575 Status
= GetVentoyVolumeName(pPhyDrive
->PhyDrive
, StartSector
, DriveLetters
, sizeof(DriveLetters
), TRUE
);
2576 if (ERROR_SUCCESS
== Status
)
2582 Log("==== Volume not found, wait and retry %d... ====", i
);
2588 if (ERROR_SUCCESS
== Status
)
2590 Log("Now lock and dismount volume <%s>", DriveLetters
);
2592 for (i
= 0; i
< MaxRetry
; i
++)
2594 hVolume
= CreateFileA(DriveLetters
,
2595 GENERIC_READ
| GENERIC_WRITE
,
2599 FILE_ATTRIBUTE_NORMAL
| FILE_FLAG_NO_BUFFERING
| FILE_FLAG_WRITE_THROUGH
,
2602 if (hVolume
== INVALID_HANDLE_VALUE
)
2604 Log("Failed to create file volume, errcode:%u, wait and retry ...", LASTERR
);
2613 if (hVolume
== INVALID_HANDLE_VALUE
)
2615 Log("Failed to create file volume, errcode:%u", LASTERR
);
2619 bRet
= DeviceIoControl(hVolume
, FSCTL_LOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2620 Log("FSCTL_LOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2622 bRet
= DeviceIoControl(hVolume
, FSCTL_DISMOUNT_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2623 Log("FSCTL_DISMOUNT_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2626 else if (ERROR_NOT_FOUND
== Status
)
2628 Log("Volume not found, maybe not supported");
2636 bRet
= TryWritePart2(hDrive
, StartSector
);
2637 if (FALSE
== bRet
&& Esp2Basic
)
2639 Log("TryWritePart2 agagin ...");
2641 bRet
= TryWritePart2(hDrive
, StartSector
);
2646 if (pPhyDrive
->PartStyle
== 0)
2648 if (DiskCheckWriteAccess(hDrive
))
2650 Log("MBR DiskCheckWriteAccess success");
2654 Log("Try write failed, now delete partition 2 for MBR...");
2655 CHECK_CLOSE_HANDLE(hDrive
);
2657 Log("Now delete partition 2...");
2658 DISK_DeleteVtoyEFIPartition(pPhyDrive
->PhyDrive
, StartSector
* 512ULL);
2660 hDrive
= GetPhysicalHandle(pPhyDrive
->PhyDrive
, TRUE
, TRUE
, FALSE
);
2661 if (hDrive
== INVALID_HANDLE_VALUE
)
2663 Log("Failed to GetPhysicalHandle for write.");
2670 Log("MBR DiskCheckWriteAccess failed");
2675 Log("TryWritePart2 failed ....");
2681 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2
);
2683 Log("Write Ventoy to disk ............................ ");
2684 if (0 != FormatPart2Fat(hDrive
, StartSector
))
2690 if (hVolume
!= INVALID_HANDLE_VALUE
)
2692 bRet
= DeviceIoControl(hVolume
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2693 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2694 CHECK_CLOSE_HANDLE(hVolume
);
2697 Log("Updating Boot Image ............................. ");
2698 if (WriteGrubStage1ToPhyDrive(hDrive
, pPhyDrive
->PartStyle
) != 0)
2704 //write reserved data
2705 SetFilePointer(hDrive
, 512 * 2040, NULL
, FILE_BEGIN
);
2706 bRet
= WriteFile(hDrive
, ReservedData
, sizeof(ReservedData
), &dwSize
, NULL
);
2707 Log("Write resv data ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2710 VentoyGetLocalBootImg(&BootImg
);
2713 memcpy(BootImg
.BootCode
+ 0x180, MBR
.BootCode
+ 0x180, 16);
2714 if (pPhyDrive
->PartStyle
)
2716 BootImg
.BootCode
[92] = 0x22;
2719 if (ForceMBR
== FALSE
&& memcmp(BootImg
.BootCode
, MBR
.BootCode
, 440) == 0)
2721 Log("Boot image has no difference, no need to write.");
2725 Log("Boot image need to write %u.", ForceMBR
);
2727 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2729 memcpy(MBR
.BootCode
, BootImg
.BootCode
, 440);
2730 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
2731 Log("Write Boot Image ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2734 if (pPhyDrive
->PartStyle
== 0)
2736 if (0x00 == MBR
.PartTbl
[0].Active
&& 0x80 == MBR
.PartTbl
[1].Active
)
2738 Log("Need to chage 1st partition active and 2nd partition inactive.");
2740 MBR
.PartTbl
[0].Active
= 0x80;
2741 MBR
.PartTbl
[1].Active
= 0x00;
2743 SetFilePointer(hDrive
, 0, NULL
, FILE_BEGIN
);
2744 bRet
= WriteFile(hDrive
, &MBR
, 512, &dwSize
, NULL
);
2745 Log("Write NEW MBR ret:%u dwSize:%u Error:%u", bRet
, dwSize
, LASTERR
);
2751 if (!WriteBackupDataToDisk(hDrive
, 0, pBackup
, 34 * 512))
2760 Log("Write backup data success, now delete %s", BackBinFile
);
2761 DeleteFileA(BackBinFile
);
2765 Log("Write backup data failed");
2772 VTOY_GPT_HDR BackupHdr
;
2774 VentoyFillBackupGptHead(pGptBkup
, &BackupHdr
);
2775 if (!WriteBackupDataToDisk(hDrive
, 512 * pGptBkup
->Head
.EfiBackupLBA
, (BYTE
*)(&BackupHdr
), 512))
2780 if (!WriteBackupDataToDisk(hDrive
, 512 * (pGptBkup
->Head
.EfiBackupLBA
- 32), (BYTE
*)(pGptBkup
->PartTbl
), 32 * 512))
2785 if (!WriteBackupDataToDisk(hDrive
, 512, (BYTE
*)pGptBkup
+ 512, 33 * 512))
2792 Log("Write backup partition table success");
2796 Log("Write backup partition table failed");
2802 //Refresh Drive Layout
2803 DeviceIoControl(hDrive
, IOCTL_DISK_UPDATE_PROPERTIES
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2807 if (hVolume
!= INVALID_HANDLE_VALUE
)
2809 bRet
= DeviceIoControl(hVolume
, FSCTL_UNLOCK_VOLUME
, NULL
, 0, NULL
, 0, &dwSize
, NULL
);
2810 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet
, LASTERR
);
2811 CHECK_CLOSE_HANDLE(hVolume
);
2820 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN
);
2821 FindProcessOccupyDisk(hDrive
, pPhyDrive
);
2824 CHECK_CLOSE_HANDLE(hDrive
);
2828 Log("Recover GPT partition type to basic");
2829 DISK_ChangeVtoyEFI2Basic(pPhyDrive
->PhyDrive
, StartSector
* 512);
2832 if (pPhyDrive
->PartStyle
== 1)
2834 if (ChangeAttr
|| ((pPhyDrive
->Part2GPTAttr
>> 56) != 0xC0))
2836 Log("Change EFI partition attr %u <0x%llx> to <0x%llx>", ChangeAttr
, pPhyDrive
->Part2GPTAttr
, 0xC000000000000001ULL
);
2837 if (DISK_ChangeVtoyEFIAttr(pPhyDrive
->PhyDrive
, StartSector
* 512ULL, 0xC000000000000001ULL
))
2839 Log("Change EFI partition attr success");
2840 pPhyDrive
->Part2GPTAttr
= 0xC000000000000001ULL
;
2844 Log("Change EFI partition attr failed");