]> glassweightruler.freedombox.rocks Git - Ventoy.git/blob - Ventoy2Disk/Ventoy2Disk/PhyDrive.c
7dde3154f7f8a6618cd855cb00bea40b69ac20cd
[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 <winternl.h>
24 #include <commctrl.h>
25 #include <initguid.h>
26 #include <vds.h>
27 #include "resource.h"
28 #include "Language.h"
29 #include "Ventoy2Disk.h"
30 #include "fat_filelib.h"
31 #include "ff.h"
32
33 /*
34 * Some code and functions in the file are copied from rufus.
35 * https://github.com/pbatard/rufus
36 */
37 #define VDS_SET_ERROR SetLastError
38 #define IVdsServiceLoader_LoadService(This, pwszMachineName, ppService) (This)->lpVtbl->LoadService(This, pwszMachineName, ppService)
39 #define IVdsServiceLoader_Release(This) (This)->lpVtbl->Release(This)
40 #define IVdsService_QueryProviders(This, masks, ppEnum) (This)->lpVtbl->QueryProviders(This, masks, ppEnum)
41 #define IVdsService_WaitForServiceReady(This) ((This)->lpVtbl->WaitForServiceReady(This))
42 #define IVdsService_CleanupObsoleteMountPoints(This) ((This)->lpVtbl->CleanupObsoleteMountPoints(This))
43 #define IVdsService_Refresh(This) ((This)->lpVtbl->Refresh(This))
44 #define IVdsService_Reenumerate(This) ((This)->lpVtbl->Reenumerate(This))
45 #define IVdsSwProvider_QueryInterface(This, riid, ppvObject) (This)->lpVtbl->QueryInterface(This, riid, ppvObject)
46 #define IVdsProvider_Release(This) (This)->lpVtbl->Release(This)
47 #define IVdsSwProvider_QueryPacks(This, ppEnum) (This)->lpVtbl->QueryPacks(This, ppEnum)
48 #define IVdsSwProvider_Release(This) (This)->lpVtbl->Release(This)
49 #define IVdsPack_QueryDisks(This, ppEnum) (This)->lpVtbl->QueryDisks(This, ppEnum)
50 #define IVdsDisk_GetProperties(This, pDiskProperties) (This)->lpVtbl->GetProperties(This, pDiskProperties)
51 #define IVdsDisk_Release(This) (This)->lpVtbl->Release(This)
52 #define IVdsDisk_QueryInterface(This, riid, ppvObject) (This)->lpVtbl->QueryInterface(This, riid, ppvObject)
53 #define IVdsAdvancedDisk_QueryPartitions(This, ppPartitionPropArray, plNumberOfPartitions) (This)->lpVtbl->QueryPartitions(This, ppPartitionPropArray, plNumberOfPartitions)
54 #define IVdsAdvancedDisk_DeletePartition(This, ullOffset, bForce, bForceProtected) (This)->lpVtbl->DeletePartition(This, ullOffset, bForce, bForceProtected)
55 #define IVdsAdvancedDisk_Clean(This, bForce, bForceOEM, bFullClean, ppAsync) (This)->lpVtbl->Clean(This, bForce, bForceOEM, bFullClean, ppAsync)
56 #define IVdsAdvancedDisk_Release(This) (This)->lpVtbl->Release(This)
57 #define IEnumVdsObject_Next(This, celt, ppObjectArray, pcFetched) (This)->lpVtbl->Next(This, celt, ppObjectArray, pcFetched)
58 #define IVdsPack_QueryVolumes(This, ppEnum) (This)->lpVtbl->QueryVolumes(This, ppEnum)
59 #define IVdsVolume_QueryInterface(This, riid, ppvObject) (This)->lpVtbl->QueryInterface(This, riid, ppvObject)
60 #define IVdsVolume_Release(This) (This)->lpVtbl->Release(This)
61 #define IVdsVolumeMF3_QueryVolumeGuidPathnames(This, pwszPathArray, pulNumberOfPaths) (This)->lpVtbl->QueryVolumeGuidPathnames(This,pwszPathArray,pulNumberOfPaths)
62 #define IVdsVolumeMF3_FormatEx2(This, pwszFileSystemTypeName, usFileSystemRevision, ulDesiredUnitAllocationSize, pwszLabel, Options, ppAsync) (This)->lpVtbl->FormatEx2(This, pwszFileSystemTypeName, usFileSystemRevision, ulDesiredUnitAllocationSize, pwszLabel, Options, ppAsync)
63 #define IVdsVolumeMF3_Release(This) (This)->lpVtbl->Release(This)
64 #define IVdsVolume_GetProperties(This, pVolumeProperties) (This)->lpVtbl->GetProperties(This,pVolumeProperties)
65 #define IVdsAsync_Cancel(This) (This)->lpVtbl->Cancel(This)
66 #define IVdsAsync_QueryStatus(This,pHrResult,pulPercentCompleted) (This)->lpVtbl->QueryStatus(This,pHrResult,pulPercentCompleted)
67 #define IVdsAsync_Wait(This,pHrResult,pAsyncOut) (This)->lpVtbl->Wait(This,pHrResult,pAsyncOut)
68 #define IVdsAsync_Release(This) (This)->lpVtbl->Release(This)
69
70 #define IUnknown_QueryInterface(This, a, b) (This)->lpVtbl->QueryInterface(This,a,b)
71 #define IUnknown_Release(This) (This)->lpVtbl->Release(This)
72
73 /*
74 * Delete all the partitions from a disk, using VDS
75 * Mostly copied from https://social.msdn.microsoft.com/Forums/vstudio/en-US/b90482ae-4e44-4b08-8731-81915030b32a/createpartition-using-vds-interface-throw-error-enointerface-dcom?forum=vcgeneral
76 */
77 BOOL DeletePartitions(DWORD DriveIndex, BOOL OnlyPart2)
78 {
79 BOOL r = FALSE;
80 HRESULT hr;
81 ULONG ulFetched;
82 wchar_t wPhysicalName[48];
83 IVdsServiceLoader *pLoader;
84 IVdsService *pService;
85 IEnumVdsObject *pEnum;
86 IUnknown *pUnk;
87
88 swprintf_s(wPhysicalName, ARRAYSIZE(wPhysicalName), L"\\\\?\\PhysicalDrive%lu", DriveIndex);
89
90 // Initialize COM
91 CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
92 CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT,
93 RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL);
94
95 // Create a VDS Loader Instance
96 hr = CoCreateInstance(&CLSID_VdsLoader, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER,
97 &IID_IVdsServiceLoader, (void **)&pLoader);
98 if (hr != S_OK) {
99 VDS_SET_ERROR(hr);
100 Log("Could not create VDS Loader Instance: %u", LASTERR);
101 goto out;
102 }
103
104 // Load the VDS Service
105 hr = IVdsServiceLoader_LoadService(pLoader, L"", &pService);
106 IVdsServiceLoader_Release(pLoader);
107 if (hr != S_OK) {
108 VDS_SET_ERROR(hr);
109 Log("Could not load VDS Service: %u", LASTERR);
110 goto out;
111 }
112
113 // Wait for the Service to become ready if needed
114 hr = IVdsService_WaitForServiceReady(pService);
115 if (hr != S_OK) {
116 VDS_SET_ERROR(hr);
117 Log("VDS Service is not ready: %u", LASTERR);
118 goto out;
119 }
120
121 // Query the VDS Service Providers
122 hr = IVdsService_QueryProviders(pService, VDS_QUERY_SOFTWARE_PROVIDERS, &pEnum);
123 if (hr != S_OK) {
124 VDS_SET_ERROR(hr);
125 Log("Could not query VDS Service Providers: %u", LASTERR);
126 goto out;
127 }
128
129 while (IEnumVdsObject_Next(pEnum, 1, &pUnk, &ulFetched) == S_OK) {
130 IVdsProvider *pProvider;
131 IVdsSwProvider *pSwProvider;
132 IEnumVdsObject *pEnumPack;
133 IUnknown *pPackUnk;
134
135 // Get VDS Provider
136 hr = IUnknown_QueryInterface(pUnk, &IID_IVdsProvider, (void **)&pProvider);
137 IUnknown_Release(pUnk);
138 if (hr != S_OK) {
139 VDS_SET_ERROR(hr);
140 Log("Could not get VDS Provider: %u", LASTERR);
141 goto out;
142 }
143
144 // Get VDS Software Provider
145 hr = IVdsSwProvider_QueryInterface(pProvider, &IID_IVdsSwProvider, (void **)&pSwProvider);
146 IVdsProvider_Release(pProvider);
147 if (hr != S_OK) {
148 VDS_SET_ERROR(hr);
149 Log("Could not get VDS Software Provider: %u", LASTERR);
150 goto out;
151 }
152
153 // Get VDS Software Provider Packs
154 hr = IVdsSwProvider_QueryPacks(pSwProvider, &pEnumPack);
155 IVdsSwProvider_Release(pSwProvider);
156 if (hr != S_OK) {
157 VDS_SET_ERROR(hr);
158 Log("Could not get VDS Software Provider Packs: %u", LASTERR);
159 goto out;
160 }
161
162 // Enumerate Provider Packs
163 while (IEnumVdsObject_Next(pEnumPack, 1, &pPackUnk, &ulFetched) == S_OK) {
164 IVdsPack *pPack;
165 IEnumVdsObject *pEnumDisk;
166 IUnknown *pDiskUnk;
167
168 hr = IUnknown_QueryInterface(pPackUnk, &IID_IVdsPack, (void **)&pPack);
169 IUnknown_Release(pPackUnk);
170 if (hr != S_OK) {
171 VDS_SET_ERROR(hr);
172 Log("Could not query VDS Software Provider Pack: %u", LASTERR);
173 goto out;
174 }
175
176 // Use the pack interface to access the disks
177 hr = IVdsPack_QueryDisks(pPack, &pEnumDisk);
178 if (hr != S_OK) {
179 VDS_SET_ERROR(hr);
180 Log("Could not query VDS disks: %u", LASTERR);
181 goto out;
182 }
183
184 // List disks
185 while (IEnumVdsObject_Next(pEnumDisk, 1, &pDiskUnk, &ulFetched) == S_OK) {
186 VDS_DISK_PROP diskprop;
187 VDS_PARTITION_PROP* prop_array;
188 LONG i, prop_array_size;
189 IVdsDisk *pDisk;
190 IVdsAdvancedDisk *pAdvancedDisk;
191
192 // Get the disk interface.
193 hr = IUnknown_QueryInterface(pDiskUnk, &IID_IVdsDisk, (void **)&pDisk);
194 if (hr != S_OK) {
195 VDS_SET_ERROR(hr);
196 Log("Could not query VDS Disk Interface: %u", LASTERR);
197 goto out;
198 }
199
200 // Get the disk properties
201 hr = IVdsDisk_GetProperties(pDisk, &diskprop);
202 if (hr != S_OK) {
203 VDS_SET_ERROR(hr);
204 Log("Could not query VDS Disk Properties: %u", LASTERR);
205 goto out;
206 }
207
208 // Isolate the disk we want
209 if (_wcsicmp(wPhysicalName, diskprop.pwszName) != 0) {
210 IVdsDisk_Release(pDisk);
211 continue;
212 }
213
214 // Instantiate the AdvanceDisk interface for our disk.
215 hr = IVdsDisk_QueryInterface(pDisk, &IID_IVdsAdvancedDisk, (void **)&pAdvancedDisk);
216 IVdsDisk_Release(pDisk);
217 if (hr != S_OK) {
218 VDS_SET_ERROR(hr);
219 Log("Could not access VDS Advanced Disk interface: %u", LASTERR);
220 goto out;
221 }
222
223 // Query the partition data, so we can get the start offset, which we need for deletion
224 hr = IVdsAdvancedDisk_QueryPartitions(pAdvancedDisk, &prop_array, &prop_array_size);
225 if (hr == S_OK) {
226 Log("Deleting ALL partition(s) from disk '%S':", diskprop.pwszName);
227 // Now go through each partition
228 for (i = 0; i < prop_array_size; i++) {
229
230 Log("* Partition %d (offset: %lld, size: %llu)", prop_array[i].ulPartitionNumber,
231 prop_array[i].ullOffset, (ULONGLONG)prop_array[i].ullSize);
232
233 if (OnlyPart2 && prop_array[i].ullOffset == 2048*512)
234 {
235 Log("Skip this partition...");
236 continue;
237 }
238
239
240 hr = IVdsAdvancedDisk_DeletePartition(pAdvancedDisk, prop_array[i].ullOffset, TRUE, TRUE);
241 if (hr != S_OK) {
242 r = FALSE;
243 VDS_SET_ERROR(hr);
244 Log("Could not delete partitions: %u", LASTERR);
245 }
246 }
247 r = TRUE;
248 }
249 else {
250 Log("No partition to delete on disk '%S'", diskprop.pwszName);
251 r = TRUE;
252 }
253 CoTaskMemFree(prop_array);
254
255 #if 0
256 // Issue a Clean while we're at it
257 HRESULT hr2 = E_FAIL;
258 ULONG completed;
259 IVdsAsync* pAsync;
260 hr = IVdsAdvancedDisk_Clean(pAdvancedDisk, TRUE, FALSE, FALSE, &pAsync);
261 while (SUCCEEDED(hr)) {
262 if (IS_ERROR(FormatStatus)) {
263 IVdsAsync_Cancel(pAsync);
264 break;
265 }
266 hr = IVdsAsync_QueryStatus(pAsync, &hr2, &completed);
267 if (SUCCEEDED(hr)) {
268 hr = hr2;
269 if (hr == S_OK)
270 break;
271 if (hr == VDS_E_OPERATION_PENDING)
272 hr = S_OK;
273 }
274 Sleep(500);
275 }
276 if (hr != S_OK) {
277 VDS_SET_ERROR(hr);
278 Log("Could not clean disk: %s", LASTERR);
279 }
280 #endif
281 IVdsAdvancedDisk_Release(pAdvancedDisk);
282 goto out;
283 }
284 }
285 }
286
287 out:
288 return r;
289 }
290
291
292 static DWORD GetVentoyVolumeName(int PhyDrive, UINT32 StartSectorId, CHAR *NameBuf, UINT32 BufLen, BOOL DelSlash)
293 {
294 size_t len;
295 BOOL bRet;
296 DWORD dwSize;
297 HANDLE hDrive;
298 HANDLE hVolume;
299 UINT64 PartOffset;
300 DWORD Status = ERROR_NOT_FOUND;
301 DISK_EXTENT *pExtents = NULL;
302 CHAR VolumeName[MAX_PATH] = { 0 };
303 VOLUME_DISK_EXTENTS DiskExtents;
304
305 PartOffset = 512ULL * StartSectorId;
306
307 Log("GetVentoyVolumeName PhyDrive %d SectorStart:%u PartOffset:%llu", PhyDrive, StartSectorId, (ULONGLONG)PartOffset);
308
309 hVolume = FindFirstVolumeA(VolumeName, sizeof(VolumeName));
310 if (hVolume == INVALID_HANDLE_VALUE)
311 {
312 return 1;
313 }
314
315 do {
316
317 len = strlen(VolumeName);
318 Log("Find volume:%s", VolumeName);
319
320 VolumeName[len - 1] = 0;
321
322 hDrive = CreateFileA(VolumeName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
323 if (hDrive == INVALID_HANDLE_VALUE)
324 {
325 continue;
326 }
327
328 bRet = DeviceIoControl(hDrive,
329 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
330 NULL,
331 0,
332 &DiskExtents,
333 (DWORD)(sizeof(DiskExtents)),
334 (LPDWORD)&dwSize,
335 NULL);
336
337 Log("IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS bRet:%u code:%u", bRet, LASTERR);
338 Log("NumberOfDiskExtents:%u DiskNumber:%u", DiskExtents.NumberOfDiskExtents, DiskExtents.Extents[0].DiskNumber);
339
340 if (bRet && DiskExtents.NumberOfDiskExtents == 1)
341 {
342 pExtents = DiskExtents.Extents;
343
344 Log("This volume DiskNumber:%u offset:%llu", pExtents->DiskNumber, (ULONGLONG)pExtents->StartingOffset.QuadPart);
345 if ((int)pExtents->DiskNumber == PhyDrive && pExtents->StartingOffset.QuadPart == PartOffset)
346 {
347 Log("This volume match");
348
349 if (!DelSlash)
350 {
351 VolumeName[len - 1] = '\\';
352 }
353
354 sprintf_s(NameBuf, BufLen, "%s", VolumeName);
355 Status = ERROR_SUCCESS;
356 CloseHandle(hDrive);
357 break;
358 }
359 }
360
361 CloseHandle(hDrive);
362 } while (FindNextVolumeA(hVolume, VolumeName, sizeof(VolumeName)));
363
364 FindVolumeClose(hVolume);
365
366 Log("GetVentoyVolumeName return %u", Status);
367 return Status;
368 }
369
370 static int GetLettersBelongPhyDrive(int PhyDrive, char *DriveLetters, size_t Length)
371 {
372 int n = 0;
373 DWORD DataSize = 0;
374 CHAR *Pos = NULL;
375 CHAR *StringBuf = NULL;
376
377 DataSize = GetLogicalDriveStringsA(0, NULL);
378 StringBuf = (CHAR *)malloc(DataSize + 1);
379 if (StringBuf == NULL)
380 {
381 return 1;
382 }
383
384 GetLogicalDriveStringsA(DataSize, StringBuf);
385
386 for (Pos = StringBuf; *Pos; Pos += strlen(Pos) + 1)
387 {
388 if (n < (int)Length && PhyDrive == GetPhyDriveByLogicalDrive(Pos[0]))
389 {
390 Log("%C: is belong to phydrive%d", Pos[0], PhyDrive);
391 DriveLetters[n++] = Pos[0];
392 }
393 }
394
395 free(StringBuf);
396 return 0;
397 }
398
399 static HANDLE GetPhysicalHandle(int Drive, BOOLEAN bLockDrive, BOOLEAN bWriteAccess, BOOLEAN bWriteShare)
400 {
401 int i;
402 DWORD dwSize;
403 DWORD LastError;
404 UINT64 EndTime;
405 HANDLE hDrive = INVALID_HANDLE_VALUE;
406 CHAR PhyDrive[128];
407 CHAR DevPath[MAX_PATH] = { 0 };
408
409 safe_sprintf(PhyDrive, "\\\\.\\PhysicalDrive%d", Drive);
410
411 if (0 == QueryDosDeviceA(PhyDrive + 4, DevPath, sizeof(DevPath)))
412 {
413 Log("QueryDosDeviceA failed error:%u", GetLastError());
414 strcpy_s(DevPath, sizeof(DevPath), "???");
415 }
416 else
417 {
418 Log("QueryDosDeviceA success %s", DevPath);
419 }
420
421 for (i = 0; i < DRIVE_ACCESS_RETRIES; i++)
422 {
423 // Try without FILE_SHARE_WRITE (unless specifically requested) so that
424 // we won't be bothered by the OS or other apps when we set up our data.
425 // However this means we might have to wait for an access gap...
426 // We keep FILE_SHARE_READ though, as this shouldn't hurt us any, and is
427 // required for enumeration.
428 hDrive = CreateFileA(PhyDrive,
429 GENERIC_READ | (bWriteAccess ? GENERIC_WRITE : 0),
430 FILE_SHARE_READ | (bWriteShare ? FILE_SHARE_WRITE : 0),
431 NULL,
432 OPEN_EXISTING,
433 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH,
434 NULL);
435
436 LastError = GetLastError();
437 Log("[%d] CreateFileA %s code:%u %p", i, PhyDrive, LastError, hDrive);
438
439 if (hDrive != INVALID_HANDLE_VALUE)
440 {
441 break;
442 }
443
444 if ((LastError != ERROR_SHARING_VIOLATION) && (LastError != ERROR_ACCESS_DENIED))
445 {
446 break;
447 }
448
449 if (i == 0)
450 {
451 Log("Waiting for access on %s [%s]...", PhyDrive, DevPath);
452 }
453 else if (!bWriteShare && (i > DRIVE_ACCESS_RETRIES / 3))
454 {
455 // If we can't seem to get a hold of the drive for some time, try to enable FILE_SHARE_WRITE...
456 Log("Warning: Could not obtain exclusive rights. Retrying with write sharing enabled...");
457 bWriteShare = TRUE;
458
459 // Try to report the process that is locking the drive
460 // We also use bit 6 as a flag to indicate that SearchProcess was called.
461 //access_mask = SearchProcess(DevPath, SEARCH_PROCESS_TIMEOUT, TRUE, TRUE, FALSE) | 0x40;
462
463 }
464 Sleep(DRIVE_ACCESS_TIMEOUT / DRIVE_ACCESS_RETRIES);
465 }
466
467 if (hDrive == INVALID_HANDLE_VALUE)
468 {
469 Log("Could not open %s %u", PhyDrive, LASTERR);
470 goto End;
471 }
472
473 if (bWriteAccess)
474 {
475 Log("Opened %s for %s write access", PhyDrive, bWriteShare ? "shared" : "exclusive");
476 }
477
478 if (bLockDrive)
479 {
480 if (DeviceIoControl(hDrive, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0, &dwSize, NULL))
481 {
482 Log("I/O boundary checks disabled");
483 }
484
485 EndTime = GetTickCount64() + DRIVE_ACCESS_TIMEOUT;
486
487 do {
488 if (DeviceIoControl(hDrive, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL))
489 {
490 Log("FSCTL_LOCK_VOLUME success");
491 goto End;
492 }
493 Sleep(DRIVE_ACCESS_TIMEOUT / DRIVE_ACCESS_RETRIES);
494 } while (GetTickCount64() < EndTime);
495
496 // If we reached this section, either we didn't manage to get a lock or the user cancelled
497 Log("Could not lock access to %s %u", PhyDrive, LASTERR);
498
499 // See if we can report the processes are accessing the drive
500 //if (!IS_ERROR(FormatStatus) && (access_mask == 0))
501 // access_mask = SearchProcess(DevPath, SEARCH_PROCESS_TIMEOUT, TRUE, TRUE, FALSE);
502 // Try to continue if the only access rights we saw were for read-only
503 //if ((access_mask & 0x07) != 0x01)
504 // safe_closehandle(hDrive);
505
506 CHECK_CLOSE_HANDLE(hDrive);
507 }
508
509 End:
510
511 if (hDrive == INVALID_HANDLE_VALUE)
512 {
513 Log("Can get handle of %s, maybe some process control it.", DevPath);
514 }
515
516 return hDrive;
517 }
518
519 int GetPhyDriveByLogicalDrive(int DriveLetter)
520 {
521 BOOL Ret;
522 DWORD dwSize;
523 HANDLE Handle;
524 VOLUME_DISK_EXTENTS DiskExtents;
525 CHAR PhyPath[128];
526
527 safe_sprintf(PhyPath, "\\\\.\\%C:", (CHAR)DriveLetter);
528
529 Handle = CreateFileA(PhyPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
530 if (Handle == INVALID_HANDLE_VALUE)
531 {
532 Log("Could not open the disk<%s>, error:%u", PhyPath, LASTERR);
533 return -1;
534 }
535
536 Ret = DeviceIoControl(Handle,
537 IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
538 NULL,
539 0,
540 &DiskExtents,
541 (DWORD)(sizeof(DiskExtents)),
542 (LPDWORD)&dwSize,
543 NULL);
544
545 if (!Ret || DiskExtents.NumberOfDiskExtents == 0)
546 {
547 Log("DeviceIoControl IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS failed %s, error:%u", PhyPath, LASTERR);
548 CHECK_CLOSE_HANDLE(Handle);
549 return -1;
550 }
551 CHECK_CLOSE_HANDLE(Handle);
552
553 Log("LogicalDrive:%s PhyDrive:%d Offset:%llu ExtentLength:%llu",
554 PhyPath,
555 DiskExtents.Extents[0].DiskNumber,
556 DiskExtents.Extents[0].StartingOffset.QuadPart,
557 DiskExtents.Extents[0].ExtentLength.QuadPart
558 );
559
560 return (int)DiskExtents.Extents[0].DiskNumber;
561 }
562
563 int GetAllPhysicalDriveInfo(PHY_DRIVE_INFO *pDriveList, DWORD *pDriveCount)
564 {
565 int i;
566 int Count;
567 int id;
568 int Letter = 'A';
569 BOOL bRet;
570 DWORD dwBytes;
571 DWORD DriveCount = 0;
572 HANDLE Handle = INVALID_HANDLE_VALUE;
573 CHAR PhyDrive[128];
574 PHY_DRIVE_INFO *CurDrive = pDriveList;
575 GET_LENGTH_INFORMATION LengthInfo;
576 STORAGE_PROPERTY_QUERY Query;
577 STORAGE_DESCRIPTOR_HEADER DevDescHeader;
578 STORAGE_DEVICE_DESCRIPTOR *pDevDesc;
579 int PhyDriveId[VENTOY_MAX_PHY_DRIVE];
580
581 Count = GetPhysicalDriveCount();
582
583 for (i = 0; i < Count && i < VENTOY_MAX_PHY_DRIVE; i++)
584 {
585 PhyDriveId[i] = i;
586 }
587
588 dwBytes = GetLogicalDrives();
589 Log("Logical Drives: 0x%x", dwBytes);
590 while (dwBytes)
591 {
592 if (dwBytes & 0x01)
593 {
594 id = GetPhyDriveByLogicalDrive(Letter);
595 Log("%C --> %d", Letter, id);
596 if (id >= 0)
597 {
598 for (i = 0; i < Count; i++)
599 {
600 if (PhyDriveId[i] == id)
601 {
602 break;
603 }
604 }
605
606 if (i >= Count)
607 {
608 Log("Add phy%d to list", i);
609 PhyDriveId[Count] = id;
610 Count++;
611 }
612 }
613 }
614
615 Letter++;
616 dwBytes >>= 1;
617 }
618
619 for (i = 0; i < Count && DriveCount < VENTOY_MAX_PHY_DRIVE; i++)
620 {
621 CHECK_CLOSE_HANDLE(Handle);
622
623 safe_sprintf(PhyDrive, "\\\\.\\PhysicalDrive%d", PhyDriveId[i]);
624 Handle = CreateFileA(PhyDrive, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
625 Log("Create file Handle:%p %s status:%u", Handle, PhyDrive, LASTERR);
626
627 if (Handle == INVALID_HANDLE_VALUE)
628 {
629 continue;
630 }
631
632 bRet = DeviceIoControl(Handle,
633 IOCTL_DISK_GET_LENGTH_INFO, NULL,
634 0,
635 &LengthInfo,
636 sizeof(LengthInfo),
637 &dwBytes,
638 NULL);
639 if (!bRet)
640 {
641 Log("DeviceIoControl IOCTL_DISK_GET_LENGTH_INFO failed error:%u", LASTERR);
642 continue;
643 }
644
645 Log("PHYSICALDRIVE%d size %llu bytes", i, (ULONGLONG)LengthInfo.Length.QuadPart);
646
647 Query.PropertyId = StorageDeviceProperty;
648 Query.QueryType = PropertyStandardQuery;
649
650 bRet = DeviceIoControl(Handle,
651 IOCTL_STORAGE_QUERY_PROPERTY,
652 &Query,
653 sizeof(Query),
654 &DevDescHeader,
655 sizeof(STORAGE_DESCRIPTOR_HEADER),
656 &dwBytes,
657 NULL);
658 if (!bRet)
659 {
660 Log("DeviceIoControl1 error:%u dwBytes:%u", LASTERR, dwBytes);
661 continue;
662 }
663
664 if (DevDescHeader.Size < sizeof(STORAGE_DEVICE_DESCRIPTOR))
665 {
666 Log("Invalid DevDescHeader.Size:%u", DevDescHeader.Size);
667 continue;
668 }
669
670 pDevDesc = (STORAGE_DEVICE_DESCRIPTOR *)malloc(DevDescHeader.Size);
671 if (!pDevDesc)
672 {
673 Log("failed to malloc error:%u len:%u", LASTERR, DevDescHeader.Size);
674 continue;
675 }
676
677 bRet = DeviceIoControl(Handle,
678 IOCTL_STORAGE_QUERY_PROPERTY,
679 &Query,
680 sizeof(Query),
681 pDevDesc,
682 DevDescHeader.Size,
683 &dwBytes,
684 NULL);
685 if (!bRet)
686 {
687 Log("DeviceIoControl2 error:%u dwBytes:%u", LASTERR, dwBytes);
688 free(pDevDesc);
689 continue;
690 }
691
692 CurDrive->PhyDrive = i;
693 CurDrive->SizeInBytes = LengthInfo.Length.QuadPart;
694 CurDrive->DeviceType = pDevDesc->DeviceType;
695 CurDrive->RemovableMedia = pDevDesc->RemovableMedia;
696 CurDrive->BusType = pDevDesc->BusType;
697
698 if (pDevDesc->VendorIdOffset)
699 {
700 safe_strcpy(CurDrive->VendorId, (char *)pDevDesc + pDevDesc->VendorIdOffset);
701 TrimString(CurDrive->VendorId);
702 }
703
704 if (pDevDesc->ProductIdOffset)
705 {
706 safe_strcpy(CurDrive->ProductId, (char *)pDevDesc + pDevDesc->ProductIdOffset);
707 TrimString(CurDrive->ProductId);
708 }
709
710 if (pDevDesc->ProductRevisionOffset)
711 {
712 safe_strcpy(CurDrive->ProductRev, (char *)pDevDesc + pDevDesc->ProductRevisionOffset);
713 TrimString(CurDrive->ProductRev);
714 }
715
716 if (pDevDesc->SerialNumberOffset)
717 {
718 safe_strcpy(CurDrive->SerialNumber, (char *)pDevDesc + pDevDesc->SerialNumberOffset);
719 TrimString(CurDrive->SerialNumber);
720 }
721
722 CurDrive++;
723 DriveCount++;
724
725 free(pDevDesc);
726
727 CHECK_CLOSE_HANDLE(Handle);
728 }
729
730 for (i = 0, CurDrive = pDriveList; i < (int)DriveCount; i++, CurDrive++)
731 {
732 Log("PhyDrv:%d BusType:%-4s Removable:%u Size:%dGB(%llu) Name:%s %s",
733 CurDrive->PhyDrive, GetBusTypeString(CurDrive->BusType), CurDrive->RemovableMedia,
734 GetHumanReadableGBSize(CurDrive->SizeInBytes), CurDrive->SizeInBytes,
735 CurDrive->VendorId, CurDrive->ProductId);
736 }
737
738 *pDriveCount = DriveCount;
739
740 return 0;
741 }
742
743
744 static HANDLE g_FatPhyDrive;
745 static UINT64 g_Part2StartSec;
746 static int GetVentoyVersionFromFatFile(CHAR *VerBuf, size_t BufLen)
747 {
748 int rc = 1;
749 int size = 0;
750 char *buf = NULL;
751 void *flfile = NULL;
752
753 flfile = fl_fopen("/grub/grub.cfg", "rb");
754 if (flfile)
755 {
756 fl_fseek(flfile, 0, SEEK_END);
757 size = (int)fl_ftell(flfile);
758
759 fl_fseek(flfile, 0, SEEK_SET);
760
761 buf = (char *)malloc(size + 1);
762 if (buf)
763 {
764 fl_fread(buf, 1, size, flfile);
765 buf[size] = 0;
766
767 rc = 0;
768 sprintf_s(VerBuf, BufLen, "%s", ParseVentoyVersionFromString(buf));
769 free(buf);
770 }
771
772 fl_fclose(flfile);
773 }
774
775 return rc;
776 }
777
778 static int VentoyFatDiskRead(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
779 {
780 DWORD dwSize;
781 BOOL bRet;
782 DWORD ReadSize;
783 LARGE_INTEGER liCurrentPosition;
784
785 liCurrentPosition.QuadPart = Sector + g_Part2StartSec;
786 liCurrentPosition.QuadPart *= 512;
787 SetFilePointerEx(g_FatPhyDrive, liCurrentPosition, &liCurrentPosition, FILE_BEGIN);
788
789 ReadSize = (DWORD)(SectorCount * 512);
790
791 bRet = ReadFile(g_FatPhyDrive, Buffer, ReadSize, &dwSize, NULL);
792 if (bRet == FALSE || dwSize != ReadSize)
793 {
794 Log("ReadFile error bRet:%u WriteSize:%u dwSize:%u ErrCode:%u\n", bRet, ReadSize, dwSize, LASTERR);
795 }
796
797 return 1;
798 }
799
800
801 int GetVentoyVerInPhyDrive(const PHY_DRIVE_INFO *pDriveInfo, MBR_HEAD *pMBR, CHAR *VerBuf, size_t BufLen)
802 {
803 int rc = 0;
804 HANDLE hDrive;
805
806 hDrive = GetPhysicalHandle(pDriveInfo->PhyDrive, FALSE, FALSE, FALSE);
807 if (hDrive == INVALID_HANDLE_VALUE)
808 {
809 return 1;
810 }
811
812 g_FatPhyDrive = hDrive;
813 g_Part2StartSec = pMBR->PartTbl[1].StartSectorId;
814
815 Log("Parse FAT fs...");
816
817 fl_init();
818
819 if (0 == fl_attach_media(VentoyFatDiskRead, NULL))
820 {
821 rc = GetVentoyVersionFromFatFile(VerBuf, BufLen);
822 }
823 else
824 {
825 rc = 1;
826 }
827
828 fl_shutdown();
829
830 CHECK_CLOSE_HANDLE(hDrive);
831
832 return rc;
833 }
834
835
836
837
838
839 static unsigned int g_disk_unxz_len = 0;
840 static BYTE *g_part_img_pos = NULL;
841 static BYTE *g_part_img_buf[VENTOY_EFI_PART_SIZE / SIZE_1MB];
842
843
844 static int VentoyFatMemRead(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
845 {
846 uint32 i;
847 uint32 offset;
848 BYTE *MbBuf = NULL;
849
850 for (i = 0; i < SectorCount; i++)
851 {
852 offset = (Sector + i) * 512;
853
854 if (g_part_img_buf[1] == NULL)
855 {
856 MbBuf = g_part_img_buf[0] + offset;
857 memcpy(Buffer + i * 512, MbBuf, 512);
858 }
859 else
860 {
861 MbBuf = g_part_img_buf[offset / SIZE_1MB];
862 memcpy(Buffer + i * 512, MbBuf + (offset % SIZE_1MB), 512);
863 }
864 }
865
866 return 1;
867 }
868
869
870 static int VentoyFatMemWrite(uint32 Sector, uint8 *Buffer, uint32 SectorCount)
871 {
872 uint32 i;
873 uint32 offset;
874 BYTE *MbBuf = NULL;
875
876 for (i = 0; i < SectorCount; i++)
877 {
878 offset = (Sector + i) * 512;
879
880 if (g_part_img_buf[1] == NULL)
881 {
882 MbBuf = g_part_img_buf[0] + offset;
883 memcpy(MbBuf, Buffer + i * 512, 512);
884 }
885 else
886 {
887 MbBuf = g_part_img_buf[offset / SIZE_1MB];
888 memcpy(MbBuf + (offset % SIZE_1MB), Buffer + i * 512, 512);
889 }
890 }
891
892 return 1;
893 }
894
895 int VentoyProcSecureBoot(BOOL SecureBoot)
896 {
897 int rc = 0;
898 int size;
899 char *filebuf = NULL;
900 void *file = NULL;
901
902 Log("VentoyProcSecureBoot %d ...", SecureBoot);
903
904 if (SecureBoot)
905 {
906 Log("Secure boot is enabled ...");
907 return 0;
908 }
909
910 fl_init();
911
912 if (0 == fl_attach_media(VentoyFatMemRead, VentoyFatMemWrite))
913 {
914 file = fl_fopen("/EFI/BOOT/grubx64_real.efi", "rb");
915 Log("Open ventoy efi file %p ", file);
916 if (file)
917 {
918 fl_fseek(file, 0, SEEK_END);
919 size = (int)fl_ftell(file);
920 fl_fseek(file, 0, SEEK_SET);
921
922 Log("ventoy efi file size %d ...", size);
923
924 filebuf = (char *)malloc(size);
925 if (filebuf)
926 {
927 fl_fread(filebuf, 1, size, file);
928 }
929
930 fl_fclose(file);
931
932 Log("Now delete all efi files ...");
933 fl_remove("/EFI/BOOT/BOOTX64.EFI");
934 fl_remove("/EFI/BOOT/grubx64.efi");
935 fl_remove("/EFI/BOOT/grubx64_real.efi");
936 fl_remove("/EFI/BOOT/MokManager.efi");
937
938 file = fl_fopen("/EFI/BOOT/BOOTX64.EFI", "wb");
939 Log("Open bootx64 efi file %p ", file);
940 if (file)
941 {
942 if (filebuf)
943 {
944 fl_fwrite(filebuf, 1, size, file);
945 }
946
947 fl_fflush(file);
948 fl_fclose(file);
949 }
950
951 if (filebuf)
952 {
953 free(filebuf);
954 }
955 }
956 }
957 else
958 {
959 rc = 1;
960 }
961
962 fl_shutdown();
963
964 return rc;
965 }
966
967
968
969 static int disk_xz_flush(void *src, unsigned int size)
970 {
971 unsigned int i;
972 BYTE *buf = (BYTE *)src;
973
974 for (i = 0; i < size; i++)
975 {
976 *g_part_img_pos = *buf++;
977
978 g_disk_unxz_len++;
979 if ((g_disk_unxz_len % SIZE_1MB) == 0)
980 {
981 g_part_img_pos = g_part_img_buf[g_disk_unxz_len / SIZE_1MB];
982 }
983 else
984 {
985 g_part_img_pos++;
986 }
987 }
988
989 return (int)size;
990 }
991
992 static void unxz_error(char *x)
993 {
994 Log("%s", x);
995 }
996
997 static BOOL TryWritePart2(HANDLE hDrive, UINT64 StartSectorId)
998 {
999 BOOL bRet;
1000 DWORD TrySize = 16 * 1024;
1001 DWORD dwSize;
1002 BYTE *Buffer = NULL;
1003 unsigned char *data = NULL;
1004 LARGE_INTEGER liCurrentPosition;
1005
1006 liCurrentPosition.QuadPart = StartSectorId * 512;
1007 SetFilePointerEx(hDrive, liCurrentPosition, &liCurrentPosition, FILE_BEGIN);
1008
1009 Buffer = malloc(TrySize);
1010
1011 bRet = WriteFile(hDrive, Buffer, TrySize, &dwSize, NULL);
1012
1013 free(Buffer);
1014
1015 Log("Try write part2 bRet:%u dwSize:%u code:%u", bRet, dwSize, LASTERR);
1016
1017 if (bRet && dwSize == TrySize)
1018 {
1019 return TRUE;
1020 }
1021
1022 return FALSE;
1023 }
1024
1025 static int FormatPart2Fat(HANDLE hDrive, UINT64 StartSectorId)
1026 {
1027 int i;
1028 int rc = 0;
1029 int len = 0;
1030 int writelen = 0;
1031 int partwrite = 0;
1032 DWORD dwSize = 0;
1033 BOOL bRet;
1034 unsigned char *data = NULL;
1035 LARGE_INTEGER liCurrentPosition;
1036 LARGE_INTEGER liNewPosition;
1037
1038 Log("FormatPart2Fat %llu...", StartSectorId);
1039
1040 rc = ReadWholeFileToBuf(VENTOY_FILE_DISK_IMG, 0, (void **)&data, &len);
1041 if (rc)
1042 {
1043 Log("Failed to read img file %p %u", data, len);
1044 return 1;
1045 }
1046
1047 liCurrentPosition.QuadPart = StartSectorId * 512;
1048 SetFilePointerEx(hDrive, liCurrentPosition, &liNewPosition, FILE_BEGIN);
1049
1050 Log("Set file pointer: %llu New pointer:%llu", liCurrentPosition.QuadPart, liNewPosition.QuadPart);
1051
1052 memset(g_part_img_buf, 0, sizeof(g_part_img_buf));
1053
1054 g_part_img_buf[0] = (BYTE *)malloc(VENTOY_EFI_PART_SIZE);
1055 if (g_part_img_buf[0])
1056 {
1057 Log("Malloc whole img buffer success, now decompress ...");
1058 unxz(data, len, NULL, NULL, g_part_img_buf[0], &writelen, unxz_error);
1059
1060 if (len == writelen)
1061 {
1062 Log("decompress finished success");
1063
1064 VentoyProcSecureBoot(g_SecureBoot);
1065
1066 for (i = 0; i < VENTOY_EFI_PART_SIZE / SIZE_1MB; i++)
1067 {
1068 dwSize = 0;
1069 bRet = WriteFile(hDrive, g_part_img_buf[0] + i * SIZE_1MB, SIZE_1MB, &dwSize, NULL);
1070 Log("Write part data bRet:%u dwSize:%u code:%u", bRet, dwSize, LASTERR);
1071
1072 if (!bRet)
1073 {
1074 rc = 1;
1075 goto End;
1076 }
1077
1078 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START + i);
1079 }
1080 }
1081 else
1082 {
1083 rc = 1;
1084 Log("decompress finished failed");
1085 goto End;
1086 }
1087 }
1088 else
1089 {
1090 Log("Failed to malloc whole img size %u, now split it", VENTOY_EFI_PART_SIZE);
1091
1092 partwrite = 1;
1093 for (i = 0; i < VENTOY_EFI_PART_SIZE / SIZE_1MB; i++)
1094 {
1095 g_part_img_buf[i] = (BYTE *)malloc(SIZE_1MB);
1096 if (g_part_img_buf[i] == NULL)
1097 {
1098 rc = 1;
1099 goto End;
1100 }
1101 }
1102
1103 Log("Malloc part img buffer success, now decompress ...");
1104
1105 g_part_img_pos = g_part_img_buf[0];
1106
1107 unxz(data, len, NULL, disk_xz_flush, NULL, NULL, unxz_error);
1108
1109 if (g_disk_unxz_len == VENTOY_EFI_PART_SIZE)
1110 {
1111 Log("decompress finished success");
1112
1113 VentoyProcSecureBoot(g_SecureBoot);
1114
1115 for (int i = 0; i < VENTOY_EFI_PART_SIZE / SIZE_1MB; i++)
1116 {
1117 dwSize = 0;
1118 bRet = WriteFile(hDrive, g_part_img_buf[i], SIZE_1MB, &dwSize, NULL);
1119 Log("Write part data bRet:%u dwSize:%u code:%u", bRet, dwSize, LASTERR);
1120
1121 if (!bRet)
1122 {
1123 rc = 1;
1124 goto End;
1125 }
1126
1127 PROGRESS_BAR_SET_POS(PT_WRITE_VENTOY_START + i);
1128 }
1129 }
1130 else
1131 {
1132 rc = 1;
1133 Log("decompress finished failed");
1134 goto End;
1135 }
1136 }
1137
1138 End:
1139
1140 if (data) free(data);
1141
1142 if (partwrite)
1143 {
1144 for (i = 0; i < VENTOY_EFI_PART_SIZE / SIZE_1MB; i++)
1145 {
1146 if (g_part_img_buf[i]) free(g_part_img_buf[i]);
1147 }
1148 }
1149 else
1150 {
1151 if (g_part_img_buf[0]) free(g_part_img_buf[0]);
1152 }
1153
1154 return rc;
1155 }
1156
1157 static int WriteGrubStage1ToPhyDrive(HANDLE hDrive)
1158 {
1159 int Len = 0;
1160 int readLen = 0;
1161 BOOL bRet;
1162 DWORD dwSize;
1163 BYTE *ImgBuf = NULL;
1164 BYTE *RawBuf = NULL;
1165
1166 Log("WriteGrubStage1ToPhyDrive ...");
1167
1168 RawBuf = (BYTE *)malloc(SIZE_1MB);
1169 if (!RawBuf)
1170 {
1171 return 1;
1172 }
1173
1174 if (ReadWholeFileToBuf(VENTOY_FILE_STG1_IMG, 0, (void **)&ImgBuf, &Len))
1175 {
1176 Log("Failed to read stage1 img");
1177 free(RawBuf);
1178 return 1;
1179 }
1180
1181 unxz(ImgBuf, Len, NULL, NULL, RawBuf, &readLen, unxz_error);
1182
1183 SetFilePointer(hDrive, 512, NULL, FILE_BEGIN);
1184
1185 bRet = WriteFile(hDrive, RawBuf, SIZE_1MB - 512, &dwSize, NULL);
1186 Log("WriteFile Ret:%u dwSize:%u ErrCode:%u", bRet, dwSize, GetLastError());
1187
1188 free(RawBuf);
1189 free(ImgBuf);
1190 return 0;
1191 }
1192
1193
1194
1195 static int FormatPart1exFAT(UINT64 DiskSizeBytes)
1196 {
1197 MKFS_PARM Option;
1198 FRESULT Ret;
1199 FATFS fs;
1200
1201 Option.fmt = FM_EXFAT;
1202 Option.n_fat = 1;
1203 Option.align = 8;
1204 Option.n_root = 1;
1205
1206 // < 32GB select 32KB as cluster size
1207 // > 32GB select 128KB as cluster size
1208 if (DiskSizeBytes / 1024 / 1024 / 1024 <= 32)
1209 {
1210 Option.au_size = 32768;
1211 }
1212 else
1213 {
1214 Option.au_size = 131072;
1215 }
1216
1217 Log("Formatting Part1 exFAT ...");
1218
1219 Ret = f_mkfs(TEXT("0:"), &Option, 0, 8 * 1024 * 1024);
1220
1221 if (FR_OK == Ret)
1222 {
1223 Log("Formatting Part1 exFAT success");
1224
1225 Ret = f_mount(&fs, TEXT("0:"), 1);
1226 Log("mount part %d", Ret);
1227
1228 if (FR_OK == Ret)
1229 {
1230 Ret = f_setlabel(TEXT("Ventoy"));
1231 Log("f_setlabel %d", Ret);
1232
1233 Ret = f_mount(0, TEXT("0:"), 1);
1234 Log("umount part %d", Ret);
1235 return 0;
1236 }
1237 else
1238 {
1239 Log("mount exfat failed %d", Ret);
1240 return 1;
1241 }
1242 }
1243 else
1244 {
1245 Log("Formatting Part1 exFAT failed");
1246 return 1;
1247 }
1248 }
1249
1250
1251
1252 int ClearVentoyFromPhyDrive(HWND hWnd, PHY_DRIVE_INFO *pPhyDrive, char *pDrvLetter)
1253 {
1254 int i;
1255 int rc = 0;
1256 int state = 0;
1257 HANDLE hDrive;
1258 DWORD dwSize;
1259 BOOL bRet;
1260 CHAR MountDrive;
1261 CHAR DriveName[] = "?:\\";
1262 CHAR DriveLetters[MAX_PATH] = { 0 };
1263 LARGE_INTEGER liCurrentPosition;
1264 char *pTmpBuf = NULL;
1265 MBR_HEAD MBR;
1266
1267 *pDrvLetter = 0;
1268
1269 Log("ClearVentoyFromPhyDrive PhyDrive%d <<%s %s %dGB>>",
1270 pPhyDrive->PhyDrive, pPhyDrive->VendorId, pPhyDrive->ProductId,
1271 GetHumanReadableGBSize(pPhyDrive->SizeInBytes));
1272
1273 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN);
1274
1275 Log("Lock disk for clean ............................. ");
1276
1277 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, FALSE, FALSE);
1278 if (hDrive == INVALID_HANDLE_VALUE)
1279 {
1280 Log("Failed to open physical disk");
1281 return 1;
1282 }
1283
1284 GetLettersBelongPhyDrive(pPhyDrive->PhyDrive, DriveLetters, sizeof(DriveLetters));
1285
1286 if (DriveLetters[0] == 0)
1287 {
1288 Log("No drive letter was assigned...");
1289 DriveName[0] = GetFirstUnusedDriveLetter();
1290 Log("GetFirstUnusedDriveLetter %C: ...", DriveName[0]);
1291 }
1292 else
1293 {
1294 // Unmount all mounted volumes that belong to this drive
1295 // Do it in reverse so that we always end on the first volume letter
1296 for (i = (int)strlen(DriveLetters); i > 0; i--)
1297 {
1298 DriveName[0] = DriveLetters[i - 1];
1299 bRet = DeleteVolumeMountPointA(DriveName);
1300 Log("Delete mountpoint %s ret:%u code:%u", DriveName, bRet, GetLastError());
1301 }
1302 }
1303
1304 MountDrive = DriveName[0];
1305 Log("Will use '%C:' as volume mountpoint", DriveName[0]);
1306
1307 // It kind of blows, but we have to relinquish access to the physical drive
1308 // for VDS to be able to delete the partitions that reside on it...
1309 DeviceIoControl(hDrive, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
1310 CHECK_CLOSE_HANDLE(hDrive);
1311
1312 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART);
1313
1314 if (!DeletePartitions(pPhyDrive->PhyDrive, FALSE))
1315 {
1316 Log("Notice: Could not delete partitions: %u", GetLastError());
1317 }
1318
1319 Log("Deleting all partitions ......................... OK");
1320
1321 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE);
1322
1323 Log("Lock disk for write ............................. ");
1324 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
1325 if (hDrive == INVALID_HANDLE_VALUE)
1326 {
1327 Log("Failed to GetPhysicalHandle for write.");
1328 rc = 1;
1329 goto End;
1330 }
1331
1332 // clear first and last 1MB space
1333 pTmpBuf = malloc(SIZE_1MB);
1334 if (!pTmpBuf)
1335 {
1336 Log("Failed to alloc memory.");
1337 rc = 1;
1338 goto End;
1339 }
1340 memset(pTmpBuf, 0, SIZE_1MB);
1341
1342 SET_FILE_POS(512);
1343 bRet = WriteFile(hDrive, pTmpBuf, SIZE_1MB - 512, &dwSize, NULL);
1344 Log("Write fisrt 1MB ret:%d size:%u err:%d", bRet, dwSize, LASTERR);
1345 if (!bRet)
1346 {
1347 rc = 1;
1348 goto End;
1349 }
1350
1351 SET_FILE_POS(SIZE_1MB);
1352 bRet = WriteFile(hDrive, pTmpBuf, SIZE_1MB, &dwSize, NULL);
1353 Log("Write 2nd 1MB ret:%d size:%u err:%d", bRet, dwSize, LASTERR);
1354 if (!bRet)
1355 {
1356 rc = 1;
1357 goto End;
1358 }
1359
1360 SET_FILE_POS(0);
1361 bRet = ReadFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL);
1362 Log("Read MBR ret:%d size:%u err:%d", bRet, dwSize, LASTERR);
1363 if (!bRet)
1364 {
1365 rc = 1;
1366 goto End;
1367 }
1368
1369 //clear boot code and partition table (reserved disk signature)
1370 memset(MBR.BootCode, 0, 440);
1371 memset(MBR.PartTbl, 0, sizeof(MBR.PartTbl));
1372
1373 VentoyFillLocation(pPhyDrive->SizeInBytes, 2048, (UINT32)(pPhyDrive->SizeInBytes / 512 - 2048), MBR.PartTbl);
1374
1375 MBR.PartTbl[0].Active = 0x80; // bootable
1376 MBR.PartTbl[0].FsFlag = 0x07; // exFAT/NTFS/HPFS
1377
1378 SET_FILE_POS(0);
1379 bRet = WriteFile(hDrive, &MBR, 512, &dwSize, NULL);
1380 Log("Write MBR ret:%d size:%u err:%d", bRet, dwSize, LASTERR);
1381 if (!bRet)
1382 {
1383 rc = 1;
1384 goto End;
1385 }
1386
1387 Log("Clear Ventoy successfully finished");
1388
1389 End:
1390
1391 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME);
1392
1393 if (pTmpBuf)
1394 {
1395 free(pTmpBuf);
1396 }
1397
1398 if (rc == 0)
1399 {
1400 Log("Mounting Ventoy Partition ....................... ");
1401 Sleep(1000);
1402
1403 state = 0;
1404 memset(DriveLetters, 0, sizeof(DriveLetters));
1405 GetLettersBelongPhyDrive(pPhyDrive->PhyDrive, DriveLetters, sizeof(DriveLetters));
1406 Log("Logical drive letter after write ventoy: <%s>", DriveLetters);
1407
1408 for (i = 0; i < sizeof(DriveLetters) && DriveLetters[i]; i++)
1409 {
1410 DriveName[0] = DriveLetters[i];
1411 Log("%s is ventoy part1, already mounted", DriveName);
1412 state = 1;
1413 }
1414
1415 if (state != 1)
1416 {
1417 Log("need to mount ventoy part1...");
1418 if (0 == GetVentoyVolumeName(pPhyDrive->PhyDrive, MBR.PartTbl[0].StartSectorId, DriveLetters, sizeof(DriveLetters), FALSE))
1419 {
1420 DriveName[0] = MountDrive;
1421 bRet = SetVolumeMountPointA(DriveName, DriveLetters);
1422 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName, DriveLetters, bRet, GetLastError());
1423
1424 *pDrvLetter = MountDrive;
1425 }
1426 else
1427 {
1428 Log("Failed to find ventoy volume");
1429 }
1430 }
1431
1432 Log("OK\n");
1433 }
1434 else
1435 {
1436 FindProcessOccupyDisk(hDrive, pPhyDrive);
1437 }
1438
1439 //Refresh Drive Layout
1440 DeviceIoControl(hDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwSize, NULL);
1441
1442 CHECK_CLOSE_HANDLE(hDrive);
1443 return rc;
1444 }
1445
1446 int InstallVentoy2PhyDrive(PHY_DRIVE_INFO *pPhyDrive)
1447 {
1448 int i;
1449 int rc = 0;
1450 int state = 0;
1451 HANDLE hDrive;
1452 DWORD dwSize;
1453 BOOL bRet;
1454 CHAR MountDrive;
1455 CHAR DriveName[] = "?:\\";
1456 CHAR DriveLetters[MAX_PATH] = { 0 };
1457 MBR_HEAD MBR;
1458
1459 Log("InstallVentoy2PhyDrive PhyDrive%d <<%s %s %dGB>>",
1460 pPhyDrive->PhyDrive, pPhyDrive->VendorId, pPhyDrive->ProductId,
1461 GetHumanReadableGBSize(pPhyDrive->SizeInBytes));
1462
1463 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN);
1464
1465 VentoyFillMBR(pPhyDrive->SizeInBytes, &MBR);
1466
1467 Log("Lock disk for clean ............................. ");
1468
1469 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, FALSE, FALSE);
1470 if (hDrive == INVALID_HANDLE_VALUE)
1471 {
1472 Log("Failed to open physical disk");
1473 return 1;
1474 }
1475
1476 GetLettersBelongPhyDrive(pPhyDrive->PhyDrive, DriveLetters, sizeof(DriveLetters));
1477
1478 if (DriveLetters[0] == 0)
1479 {
1480 Log("No drive letter was assigned...");
1481 DriveName[0] = GetFirstUnusedDriveLetter();
1482 Log("GetFirstUnusedDriveLetter %C: ...", DriveName[0]);
1483 }
1484 else
1485 {
1486 // Unmount all mounted volumes that belong to this drive
1487 // Do it in reverse so that we always end on the first volume letter
1488 for (i = (int)strlen(DriveLetters); i > 0; i--)
1489 {
1490 DriveName[0] = DriveLetters[i - 1];
1491 bRet = DeleteVolumeMountPointA(DriveName);
1492 Log("Delete mountpoint %s ret:%u code:%u", DriveName, bRet, GetLastError());
1493 }
1494 }
1495
1496 MountDrive = DriveName[0];
1497 Log("Will use '%C:' as volume mountpoint", DriveName[0]);
1498
1499 // It kind of blows, but we have to relinquish access to the physical drive
1500 // for VDS to be able to delete the partitions that reside on it...
1501 DeviceIoControl(hDrive, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
1502 CHECK_CLOSE_HANDLE(hDrive);
1503
1504 PROGRESS_BAR_SET_POS(PT_DEL_ALL_PART);
1505
1506 if (!DeletePartitions(pPhyDrive->PhyDrive, FALSE))
1507 {
1508 Log("Notice: Could not delete partitions: %u", GetLastError());
1509 }
1510
1511 Log("Deleting all partitions ......................... OK");
1512
1513 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE);
1514
1515 Log("Lock disk for write ............................. ");
1516 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
1517 if (hDrive == INVALID_HANDLE_VALUE)
1518 {
1519 Log("Failed to GetPhysicalHandle for write.");
1520 rc = 1;
1521 goto End;
1522 }
1523
1524 //Refresh Drive Layout
1525 DeviceIoControl(hDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwSize, NULL);
1526
1527 disk_io_set_param(hDrive, MBR.PartTbl[0].StartSectorId + MBR.PartTbl[0].SectorCount);
1528
1529 PROGRESS_BAR_SET_POS(PT_FORMAT_PART1);
1530
1531 Log("Formatting part1 exFAT ...");
1532 if (0 != FormatPart1exFAT(pPhyDrive->SizeInBytes))
1533 {
1534 log("FormatPart1exFAT failed.");
1535 rc = 1;
1536 goto End;
1537 }
1538
1539 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2);
1540 Log("Writing part2 FAT img ...");
1541 if (0 != FormatPart2Fat(hDrive, MBR.PartTbl[1].StartSectorId))
1542 {
1543 log("FormatPart2Fat failed.");
1544 rc = 1;
1545 goto End;
1546 }
1547
1548 PROGRESS_BAR_SET_POS(PT_WRITE_STG1_IMG);
1549 Log("Writting Boot Image ............................. ");
1550 if (WriteGrubStage1ToPhyDrive(hDrive) != 0)
1551 {
1552 log("WriteGrubStage1ToPhyDrive failed.");
1553 rc = 1;
1554 goto End;
1555 }
1556
1557 PROGRESS_BAR_SET_POS(PT_WRITE_PART_TABLE);
1558 Log("Writting Partition Table ........................ ");
1559 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
1560 if (!WriteFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL))
1561 {
1562 rc = 1;
1563 Log("Write MBR Failed, dwSize:%u ErrCode:%u", dwSize, GetLastError());
1564 goto End;
1565 }
1566
1567 Log("Write MBR OK ...");
1568
1569 //Refresh Drive Layout
1570 DeviceIoControl(hDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwSize, NULL);
1571
1572 End:
1573
1574 PROGRESS_BAR_SET_POS(PT_MOUNT_VOLUME);
1575
1576 if (rc == 0)
1577 {
1578 Log("Mounting Ventoy Partition ....................... ");
1579 Sleep(1000);
1580
1581 state = 0;
1582 memset(DriveLetters, 0, sizeof(DriveLetters));
1583 GetLettersBelongPhyDrive(pPhyDrive->PhyDrive, DriveLetters, sizeof(DriveLetters));
1584 Log("Logical drive letter after write ventoy: <%s>", DriveLetters);
1585
1586 for (i = 0; i < sizeof(DriveLetters) && DriveLetters[i]; i++)
1587 {
1588 DriveName[0] = DriveLetters[i];
1589 if (IsVentoyLogicalDrive(DriveName[0]))
1590 {
1591 Log("%s is ventoy part2, delete mountpoint", DriveName);
1592 DeleteVolumeMountPointA(DriveName);
1593 }
1594 else
1595 {
1596 Log("%s is ventoy part1, already mounted", DriveName);
1597 state = 1;
1598 }
1599 }
1600
1601 if (state != 1)
1602 {
1603 Log("need to mount ventoy part1...");
1604 if (0 == GetVentoyVolumeName(pPhyDrive->PhyDrive, MBR.PartTbl[0].StartSectorId, DriveLetters, sizeof(DriveLetters), FALSE))
1605 {
1606 DriveName[0] = MountDrive;
1607 bRet = SetVolumeMountPointA(DriveName, DriveLetters);
1608 Log("SetVolumeMountPoint <%s> <%s> bRet:%u code:%u", DriveName, DriveLetters, bRet, GetLastError());
1609 }
1610 else
1611 {
1612 Log("Failed to find ventoy volume");
1613 }
1614 }
1615 Log("OK\n");
1616 }
1617 else
1618 {
1619 FindProcessOccupyDisk(hDrive, pPhyDrive);
1620 }
1621
1622 CHECK_CLOSE_HANDLE(hDrive);
1623 return rc;
1624 }
1625
1626 int UpdateVentoy2PhyDrive(PHY_DRIVE_INFO *pPhyDrive)
1627 {
1628 int i;
1629 int rc = 0;
1630 BOOL ForceMBR = FALSE;
1631 HANDLE hVolume;
1632 HANDLE hDrive;
1633 DWORD Status;
1634 DWORD dwSize;
1635 BOOL bRet;
1636 CHAR DriveName[] = "?:\\";
1637 CHAR DriveLetters[MAX_PATH] = { 0 };
1638 UINT32 StartSector;
1639 UINT64 ReservedMB = 0;
1640 MBR_HEAD BootImg;
1641 MBR_HEAD MBR;
1642
1643 Log("UpdateVentoy2PhyDrive PhyDrive%d <<%s %s %dGB>>",
1644 pPhyDrive->PhyDrive, pPhyDrive->VendorId, pPhyDrive->ProductId,
1645 GetHumanReadableGBSize(pPhyDrive->SizeInBytes));
1646
1647 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_CLEAN);
1648
1649 Log("Lock disk for umount ............................ ");
1650
1651 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, FALSE, FALSE);
1652 if (hDrive == INVALID_HANDLE_VALUE)
1653 {
1654 Log("Failed to open physical disk");
1655 return 1;
1656 }
1657
1658 // Read MBR
1659 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
1660 ReadFile(hDrive, &MBR, sizeof(MBR), &dwSize, NULL);
1661
1662 StartSector = MBR.PartTbl[1].StartSectorId;
1663 Log("StartSector in PartTbl:%u", StartSector);
1664
1665 ReservedMB = (pPhyDrive->SizeInBytes / 512 - (StartSector + VENTOY_EFI_PART_SIZE / 512)) / 2048;
1666 Log("Reserved Disk Space:%u MB", ReservedMB);
1667
1668 GetLettersBelongPhyDrive(pPhyDrive->PhyDrive, DriveLetters, sizeof(DriveLetters));
1669
1670 if (DriveLetters[0] == 0)
1671 {
1672 Log("No drive letter was assigned...");
1673 }
1674 else
1675 {
1676 // Unmount all mounted volumes that belong to this drive
1677 // Do it in reverse so that we always end on the first volume letter
1678 for (i = (int)strlen(DriveLetters); i > 0; i--)
1679 {
1680 DriveName[0] = DriveLetters[i - 1];
1681 if (IsVentoyLogicalDrive(DriveName[0]))
1682 {
1683 Log("%s is ventoy logical drive", DriveName);
1684 bRet = DeleteVolumeMountPointA(DriveName);
1685 Log("Delete mountpoint %s ret:%u code:%u", DriveName, bRet, LASTERR);
1686 break;
1687 }
1688 }
1689 }
1690
1691 // It kind of blows, but we have to relinquish access to the physical drive
1692 // for VDS to be able to delete the partitions that reside on it...
1693 DeviceIoControl(hDrive, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
1694 CHECK_CLOSE_HANDLE(hDrive);
1695
1696 PROGRESS_BAR_SET_POS(PT_LOCK_FOR_WRITE);
1697
1698 Log("Lock disk for update ............................ ");
1699 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
1700 if (hDrive == INVALID_HANDLE_VALUE)
1701 {
1702 Log("Failed to GetPhysicalHandle for write.");
1703 rc = 1;
1704 goto End;
1705 }
1706
1707 PROGRESS_BAR_SET_POS(PT_LOCK_VOLUME);
1708
1709 Log("Lock volume for update .......................... ");
1710 hVolume = INVALID_HANDLE_VALUE;
1711 Status = GetVentoyVolumeName(pPhyDrive->PhyDrive, MBR.PartTbl[1].StartSectorId, DriveLetters, sizeof(DriveLetters), TRUE);
1712 if (ERROR_SUCCESS == Status)
1713 {
1714 Log("Now lock and dismount volume <%s>", DriveLetters);
1715 hVolume = CreateFileA(DriveLetters,
1716 GENERIC_READ | GENERIC_WRITE,
1717 FILE_SHARE_READ,
1718 NULL,
1719 OPEN_EXISTING,
1720 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH,
1721 NULL);
1722
1723 if (hVolume == INVALID_HANDLE_VALUE)
1724 {
1725 Log("Failed to create file volume, errcode:%u", LASTERR);
1726 rc = 1;
1727 goto End;
1728 }
1729
1730 bRet = DeviceIoControl(hVolume, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
1731 Log("FSCTL_LOCK_VOLUME bRet:%u code:%u", bRet, LASTERR);
1732
1733 bRet = DeviceIoControl(hVolume, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
1734 Log("FSCTL_DISMOUNT_VOLUME bRet:%u code:%u", bRet, LASTERR);
1735 }
1736 else if (ERROR_NOT_FOUND == Status)
1737 {
1738 Log("Volume not found, maybe not supported");
1739 }
1740 else
1741 {
1742 rc = 1;
1743 goto End;
1744 }
1745
1746
1747 if (!TryWritePart2(hDrive, StartSector))
1748 {
1749 ForceMBR = TRUE;
1750 Log("Try write failed, now delete partition 2...");
1751
1752 CHECK_CLOSE_HANDLE(hDrive);
1753
1754 Log("Now delete partition 2...");
1755 DeletePartitions(pPhyDrive->PhyDrive, TRUE);
1756
1757 hDrive = GetPhysicalHandle(pPhyDrive->PhyDrive, TRUE, TRUE, FALSE);
1758 if (hDrive == INVALID_HANDLE_VALUE)
1759 {
1760 Log("Failed to GetPhysicalHandle for write.");
1761 rc = 1;
1762 goto End;
1763 }
1764 }
1765
1766
1767 PROGRESS_BAR_SET_POS(PT_FORMAT_PART2);
1768
1769 Log("Write Ventoy to disk ............................ ");
1770 if (0 != FormatPart2Fat(hDrive, StartSector))
1771 {
1772 rc = 1;
1773 goto End;
1774 }
1775
1776 if (hVolume != INVALID_HANDLE_VALUE)
1777 {
1778 bRet = DeviceIoControl(hVolume, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &dwSize, NULL);
1779 Log("FSCTL_UNLOCK_VOLUME bRet:%u code:%u", bRet, LASTERR);
1780 CHECK_CLOSE_HANDLE(hVolume);
1781 }
1782
1783 Log("Updating Boot Image ............................. ");
1784 if (WriteGrubStage1ToPhyDrive(hDrive) != 0)
1785 {
1786 rc = 1;
1787 goto End;
1788 }
1789
1790 // Boot Image
1791 VentoyGetLocalBootImg(&BootImg);
1792
1793 // Use Old UUID
1794 memcpy(BootImg.BootCode + 0x180, MBR.BootCode + 0x180, 16);
1795
1796 if (ForceMBR == FALSE && memcmp(BootImg.BootCode, MBR.BootCode, 440) == 0)
1797 {
1798 Log("Boot image has no difference, no need to write.");
1799 }
1800 else
1801 {
1802 Log("Boot image need to write %u.", ForceMBR);
1803
1804 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
1805
1806 memcpy(MBR.BootCode, BootImg.BootCode, 440);
1807 bRet = WriteFile(hDrive, &MBR, 512, &dwSize, NULL);
1808 Log("Write Boot Image ret:%u dwSize:%u Error:%u", bRet, dwSize, LASTERR);
1809 }
1810
1811 if (0x00 == MBR.PartTbl[0].Active && 0x80 == MBR.PartTbl[1].Active)
1812 {
1813 Log("Need to chage 1st partition active and 2nd partition inactive.");
1814
1815 MBR.PartTbl[0].Active = 0x80;
1816 MBR.PartTbl[1].Active = 0x00;
1817
1818 SetFilePointer(hDrive, 0, NULL, FILE_BEGIN);
1819 bRet = WriteFile(hDrive, &MBR, 512, &dwSize, NULL);
1820 Log("Write NEW MBR ret:%u dwSize:%u Error:%u", bRet, dwSize, LASTERR);
1821 }
1822
1823 //Refresh Drive Layout
1824 DeviceIoControl(hDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, &dwSize, NULL);
1825
1826 End:
1827
1828 if (rc == 0)
1829 {
1830 Log("OK");
1831 }
1832 else
1833 {
1834 FindProcessOccupyDisk(hDrive, pPhyDrive);
1835 }
1836
1837 CHECK_CLOSE_HANDLE(hDrive);
1838
1839 return rc;
1840 }
1841
1842