forked from pbatard/rufus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformat.c
2057 lines (1888 loc) · 72.1 KB
/
format.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Rufus: The Reliable USB Formatting Utility
* Formatting function calls
* Copyright © 2011-2024 Pete Batard <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#endif
#include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
#include <stddef.h>
#include <ctype.h>
#include <locale.h>
#include <assert.h>
#if !defined(__MINGW32__)
#include <vds.h>
#endif
#include "rufus.h"
#include "format.h"
#include "missing.h"
#include "resource.h"
#include "settings.h"
#include "winio.h"
#include "msapi_utf8.h"
#include "localization.h"
#include "br.h"
#include "vhd.h"
#include "wue.h"
#include "fat16.h"
#include "fat32.h"
#include "ntfs.h"
#include "partition_info.h"
#include "file.h"
#include "drive.h"
#include "format.h"
#include "badblocks.h"
#include "bled/bled.h"
#include "../res/grub/grub_version.h"
/* Numbers of buffer used for asynchronous DD reads */
#define NUM_BUFFERS 2
/*
* Globals
*/
const char* FileSystemLabel[FS_MAX] = { "FAT", "FAT32", "NTFS", "UDF", "exFAT", "ReFS", "ext2", "ext3", "ext4" };
DWORD ErrorStatus = 0, LastWriteError = 0;
badblocks_report report = { 0 };
static float format_percent = 0.0f;
static int task_number = 0, actual_fs_type;
static unsigned int sec_buf_pos = 0;
extern const int nb_steps[FS_MAX];
extern const char* md5sum_name[2];
extern uint32_t dur_mins, dur_secs;
extern uint32_t wim_nb_files, wim_proc_files, wim_extra_files;
extern BOOL force_large_fat32, enable_ntfs_compression, lock_drive, zero_drive, fast_zeroing, enable_file_indexing;
extern BOOL write_as_image, use_vds, write_as_esp, is_vds_available, has_ffu_support, use_rufus_mbr;
extern char* archive_path;
uint8_t *grub2_buf = NULL, *sec_buf = NULL;
long grub2_len;
/*
* Convert the fmifs outputs messages (that use an OEM code page) to UTF-8
*/
static void OutputUTF8Message(const char* src)
{
int len;
wchar_t* wdst = NULL;
if (src == NULL)
goto out;
len = (int)safe_strlen(src);
while ((len > 0) && ((src[len-1] == 0x0A) || (src[len-1] == 0x0D) || (src[len-1] == ' ')))
len--;
if (len == 0)
goto out;
len = MultiByteToWideChar(CP_OEMCP, 0, src, len, NULL, 0);
if (len == 0)
goto out;
wdst = (wchar_t*)calloc(len+1, sizeof(wchar_t));
if ((wdst == NULL) || (MultiByteToWideChar(CP_OEMCP, 0, src, len, wdst, len+1) == 0))
goto out;
uprintf("%S", wdst);
out:
safe_free(wdst);
}
/*
* FormatEx callback. Return FALSE to halt operations
*/
static BOOLEAN __stdcall FormatExCallback(FILE_SYSTEM_CALLBACK_COMMAND Command, DWORD Action, PVOID pData)
{
char percent_str[8];
if (IS_ERROR(ErrorStatus))
return FALSE;
if_not_assert((actual_fs_type >= 0) && (actual_fs_type < FS_MAX))
return FALSE;
switch(Command) {
case FCC_PROGRESS:
static_sprintf(percent_str, "%lu%%", *((DWORD*)pData));
PrintInfo(0, MSG_217, percent_str);
UpdateProgress(OP_FORMAT, 1.0f * (*((DWORD*)pData)));
break;
case FCC_STRUCTURE_PROGRESS: // No progress on quick format
if (task_number < nb_steps[actual_fs_type] - 1) {
if (task_number == 0)
uprintf("Creating file system...");
PrintInfo(0, MSG_218, ++task_number, nb_steps[actual_fs_type]);
format_percent += 100.0f / (1.0f * nb_steps[actual_fs_type]);
UpdateProgress(OP_CREATE_FS, format_percent);
}
break;
case FCC_DONE:
PrintInfo(0, MSG_218, nb_steps[actual_fs_type], nb_steps[actual_fs_type]);
UpdateProgress(OP_CREATE_FS, 100.0f);
if(*(BOOLEAN*)pData == FALSE) {
uprintf("Error while formatting");
ErrorStatus = RUFUS_ERROR(ERROR_GEN_FAILURE);
}
break;
case FCC_DONE_WITH_STRUCTURE:
break;
case FCC_INCOMPATIBLE_FILE_SYSTEM:
uprintf("Incompatible File System");
ErrorStatus = RUFUS_ERROR(APPERR(ERROR_INCOMPATIBLE_FS));
break;
case FCC_ACCESS_DENIED:
uprintf("Access denied");
ErrorStatus = RUFUS_ERROR(ERROR_ACCESS_DENIED);
break;
case FCC_MEDIA_WRITE_PROTECTED:
uprintf("Media is write protected");
ErrorStatus = RUFUS_ERROR(ERROR_WRITE_PROTECT);
break;
case FCC_VOLUME_IN_USE:
uprintf("Volume is in use");
ErrorStatus = RUFUS_ERROR(ERROR_DEVICE_IN_USE);
break;
case FCC_DEVICE_NOT_READY:
uprintf("The device is not ready");
ErrorStatus = RUFUS_ERROR(ERROR_NOT_READY);
break;
case FCC_CANT_QUICK_FORMAT:
uprintf("Cannot quick format this volume");
ErrorStatus = RUFUS_ERROR(APPERR(ERROR_CANT_QUICK_FORMAT));
break;
case FCC_BAD_LABEL:
uprintf("Bad label");
ErrorStatus = RUFUS_ERROR(ERROR_LABEL_TOO_LONG);
break;
case FCC_OUTPUT:
OutputUTF8Message(((PTEXTOUTPUT)pData)->Output);
break;
case FCC_CLUSTER_SIZE_TOO_BIG:
case FCC_CLUSTER_SIZE_TOO_SMALL:
uprintf("Unsupported cluster size");
ErrorStatus = RUFUS_ERROR(APPERR(ERROR_INVALID_CLUSTER_SIZE));
break;
case FCC_VOLUME_TOO_BIG:
case FCC_VOLUME_TOO_SMALL:
uprintf("Volume is too %s", (Command == FCC_VOLUME_TOO_BIG) ? "big" : "small");
ErrorStatus = RUFUS_ERROR(APPERR(ERROR_INVALID_VOLUME_SIZE));
break;
case FCC_NO_MEDIA_IN_DRIVE:
uprintf("No media in drive");
ErrorStatus = RUFUS_ERROR(ERROR_NO_MEDIA_IN_DRIVE);
break;
case FCC_ALIGNMENT_VIOLATION:
uprintf("Partition start offset is not aligned to the cluster size");
ErrorStatus = RUFUS_ERROR(ERROR_OFFSET_ALIGNMENT_VIOLATION);
break;
default:
uprintf("FormatExCallback: Received unhandled command 0x%02X - aborting", Command);
ErrorStatus = RUFUS_ERROR(ERROR_NOT_SUPPORTED);
break;
}
return (!IS_ERROR(ErrorStatus));
}
/*
* Chkdsk callback. Return FALSE to halt operations
*/
static BOOLEAN __stdcall ChkdskCallback(FILE_SYSTEM_CALLBACK_COMMAND Command, DWORD Action, PVOID pData)
{
DWORD* percent;
if (IS_ERROR(ErrorStatus))
return FALSE;
switch (Command) {
case FCC_PROGRESS:
case FCC_CHECKDISK_PROGRESS:
percent = (DWORD*)pData;
PrintInfo(0, MSG_219, *percent);
break;
case FCC_DONE:
if (*(BOOLEAN*)pData == FALSE) {
uprintf("Error while checking disk");
return FALSE;
}
break;
case FCC_UNKNOWN1A:
case FCC_DONE_WITH_STRUCTURE:
// Silence these specific calls
break;
case FCC_INCOMPATIBLE_FILE_SYSTEM:
uprintf("Incompatible File System");
return FALSE;
case FCC_ACCESS_DENIED:
uprintf("Access denied");
return FALSE;
case FCC_MEDIA_WRITE_PROTECTED:
uprintf("Media is write protected");
return FALSE;
case FCC_VOLUME_IN_USE:
uprintf("Volume is in use");
return FALSE;
case FCC_OUTPUT:
OutputUTF8Message(((PTEXTOUTPUT)pData)->Output);
break;
case FCC_NO_MEDIA_IN_DRIVE:
uprintf("No media in drive");
return FALSE;
case FCC_READ_ONLY_MODE:
uprintf("Media has been switched to read-only - Leaving checkdisk");
break;
default:
uprintf("ChkdskExCallback: received unhandled command %X", Command);
// Assume the command isn't an error
break;
}
return TRUE;
}
/*
* Converts an UTF-8 label to a valid FAT/NTFS one
* TODO: Use IVdsService::QueryFileSystemTypes -> VDS_FILE_SYSTEM_TYPE_PROP
* to get the list of unauthorised and max length for each FS.
*/
static void ToValidLabel(char* Label, BOOL bFAT)
{
size_t i, j, k;
BOOL found;
const WCHAR unauthorized[] = L"*?,;:/\\|+=<>[]\"";
const WCHAR to_underscore[] = L"\t.";
char label[16] = { 0 };
WCHAR *wLabel = utf8_to_wchar(Label);
if (wLabel == NULL)
return;
for (i = 0, k = 0; i < wcslen(wLabel); i++) {
if (bFAT) { // NTFS does allows all the FAT unauthorized above
found = FALSE;
for (j = 0; j < wcslen(unauthorized); j++) {
if (wLabel[i] == unauthorized[j]) {
found = TRUE;
break;
}
}
// A FAT label that contains extended chars will be rejected
if (wLabel[i] >= 0x80) {
wLabel[k++] = L'_';
found = TRUE;
}
if (found)
continue;
}
found = FALSE;
for (j = 0; j < wcslen(to_underscore); j++) {
if (wLabel[i] == to_underscore[j]) {
wLabel[k++] = '_';
found = TRUE;
break;
}
}
if (found)
continue;
wLabel[k++] = bFAT ? toupper(wLabel[i]) : wLabel[i];
}
wLabel[k] = 0;
if (bFAT) {
if (wcslen(wLabel) > 11)
wLabel[11] = 0;
for (i = 0, j = 0; wLabel[i] != 0 ; i++)
if (wLabel[i] == '_')
j++;
if (i < 2*j) {
// If the final label is mostly underscore, use an alternate label according to the
// size (eg: "256 MB", "7.9 GB"). Note that we can't use SelectedDrive.proposed_label
// here as it may contain localized character for GB or MB, so make sure that the
// effective label we use is an English one, and also make sure we convert the dot.
static_sprintf(label, "%s", SizeToHumanReadable(SelectedDrive.DiskSize, TRUE, FALSE));
for (i = 0; label[i] != 0; i++)
wLabel[i] = (label[i] == '.') ? '_' : label[i];
wLabel[i] = 0;
uprintf("FAT label is mostly underscores. Using '%S' label instead.", wLabel);
}
} else if (wcslen(wLabel) > 32) {
wLabel[32] = 0;
}
// Needed for disk by label isolinux.cfg workaround
wchar_to_utf8_no_alloc(wLabel, img_report.usb_label, sizeof(img_report.usb_label));
safe_strcpy(Label, strlen(Label) + 1, img_report.usb_label);
free(wLabel);
}
/*
* Call on VDS to format a partition
*/
static BOOL FormatNativeVds(DWORD DriveIndex, uint64_t PartitionOffset, DWORD ClusterSize, LPCSTR FSName, LPCSTR Label, DWORD Flags)
{
BOOL r = FALSE, bFoundVolume = FALSE;
HRESULT hr;
ULONG ulFetched;
IVdsServiceLoader *pLoader;
IVdsService *pService;
IEnumVdsObject *pEnum;
IUnknown *pUnk;
char* VolumeName = NULL;
WCHAR *wVolumeName = NULL, *wLabel = utf8_to_wchar(Label), *wFSName = utf8_to_wchar(FSName);
if ((strcmp(FSName, FileSystemLabel[FS_EXFAT]) == 0) && !((dur_mins == 0) && (dur_secs == 0))) {
PrintInfo(0, MSG_220, FSName, dur_mins, dur_secs);
} else {
PrintInfo(0, MSG_222, FSName);
}
uprintf("Formatting to %s (using VDS)", FSName);
UpdateProgressWithInfoInit(NULL, TRUE);
VolumeName = GetLogicalName(DriveIndex, PartitionOffset, TRUE, TRUE);
wVolumeName = utf8_to_wchar(VolumeName);
if (wVolumeName == NULL) {
uprintf("Could not read volume name");
ErrorStatus = RUFUS_ERROR(ERROR_GEN_FAILURE);
goto out;
}
// Initialize COM
IGNORE_RETVAL(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
IGNORE_RETVAL(CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT,
RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL));
// Create a VDS Loader Instance
hr = CoCreateInstance(&CLSID_VdsLoader, NULL, CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER,
&IID_IVdsServiceLoader, (void **)&pLoader);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not create VDS Loader Instance: %s", WindowsErrorString());
goto out;
}
// Load the VDS Service
hr = IVdsServiceLoader_LoadService(pLoader, L"", &pService);
IVdsServiceLoader_Release(pLoader);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not load VDS Service: %s", WindowsErrorString());
goto out;
}
// Wait for the Service to become ready if needed
hr = IVdsService_WaitForServiceReady(pService);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("VDS Service is not ready: %s", WindowsErrorString());
goto out;
}
// Query the VDS Service Providers
hr = IVdsService_QueryProviders(pService, VDS_QUERY_SOFTWARE_PROVIDERS, &pEnum);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not query VDS Service Providers: %s", WindowsErrorString());
goto out;
}
while (IEnumVdsObject_Next(pEnum, 1, &pUnk, &ulFetched) == S_OK) {
IVdsProvider *pProvider;
IVdsSwProvider *pSwProvider;
IEnumVdsObject *pEnumPack;
IUnknown *pPackUnk;
CHECK_FOR_USER_CANCEL;
// Get VDS Provider
hr = IUnknown_QueryInterface(pUnk, &IID_IVdsProvider, (void **)&pProvider);
IUnknown_Release(pUnk);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not get VDS Provider: %s", WindowsErrorString());
goto out;
}
// Get VDS Software Provider
hr = IVdsSwProvider_QueryInterface(pProvider, &IID_IVdsSwProvider, (void **)&pSwProvider);
IVdsProvider_Release(pProvider);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not get VDS Software Provider: %s", WindowsErrorString());
goto out;
}
// Get VDS Software Provider Packs
hr = IVdsSwProvider_QueryPacks(pSwProvider, &pEnumPack);
IVdsSwProvider_Release(pSwProvider);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not get VDS Software Provider Packs: %s", WindowsErrorString());
goto out;
}
// Enumerate Provider Packs
while (IEnumVdsObject_Next(pEnumPack, 1, &pPackUnk, &ulFetched) == S_OK) {
IVdsPack *pPack;
IEnumVdsObject *pEnumVolume;
IUnknown *pVolumeUnk;
CHECK_FOR_USER_CANCEL;
hr = IUnknown_QueryInterface(pPackUnk, &IID_IVdsPack, (void **)&pPack);
IUnknown_Release(pPackUnk);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not query VDS Software Provider Pack: %s", WindowsErrorString());
goto out;
}
// Use the pack interface to access the volumes
hr = IVdsPack_QueryVolumes(pPack, &pEnumVolume);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not query VDS volumes: %s", WindowsErrorString());
goto out;
}
// List volumes
while (IEnumVdsObject_Next(pEnumVolume, 1, &pVolumeUnk, &ulFetched) == S_OK) {
BOOL match;
HRESULT hr2 = E_FAIL;
VDS_VOLUME_PROP VolumeProps;
LPWSTR *wszPathArray;
ULONG ulPercentCompleted, ulNumberOfPaths;
USHORT usFsVersion = 0;
IVdsVolume *pVolume;
IVdsAsync* pAsync;
IVdsVolumeMF3 *pVolumeMF3;
CHECK_FOR_USER_CANCEL;
// Get the volume interface.
hr = IUnknown_QueryInterface(pVolumeUnk, &IID_IVdsVolume, (void **)&pVolume);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not query VDS Volume Interface: %s", WindowsErrorString());
goto out;
}
hr = IVdsVolume_GetProperties(pVolume, &VolumeProps);
if ((hr != S_OK) && (hr != VDS_S_PROPERTIES_INCOMPLETE)) {
VDS_SET_ERROR(hr);
IVdsVolume_Release(pVolume);
uprintf("Could not query VDS Volume Properties: %s", WindowsErrorString());
continue;
}
CoTaskMemFree(VolumeProps.pwszName);
// Instantiate the IVdsVolumeMF3 interface for our volume.
hr = IVdsVolume_QueryInterface(pVolume, &IID_IVdsVolumeMF3, (void **)&pVolumeMF3);
IVdsVolume_Release(pVolume);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not access VDS VolumeMF3 interface: %s", WindowsErrorString());
continue;
}
// Query the volume GUID
hr = IVdsVolumeMF3_QueryVolumeGuidPathnames(pVolumeMF3, &wszPathArray, &ulNumberOfPaths);
if (hr != S_OK) {
VDS_SET_ERROR(hr);
uprintf("Could not query VDS VolumeGuidPathnames: %s", WindowsErrorString());
continue;
}
if (ulNumberOfPaths > 1)
uprintf("Notice: Volume %S has more than one GUID...", wszPathArray[0]);
match = (wcscmp(wVolumeName, wszPathArray[0]) == 0);
CoTaskMemFree(wszPathArray);
if (!match)
continue;
bFoundVolume = TRUE;
if (strcmp(Label, FileSystemLabel[FS_UDF]) == 0)
usFsVersion = ReadSetting32(SETTING_USE_UDF_VERSION);
if (ClusterSize < 0x200) {
ClusterSize = 0;
uprintf("Using default cluster size");
} else {
uprintf("Using cluster size: %d bytes", ClusterSize);
}
format_percent = 0.0f;
uprintf("%s format was selected", (Flags & FP_QUICK) ? "Quick" : "Slow");
if (Flags & FP_COMPRESSION)
uprintf("NTFS compression is enabled");
hr = IVdsVolumeMF3_FormatEx2(pVolumeMF3, wFSName, usFsVersion, ClusterSize, wLabel, Flags, &pAsync);
while (SUCCEEDED(hr)) {
if (IS_ERROR(ErrorStatus)) {
IVdsAsync_Cancel(pAsync);
break;
}
hr = IVdsAsync_QueryStatus(pAsync, &hr2, &ulPercentCompleted);
if (SUCCEEDED(hr)) {
if (Flags & FP_QUICK) {
// Progress report on quick format is useless, so we'll just pretend we have 2 tasks
PrintInfo(0, MSG_218, (ulPercentCompleted < 100) ? 1 : 2, 2);
UpdateProgress(OP_CREATE_FS, (float)ulPercentCompleted);
} else {
UpdateProgressWithInfo(OP_FORMAT, MSG_217, ulPercentCompleted, 100);
}
hr = hr2;
if (hr == S_OK)
break;
if (hr == VDS_E_OPERATION_PENDING)
hr = S_OK;
}
Sleep(500);
}
if (!SUCCEEDED(hr)) {
VDS_SET_ERROR(hr);
uprintf("Could not format drive: %s", WindowsErrorString());
goto out;
}
IVdsAsync_Release(pAsync);
IVdsVolumeMF3_Release(pVolumeMF3);
if (!IS_ERROR(ErrorStatus)) {
uprintf("Format completed.");
r = TRUE;
}
goto out;
}
}
}
out:
if ((!bFoundVolume) && (ErrorStatus == 0))
ErrorStatus = RUFUS_ERROR(ERROR_PATH_NOT_FOUND);
safe_free(VolumeName);
safe_free(wVolumeName);
safe_free(wLabel);
safe_free(wFSName);
CoUninitialize();
return r;
}
/*
* Call on fmifs.dll's FormatEx() to format the drive
*/
static BOOL FormatNative(DWORD DriveIndex, uint64_t PartitionOffset, DWORD ClusterSize, LPCSTR FSName, LPCSTR Label, DWORD Flags)
{
BOOL r = FALSE;
PF_DECL(FormatEx);
PF_DECL(EnableVolumeCompression);
char *locale, *VolumeName = NULL;
WCHAR* wVolumeName = NULL, *wLabel = utf8_to_wchar(Label), *wFSName = utf8_to_wchar(FSName);
size_t i;
if ((strcmp(FSName, FileSystemLabel[FS_EXFAT]) == 0) && !((dur_mins == 0) && (dur_secs == 0))) {
PrintInfo(0, MSG_220, FSName, dur_mins, dur_secs);
} else {
PrintInfo(0, MSG_222, FSName);
}
uprintf("Formatting to %s (using IFS)", FSName);
VolumeName = GetLogicalName(DriveIndex, PartitionOffset, TRUE, TRUE);
wVolumeName = utf8_to_wchar(VolumeName);
if (wVolumeName == NULL) {
uprintf("Could not read volume name (%s)", VolumeName);
ErrorStatus = RUFUS_ERROR(ERROR_GEN_FAILURE);
goto out;
}
// Hey, nice consistency here, Microsoft! - FormatEx() fails if wVolumeName has
// a trailing backslash, but EnableCompression() fails without...
wVolumeName[wcslen(wVolumeName)-1] = 0; // Remove trailing backslash
// LoadLibrary("fmifs.dll") appears to changes the locale, which can lead to
// problems with tolower(). Make sure we restore the locale. For more details,
// see https://sourceforge.net/p/mingw/mailman/message/29269040/
locale = setlocale(LC_ALL, NULL);
PF_INIT_OR_OUT(FormatEx, fmifs);
PF_INIT(EnableVolumeCompression, fmifs);
setlocale(LC_ALL, locale);
if (ClusterSize < 0x200) {
// 0 is FormatEx's value for default, which we need to use for UDF
ClusterSize = 0;
uprintf("Using default cluster size");
} else {
uprintf("Using cluster size: %d bytes", ClusterSize);
}
format_percent = 0.0f;
task_number = 0;
uprintf("%s format was selected", (Flags & FP_QUICK) ? "Quick" : "Slow");
for (i = 0; i < WRITE_RETRIES; i++) {
pfFormatEx(wVolumeName, SelectedDrive.MediaType, wFSName, wLabel,
(Flags & FP_QUICK), ClusterSize, FormatExCallback);
if (!IS_ERROR(ErrorStatus) || (HRESULT_CODE(ErrorStatus) == ERROR_CANCELLED))
break;
uprintf("%s - Retrying...", WindowsErrorString());
Sleep(WRITE_TIMEOUT);
}
if (IS_ERROR(ErrorStatus))
goto out;
if (Flags & FP_COMPRESSION) {
wVolumeName[wcslen(wVolumeName)] = '\\'; // Add trailing backslash back again
if (pfEnableVolumeCompression(wVolumeName, FPF_COMPRESSED)) {
uprintf("Enabled NTFS compression");
} else {
uprintf("Could not enable NTFS compression: %s", WindowsErrorString());
}
}
if (!IS_ERROR(ErrorStatus)) {
uprintf("Format completed.");
r = TRUE;
}
out:
if (!r && !IS_ERROR(ErrorStatus))
ErrorStatus = RUFUS_ERROR(SCODE_CODE(GetLastError()));
safe_free(VolumeName);
safe_free(wVolumeName);
safe_free(wLabel);
safe_free(wFSName);
return r;
}
BOOL FormatPartition(DWORD DriveIndex, uint64_t PartitionOffset, DWORD UnitAllocationSize, USHORT FSType, LPCSTR Label, DWORD Flags)
{
if ((DriveIndex < 0x80) || (DriveIndex > 0x100) || (FSType >= FS_MAX) ||
((UnitAllocationSize != 0) && (!IS_POWER_OF_2(UnitAllocationSize)))) {
ErrorStatus = RUFUS_ERROR(ERROR_INVALID_PARAMETER);
return FALSE;
}
actual_fs_type = FSType;
if ((FSType == FS_FAT32) && ((SelectedDrive.DiskSize > LARGE_FAT32_SIZE) || (force_large_fat32) || (Flags & FP_LARGE_FAT32)))
return FormatLargeFAT32(DriveIndex, PartitionOffset, UnitAllocationSize, FileSystemLabel[FSType], Label, Flags);
else if (IS_EXT(FSType))
return FormatExtFs(DriveIndex, PartitionOffset, UnitAllocationSize, FileSystemLabel[FSType], Label, Flags);
else if (use_vds)
return FormatNativeVds(DriveIndex, PartitionOffset, UnitAllocationSize, FileSystemLabel[FSType], Label, Flags);
else
return FormatNative(DriveIndex, PartitionOffset, UnitAllocationSize, FileSystemLabel[FSType], Label, Flags);
}
/*
* Call on fmifs.dll's Chkdsk() to fixup the filesystem
*/
static BOOL CheckDisk(char DriveLetter)
{
BOOL r = FALSE;
PF_DECL(Chkdsk);
WCHAR wDriveRoot[] = L"?:\\";
WCHAR wFSType[32];
size_t i;
wDriveRoot[0] = (WCHAR)DriveLetter;
PrintInfoDebug(0, MSG_223);
PF_INIT_OR_OUT(Chkdsk, Fmifs);
GetWindowTextW(hFileSystem, wFSType, ARRAYSIZE(wFSType));
// We may have a " (Default)" trail
for (i=0; i<wcslen(wFSType); i++) {
if (wFSType[i] == ' ') {
wFSType[i] = 0;
break;
}
}
pfChkdsk(wDriveRoot, wFSType, FALSE, FALSE, FALSE, FALSE, NULL, NULL, ChkdskCallback);
if (!IS_ERROR(ErrorStatus)) {
uprintf("NTFS Fixup completed.");
r = TRUE;
}
out:
return r;
}
static BOOL ClearMBRGPT(HANDLE hPhysicalDrive, LONGLONG DiskSize, DWORD SectorSize, BOOL add1MB)
{
BOOL r = FALSE;
LARGE_INTEGER liFilePointer;
uint64_t num_sectors_to_clear;
unsigned char* pZeroBuf = NULL;
PrintInfoDebug(0, MSG_224);
// http://en.wikipedia.org/wiki/GUID_Partition_Table tells us we should clear 34 sectors at the
// beginning and 33 at the end. We bump these values to MAX_SECTORS_TO_CLEAR each end to help
// with reluctant access to large drive.
// We try to clear at least 1MB + the VBR when Large FAT32 is selected (add1MB), but
// don't do it otherwise, as it seems unnecessary and may take time for slow drives.
// Also, for various reasons (one of which being that Windows seems to have issues
// with GPT drives that contain a lot of small partitions) we try not not to clear
// sectors further than the lowest partition already residing on the disk.
num_sectors_to_clear = min(SelectedDrive.FirstDataSector, (DWORD)((add1MB ? 2048 : 0) + MAX_SECTORS_TO_CLEAR));
// Special case for big floppy disks (FirstDataSector = 0)
if (num_sectors_to_clear < 4)
num_sectors_to_clear = (DWORD)((add1MB ? 2048 : 0) + MAX_SECTORS_TO_CLEAR);
uprintf("Erasing %llu sectors", num_sectors_to_clear);
pZeroBuf = calloc(SectorSize, (size_t)num_sectors_to_clear);
if (pZeroBuf == NULL) {
ErrorStatus = RUFUS_ERROR(ERROR_NOT_ENOUGH_MEMORY);
goto out;
}
liFilePointer.QuadPart = 0ULL;
if (!SetFilePointerEx(hPhysicalDrive, liFilePointer, &liFilePointer, FILE_BEGIN) || (liFilePointer.QuadPart != 0ULL))
uprintf("Warning: Could not reset disk position");
if (!WriteFileWithRetry(hPhysicalDrive, pZeroBuf, (DWORD)(SectorSize * num_sectors_to_clear), NULL, WRITE_RETRIES))
goto out;
CHECK_FOR_USER_CANCEL;
liFilePointer.QuadPart = DiskSize - (LONGLONG)SectorSize * MAX_SECTORS_TO_CLEAR;
// Windows seems to be an ass about keeping a lock on a backup GPT,
// so we try to be lenient about not being able to clear it.
if (SetFilePointerEx(hPhysicalDrive, liFilePointer, &liFilePointer, FILE_BEGIN)) {
IGNORE_RETVAL(WriteFileWithRetry(hPhysicalDrive, pZeroBuf,
SectorSize * MAX_SECTORS_TO_CLEAR, NULL, WRITE_RETRIES));
}
r = TRUE;
out:
safe_free(pZeroBuf);
return r;
}
/*
* Process the Master Boot Record
*/
static BOOL WriteMBR(HANDLE hPhysicalDrive)
{
BOOL r = FALSE;
BOOL needs_masquerading = HAS_WINPE(img_report) && (!img_report.uses_minint);
uint8_t* buffer = NULL;
FAKE_FD fake_fd = { 0 };
FILE* fp = (FILE*)&fake_fd;
const char* using_msg = "Using %s MBR";
if (SelectedDrive.SectorSize < 512)
goto out;
if (partition_type == PARTITION_STYLE_GPT) {
// Add a notice with a protective MBR
fake_fd._handle = (char*)hPhysicalDrive;
set_bytes_per_sector(SelectedDrive.SectorSize);
uprintf(using_msg, "Rufus protective");
r = write_rufus_msg_mbr(fp);
goto notify;
}
// FormatEx rewrites the MBR and removes the LBA attribute of FAT16
// and FAT32 partitions - we need to correct this in the MBR
buffer = (uint8_t*)_mm_malloc(SelectedDrive.SectorSize, 16);
if (buffer == NULL) {
uprintf("Could not allocate memory for MBR");
ErrorStatus = RUFUS_ERROR(ERROR_NOT_ENOUGH_MEMORY);
goto out;
}
if (!read_sectors(hPhysicalDrive, SelectedDrive.SectorSize, 0, 1, buffer)) {
uprintf("Could not read MBR");
ErrorStatus = RUFUS_ERROR(ERROR_READ_FAULT);
goto out;
}
switch (ComboBox_GetCurItemData(hFileSystem)) {
case FS_FAT16:
if (buffer[0x1c2] == 0x0e) {
uprintf("Partition is already FAT16 LBA...");
} else if ((buffer[0x1c2] != 0x04) && (buffer[0x1c2] != 0x06)) {
uprintf("Warning: converting a non FAT16 partition to FAT16 LBA: FS type=0x%02x", buffer[0x1c2]);
}
buffer[0x1c2] = 0x0e;
break;
case FS_FAT32:
if (buffer[0x1c2] == 0x0c) {
uprintf("Partition is already FAT32 LBA...");
} else if (buffer[0x1c2] != 0x0b) {
uprintf("Warning: converting a non FAT32 partition to FAT32 LBA: FS type=0x%02x", buffer[0x1c2]);
}
buffer[0x1c2] = 0x0c;
break;
}
if ((boot_type != BT_NON_BOOTABLE) && (target_type == TT_BIOS)) {
// Set first partition bootable or masquerade as second disk
buffer[0x1be] = needs_masquerading ? 0x81 : 0x80;
uprintf("Set bootable USB partition as 0x%02X", buffer[0x1be]);
}
if (!write_sectors(hPhysicalDrive, SelectedDrive.SectorSize, 0, 1, buffer)) {
uprintf("Could not write MBR");
ErrorStatus = RUFUS_ERROR(ERROR_WRITE_FAULT);
goto out;
}
fake_fd._handle = (char*)hPhysicalDrive;
set_bytes_per_sector(SelectedDrive.SectorSize);
// What follows is really a case statement with complex conditions listed
// by order of preference
if ((boot_type == BT_IMAGE) && HAS_WINDOWS(img_report) && (allow_dual_uefi_bios) && (target_type == TT_BIOS))
goto windows_mbr;
// Non bootable or forced UEFI (zeroed MBR)
if ((boot_type == BT_NON_BOOTABLE) || (target_type == TT_UEFI)) {
uprintf(using_msg, "Zeroed");
r = write_zero_mbr(fp);
goto notify;
}
// Syslinux
if ( (boot_type == BT_SYSLINUX_V4) || (boot_type == BT_SYSLINUX_V6) ||
((boot_type == BT_IMAGE) && HAS_SYSLINUX(img_report)) ) {
uprintf(using_msg, "Syslinux");
r = write_syslinux_mbr(fp);
goto notify;
}
// Grub 2.0
if ( ((boot_type == BT_IMAGE) && (img_report.has_grub2)) || (boot_type == BT_GRUB2) ) {
uprintf(using_msg, "Grub 2.0");
r = write_grub2_mbr(fp);
goto notify;
}
// Grub4DOS
if ( ((boot_type == BT_IMAGE) && (img_report.has_grub4dos)) || (boot_type == BT_GRUB4DOS) ) {
uprintf(using_msg, "Grub4DOS");
r = write_grub4dos_mbr(fp);
goto notify;
}
// ReactOS
if (boot_type == BT_REACTOS) {
uprintf(using_msg, "ReactOS");
r = write_reactos_mbr(fp);
goto notify;
}
// KolibriOS
if ( (boot_type == BT_IMAGE) && HAS_KOLIBRIOS(img_report) && (IS_FAT(fs_type))) {
uprintf(using_msg, "KolibriOS");
r = write_kolibrios_mbr(fp);
goto notify;
}
// If everything else failed, fall back to a conventional Windows/Rufus MBR
windows_mbr:
if (needs_masquerading || use_rufus_mbr) {
uprintf(using_msg, APPLICATION_NAME);
r = write_rufus_mbr(fp);
} else {
uprintf(using_msg, "Windows 7");
r = write_win7_mbr(fp);
}
notify:
// Tell the system we've updated the disk properties
if (!DeviceIoControl(hPhysicalDrive, IOCTL_DISK_UPDATE_PROPERTIES, NULL, 0, NULL, 0, NULL, NULL))
uprintf("Failed to notify system about disk properties update: %s", WindowsErrorString());
out:
safe_mm_free(buffer);
return r;
}
/*
* Write Secondary Boot Record (usually right after the MBR)
*/
static BOOL WriteSBR(HANDLE hPhysicalDrive)
{
// TODO: Do we need anything special for 4K sectors?
DWORD size, max_size, br_size = 0x200;
int r, sub_type = boot_type;
uint8_t *buf = NULL;
FAKE_FD fake_fd = { 0 };
FILE* fp = (FILE*)&fake_fd;
fake_fd._handle = (char*)hPhysicalDrive;
set_bytes_per_sector(SelectedDrive.SectorSize);
// Syslinux has precedence over Grub
if ((boot_type == BT_IMAGE) && (!HAS_SYSLINUX(img_report))) {
if (img_report.has_grub4dos)
sub_type = BT_GRUB4DOS;
if (img_report.has_grub2)
sub_type = BT_GRUB2;
}
// Use BT_MAX for the protective message
if ((boot_type != BT_NON_BOOTABLE) && (partition_type == PARTITION_STYLE_GPT))
sub_type = BT_MAX;
switch (sub_type) {
case BT_GRUB4DOS:
uprintf("Writing Grub4Dos SBR");
buf = GetResource(hMainInstance, MAKEINTRESOURCEA(IDR_GR_GRUB_GRLDR_MBR), _RT_RCDATA, "grldr.mbr", &size, FALSE);
if ((buf == NULL) || (size <= br_size)) {
uprintf("grldr.mbr is either not present or too small");
return FALSE;
}
buf = &buf[br_size];
size -= br_size;
break;
case BT_GRUB2:
if (grub2_buf != NULL) {
uprintf("Writing Grub 2.0 SBR (from download) %s",
IsBufferInDB(grub2_buf, grub2_len)?"✓":"✗");
buf = grub2_buf;
size = (DWORD)grub2_len;
} else {
uprintf("Writing Grub 2.0 SBR (from embedded)");
buf = GetResource(hMainInstance, MAKEINTRESOURCEA(IDR_GR_GRUB2_CORE_IMG), _RT_RCDATA, "core.img", &size, FALSE);
if (buf == NULL) {
uprintf("Could not access core.img");
return FALSE;
}
}
break;
case BT_MAX:
uprintf("Writing protective message SBR");
size = 4 * KB;
br_size = 17 * KB; // 34 sectors are reserved for protective MBR + primary GPT
buf = GetResource(hMainInstance, MAKEINTRESOURCEA(IDR_SBR_MSG), _RT_RCDATA, "msg.txt", &size, TRUE);
if (buf == NULL) {
uprintf("Could not access message");
return FALSE;
}
break;
default:
// No need to write secondary block
return TRUE;
}
// Ensure that we have sufficient space for the SBR
max_size = (DWORD)SelectedDrive.Partition[0].Offset;
if (br_size + size > max_size) {
uprintf(" SBR size is too large - You may need to uncheck 'Add fixes for old BIOSes'.");
if (sub_type == BT_MAX)
safe_free(buf);
return FALSE;
}
r = write_data(fp, br_size, buf, (uint64_t)size);
safe_free(grub2_buf);
if (sub_type == BT_MAX)
safe_free(buf);
return (r != 0);
}
/*
* Process the Partition Boot Record
*/
static __inline const char* bt_to_name(void) {
switch (boot_type) {
case BT_FREEDOS: return "FreeDOS";
case BT_REACTOS: return "ReactOS";
default:
return ((boot_type == BT_IMAGE) && HAS_KOLIBRIOS(img_report)) ? "KolibriOS" : "Standard";
}
}