forked from Surachai-kent/util-linux
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpt.c
More file actions
3381 lines (2785 loc) · 85.8 KB
/
gpt.c
File metadata and controls
3381 lines (2785 loc) · 85.8 KB
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) 2007 Karel Zak <kzak@redhat.com>
* Copyright (C) 2012 Davidlohr Bueso <dave@gnu.org>
*
* GUID Partition Table (GPT) support. Based on UEFI Specs 2.3.1
* Chapter 5: GUID Partition Table (GPT) Disk Layout (Jun 27th, 2012).
* Some ideas and inspiration from GNU parted and gptfdisk.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <inttypes.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <uuid.h>
#include "fdiskP.h"
#include "crc32.h"
#include "blkdev.h"
#include "bitops.h"
#include "strutils.h"
#include "all-io.h"
#include "pt-mbr.h"
#include "encode.h"
/**
* SECTION: gpt
* @title: UEFI GPT
* @short_description: specific functionality
*/
#define GPT_HEADER_SIGNATURE 0x5452415020494645LL /* EFI PART */
#define GPT_HEADER_REVISION_V1_02 0x00010200
#define GPT_HEADER_REVISION_V1_00 0x00010000
#define GPT_HEADER_REVISION_V0_99 0x00009900
#define GPT_HEADER_MINSZ 92 /* bytes */
#define GPT_PMBR_LBA 0
#define GPT_MBR_PROTECTIVE 1
#define GPT_MBR_HYBRID 2
#define GPT_PRIMARY_PARTITION_TABLE_LBA 0x00000001ULL
#define EFI_PMBR_OSTYPE 0xEE
#define MSDOS_MBR_SIGNATURE 0xAA55
#define GPT_PART_NAME_LEN (72 / sizeof(uint16_t))
#define GPT_NPARTITIONS ((size_t) FDISK_GPT_NPARTITIONS_DEFAULT)
/* Globally unique identifier */
struct gpt_guid {
uint32_t time_low;
uint16_t time_mid;
uint16_t time_hi_and_version;
uint8_t clock_seq_hi;
uint8_t clock_seq_low;
uint8_t node[6];
};
/* only checking that the GUID is 0 is enough to verify an empty partition. */
#define GPT_UNUSED_ENTRY_GUID \
((struct gpt_guid) { 0x00000000, 0x0000, 0x0000, 0x00, 0x00, \
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }})
/* Linux native partition type */
#define GPT_DEFAULT_ENTRY_TYPE "0FC63DAF-8483-4772-8E79-3D69D8477DE4"
/*
* Attribute bits
*/
enum {
/* UEFI specific */
GPT_ATTRBIT_REQ = 0,
GPT_ATTRBIT_NOBLOCK = 1,
GPT_ATTRBIT_LEGACY = 2,
/* GUID specific (range 48..64)*/
GPT_ATTRBIT_GUID_FIRST = 48,
GPT_ATTRBIT_GUID_COUNT = 16
};
#define GPT_ATTRSTR_REQ "RequiredPartition"
#define GPT_ATTRSTR_REQ_TYPO "RequiredPartiton"
#define GPT_ATTRSTR_NOBLOCK "NoBlockIOProtocol"
#define GPT_ATTRSTR_LEGACY "LegacyBIOSBootable"
/* The GPT Partition entry array contains an array of GPT entries. */
struct gpt_entry {
struct gpt_guid type; /* purpose and type of the partition */
struct gpt_guid partition_guid;
uint64_t lba_start;
uint64_t lba_end;
uint64_t attrs;
uint16_t name[GPT_PART_NAME_LEN];
} __attribute__ ((packed));
/* GPT header */
struct gpt_header {
uint64_t signature; /* header identification */
uint32_t revision; /* header version */
uint32_t size; /* in bytes */
uint32_t crc32; /* header CRC checksum */
uint32_t reserved1; /* must be 0 */
uint64_t my_lba; /* LBA of block that contains this struct (LBA 1) */
uint64_t alternative_lba; /* backup GPT header */
uint64_t first_usable_lba; /* first usable logical block for partitions */
uint64_t last_usable_lba; /* last usable logical block for partitions */
struct gpt_guid disk_guid; /* unique disk identifier */
uint64_t partition_entry_lba; /* LBA of start of partition entries array */
uint32_t npartition_entries; /* total partition entries - normally 128 */
uint32_t sizeof_partition_entry; /* bytes for each GUID pt */
uint32_t partition_entry_array_crc32; /* partition CRC checksum */
uint8_t reserved2[512 - 92]; /* must all be 0 */
} __attribute__ ((packed));
struct gpt_record {
uint8_t boot_indicator; /* unused by EFI, set to 0x80 for bootable */
uint8_t start_head; /* unused by EFI, pt start in CHS */
uint8_t start_sector; /* unused by EFI, pt start in CHS */
uint8_t start_track;
uint8_t os_type; /* EFI and legacy non-EFI OS types */
uint8_t end_head; /* unused by EFI, pt end in CHS */
uint8_t end_sector; /* unused by EFI, pt end in CHS */
uint8_t end_track; /* unused by EFI, pt end in CHS */
uint32_t starting_lba; /* used by EFI - start addr of the on disk pt */
uint32_t size_in_lba; /* used by EFI - size of pt in LBA */
} __attribute__ ((packed));
/* Protected MBR and legacy MBR share same structure */
struct gpt_legacy_mbr {
uint8_t boot_code[440];
uint32_t unique_mbr_signature;
uint16_t unknown;
struct gpt_record partition_record[4];
uint16_t signature;
} __attribute__ ((packed));
/*
* Here be dragons!
* See: http://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs
*/
#define DEF_GUID(_u, _n) \
{ \
.typestr = (_u), \
.name = (_n), \
}
static struct fdisk_parttype gpt_parttypes[] =
{
#include "pt-gpt-partnames.h"
};
static const struct fdisk_shortcut gpt_parttype_cuts[] =
{
{ .shortcut = "L", .alias = "linux", .data = "0FC63DAF-8483-4772-8E79-3D69D8477DE4" }, /* Linux */
{ .shortcut = "S", .alias = "swap", .data = "0657FD6D-A4AB-43C4-84E5-0933C84B4F4F" }, /* Swap */
{ .shortcut = "H", .alias = "home", .data = "933AC7E1-2EB4-4F13-B844-0E14E2AEF915" }, /* Home */
{ .shortcut = "U", .alias = "uefi", .data = "C12A7328-F81F-11D2-BA4B-00A0C93EC93B" }, /* UEFI system */
{ .shortcut = "R", .alias = "raid", .data = "A19D880F-05FC-4D3B-A006-743F0F84911E" }, /* Linux RAID */
{ .shortcut = "V", .alias = "lvm", .data = "E6D6D379-F507-44C2-A23C-238F2A3DF928" } /* LVM */
};
#define alignment_required(_x) ((_x)->grain != (_x)->sector_size)
/* gpt_entry macros */
#define gpt_partition_start(_e) le64_to_cpu((_e)->lba_start)
#define gpt_partition_end(_e) le64_to_cpu((_e)->lba_end)
/*
* in-memory fdisk GPT stuff
*/
struct fdisk_gpt_label {
struct fdisk_label head; /* generic part */
/* gpt specific part */
struct gpt_header *pheader; /* primary header */
struct gpt_header *bheader; /* backup header */
unsigned char *ents; /* entries (partitions) */
unsigned int no_relocate :1, /* do not fix backup location */
minimize :1;
};
static void gpt_deinit(struct fdisk_label *lb);
static inline struct fdisk_gpt_label *self_label(struct fdisk_context *cxt)
{
return (struct fdisk_gpt_label *) cxt->label;
}
/*
* Returns the partition length, or 0 if end is before beginning.
*/
static uint64_t gpt_partition_size(const struct gpt_entry *e)
{
uint64_t start = gpt_partition_start(e);
uint64_t end = gpt_partition_end(e);
return start > end ? 0 : end - start + 1ULL;
}
/* prints UUID in the real byte order! */
static void gpt_debug_uuid(const char *mesg, struct gpt_guid *guid)
{
const unsigned char *uuid = (unsigned char *) guid;
fprintf(stderr, "%s: "
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
mesg,
uuid[0], uuid[1], uuid[2], uuid[3],
uuid[4], uuid[5],
uuid[6], uuid[7],
uuid[8], uuid[9],
uuid[10], uuid[11], uuid[12], uuid[13], uuid[14],uuid[15]);
}
/*
* UUID is traditionally 16 byte big-endian array, except Intel EFI
* specification where the UUID is a structure of little-endian fields.
*/
static void swap_efi_guid(struct gpt_guid *uid)
{
uid->time_low = swab32(uid->time_low);
uid->time_mid = swab16(uid->time_mid);
uid->time_hi_and_version = swab16(uid->time_hi_and_version);
}
static int string_to_guid(const char *in, struct gpt_guid *guid)
{
if (uuid_parse(in, (unsigned char *) guid)) { /* BE */
DBG(GPT, ul_debug("failed to parse GUID: %s", in));
return -EINVAL;
}
swap_efi_guid(guid); /* LE */
return 0;
}
static char *guid_to_string(const struct gpt_guid *guid, char *out)
{
struct gpt_guid u = *guid; /* LE */
swap_efi_guid(&u); /* BE */
uuid_unparse_upper((unsigned char *) &u, out);
return out;
}
static struct fdisk_parttype *gpt_partition_parttype(
struct fdisk_context *cxt,
const struct gpt_entry *e)
{
struct fdisk_parttype *t;
char str[UUID_STR_LEN];
struct gpt_guid guid = e->type;
guid_to_string(&guid, str);
t = fdisk_label_get_parttype_from_string(cxt->label, str);
return t ? : fdisk_new_unknown_parttype(0, str);
}
static void gpt_entry_set_type(struct gpt_entry *e, struct gpt_guid *uuid)
{
e->type = *uuid;
DBG(GPT, gpt_debug_uuid("new type", uuid));
}
static int gpt_entry_set_name(struct gpt_entry *e, char *str)
{
uint16_t name[GPT_PART_NAME_LEN] = { 0 };
size_t i, mblen = 0;
uint8_t *in = (uint8_t *) str;
for (i = 0; *in && i < GPT_PART_NAME_LEN; in++) {
if (!mblen) {
if (!(*in & 0x80)) {
name[i++] = *in;
} else if ((*in & 0xE0) == 0xC0) {
mblen = 1;
name[i] = (uint16_t)(*in & 0x1F) << (mblen *6);
} else if ((*in & 0xF0) == 0xE0) {
mblen = 2;
name[i] = (uint16_t)(*in & 0x0F) << (mblen *6);
} else {
/* broken UTF-8 or code point greater than U+FFFF */
return -EILSEQ;
}
} else {
/* incomplete UTF-8 sequence */
if ((*in & 0xC0) != 0x80)
return -EILSEQ;
name[i] |= (uint16_t)(*in & 0x3F) << (--mblen *6);
if (!mblen) {
/* check for code points reserved for surrogate pairs*/
if ((name[i] & 0xF800) == 0xD800)
return -EILSEQ;
i++;
}
}
}
for (i = 0; i < GPT_PART_NAME_LEN; i++)
e->name[i] = cpu_to_le16(name[i]);
return (int)((char *) in - str);
}
static int gpt_entry_set_uuid(struct gpt_entry *e, char *str)
{
struct gpt_guid uuid;
int rc;
rc = string_to_guid(str, &uuid);
if (rc)
return rc;
e->partition_guid = uuid;
return 0;
}
static inline int gpt_entry_is_used(const struct gpt_entry *e)
{
return memcmp(&e->type, &GPT_UNUSED_ENTRY_GUID,
sizeof(struct gpt_guid)) != 0;
}
static const char *gpt_get_header_revstr(struct gpt_header *header)
{
if (!header)
goto unknown;
switch (le32_to_cpu(header->revision)) {
case GPT_HEADER_REVISION_V1_02:
return "1.2";
case GPT_HEADER_REVISION_V1_00:
return "1.0";
case GPT_HEADER_REVISION_V0_99:
return "0.99";
default:
goto unknown;
}
unknown:
return "unknown";
}
static inline unsigned char *gpt_get_entry_ptr(struct fdisk_gpt_label *gpt, size_t i)
{
return gpt->ents + le32_to_cpu(gpt->pheader->sizeof_partition_entry) * i;
}
static inline struct gpt_entry *gpt_get_entry(struct fdisk_gpt_label *gpt, size_t i)
{
return (struct gpt_entry *) gpt_get_entry_ptr(gpt, i);
}
static inline struct gpt_entry *gpt_zeroize_entry(struct fdisk_gpt_label *gpt, size_t i)
{
return (struct gpt_entry *) memset(gpt_get_entry_ptr(gpt, i),
0, le32_to_cpu(gpt->pheader->sizeof_partition_entry));
}
/* Use to access array of entries, for() loops, etc. But don't use when
* you directly do something with GPT header, then use uint32_t.
*/
static inline size_t gpt_get_nentries(struct fdisk_gpt_label *gpt)
{
return (size_t) le32_to_cpu(gpt->pheader->npartition_entries);
}
/* calculate size of entries array in bytes for specified number of entries */
static inline int gpt_calculate_sizeof_entries(
struct gpt_header *hdr,
uint32_t nents, size_t *sz)
{
uint32_t esz = hdr ? le32_to_cpu(hdr->sizeof_partition_entry) :
sizeof(struct gpt_entry);
if (nents == 0 || esz == 0 || SIZE_MAX/esz < nents) {
DBG(GPT, ul_debug("entries array size check failed"));
return -ERANGE;
}
*sz = (size_t) nents * esz;
return 0;
}
/* calculate size of entries array in sectors for specified number of entries */
static inline int gpt_calculate_sectorsof_entries(
struct gpt_header *hdr,
uint32_t nents, uint64_t *sz,
struct fdisk_context *cxt)
{
size_t esz = 0;
int rc = gpt_calculate_sizeof_entries(hdr, nents, &esz); /* in bytes */
if (rc == 0)
*sz = (esz + cxt->sector_size - 1) / cxt->sector_size;
return rc;
}
/* calculate alternative (backup) entries array offset from primary header */
static inline int gpt_calculate_alternative_entries_lba(
struct gpt_header *hdr,
uint32_t nents,
uint64_t *sz,
struct fdisk_context *cxt)
{
uint64_t esects = 0;
int rc = gpt_calculate_sectorsof_entries(hdr, nents, &esects, cxt);
if (rc)
return rc;
if (cxt->total_sectors < 1ULL + esects)
return -ENOSPC;
*sz = cxt->total_sectors - 1ULL - esects;
return 0;
}
static inline int gpt_calculate_last_lba(
struct gpt_header *hdr,
uint32_t nents,
uint64_t *sz,
struct fdisk_context *cxt)
{
uint64_t esects = 0;
int rc = gpt_calculate_sectorsof_entries(hdr, nents, &esects, cxt);
if (rc)
return rc;
if (cxt->total_sectors < 2ULL + esects)
return -ENOSPC;
*sz = cxt->total_sectors - 2ULL - esects;
return 0;
}
static inline int gpt_calculate_first_lba(
struct gpt_header *hdr,
uint32_t nents,
uint64_t *sz,
struct fdisk_context *cxt)
{
uint64_t esects = 0;
int rc = gpt_calculate_sectorsof_entries(hdr, nents, &esects, cxt);
if (rc == 0)
*sz = esects + 2ULL;
return rc;
}
/* the current size of entries array in bytes */
static inline int gpt_sizeof_entries(struct gpt_header *hdr, size_t *sz)
{
return gpt_calculate_sizeof_entries(hdr, le32_to_cpu(hdr->npartition_entries), sz);
}
static char *gpt_get_header_id(struct gpt_header *header)
{
char str[UUID_STR_LEN];
struct gpt_guid guid = header->disk_guid;
guid_to_string(&guid, str);
return strdup(str);
}
/*
* Builds a clean new valid protective MBR - will wipe out any existing data.
* Returns 0 on success, otherwise < 0 on error.
*/
static int gpt_mknew_pmbr(struct fdisk_context *cxt)
{
struct gpt_legacy_mbr *pmbr = NULL;
int rc;
if (!cxt || !cxt->firstsector)
return -ENOSYS;
if (fdisk_has_protected_bootbits(cxt))
rc = fdisk_init_firstsector_buffer(cxt, 0, MBR_PT_BOOTBITS_SIZE);
else
rc = fdisk_init_firstsector_buffer(cxt, 0, 0);
if (rc)
return rc;
pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
memset(pmbr->partition_record, 0, sizeof(pmbr->partition_record));
pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
pmbr->partition_record[0].start_sector = 2;
pmbr->partition_record[0].end_head = 0xFF;
pmbr->partition_record[0].end_sector = 0xFF;
pmbr->partition_record[0].end_track = 0xFF;
pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
pmbr->partition_record[0].size_in_lba =
cpu_to_le32((uint32_t) min( cxt->total_sectors - 1ULL, 0xFFFFFFFFULL) );
return 0;
}
/* Move backup header to the end of the device */
static int gpt_fix_alternative_lba(struct fdisk_context *cxt, struct fdisk_gpt_label *gpt)
{
struct gpt_header *p, *b;
uint64_t x = 0, orig;
size_t nents;
int rc;
if (!cxt)
return -EINVAL;
p = gpt->pheader; /* primary */
b = gpt->bheader; /* backup */
nents = le32_to_cpu(p->npartition_entries);
orig = le64_to_cpu(p->alternative_lba);
/* reference from primary to backup */
p->alternative_lba = cpu_to_le64(cxt->total_sectors - 1ULL);
/* reference from backup to primary */
b->alternative_lba = p->my_lba;
b->my_lba = p->alternative_lba;
/* fix backup partitions array address */
rc = gpt_calculate_alternative_entries_lba(p, nents, &x, cxt);
if (rc)
goto failed;
b->partition_entry_lba = cpu_to_le64(x);
/* update last usable LBA */
rc = gpt_calculate_last_lba(p, nents, &x, cxt);
if (rc)
goto failed;
p->last_usable_lba = cpu_to_le64(x);
b->last_usable_lba = cpu_to_le64(x);
DBG(GPT, ul_debug("Alternative-LBA updated from %"PRIu64" to %"PRIu64,
orig, le64_to_cpu(p->alternative_lba)));
return 0;
failed:
DBG(GPT, ul_debug("failed to fix alternative-LBA [rc=%d]", rc));
return rc;
}
static uint64_t gpt_calculate_minimal_size(struct fdisk_context *cxt, struct fdisk_gpt_label *gpt)
{
size_t i;
uint64_t x = 0, total = 0;
struct gpt_header *hdr;
assert(cxt);
assert(gpt);
assert(gpt->pheader);
assert(gpt->ents);
hdr = gpt->pheader;
/* LBA behind the last partition */
for (i = 0; i < gpt_get_nentries(gpt); i++) {
struct gpt_entry *e = gpt_get_entry(gpt, i);
if (gpt_entry_is_used(e)) {
uint64_t end = gpt_partition_end(e);
if (end > x)
x = end;
}
}
total = x + 1;
/* the current last LBA usable for partitions */
gpt_calculate_last_lba(hdr, le32_to_cpu(hdr->npartition_entries), &x, cxt);
/* size of all stuff at the end of the device */
total += cxt->total_sectors - x;
DBG(GPT, ul_debug("minimal device is %"PRIu64, total));
return total;
}
static int gpt_possible_minimize(struct fdisk_context *cxt, struct fdisk_gpt_label *gpt)
{
struct gpt_header *hdr = gpt->pheader;
uint64_t total = gpt_calculate_minimal_size(cxt, gpt);
return le64_to_cpu(hdr->alternative_lba) > (total - 1ULL);
}
/* move backup header behind the last partition */
static int gpt_minimize_alternative_lba(struct fdisk_context *cxt, struct fdisk_gpt_label *gpt)
{
uint64_t total = gpt_calculate_minimal_size(cxt, gpt);
uint64_t orig = cxt->total_sectors;
int rc;
/* Let's temporary change size of the device to recalculate backup header */
cxt->total_sectors = total;
rc = gpt_fix_alternative_lba(cxt, gpt);
if (rc)
return rc;
cxt->total_sectors = orig;
fdisk_label_set_changed(cxt->label, 1);
return 0;
}
/* some universal differences between the headers */
static void gpt_mknew_header_common(struct fdisk_context *cxt,
struct gpt_header *header, uint64_t lba)
{
if (!cxt || !header)
return;
header->my_lba = cpu_to_le64(lba);
if (lba == GPT_PRIMARY_PARTITION_TABLE_LBA) {
/* primary */
header->alternative_lba = cpu_to_le64(cxt->total_sectors - 1ULL);
header->partition_entry_lba = cpu_to_le64(2ULL);
} else {
/* backup */
uint64_t x = 0;
gpt_calculate_alternative_entries_lba(header,
le32_to_cpu(header->npartition_entries), &x, cxt);
header->alternative_lba = cpu_to_le64(GPT_PRIMARY_PARTITION_TABLE_LBA);
header->partition_entry_lba = cpu_to_le64(x);
}
}
/*
* Builds a new GPT header (at sector lba) from a backup header2.
* If building a primary header, then backup is the secondary, and vice versa.
*
* Always pass a new (zeroized) header to build upon as we don't
* explicitly zero-set some values such as CRCs and reserved.
*
* Returns 0 on success, otherwise < 0 on error.
*/
static int gpt_mknew_header_from_bkp(struct fdisk_context *cxt,
struct gpt_header *header,
uint64_t lba,
struct gpt_header *header2)
{
if (!cxt || !header || !header2)
return -ENOSYS;
header->signature = header2->signature;
header->revision = header2->revision;
header->size = header2->size;
header->npartition_entries = header2->npartition_entries;
header->sizeof_partition_entry = header2->sizeof_partition_entry;
header->first_usable_lba = header2->first_usable_lba;
header->last_usable_lba = header2->last_usable_lba;
memcpy(&header->disk_guid,
&header2->disk_guid, sizeof(header2->disk_guid));
gpt_mknew_header_common(cxt, header, lba);
return 0;
}
static struct gpt_header *gpt_copy_header(struct fdisk_context *cxt,
struct gpt_header *src)
{
struct gpt_header *res;
if (!cxt || !src)
return NULL;
assert(cxt->sector_size >= sizeof(struct gpt_header));
res = calloc(1, cxt->sector_size);
if (!res) {
fdisk_warn(cxt, _("failed to allocate GPT header"));
return NULL;
}
res->my_lba = src->alternative_lba;
res->alternative_lba = src->my_lba;
res->signature = src->signature;
res->revision = src->revision;
res->size = src->size;
res->npartition_entries = src->npartition_entries;
res->sizeof_partition_entry = src->sizeof_partition_entry;
res->first_usable_lba = src->first_usable_lba;
res->last_usable_lba = src->last_usable_lba;
memcpy(&res->disk_guid, &src->disk_guid, sizeof(src->disk_guid));
if (res->my_lba == GPT_PRIMARY_PARTITION_TABLE_LBA)
res->partition_entry_lba = cpu_to_le64(2ULL);
else {
uint64_t esz = (uint64_t) le32_to_cpu(src->npartition_entries) * sizeof(struct gpt_entry);
uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
res->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1ULL - esects);
}
return res;
}
static int get_script_u64(struct fdisk_context *cxt, uint64_t *num, const char *name)
{
const char *str;
int pwr = 0, rc = 0;
assert(cxt);
*num = 0;
if (!cxt->script)
return 1;
str = fdisk_script_get_header(cxt->script, name);
if (!str)
return 1;
rc = parse_size(str, (uintmax_t *) num, &pwr);
if (rc < 0)
return rc;
if (pwr)
*num /= cxt->sector_size;
return 0;
}
static int count_first_last_lba(struct fdisk_context *cxt,
uint64_t *first, uint64_t *last,
uint32_t *maxents)
{
int rc = 0;
uint64_t flba = 0, llba = 0;
uint64_t nents = GPT_NPARTITIONS;
assert(cxt);
assert(first);
assert(last);
*first = *last = 0;
/* Get the table length from the script, if given */
if (cxt->script) {
rc = get_script_u64(cxt, &nents, "table-length");
if (rc == 1)
nents = GPT_NPARTITIONS; /* undefined by script */
else if (rc < 0)
return rc;
}
/* The table length was not changed by the script, compute it. */
if (flba == 0) {
/* If the device is not large enough reduce this number of
* partitions and try to recalculate it again, until we get
* something useful or return error.
*/
for (; nents > 0; nents--) {
rc = gpt_calculate_last_lba(NULL, nents, &llba, cxt);
if (rc == 0)
rc = gpt_calculate_first_lba(NULL, nents, &flba, cxt);
if (llba < flba)
rc = -ENOSPC;
else if (rc == 0)
break;
}
}
if (rc)
return rc;
if (maxents)
*maxents = nents;
/* script default */
if (cxt->script) {
rc = get_script_u64(cxt, first, "first-lba");
if (rc < 0)
return rc;
DBG(GPT, ul_debug("FirstLBA: script=%"PRIu64", uefi=%"PRIu64", topology=%ju.",
*first, flba, (uintmax_t)cxt->first_lba));
if (rc == 0 && (*first < flba || *first > llba)) {
fdisk_warnx(cxt, _("First LBA specified by script is out of range."));
return -ERANGE;
}
rc = get_script_u64(cxt, last, "last-lba");
if (rc < 0)
return rc;
DBG(GPT, ul_debug("LastLBA: script=%"PRIu64", uefi=%"PRIu64", topology=%ju.",
*last, llba, (uintmax_t)cxt->last_lba));
if (rc == 0 && (*last > llba || *last < flba)) {
fdisk_warnx(cxt, _("Last LBA specified by script is out of range."));
return -ERANGE;
}
}
if (!*last)
*last = llba;
/* default by topology */
if (!*first)
*first = flba < cxt->first_lba &&
cxt->first_lba < *last ? cxt->first_lba : flba;
return 0;
}
/*
* Builds a clean new GPT header (currently under revision 1.0).
*
* Always pass a new (zeroized) header to build upon as we don't
* explicitly zero-set some values such as CRCs and reserved.
*
* Returns 0 on success, otherwise < 0 on error.
*/
static int gpt_mknew_header(struct fdisk_context *cxt,
struct gpt_header *header, uint64_t lba)
{
uint64_t first, last;
uint32_t nents = 0;
int has_id = 0, rc;
if (!cxt || !header)
return -ENOSYS;
header->signature = cpu_to_le64(GPT_HEADER_SIGNATURE);
header->revision = cpu_to_le32(GPT_HEADER_REVISION_V1_00);
/* According to EFI standard it's valid to count all the first
* sector into header size, but some tools may have a problem
* to accept it, so use the header without the zeroed area.
* This does not have any impact to CRC, etc. --kzak Jan-2015
*/
header->size = cpu_to_le32(sizeof(struct gpt_header)
- sizeof(header->reserved2));
/* Set {First,Last}LBA and number of the partitions
* (default is GPT_NPARTITIONS) */
rc = count_first_last_lba(cxt, &first, &last, &nents);
if (rc)
return rc;
header->npartition_entries = cpu_to_le32(nents);
header->sizeof_partition_entry = cpu_to_le32(sizeof(struct gpt_entry));
header->first_usable_lba = cpu_to_le64(first);
header->last_usable_lba = cpu_to_le64(last);
gpt_mknew_header_common(cxt, header, lba);
if (cxt->script) {
const char *id = fdisk_script_get_header(cxt->script, "label-id");
struct gpt_guid guid = header->disk_guid;
if (id && string_to_guid(id, &guid) == 0)
has_id = 1;
header->disk_guid = guid;
}
if (!has_id) {
struct gpt_guid guid;
uuid_generate_random((unsigned char *) &guid);
swap_efi_guid(&guid);
header->disk_guid = guid;
}
return 0;
}
/*
* Checks if there is a valid protective MBR partition table.
* Returns 0 if it is invalid or failure. Otherwise, return
* GPT_MBR_PROTECTIVE or GPT_MBR_HYBRID, depending on the detection.
*/
static int valid_pmbr(struct fdisk_context *cxt)
{
int i, part = 0, ret = 0; /* invalid by default */
struct gpt_legacy_mbr *pmbr = NULL;
if (!cxt->firstsector)
goto done;
pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
if (le16_to_cpu(pmbr->signature) != MSDOS_MBR_SIGNATURE)
goto done;
/* seems like a valid MBR was found, check DOS primary partitions */
for (i = 0; i < 4; i++) {
if (pmbr->partition_record[i].os_type == EFI_PMBR_OSTYPE) {
/*
* Ok, we at least know that there's a protective MBR,
* now check if there are other partition types for
* hybrid MBR.
*/
part = i;
ret = GPT_MBR_PROTECTIVE;
break;
}
}
if (ret != GPT_MBR_PROTECTIVE)
goto done;
for (i = 0 ; i < 4; i++) {
if ((pmbr->partition_record[i].os_type != EFI_PMBR_OSTYPE) &&
(pmbr->partition_record[i].os_type != 0x00)) {
ret = GPT_MBR_HYBRID;
goto done;
}
}
/* LBA of the GPT partition header */
if (pmbr->partition_record[part].starting_lba !=
cpu_to_le32(GPT_PRIMARY_PARTITION_TABLE_LBA))
goto done;
/*
* Protective MBRs take up the lesser of the whole disk
* or 2 TiB (32bit LBA), ignoring the rest of the disk.
* Some partitioning programs, nonetheless, choose to set
* the size to the maximum 32-bit limitation, disregarding
* the disk size.
*
* Hybrid MBRs do not necessarily comply with this.
*
* Consider a bad value here to be a warning to support dd-ing
* an image from a smaller disk to a bigger disk.
*/
if (ret == GPT_MBR_PROTECTIVE) {
uint64_t sz_lba = (uint64_t) le32_to_cpu(pmbr->partition_record[part].size_in_lba);
if (sz_lba != cxt->total_sectors - 1ULL && sz_lba != 0xFFFFFFFFULL) {
fdisk_warnx(cxt, _("GPT PMBR size mismatch (%"PRIu64" != %"PRIu64") "
"will be corrected by write."),
sz_lba, cxt->total_sectors - (uint64_t) 1);
/* Note that gpt_write_pmbr() overwrites PMBR, but we want to keep it valid already
* in memory too to disable warnings when valid_pmbr() called next time */
pmbr->partition_record[part].size_in_lba =
cpu_to_le32((uint32_t) min( cxt->total_sectors - 1ULL, 0xFFFFFFFFULL) );
fdisk_label_set_changed(cxt->label, 1);
}
}
done:
DBG(GPT, ul_debug("PMBR type: %s",
ret == GPT_MBR_PROTECTIVE ? "protective" :
ret == GPT_MBR_HYBRID ? "hybrid" : "???" ));
return ret;
}
static uint64_t last_lba(struct fdisk_context *cxt)
{
struct stat s;
uint64_t sectors = 0;
memset(&s, 0, sizeof(s));
if (fstat(cxt->dev_fd, &s) == -1) {
fdisk_warn(cxt, _("gpt: stat() failed"));
return 0;
}
if (S_ISBLK(s.st_mode))
sectors = cxt->total_sectors - 1ULL;
else if (S_ISREG(s.st_mode))
sectors = ((uint64_t) s.st_size /
(uint64_t) cxt->sector_size) - 1ULL;
else
fdisk_warnx(cxt, _("gpt: cannot handle files with mode %o"), s.st_mode);
DBG(GPT, ul_debug("last LBA: %"PRIu64"", sectors));
return sectors;
}
static ssize_t read_lba(struct fdisk_context *cxt, uint64_t lba,
void *buffer, const size_t bytes)
{
off_t offset = lba * cxt->sector_size;
if (lseek(cxt->dev_fd, offset, SEEK_SET) == (off_t) -1)
return -1;