-
Notifications
You must be signed in to change notification settings - Fork 9
/
gdisk.c
1716 lines (1504 loc) · 65.5 KB
/
gdisk.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
// Copyright (c) 2008 David Caldwell, All Rights Reserved.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>
#include <wchar.h>
#include <errno.h>
#include <inttypes.h>
#include <sys/param.h> // PATH_MAX on both linux and OS X
#include <sys/stat.h> // mkdir
#include <err.h>
#include <readline/readline.h>
#include <readline/history.h>
#include "lengthof.h"
#include "round.h"
#include "guid.h"
#include "partition-type.h"
#include "device.h"
#include "gpt.h"
#include "mbr.h"
#include "autolist.h"
#include "csprintf.h"
#include "human.h"
#include "xmem.h"
#include "dalloc.h"
#include "gdisk.h"
autolist_define(command);
static int run_command(char *line, char **final_line);
static struct partition_table read_table(struct device *dev);
static void free_table(struct partition_table t);
static char *command_completion(const char *text, int state);
static char *partition_type_completion(const char *text, int state);
static char *partition_size_completion(const char *text, int state);
struct free_space {
uint64_t first_lba;
uint64_t blocks;
};
static struct free_space *find_free_spaces(struct partition_table unsorted);
static struct free_space largest_free_space(struct partition_table unsorted);
static bool table_is_dirty(struct partition_table t);
static void dump_dev(struct device *dev);
static void dump_header(struct gpt_header *header);
static void dump_partition(struct gpt_partition *p);
static size_t sncatprintf(char *buffer, size_t space, char *format, ...) __attribute__ ((format (printf, 3, 4)));
static char *tr(char *in, char *from, char *to);
static char *trdup(char *in, char *from, char *to);
static char *ctr(char *in, char *from, char *to);
static char *trim(char *s);
static void usage(char *me, int exit_code)
{
fprintf(exit_code ? stderr : stdout,
"Usage: \n"
" %s <device>\n"
"%s", me, device_help());
exit(exit_code);
}
struct partition_table g_table;
int main(int c, char **v)
{
char *device_name = v[1];
if (!device_name)
usage(v[0], 1);
struct device *dev = open_device(device_name);
if (!dev)
err(0, "Couldn't find device %s", v[1]);
if (dev->sector_size < 512)
err(0, "Disk has a sector size of %lu which is not big enough to support an MBR which I don't support yet.", dev->sector_size);
g_table = read_table(dev);
char *line, *final_line;
int status = 0;
do {
rl_completion_entry_function = (void*)command_completion; // rl_completion_entry_function is defined to return an int??
rl_completion_append_character = ' ';
line = readline("gdisk> ");
if (!line) {
printf("\n");
break;
}
status = run_command(line, &final_line);
add_history(final_line);
free(line);
free(final_line);
} while (status != ECANCELED); // Special case meaning Quit!
if (table_is_dirty(g_table))
printf("Quitting without saving changes.\n");
free_table(g_table);
//if (!write_mbr(dev, mbr))
// warn("Couldn't write MBR sector");
}
char *next_word(char **line)
{
if (!*line) return NULL;
if (**line == '"') {
char *s = ++*line; // skip quote
while (**line != '"' && **line != '\0')
++*line;
if (**line)
*(*line)++ = '\0';
if (**line == '\0')
*line = NULL;
return s;
}
return strsep(line, " \t\f\r\n");
}
static char **parse_command(char *line)
{
char **v = dcalloc(1, sizeof(char*));
int c = 0;
char *rest = line;
char *word;
while (word = next_word(&rest)) {
if (!*word) continue; // compact multiple consecutive separators
v = drealloc(v, sizeof(char *) * (c+2));
v[c] = word;
v[c+1] = NULL;
c++;
}
return v;
}
static struct command *find_command(char *command)
{
foreach_autolist(struct command *c, command)
if (strcmp(command, c->name) == 0)
return c;
return NULL;
}
static int run_command(char *line, char **final_line)
{
if (final_line) *final_line = xstrdup(line);
dalloc_start();
int status = 0;
char **cmdv = NULL;
char **argv = parse_command(line);
int argc;
for (argc=0; argv[argc]; argc++) {}
if (!argc) goto done; // Blank line
for (char **v = argv; *v; v++)
if (strchr(*v, '"')) {
fprintf(stderr, "Sorry, embedded quotes don't work (yet?). If you are trying to do\n"
"'--arg=\"a b\"' then do '--arg \"a b\"' or '\"--arg=a b\"' instead.\n"
"Yeah, that sucks. Send me a patch if it bugs you that much.\n");
status = EINVAL;
goto done;
}
struct command *c = find_command(argv[0]);
if (!c) {
printf("Command not found: '%s'\n", argv[0]);
status = EINVAL;
goto done;
}
int args;
for (args=0; c->arg[args].name; args++) {}
cmdv = dcalloc(1+args+1, sizeof(*argv));
cmdv[0] = argv[0];
for (int i=1; i<argc; i++) {
if (argv[i][0] == '-') {
char *rest = argv[i];
char *name = strsep(&rest, "=");
while (*name == '-') name++;
for (int a=0; a<args; a++)
if (strcmp(c->arg[a].name, name) == 0) {
char **arg = &cmdv[a+1];
if (c->arg[a].type == C_Flag)
*arg = argv[i];
else if (!rest || !*rest)
if (i+1 >= argc) {
fprintf(stderr, "Missing parameter for argument \"%s\"\n", name);
status = EINVAL;
goto done;
} else
*arg = argv[++i];
else
*arg = rest;
goto found;
}
fprintf(stderr, "Command \"%s\" has no such argument \"%s\". Try 'help %s'\n", c->name, name, c->name);
status = EINVAL;
goto done;
} else {
for (int o=1; o<args+1; o++)
if (!cmdv[o] && c->arg[o-1].type != C_Flag) {
cmdv[o] = argv[i];
goto found;
}
fprintf(stderr, "Too many arguments for command '%s'\n", argv[0]);
status = EINVAL;
goto done;
}
found:;
}
char **v = cmdv + 1; // start past command name.
for (int a=0; a<args; a++, v++) {
if (*v) continue; // Don't prompt for args entered on command line.
if (c->arg[a].type & C_Optional)
continue;
char *prompt = dsprintf("%s: Enter %s: ", c->name, c->arg[a].help);
if (!prompt) err(ENOMEM, "No memory for argument prompt");
if (C_Type(c->arg[a].type) == C_File)
rl_completion_entry_function = (void*)rl_filename_completion_function;
else if (C_Type(c->arg[a].type) == C_Partition_Type)
#warning "BUG: partition type completion doesn't do spaces right"
rl_completion_entry_function = (void*)partition_type_completion;
else if (C_Type(c->arg[a].type) == C_FreeSpace)
rl_completion_entry_function = (void*)partition_size_completion;
// rl_completer_quote_characters = "\"'";
// rl_basic_word_break_characters = "";
rl_completion_append_character = '\0';
*v = dalloc_remember(readline(prompt));
if (!*v) goto done;
*v = trim(*v);
if (final_line) {
*final_line = xstrcat(*final_line, " ");
*final_line = xstrcat(*final_line, *v);
}
}
status = c->handler(cmdv);
done:
dalloc_free();
return status;
}
static char *arg_name(struct command_arg_ *arg)
{
return dsprintf("%s%s%s",
arg->type == C_Flag ? "--" : "<",
arg->name,
arg->type == C_Flag ? "" : ">");
}
static int compare_command_name(const void *a, const void *b)
{
return strcmp((*(struct command **)a)->name, (*(struct command **)b)->name);
}
static int help(char **arg)
{
if (arg[1]) {
struct command *c = find_command(arg[1]);
if (!c) {
printf("No such command: '%s'\n", arg[1]);
return 0;
}
printf("%s:\n %s\n\nUsage:\n %s", c->name, c->help, c->name);
for (int a=0; c->arg[a].name; a++) {
printf(" %s%s%s",
c->arg[a].type & C_Optional ? "[ " : "",
arg_name(&c->arg[a]),
c->arg[a].type & C_Optional ? " ]" : "");
}
printf("\n\nArguments:\n");
for (int a=0; c->arg[a].name; a++) {
printf(" %s: %s\n", arg_name(&c->arg[a]), c->arg[a].help);
}
return 0;
}
printf("Commands:\n");
int width=0, count=0;
foreach_autolist(struct command *c, command) {
width=MAX(width, strlen(c->name));
count++;
}
struct command *command[count], **c = command;
foreach_autolist(struct command *cmd, command)
*c++ = cmd;
qsort(command, count, sizeof(*command), compare_command_name);
for (c=command; c < &command[count]; c++)
printf("%-*s %s\n", width+2, (*c)->name, (*c)->help);
return 0;
}
command_add("help", help, "Show a list of commands",
command_arg("command", C_String|C_Optional, "Command to get help with"));
static int quit(char **arg)
{
return ECANCELED; // total special case. Weak.
}
command_add("quit", quit, "Quit, leaving the disk untouched.");
static char *command_completion(const char *text, int state)
{
int i=0;
foreach_autolist(struct command *c, command)
if (strncmp(text, c->name, strlen(text)) == 0 &&
i++ == state)
return xstrdup(c->name);
return NULL;
}
static char *partition_size_completion(const char *text, int state)
{
struct free_space *space = find_free_spaces(g_table);
char *size = NULL;
for (int i=0, s=0; i<space[i].blocks; i++) {
char *_size = NULL; asprintf(&_size, "%"PRId64, space[i].blocks * g_table.dev->sector_size);
if (strncasecmp(text, _size, strlen(text)) == 0 && s++ == state) {
size = _size;
break;
}
free(_size);
}
free(space);
return size;
}
static char *partition_type_completion(const char *text, int state)
{
for (int i=0, s=0; gpt_partition_type[i].name; i++) {
char *_name = trdup(gpt_partition_type[i].name, " ", "_");
if (strncasecmp(text, _name, strlen(text)) == 0 &&
s++ == state)
return _name;
free(_name);
}
return NULL;
}
static void update_gpt_crc(struct gpt_header *h, struct gpt_partition *p)
{
h->partition_crc32 = gpt_partition_crc32(h, p);
h->header_crc32 = gpt_header_crc32(h);
}
static void update_table_crc(struct partition_table *t)
{
update_gpt_crc(t->header, t->partition);
update_gpt_crc(t->alt_header, t->partition);
}
static bool gpt_crc_valid(struct gpt_header *h, struct gpt_partition *p)
{
return h->partition_crc32 == gpt_partition_crc32(h, p) && h->header_crc32 == gpt_header_crc32(h);
}
static void utf16_from_ascii(uint16_t *utf16le, char *ascii, int n)
{
if (!n) return;
while (--n && (*utf16le++ = *ascii++)) {}
*utf16le = '\0';
}
static bool partition_entry_is_representable_in_mbr(struct gpt_partition entry)
{
// MBR only has 32 bits for the LBA. So if the partition is further up the disk than that then it can't be represented in the MBR.
return !guid_eq(gpt_partition_type_empty, entry.partition_type) &&
entry.first_lba < 0x100000000LL &&
entry.last_lba - entry.first_lba < 0x100000000LL;
}
static void create_mbr_alias_table(struct partition_table *t)
{
int synced = -1;
for (int i=0; i<lengthof(t->alias); i++)
t->alias[i] = -1;
for (int mp=0; mp<lengthof(t->mbr.partition); mp++) {
if (!t->mbr.partition[mp].partition_type)
continue;
for (int gp=0; gp<t->header->partition_entries; gp++)
if (partition_entry_is_representable_in_mbr(t->partition[gp]) &&
(t->mbr.partition[mp].first_sector_lba == t->partition[gp].first_lba ||
// first partition could be type EE which covers the GPT partition table and the optional EFI filesystem.
// The EFI filesystem in the GPT doesn't cover the EFI partition table, so the starts might not line up.
t->mbr.partition[mp].first_sector_lba == 1 && t->mbr.partition[mp].partition_type == 0xee) &&
t->mbr.partition[mp].first_sector_lba + t->mbr.partition[mp].sectors == t->partition[gp].last_lba + 1) {
t->alias[mp] = gp;
if (synced < 0) synced = 1;
break;
}
if (t->alias[mp] == -1)
synced = 0;
}
t->options.mbr_sync = synced == 1;
}
static unsigned long partition_sectors(struct partition_table t)
{
return divide_round_up(t.header->partition_entry_size * t.header->partition_entries, t.dev->sector_size);
}
static struct partition_table blank_table(struct device *dev)
{
struct partition_table t = {};
t.dev = dev;
t.header = alloc_sectors(dev, 1);
t.alt_header = alloc_sectors(dev, 1);
const int partitions = 128;
const int partition_sectors = divide_round_up(partitions * sizeof(struct gpt_partition), dev->sector_size);
*t.header = (struct gpt_header) {
.signature = "EFI PART",
.revision = PARTITION_REVISION,
.header_size = sizeof(struct gpt_header),
.my_lba = 1,
.alternate_lba = dev->sector_count-1,
.first_usable_lba = 2 + partition_sectors,
.last_usable_lba = dev->sector_count-2 - partition_sectors,
.disk_guid = guid_create(),
.partition_entry_lba = 2,
.partition_entries = partitions,
.partition_entry_size = sizeof(struct gpt_partition),
};
*t.alt_header = *t.header;
t.alt_header->alternate_lba = t.header->my_lba;
t.alt_header->my_lba = t.header->alternate_lba;
t.alt_header->partition_entry_lba = t.header->last_usable_lba + 1;
t.partition = alloc_sectors(dev, partition_sectors);
for (int i=0; i<lengthof(t.alias); i++)
t.alias[i] = -1;
return t;
}
static int command_clear_table(char **arg)
{
struct mbr mbr = g_table.mbr;
g_table = blank_table(g_table.dev);
g_table.mbr = mbr;
return 0;
}
command_add("clear-table", command_clear_table, "Clear out GPT partition table for a nice fresh start.");
static struct mbr blank_mbr(struct device *dev)
{
struct mbr mbr = { .mbr_signature = MBR_SIGNATURE };
// Even a blank MBR should preserve the boot code.
struct mbr code = read_mbr(dev);
memcpy(mbr.code, code.code, sizeof(mbr.code));
return mbr;
}
static int command_clear_mbr(char **arg)
{
g_table.mbr = blank_mbr(g_table.dev);
create_mbr_alias_table(&g_table);
return 0;
}
command_add("clear-mbr", command_clear_mbr, "Clear out MBR partition table and start anew.");
static int command_create_protective_mbr(char **arg)
{
g_table.mbr = blank_mbr(g_table.dev);
g_table.mbr.partition[0] = (struct mbr_partition) {
.first_sector_lba = 1,
.sectors = g_table.dev->sector_count-1,
.partition_type = 0xee,
};
create_mbr_alias_table(&g_table);
return 0;
}
command_add("create-protective-mbr", command_create_protective_mbr, "Replace MBR entries with a protective MBR as per the EFI spec.");
static int command_add_protective_mbr_partition(char **arg)
{
struct partition_table *t = &g_table;
for (int i=0; i < lengthof(t->mbr.partition); i++)
if (t->mbr.partition[i].partition_type == 0) {
t->mbr.partition[i] = (struct mbr_partition) {
.first_sector_lba = 1,
.sectors = g_table.header->first_usable_lba-1-1/*mbr*/,
.partition_type = 0xee,
};
return 0;
}
fprintf(stderr, "No free MBR partitions found.\n");
return ENOSPC;
}
command_add("add-protective-mbr-partition", command_add_protective_mbr_partition, "Add a protective MBR entry that just covers the EFI partitioning sectors.");
static struct partition_table gpt_table_from_mbr(struct mbr mbr, struct device *dev)
{
struct partition_table t = blank_table(dev);
t.mbr = mbr;
for (int mp=0,gp=0; mp<lengthof(t.mbr.partition); mp++) {
if (t.mbr.partition[mp].partition_type) {
if (t.mbr.partition[mp].partition_type == 0xee)
continue;
t.partition[gp].first_lba = t.mbr.partition[mp].first_sector_lba;
t.partition[gp].last_lba = t.mbr.partition[mp].first_sector_lba + t.mbr.partition[mp].sectors - 1;
if (t.partition[gp].first_lba < t.header->first_usable_lba ||
t.partition[gp].last_lba > t.header->last_usable_lba)
printf("ouch, mbr partition %d [%"PRId64"d,%"PRId64"d] outside of usable gpt space [%"PRId64"d,%"PRId64"d]\n",
mp+1, t.partition[gp].first_lba, t.partition[gp].last_lba, t.header->first_usable_lba, t.header->last_usable_lba);
utf16_from_ascii(t.partition[gp].name, csprintf("MBR %d\n", mp+1), lengthof(t.partition[gp].name));
for (int i=0; gpt_partition_type[i].name; i++)
for (int j=0; gpt_partition_type[i].mbr_equivalent[j]; j++)
if (t.mbr.partition[mp].partition_type == gpt_partition_type[i].mbr_equivalent[j]) {
t.partition[gp].partition_type = gpt_partition_type[i].guid;
goto found;
}
// Not found, use gdisk specific guid to mean "unknown".
t.partition[gp].partition_type = GUID(b334117e,118d,11de,9b0f,001cc0952d53);
found:
t.partition[gp].partition_guid = guid_create();
t.alias[mp] = gp++;
}
}
t.options.mbr_sync = true;
update_table_crc(&t);
return t;
}
static int gpt_from_mbr(char **arg)
{
struct device *dev = g_table.dev;
struct mbr mbr = g_table.mbr;
free_table(g_table);
g_table = gpt_table_from_mbr(mbr, dev);
return 0;
}
command_add("init-gpt-from-mbr", gpt_from_mbr, "(Re)create GPT partition table using data from the MBR partition table");
static int recreate_gpt(char **arg)
{
struct partition_table new_table = blank_table(g_table.dev);
new_table.header->disk_guid = new_table.alt_header->disk_guid = g_table.header->disk_guid;
assert(new_table.header->partition_entries == g_table.header->partition_entries);
/* Should never happen because for now all gpt partitions have the same number of entries: */
if (new_table.header->partition_entries < g_table.header->partition_entries)
fprintf(stderr, "Warning: new partition table has less partition entries (%d) than the old table (%d). Some partitions may be dropped.\n",
new_table.header->partition_entries, g_table.header->partition_entries);
struct partition_table gt = g_table;
g_table.header = new_table.header;
g_table.alt_header = new_table.alt_header;
new_table.header = gt.header;
new_table.alt_header = gt.alt_header;
free_table(new_table);
update_table_crc(&g_table);
return 0;
}
command_add("recreate-gpt", recreate_gpt, "Recreate GPT partition table using partitions in current GPT. Useful for resizing disks.");
static struct partition_table read_gpt_table(struct device *dev)
{
struct partition_table t = {};
t.dev = dev;
bool primary_valid = true, alternate_valid = true;
#define header_error(format, ...) ({ \
fprintf(stderr, format, ##__VA_ARGS__); \
fprintf(stderr, ". Assuming blank partition...\n"); \
free_table(t); \
blank_table(dev); \
})
#define header_warning(format, ...) ({ \
fprintf(stderr, "Warning: "); \
fprintf(stderr, format, ##__VA_ARGS__); \
fprintf(stderr, ".\n"); \
})
#define header_corrupt(which, format, ...) ({ \
header_warning(format, ##__VA_ARGS__); \
which ## _valid = false; \
if (!primary_valid && !alternate_valid) \
return header_error("There were no valid GPT headers found"); \
})
t.header = get_sectors(dev,1,1);
if (memcmp(t.header->signature, "EFI PART", sizeof(t.header->signature)) != 0)
header_corrupt(primary, "Missing signature in primary GPT header");
else
gpt_header_to_host(t.header);
t.alt_header = get_sectors(dev, primary_valid ? t.header->alternate_lba : dev->sector_count-1, 1);
if (memcmp(t.alt_header->signature, "EFI PART", sizeof(t.alt_header->signature)) != 0)
header_corrupt(alternate, "Missing signature in altername GPT header");
else
gpt_header_to_host(t.alt_header);
if (primary_valid && t.header->header_size != sizeof(struct gpt_header))
header_corrupt(primary, "Partition header is %d bytes long instead of %zd", t.header->header_size, sizeof(struct gpt_header));
if (alternate_valid && t.alt_header->header_size != sizeof(struct gpt_header))
header_corrupt(alternate, "Partition header is %d bytes long instead of %zd", t.header->header_size, sizeof(struct gpt_header));
if (primary_valid && t.header->partition_entry_size != sizeof(struct gpt_partition))
header_corrupt(primary, "Size of partition entries are %d instead of %zd", t.header->partition_entry_size, sizeof(struct gpt_partition));
if (alternate_valid && t.alt_header->partition_entry_size != sizeof(struct gpt_partition))
header_corrupt(alternate, "Size of partition entries are %d instead of %zd", t.alt_header->partition_entry_size, sizeof(struct gpt_partition));
uint64_t primary_lba,alternate_lba;
if (primary_valid && alternate_valid && t.header->my_lba != t.alt_header->alternate_lba) {
header_warning("Header LBA is %"PRId64" but alternate header claims it is %"PRId64"", t.header->my_lba, t.header->alternate_lba);
if (t.header->my_lba == 1 || t.alt_header->alternate_lba == 1)
primary_lba = 1; // It *really* should be one.
else
primary_lba = t.header->my_lba; // In any other screwball case, trust the primary header.
} else
primary_lba = primary_valid ? t.header->my_lba : t.alt_header->alternate_lba;
if (primary_lba != 1)
header_warning("Header LBA is %"PRId64" and not 1", primary_lba);
if (primary_valid && alternate_valid && t.header->alternate_lba != t.alt_header->my_lba) {
header_warning("Primary header says Alternate header LBA is %"PRId64" but alternate header claims it is %"PRId64"", t.header->alternate_lba, t.header->my_lba);
if (t.header->my_lba == dev->sector_count-1 || t.alt_header->alternate_lba == dev->sector_count-1)
alternate_lba = dev->sector_count-1;
else
alternate_lba = t.header->alternate_lba; // In any other screwball case, trust the primary header.
} else
alternate_lba = primary_valid ? t.header->alternate_lba : t.alt_header->my_lba;
if (alternate_lba != dev->sector_count-1)
header_warning("Alternate header LBA is %"PRId64" and not at the end of the disk (LBA: %llu)", alternate_lba, dev->sector_count-1);
// Technically we can guess the start lba and check the validity of the opposite table if the one we're looking at doesn't CRC..
if (primary_valid) {
if (t.header->partition_entries * t.header->partition_entry_size / dev->sector_size > dev->sector_count/2)
header_corrupt(primary, "The number of partition_entries is ludicrous: %d", t.header->partition_entries);
else {
t.partition = get_sectors(dev, t.header->partition_entry_lba, divide_round_up(t.header->partition_entry_size * t.header->partition_entries,dev->sector_size));
gpt_partition_to_host(t.partition, t.header->partition_entries);
if (!gpt_crc_valid(t.header, t.partition)) {
header_warning("Header CRC is not valid. Fixing.");
update_table_crc(&t);
}
}
} else if (alternate_valid) {
if (t.alt_header->partition_entries * t.alt_header->partition_entry_size / dev->sector_size > dev->sector_count/2)
header_corrupt(alternate, "The number of partition_entries is ludicrous: %d", t.alt_header->partition_entries);
else {
t.partition = get_sectors(dev, t.alt_header->partition_entry_lba, divide_round_up(t.alt_header->partition_entry_size * t.alt_header->partition_entries,dev->sector_size));
gpt_partition_to_host(t.partition, t.alt_header->partition_entries);
if (!gpt_crc_valid(t.alt_header, t.partition)) {
header_warning("Alt Header CRC is not valid. Fixing.");
update_table_crc(&t);
}
}
}
#warning "TODO: Sanity check first_usable_lba and last_usable_lba."
// If one is bad, fix it from the other one...
if (primary_valid && !alternate_valid) {
*t.alt_header = *t.header;
uint64_t temp = t.alt_header->my_lba;
t.alt_header->my_lba = t.alt_header->alternate_lba;
t.alt_header->alternate_lba = temp;
t.alt_header->partition_entry_lba = t.alt_header->last_usable_lba + 1;
} else if (!primary_valid && alternate_valid) {
*t.header = *t.alt_header;
uint64_t temp = t.header->my_lba;
t.header->my_lba = t.header->alternate_lba;
t.header->alternate_lba = temp;
t.header->partition_entry_lba = t.header->my_lba + 1;
}
#warning "TODO: Capture both sets of partition tables in case on has a bad crc."
return t;
}
static struct partition_table read_table(struct device *dev)
{
struct partition_table t = read_gpt_table(dev);
t.mbr = read_mbr(dev);
create_mbr_alias_table(&t);
return t;
}
#warning "TODO: Add 'fix' command that moves alternate partition and header to end of disk"
#warning "TODO: Add 'new-guids' command (with better name) that recreates all the guids in the table (run it after an image copy)"
static void free_table(struct partition_table t)
{
free(t.header);
free(t.alt_header);
free(t.partition);
}
static struct partition_table dup_table(struct partition_table t)
{
struct partition_table dup;
dup = t;
dup.header = xmemdup(t.header, t.dev->sector_size);
dup.alt_header = xmemdup(t.alt_header, t.dev->sector_size);
dup.partition = xmemdup(t.partition, partition_sectors(t) * t.dev->sector_size);
return dup;
}
static int compare_partition_entries(const void *_a, const void *_b)
{
const struct gpt_partition *a = _a, *b = _b;
int a_empty = guid_eq(gpt_partition_type_empty, a->partition_type),
b_empty = guid_eq(gpt_partition_type_empty, b->partition_type);
if (a_empty || b_empty)
return a_empty - b_empty;
return (long long)a->first_lba - (long long)b->first_lba;
}
static void compact_and_sort(struct partition_table *t)
{
qsort(t->partition, t->header->partition_entries, sizeof(*t->partition), compare_partition_entries);
update_table_crc(&g_table);
create_mbr_alias_table(t);
}
static int command_compact_and_sort(char **arg)
{
compact_and_sort(&g_table);
return 0;
}
command_add("compact-and-sort", command_compact_and_sort, "Remove \"holes\" from table and sort entries in ascending order");
static struct gpt_partition *find_unused_partition(struct partition_table t)
{
for (int i=0; i<t.header->partition_entries; i++)
if (guid_eq(gpt_partition_type_empty, g_table.partition[i].partition_type))
return &g_table.partition[i];
return NULL;
}
static struct free_space *find_free_spaces(struct partition_table unsorted)
{
// To make this sane we sort the partition table first.
struct partition_table t = dup_table(unsorted);
compact_and_sort(&t);
uint64_t free_start = t.header->first_usable_lba;
struct free_space *space = malloc(sizeof(*space)*(t.header->partition_entries+1+1/*NULL*/));
int s=0;
for (int p=0; p<t.header->partition_entries; p++) {
if (guid_eq(gpt_partition_type_empty, t.partition[p].partition_type))
break;
if (t.partition[p].first_lba - free_start > 0)
space[s++] = (struct free_space) { .blocks = t.partition[p].first_lba - free_start,
.first_lba = free_start };
free_start = t.partition[p].last_lba + 1;
}
// Check for it fitting in the end (probably the most common case)
if (t.header->last_usable_lba+1 - free_start > 0)
space[s++] = (struct free_space) { .blocks = t.header->last_usable_lba+1 - free_start,
.first_lba = free_start };
space[s++] = (struct free_space) { };
free_table(t);
return space;
}
static uint64_t find_free_space(struct partition_table unsorted, uint64_t blocks)
{
uint64_t start = -1LL;
struct free_space *space = find_free_spaces(unsorted);
for (int i=0; i<space[i].blocks; i++)
if (space[i].blocks >= blocks) {
start = space[i].first_lba;
break;
}
free(space);
return start;
}
static struct free_space largest_free_space(struct partition_table unsorted)
{
struct free_space found = { .blocks = 0 };
struct free_space *space = find_free_spaces(unsorted);
for (int i=0; i<space[i].blocks; i++)
if (space[i].blocks >= found.blocks)
found = space[i];
free(space);
return found;
}
static GUID type_guid_from_string(char *s)
{
for (int t=0; gpt_partition_type[t].name; t++) {
if (strcasecmp(s, ctr(gpt_partition_type[t].name, " ", "_")) == 0)
return gpt_partition_type[t].guid;
}
return guid_from_string(s);
}
static bool sync_partition_to_mbr(struct partition_table *t, int gpt_index)
{
int mbr_type;
struct gpt_partition *p = &t->partition[gpt_index];
if (!partition_entry_is_representable_in_mbr(*p) ||
!(mbr_type = find_mbr_equivalent(p->partition_type)))
return false;
for (int i=0; i < lengthof(t->mbr.partition); i++)
if (t->mbr.partition[i].partition_type == 0) {
t->mbr.partition[i] = (struct mbr_partition) {
.status = 0,
.first_sector = {}, // Need disk geometry to do this properly
.last_sector = {}, // Need disk geometry to do this properly
.partition_type = mbr_type,
.first_sector_lba = p->first_lba,
.sectors = p->last_lba - p->first_lba + 1,
};
t->alias[i] = gpt_index;
return true;
}
return false;
}
static int command_create_partition(char **arg)
{
enum { Type=1, Size, Label, First_lba, Last_lba, System, Guid };
struct gpt_partition part = {};
part.partition_type = type_guid_from_string(arg[Type]);
if (guid_eq(bad_guid, part.partition_type)) {
fprintf(stderr, "Unknown GUID format: \"%s\"\n", arg[Type]);
return EINVAL;
}
part.partition_guid = arg[Guid] ? guid_from_string(arg[Guid]) : guid_create();
if (guid_eq(bad_guid, part.partition_guid)) {
fprintf(stderr, "Unknown GUID format: \"%s\"\n", arg[Guid]);
return EINVAL;
}
uint64_t size = human_size(arg[Size]);
uint64_t blocks = divide_round_up(size, g_table.dev->sector_size);
if (arg[First_lba] && !size && !arg[Last_lba]) {
fprintf(stderr, "If you specify the first LBA then you must give a size or a last LBA.\n");
return EINVAL;
}
if (size && arg[Last_lba]) {
fprintf(stderr, "You can't give both a size and a last LBA.\n");
return EINVAL;
}
if (!size && !arg[First_lba]) {
struct free_space largest = largest_free_space(g_table);
if (!largest.blocks) {
fprintf(stderr, "There is no free space left!\n");
return ENOSPC;
}
blocks = largest.blocks;
size = blocks * g_table.dev->sector_size;
part.first_lba = largest.first_lba;
printf("Largest unused space: %"PRId64" blocks (%"PRId64", %s) at block %"PRId64".\n",
blocks, size, human_string(size), part.first_lba);
} else
part.first_lba = arg[First_lba] ? strtoull(arg[First_lba], NULL, 0) : find_free_space(g_table, blocks);
if (part.first_lba == -1LL) {
fprintf(stderr, "Couldn't find %"PRId64" blocks (%"PRId64", %s) of free space.\n", blocks, size, human_string(size));
return ENOSPC;
}
part.last_lba = arg[Last_lba] ? strtoull(arg[Last_lba], NULL, 0) : part.first_lba + blocks - 1;
part.attributes = 0 | (arg[System] ? PA_SYSTEM_PARTITION : 0);
utf16_from_ascii(part.name, arg[Label] ? arg[Label] : "", lengthof(part.name));
if (part.last_lba < part.first_lba) {
fprintf(stderr, "Last LBA (%"PRIu64") must be larger than the Start LBA (%"PRIu64")\n", part.last_lba, part.first_lba);
return EINVAL;
}
if (part.first_lba < g_table.header->first_usable_lba) {
fprintf(stderr, "First LBA (%"PRIu64") must be greater (or equal) to the First Usable LBA (%"PRIu64")\n", part.first_lba, g_table.header->first_usable_lba);
return EINVAL;
}
if (part.last_lba > g_table.header->last_usable_lba) {
fprintf(stderr, "Last LBA (%"PRIu64") must be smaller than the Last Usable LBA (%"PRIu64")\n", part.last_lba, g_table.header->last_usable_lba);
return EINVAL;
}
dump_partition(&part);
struct gpt_partition *p = find_unused_partition(g_table);
if (!p) {
fprintf(stderr, "Partition table is full.\n");
return ENOSPC;
}
*p = part;
update_table_crc(&g_table);
if (g_table.options.mbr_sync)
sync_partition_to_mbr(&g_table, p - g_table.partition);
return 0;
}
command_add("new", command_create_partition, "Create a new partition entry in the table",
command_arg("type", C_Partition_Type, "Type of new partition"),
command_arg("size", C_FreeSpace, "Size of the new partition"),
command_arg("label", C_String|C_Optional, "The name of the new partition"),
command_arg("first_lba", C_String|C_Optional, "The first block of the new partition"),
command_arg("last_lba", C_String|C_Optional, "The last block of the new partition (this overrides the size argument)"),
command_arg("system", C_Flag, "Set the \"System Partition\" attribute"),
command_arg("guid", C_String|C_Optional, "The GUID of the new partition")
);
static int get_mbr_alias(struct partition_table t, int index)
{
for (int m=0; m<lengthof(t.alias); m++)
if (g_table.alias[m] == index)
return m;
return -1;
}
static void delete_mbr_partition(struct partition_table *t, int mbr_index)
{
memset(&t->mbr.partition[mbr_index], 0, sizeof(*t->mbr.partition));
t->alias[mbr_index] = -1;
}
static int choose_partition(char *string)
{
int index = strtol(string, NULL, 0);
if (index < 0 || index >= g_table.header->partition_entries) {
fprintf(stderr, "Bad index '%d'. Should be between 0 and %d (inclusive).\n", index, g_table.header->partition_entries-1);
return -1;
}
if (guid_eq(g_table.partition[index].partition_type, gpt_partition_type_empty)) {
fprintf(stderr, "Partition '%d' is empty.\n", index);
return -1;
}
return index;
}
static int command_delete_partition(char **arg)
{
int index = choose_partition(arg[1]);
if (index < 0) return EINVAL;
memset(&g_table.partition[index], 0, sizeof(g_table.partition[index]));
update_table_crc(&g_table);
int mbr_alias = get_mbr_alias(g_table, index);
if (g_table.options.mbr_sync && mbr_alias != -1)
delete_mbr_partition(&g_table, mbr_alias);
return 0;
}
command_add("delete", command_delete_partition, "Delete a partition from the table",
command_arg("index", C_Number, "The index number of the partition. The first partition is partition zero"));
static int command_sync_mbr(char **arg)
{
if (g_table.options.mbr_sync && !arg[1]) {
fprintf(stderr, "MBR is already synced to GPT. Use --force flag to force a re-sync.\n");
return EEXIST;
}
for (int i=0; i < lengthof(g_table.mbr.partition); i++)
delete_mbr_partition(&g_table, i);
for (int i=0; i < g_table.header->partition_entries; i++)
sync_partition_to_mbr(&g_table, i);
g_table.options.mbr_sync = true;
return 0;
}
command_add("init-mbr-from-gpt", command_sync_mbr, "(Re)create MBR partition table using data from the GPT partition table",
command_arg("force", C_Flag, "Force a re-sync if the MBR already looks synced"));
static int command_sync_mbr_partition(char **arg)
{
int index = choose_partition(arg[1]);
if (index < 0) return EINVAL;