]> glassweightruler.freedombox.rocks Git - Ventoy.git/blob - Ventoy2Disk/Ventoy2Disk/Utility.c
Change the MBR partition type to 0x0C when select FAT32 for installation.
[Ventoy.git] / Ventoy2Disk / Ventoy2Disk / Utility.c
1 /******************************************************************************
2 * Utility.c
3 *
4 * Copyright (c) 2021, 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 #include <Windows.h>
22 #include "Ventoy2Disk.h"
23
24 void TraceOut(const char *Fmt, ...)
25 {
26 va_list Arg;
27 int Len = 0;
28 FILE *File = NULL;
29 char szBuf[1024];
30
31 va_start(Arg, Fmt);
32 Len += vsnprintf_s(szBuf + Len, sizeof(szBuf)-Len, sizeof(szBuf)-Len, Fmt, Arg);
33 va_end(Arg);
34
35 fopen_s(&File, VENTOY_FILE_LOG, "a+");
36 if (File)
37 {
38 fwrite(szBuf, 1, Len, File);
39 fclose(File);
40 }
41 }
42
43 void Log(const char *Fmt, ...)
44 {
45 va_list Arg;
46 int Len = 0;
47 FILE *File = NULL;
48 SYSTEMTIME Sys;
49 char szBuf[1024];
50
51 GetLocalTime(&Sys);
52 Len += safe_sprintf(szBuf,
53 "[%4d/%02d/%02d %02d:%02d:%02d.%03d] ",
54 Sys.wYear, Sys.wMonth, Sys.wDay,
55 Sys.wHour, Sys.wMinute, Sys.wSecond,
56 Sys.wMilliseconds);
57
58 va_start(Arg, Fmt);
59 Len += vsnprintf_s(szBuf + Len, sizeof(szBuf)-Len, sizeof(szBuf)-Len, Fmt, Arg);
60 va_end(Arg);
61
62 //printf("%s\n", szBuf);
63
64 #if 1
65 fopen_s(&File, VENTOY_FILE_LOG, "a+");
66 if (File)
67 {
68 fwrite(szBuf, 1, Len, File);
69 fwrite("\n", 1, 1, File);
70 fclose(File);
71 }
72 #endif
73
74 }
75
76 const char* GUID2String(void *guid, char *buf, int len)
77 {
78 GUID* pGUID = (GUID*)guid;
79 sprintf_s(buf, len, "{%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
80 pGUID->Data1, pGUID->Data2, pGUID->Data3,
81 pGUID->Data4[0], pGUID->Data4[1],
82 pGUID->Data4[2], pGUID->Data4[3], pGUID->Data4[4], pGUID->Data4[5], pGUID->Data4[6], pGUID->Data4[7]
83 );
84 return buf;
85 }
86
87 BOOL IsPathExist(BOOL Dir, const char *Fmt, ...)
88 {
89 va_list Arg;
90 HANDLE hFile;
91 DWORD Attr;
92 CHAR FilePath[MAX_PATH];
93
94 va_start(Arg, Fmt);
95 vsnprintf_s(FilePath, sizeof(FilePath), sizeof(FilePath), Fmt, Arg);
96 va_end(Arg);
97
98 hFile = CreateFileA(FilePath, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
99 if (INVALID_HANDLE_VALUE == hFile)
100 {
101 return FALSE;
102 }
103
104 CloseHandle(hFile);
105
106 Attr = GetFileAttributesA(FilePath);
107
108 if (Dir)
109 {
110 if ((Attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
111 {
112 return FALSE;
113 }
114 }
115 else
116 {
117 if (Attr & FILE_ATTRIBUTE_DIRECTORY)
118 {
119 return FALSE;
120 }
121 }
122
123 return TRUE;
124 }
125
126 int SaveBufToFile(const CHAR *FileName, const void *Buffer, int BufLen)
127 {
128 FILE *File = NULL;
129 void *Data = NULL;
130
131 fopen_s(&File, FileName, "wb");
132 if (File == NULL)
133 {
134 Log("Failed to open file %s", FileName);
135 return 1;
136 }
137
138 fwrite(Buffer, 1, BufLen, File);
139 fclose(File);
140 return 0;
141 }
142
143 int ReadWholeFileToBuf(const CHAR *FileName, int ExtLen, void **Bufer, int *BufLen)
144 {
145 int FileSize;
146 FILE *File = NULL;
147 void *Data = NULL;
148
149 fopen_s(&File, FileName, "rb");
150 if (File == NULL)
151 {
152 Log("Failed to open file %s", FileName);
153 return 1;
154 }
155
156 fseek(File, 0, SEEK_END);
157 FileSize = (int)ftell(File);
158
159 Data = malloc(FileSize + ExtLen);
160 if (!Data)
161 {
162 fclose(File);
163 return 1;
164 }
165
166 fseek(File, 0, SEEK_SET);
167 fread(Data, 1, FileSize, File);
168
169 fclose(File);
170
171 *Bufer = Data;
172 *BufLen = FileSize;
173
174 return 0;
175 }
176
177 const CHAR* GetLocalVentoyVersion(void)
178 {
179 int rc;
180 int FileSize;
181 CHAR *Pos = NULL;
182 CHAR *Buf = NULL;
183 static CHAR LocalVersion[64] = { 0 };
184
185 if (LocalVersion[0] == 0)
186 {
187 rc = ReadWholeFileToBuf(VENTOY_FILE_VERSION, 1, (void **)&Buf, &FileSize);
188 if (rc)
189 {
190 return "";
191 }
192 Buf[FileSize] = 0;
193
194 for (Pos = Buf; *Pos; Pos++)
195 {
196 if (*Pos == '\r' || *Pos == '\n')
197 {
198 *Pos = 0;
199 break;
200 }
201 }
202
203 safe_sprintf(LocalVersion, "%s", Buf);
204 free(Buf);
205 }
206
207 return LocalVersion;
208 }
209
210 const CHAR* ParseVentoyVersionFromString(CHAR *Buf)
211 {
212 CHAR *Pos = NULL;
213 CHAR *End = NULL;
214 static CHAR LocalVersion[64] = { 0 };
215
216 Pos = strstr(Buf, "VENTOY_VERSION=");
217 if (Pos)
218 {
219 Pos += strlen("VENTOY_VERSION=");
220 if (*Pos == '"')
221 {
222 Pos++;
223 }
224
225 End = Pos;
226 while (*End != 0 && *End != '"' && *End != '\r' && *End != '\n')
227 {
228 End++;
229 }
230
231 *End = 0;
232
233 safe_sprintf(LocalVersion, "%s", Pos);
234 return LocalVersion;
235 }
236
237 return "";
238 }
239
240 BOOL IsWow64(void)
241 {
242 typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
243 LPFN_ISWOW64PROCESS fnIsWow64Process;
244 BOOL bIsWow64 = FALSE;
245 CHAR Wow64Dir[MAX_PATH];
246
247 fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandleA("kernel32"), "IsWow64Process");
248 if (NULL != fnIsWow64Process)
249 {
250 fnIsWow64Process(GetCurrentProcess(), &bIsWow64);
251 }
252
253 if (!bIsWow64)
254 {
255 if (GetSystemWow64DirectoryA(Wow64Dir, sizeof(Wow64Dir)))
256 {
257 Log("GetSystemWow64DirectoryA=<%s>", Wow64Dir);
258 bIsWow64 = TRUE;
259 }
260 }
261
262 return bIsWow64;
263 }
264
265 /*
266 * Some code and functions in the file are copied from rufus.
267 * https://github.com/pbatard/rufus
268 */
269
270 /* Windows versions */
271 enum WindowsVersion {
272 WINDOWS_UNDEFINED = -1,
273 WINDOWS_UNSUPPORTED = 0,
274 WINDOWS_XP = 0x51,
275 WINDOWS_2003 = 0x52, // Also XP_64
276 WINDOWS_VISTA = 0x60, // Also Server 2008
277 WINDOWS_7 = 0x61, // Also Server 2008_R2
278 WINDOWS_8 = 0x62, // Also Server 2012
279 WINDOWS_8_1 = 0x63, // Also Server 2012_R2
280 WINDOWS_10_PREVIEW1 = 0x64,
281 WINDOWS_10 = 0xA0, // Also Server 2016, also Server 2019
282 WINDOWS_11 = 0xB0, // Also Server 2022
283 WINDOWS_MAX
284 };
285
286 static const char* GetEdition(DWORD ProductType)
287 {
288 // From: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getproductinfo
289 // These values can be found in the winnt.h header.
290 switch (ProductType) {
291 case 0x00000000: return ""; // Undefined
292 case 0x00000001: return "Ultimate";
293 case 0x00000002: return "Home Basic";
294 case 0x00000003: return "Home Premium";
295 case 0x00000004: return "Enterprise";
296 case 0x00000005: return "Home Basic N";
297 case 0x00000006: return "Business";
298 case 0x00000007: return "Server Standard";
299 case 0x00000008: return "Server Datacenter";
300 case 0x00000009: return "Smallbusiness Server";
301 case 0x0000000A: return "Server Enterprise";
302 case 0x0000000B: return "Starter";
303 case 0x0000000C: return "Server Datacenter (Core)";
304 case 0x0000000D: return "Server Standard (Core)";
305 case 0x0000000E: return "Server Enterprise (Core)";
306 case 0x00000010: return "Business N";
307 case 0x00000011: return "Web Server";
308 case 0x00000012: return "HPC Edition";
309 case 0x00000013: return "Storage Server (Essentials)";
310 case 0x0000001A: return "Home Premium N";
311 case 0x0000001B: return "Enterprise N";
312 case 0x0000001C: return "Ultimate N";
313 case 0x00000022: return "Home Server";
314 case 0x00000024: return "Server Standard without Hyper-V";
315 case 0x00000025: return "Server Datacenter without Hyper-V";
316 case 0x00000026: return "Server Enterprise without Hyper-V";
317 case 0x00000027: return "Server Datacenter without Hyper-V (Core)";
318 case 0x00000028: return "Server Standard without Hyper-V (Core)";
319 case 0x00000029: return "Server Enterprise without Hyper-V (Core)";
320 case 0x0000002A: return "Hyper-V Server";
321 case 0x0000002F: return "Starter N";
322 case 0x00000030: return "Pro";
323 case 0x00000031: return "Pro N";
324 case 0x00000034: return "Server Solutions Premium";
325 case 0x00000035: return "Server Solutions Premium (Core)";
326 case 0x00000040: return "Server Hyper Core V";
327 case 0x00000042: return "Starter E";
328 case 0x00000043: return "Home Basic E";
329 case 0x00000044: return "Premium E";
330 case 0x00000045: return "Pro E";
331 case 0x00000046: return "Enterprise E";
332 case 0x00000047: return "Ultimate E";
333 case 0x00000048: return "Enterprise (Eval)";
334 case 0x0000004F: return "Server Standard (Eval)";
335 case 0x00000050: return "Server Datacenter (Eval)";
336 case 0x00000054: return "Enterprise N (Eval)";
337 case 0x00000057: return "Thin PC";
338 case 0x00000058: case 0x00000059: case 0x0000005A: case 0x0000005B: case 0x0000005C: return "Embedded";
339 case 0x00000062: return "Home N";
340 case 0x00000063: return "Home China";
341 case 0x00000064: return "Home Single Language";
342 case 0x00000065: return "Home";
343 case 0x00000067: return "Pro with Media Center";
344 case 0x00000069: case 0x0000006A: case 0x0000006B: case 0x0000006C: return "Embedded";
345 case 0x0000006F: return "Home Connected";
346 case 0x00000070: return "Pro Student";
347 case 0x00000071: return "Home Connected N";
348 case 0x00000072: return "Pro Student N";
349 case 0x00000073: return "Home Connected Single Language";
350 case 0x00000074: return "Home Connected China";
351 case 0x00000079: return "Education";
352 case 0x0000007A: return "Education N";
353 case 0x0000007D: return "Enterprise LTSB";
354 case 0x0000007E: return "Enterprise LTSB N";
355 case 0x0000007F: return "Pro S";
356 case 0x00000080: return "Pro S N";
357 case 0x00000081: return "Enterprise LTSB (Eval)";
358 case 0x00000082: return "Enterprise LTSB N (Eval)";
359 case 0x0000008A: return "Pro Single Language";
360 case 0x0000008B: return "Pro China";
361 case 0x0000008C: return "Enterprise Subscription";
362 case 0x0000008D: return "Enterprise Subscription N";
363 case 0x00000091: return "Server Datacenter SA (Core)";
364 case 0x00000092: return "Server Standard SA (Core)";
365 case 0x00000095: return "Utility VM";
366 case 0x000000A1: return "Pro for Workstations";
367 case 0x000000A2: return "Pro for Workstations N";
368 case 0x000000A4: return "Pro for Education";
369 case 0x000000A5: return "Pro for Education N";
370 case 0x000000AB: return "Enterprise G"; // I swear Microsoft are just making up editions...
371 case 0x000000AC: return "Enterprise G N";
372 case 0x000000B6: return "Home OS";
373 case 0x000000B7: return "Cloud E";
374 case 0x000000B8: return "Cloud E N";
375 case 0x000000BD: return "Lite";
376 case 0xABCDABCD: return "(Unlicensed)";
377 default: return "(Unknown Edition)";
378 }
379 }
380
381 #define is_x64 IsWow64
382 #define static_strcpy safe_strcpy
383 #define REGKEY_HKCU HKEY_CURRENT_USER
384 #define REGKEY_HKLM HKEY_LOCAL_MACHINE
385 static int nWindowsVersion = WINDOWS_UNDEFINED;
386 static int nWindowsBuildNumber = -1;
387 static char WindowsVersionStr[128] = "";
388
389 /* Helpers for 32 bit registry operations */
390
391 /*
392 * Read a generic registry key value. If a short key_name is used, assume that
393 * it belongs to the application and create the app subkey if required
394 */
395 static __inline BOOL _GetRegistryKey(HKEY key_root, const char* key_name, DWORD reg_type,
396 LPBYTE dest, DWORD dest_size)
397 {
398 const char software_prefix[] = "SOFTWARE\\";
399 char long_key_name[MAX_PATH] = { 0 };
400 BOOL r = FALSE;
401 size_t i;
402 LONG s;
403 HKEY hSoftware = NULL, hApp = NULL;
404 DWORD dwType = -1, dwSize = dest_size;
405
406 memset(dest, 0, dest_size);
407
408 if (key_name == NULL)
409 return FALSE;
410
411 for (i = strlen(key_name); i>0; i--) {
412 if (key_name[i] == '\\')
413 break;
414 }
415
416 if (i > 0) {
417 // Prefix with "SOFTWARE" if needed
418 if (_strnicmp(key_name, software_prefix, sizeof(software_prefix)-1) != 0) {
419 if (i + sizeof(software_prefix) >= sizeof(long_key_name))
420 return FALSE;
421 strcpy_s(long_key_name, sizeof(long_key_name), software_prefix);
422 strcat_s(long_key_name, sizeof(long_key_name), key_name);
423 long_key_name[sizeof(software_prefix)+i - 1] = 0;
424 }
425 else {
426 if (i >= sizeof(long_key_name))
427 return FALSE;
428 static_strcpy(long_key_name, key_name);
429 long_key_name[i] = 0;
430 }
431 i++;
432 if (RegOpenKeyExA(key_root, long_key_name, 0, KEY_READ, &hApp) != ERROR_SUCCESS) {
433 hApp = NULL;
434 goto out;
435 }
436 }
437 else {
438 if (RegOpenKeyExA(key_root, "SOFTWARE", 0, KEY_READ | KEY_CREATE_SUB_KEY, &hSoftware) != ERROR_SUCCESS) {
439 hSoftware = NULL;
440 goto out;
441 }
442 }
443
444 s = RegQueryValueExA(hApp, &key_name[i], NULL, &dwType, (LPBYTE)dest, &dwSize);
445 // No key means default value of 0 or empty string
446 if ((s == ERROR_FILE_NOT_FOUND) || ((s == ERROR_SUCCESS) && (dwType == reg_type) && (dwSize > 0))) {
447 r = TRUE;
448 }
449 out:
450 if (hSoftware != NULL)
451 RegCloseKey(hSoftware);
452 if (hApp != NULL)
453 RegCloseKey(hApp);
454 return r;
455 }
456
457 #define GetRegistryKey32(root, key, pval) _GetRegistryKey(root, key, REG_DWORD, (LPBYTE)pval, sizeof(DWORD))
458 static __inline INT32 ReadRegistryKey32(HKEY root, const char* key) {
459 DWORD val;
460 GetRegistryKey32(root, key, &val);
461 return (INT32)val;
462 }
463
464 /*
465 * Modified from smartmontools' os_win32.cpp
466 */
467 void GetWindowsVersion(void)
468 {
469 OSVERSIONINFOEXA vi, vi2;
470 DWORD dwProductType;
471 const char* w = 0;
472 const char* w64 = "32 bit";
473 char *vptr;
474 size_t vlen;
475 unsigned major, minor;
476 ULONGLONG major_equal, minor_equal;
477 BOOL ws;
478
479 nWindowsVersion = WINDOWS_UNDEFINED;
480 static_strcpy(WindowsVersionStr, "Windows Undefined");
481
482 // suppress the C4996 warning for GetVersionExA
483 #pragma warning(push)
484 #pragma warning(disable:4996)
485
486 memset(&vi, 0, sizeof(vi));
487 vi.dwOSVersionInfoSize = sizeof(vi);
488 if (!GetVersionExA((OSVERSIONINFOA *)&vi)) {
489 memset(&vi, 0, sizeof(vi));
490 vi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOA);
491 if (!GetVersionExA((OSVERSIONINFOA *)&vi))
492 return;
493 }
494
495 #pragma warning(pop)
496
497 if (vi.dwPlatformId == VER_PLATFORM_WIN32_NT) {
498
499 if (vi.dwMajorVersion > 6 || (vi.dwMajorVersion == 6 && vi.dwMinorVersion >= 2)) {
500 // Starting with Windows 8.1 Preview, GetVersionEx() does no longer report the actual OS version
501 // See: http://msdn.microsoft.com/en-us/library/windows/desktop/dn302074.aspx
502 // And starting with Windows 10 Preview 2, Windows enforces the use of the application/supportedOS
503 // manifest in order for VerSetConditionMask() to report the ACTUAL OS major and minor...
504
505 major_equal = VerSetConditionMask(0, VER_MAJORVERSION, VER_EQUAL);
506 for (major = vi.dwMajorVersion; major <= 9; major++) {
507 memset(&vi2, 0, sizeof(vi2));
508 vi2.dwOSVersionInfoSize = sizeof(vi2); vi2.dwMajorVersion = major;
509 if (!VerifyVersionInfoA(&vi2, VER_MAJORVERSION, major_equal))
510 continue;
511 if (vi.dwMajorVersion < major) {
512 vi.dwMajorVersion = major; vi.dwMinorVersion = 0;
513 }
514
515 minor_equal = VerSetConditionMask(0, VER_MINORVERSION, VER_EQUAL);
516 for (minor = vi.dwMinorVersion; minor <= 9; minor++) {
517 memset(&vi2, 0, sizeof(vi2)); vi2.dwOSVersionInfoSize = sizeof(vi2);
518 vi2.dwMinorVersion = minor;
519 if (!VerifyVersionInfoA(&vi2, VER_MINORVERSION, minor_equal))
520 continue;
521 vi.dwMinorVersion = minor;
522 break;
523 }
524
525 break;
526 }
527 }
528
529 if (vi.dwMajorVersion <= 0xf && vi.dwMinorVersion <= 0xf) {
530 ws = (vi.wProductType <= VER_NT_WORKSTATION);
531 nWindowsVersion = vi.dwMajorVersion << 4 | vi.dwMinorVersion;
532 switch (nWindowsVersion) {
533 case WINDOWS_XP: w = "XP";
534 break;
535 case WINDOWS_2003: w = (ws ? "XP_64" : (!GetSystemMetrics(89) ? "Server 2003" : "Server 2003_R2"));
536 break;
537 case WINDOWS_VISTA: w = (ws ? "Vista" : "Server 2008");
538 break;
539 case WINDOWS_7: w = (ws ? "7" : "Server 2008_R2");
540 break;
541 case WINDOWS_8: w = (ws ? "8" : "Server 2012");
542 break;
543 case WINDOWS_8_1: w = (ws ? "8.1" : "Server 2012_R2");
544 break;
545 case WINDOWS_10_PREVIEW1: w = (ws ? "10 (Preview 1)" : "Server 10 (Preview 1)");
546 break;
547 // Starting with Windows 10 Preview 2, the major is the same as the public-facing version
548 case WINDOWS_10:
549 if (vi.dwBuildNumber < 20000) {
550 w = (ws ? "10" : ((vi.dwBuildNumber < 17763) ? "Server 2016" : "Server 2019"));
551 break;
552 }
553 nWindowsVersion = WINDOWS_11;
554 // Fall through
555 case WINDOWS_11: w = (ws ? "11" : "Server 2022");
556 break;
557 default:
558 if (nWindowsVersion < WINDOWS_XP)
559 nWindowsVersion = WINDOWS_UNSUPPORTED;
560 else
561 w = "12 or later";
562 break;
563 }
564 }
565 }
566
567 if (is_x64())
568 w64 = "64-bit";
569
570 GetProductInfo(vi.dwMajorVersion, vi.dwMinorVersion, vi.wServicePackMajor, vi.wServicePackMinor, &dwProductType);
571 vptr = WindowsVersionStr;
572 vlen = sizeof(WindowsVersionStr) - 1;
573
574 if (!w)
575 sprintf_s(vptr, vlen, "%s %u.%u %s", (vi.dwPlatformId == VER_PLATFORM_WIN32_NT ? "NT" : "??"),
576 (unsigned)vi.dwMajorVersion, (unsigned)vi.dwMinorVersion, w64);
577 else if (vi.wServicePackMinor)
578 sprintf_s(vptr, vlen, "%s SP%u.%u %s", w, vi.wServicePackMajor, vi.wServicePackMinor, w64);
579 else if (vi.wServicePackMajor)
580 sprintf_s(vptr, vlen, "%s SP%u %s", w, vi.wServicePackMajor, w64);
581 else
582 sprintf_s(vptr, vlen, "%s%s%s, %s",
583 w, (dwProductType != PRODUCT_UNDEFINED) ? " " : "", GetEdition(dwProductType), w64);
584
585 // Add the build number (including UBR if available) for Windows 8.0 and later
586 nWindowsBuildNumber = vi.dwBuildNumber;
587 if (nWindowsVersion >= 0x62) {
588 int nUbr = ReadRegistryKey32(REGKEY_HKLM, "Software\\Microsoft\\Windows NT\\CurrentVersion\\UBR");
589 vptr = WindowsVersionStr + strlen(WindowsVersionStr);
590 vlen = sizeof(WindowsVersionStr) - strlen(WindowsVersionStr) - 1;
591 if (nUbr > 0)
592 sprintf_s(vptr, vlen, " (Build %d.%d)", nWindowsBuildNumber, nUbr);
593 else
594 sprintf_s(vptr, vlen, " (Build %d)", nWindowsBuildNumber);
595 }
596 }
597
598
599
600 void DumpWindowsVersion(void)
601 {
602 GetWindowsVersion();
603 Log("Windows Version: <<Windows %s>>", WindowsVersionStr);
604 return;
605 }
606
607
608 BOOL IsVentoyLogicalDrive(CHAR DriveLetter)
609 {
610 int i;
611 CONST CHAR *Files[] =
612 {
613 "EFI\\BOOT\\BOOTX64.EFI",
614 "grub\\themes\\ventoy\\theme.txt",
615 "ventoy\\ventoy.cpio",
616 };
617
618 for (i = 0; i < sizeof(Files) / sizeof(Files[0]); i++)
619 {
620 if (!IsFileExist("%C:\\%s", DriveLetter, Files[i]))
621 {
622 return FALSE;
623 }
624 }
625
626 return TRUE;
627 }
628
629
630 int VentoyFillMBRLocation(UINT64 DiskSizeInBytes, UINT32 StartSectorId, UINT32 SectorCount, PART_TABLE *Table)
631 {
632 BYTE Head;
633 BYTE Sector;
634 BYTE nSector = 63;
635 BYTE nHead = 8;
636 UINT32 Cylinder;
637 UINT32 EndSectorId;
638
639 while (nHead != 0 && (DiskSizeInBytes / 512 / nSector / nHead) > 1024)
640 {
641 nHead = (BYTE)nHead * 2;
642 }
643
644 if (nHead == 0)
645 {
646 nHead = 255;
647 }
648
649 Cylinder = StartSectorId / nSector / nHead;
650 Head = StartSectorId / nSector % nHead;
651 Sector = StartSectorId % nSector + 1;
652
653 Table->StartHead = Head;
654 Table->StartSector = Sector;
655 Table->StartCylinder = Cylinder;
656
657 EndSectorId = StartSectorId + SectorCount - 1;
658 Cylinder = EndSectorId / nSector / nHead;
659 Head = EndSectorId / nSector % nHead;
660 Sector = EndSectorId % nSector + 1;
661
662 Table->EndHead = Head;
663 Table->EndSector = Sector;
664 Table->EndCylinder = Cylinder;
665
666 Table->StartSectorId = StartSectorId;
667 Table->SectorCount = SectorCount;
668
669 return 0;
670 }
671
672 int VentoyFillMBR(UINT64 DiskSizeBytes, MBR_HEAD *pMBR, int PartStyle, UINT8 FsFlag)
673 {
674 GUID Guid;
675 int ReservedValue;
676 UINT32 DiskSignature;
677 UINT32 DiskSectorCount;
678 UINT32 PartSectorCount;
679 UINT32 PartStartSector;
680 UINT32 ReservedSector;
681
682 VentoyGetLocalBootImg(pMBR);
683
684 CoCreateGuid(&Guid);
685
686 memcpy(&DiskSignature, &Guid, sizeof(UINT32));
687
688 Log("Disk signature: 0x%08x", DiskSignature);
689
690 *((UINT32 *)(pMBR->BootCode + 0x1B8)) = DiskSignature;
691 memcpy(pMBR->BootCode + 0x180, &Guid, 16);
692
693 if (DiskSizeBytes / 512 > 0xFFFFFFFF)
694 {
695 DiskSectorCount = 0xFFFFFFFF;
696 }
697 else
698 {
699 DiskSectorCount = (UINT32)(DiskSizeBytes / 512);
700 }
701
702 ReservedValue = GetReservedSpaceInMB();
703 if (ReservedValue <= 0)
704 {
705 ReservedSector = 0;
706 }
707 else
708 {
709 ReservedSector = (UINT32)(ReservedValue * 2048);
710 }
711
712 if (PartStyle)
713 {
714 ReservedSector += 33; // backup GPT part table
715 }
716
717 // check aligned with 4KB
718 if (IsPartNeed4KBAlign())
719 {
720 UINT64 sectors = DiskSizeBytes / 512;
721 if (sectors % 8)
722 {
723 Log("Disk need to align with 4KB %u", (UINT32)(sectors % 8));
724 ReservedSector += (UINT32)(sectors % 8);
725 }
726 }
727
728 Log("ReservedSector: %u", ReservedSector);
729
730 //Part1
731 PartStartSector = VENTOY_PART1_START_SECTOR;
732 PartSectorCount = DiskSectorCount - ReservedSector - VENTOY_EFI_PART_SIZE / 512 - PartStartSector;
733 VentoyFillMBRLocation(DiskSizeBytes, PartStartSector, PartSectorCount, pMBR->PartTbl);
734
735 pMBR->PartTbl[0].Active = 0x80; // bootable
736 pMBR->PartTbl[0].FsFlag = FsFlag; // File system flag 07:exFAT/NTFS/HPFS 0C:FAT32
737
738 //Part2
739 PartStartSector += PartSectorCount;
740 PartSectorCount = VENTOY_EFI_PART_SIZE / 512;
741 VentoyFillMBRLocation(DiskSizeBytes, PartStartSector, PartSectorCount, pMBR->PartTbl + 1);
742
743 pMBR->PartTbl[1].Active = 0x00;
744 pMBR->PartTbl[1].FsFlag = 0xEF; // EFI System Partition
745
746 pMBR->Byte55 = 0x55;
747 pMBR->ByteAA = 0xAA;
748
749 return 0;
750 }
751
752
753 static int VentoyFillProtectMBR(UINT64 DiskSizeBytes, MBR_HEAD *pMBR)
754 {
755 GUID Guid;
756 UINT32 DiskSignature;
757 UINT64 DiskSectorCount;
758
759 VentoyGetLocalBootImg(pMBR);
760
761 CoCreateGuid(&Guid);
762
763 memcpy(&DiskSignature, &Guid, sizeof(UINT32));
764
765 Log("Disk signature: 0x%08x", DiskSignature);
766
767 *((UINT32 *)(pMBR->BootCode + 0x1B8)) = DiskSignature;
768 memcpy(pMBR->BootCode + 0x180, &Guid, 16);
769
770 DiskSectorCount = DiskSizeBytes / 512 - 1;
771 if (DiskSectorCount > 0xFFFFFFFF)
772 {
773 DiskSectorCount = 0xFFFFFFFF;
774 }
775
776 memset(pMBR->PartTbl, 0, sizeof(pMBR->PartTbl));
777
778 pMBR->PartTbl[0].Active = 0x00;
779 pMBR->PartTbl[0].FsFlag = 0xee; // EE
780
781 pMBR->PartTbl[0].StartHead = 0;
782 pMBR->PartTbl[0].StartSector = 1;
783 pMBR->PartTbl[0].StartCylinder = 0;
784 pMBR->PartTbl[0].EndHead = 254;
785 pMBR->PartTbl[0].EndSector = 63;
786 pMBR->PartTbl[0].EndCylinder = 1023;
787
788 pMBR->PartTbl[0].StartSectorId = 1;
789 pMBR->PartTbl[0].SectorCount = (UINT32)DiskSectorCount;
790
791 pMBR->Byte55 = 0x55;
792 pMBR->ByteAA = 0xAA;
793
794 pMBR->BootCode[92] = 0x22;
795
796 return 0;
797 }
798
799 int VentoyFillWholeGpt(UINT64 DiskSizeBytes, VTOY_GPT_INFO *pInfo)
800 {
801 UINT64 Part1SectorCount = 0;
802 UINT64 DiskSectorCount = DiskSizeBytes / 512;
803 VTOY_GPT_HDR *Head = &pInfo->Head;
804 VTOY_GPT_PART_TBL *Table = pInfo->PartTbl;
805 static GUID WindowsDataPartType = { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
806
807 VentoyFillProtectMBR(DiskSizeBytes, &pInfo->MBR);
808
809 Part1SectorCount = DiskSectorCount - 33 - 2048;
810
811 memcpy(Head->Signature, "EFI PART", 8);
812 Head->Version[2] = 0x01;
813 Head->Length = 92;
814 Head->Crc = 0;
815 Head->EfiStartLBA = 1;
816 Head->EfiBackupLBA = DiskSectorCount - 1;
817 Head->PartAreaStartLBA = 34;
818 Head->PartAreaEndLBA = DiskSectorCount - 34;
819 CoCreateGuid(&Head->DiskGuid);
820 Head->PartTblStartLBA = 2;
821 Head->PartTblTotNum = 128;
822 Head->PartTblEntryLen = 128;
823
824
825 memcpy(&(Table[0].PartType), &WindowsDataPartType, sizeof(GUID));
826 CoCreateGuid(&(Table[0].PartGuid));
827 Table[0].StartLBA = 2048;
828 Table[0].LastLBA = 2048 + Part1SectorCount - 1;
829 Table[0].Attr = 0;
830 memcpy(Table[0].Name, L"Data", 4 * 2);
831
832 //Update CRC
833 Head->PartTblCrc = VentoyCrc32(Table, sizeof(pInfo->PartTbl));
834 Head->Crc = VentoyCrc32(Head, Head->Length);
835
836 return 0;
837 }
838
839 int VentoyFillGpt(UINT64 DiskSizeBytes, VTOY_GPT_INFO *pInfo)
840 {
841 INT64 ReservedValue = 0;
842 UINT64 ModSectorCount = 0;
843 UINT64 ReservedSector = 33;
844 UINT64 Part1SectorCount = 0;
845 UINT64 DiskSectorCount = DiskSizeBytes / 512;
846 VTOY_GPT_HDR *Head = &pInfo->Head;
847 VTOY_GPT_PART_TBL *Table = pInfo->PartTbl;
848 static GUID WindowsDataPartType = { 0xebd0a0a2, 0xb9e5, 0x4433, { 0x87, 0xc0, 0x68, 0xb6, 0xb7, 0x26, 0x99, 0xc7 } };
849 static GUID EspPartType = { 0xc12a7328, 0xf81f, 0x11d2, { 0xba, 0x4b, 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b } };
850 static GUID BiosGrubPartType = { 0x21686148, 0x6449, 0x6e6f, { 0x74, 0x4e, 0x65, 0x65, 0x64, 0x45, 0x46, 0x49 } };
851
852 VentoyFillProtectMBR(DiskSizeBytes, &pInfo->MBR);
853
854 ReservedValue = GetReservedSpaceInMB();
855 if (ReservedValue > 0)
856 {
857 ReservedSector += ReservedValue * 2048;
858 }
859
860 Part1SectorCount = DiskSectorCount - ReservedSector - (VENTOY_EFI_PART_SIZE / 512) - 2048;
861
862 ModSectorCount = (Part1SectorCount % 8);
863 if (ModSectorCount)
864 {
865 Log("Part1SectorCount:%llu is not aligned by 4KB (%llu)", (ULONGLONG)Part1SectorCount, (ULONGLONG)ModSectorCount);
866 }
867
868 // check aligned with 4KB
869 if (IsPartNeed4KBAlign())
870 {
871 if (ModSectorCount)
872 {
873 Log("Disk need to align with 4KB %u", (UINT32)ModSectorCount);
874 Part1SectorCount -= ModSectorCount;
875 }
876 else
877 {
878 Log("no need to align with 4KB");
879 }
880 }
881
882 memcpy(Head->Signature, "EFI PART", 8);
883 Head->Version[2] = 0x01;
884 Head->Length = 92;
885 Head->Crc = 0;
886 Head->EfiStartLBA = 1;
887 Head->EfiBackupLBA = DiskSectorCount - 1;
888 Head->PartAreaStartLBA = 34;
889 Head->PartAreaEndLBA = DiskSectorCount - 34;
890 CoCreateGuid(&Head->DiskGuid);
891 Head->PartTblStartLBA = 2;
892 Head->PartTblTotNum = 128;
893 Head->PartTblEntryLen = 128;
894
895
896 memcpy(&(Table[0].PartType), &WindowsDataPartType, sizeof(GUID));
897 CoCreateGuid(&(Table[0].PartGuid));
898 Table[0].StartLBA = 2048;
899 Table[0].LastLBA = 2048 + Part1SectorCount - 1;
900 Table[0].Attr = 0;
901 memcpy(Table[0].Name, L"Ventoy", 6 * 2);
902
903 // to fix windows issue
904 //memcpy(&(Table[1].PartType), &EspPartType, sizeof(GUID));
905 memcpy(&(Table[1].PartType), &WindowsDataPartType, sizeof(GUID));
906 CoCreateGuid(&(Table[1].PartGuid));
907 Table[1].StartLBA = Table[0].LastLBA + 1;
908 Table[1].LastLBA = Table[1].StartLBA + VENTOY_EFI_PART_SIZE / 512 - 1;
909 Table[1].Attr = 0xC000000000000001ULL;
910 memcpy(Table[1].Name, L"VTOYEFI", 7 * 2);
911
912 #if 0
913 memcpy(&(Table[2].PartType), &BiosGrubPartType, sizeof(GUID));
914 CoCreateGuid(&(Table[2].PartGuid));
915 Table[2].StartLBA = 34;
916 Table[2].LastLBA = 2047;
917 Table[2].Attr = 0;
918 #endif
919
920 //Update CRC
921 Head->PartTblCrc = VentoyCrc32(Table, sizeof(pInfo->PartTbl));
922 Head->Crc = VentoyCrc32(Head, Head->Length);
923
924 return 0;
925 }
926
927 int VentoyFillBackupGptHead(VTOY_GPT_INFO *pInfo, VTOY_GPT_HDR *pHead)
928 {
929 UINT64 LBA;
930 UINT64 BackupLBA;
931
932 memcpy(pHead, &pInfo->Head, sizeof(VTOY_GPT_HDR));
933
934 LBA = pHead->EfiStartLBA;
935 BackupLBA = pHead->EfiBackupLBA;
936
937 pHead->EfiStartLBA = BackupLBA;
938 pHead->EfiBackupLBA = LBA;
939 pHead->PartTblStartLBA = BackupLBA + 1 - 33;
940
941 pHead->Crc = 0;
942 pHead->Crc = VentoyCrc32(pHead, pHead->Length);
943
944 return 0;
945 }
946
947 CHAR GetFirstUnusedDriveLetter(void)
948 {
949 CHAR Letter = 'D';
950 DWORD Drives = GetLogicalDrives();
951
952 Drives >>= 3;
953 while (Drives & 0x1)
954 {
955 Letter++;
956 Drives >>= 1;
957 }
958
959 return Letter;
960 }
961
962 const CHAR * GetBusTypeString(STORAGE_BUS_TYPE Type)
963 {
964 switch (Type)
965 {
966 case BusTypeUnknown: return "unknown";
967 case BusTypeScsi: return "SCSI";
968 case BusTypeAtapi: return "Atapi";
969 case BusTypeAta: return "ATA";
970 case BusType1394: return "1394";
971 case BusTypeSsa: return "SSA";
972 case BusTypeFibre: return "Fibre";
973 case BusTypeUsb: return "USB";
974 case BusTypeRAID: return "RAID";
975 case BusTypeiScsi: return "iSCSI";
976 case BusTypeSas: return "SAS";
977 case BusTypeSata: return "SATA";
978 case BusTypeSd: return "SD";
979 case BusTypeMmc: return "MMC";
980 case BusTypeVirtual: return "Virtual";
981 case BusTypeFileBackedVirtual: return "FileBackedVirtual";
982 case BusTypeSpaces: return "Spaces";
983 case BusTypeNvme: return "Nvme";
984 }
985 return "unknown";
986 }
987
988 int VentoyGetLocalBootImg(MBR_HEAD *pMBR)
989 {
990 int Len = 0;
991 BYTE *ImgBuf = NULL;
992 static int Loaded = 0;
993 static MBR_HEAD MBR;
994
995 if (Loaded)
996 {
997 memcpy(pMBR, &MBR, 512);
998 return 0;
999 }
1000
1001 if (0 == ReadWholeFileToBuf(VENTOY_FILE_BOOT_IMG, 0, (void **)&ImgBuf, &Len))
1002 {
1003 Log("Copy boot img success");
1004 memcpy(pMBR, ImgBuf, 512);
1005 free(ImgBuf);
1006
1007 CoCreateGuid((GUID *)(pMBR->BootCode + 0x180));
1008
1009 memcpy(&MBR, pMBR, 512);
1010 Loaded = 1;
1011
1012 return 0;
1013 }
1014 else
1015 {
1016 Log("Copy boot img failed");
1017 return 1;
1018 }
1019 }
1020
1021 int GetHumanReadableGBSize(UINT64 SizeBytes)
1022 {
1023 int i;
1024 int Pow2 = 1;
1025 double Delta;
1026 double GB = SizeBytes * 1.0 / 1000 / 1000 / 1000;
1027
1028 if ((SizeBytes % 1073741824) == 0)
1029 {
1030 return (int)(SizeBytes / 1073741824);
1031 }
1032
1033 for (i = 0; i < 12; i++)
1034 {
1035 if (Pow2 > GB)
1036 {
1037 Delta = (Pow2 - GB) / Pow2;
1038 }
1039 else
1040 {
1041 Delta = (GB - Pow2) / Pow2;
1042 }
1043
1044 if (Delta < 0.05)
1045 {
1046 return Pow2;
1047 }
1048
1049 Pow2 <<= 1;
1050 }
1051
1052 return (int)GB;
1053 }
1054
1055 void TrimString(CHAR *String)
1056 {
1057 CHAR *Pos1 = String;
1058 CHAR *Pos2 = String;
1059 size_t Len = strlen(String);
1060
1061 while (Len > 0)
1062 {
1063 if (String[Len - 1] != ' ' && String[Len - 1] != '\t')
1064 {
1065 break;
1066 }
1067 String[Len - 1] = 0;
1068 Len--;
1069 }
1070
1071 while (*Pos1 == ' ' || *Pos1 == '\t')
1072 {
1073 Pos1++;
1074 }
1075
1076 while (*Pos1)
1077 {
1078 *Pos2++ = *Pos1++;
1079 }
1080 *Pos2++ = 0;
1081
1082 return;
1083 }
1084
1085 int GetRegDwordValue(HKEY Key, LPCSTR SubKey, LPCSTR ValueName, DWORD *pValue)
1086 {
1087 HKEY hKey;
1088 DWORD Type;
1089 DWORD Size;
1090 LSTATUS lRet;
1091 DWORD Value;
1092
1093 lRet = RegOpenKeyExA(Key, SubKey, 0, KEY_QUERY_VALUE, &hKey);
1094 Log("RegOpenKeyExA <%s> Ret:%ld", SubKey, lRet);
1095
1096 if (ERROR_SUCCESS == lRet)
1097 {
1098 Size = sizeof(Value);
1099 lRet = RegQueryValueExA(hKey, ValueName, NULL, &Type, (LPBYTE)&Value, &Size);
1100 Log("RegQueryValueExA <%s> ret:%u Size:%u Value:%u", ValueName, lRet, Size, Value);
1101
1102 *pValue = Value;
1103 RegCloseKey(hKey);
1104
1105 return 0;
1106 }
1107 else
1108 {
1109 return 1;
1110 }
1111 }
1112
1113 int GetPhysicalDriveCount(void)
1114 {
1115 DWORD Value;
1116 int Count = 0;
1117
1118 if (GetRegDwordValue(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Services\\disk\\Enum", "Count", &Value) == 0)
1119 {
1120 Count = (int)Value;
1121 }
1122
1123 Log("GetPhysicalDriveCount: %d", Count);
1124 return Count;
1125 }
1126
1127 void VentoyStringToUpper(CHAR* str)
1128 {
1129 while (str && *str)
1130 {
1131 if (*str >= 'a' && *str <= 'z')
1132 {
1133 *str = toupper(*str);
1134 }
1135 str++;
1136 }
1137 }