]> glassweightruler.freedombox.rocks Git - Ventoy.git/blob - Ventoy2Disk/Ventoy2Disk/PhyDrive.c
11e3d966f7d6f21235bfef01edec7b874a439176
[Ventoy.git] / Ventoy2Disk / Ventoy2Disk / PhyDrive.c
1 /******************************************************************************
2 * PhyDrive.c
3 *
4 * Copyright (c) 2020, longpanda <admin@ventoy.net>
5 * Copyright (c) 2011-2020, Pete Batard <pete@akeo.ie>
6 *
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.
11 *
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.
16 *
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/>.
19 *
20 */
21
22 #include <Windows.h>
23 #include <time.h>
24 #include <winternl.h>
25 #include <commctrl.h>
26 #include <initguid.h>
27 #include "resource.h"
28 #include "Language.h"
29 #include "Ventoy2Disk.h"
30 #include "fat_filelib.h"
31 #include "ff.h"
32 #include "DiskService.h"
33
34 static int g_backup_bin_index = 0;
35
36
37 static BOOL WriteDataToPhyDisk(HANDLE hDrive, UINT64 Offset, VOID *buffer, DWORD len)
38 {
39 BOOL bRet;
40 DWORD dwSize = 0;
41 LARGE_INTEGER liCurPosition;
42 LARGE_INTEGER liNewPosition;
43
44 liCurPosition.QuadPart = (LONGLONG)Offset;
45 liNewPosition.QuadPart = 0;
46 if (0 == SetFilePointerEx(hDrive, liCurPosition, &liNewPosition, FILE_BEGIN) ||
47 liNewPosition.QuadPart != liCurPosition.QuadPart)
48 {
49 Log("SetFilePointerEx Failed %u", LASTERR);
50 return FALSE;
51 }
52
53 bRet = WriteFile(hDrive, buffer, len, &dwSize, NULL);
54 if (bRet == FALSE || dwSize != len)
55 {
56 Log("Write file error %u %u", dwSize, LASTERR);
57 return FALSE;
58 }
59
60 return TRUE;
61 }
62
63
64 static DWORD GetVentoyVolumeName(int PhyDrive, UINT64 StartSectorId, CHAR *NameBuf, UINT32 BufLen, BOOL DelSlash)
65 {
66 size_t len;
67 BOOL bRet;
68 DWORD dwSize;
69 HANDLE hDrive;
70 HANDLE hVolume;
71 UINT64 PartOffset;
72 DWORD Status = ERROR_NOT_FOUND;
73 DISK_EXTENT *pExtents = NULL;
74 CHAR VolumeName[MAX_PATH] = { 0 };
75 VOLUME_DISK_EXTENTS DiskExtents;
76
77 PartOffset = 512ULL * StartSectorId;
78
79 Log("GetVentoyVolumeName PhyDrive %d SectorStart:%llu PartOffset:%llu", PhyDrive, (ULONGLONG)StartSectorId, (ULONGLONG)PartOffset);
80
81 hVolume = FindFirstVolumeA(VolumeName, sizeof(VolumeName));
82 if (hVolume == INVALID_HANDLE_VALUE)
83 {
84 return 1;
85 }
86
87 do {
88
89 len = strlen(VolumeName);
90 Log("Find volume:%s", VolumeName);
91
92 VolumeName[len - 1] = 0;
93
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)
96 {
97 continue;
98 }
99
100 bRet = DeviceIoControl(hDrive,
101 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
102 NULL,
103 0,
104 &DiskExtents,
105 (DWORD)(sizeof(DiskExtents)),
106 (LPDWORD)&dwSize,
107 NULL);
108
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);
111
112 if (bRet && DiskExtents.NumberOfDiskExtents == 1)
113 {
114 pExtents = DiskExtents.Extents;
115
116 Log("This volume DiskNumber:%u offset:%llu", pExtents->DiskNumber, (ULONGLONG)pExtents->StartingOffset.QuadPart);
117 if ((int)pExtents->DiskNumber == PhyDrive && pExtents->StartingOffset.QuadPart == PartOffset)
118 {
119 Log("This volume match");
120
121 if (!DelSlash)
122 {
123 VolumeName[len - 1] = '\\';
124 }
125
126 sprintf_s(NameBuf, BufLen, "%s", VolumeName);
127 Status = ERROR_SUCCESS;
128 CloseHandle(hDrive);
129 break;
130 }
131 }
132
133 CloseHandle(hDrive);
134 } while (FindNextVolumeA(hVolume, VolumeName, sizeof(VolumeName)));
135
136 FindVolumeClose(hVolume);
137
138 Log("GetVentoyVolumeName return %u", Status);
139 return Status;
140 }
141
142 static int GetLettersBelongPhyDrive(int PhyDrive, char *DriveLetters, size_t Length)
143 {
144 int n = 0;
145 DWORD DataSize = 0;
146 CHAR *Pos = NULL;
147 CHAR *StringBuf = NULL;
148
149 DataSize = GetLogicalDriveStringsA(0, NULL);
150 StringBuf = (CHAR *)malloc(DataSize + 1);
151 if (StringBuf == NULL)
152 {
153 return 1;
154 }
155
156 GetLogicalDriveStringsA(DataSize, StringBuf);
157
158 for (Pos = StringBuf; *Pos; Pos += strlen(Pos) + 1)
159 {
160 if (n < (int)Length && PhyDrive == GetPhyDriveByLogicalDrive(Pos[0], NULL))
161 {
162 Log("%C: is belong to phydrive%d", Pos[0], PhyDrive);
163 DriveLetters[n++] = Pos[0];
164 }
165 }
166
167 free(StringBuf);
168 return 0;
169 }
170
171 HANDLE GetPhysicalHandle(int Drive, BOOLEAN bLockDrive, BOOLEAN bWriteAccess, BOOLEAN bWriteShare)
172 {
173 int i;
174 DWORD dwSize;
175 DWORD LastError;
176 UINT64 EndTime;
177 HANDLE hDrive = INVALID_HANDLE_VALUE;
178 CHAR PhyDrive[128];
179 CHAR DevPath[MAX_PATH] = { 0 };
180
181 safe_sprintf(PhyDrive, "\\\\.\\PhysicalDrive%d", Drive);
182
183 if (0 == QueryDosDeviceA(PhyDrive + 4, DevPath, sizeof(DevPath)))
184 {
185 Log("QueryDosDeviceA failed error:%u", GetLastError());
186 strcpy_s(DevPath, sizeof(DevPath), "???");
187 }
188 else
189 {
190 Log("QueryDosDeviceA success %s", DevPath);
191 }
192
193 for (i = 0; i < DRIVE_ACCESS_RETRIES; i++)
194 {
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),
203 NULL,
204 OPEN_EXISTING,
205 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH,
206 NULL);
207
208 LastError = GetLastError();
209 Log("[%d] CreateFileA %s code:%u %p", i, PhyDrive, LastError, hDrive);
210
211 if (hDrive != INVALID_HANDLE_VALUE)
212 {
213 break;
214 }
215
216 if ((LastError != ERROR_SHARING_VIOLATION) && (LastError != ERROR_ACCESS_DENIED))
217 {
218 break;
219 }
220
221 if (i == 0)
222 {
223 Log("Waiting for access on %s [%s]...", PhyDrive, DevPath);
224 }
225 else if (!bWriteShare && (i > DRIVE_ACCESS_RETRIES / 3))
226 {
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...");
229 bWriteShare = TRUE;
230
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;
234
235 }
236 Sleep(DRIVE_ACCESS_TIMEOUT / DRIVE_ACCESS_RETRIES);
237 }
238
239 if (hDrive == INVALID_HANDLE_VALUE)
240 {
241 Log("Could not open %s %u", PhyDrive, LASTERR);
242 goto End;
243 }
244
245 if (bWriteAccess)
246 {
247 Log("Opened %s for %s write access", PhyDrive, bWriteShare ? "shared" : "exclusive");
248 }
249
250 if (bLockDrive)
251 {
252 if (DeviceIoControl(hDrive, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0, &dwSize, NULL))
253 {
254 Log("I/O boundary checks disabled");
255 }
256
257 EndTime = GetTickCount64() + DRIVE_ACCESS_TIMEOUT;
258
259 do {
260 if (DeviceIoControl(hDrive, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL))
261 {
262 Log("FSCTL_LOCK_VOLUME success");
263 goto End;
264 }
265 Sleep(DRIVE_ACCESS_TIMEOUT / DRIVE_ACCESS_RETRIES);
266 } while (GetTickCount64() < EndTime);
267
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);
270
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);
277
278 CHECK_CLOSE_HANDLE(hDrive);
279 }
280
281 End:
282
283 if (hDrive == INVALID_HANDLE_VALUE)
284 {
285 Log("Can get handle of %s, maybe some process control it.", DevPath);
286 }
287
288 return hDrive;
289 }
290
291 int GetPhyDriveByLogicalDrive(int DriveLetter, UINT64 *Offset)
292 {
293 BOOL Ret = FALSE;
294 DWORD dwSize = 0;
295 HANDLE Handle = INVALID_HANDLE_VALUE;
296 VOLUME_DISK_EXTENTS DiskExtents;
297 CHAR PhyPath[128];
298
299 safe_sprintf(PhyPath, "\\\\.\\%C:", (CHAR)DriveLetter);
300
301 Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
302 if (Handle == INVALID_HANDLE_VALUE)
303 {
304 Log("Could not open the disk<%s>, error:%u", PhyPath, LASTERR);
305 return -1;
306 }
307
308 memset(&DiskExtents, 0, sizeof(DiskExtents));
309 Ret = DeviceIoControl(Handle,
310 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
311 NULL,
312 0,
313 &DiskExtents,
314 (DWORD)(sizeof(DiskExtents)),
315 (LPDWORD)&dwSize,
316 NULL);
317
318 if (!Ret || DiskExtents.NumberOfDiskExtents == 0)
319 {
320 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath, LASTERR);
321 CHECK_CLOSE_HANDLE(Handle);
322 return -1;
323 }
324 CHECK_CLOSE_HANDLE(Handle);
325
326 Log("LogicalDrive:%s PhyDrive:%d Num:%d Offset:%llu ExtentLength:%llu",
327 PhyPath,
328 DiskExtents.Extents[0].DiskNumber,
329 DiskExtents.NumberOfDiskExtents,
330 DiskExtents.Extents[0].StartingOffset.QuadPart,
331 DiskExtents.Extents[0].ExtentLength.QuadPart
332 );
333
334 if (Offset)
335 {
336 *Offset = (UINT64)(DiskExtents.Extents[0].StartingOffset.QuadPart);
337 }
338
339 return (int)DiskExtents.Extents[0].DiskNumber;
340 }
341
342 int GetAllPhysicalDriveInfo(PHY_DRIVE_INFO *pDriveList, DWORD *pDriveCount)
343 {
344 int i;
345 int Count;
346 int id;
347 int Letter = 'A';
348 BOOL bRet;
349 DWORD dwBytes;
350 DWORD DriveCount = 0;
351 HANDLE Handle = INVALID_HANDLE_VALUE;
352 CHAR PhyDrive[128];
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];
359
360 Count = GetPhysicalDriveCount();
361
362 for (i = 0; i < Count && i < VENTOY_MAX_PHY_DRIVE; i++)
363 {
364 PhyDriveId[i] = i;
365 }
366
367 dwBytes = GetLogicalDrives();
368 Log("Logical Drives: 0x%x", dwBytes);
369 while (dwBytes)
370 {
371 if (dwBytes & 0x01)
372 {
373 id = GetPhyDriveByLogicalDrive(Letter, NULL);
374 Log("%C --> %d", Letter, id);
375 if (id >= 0)
376 {
377 for (i = 0; i < Count; i++)
378 {
379 if (PhyDriveId[i] == id)
380 {
381 break;
382 }
383 }
384
385 if (i >= Count)
386 {
387 Log("Add phy%d to list", i);
388 PhyDriveId[Count] = id;
389 Count++;
390 }
391 }
392 }
393
394 Letter++;
395 dwBytes >>= 1;
396 }
397
398 for (i = 0; i < Count && DriveCount < VENTOY_MAX_PHY_DRIVE; i++)
399 {
400 CHECK_CLOSE_HANDLE(Handle);
401
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);
405
406 if (Handle == INVALID_HANDLE_VALUE)
407 {
408 continue;
409 }
410
411 bRet = DeviceIoControl(Handle,
412 IOCTL_DISK_GET_LENGTH_INFO, NULL,
413 0,
414 &LengthInfo,
415 sizeof(LengthInfo),
416 &dwBytes,
417 NULL);
418 if (!bRet)
419 {
420 Log("DeviceIoControl IOCTL_DISK_GET_LENGTH_INFO failed error:%u", LASTERR);
421 continue;
422 }
423
424 Log("PHYSICALDRIVE%d size %llu bytes", i, (ULONGLONG)LengthInfo.Length.QuadPart);
425
426 Query.PropertyId = StorageDeviceProperty;
427 Query.QueryType = PropertyStandardQuery;
428
429 bRet = DeviceIoControl(Handle,
430 IOCTL_STORAGE_QUERY_PROPERTY,
431 &Query,
432 sizeof(Query),
433 &DevDescHeader,
434 sizeof(STORAGE_DESCRIPTOR_HEADER),
435 &dwBytes,
436 NULL);
437 if (!bRet)
438 {
439 Log("DeviceIoControl1 error:%u dwBytes:%u", LASTERR, dwBytes);
440 continue;
441 }
442
443 if (DevDescHeader.Size < sizeof(STORAGE_DEVICE_DESCRIPTOR))
444 {
445 Log("Invalid DevDescHeader.Size:%u", DevDescHeader.Size);
446 continue;
447 }
448
449 pDevDesc = (STORAGE_DEVICE_DESCRIPTOR *)malloc(DevDescHeader.Size);
450 if (!pDevDesc)
451 {
452 Log("failed to malloc error:%u len:%u", LASTERR, DevDescHeader.Size);
453 continue;
454 }
455
456 bRet = DeviceIoControl(Handle,
457 IOCTL_STORAGE_QUERY_PROPERTY,
458 &Query,
459 sizeof(Query),
460 pDevDesc,
461 DevDescHeader.Size,
462 &dwBytes,
463 NULL);
464 if (!bRet)
465 {
466 Log("DeviceIoControl2 error:%u dwBytes:%u", LASTERR, dwBytes);
467 free(pDevDesc);
468 continue;
469 }
470
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;
476
477 if (pDevDesc->VendorIdOffset)
478 {
479 safe_strcpy(CurDrive->VendorId, (char *)pDevDesc + pDevDesc->VendorIdOffset);
480 TrimString(CurDrive->VendorId);
481 }
482
483 if (pDevDesc->ProductIdOffset)
484 {
485 safe_strcpy(CurDrive->ProductId, (char *)pDevDesc + pDevDesc->ProductIdOffset);
486 TrimString(CurDrive->ProductId);
487 }
488
489 if (pDevDesc->ProductRevisionOffset)
490 {
491 safe_strcpy(CurDrive->ProductRev, (char *)pDevDesc + pDevDesc->ProductRevisionOffset);
492 TrimString(CurDrive->ProductRev);
493 }
494
495 if (pDevDesc->SerialNumberOffset)
496 {
497 safe_strcpy(CurDrive->SerialNumber, (char *)pDevDesc + pDevDesc->SerialNumberOffset);
498 TrimString(CurDrive->SerialNumber);
499 }
500
501 CurDrive++;
502 DriveCount++;
503
504 free(pDevDesc);
505
506 CHECK_CLOSE_HANDLE(Handle);
507 }
508
509 for (i = 0, CurDrive = pDriveList; i < (int)DriveCount; i++, CurDrive++)
510 {
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);
515 }
516
517 *pDriveCount = DriveCount;
518
519 return 0;
520 }
521
522
523 static HANDLE g_FatPhyDrive;
524 static UINT64 g_Part2StartSec;
525 static int GetVentoyVersionFromFatFile(CHAR *VerBuf, size_t BufLen)
526 {
527 int rc = 1;
528 int size = 0;
529 char *buf = NULL;
530 void *flfile = NULL;
531
532 flfile = fl_fopen("/grub/grub.cfg", "rb");
533 if (flfile)
534 {
535 fl_fseek(flfile, 0, SEEK_END);
536 size = (int)fl_ftell(flfile);
537
538 fl_fseek(flfile, 0, SEEK_SET);
539
540 buf = (char *)malloc(size + 1);
541 if (buf)
542 {
543 fl_fread(buf, 1, size, flfile);
544 buf[size] = 0;
545
546 rc = 0;
547 sprintf_s(VerBuf, BufLen, "%s", ParseVentoyVersionFromString(buf));
548 free(buf);
549 }
550
551 fl_fclose(flfile);
552 }
553
554 return rc;
555 }
556
557 static int VentoyFatDiskRead(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
558 {
559 DWORD dwSize;
560 BOOL bRet;
561 DWORD ReadSize;
562 LARGE_INTEGER liCurrentPosition;
563
564 liCurrentPosition.QuadPart = Sector + g_Part2StartSec;
565 liCurrentPosition.QuadPart *= 512;
566 SetFilePointerEx(g_FatPhyDrive, liCurrentPosition, &liCurrentPosition, FILE_BEGIN);
567
568 ReadSize = (DWORD)(SectorCount * 512);
569
570 bRet = ReadFile(g_FatPhyDrive, Buffer, ReadSize, &dwSize, NULL);
571 if (bRet == FALSE || dwSize != ReadSize)
572 {
573 Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u\n", bRet, ReadSize, dwSize, LASTERR);
574 }
575
576 return 1;
577 }
578
579
580 int GetVentoyVerInPhyDrive(const PHY_DRIVE_INFO *pDriveInfo, UINT64 Part2StartSector, CHAR *VerBuf, size_t BufLen, BOOL *pSecureBoot)
581 {
582 int rc = 0;
583 HANDLE hDrive;
584 void *flfile;
585
586 hDrive = GetPhysicalHandle(pDriveInfo->PhyDrive, FALSE, FALSE, FALSE);
587 if (hDrive == INVALID_HANDLE_VALUE)
588 {
589 return 1;
590 }
591
592 g_FatPhyDrive = hDrive;
593 g_Part2StartSec = Part2StartSector;
594
595 Log("Parse FAT fs...");
596
597 fl_init();
598
599 if (0 == fl_attach_media(VentoyFatDiskRead, NULL))
600 {
601 Log("attach media success...");
602 rc = GetVentoyVersionFromFatFile(VerBuf, BufLen);
603 }
604 else
605 {
606 Log("attach media failed...");
607 rc = 1;
608 }
609
610 Log("GetVentoyVerInPhyDrive rc=%d...", rc);
611 if (rc == 0)
612 {
613 Log("VentoyVerInPhyDrive %d is <%s>...", pDriveInfo->PhyDrive, VerBuf);
614
615 flfile = fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
616 if (flfile)
617 {
618 *pSecureBoot = TRUE;
619 fl_fclose(flfile);
620 }
621 }
622
623 fl_shutdown();
624
625 CHECK_CLOSE_HANDLE(hDrive);
626
627 return rc;
628 }
629
630
631
632
633
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];
637
638
639 static int VentoyFatMemRead(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
640 {
641 uint32 i;
642 uint32 offset;
643 BYTE *MbBuf = NULL;
644
645 for (i = 0; i < SectorCount; i++)
646 {
647 offset = (Sector + i) * 512;
648
649 if (g_part_img_buf[1] == NULL)
650 {
651 MbBuf = g_part_img_buf[0] + offset;
652 memcpy(Buffer + i * 512, MbBuf, 512);
653 }
654 else
655 {
656 MbBuf = g_part_img_buf[offset / SIZE_1MB];
657 memcpy(Buffer + i * 512, MbBuf + (offset % SIZE_1MB), 512);
658 }
659 }
660
661 return 1;
662 }
663
664
665 static int VentoyFatMemWrite(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
666 {
667 uint32 i;
668 uint32 offset;
669 BYTE *MbBuf = NULL;
670
671 for (i = 0; i < SectorCount; i++)
672 {
673 offset = (Sector + i) * 512;
674
675 if (g_part_img_buf[1] == NULL)
676 {
677 MbBuf = g_part_img_buf[0] + offset;
678 memcpy(MbBuf, Buffer + i * 512, 512);
679 }
680 else
681 {
682 MbBuf = g_part_img_buf[offset / SIZE_1MB];
683 memcpy(MbBuf + (offset % SIZE_1MB), Buffer + i * 512, 512);
684 }
685 }
686
687 return 1;
688 }
689
690 int VentoyProcSecureBoot(BOOL SecureBoot)
691 {
692 int rc = 0;
693 int size;
694 char *filebuf = NULL;
695 void *file = NULL;
696
697 Log("VentoyProcSecureBoot %d ...", SecureBoot);
698
699 if (SecureBoot)
700 {
701 Log("Secure boot is enabled ...");
702 return 0;
703 }
704
705 fl_init();
706
707 if (0 == fl_attach_media(VentoyFatMemRead, VentoyFatMemWrite))
708 {
709 file = fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
710 Log("Open ventoy efi file %p ", file);
711 if (file)
712 {
713 fl_fseek(file, 0, SEEK_END);
714 size = (int)fl_ftell(file);
715 fl_fseek(file, 0, SEEK_SET);
716
717 Log("ventoy efi file size %d ...", size);
718
719 filebuf = (char *)malloc(size);
720 if (filebuf)
721 {
722 fl_fread(filebuf, 1, size, file);
723 }
724
725 fl_fclose(file);
726
727 Log("Now delete all efi files ...");
728 fl_remove("/EFI/BOOT/BOOTX64.EFI");
729 fl_remove("/EFI/BOOT/grubx64.efi");
730 fl_remove("/EFI/BOOT/grubx64_real.efi");
731 fl_remove("/EFI/BOOT/MokManager.efi");
732 fl_remove("/EFI/BOOT/mmx64.efi");
733 fl_remove("/ENROLL_THIS_KEY_IN_MOKMANAGER.cer");
734 fl_remove("/EFI/BOOT/grub.efi");
735
736 file = fl_fopen("/EFI/BOOT/BOOTX64.EFI", "wb");
737 Log("Open bootx64 efi file %p ", file);
738 if (file)
739 {
740 if (filebuf)
741 {
742 fl_fwrite(filebuf, 1, size, file);
743 }
744
745 fl_fflush(file);
746 fl_fclose(file);
747 }
748
749 if (filebuf)
750 {
751 free(filebuf);
752 }
753 }
754
755 file = fl_fopen("/EFI/BOOT/grubia32_real.efi", "rb");
756 Log("Open ventoy efi file %p ", file);
757 if (file)
758 {
759 fl_fseek(file, 0, SEEK_END);
760 size = (int)fl_ftell(file);
761 fl_fseek(file, 0, SEEK_SET);
762
763 Log("ventoy efi file size %d ...", size);
764
765 filebuf = (char *)malloc(size);
766 if (filebuf)
767 {
768 fl_fread(filebuf, 1, size, file);
769 }
770
771 fl_fclose(file);
772
773 Log("Now delete all efi files ...");
774 fl_remove("/EFI/BOOT/BOOTIA32.EFI");
775 fl_remove("/EFI/BOOT/grubia32.efi");
776 fl_remove("/EFI/BOOT/grubia32_real.efi");
777 fl_remove("/EFI/BOOT/mmia32.efi");
778
779 file = fl_fopen("/EFI/BOOT/BOOTIA32.EFI", "wb");
780 Log("Open bootia32 efi file %p ", file);
781 if (file)
782 {
783 if (filebuf)
784 {
785 fl_fwrite(filebuf, 1, size, file);
786 }
787
788 fl_fflush(file);
789 fl_fclose(file);
790 }
791
792 if (filebuf)
793 {
794 free(filebuf);
795 }
796 }
797
798 }
799 else
800 {
801 rc = 1;
802 }
803
804 fl_shutdown();
805
806 return rc;
807 }
808
809
810
811 static int disk_xz_flush(void *src, unsigned int size)
812 {
813 unsigned int i;
814 BYTE *buf = (BYTE *)src;
815
816 for (i = 0; i < size; i++)
817 {
818 *g_part_img_pos = *buf++;
819
820 g_disk_unxz_len++;
821 if ((g_disk_unxz_len % SIZE_1MB) == 0)
822 {
823 g_part_img_pos = g_part_img_buf[g_disk_unxz_len / SIZE_1MB];
824 }
825 else
826 {
827 g_part_img_pos++;
828 }
829 }
830
831 return (int)size;
832 }
833
834 static void unxz_error(char *x)
835 {
836 Log("%s", x);
837 }
838
839 static BOOL TryWritePart2(HANDLE hDrive, UINT64 StartSectorId)
840 {
841 BOOL bRet;
842 DWORD TrySize = 16 * 1024;
843 DWORD dwSize;
844 BYTE *Buffer = NULL;
845 unsigned char *data = NULL;
846 LARGE_INTEGER liCurrentPosition;
847
848 liCurrentPosition.QuadPart = StartSectorId * 512;
849 SetFilePointerEx(hDrive, liCurrentPosition, &liCurrentPosition, FILE_BEGIN);
850
851 Buffer = malloc(TrySize);
852
853 bRet = WriteFile(hDrive, Buffer, TrySize, &dwSize, NULL);
854
855 free(Buffer);
856
857 Log("Try write part2 bRet:%u dwSize:%u code:%u", bRet, dwSize, LASTERR);
858
859 if (bRet && dwSize == TrySize)
860 {
861 return TRUE;
862 }
863
864 return FALSE;
865 }
866
867 static int FormatPart2Fat(HANDLE hDrive, UINT64 StartSectorId)
868 {
869 int i;
870 int rc = 0;
871 int len = 0;
872 int writelen = 0;
873 int partwrite = 0;
874 int Pos = PT_WRITE_VENTOY_START;
875 DWORD dwSize = 0;
876 BOOL bRet;
877 unsigned char *data = NULL;
878 LARGE_INTEGER liCurrentPosition;
879 LARGE_INTEGER liNewPosition;
880 BYTE *CheckBuf = NULL;
881
882 Log("FormatPart2Fat %llu...", (ULONGLONG)StartSectorId);
883
884 CheckBuf = malloc(SIZE_1MB);
885 if (!CheckBuf)
886 {
887 Log("Failed to malloc check buf");
888 return 1;
889 }
890
891 rc = ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG, 0, (void **)&data, &len);
892 if (rc)
893 {
894 Log("Failed to read img file %p %u", data, len);
895 free(CheckBuf);
896 return 1;
897 }
898
899 liCurrentPosition.QuadPart = StartSectorId * 512;
900 SetFilePointerEx(hDrive, liCurrentPosition, &liNewPosition, FILE_BEGIN);
901
902 memset(g_part_img_buf, 0, sizeof(g_part_img_buf));
903
904 g_part_img_buf[0] = (BYTE *)malloc(VENTOY_EFI_PART_SIZE);
905 if (g_part_img_buf[0])
906 {
907 Log("Malloc whole img buffer success, now decompress ...");
908 unxz(data, len, NULL, NULL, g_part_img_buf[0], &writelen, unxz_error);
909
910 if (len == writelen)
911 {
912 Log("decompress finished success");
913
914 VentoyProcSecureBoot(g_SecureBoot);
915
916 for (i = 0; i < VENTOY_EFI_PART_SIZE / SIZE_1MB; i++)
917 {
918 dwSize = 0;
919 bRet = WriteFile(hDrive, g_part_img_buf[0] + i * SIZE_1MB, SIZE_1MB, &dwSize, NULL);
920 Log("Write part data bRet:%u dwSize:%u code:%u", bRet, dwSize, LASTERR);
921
922 if (!bRet)
923 {
924 rc = 1;
925 goto End;
926 }
927
928 PROGRESS_BAR_SET_POS(Pos);
929 if (i % 2 == 0)
930 {
931 Pos++;
932 }
933 }
934
935 //Read and check the data
936 liCurrentPosition.QuadPart = StartSectorId * 512;
937 SetFilePointerEx(hDrive, liCurrentPosition, &liNewPosition, FILE_BEGIN);
938
939 for (i = 0; i < VENTOY_EFI_PART_SIZE / SIZE_1MB; i++)
940 {
941 bRet = ReadFile(hDrive, CheckBuf, SIZE_1MB, &dwSize, NULL);
942 Log("Read part data bRet:%u dwSize:%u code:%u", bRet, dwSize, LASTERR);
943
944 if (!bRet || memcmp(CheckBuf, g_part_img_buf[0] + i * SIZE_1MB, SIZE_1MB))
945 {
946 Log("### [Check Fail] The data write and read does not match");
947 rc = 1;
948 goto End;
949 }
950
951 PROGRESS_BAR_SET_POS(Pos);
952 if (i % 2 == 0)
953 {
954 Pos++;
955 }
956 }
957 }
958 else
959 {
960 rc = 1;
961 Log("decompress finished failed");
962 goto End;
963 }
964 }
965 else
966 {
967 Log("Failed to malloc whole img size %u, now split it", VENTOY_EFI_PART_SIZE);
968
969 partwrite = 1;
970 for (i = 0; i < VENTOY_EFI_PART_SIZE / SIZE_1MB; i++)
971 {
972 g_part_img_buf[i] = (BYTE *)malloc(SIZE_1MB);
973 if (g_part_img_buf[i] == NULL)
974 {
975 rc = 1;
976 goto End;
977 }
978 }
979
980 Log("Malloc part img buffer success, now decompress ...");
981
982 g_part_img_pos = g_part_img_buf[0];
983
984 unxz(data, len, NULL, disk_xz_flush, NULL, NULL, unxz_error);
985
986 if (g_disk_unxz_len == VENTOY_EFI_PART_SIZE)
987 {
988 Log("decompress finished success");
989
990 VentoyProcSecureBoot(g_SecureBoot);
991
992 for (i = 0; i < VENTOY_EFI_PART_SIZE / SIZE_1MB; i++)
993 {
994 dwSize = 0;
995 bRet = WriteFile(hDrive, g_part_img_buf[i], SIZE_1MB, &dwSize, NULL);
996 Log("Write part data bRet:%u dwSize:%u code:%u", bRet, dwSize, LASTERR);
997
998 if (!bRet)
999 {
1000 rc = 1;
1001 goto End;
1002 }
1003
1004 PROGRESS_BAR_SET_POS(Pos);
1005 if (i % 2 == 0)
1006 {
1007 Pos++;
1008 }
1009 }
1010
1011 //Read and check the data
1012 liCurrentPosition.QuadPart = StartSectorId * 512;
1013 SetFilePointerEx(hDrive, liCurrentPosition, &liNewPosition, FILE_BEGIN);
1014
1015 for (i = 0; i < VENTOY_EFI_PART_SIZE / SIZE_1MB; i++)
1016 {
1017 bRet = ReadFile(hDrive, CheckBuf, SIZE_1MB, &dwSize, NULL);
1018 Log("Read part data bRet:%u dwSize:%u code:%u", bRet, dwSize, LASTERR);
1019
1020 if (!bRet || memcmp(CheckBuf, g_part_img_buf[i], SIZE_1MB))
1021 {
1022 Log("### [Check Fail] The data write and read does not match");
1023 rc = 1;
1024 goto End;
1025 }
1026
1027 PROGRESS_BAR_SET_POS(Pos);
1028 if (i % 2 == 0)
1029 {
1030 Pos++;
1031 }
1032 }
1033 }
1034 else
1035 {
1036 rc = 1;
1037 Log("decompress finished failed");
1038 goto End;
1039 }
1040 }
1041
1042 End:
1043
1044 if (data) free(data);
1045 if (CheckBuf)free(CheckBuf);
1046
1047 if (partwrite)
1048 {
1049 for (i = 0; i < VENTOY_EFI_PART_SIZE / SIZE_1MB; i++)
1050 {
1051 if (g_part_img_buf[i]) free(g_part_img_buf[i]);
1052 }
1053 }
1054 else
1055 {
1056 if (g_part_img_buf[0]) free(g_part_img_buf[0]);
1057 }
1058
1059 return rc;
1060 }
1061
1062 static int WriteGrubStage1ToPhyDrive(HANDLE hDrive, int PartStyle)
1063 {
1064 int Len = 0;
1065 int readLen = 0;
1066 BOOL bRet;
1067 DWORD dwSize;
1068 BYTE *ImgBuf = NULL;
1069 BYTE *RawBuf = NULL;
1070
1071 Log("WriteGrubStage1ToPhyDrive ...");
1072
1073 RawBuf = (BYTE *)malloc(SIZE_1MB);
1074 if (!RawBuf)
1075 {
1076 return 1;
1077 }
1078
1079 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG, 0, (void **)&ImgBuf, &Len))
1080 {
1081 Log("Failed to read stage1 img");
1082 free(RawBuf);
1083 return 1;
1084 }
1085
1086 unxz(ImgBuf, Len, NULL, NULL, RawBuf, &readLen, unxz_error);
1087
1088 if (PartStyle)
1089 {
1090 Log("Write GPT stage1 ...");
1091 RawBuf[500] = 35;//update blocklist
1092 SetFilePointer(hDrive, 512 * 34, NULL, FILE_BEGIN);
1093 bRet = WriteFile(hDrive, RawBuf, SIZE_1MB - 512 * 34, &dwSize, NULL);
1094 }
1095 else
1096 {
1097 Log("Write MBR stage1 ...");
1098 SetFilePointer(hDrive, 512, NULL, FILE_BEGIN);
1099 bRet = WriteFile(hDrive, RawBuf, SIZE_1MB - 512, &dwSize, NULL);
1100 }
1101
1102 Log("WriteFile Ret:%u dwSize:%u ErrCode:%u", bRet, dwSize, GetLastError());
1103
1104 free(RawBuf);
1105 free(ImgBuf);
1106 return 0;
1107 }
1108
1109
1110 static int FormatPart1LargeFAT32(UINT64 DiskSizeBytes, int CluserSize)
1111 {
1112 MKFS_PARM Option;
1113 FRESULT Ret;
1114 FATFS FS;
1115
1116 Option.fmt = FM_FAT32;
1117 Option.n_fat = 1;
1118 Option.align = 8;
1119 Option.n_root = 1;
1120
1121 if (CluserSize == 0)
1122 {
1123 // < 32GB select 32KB as cluster size
1124 // > 32GB select 128KB as cluster size
1125 if (DiskSizeBytes / 1024 / 1024 / 1024 <= 32)
1126 {
1127 Option.au_size = 32768;
1128 }
1129 else
1130 {
1131 Option.au_size = 131072;
1132 }
1133 }
1134 else
1135 {
1136 Option.au_size = CluserSize;
1137 }
1138
1139 Log("Formatting Part1 large FAT32 ClusterSize:%u(%uKB) ...", CluserSize, CluserSize / 1024);
1140
1141 disk_io_reset_write_error();
1142
1143 Ret = f_mkfs(TEXT("0:"), &Option, 0, 8 * 1024 * 1024);
1144 if (FR_OK == Ret)
1145 {
1146 if (disk_io_is_write_error())
1147 {
1148 Log("Formatting Part1 large FAT32 failed, write error.");
1149 return 1;
1150 }
1151
1152 Log("Formatting Part1 large FAT32 success, now set label");
1153
1154 Ret = f_mount(&FS, TEXT("0:"), 1);
1155 if (FR_OK == Ret)
1156 {
1157 Log("f_mount SUCCESS");
1158 Ret = f_setlabel(TEXT("0:Ventoy"));
1159 if (FR_OK == Ret)
1160 {
1161 Log("f_setlabel SUCCESS");
1162 Ret = f_unmount(TEXT("0:"));
1163 Log("f_unmount %d %s", Ret, (FR_OK == Ret) ? "SUCCESS" : "FAILED");
1164 }
1165 else
1166 {
1167 Log("f_setlabel failed %d", Ret);
1168 }
1169 }
1170 else
1171 {
1172 Log("f_mount failed %d", Ret);
1173 }
1174
1175 return 0;
1176 }
1177 else
1178 {
1179 Log("Formatting Part1 large FAT32 failed");
1180 return 1;
1181 }
1182 }
1183
1184 static int FormatPart1exFAT(UINT64 DiskSizeBytes)
1185 {
1186 MKFS_PARM Option;
1187 FRESULT Ret;
1188
1189 Option.fmt = FM_EXFAT;
1190 Option.n_fat = 1;
1191 Option.align = 8;
1192 Option.n_root = 1;
1193
1194 // < 32GB select 32KB as cluster size
1195 // > 32GB select 128KB as cluster size
1196 if (DiskSizeBytes / 1024 / 1024 / 1024 <= 32)
1197 {
1198 Option.au_size = 32768;
1199 }
1200 else
1201 {
1202 Option.au_size = 131072;
1203 }
1204
1205 Log("Formatting Part1 exFAT ...");
1206
1207 disk_io_reset_write_error();
1208
1209 Ret = f_mkfs(TEXT("0:"), &Option, 0, 8 * 1024 * 1024);
1210 if (FR_OK == Ret)
1211 {
1212 if (disk_io_is_write_error())
1213 {
1214 Log("Formatting Part1 exFAT failed, write error.");
1215 return 1;
1216 }
1217
1218 Log("Formatting Part1 exFAT success");
1219 return 0;
1220 }
1221 else
1222 {
1223 Log("Formatting Part1 exFAT failed");
1224 return 1;
1225 }
1226 }
1227
1228 static int ZeroPart1FileSystem(HANDLE hDrive, UINT64 Part2StartSector)
1229 {
1230 int i;
1231 DWORD dwSize = 0;
1232 LARGE_INTEGER liCurPos;
1233 LARGE_INTEGER liNewPos;
1234 CHAR TmpBuffer[1024] = { 0 };
1235
1236 liCurPos.QuadPart = VENTOY_PART1_START_SECTOR * 512;
1237 liNewPos.QuadPart = 0;
1238 if (0 == SetFilePointerEx(hDrive, liCurPos, &liNewPos, FILE_BEGIN) ||
1239 liNewPos.QuadPart != liCurPos.QuadPart)
1240 {
1241 Log("SetFilePointerEx Failed %u %llu %llu", LASTERR, (ULONGLONG)liCurPos.QuadPart, (ULONGLONG)liNewPos.QuadPart);
1242 return 1;
1243 }
1244
1245 for (i = 0; i < 1024; i++)
1246 {
1247 WriteFile(hDrive, TmpBuffer, 1024, &dwSize, NULL);
1248 }
1249
1250 liCurPos.QuadPart = (Part2StartSector * 512) - (1024 * 1024);
1251 liNewPos.QuadPart = 0;
1252 if (0 == SetFilePointerEx(hDrive, liCurPos, &liNewPos, FILE_BEGIN) ||
1253 liNewPos.QuadPart != liCurPos.QuadPart)
1254 {
1255 Log("SetFilePointerEx Failed %u %llu %llu", LASTERR, (ULONGLONG)liCurPos.QuadPart, (ULONGLONG)liNewPos.QuadPart);
1256 return 1;
1257 }
1258
1259 for (i = 0; i < 1024; i++)
1260 {
1261 WriteFile(hDrive, TmpBuffer, 1024, &dwSize, NULL);
1262 }
1263
1264 Log("Zero Part1 SUCCESS");
1265 return 0;
1266 }
1267
1268 int ClearVentoyFromPhyDrive(HWND hWnd, PHY_DRIVE_INFO *pPhyDrive, char *pDrvLetter)
1269 {
1270 int i;
1271 int rc = 0;
1272 int state = 0;
1273 HANDLE hDrive;
1274 DWORD dwSize;
1275 BOOL bRet;
1276 CHAR MountDrive;
1277 CHAR DriveName[] = "?:\\";
1278 CHAR DriveLetters[MAX_PATH] = { 0 };
1279 LARGE_INTEGER liCurrentPosition;
1280 char *pTmpBuf = NULL;
1281 MBR_HEAD MBR;
1282
1283 *pDrvLetter = 0;
1284
1285 Log("ClearVentoyFromPhyDrive PhyDrive%d <<%s %s %dGB>>",
1286 pPhyDrive->PhyDrive, pPhyDrive->VendorId, pPhyDrive->ProductId,
1287 GetHumanReadableGBSize(pPhyDrive->SizeInBytes));
1288
1289 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN);
1290
1291 Log("Lock disk for clean ............................. ");
1292
1293 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, FALSE, FALSE);
1294 if (hDrive == INVALID_HANDLE_VALUE)
1295 {
1296 Log("Failed to open physical disk");
1297 return 1;
1298 }
1299
1300 GetLettersBelongPhyDrive(pPhyDrive->PhyDrive, DriveLetters, sizeof(DriveLetters));
1301
1302 if (DriveLetters[0] == 0)
1303 {
1304 Log("No drive letter was assigned...");
1305 DriveName[0] = GetFirstUnusedDriveLetter();
1306 Log("GetFirstUnusedDriveLetter %C: ...", DriveName[0]);
1307 }
1308 else
1309 {
1310 // Unmount all mounted volumes that belong to this drive
1311 // Do it in reverse so that we always end on the first volume letter
1312 for (i = (int)strlen(DriveLetters); i > 0; i--)
1313 {
1314 DriveName[0] = DriveLetters[i - 1];
1315 bRet = DeleteVolumeMountPointA(DriveName);
1316 Log("Delete mountpoint %s ret:%u code:%u", DriveName, bRet, GetLastError());
1317 }
1318 }
1319
1320 MountDrive = DriveName[0];
1321 Log("Will use '%C:' as volume mountpoint", DriveName[0]);
1322
1323 // It kind of blows, but we have to relinquish access to the physical drive
1324 // for VDS to be able to delete the partitions that reside on it...
1325 DeviceIoControl(hDrive, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
1326 CHECK_CLOSE_HANDLE(hDrive);
1327
1328 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART);
1329
1330 if (!VDS_DeleteAllPartitions(pPhyDrive->PhyDrive))
1331 {
1332 Log("Notice: Could not delete partitions: %u", GetLastError());
1333 }
1334
1335 Log("Deleting all partitions ......................... OK");
1336
1337 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE);
1338
1339 Log("Lock disk for write ............................. ");
1340 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
1341 if (hDrive == INVALID_HANDLE_VALUE)
1342 {
1343 Log("Failed to GetPhysicalHandle for write.");
1344 rc = 1;
1345 goto End;
1346 }
1347
1348 // clear first and last 2MB space
1349 pTmpBuf = malloc(SIZE_2MB);
1350 if (!pTmpBuf)
1351 {
1352 Log("Failed to alloc memory.");
1353 rc = 1;
1354 goto End;
1355 }
1356 memset(pTmpBuf, 0, SIZE_2MB);
1357
1358 SET_FILE_POS(512);
1359 bRet = WriteFile(hDrive, pTmpBuf, SIZE_2MB - 512, &dwSize, NULL);
1360 Log("Write fisrt 1MB ret:%d size:%u err:%d", bRet, dwSize, LASTERR);
1361 if (!bRet)
1362 {
1363 rc = 1;
1364 goto End;
1365 }
1366
1367 SET_FILE_POS(pPhyDrive->SizeInBytes - SIZE_2MB);
1368 bRet = WriteFile(hDrive, pTmpBuf, SIZE_2MB, &dwSize, NULL);
1369 Log("Write 2nd 1MB ret:%d size:%u err:%d", bRet, dwSize, LASTERR);
1370 if (!bRet)
1371 {
1372 rc = 1;
1373 goto End;
1374 }
1375
1376 SET_FILE_POS(0);
1377
1378 if (pPhyDrive->SizeInBytes > 2199023255552ULL)
1379 {
1380 VTOY_GPT_INFO *pGptInfo;
1381 VTOY_GPT_HDR BackupHead;
1382 LARGE_INTEGER liCurrentPosition;
1383
1384 pGptInfo = (VTOY_GPT_INFO *)pTmpBuf;
1385
1386 VentoyFillWholeGpt(pPhyDrive->SizeInBytes, pGptInfo);
1387
1388 SET_FILE_POS(pPhyDrive->SizeInBytes - 512);
1389 VentoyFillBackupGptHead(pGptInfo, &BackupHead);
1390 if (!WriteFile(hDrive, &BackupHead, sizeof(VTOY_GPT_HDR), &dwSize, NULL))
1391 {
1392 rc = 1;
1393 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize, sizeof(VTOY_GPT_INFO), GetLastError());
1394 goto End;
1395 }
1396
1397 SET_FILE_POS(pPhyDrive->SizeInBytes - 512 * 33);
1398 if (!WriteFile(hDrive, pGptInfo->PartTbl, sizeof(pGptInfo->PartTbl), &dwSize, NULL))
1399 {
1400 rc = 1;
1401 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize, sizeof(VTOY_GPT_INFO), GetLastError());
1402 goto End;
1403 }
1404
1405 SET_FILE_POS(0);
1406 if (!WriteFile(hDrive, pGptInfo, sizeof(VTOY_GPT_INFO), &dwSize, NULL))
1407 {
1408 rc = 1;
1409 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize, sizeof(VTOY_GPT_INFO), GetLastError());
1410 goto End;
1411 }
1412
1413 Log("Write GPT Info OK ...");
1414 }
1415 else
1416 {
1417 bRet = ReadFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL);
1418 Log("Read MBR ret:%d size:%u err:%d", bRet, dwSize, LASTERR);
1419 if (!bRet)
1420 {
1421 rc = 1;
1422 goto End;
1423 }
1424
1425 //clear boot code and partition table (reserved disk signature)
1426 memset(MBR.BootCode, 0, 440);
1427 memset(MBR.PartTbl, 0, sizeof(MBR.PartTbl));
1428
1429 VentoyFillMBRLocation(pPhyDrive->SizeInBytes, 2048, (UINT32)(pPhyDrive->SizeInBytes / 512 - 2048), MBR.PartTbl);
1430
1431 MBR.PartTbl[0].Active = 0x00; // bootable
1432 MBR.PartTbl[0].FsFlag = 0x07; // exFAT/NTFS/HPFS
1433
1434 SET_FILE_POS(0);
1435 bRet = WriteFile(hDrive, &MBR, 512, &dwSize, NULL);
1436 Log("Write MBR ret:%d size:%u err:%d", bRet, dwSize, LASTERR);
1437 if (!bRet)
1438 {
1439 rc = 1;
1440 goto End;
1441 }
1442 }
1443
1444 Log("Clear Ventoy successfully finished");
1445
1446 //Refresh Drive Layout
1447 DeviceIoControl(hDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwSize, NULL);
1448
1449 End:
1450
1451 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME);
1452 PROGRESS_BAR_SET_POS(PT_REFORMAT_FINISH);
1453
1454 if (pTmpBuf)
1455 {
1456 free(pTmpBuf);
1457 }
1458
1459 if (rc == 0)
1460 {
1461 Log("Mounting Ventoy Partition ....................... ");
1462 Sleep(1000);
1463
1464 state = 0;
1465 memset(DriveLetters, 0, sizeof(DriveLetters));
1466 GetLettersBelongPhyDrive(pPhyDrive->PhyDrive, DriveLetters, sizeof(DriveLetters));
1467 Log("Logical drive letter after write ventoy: <%s>", DriveLetters);
1468
1469 for (i = 0; i < sizeof(DriveLetters) && DriveLetters[i]; i++)
1470 {
1471 DriveName[0] = DriveLetters[i];
1472 Log("%s is ventoy part1, already mounted", DriveName);
1473 state = 1;
1474 }
1475
1476 if (state != 1)
1477 {
1478 Log("need to mount ventoy part1...");
1479 if (0 == GetVentoyVolumeName(pPhyDrive->PhyDrive, 2048, DriveLetters, sizeof(DriveLetters), FALSE))
1480 {
1481 DriveName[0] = MountDrive;
1482 bRet = SetVolumeMountPointA(DriveName, DriveLetters);
1483 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName, DriveLetters, bRet, GetLastError());
1484
1485 *pDrvLetter = MountDrive;
1486 }
1487 else
1488 {
1489 Log("Failed to find ventoy volume");
1490 }
1491 }
1492
1493 Log("OK\n");
1494 }
1495 else
1496 {
1497 FindProcessOccupyDisk(hDrive, pPhyDrive);
1498 }
1499
1500 CHECK_CLOSE_HANDLE(hDrive);
1501 return rc;
1502 }
1503
1504 int InstallVentoy2FileImage(PHY_DRIVE_INFO *pPhyDrive, int PartStyle)
1505 {
1506 int i;
1507 int rc = 1;
1508 int Len = 0;
1509 int dataLen = 0;
1510 UINT size = 0;
1511 UINT segnum = 0;
1512 UINT32 chksum = 0;
1513 UINT64 data_offset = 0;
1514 UINT64 Part2StartSector = 0;
1515 UINT64 Part1StartSector = 0;
1516 UINT64 Part1SectorCount = 0;
1517 UINT8 *pData = NULL;
1518 UINT8 *pBkGptPartTbl = NULL;
1519 BYTE *ImgBuf = NULL;
1520 MBR_HEAD *pMBR = NULL;
1521 VTSI_FOOTER *pImgFooter = NULL;
1522 VTSI_SEGMENT *pSegment = NULL;
1523 VTOY_GPT_INFO *pGptInfo = NULL;
1524 VTOY_GPT_HDR *pBkGptHdr = NULL;
1525 FILE *fp = NULL;
1526
1527 Log("InstallVentoy2FileImage %s PhyDrive%d <<%s %s %dGB>>",
1528 PartStyle ? "GPT" : "MBR", pPhyDrive->PhyDrive, pPhyDrive->VendorId, pPhyDrive->ProductId,
1529 GetHumanReadableGBSize(pPhyDrive->SizeInBytes));
1530
1531 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN);
1532
1533 size = SIZE_1MB + VENTOY_EFI_PART_SIZE + 33 * 512 + VTSI_IMG_MAX_SEG * sizeof(VTSI_SEGMENT) + sizeof(VTSI_FOOTER);
1534
1535 pData = (UINT8 *)malloc(size);
1536 if (!pData)
1537 {
1538 Log("malloc image buffer failed %d.", size);
1539 goto End;
1540 }
1541
1542 pImgFooter = (VTSI_FOOTER *)(pData + size - sizeof(VTSI_FOOTER));
1543 pSegment = (VTSI_SEGMENT *)((UINT8 *)pImgFooter - VTSI_IMG_MAX_SEG * sizeof(VTSI_SEGMENT));
1544 memset(pImgFooter, 0, sizeof(VTSI_FOOTER));
1545 memset(pSegment, 0, VTSI_IMG_MAX_SEG * sizeof(VTSI_SEGMENT));
1546
1547 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START);
1548
1549 Log("Writing Boot Image ............................. ");
1550 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG, 0, (void **)&ImgBuf, &Len))
1551 {
1552 Log("Failed to read stage1 img");
1553 goto End;
1554 }
1555
1556 unxz(ImgBuf, Len, NULL, NULL, pData, &dataLen, unxz_error);
1557 SAFE_FREE(ImgBuf);
1558
1559 Log("decompress %s len:%d", VENTOY_FILE_STG1_IMG, dataLen);
1560
1561 if (PartStyle)
1562 {
1563 pData[500] = 35;//update blocklist
1564 memmove(pData + 34 * 512, pData, SIZE_1MB - 512 * 34);
1565 memset(pData, 0, 34 * 512);
1566
1567 pGptInfo = (VTOY_GPT_INFO *)pData;
1568 memset(pGptInfo, 0, sizeof(VTOY_GPT_INFO));
1569 VentoyFillGpt(pPhyDrive->SizeInBytes, pGptInfo);
1570
1571 pBkGptPartTbl = pData + SIZE_1MB + VENTOY_EFI_PART_SIZE;
1572 memset(pBkGptPartTbl, 0, 33 * 512);
1573
1574 memcpy(pBkGptPartTbl, pGptInfo->PartTbl, 32 * 512);
1575 pBkGptHdr = (VTOY_GPT_HDR *)(pBkGptPartTbl + 32 * 512);
1576 VentoyFillBackupGptHead(pGptInfo, pBkGptHdr);
1577
1578 Part1StartSector = pGptInfo->PartTbl[0].StartLBA;
1579 Part1SectorCount = pGptInfo->PartTbl[0].LastLBA - Part1StartSector + 1;
1580 Part2StartSector = pGptInfo->PartTbl[1].StartLBA;
1581
1582 Log("Write GPT Info OK ...");
1583 }
1584 else
1585 {
1586 memmove(pData + 512, pData, SIZE_1MB - 512);
1587 memset(pData, 0, 512);
1588
1589 pMBR = (MBR_HEAD *)pData;
1590 VentoyFillMBR(pPhyDrive->SizeInBytes, pMBR, PartStyle);
1591 Part1StartSector = pMBR->PartTbl[0].StartSectorId;
1592 Part1SectorCount = pMBR->PartTbl[0].SectorCount;
1593 Part2StartSector = pMBR->PartTbl[1].StartSectorId;
1594
1595 Log("Write MBR OK ...");
1596 }
1597
1598 Log("Writing EFI part Image ............................. ");
1599 rc = ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG, 0, (void **)&ImgBuf, &Len);
1600 if (rc)
1601 {
1602 Log("Failed to read img file %p %u", ImgBuf, Len);
1603 goto End;
1604 }
1605
1606 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START + 28);
1607 memset(g_part_img_buf, 0, sizeof(g_part_img_buf));
1608 unxz(ImgBuf, Len, NULL, NULL, pData + SIZE_1MB, &dataLen, unxz_error);
1609 if (dataLen == Len)
1610 {
1611 Log("decompress finished success");
1612 g_part_img_buf[0] = pData + SIZE_1MB;
1613
1614 VentoyProcSecureBoot(g_SecureBoot);
1615 }
1616 else
1617 {
1618 Log("decompress finished failed");
1619 goto End;
1620 }
1621
1622 fopen_s(&fp, "VentoySparseImg.vtsi", "wb+");
1623 if (!fp)
1624 {
1625 Log("Failed to create Ventoy img file");
1626 goto End;
1627 }
1628
1629 Log("Writing stage1 data ............................. ");
1630
1631 fwrite(pData, 1, SIZE_1MB, fp);
1632
1633 pSegment[0].disk_start_sector = 0;
1634 pSegment[0].sector_num = SIZE_1MB / 512;
1635 pSegment[0].data_offset = data_offset;
1636 data_offset += pSegment[0].sector_num * 512;
1637
1638 disk_io_set_param(INVALID_HANDLE_VALUE, Part1StartSector + Part1SectorCount);// include the 2048 sector gap
1639 disk_io_set_imghook(fp, pSegment + 1, VTSI_IMG_MAX_SEG - 1, data_offset);
1640
1641 Log("Formatting part1 exFAT ...");
1642 if (0 != FormatPart1exFAT(pPhyDrive->SizeInBytes))
1643 {
1644 Log("FormatPart1exFAT failed.");
1645 disk_io_reset_imghook(&segnum, &data_offset);
1646 goto End;
1647 }
1648
1649 disk_io_reset_imghook(&segnum, &data_offset);
1650 segnum++;
1651
1652 Log("current segment number:%d dataoff:%ld", segnum, (long)data_offset);
1653
1654 //write data
1655 Log("Writing part2 data ............................. ");
1656 fwrite(pData + SIZE_1MB, 1, VENTOY_EFI_PART_SIZE, fp);
1657 pSegment[segnum].disk_start_sector = Part2StartSector;
1658 pSegment[segnum].sector_num = VENTOY_EFI_PART_SIZE / 512;
1659 pSegment[segnum].data_offset = data_offset;
1660 data_offset += pSegment[segnum].sector_num * 512;
1661 segnum++;
1662
1663 if (PartStyle)
1664 {
1665 Log("Writing backup gpt table ............................. ");
1666 fwrite(pBkGptPartTbl, 1, 33 * 512, fp);
1667 pSegment[segnum].disk_start_sector = pPhyDrive->SizeInBytes / 512 - 33;
1668 pSegment[segnum].sector_num = 33;
1669 pSegment[segnum].data_offset = data_offset;
1670 data_offset += pSegment[segnum].sector_num * 512;
1671 segnum++;
1672 }
1673
1674 Log("Writing segment metadata ............................. ");
1675
1676 for (i = 0; i < (int)segnum; i++)
1677 {
1678 Log("SEG[%d]: PhySector:%llu SectorNum:%llu DataOffset:%llu(sector:%llu)", i, pSegment[i].disk_start_sector, pSegment[i].sector_num,
1679 pSegment[i].data_offset, pSegment[i].data_offset / 512);
1680 }
1681
1682 dataLen = segnum * sizeof(VTSI_SEGMENT);
1683 fwrite(pSegment, 1, dataLen, fp);
1684
1685 if (dataLen % 512)
1686 {
1687 //pData + SIZE_1MB - 8192 is a temp data buffer with zero
1688 fwrite(pData + SIZE_1MB - 8192, 1, 512 - (dataLen % 512), fp);
1689 }
1690
1691 //Fill footer
1692 pImgFooter->magic = VTSI_IMG_MAGIC;
1693 pImgFooter->version = 1;
1694 pImgFooter->disk_size = pPhyDrive->SizeInBytes;
1695 memcpy(&pImgFooter->disk_signature, pPhyDrive->MBR.BootCode + 0x1b8, 4);
1696 pImgFooter->segment_num = segnum;
1697 pImgFooter->segment_offset = data_offset;
1698
1699 for (i = 0, chksum = 0; i < (int)(segnum * sizeof(VTSI_SEGMENT)); i++)
1700 {
1701 chksum += *((UINT8 *)pSegment + i);
1702 }
1703 pImgFooter->segment_chksum = ~chksum;
1704
1705 for (i = 0, chksum = 0; i < sizeof(VTSI_FOOTER); i++)
1706 {
1707 chksum += *((UINT8 *)pImgFooter + i);
1708 }
1709 pImgFooter->foot_chksum = ~chksum;
1710
1711 Log("Writing footer segnum(%u) segoffset(%llu) ......................", segnum, data_offset);
1712 Log("disk_size=%llu disk_signature=%lx segment_offset=%llu", pImgFooter->disk_size, pImgFooter->disk_signature, pImgFooter->segment_offset);
1713
1714 fwrite(pImgFooter, 1, sizeof(VTSI_FOOTER), fp);
1715 fclose(fp);
1716
1717 Log("Writing Ventoy image file finished, the file size should be %llu .", data_offset + 512 + ((dataLen + 511) / 512 * 512));
1718
1719 rc = 0;
1720
1721 End:
1722
1723 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME);
1724 PROGRESS_BAR_SET_POS(PT_REFORMAT_FINISH);
1725
1726 Log("retcode:%d\n", rc);
1727
1728 SAFE_FREE(pData);
1729 SAFE_FREE(ImgBuf);
1730
1731 return rc;
1732 }
1733
1734
1735 int InstallVentoy2PhyDrive(PHY_DRIVE_INFO *pPhyDrive, int PartStyle, int TryId)
1736 {
1737 int i;
1738 int rc = 0;
1739 int state = 0;
1740 BOOL ReformatOK;
1741 HANDLE hDrive;
1742 DWORD dwSize;
1743 BOOL bRet;
1744 CHAR MountDrive;
1745 CHAR DriveName[] = "?:\\";
1746 CHAR DriveLetters[MAX_PATH] = { 0 };
1747 MBR_HEAD MBR;
1748 VTOY_GPT_INFO *pGptInfo = NULL;
1749 UINT64 Part1StartSector = 0;
1750 UINT64 Part1SectorCount = 0;
1751 UINT64 Part2StartSector = 0;
1752 BOOL LargeFAT32 = FALSE;
1753
1754 Log("#####################################################");
1755 Log("InstallVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId,
1756 PartStyle ? "GPT" : "MBR", pPhyDrive->PhyDrive, pPhyDrive->VendorId, pPhyDrive->ProductId,
1757 GetHumanReadableGBSize(pPhyDrive->SizeInBytes));
1758 Log("#####################################################");
1759
1760 if (PartStyle)
1761 {
1762 pGptInfo = malloc(sizeof(VTOY_GPT_INFO));
1763 memset(pGptInfo, 0, sizeof(VTOY_GPT_INFO));
1764 }
1765
1766 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN);
1767
1768 if (PartStyle)
1769 {
1770 VentoyFillGpt(pPhyDrive->SizeInBytes, pGptInfo);
1771 Part1StartSector = pGptInfo->PartTbl[0].StartLBA;
1772 Part1SectorCount = pGptInfo->PartTbl[0].LastLBA - Part1StartSector + 1;
1773 Part2StartSector = pGptInfo->PartTbl[1].StartLBA;
1774 }
1775 else
1776 {
1777 VentoyFillMBR(pPhyDrive->SizeInBytes, &MBR, PartStyle);
1778 Part1StartSector = MBR.PartTbl[0].StartSectorId;
1779 Part1SectorCount = MBR.PartTbl[0].SectorCount;
1780 Part2StartSector = MBR.PartTbl[1].StartSectorId;
1781 }
1782
1783 Log("Lock disk for clean ............................. ");
1784
1785 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, FALSE, FALSE);
1786 if (hDrive == INVALID_HANDLE_VALUE)
1787 {
1788 Log("Failed to open physical disk");
1789 free(pGptInfo);
1790 return 1;
1791 }
1792
1793 GetLettersBelongPhyDrive(pPhyDrive->PhyDrive, DriveLetters, sizeof(DriveLetters));
1794
1795 if (DriveLetters[0] == 0)
1796 {
1797 Log("No drive letter was assigned...");
1798 DriveName[0] = GetFirstUnusedDriveLetter();
1799 Log("GetFirstUnusedDriveLetter %C: ...", DriveName[0]);
1800 }
1801 else
1802 {
1803 // Unmount all mounted volumes that belong to this drive
1804 // Do it in reverse so that we always end on the first volume letter
1805 for (i = (int)strlen(DriveLetters); i > 0; i--)
1806 {
1807 DriveName[0] = DriveLetters[i - 1];
1808 bRet = DeleteVolumeMountPointA(DriveName);
1809 Log("Delete mountpoint %s ret:%u code:%u", DriveName, bRet, GetLastError());
1810 }
1811 }
1812
1813 MountDrive = DriveName[0];
1814 Log("Will use '%C:' as volume mountpoint", DriveName[0]);
1815
1816 // It kind of blows, but we have to relinquish access to the physical drive
1817 // for VDS to be able to delete the partitions that reside on it...
1818 DeviceIoControl(hDrive, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
1819 CHECK_CLOSE_HANDLE(hDrive);
1820
1821 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART);
1822
1823 if (!VDS_DeleteAllPartitions(pPhyDrive->PhyDrive))
1824 {
1825 Log("Notice: Could not delete partitions: 0x%x, but we continue.", GetLastError());
1826 }
1827
1828 Log("Deleting all partitions ......................... OK");
1829
1830 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE);
1831
1832 Log("Lock disk for write ............................. ");
1833 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
1834 if (hDrive == INVALID_HANDLE_VALUE)
1835 {
1836 Log("Failed to GetPhysicalHandle for write.");
1837 rc = 1;
1838 goto End;
1839 }
1840
1841 //Refresh Drive Layout
1842 DeviceIoControl(hDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwSize, NULL);
1843
1844 disk_io_set_param(hDrive, Part1StartSector + Part1SectorCount);// include the 2048 sector gap
1845
1846 PROGRESS_BAR_SET_POS(PT_FORMAT_PART1);
1847
1848 if (PartStyle == 1 && pPhyDrive->PartStyle == 0)
1849 {
1850 Log("Wait for format part1 ...");
1851 Sleep(1000 * 5);
1852 }
1853
1854 if (GetVentoyFsType() == VTOY_FS_FAT32 && (Part1SectorCount * 512 >= FAT32_MAX_LIMIT))
1855 {
1856 Log("Formatting part1 large FAT32 ...");
1857 LargeFAT32 = TRUE;
1858 if (0 != FormatPart1LargeFAT32(pPhyDrive->SizeInBytes, GetClusterSize()))
1859 {
1860 Log("FormatPart1LargeFAT32 failed.");
1861 rc = 1;
1862 goto End;
1863 }
1864 }
1865 else
1866 {
1867 Log("Zero part1 file system ...");
1868 if (0 != ZeroPart1FileSystem(hDrive, Part2StartSector))
1869 {
1870 Log("ZeroPart1FileSystem failed.");
1871 rc = 1;
1872 goto End;
1873 }
1874 }
1875
1876 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2);
1877 Log("Writing part2 FAT img ...");
1878
1879 if (0 != FormatPart2Fat(hDrive, Part2StartSector))
1880 {
1881 Log("FormatPart2Fat failed.");
1882 rc = 1;
1883 goto End;
1884 }
1885
1886 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG);
1887 Log("Writing Boot Image ............................. ");
1888 if (WriteGrubStage1ToPhyDrive(hDrive, PartStyle) != 0)
1889 {
1890 Log("WriteGrubStage1ToPhyDrive failed.");
1891 rc = 1;
1892 goto End;
1893 }
1894
1895 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE);
1896 Log("Writing Partition Table ........................ ");
1897 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
1898
1899 if (PartStyle)
1900 {
1901 VTOY_GPT_HDR BackupHead;
1902 LARGE_INTEGER liCurrentPosition;
1903
1904 SET_FILE_POS(pPhyDrive->SizeInBytes - 512);
1905 VentoyFillBackupGptHead(pGptInfo, &BackupHead);
1906 if (!WriteFile(hDrive, &BackupHead, sizeof(VTOY_GPT_HDR), &dwSize, NULL))
1907 {
1908 rc = 1;
1909 Log("Write GPT Backup Head Failed, dwSize:%u (%u) ErrCode:%u", dwSize, sizeof(VTOY_GPT_INFO), GetLastError());
1910 goto End;
1911 }
1912
1913 SET_FILE_POS(pPhyDrive->SizeInBytes - 512 * 33);
1914 if (!WriteFile(hDrive, pGptInfo->PartTbl, sizeof(pGptInfo->PartTbl), &dwSize, NULL))
1915 {
1916 rc = 1;
1917 Log("Write GPT Backup Part Table Failed, dwSize:%u (%u) ErrCode:%u", dwSize, sizeof(VTOY_GPT_INFO), GetLastError());
1918 goto End;
1919 }
1920
1921 SET_FILE_POS(0);
1922 if (!WriteFile(hDrive, pGptInfo, sizeof(VTOY_GPT_INFO), &dwSize, NULL))
1923 {
1924 rc = 1;
1925 Log("Write GPT Info Failed, dwSize:%u (%u) ErrCode:%u", dwSize, sizeof(VTOY_GPT_INFO), GetLastError());
1926 goto End;
1927 }
1928
1929 Log("Write GPT Info OK ...");
1930 memcpy(&(pPhyDrive->MBR), &(pGptInfo->MBR), 512);
1931 }
1932 else
1933 {
1934 if (!WriteFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL))
1935 {
1936 rc = 1;
1937 Log("Write MBR Failed, dwSize:%u ErrCode:%u", dwSize, GetLastError());
1938 goto End;
1939 }
1940 Log("Write MBR OK ...");
1941 memcpy(&(pPhyDrive->MBR), &MBR, 512);
1942 }
1943
1944 //Refresh Drive Layout
1945 DeviceIoControl(hDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwSize, NULL);
1946
1947 End:
1948
1949 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME);
1950
1951 if (rc == 0)
1952 {
1953 Log("Mounting Ventoy Partition ....................... ");
1954 Sleep(1000);
1955
1956 state = 0;
1957 memset(DriveLetters, 0, sizeof(DriveLetters));
1958 GetLettersBelongPhyDrive(pPhyDrive->PhyDrive, DriveLetters, sizeof(DriveLetters));
1959 Log("Logical drive letter after write ventoy: <%s>", DriveLetters);
1960
1961 for (i = 0; i < sizeof(DriveLetters) && DriveLetters[i]; i++)
1962 {
1963 DriveName[0] = DriveLetters[i];
1964 if (IsVentoyLogicalDrive(DriveName[0]))
1965 {
1966 Log("%s is ventoy part2, delete mountpoint", DriveName);
1967 DeleteVolumeMountPointA(DriveName);
1968 }
1969 else
1970 {
1971 Log("%s is ventoy part1, already mounted", DriveName);
1972 MountDrive = DriveName[0];
1973 state = 1;
1974 }
1975 }
1976
1977 if (state != 1)
1978 {
1979 Log("need to mount ventoy part1...");
1980
1981 if (0 == GetVentoyVolumeName(pPhyDrive->PhyDrive, Part1StartSector, DriveLetters, sizeof(DriveLetters), FALSE))
1982 {
1983 DriveName[0] = MountDrive;
1984 bRet = SetVolumeMountPointA(DriveName, DriveLetters);
1985 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName, DriveLetters, bRet, GetLastError());
1986
1987 if (bRet)
1988 {
1989 state = 1;
1990 }
1991 }
1992 else
1993 {
1994 Log("Failed to find ventoy volume");
1995 }
1996 }
1997
1998 // close handle, or it will deny reformat
1999 Log("Close handle ...");
2000 CHECK_CLOSE_HANDLE(hDrive);
2001
2002 ReformatOK = TRUE;
2003
2004 if (state)
2005 {
2006 if (LargeFAT32)
2007 {
2008 Log("No need to reformat for large FAT32");
2009 pPhyDrive->VentoyFsClusterSize = GetVolumeClusterSize(MountDrive);
2010 }
2011 else
2012 {
2013 bRet = DISK_FormatVolume(MountDrive, GetVentoyFsType(), Part1SectorCount * 512);
2014 for (i = 0; bRet == FALSE && i < 2; i++)
2015 {
2016 Log("Wait and retry reformat ...");
2017 Sleep(1000);
2018 bRet = DISK_FormatVolume(MountDrive, GetVentoyFsType(), Part1SectorCount * 512);
2019 }
2020
2021 if (bRet)
2022 {
2023 Log("Reformat %C:\\ to %s SUCCESS", MountDrive, GetVentoyFsName());
2024 pPhyDrive->VentoyFsClusterSize = GetVolumeClusterSize(MountDrive);
2025
2026 if ((GetVentoyFsType() != VTOY_FS_UDF) && (pPhyDrive->VentoyFsClusterSize < 2048))
2027 {
2028 for (i = 0; i < 10; i++)
2029 {
2030 Log("### Invalid cluster size %d ###", pPhyDrive->VentoyFsClusterSize);
2031 }
2032 }
2033 }
2034 else
2035 {
2036 ReformatOK = FALSE;
2037 Log("Reformat %C:\\ to %s FAILED", MountDrive, GetVentoyFsName());
2038 }
2039 }
2040 }
2041 else
2042 {
2043 Log("Can not reformat %s to %s", DriveName, GetVentoyFsName());
2044 }
2045
2046 if (!ReformatOK)
2047 {
2048 Log("Format to exfat with built-in algorithm");
2049
2050 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
2051 if (hDrive == INVALID_HANDLE_VALUE)
2052 {
2053 Log("Failed to GetPhysicalHandle for write.");
2054 }
2055 else
2056 {
2057 if (0 != FormatPart1exFAT(pPhyDrive->SizeInBytes))
2058 {
2059 Log("FormatPart1exFAT SUCCESS.");
2060 }
2061 else
2062 {
2063 Log("FormatPart1exFAT FAILED.");
2064 }
2065
2066 CHECK_CLOSE_HANDLE(hDrive);
2067 }
2068 }
2069
2070 Log("OK\n");
2071 }
2072 else
2073 {
2074 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN);
2075
2076 FindProcessOccupyDisk(hDrive, pPhyDrive);
2077
2078 if (!VDS_IsLastAvaliable())
2079 {
2080 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2081 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2082 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2083 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2084 Log("###### [Error:] Virtual Disk Service (VDS) Unavailable ######");
2085 }
2086
2087 CHECK_CLOSE_HANDLE(hDrive);
2088 }
2089
2090 if (pGptInfo)
2091 {
2092 free(pGptInfo);
2093 }
2094
2095 return rc;
2096 }
2097
2098
2099 int PartitionResizeForVentoy(PHY_DRIVE_INFO *pPhyDrive)
2100 {
2101 int i, j;
2102 int rc = 1;
2103 int PhyDrive;
2104 int PartStyle;
2105 INT64 ReservedValue;
2106 UINT64 RecudeBytes;
2107 GUID Guid;
2108 MBR_HEAD MBR;
2109 VTOY_GPT_INFO *pGPT;
2110 MBR_HEAD *pMBR;
2111 DWORD dwSize = 0;
2112 VTOY_GPT_HDR BackupHead;
2113 HANDLE hDrive = INVALID_HANDLE_VALUE;
2114 GUID ZeroGuid = { 0 };
2115 static GUID WindowsDataPartType = { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
2116 static GUID EspPartType = { 0xc12a7328, 0xf81f, 0x11d2, { 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b } };
2117 static GUID BiosGrubPartType = { 0x21686148, 0x6449, 0x6e6f, { 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46, 0x49 } };
2118
2119 Log("#####################################################");
2120 Log("PartitionResizeForVentoy PhyDrive%d <<%s %s %dGB>>",
2121 pPhyDrive->PhyDrive, pPhyDrive->VendorId, pPhyDrive->ProductId,
2122 GetHumanReadableGBSize(pPhyDrive->SizeInBytes));
2123 Log("#####################################################");
2124
2125 pGPT = &(pPhyDrive->Gpt);
2126 pMBR = &(pPhyDrive->Gpt.MBR);
2127 Log("Disksize:%llu Part2Start:%llu", pPhyDrive->SizeInBytes, pPhyDrive->ResizePart2StartSector * 512);
2128
2129 if (pMBR->PartTbl[0].FsFlag == 0xEE && memcmp(pGPT->Head.Signature, "EFI PART", 8) == 0)
2130 {
2131 PartStyle = 1;
2132 }
2133 else
2134 {
2135 PartStyle = 0;
2136 }
2137
2138 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN);
2139
2140 RecudeBytes = VENTOY_EFI_PART_SIZE;
2141 ReservedValue = GetReservedSpaceInMB();
2142 if (ReservedValue > 0)
2143 {
2144 Log("Reduce add reserved space %lldMB", (LONGLONG)ReservedValue);
2145 RecudeBytes += (UINT64)(ReservedValue * SIZE_1MB);
2146 }
2147
2148
2149 if (pPhyDrive->ResizeNoShrink == FALSE)
2150 {
2151 Log("Need to shrink the volume");
2152 if (DISK_ShrinkVolume(pPhyDrive->PhyDrive, pPhyDrive->ResizeVolumeGuid, pPhyDrive->Part1DriveLetter, pPhyDrive->ResizeOldPart1Size, RecudeBytes))
2153 {
2154 Log("Shrink volume success, now check again");
2155
2156 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
2157 if (hDrive == INVALID_HANDLE_VALUE)
2158 {
2159 Log("Failed to GetPhysicalHandle for update.");
2160 goto End;
2161 }
2162
2163 //Refresh Drive Layout
2164 DeviceIoControl(hDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwSize, NULL);
2165
2166 CHECK_CLOSE_HANDLE(hDrive);
2167
2168
2169 if (PartResizePreCheck(NULL) && pPhyDrive->ResizeNoShrink)
2170 {
2171 Log("Recheck after Shrink volume success");
2172 Log("After shrink Disksize:%llu Part2Start:%llu", pPhyDrive->SizeInBytes, pPhyDrive->ResizePart2StartSector * 512);
2173 }
2174 else
2175 {
2176 Log("Recheck after Shrink volume failed %u", pPhyDrive->ResizeNoShrink);
2177 goto End;
2178 }
2179 }
2180 else
2181 {
2182 Log("Shrink volume failed");
2183 goto End;
2184 }
2185 }
2186
2187
2188 //Now try write data
2189 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
2190 if (hDrive == INVALID_HANDLE_VALUE)
2191 {
2192 Log("Failed to GetPhysicalHandle for update.");
2193 goto End;
2194 }
2195
2196
2197 //Write partition 2 data
2198 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2);
2199 if (0 != FormatPart2Fat(hDrive, pPhyDrive->ResizePart2StartSector))
2200 {
2201 Log("FormatPart2Fat failed.");
2202 goto End;
2203 }
2204
2205 //Write grub stage2 gap
2206 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG);
2207 Log("Writing Boot Image ............................. ");
2208 if (WriteGrubStage1ToPhyDrive(hDrive, PartStyle) != 0)
2209 {
2210 Log("WriteGrubStage1ToPhyDrive failed.");
2211 goto End;
2212 }
2213
2214
2215 //Write partition table
2216 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE);
2217 Log("Writing partition table ............................. ");
2218
2219 VentoyGetLocalBootImg(&MBR);
2220 CoCreateGuid(&Guid);
2221 memcpy(MBR.BootCode + 0x180, &Guid, 16);
2222 memcpy(pMBR->BootCode, MBR.BootCode, 440);
2223
2224 if (PartStyle == 0)
2225 {
2226 for (i = 1; i < 4; i++)
2227 {
2228 if (pMBR->PartTbl[i].SectorCount == 0)
2229 {
2230 break;
2231 }
2232 }
2233
2234 if (i >= 4)
2235 {
2236 Log("Can not find MBR free partition table");
2237 goto End;
2238 }
2239
2240 for (j = i - 1; j > 0; j--)
2241 {
2242 Log("Move MBR partition table %d --> %d", j + 1, j + 2);
2243 memcpy(pMBR->PartTbl + (j + 1), pMBR->PartTbl + j, sizeof(PART_TABLE));
2244 }
2245
2246 memset(pMBR->PartTbl + 1, 0, sizeof(PART_TABLE));
2247 VentoyFillMBRLocation(pPhyDrive->SizeInBytes, (UINT32)pPhyDrive->ResizePart2StartSector, VENTOY_EFI_PART_SIZE / 512, pMBR->PartTbl + 1);
2248 pMBR->PartTbl[0].Active = 0x80; // bootable
2249 pMBR->PartTbl[1].Active = 0x00;
2250 pMBR->PartTbl[1].FsFlag = 0xEF; // EFI System Partition
2251
2252 if (!WriteDataToPhyDisk(hDrive, 0, pMBR, 512))
2253 {
2254 Log("Legacy BIOS write MBR failed");
2255 goto End;
2256 }
2257 }
2258 else
2259 {
2260 for (i = 1; i < 128; i++)
2261 {
2262 if (memcmp(&(pGPT->PartTbl[i].PartGuid), &ZeroGuid, sizeof(GUID)) == 0)
2263 {
2264 break;
2265 }
2266 }
2267
2268 if (i >= 128)
2269 {
2270 Log("Can not find GPT free partition table");
2271 goto End;
2272 }
2273
2274 for (j = i - 1; j > 0; j--)
2275 {
2276 Log("Move GPT partition table %d --> %d", j + 1, j + 2);
2277 memcpy(pGPT->PartTbl + (j + 1), pGPT->PartTbl + j, sizeof(VTOY_GPT_PART_TBL));
2278 }
2279
2280
2281 pMBR->BootCode[92] = 0x22;
2282
2283 // to fix windows issue
2284 memset(pGPT->PartTbl + 1, 0, sizeof(VTOY_GPT_PART_TBL));
2285 memcpy(&(pGPT->PartTbl[1].PartType), &WindowsDataPartType, sizeof(GUID));
2286 CoCreateGuid(&(pGPT->PartTbl[1].PartGuid));
2287
2288 pGPT->PartTbl[1].StartLBA = pGPT->PartTbl[0].LastLBA + 1;
2289 pGPT->PartTbl[1].LastLBA = pGPT->PartTbl[1].StartLBA + VENTOY_EFI_PART_SIZE / 512 - 1;
2290 pGPT->PartTbl[1].Attr = 0xC000000000000001ULL;
2291 memcpy(pGPT->PartTbl[1].Name, L"VTOYEFI", 7 * 2);
2292
2293 //Update CRC
2294 pGPT->Head.PartTblCrc = VentoyCrc32(pGPT->PartTbl, sizeof(pGPT->PartTbl));
2295 pGPT->Head.Crc = 0;
2296 pGPT->Head.Crc = VentoyCrc32(&(pGPT->Head), pGPT->Head.Length);
2297
2298 Log("pGPT->Head.EfiStartLBA=%llu", (ULONGLONG)pGPT->Head.EfiStartLBA);
2299 Log("pGPT->Head.EfiBackupLBA=%llu", (ULONGLONG)pGPT->Head.EfiBackupLBA);
2300
2301 VentoyFillBackupGptHead(pGPT, &BackupHead);
2302 if (!WriteDataToPhyDisk(hDrive, pGPT->Head.EfiBackupLBA * 512, &BackupHead, 512))
2303 {
2304 Log("UEFI write backup head failed");
2305 goto End;
2306 }
2307
2308 if (!WriteDataToPhyDisk(hDrive, (pGPT->Head.EfiBackupLBA - 32) * 512, pGPT->PartTbl, 512 * 32))
2309 {
2310 Log("UEFI write backup partition table failed");
2311 goto End;
2312 }
2313
2314 if (!WriteDataToPhyDisk(hDrive, 0, pGPT, 512 * 34))
2315 {
2316 Log("UEFI write MBR & Main partition table failed");
2317 goto End;
2318 }
2319 }
2320
2321
2322
2323 //Refresh Drive Layout
2324 DeviceIoControl(hDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwSize, NULL);
2325
2326 //We must close handle here, because it will block the refresh bellow
2327 CHECK_CLOSE_HANDLE(hDrive);
2328
2329 Sleep(2000);
2330
2331 //Refresh disk list
2332 PhyDrive = pPhyDrive->PhyDrive;
2333
2334 Log("#### Now Refresh PhyDrive ####");
2335 Ventoy2DiskDestroy();
2336 Ventoy2DiskInit();
2337
2338 pPhyDrive = GetPhyDriveInfoByPhyDrive(PhyDrive);
2339 if (pPhyDrive)
2340 {
2341 if (pPhyDrive->VentoyVersion[0] == 0)
2342 {
2343 Log("After process the Ventoy version is still invalid");
2344 goto End;
2345 }
2346
2347 Log("### Ventoy non-destructive installation successfully finished <%s>", pPhyDrive->VentoyVersion);
2348 }
2349 else
2350 {
2351 Log("### Ventoy non-destructive installation successfully finished <not found>");
2352 }
2353
2354 InitComboxCtrl(g_DialogHwnd, PhyDrive);
2355
2356 rc = 0;
2357
2358 End:
2359 CHECK_CLOSE_HANDLE(hDrive);
2360 return rc;
2361 }
2362
2363
2364 static BOOL DiskCheckWriteAccess(HANDLE hDrive)
2365 {
2366 DWORD dwSize;
2367 BOOL ret = FALSE;
2368 BOOL bRet = FALSE;
2369 BYTE Buffer[512];
2370 LARGE_INTEGER liCurPosition;
2371 LARGE_INTEGER liNewPosition;
2372
2373 liCurPosition.QuadPart = 2039 * 512;
2374 liNewPosition.QuadPart = 0;
2375 if (0 == SetFilePointerEx(hDrive, liCurPosition, &liNewPosition, FILE_BEGIN) ||
2376 liNewPosition.QuadPart != liCurPosition.QuadPart)
2377 {
2378 Log("SetFilePointer1 Failed %u", LASTERR);
2379 goto out;
2380 }
2381
2382
2383 dwSize = 0;
2384 ret = ReadFile(hDrive, Buffer, 512, &dwSize, NULL);
2385 if ((!ret) || (dwSize != 512))
2386 {
2387 Log("Failed to read %d %u 0x%x", ret, dwSize, LASTERR);
2388 goto out;
2389 }
2390
2391
2392 liCurPosition.QuadPart = 2039 * 512;
2393 liNewPosition.QuadPart = 0;
2394 if (0 == SetFilePointerEx(hDrive, liCurPosition, &liNewPosition, FILE_BEGIN) ||
2395 liNewPosition.QuadPart != liCurPosition.QuadPart)
2396 {
2397 Log("SetFilePointer2 Failed %u", LASTERR);
2398 goto out;
2399 }
2400
2401 dwSize = 0;
2402 ret = WriteFile(hDrive, Buffer, 512, &dwSize, NULL);
2403 if ((!ret) || dwSize != 512)
2404 {
2405 Log("Failed to write %d %u %u", ret, dwSize, LASTERR);
2406 goto out;
2407 }
2408
2409 bRet = TRUE;
2410
2411 out:
2412
2413 return bRet;
2414 }
2415
2416 static BOOL BackupDataBeforeCleanDisk(int PhyDrive, UINT64 DiskSize, BYTE **pBackup)
2417 {
2418 DWORD dwSize;
2419 DWORD dwStatus;
2420 BOOL Return = FALSE;
2421 BOOL ret = FALSE;
2422 BYTE *backup = NULL;
2423 UINT64 offset;
2424 HANDLE hDrive = INVALID_HANDLE_VALUE;
2425 LARGE_INTEGER liCurPosition;
2426 LARGE_INTEGER liNewPosition;
2427 VTOY_GPT_INFO *pGPT = NULL;
2428
2429 Log("BackupDataBeforeCleanDisk %d", PhyDrive);
2430
2431 // step1: check write access
2432 hDrive = GetPhysicalHandle(PhyDrive, TRUE, TRUE, FALSE);
2433 if (hDrive == INVALID_HANDLE_VALUE)
2434 {
2435 Log("Failed to GetPhysicalHandle for write.");
2436 goto out;
2437 }
2438
2439 if (DiskCheckWriteAccess(hDrive))
2440 {
2441 Log("DiskCheckWriteAccess success");
2442 CHECK_CLOSE_HANDLE(hDrive);
2443 }
2444 else
2445 {
2446 Log("DiskCheckWriteAccess failed");
2447 goto out;
2448 }
2449
2450 //step2 backup 4MB data
2451 backup = malloc(SIZE_1MB * 4);
2452 if (!backup)
2453 {
2454 goto out;
2455 }
2456
2457 hDrive = GetPhysicalHandle(PhyDrive, FALSE, FALSE, FALSE);
2458 if (hDrive == INVALID_HANDLE_VALUE)
2459 {
2460 goto out;
2461 }
2462
2463 //read first 2MB
2464 dwStatus = SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
2465 if (dwStatus != 0)
2466 {
2467 goto out;
2468 }
2469
2470 dwSize = 0;
2471 ret = ReadFile(hDrive, backup, SIZE_2MB, &dwSize, NULL);
2472 if ((!ret) || (dwSize != SIZE_2MB))
2473 {
2474 Log("Failed to read %d %u 0x%x", ret, dwSize, LASTERR);
2475 goto out;
2476 }
2477
2478 pGPT = (VTOY_GPT_INFO *)backup;
2479 offset = pGPT->Head.EfiBackupLBA * 512;
2480 if (offset >= (DiskSize - SIZE_2MB) && offset < DiskSize)
2481 {
2482 Log("EFI partition table check success");
2483 }
2484 else
2485 {
2486 Log("Backup EFI LBA not in last 2MB range: %llu", pGPT->Head.EfiBackupLBA);
2487 goto out;
2488 }
2489
2490 //read last 2MB
2491 liCurPosition.QuadPart = DiskSize - SIZE_2MB;
2492 liNewPosition.QuadPart = 0;
2493 if (0 == SetFilePointerEx(hDrive, liCurPosition, &liNewPosition, FILE_BEGIN) ||
2494 liNewPosition.QuadPart != liCurPosition.QuadPart)
2495 {
2496 goto out;
2497 }
2498
2499 dwSize = 0;
2500 ret = ReadFile(hDrive, backup + SIZE_2MB, SIZE_2MB, &dwSize, NULL);
2501 if ((!ret) || (dwSize != SIZE_2MB))
2502 {
2503 Log("Failed to read %d %u 0x%x", ret, dwSize, LASTERR);
2504 goto out;
2505 }
2506
2507 *pBackup = backup;
2508 backup = NULL; //For don't free later
2509 Return = TRUE;
2510
2511 out:
2512 CHECK_CLOSE_HANDLE(hDrive);
2513 if (backup)
2514 free(backup);
2515
2516 return Return;
2517 }
2518
2519
2520 static BOOL WriteBackupDataToDisk(HANDLE hDrive, UINT64 Offset, BYTE *Data, DWORD Length)
2521 {
2522 DWORD dwSize = 0;
2523 BOOL ret = FALSE;
2524 LARGE_INTEGER liCurPosition;
2525 LARGE_INTEGER liNewPosition;
2526
2527 Log("WriteBackupDataToDisk %llu %p %u", Offset, Data, Length);
2528
2529 liCurPosition.QuadPart = Offset;
2530 liNewPosition.QuadPart = 0;
2531 if (0 == SetFilePointerEx(hDrive, liCurPosition, &liNewPosition, FILE_BEGIN) ||
2532 liNewPosition.QuadPart != liCurPosition.QuadPart)
2533 {
2534 return FALSE;
2535 }
2536
2537 ret = WriteFile(hDrive, Data, Length, &dwSize, NULL);
2538 if ((!ret) || dwSize != Length)
2539 {
2540 Log("Failed to write %d %u %u", ret, dwSize, LASTERR);
2541 return FALSE;
2542 }
2543
2544 Log("WriteBackupDataToDisk %llu %p %u success", Offset, Data, Length);
2545 return TRUE;
2546 }
2547
2548
2549 int UpdateVentoy2PhyDrive(PHY_DRIVE_INFO *pPhyDrive, int TryId)
2550 {
2551 int i;
2552 int rc = 0;
2553 int MaxRetry = 4;
2554 BOOL ForceMBR = FALSE;
2555 BOOL Esp2Basic = FALSE;
2556 BOOL ChangeAttr = FALSE;
2557 BOOL CleanDisk = FALSE;
2558 BOOL DelEFI = FALSE;
2559 BOOL bWriteBack = TRUE;
2560 HANDLE hVolume;
2561 HANDLE hDrive;
2562 DWORD Status;
2563 DWORD dwSize;
2564 BOOL bRet;
2565 CHAR DriveName[] = "?:\\";
2566 CHAR DriveLetters[MAX_PATH] = { 0 };
2567 CHAR BackBinFile[MAX_PATH];
2568 UINT64 StartSector;
2569 UINT64 ReservedMB = 0;
2570 MBR_HEAD BootImg;
2571 MBR_HEAD MBR;
2572 BYTE *pBackup = NULL;
2573 VTOY_GPT_INFO *pGptInfo = NULL;
2574 VTOY_GPT_INFO *pGptBkup = NULL;
2575 UINT8 ReservedData[4096];
2576
2577 Log("#####################################################");
2578 Log("UpdateVentoy2PhyDrive try%d %s PhyDrive%d <<%s %s %dGB>>", TryId,
2579 pPhyDrive->PartStyle ? "GPT" : "MBR", pPhyDrive->PhyDrive, pPhyDrive->VendorId, pPhyDrive->ProductId,
2580 GetHumanReadableGBSize(pPhyDrive->SizeInBytes));
2581 Log("#####################################################");
2582
2583 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN);
2584
2585 Log("Lock disk for umount ............................ ");
2586
2587 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, FALSE, FALSE);
2588 if (hDrive == INVALID_HANDLE_VALUE)
2589 {
2590 Log("Failed to open physical disk");
2591 return 1;
2592 }
2593
2594 if (pPhyDrive->PartStyle)
2595 {
2596 pGptInfo = malloc(2 * sizeof(VTOY_GPT_INFO));
2597 if (!pGptInfo)
2598 {
2599 return 1;
2600 }
2601
2602 memset(pGptInfo, 0, 2 * sizeof(VTOY_GPT_INFO));
2603 pGptBkup = pGptInfo + 1;
2604
2605 // Read GPT Info
2606 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
2607 ReadFile(hDrive, pGptInfo, sizeof(VTOY_GPT_INFO), &dwSize, NULL);
2608 memcpy(pGptBkup, pGptInfo, sizeof(VTOY_GPT_INFO));
2609
2610 //MBR will be used to compare with local boot image
2611 memcpy(&MBR, &pGptInfo->MBR, sizeof(MBR_HEAD));
2612
2613 StartSector = pGptInfo->PartTbl[1].StartLBA;
2614 Log("GPT StartSector in PartTbl:%llu", (ULONGLONG)StartSector);
2615
2616 ReservedMB = (pPhyDrive->SizeInBytes / 512 - (StartSector + VENTOY_EFI_PART_SIZE / 512) - 33) / 2048;
2617 Log("GPT Reserved Disk Space:%llu MB", (ULONGLONG)ReservedMB);
2618 }
2619 else
2620 {
2621 // Read MBR
2622 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
2623 ReadFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL);
2624
2625 StartSector = MBR.PartTbl[1].StartSectorId;
2626 Log("MBR StartSector in PartTbl:%llu", (ULONGLONG)StartSector);
2627
2628 ReservedMB = (pPhyDrive->SizeInBytes / 512 - (StartSector + VENTOY_EFI_PART_SIZE / 512)) / 2048;
2629 Log("MBR Reserved Disk Space:%llu MB", (ULONGLONG)ReservedMB);
2630 }
2631
2632 //Read Reserved Data
2633 SetFilePointer(hDrive, 512 * 2040, NULL, FILE_BEGIN);
2634 ReadFile(hDrive, ReservedData, sizeof(ReservedData), &dwSize, NULL);
2635
2636 GetLettersBelongPhyDrive(pPhyDrive->PhyDrive, DriveLetters, sizeof(DriveLetters));
2637
2638 if (DriveLetters[0] == 0)
2639 {
2640 Log("No drive letter was assigned...");
2641 }
2642 else
2643 {
2644 // Unmount all mounted volumes that belong to this drive
2645 // Do it in reverse so that we always end on the first volume letter
2646 for (i = (int)strlen(DriveLetters); i > 0; i--)
2647 {
2648 DriveName[0] = DriveLetters[i - 1];
2649 if (IsVentoyLogicalDrive(DriveName[0]))
2650 {
2651 Log("%s is ventoy logical drive", DriveName);
2652 bRet = DeleteVolumeMountPointA(DriveName);
2653 Log("Delete mountpoint %s ret:%u code:%u", DriveName, bRet, LASTERR);
2654 break;
2655 }
2656 }
2657 }
2658
2659 // It kind of blows, but we have to relinquish access to the physical drive
2660 // for VDS to be able to delete the partitions that reside on it...
2661 DeviceIoControl(hDrive, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
2662 CHECK_CLOSE_HANDLE(hDrive);
2663
2664 if (pPhyDrive->PartStyle == 1)
2665 {
2666 Log("TryId=%d EFI GPT partition type is 0x%llx", TryId, pPhyDrive->Part2GPTAttr);
2667 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART);
2668
2669 if (TryId == 1)
2670 {
2671 Log("Change GPT partition type to ESP");
2672 if (DISK_ChangeVtoyEFI2ESP(pPhyDrive->PhyDrive, StartSector * 512ULL))
2673 {
2674 Esp2Basic = TRUE;
2675 Sleep(3000);
2676 }
2677 }
2678 else if (TryId == 2)
2679 {
2680 Log("Change GPT partition attribute");
2681 if (DISK_ChangeVtoyEFIAttr(pPhyDrive->PhyDrive, StartSector * 512ULL, 0x8000000000000001))
2682 {
2683 ChangeAttr = TRUE;
2684 Sleep(2000);
2685 }
2686 }
2687 else if (TryId == 3)
2688 {
2689 DISK_DeleteVtoyEFIPartition(pPhyDrive->PhyDrive, StartSector * 512ULL);
2690 DelEFI = TRUE;
2691 }
2692 else if (TryId == 4)
2693 {
2694 Log("Clean disk GPT partition table");
2695 if (BackupDataBeforeCleanDisk(pPhyDrive->PhyDrive, pPhyDrive->SizeInBytes, &pBackup))
2696 {
2697 sprintf_s(BackBinFile, sizeof(BackBinFile), ".\\ventoy\\phydrive%d_%u_%d.bin",
2698 pPhyDrive->PhyDrive, GetCurrentProcessId(), g_backup_bin_index++);
2699 SaveBufToFile(BackBinFile, pBackup, 4 * SIZE_1MB);
2700 Log("Save backup data to %s", BackBinFile);
2701
2702 Log("Success to backup data before clean");
2703 CleanDisk = TRUE;
2704 DISK_CleanDisk(pPhyDrive->PhyDrive);
2705 Sleep(3000);
2706 }
2707 else
2708 {
2709 Log("Failed to backup data before clean");
2710 }
2711 }
2712 }
2713
2714 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE);
2715
2716 Log("Lock disk for update ............................ ");
2717 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
2718 if (hDrive == INVALID_HANDLE_VALUE)
2719 {
2720 Log("Failed to GetPhysicalHandle for write.");
2721 rc = 1;
2722 goto End;
2723 }
2724
2725 PROGRESS_BAR_SET_POS(PT_LOCK_VOLUME);
2726
2727 Log("Lock volume for update .......................... ");
2728 hVolume = INVALID_HANDLE_VALUE;
2729
2730 //If we change VTOYEFI to ESP, it can not have s volume name, so don't try to get it.
2731 if (CleanDisk)
2732 {
2733 //writeback the last 2MB
2734 if (!WriteBackupDataToDisk(hDrive, pPhyDrive->SizeInBytes - SIZE_2MB, pBackup + SIZE_2MB, SIZE_2MB))
2735 {
2736 bWriteBack = FALSE;
2737 }
2738
2739 //write the first 2MB except parttable
2740 if (!WriteBackupDataToDisk(hDrive, 34 * 512, pBackup + 34 * 512, SIZE_2MB - 34 * 512))
2741 {
2742 bWriteBack = FALSE;
2743 }
2744
2745 Status = ERROR_NOT_FOUND;
2746 }
2747 else if (DelEFI)
2748 {
2749 Status = ERROR_NOT_FOUND;
2750 }
2751 else if (Esp2Basic)
2752 {
2753 Status = ERROR_NOT_FOUND;
2754 }
2755 else
2756 {
2757 for (i = 0; i < MaxRetry; i++)
2758 {
2759 Status = GetVentoyVolumeName(pPhyDrive->PhyDrive, StartSector, DriveLetters, sizeof(DriveLetters), TRUE);
2760 if (ERROR_SUCCESS == Status)
2761 {
2762 break;
2763 }
2764 else
2765 {
2766 Log("==== Volume not found, wait and retry %d... ====", i);
2767 Sleep(2);
2768 }
2769 }
2770 }
2771
2772 if (ERROR_SUCCESS == Status)
2773 {
2774 Log("Now lock and dismount volume <%s>", DriveLetters);
2775
2776 for (i = 0; i < MaxRetry; i++)
2777 {
2778 hVolume = CreateFileA(DriveLetters,
2779 GENERIC_READ | GENERIC_WRITE,
2780 FILE_SHARE_READ,
2781 NULL,
2782 OPEN_EXISTING,
2783 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH,
2784 NULL);
2785
2786 if (hVolume == INVALID_HANDLE_VALUE)
2787 {
2788 Log("Failed to create file volume, errcode:%u, wait and retry ...", LASTERR);
2789 Sleep(2000);
2790 }
2791 else
2792 {
2793 break;
2794 }
2795 }
2796
2797 if (hVolume == INVALID_HANDLE_VALUE)
2798 {
2799 Log("Failed to create file volume, errcode:%u", LASTERR);
2800 }
2801 else
2802 {
2803 bRet = DeviceIoControl(hVolume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
2804 Log("FSCTL_LOCK_VOLUME bRet:%u code:%u", bRet, LASTERR);
2805
2806 bRet = DeviceIoControl(hVolume, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
2807 Log("FSCTL_DISMOUNT_VOLUME bRet:%u code:%u", bRet, LASTERR);
2808 }
2809 }
2810 else if (ERROR_NOT_FOUND == Status)
2811 {
2812 Log("Volume not found, maybe not supported");
2813 }
2814 else
2815 {
2816 rc = 1;
2817 goto End;
2818 }
2819
2820 bRet = TryWritePart2(hDrive, StartSector);
2821 if (FALSE == bRet && Esp2Basic)
2822 {
2823 Log("TryWritePart2 agagin ...");
2824 Sleep(3000);
2825 bRet = TryWritePart2(hDrive, StartSector);
2826 }
2827
2828 if (!bRet)
2829 {
2830 if (pPhyDrive->PartStyle == 0)
2831 {
2832 if (DiskCheckWriteAccess(hDrive))
2833 {
2834 Log("MBR DiskCheckWriteAccess success");
2835
2836 ForceMBR = TRUE;
2837
2838 Log("Try write failed, now delete partition 2 for MBR...");
2839 CHECK_CLOSE_HANDLE(hDrive);
2840
2841 Log("Now delete partition 2...");
2842 DISK_DeleteVtoyEFIPartition(pPhyDrive->PhyDrive, StartSector * 512ULL);
2843
2844 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
2845 if (hDrive == INVALID_HANDLE_VALUE)
2846 {
2847 Log("Failed to GetPhysicalHandle for write.");
2848 rc = 1;
2849 goto End;
2850 }
2851 }
2852 else
2853 {
2854 Log("MBR DiskCheckWriteAccess failed");
2855 }
2856 }
2857 else
2858 {
2859 Log("TryWritePart2 failed ....");
2860 rc = 1;
2861 goto End;
2862 }
2863 }
2864
2865 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2);
2866
2867 Log("Write Ventoy to disk ............................ ");
2868 if (0 != FormatPart2Fat(hDrive, StartSector))
2869 {
2870 rc = 1;
2871 goto End;
2872 }
2873
2874 if (hVolume != INVALID_HANDLE_VALUE)
2875 {
2876 bRet = DeviceIoControl(hVolume, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
2877 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet, LASTERR);
2878 CHECK_CLOSE_HANDLE(hVolume);
2879 }
2880
2881 Log("Updating Boot Image ............................. ");
2882 if (WriteGrubStage1ToPhyDrive(hDrive, pPhyDrive->PartStyle) != 0)
2883 {
2884 rc = 1;
2885 goto End;
2886 }
2887
2888 //write reserved data
2889 SetFilePointer(hDrive, 512 * 2040, NULL, FILE_BEGIN);
2890 bRet = WriteFile(hDrive, ReservedData, sizeof(ReservedData), &dwSize, NULL);
2891 Log("Write resv data ret:%u dwSize:%u Error:%u", bRet, dwSize, LASTERR);
2892
2893 // Boot Image
2894 VentoyGetLocalBootImg(&BootImg);
2895
2896 // Use Old UUID
2897 memcpy(BootImg.BootCode + 0x180, MBR.BootCode + 0x180, 16);
2898 if (pPhyDrive->PartStyle)
2899 {
2900 BootImg.BootCode[92] = 0x22;
2901 }
2902
2903 if (ForceMBR == FALSE && memcmp(BootImg.BootCode, MBR.BootCode, 440) == 0)
2904 {
2905 Log("Boot image has no difference, no need to write.");
2906 }
2907 else
2908 {
2909 Log("Boot image need to write %u.", ForceMBR);
2910
2911 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
2912
2913 memcpy(MBR.BootCode, BootImg.BootCode, 440);
2914 bRet = WriteFile(hDrive, &MBR, 512, &dwSize, NULL);
2915 Log("Write Boot Image ret:%u dwSize:%u Error:%u", bRet, dwSize, LASTERR);
2916 }
2917
2918 if (pPhyDrive->PartStyle == 0)
2919 {
2920 if (0x00 == MBR.PartTbl[0].Active && 0x80 == MBR.PartTbl[1].Active)
2921 {
2922 Log("Need to chage 1st partition active and 2nd partition inactive.");
2923
2924 MBR.PartTbl[0].Active = 0x80;
2925 MBR.PartTbl[1].Active = 0x00;
2926
2927 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
2928 bRet = WriteFile(hDrive, &MBR, 512, &dwSize, NULL);
2929 Log("Write NEW MBR ret:%u dwSize:%u Error:%u", bRet, dwSize, LASTERR);
2930 }
2931 }
2932
2933 if (CleanDisk)
2934 {
2935 if (!WriteBackupDataToDisk(hDrive, 0, pBackup, 34 * 512))
2936 {
2937 bWriteBack = FALSE;
2938 }
2939
2940 free(pBackup);
2941
2942 if (bWriteBack)
2943 {
2944 Log("Write backup data success, now delete %s", BackBinFile);
2945 DeleteFileA(BackBinFile);
2946 }
2947 else
2948 {
2949 Log("Write backup data failed");
2950 }
2951
2952 Sleep(1000);
2953 }
2954 else if (DelEFI)
2955 {
2956 VTOY_GPT_HDR BackupHdr;
2957
2958 VentoyFillBackupGptHead(pGptBkup, &BackupHdr);
2959 if (!WriteBackupDataToDisk(hDrive, 512 * pGptBkup->Head.EfiBackupLBA, (BYTE*)(&BackupHdr), 512))
2960 {
2961 bWriteBack = FALSE;
2962 }
2963
2964 if (!WriteBackupDataToDisk(hDrive, 512 * (pGptBkup->Head.EfiBackupLBA - 32), (BYTE*)(pGptBkup->PartTbl), 32 * 512))
2965 {
2966 bWriteBack = FALSE;
2967 }
2968
2969 if (!WriteBackupDataToDisk(hDrive, 512, (BYTE*)pGptBkup + 512, 33 * 512))
2970 {
2971 bWriteBack = FALSE;
2972 }
2973
2974 if (bWriteBack)
2975 {
2976 Log("Write backup partition table success");
2977 }
2978 else
2979 {
2980 Log("Write backup partition table failed");
2981 }
2982
2983 Sleep(1000);
2984 }
2985
2986 //Refresh Drive Layout
2987 DeviceIoControl(hDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwSize, NULL);
2988
2989 End:
2990
2991 if (hVolume != INVALID_HANDLE_VALUE)
2992 {
2993 bRet = DeviceIoControl(hVolume, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
2994 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet, LASTERR);
2995 CHECK_CLOSE_HANDLE(hVolume);
2996 }
2997
2998 if (rc == 0)
2999 {
3000 Log("OK");
3001 }
3002 else
3003 {
3004 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN);
3005 FindProcessOccupyDisk(hDrive, pPhyDrive);
3006 }
3007
3008 CHECK_CLOSE_HANDLE(hDrive);
3009
3010 if (Esp2Basic)
3011 {
3012 Log("Recover GPT partition type to basic");
3013 DISK_ChangeVtoyEFI2Basic(pPhyDrive->PhyDrive, StartSector * 512);
3014 }
3015
3016 if (pPhyDrive->PartStyle == 1)
3017 {
3018 if (ChangeAttr || ((pPhyDrive->Part2GPTAttr >> 56) != 0xC0))
3019 {
3020 Log("Change EFI partition attr %u <0x%llx> to <0x%llx>", ChangeAttr, pPhyDrive->Part2GPTAttr, 0xC000000000000001ULL);
3021 if (DISK_ChangeVtoyEFIAttr(pPhyDrive->PhyDrive, StartSector * 512ULL, 0xC000000000000001ULL))
3022 {
3023 Log("Change EFI partition attr success");
3024 pPhyDrive->Part2GPTAttr = 0xC000000000000001ULL;
3025 }
3026 else
3027 {
3028 Log("Change EFI partition attr failed");
3029 }
3030 }
3031 }
3032
3033 if (pGptInfo)
3034 {
3035 free(pGptInfo);
3036 }
3037
3038 return rc;
3039 }
3040
3041