]> git.ipfire.org Git - thirdparty/util-linux.git/blob - libfdisk/src/gpt.c
Merge branch 'master' of https://github.com/yurchor/util-linux
[thirdparty/util-linux.git] / libfdisk / src / gpt.c
1 /*
2 * Copyright (C) 2007 Karel Zak <kzak@redhat.com>
3 * Copyright (C) 2012 Davidlohr Bueso <dave@gnu.org>
4 *
5 * GUID Partition Table (GPT) support. Based on UEFI Specs 2.3.1
6 * Chapter 5: GUID Partition Table (GPT) Disk Layout (Jun 27th, 2012).
7 * Some ideas and inspiration from GNU parted and gptfdisk.
8 */
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <inttypes.h>
13 #include <sys/stat.h>
14 #include <sys/utsname.h>
15 #include <sys/types.h>
16 #include <fcntl.h>
17 #include <unistd.h>
18 #include <errno.h>
19 #include <ctype.h>
20 #include <uuid.h>
21
22 #include "fdiskP.h"
23
24 #include "nls.h"
25 #include "crc32.h"
26 #include "blkdev.h"
27 #include "bitops.h"
28 #include "strutils.h"
29 #include "all-io.h"
30
31 #define GPT_HEADER_SIGNATURE 0x5452415020494645LL /* EFI PART */
32 #define GPT_HEADER_REVISION_V1_02 0x00010200
33 #define GPT_HEADER_REVISION_V1_00 0x00010000
34 #define GPT_HEADER_REVISION_V0_99 0x00009900
35 #define GPT_HEADER_MINSZ 92 /* bytes */
36
37 #define GPT_PMBR_LBA 0
38 #define GPT_MBR_PROTECTIVE 1
39 #define GPT_MBR_HYBRID 2
40
41 #define GPT_PRIMARY_PARTITION_TABLE_LBA 0x00000001
42
43 #define EFI_PMBR_OSTYPE 0xEE
44 #define MSDOS_MBR_SIGNATURE 0xAA55
45 #define GPT_PART_NAME_LEN 72 / sizeof(uint16_t)
46 #define GPT_NPARTITIONS 128
47
48 /* Globally unique identifier */
49 struct gpt_guid {
50 uint32_t time_low;
51 uint16_t time_mid;
52 uint16_t time_hi_and_version;
53 uint8_t clock_seq_hi;
54 uint8_t clock_seq_low;
55 uint8_t node[6];
56 };
57
58
59 /* only checking that the GUID is 0 is enough to verify an empty partition. */
60 #define GPT_UNUSED_ENTRY_GUID \
61 ((struct gpt_guid) { 0x00000000, 0x0000, 0x0000, 0x00, 0x00, \
62 { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }})
63
64 /* Linux native partition type */
65 #define GPT_DEFAULT_ENTRY_TYPE "0FC63DAF-8483-4772-8E79-3D69D8477DE4"
66
67 /*
68 * Attribute bits
69 */
70 struct gpt_attr {
71 uint64_t required_to_function:1;
72 uint64_t no_blockio_protocol:1;
73 uint64_t legacy_bios_bootable:1;
74 uint64_t reserved:45;
75 uint64_t guid_secific:16;
76 } __attribute__ ((packed));
77
78 /* The GPT Partition entry array contains an array of GPT entries. */
79 struct gpt_entry {
80 struct gpt_guid type; /* purpose and type of the partition */
81 struct gpt_guid partition_guid;
82 uint64_t lba_start;
83 uint64_t lba_end;
84 struct gpt_attr attr;
85 uint16_t name[GPT_PART_NAME_LEN];
86 } __attribute__ ((packed));
87
88 /* GPT header */
89 struct gpt_header {
90 uint64_t signature; /* header identification */
91 uint32_t revision; /* header version */
92 uint32_t size; /* in bytes */
93 uint32_t crc32; /* header CRC checksum */
94 uint32_t reserved1; /* must be 0 */
95 uint64_t my_lba; /* LBA that contains this struct (LBA 1) */
96 uint64_t alternative_lba; /* backup GPT header */
97 uint64_t first_usable_lba; /* first usable logical block for partitions */
98 uint64_t last_usable_lba; /* last usable logical block for partitions */
99 struct gpt_guid disk_guid; /* unique disk identifier */
100 uint64_t partition_entry_lba; /* stat LBA of the partition entry array */
101 uint32_t npartition_entries; /* total partition entries - normally 128 */
102 uint32_t sizeof_partition_entry; /* bytes for each GUID pt */
103 uint32_t partition_entry_array_crc32; /* partition CRC checksum */
104 uint8_t reserved2[512 - 92]; /* must be 0 */
105 } __attribute__ ((packed));
106
107 struct gpt_record {
108 uint8_t boot_indicator; /* unused by EFI, set to 0x80 for bootable */
109 uint8_t start_head; /* unused by EFI, pt start in CHS */
110 uint8_t start_sector; /* unused by EFI, pt start in CHS */
111 uint8_t start_track;
112 uint8_t os_type; /* EFI and legacy non-EFI OS types */
113 uint8_t end_head; /* unused by EFI, pt end in CHS */
114 uint8_t end_sector; /* unused by EFI, pt end in CHS */
115 uint8_t end_track; /* unused by EFI, pt end in CHS */
116 uint32_t starting_lba; /* used by EFI - start addr of the on disk pt */
117 uint32_t size_in_lba; /* used by EFI - size of pt in LBA */
118 } __attribute__ ((packed));
119
120 /* Protected MBR and legacy MBR share same structure */
121 struct gpt_legacy_mbr {
122 uint8_t boot_code[440];
123 uint32_t unique_mbr_signature;
124 uint16_t unknown;
125 struct gpt_record partition_record[4];
126 uint16_t signature;
127 } __attribute__ ((packed));
128
129 /*
130 * Here be dragons!
131 * See: http://en.wikipedia.org/wiki/GUID_Partition_Table#Partition_type_GUIDs
132 */
133 #define DEF_GUID(_u, _n) \
134 { \
135 .typestr = (_u), \
136 .name = (_n), \
137 }
138
139 static struct fdisk_parttype gpt_parttypes[] =
140 {
141 /* Generic OS */
142 DEF_GUID("C12A7328-F81F-11D2-BA4B-00A0C93EC93B", N_("EFI System")),
143
144 DEF_GUID("024DEE41-33E7-11D3-9D69-0008C781F39F", N_("MBR partition scheme")),
145 /* Hah!IdontneedEFI */
146 DEF_GUID("21686148-6449-6E6F-744E-656564454649", N_("BIOS boot partition")),
147
148 /* Windows */
149 DEF_GUID("E3C9E316-0B5C-4DB8-817D-F92DF00215AE", N_("Microsoft reserved")),
150 DEF_GUID("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7", N_("Microsoft basic data")),
151 DEF_GUID("5808C8AA-7E8F-42E0-85D2-E1E90434CFB3", N_("Microsoft LDM metadata")),
152 DEF_GUID("AF9B60A0-1431-4F62-BC68-3311714A69AD", N_("Microsoft LDM data")),
153 DEF_GUID("DE94BBA4-06D1-4D40-A16A-BFD50179D6AC", N_("Windows recovery environment")),
154 DEF_GUID("37AFFC90-EF7D-4E96-91C3-2D7AE055B174", N_("IBM General Parallel Fs")),
155
156 /* HP-UX */
157 DEF_GUID("75894C1E-3AEB-11D3-B7C1-7B03A0000000", N_("HP-UX data partition")),
158 DEF_GUID("E2A1E728-32E3-11D6-A682-7B03A0000000", N_("HP-UX service partition")),
159
160 /* Linux */
161 DEF_GUID("0FC63DAF-8483-4772-8E79-3D69D8477DE4", N_("Linux filesystem")),
162 DEF_GUID("A19D880F-05FC-4D3B-A006-743F0F84911E", N_("Linux RAID")),
163 DEF_GUID("0657FD6D-A4AB-43C4-84E5-0933C84B4F4F", N_("Linux swap")),
164 DEF_GUID("E6D6D379-F507-44C2-A23C-238F2A3DF928", N_("Linux LVM")),
165 DEF_GUID("8DA63339-0007-60C0-C436-083AC8230908", N_("Linux reserved")),
166
167 /* FreeBSD */
168 DEF_GUID("516E7CB4-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD data")),
169 DEF_GUID("83BD6B9D-7F41-11DC-BE0B-001560B84F0F", N_("FreeBSD boot")),
170 DEF_GUID("516E7CB5-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD swap")),
171 DEF_GUID("516E7CB6-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD UFS")),
172 DEF_GUID("516E7CBA-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD ZFS")),
173 DEF_GUID("516E7CB8-6ECF-11D6-8FF8-00022D09712B", N_("FreeBSD Vinum")),
174
175 /* Apple OSX */
176 DEF_GUID("48465300-0000-11AA-AA11-00306543ECAC", N_("Apple HFS/HFS+")),
177 DEF_GUID("55465300-0000-11AA-AA11-00306543ECAC", N_("Apple UFS")),
178 DEF_GUID("52414944-0000-11AA-AA11-00306543ECAC", N_("Apple RAID")),
179 DEF_GUID("52414944-5F4F-11AA-AA11-00306543ECAC", N_("Apple RAID offline")),
180 DEF_GUID("426F6F74-0000-11AA-AA11-00306543ECAC", N_("Apple boot")),
181 DEF_GUID("4C616265-6C00-11AA-AA11-00306543ECAC", N_("Apple label")),
182 DEF_GUID("5265636F-7665-11AA-AA11-00306543ECAC", N_("Apple TV recovery")),
183 DEF_GUID("53746F72-6167-11AA-AA11-00306543ECAC", N_("Apple Core storage")),
184
185 /* Solaris */
186 DEF_GUID("6A82CB45-1DD2-11B2-99A6-080020736631", N_("Solaris boot")),
187 DEF_GUID("6A85CF4D-1DD2-11B2-99A6-080020736631", N_("Solaris root")),
188 /* same as Apple ZFS */
189 DEF_GUID("6A898CC3-1DD2-11B2-99A6-080020736631", N_("Solaris /usr & Apple ZFS")),
190 DEF_GUID("6A87C46F-1DD2-11B2-99A6-080020736631", N_("Solaris swap")),
191 DEF_GUID("6A8B642B-1DD2-11B2-99A6-080020736631", N_("Solaris backup")),
192 DEF_GUID("6A8EF2E9-1DD2-11B2-99A6-080020736631", N_("Solaris /var")),
193 DEF_GUID("6A90BA39-1DD2-11B2-99A6-080020736631", N_("Solaris /home")),
194 DEF_GUID("6A9283A5-1DD2-11B2-99A6-080020736631", N_("Solaris alternate sector")),
195 DEF_GUID("6A945A3B-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 1")),
196 DEF_GUID("6A9630D1-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 2")),
197 DEF_GUID("6A980767-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 3")),
198 DEF_GUID("6A96237F-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 4")),
199 DEF_GUID("6A8D2AC7-1DD2-11B2-99A6-080020736631", N_("Solaris reserved 5")),
200
201 /* NetBSD */
202 DEF_GUID("49F48D32-B10E-11DC-B99B-0019D1879648", N_("NetBSD swap")),
203 DEF_GUID("49F48D5A-B10E-11DC-B99B-0019D1879648", N_("NetBSD FFS")),
204 DEF_GUID("49F48D82-B10E-11DC-B99B-0019D1879648", N_("NetBSD LFS")),
205 DEF_GUID("2DB519C4-B10E-11DC-B99B-0019D1879648", N_("NetBSD concatenated")),
206 DEF_GUID("2DB519EC-B10E-11DC-B99B-0019D1879648", N_("NetBSD encrypted")),
207 DEF_GUID("49F48DAA-B10E-11DC-B99B-0019D1879648", N_("NetBSD RAID")),
208
209 /* ChromeOS */
210 DEF_GUID("FE3A2A5D-4F32-41A7-B725-ACCC3285A309", N_("ChromeOS kernel")),
211 DEF_GUID("3CB8E202-3B7E-47DD-8A3C-7FF2A13CFCEC", N_("ChromeOS root fs")),
212 DEF_GUID("2E0A753D-9E48-43B0-8337-B15192CB1B5E", N_("ChromeOS reserved")),
213
214 /* MidnightBSD */
215 DEF_GUID("85D5E45A-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD data")),
216 DEF_GUID("85D5E45E-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD boot")),
217 DEF_GUID("85D5E45B-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD swap")),
218 DEF_GUID("0394Ef8B-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD UFS")),
219 DEF_GUID("85D5E45D-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD ZFS")),
220 DEF_GUID("85D5E45C-237C-11E1-B4B3-E89A8F7FC3A7", N_("MidnightBSD Vinum")),
221 };
222
223 /* gpt_entry macros */
224 #define gpt_partition_start(_e) le64_to_cpu((_e)->lba_start)
225 #define gpt_partition_end(_e) le64_to_cpu((_e)->lba_end)
226
227 /*
228 * in-memory fdisk GPT stuff
229 */
230 struct fdisk_gpt_label {
231 struct fdisk_label head; /* generic part */
232
233 /* gpt specific part */
234 struct gpt_header *pheader; /* primary header */
235 struct gpt_header *bheader; /* backup header */
236 struct gpt_entry *ents; /* entries (partitions) */
237 };
238
239 static void gpt_deinit(struct fdisk_label *lb);
240 static struct fdisk_parttype *gpt_get_partition_type(struct fdisk_context *cxt, size_t i);
241
242 static inline struct fdisk_gpt_label *self_label(struct fdisk_context *cxt)
243 {
244 return (struct fdisk_gpt_label *) cxt->label;
245 }
246
247 /*
248 * Returns the partition length, or 0 if end is before beginning.
249 */
250 static uint64_t gpt_partition_size(const struct gpt_entry *e)
251 {
252 uint64_t start = gpt_partition_start(e);
253 uint64_t end = gpt_partition_end(e);
254
255 return start > end ? 0 : end - start + 1ULL;
256 }
257
258 #ifdef CONFIG_LIBFDISK_DEBUG
259 /* prints UUID in the real byte order! */
260 static void dbgprint_uuid(const char *mesg, struct gpt_guid *guid)
261 {
262 const unsigned char *uuid = (unsigned char *) guid;
263
264 fprintf(stderr, "%s: "
265 "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
266 mesg,
267 uuid[0], uuid[1], uuid[2], uuid[3],
268 uuid[4], uuid[5],
269 uuid[6], uuid[7],
270 uuid[8], uuid[9],
271 uuid[10], uuid[11], uuid[12], uuid[13], uuid[14],uuid[15]);
272 }
273 #endif
274
275 /*
276 * UUID is traditionally 16 byte big-endian array, except Intel EFI
277 * specification where the UUID is a structure of little-endian fields.
278 */
279 static void swap_efi_guid(struct gpt_guid *uid)
280 {
281 uid->time_low = swab32(uid->time_low);
282 uid->time_mid = swab16(uid->time_mid);
283 uid->time_hi_and_version = swab16(uid->time_hi_and_version);
284 }
285
286 static int string_to_guid(const char *in, struct gpt_guid *guid)
287 {
288 if (uuid_parse(in, (unsigned char *) guid)) /* BE */
289 return -1;
290 swap_efi_guid(guid); /* LE */
291 return 0;
292 }
293
294 static char *guid_to_string(struct gpt_guid *guid, char *out)
295 {
296 struct gpt_guid u = *guid; /* LE */
297
298 swap_efi_guid(&u); /* BE */
299 uuid_unparse_upper((unsigned char *) &u, out);
300
301 return out;
302 }
303
304 static const char *gpt_get_header_revstr(struct gpt_header *header)
305 {
306 if (!header)
307 goto unknown;
308
309 switch (header->revision) {
310 case GPT_HEADER_REVISION_V1_02:
311 return "1.2";
312 case GPT_HEADER_REVISION_V1_00:
313 return "1.0";
314 case GPT_HEADER_REVISION_V0_99:
315 return "0.99";
316 default:
317 goto unknown;
318 }
319
320 unknown:
321 return "unknown";
322 }
323
324 static inline int partition_unused(const struct gpt_entry *e)
325 {
326 return !memcmp(&e->type, &GPT_UNUSED_ENTRY_GUID,
327 sizeof(struct gpt_guid));
328 }
329
330 /*
331 * Builds a clean new valid protective MBR - will wipe out any existing data.
332 * Returns 0 on success, otherwise < 0 on error.
333 */
334 static int gpt_mknew_pmbr(struct fdisk_context *cxt)
335 {
336 struct gpt_legacy_mbr *pmbr = NULL;
337
338 if (!cxt || !cxt->firstsector)
339 return -ENOSYS;
340
341 fdisk_zeroize_firstsector(cxt);
342
343 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
344
345 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
346 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
347 pmbr->partition_record[0].start_sector = 1;
348 pmbr->partition_record[0].end_head = 0xFE;
349 pmbr->partition_record[0].end_sector = 0xFF;
350 pmbr->partition_record[0].end_track = 0xFF;
351 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
352 pmbr->partition_record[0].size_in_lba =
353 cpu_to_le32(min((uint32_t) cxt->total_sectors - 1, 0xFFFFFFFF));
354
355 return 0;
356 }
357
358 /* some universal differences between the headers */
359 static void gpt_mknew_header_common(struct fdisk_context *cxt,
360 struct gpt_header *header, uint64_t lba)
361 {
362 if (!cxt || !header)
363 return;
364
365 header->my_lba = cpu_to_le64(lba);
366
367 if (lba == GPT_PRIMARY_PARTITION_TABLE_LBA) { /* primary */
368 header->alternative_lba = cpu_to_le64(cxt->total_sectors - 1);
369 header->partition_entry_lba = cpu_to_le64(2);
370 } else { /* backup */
371 uint64_t esz = le32_to_cpu(header->npartition_entries) * sizeof(struct gpt_entry);
372 uint64_t esects = (esz + cxt->sector_size - 1) / cxt->sector_size;
373
374 header->alternative_lba = cpu_to_le64(GPT_PRIMARY_PARTITION_TABLE_LBA);
375 header->partition_entry_lba = cpu_to_le64(cxt->total_sectors - 1 - esects);
376 }
377 }
378
379 /*
380 * Builds a new GPT header (at sector lba) from a backup header2.
381 * If building a primary header, then backup is the secondary, and vice versa.
382 *
383 * Always pass a new (zeroized) header to build upon as we don't
384 * explicitly zero-set some values such as CRCs and reserved.
385 *
386 * Returns 0 on success, otherwise < 0 on error.
387 */
388 static int gpt_mknew_header_from_bkp(struct fdisk_context *cxt,
389 struct gpt_header *header,
390 uint64_t lba,
391 struct gpt_header *header2)
392 {
393 if (!cxt || !header || !header2)
394 return -ENOSYS;
395
396 header->signature = header2->signature;
397 header->revision = header2->revision;
398 header->size = header2->size;
399 header->npartition_entries = header2->npartition_entries;
400 header->sizeof_partition_entry = header2->sizeof_partition_entry;
401 header->first_usable_lba = header2->first_usable_lba;
402 header->last_usable_lba = header2->last_usable_lba;
403
404 memcpy(&header->disk_guid,
405 &header2->disk_guid, sizeof(header2->disk_guid));
406 gpt_mknew_header_common(cxt, header, lba);
407
408 return 0;
409 }
410
411 /*
412 * Builds a clean new GPT header (currently under revision 1.0).
413 *
414 * Always pass a new (zeroized) header to build upon as we don't
415 * explicitly zero-set some values such as CRCs and reserved.
416 *
417 * Returns 0 on success, otherwise < 0 on error.
418 */
419 static int gpt_mknew_header(struct fdisk_context *cxt,
420 struct gpt_header *header, uint64_t lba)
421 {
422 uint64_t esz = 0, first, last;
423
424 if (!cxt || !header)
425 return -ENOSYS;
426
427 esz = sizeof(struct gpt_entry) * GPT_NPARTITIONS / cxt->sector_size;
428
429 header->signature = cpu_to_le64(GPT_HEADER_SIGNATURE);
430 header->revision = cpu_to_le32(GPT_HEADER_REVISION_V1_00);
431 header->size = cpu_to_le32(sizeof(struct gpt_header));
432
433 /*
434 * 128 partitions is the default. It can go behond this, however,
435 * we're creating a de facto header here, so no funny business.
436 */
437 header->npartition_entries = cpu_to_le32(GPT_NPARTITIONS);
438 header->sizeof_partition_entry = cpu_to_le32(sizeof(struct gpt_entry));
439
440 last = cxt->total_sectors - 2 - esz;
441 first = esz + 2;
442
443 if (first < cxt->first_lba && cxt->first_lba < last)
444 /* Align according to topology */
445 first = cxt->first_lba;
446
447 header->first_usable_lba = cpu_to_le64(first);
448 header->last_usable_lba = cpu_to_le64(last);
449
450 gpt_mknew_header_common(cxt, header, lba);
451 uuid_generate_random((unsigned char *) &header->disk_guid);
452 swap_efi_guid(&header->disk_guid);
453
454 return 0;
455 }
456
457 /*
458 * Checks if there is a valid protective MBR partition table.
459 * Returns 0 if it is invalid or failure. Otherwise, return
460 * GPT_MBR_PROTECTIVE or GPT_MBR_HYBRID, depeding on the detection.
461 */
462 static int valid_pmbr(struct fdisk_context *cxt)
463 {
464 int i, part = 0, ret = 0; /* invalid by default */
465 struct gpt_legacy_mbr *pmbr = NULL;
466 uint32_t sz_lba = 0;
467
468 if (!cxt->firstsector)
469 goto done;
470
471 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
472
473 if (le16_to_cpu(pmbr->signature) != MSDOS_MBR_SIGNATURE)
474 goto done;
475
476 /* LBA of the GPT partition header */
477 if (pmbr->partition_record[0].starting_lba !=
478 cpu_to_le32(GPT_PRIMARY_PARTITION_TABLE_LBA))
479 goto done;
480
481 /* seems like a valid MBR was found, check DOS primary partitions */
482 for (i = 0; i < 4; i++) {
483 if (pmbr->partition_record[i].os_type == EFI_PMBR_OSTYPE) {
484 /*
485 * Ok, we at least know that there's a protective MBR,
486 * now check if there are other partition types for
487 * hybrid MBR.
488 */
489 part = i;
490 ret = GPT_MBR_PROTECTIVE;
491 goto check_hybrid;
492 }
493 }
494
495 if (ret != GPT_MBR_PROTECTIVE)
496 goto done;
497 check_hybrid:
498 for (i = 0 ; i < 4; i++) {
499 if ((pmbr->partition_record[i].os_type != EFI_PMBR_OSTYPE) &&
500 (pmbr->partition_record[i].os_type != 0x00))
501 ret = GPT_MBR_HYBRID;
502 }
503
504 /*
505 * Protective MBRs take up the lesser of the whole disk
506 * or 2 TiB (32bit LBA), ignoring the rest of the disk.
507 * Some partitioning programs, nonetheless, choose to set
508 * the size to the maximum 32-bit limitation, disregarding
509 * the disk size.
510 *
511 * Hybrid MBRs do not necessarily comply with this.
512 */
513 if (ret == GPT_MBR_PROTECTIVE) {
514 sz_lba = le32_to_cpu(pmbr->partition_record[part].size_in_lba);
515 if (sz_lba != (uint32_t) cxt->total_sectors - 1 && sz_lba != 0xFFFFFFFF)
516 ret = 0;
517 }
518 done:
519 return ret;
520 }
521
522 static uint64_t last_lba(struct fdisk_context *cxt)
523 {
524 struct stat s;
525
526 memset(&s, 0, sizeof(s));
527 if (fstat(cxt->dev_fd, &s) == -1) {
528 fdisk_warn(cxt, _("gpt: stat() failed"));
529 return 0;
530 }
531
532 if (S_ISBLK(s.st_mode))
533 return cxt->total_sectors - 1;
534 else if (S_ISREG(s.st_mode)) {
535 uint64_t sectors = s.st_size >> cxt->sector_size;
536 return (sectors / cxt->sector_size) - 1ULL;
537 } else
538 fdisk_warnx(cxt, _("gpt: cannot handle files with mode %o"), s.st_mode);
539 return 0;
540 }
541
542 static ssize_t read_lba(struct fdisk_context *cxt, uint64_t lba,
543 void *buffer, const size_t bytes)
544 {
545 off_t offset = lba * cxt->sector_size;
546
547 if (lseek(cxt->dev_fd, offset, SEEK_SET) == (off_t) -1)
548 return -1;
549 return read(cxt->dev_fd, buffer, bytes) != bytes;
550 }
551
552
553 /* Returns the GPT entry array */
554 static struct gpt_entry *gpt_read_entries(struct fdisk_context *cxt,
555 struct gpt_header *header)
556 {
557 ssize_t sz;
558 struct gpt_entry *ret = NULL;
559 off_t offset;
560
561 assert(cxt);
562 assert(header);
563
564 sz = le32_to_cpu(header->npartition_entries) *
565 le32_to_cpu(header->sizeof_partition_entry);
566
567 ret = calloc(1, sz);
568 if (!ret)
569 return NULL;
570 offset = le64_to_cpu(header->partition_entry_lba) *
571 cxt->sector_size;
572
573 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
574 goto fail;
575 if (sz != read(cxt->dev_fd, ret, sz))
576 goto fail;
577
578 return ret;
579
580 fail:
581 free(ret);
582 return NULL;
583 }
584
585 static inline uint32_t count_crc32(const unsigned char *buf, size_t len)
586 {
587 return (crc32(~0L, buf, len) ^ ~0L);
588 }
589
590 /*
591 * Recompute header and partition array 32bit CRC checksums.
592 * This function does not fail - if there's corruption, then it
593 * will be reported when checksuming it again (ie: probing or verify).
594 */
595 static void gpt_recompute_crc(struct gpt_header *header, struct gpt_entry *ents)
596 {
597 uint32_t crc = 0;
598 size_t entry_sz = 0;
599
600 if (!header)
601 return;
602
603 /* header CRC */
604 header->crc32 = 0;
605 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
606 header->crc32 = cpu_to_le32(crc);
607
608 /* partition entry array CRC */
609 header->partition_entry_array_crc32 = 0;
610 entry_sz = le32_to_cpu(header->npartition_entries) *
611 le32_to_cpu(header->sizeof_partition_entry);
612
613 crc = count_crc32((unsigned char *) ents, entry_sz);
614 header->partition_entry_array_crc32 = cpu_to_le32(crc);
615 }
616
617 /*
618 * Compute the 32bit CRC checksum of the partition table header.
619 * Returns 1 if it is valid, otherwise 0.
620 */
621 static int gpt_check_header_crc(struct gpt_header *header, struct gpt_entry *ents)
622 {
623 uint32_t crc, orgcrc = le32_to_cpu(header->crc32);
624
625 header->crc32 = 0;
626 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
627 header->crc32 = cpu_to_le32(orgcrc);
628
629 if (crc == le32_to_cpu(header->crc32))
630 return 1;
631
632 /*
633 * If we have checksum mismatch it may be due to stale data,
634 * like a partition being added or deleted. Recompute the CRC again
635 * and make sure this is not the case.
636 */
637 if (ents) {
638 gpt_recompute_crc(header, ents);
639 orgcrc = le32_to_cpu(header->crc32);
640 header->crc32 = 0;
641 crc = count_crc32((unsigned char *) header, le32_to_cpu(header->size));
642 header->crc32 = cpu_to_le32(orgcrc);
643
644 return crc == le32_to_cpu(header->crc32);
645 }
646
647 return 0;
648 }
649
650 /*
651 * It initializes the partition entry array.
652 * Returns 1 if the checksum is valid, otherwise 0.
653 */
654 static int gpt_check_entryarr_crc(struct gpt_header *header,
655 struct gpt_entry *ents)
656 {
657 int ret = 0;
658 ssize_t entry_sz;
659 uint32_t crc;
660
661 if (!header || !ents)
662 goto done;
663
664 entry_sz = le32_to_cpu(header->npartition_entries) *
665 le32_to_cpu(header->sizeof_partition_entry);
666
667 if (!entry_sz)
668 goto done;
669
670 crc = count_crc32((unsigned char *) ents, entry_sz);
671 ret = (crc == le32_to_cpu(header->partition_entry_array_crc32));
672 done:
673 return ret;
674 }
675
676 static int gpt_check_lba_sanity(struct fdisk_context *cxt, struct gpt_header *header)
677 {
678 int ret = 0;
679 uint64_t lu, fu, lastlba = last_lba(cxt);
680
681 fu = le64_to_cpu(header->first_usable_lba);
682 lu = le64_to_cpu(header->last_usable_lba);
683
684 /* check if first and last usable LBA make sense */
685 if (lu < fu) {
686 DBG(LABEL, dbgprint("error: header last LBA is before first LBA"));
687 goto done;
688 }
689
690 /* check if first and last usable LBAs with the disk's last LBA */
691 if (fu > lastlba || lu > lastlba) {
692 DBG(LABEL, dbgprint("error: header LBAs are after the disk's last LBA"));
693 goto done;
694 }
695
696 /* the header has to be outside usable range */
697 if (fu < GPT_PRIMARY_PARTITION_TABLE_LBA &&
698 GPT_PRIMARY_PARTITION_TABLE_LBA < lu) {
699 DBG(LABEL, dbgprint("error: header outside of usable range"));
700 goto done;
701 }
702
703 ret = 1; /* sane */
704 done:
705 return ret;
706 }
707
708 /* Check if there is a valid header signature */
709 static int gpt_check_signature(struct gpt_header *header)
710 {
711 return header->signature == cpu_to_le64(GPT_HEADER_SIGNATURE);
712 }
713
714 /*
715 * Return the specified GPT Header, or NULL upon failure/invalid.
716 * Note that all tests must pass to ensure a valid header,
717 * we do not rely on only testing the signature for a valid probe.
718 */
719 static struct gpt_header *gpt_read_header(struct fdisk_context *cxt,
720 uint64_t lba,
721 struct gpt_entry **_ents)
722 {
723 struct gpt_header *header = NULL;
724 struct gpt_entry *ents = NULL;
725 uint32_t hsz;
726
727 if (!cxt)
728 return NULL;
729
730 header = calloc(1, sizeof(*header));
731 if (!header)
732 return NULL;
733
734 /* read and verify header */
735 if (read_lba(cxt, lba, header, sizeof(struct gpt_header)) != 0)
736 goto invalid;
737
738 if (!gpt_check_signature(header))
739 goto invalid;
740
741 if (!gpt_check_header_crc(header, NULL))
742 goto invalid;
743
744 /* read and verify entries */
745 ents = gpt_read_entries(cxt, header);
746 if (!ents)
747 goto invalid;
748
749 if (!gpt_check_entryarr_crc(header, ents))
750 goto invalid;
751
752 if (!gpt_check_lba_sanity(cxt, header))
753 goto invalid;
754
755 /* valid header must be at MyLBA */
756 if (le64_to_cpu(header->my_lba) != lba)
757 goto invalid;
758
759 /* make sure header size is between 92 and sector size bytes */
760 hsz = le32_to_cpu(header->size);
761 if (hsz < GPT_HEADER_MINSZ || hsz > cxt->sector_size)
762 goto invalid;
763
764 if (_ents)
765 *_ents = ents;
766 else
767 free(ents);
768
769 return header;
770 invalid:
771 free(header);
772 free(ents);
773 return NULL;
774 }
775
776
777 static int gpt_locate_disklabel(struct fdisk_context *cxt, int n,
778 const char **name, off_t *offset, size_t *size)
779 {
780 struct fdisk_gpt_label *gpt;
781
782 assert(cxt);
783
784 *name = NULL;
785 *offset = 0;
786 *size = 0;
787
788 switch (n) {
789 case 0:
790 *name = "PMBR";
791 *offset = 0;
792 *size = 512;
793 break;
794 case 1:
795 *name = _("GPT Header");
796 *offset = GPT_PRIMARY_PARTITION_TABLE_LBA * cxt->sector_size;
797 *size = sizeof(struct gpt_header);
798 break;
799 case 2:
800 *name = _("GPT Entries");
801 gpt = self_label(cxt);
802 *offset = le64_to_cpu(gpt->pheader->partition_entry_lba) * cxt->sector_size;
803 *size = le32_to_cpu(gpt->pheader->npartition_entries) *
804 le32_to_cpu(gpt->pheader->sizeof_partition_entry);
805 break;
806 default:
807 return 1; /* no more chunks */
808 }
809
810 return 0;
811 }
812
813
814
815 /*
816 * Returns the number of partitions that are in use.
817 */
818 static unsigned partitions_in_use(struct gpt_header *header, struct gpt_entry *e)
819 {
820 uint32_t i, used = 0;
821
822 if (!header || ! e)
823 return 0;
824
825 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++)
826 if (!partition_unused(&e[i]))
827 used++;
828 return used;
829 }
830
831
832 /*
833 * Check if a partition is too big for the disk (sectors).
834 * Returns the faulting partition number, otherwise 0.
835 */
836 static uint32_t partition_check_too_big(struct gpt_header *header,
837 struct gpt_entry *e, uint64_t sectors)
838 {
839 uint32_t i;
840
841 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
842 if (partition_unused(&e[i]))
843 continue;
844 if (gpt_partition_end(&e[i]) >= sectors)
845 return i + 1;
846 }
847
848 return 0;
849 }
850
851 /*
852 * Check if a partition ends before it begins
853 * Returns the faulting partition number, otherwise 0.
854 */
855 static uint32_t partition_start_after_end(struct gpt_header *header, struct gpt_entry *e)
856 {
857 uint32_t i;
858
859 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
860 if (partition_unused(&e[i]))
861 continue;
862 if (gpt_partition_start(&e[i]) > gpt_partition_end(&e[i]))
863 return i + 1;
864 }
865
866 return 0;
867 }
868
869 /*
870 * Check if partition e1 overlaps with partition e2
871 */
872 static inline int partition_overlap(struct gpt_entry *e1, struct gpt_entry *e2)
873 {
874 uint64_t start1 = gpt_partition_start(e1);
875 uint64_t end1 = gpt_partition_end(e1);
876 uint64_t start2 = gpt_partition_start(e2);
877 uint64_t end2 = gpt_partition_end(e2);
878
879 return (start1 && start2 && (start1 <= end2) != (end1 < start2));
880 }
881
882 /*
883 * Find any paritions that overlap.
884 */
885 static uint32_t partition_check_overlaps(struct gpt_header *header, struct gpt_entry *e)
886 {
887 uint32_t i, j;
888
889 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++)
890 for (j = 0; j < i; j++) {
891 if (partition_unused(&e[i]) ||
892 partition_unused(&e[j]))
893 continue;
894 if (partition_overlap(&e[i], &e[j])) {
895 DBG(LABEL, dbgprint("GPT partitions overlap detected [%u vs. %u]", i, j));
896 return i + 1;
897 }
898 }
899
900 return 0;
901 }
902
903 /*
904 * Find the first available block after the starting point; returns 0 if
905 * there are no available blocks left, or error. From gdisk.
906 */
907 static uint64_t find_first_available(struct gpt_header *header,
908 struct gpt_entry *e, uint64_t start)
909 {
910 uint64_t first;
911 uint32_t i, first_moved = 0;
912
913 uint64_t fu, lu;
914
915 if (!header || !e)
916 return 0;
917
918 fu = le64_to_cpu(header->first_usable_lba);
919 lu = le64_to_cpu(header->last_usable_lba);
920
921 /*
922 * Begin from the specified starting point or from the first usable
923 * LBA, whichever is greater...
924 */
925 first = start < fu ? fu : start;
926
927 /*
928 * Now search through all partitions; if first is within an
929 * existing partition, move it to the next sector after that
930 * partition and repeat. If first was moved, set firstMoved
931 * flag; repeat until firstMoved is not set, so as to catch
932 * cases where partitions are out of sequential order....
933 */
934 do {
935 first_moved = 0;
936 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
937 if (partition_unused(&e[i]))
938 continue;
939 if (first < gpt_partition_start(&e[i]))
940 continue;
941 if (first <= gpt_partition_end(&e[i])) {
942 first = gpt_partition_end(&e[i]) + 1;
943 first_moved = 1;
944 }
945 }
946 } while (first_moved == 1);
947
948 if (first > lu)
949 first = 0;
950
951 return first;
952 }
953
954
955 /* Returns last available sector in the free space pointed to by start. From gdisk. */
956 static uint64_t find_last_free(struct gpt_header *header,
957 struct gpt_entry *e, uint64_t start)
958 {
959 uint32_t i;
960 uint64_t nearest_start;
961
962 if (!header || !e)
963 return 0;
964
965 nearest_start = le64_to_cpu(header->last_usable_lba);
966
967 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
968 uint64_t ps = gpt_partition_start(&e[i]);
969
970 if (nearest_start > ps && ps > start)
971 nearest_start = ps - 1;
972 }
973
974 return nearest_start;
975 }
976
977 /* Returns the last free sector on the disk. From gdisk. */
978 static uint64_t find_last_free_sector(struct gpt_header *header,
979 struct gpt_entry *e)
980 {
981 uint32_t i, last_moved;
982 uint64_t last = 0;
983
984 if (!header || !e)
985 goto done;
986
987 /* start by assuming the last usable LBA is available */
988 last = le64_to_cpu(header->last_usable_lba);
989 do {
990 last_moved = 0;
991 for (i = 0; i < le32_to_cpu(header->npartition_entries); i++) {
992 if ((last >= gpt_partition_start(&e[i])) &&
993 (last <= gpt_partition_end(&e[i]))) {
994 last = gpt_partition_start(&e[i]) - 1;
995 last_moved = 1;
996 }
997 }
998 } while (last_moved == 1);
999 done:
1000 return last;
1001 }
1002
1003 /*
1004 * Finds the first available sector in the largest block of unallocated
1005 * space on the disk. Returns 0 if there are no available blocks left.
1006 * From gdisk.
1007 */
1008 static uint64_t find_first_in_largest(struct gpt_header *header, struct gpt_entry *e)
1009 {
1010 uint64_t start = 0, first_sect, last_sect;
1011 uint64_t segment_size, selected_size = 0, selected_segment = 0;
1012
1013 if (!header || !e)
1014 goto done;
1015
1016 do {
1017 first_sect = find_first_available(header, e, start);
1018 if (first_sect != 0) {
1019 last_sect = find_last_free(header, e, first_sect);
1020 segment_size = last_sect - first_sect + 1;
1021
1022 if (segment_size > selected_size) {
1023 selected_size = segment_size;
1024 selected_segment = first_sect;
1025 }
1026 start = last_sect + 1;
1027 }
1028 } while (first_sect != 0);
1029
1030 done:
1031 return selected_segment;
1032 }
1033
1034 /*
1035 * Find the total number of free sectors, the number of segments in which
1036 * they reside, and the size of the largest of those segments. From gdisk.
1037 */
1038 static uint64_t get_free_sectors(struct fdisk_context *cxt, struct gpt_header *header,
1039 struct gpt_entry *e, uint32_t *nsegments,
1040 uint64_t *largest_segment)
1041 {
1042 uint32_t num = 0;
1043 uint64_t first_sect, last_sect;
1044 uint64_t largest_seg = 0, segment_sz;
1045 uint64_t totfound = 0, start = 0; /* starting point for each search */
1046
1047 if (!cxt->total_sectors)
1048 goto done;
1049
1050 do {
1051 first_sect = find_first_available(header, e, start);
1052 if (first_sect) {
1053 last_sect = find_last_free(header, e, first_sect);
1054 segment_sz = last_sect - first_sect + 1;
1055
1056 if (segment_sz > largest_seg)
1057 largest_seg = segment_sz;
1058 totfound += segment_sz;
1059 num++;
1060 start = last_sect + 1;
1061 }
1062 } while (first_sect);
1063
1064 done:
1065 if (nsegments)
1066 *nsegments = num;
1067 if (largest_segment)
1068 *largest_segment = largest_seg;
1069
1070 return totfound;
1071 }
1072
1073 static int gpt_probe_label(struct fdisk_context *cxt)
1074 {
1075 int mbr_type;
1076 struct fdisk_gpt_label *gpt;
1077
1078 assert(cxt);
1079 assert(cxt->label);
1080 assert(fdisk_is_disklabel(cxt, GPT));
1081
1082 gpt = self_label(cxt);
1083
1084 mbr_type = valid_pmbr(cxt);
1085 if (!mbr_type)
1086 goto failed;
1087
1088 DBG(LABEL, dbgprint("found a %s MBR", mbr_type == GPT_MBR_PROTECTIVE ?
1089 "protective" : "hybrid"));
1090
1091 /* primary header */
1092 gpt->pheader = gpt_read_header(cxt, GPT_PRIMARY_PARTITION_TABLE_LBA,
1093 &gpt->ents);
1094
1095 /*
1096 * TODO: If the primary GPT is corrupt, we must check the last LBA of the
1097 * device to see if it has a valid GPT Header and point to a valid GPT
1098 * Partition Entry Array.
1099 * If it points to a valid GPT Partition Entry Array, then software should
1100 * restore the primary GPT if allowed by platform policy settings.
1101 *
1102 * For now we just abort GPT probing!
1103 */
1104 if (!gpt->pheader || !gpt->ents)
1105 goto failed;
1106
1107 /* OK, probing passed, now initialize backup header and fdisk variables. */
1108 gpt->bheader = gpt_read_header(cxt, last_lba(cxt), NULL);
1109
1110 cxt->label->nparts_max = le32_to_cpu(gpt->pheader->npartition_entries);
1111 cxt->label->nparts_cur = partitions_in_use(gpt->pheader, gpt->ents);
1112 return 1;
1113 failed:
1114 DBG(LABEL, dbgprint("GPT probe failed"));
1115 gpt_deinit(cxt->label);
1116 return 0;
1117 }
1118
1119 /*
1120 * Stolen from libblkid - can be removed once partition semantics
1121 * are added to the fdisk API.
1122 */
1123 static char *encode_to_utf8(unsigned char *src, size_t count)
1124 {
1125 uint16_t c;
1126 char *dest;
1127 size_t i, j, len = count;
1128
1129 dest = calloc(1, count);
1130 if (!dest)
1131 return NULL;
1132
1133 for (j = i = 0; i + 2 <= count; i += 2) {
1134 /* always little endian */
1135 c = (src[i+1] << 8) | src[i];
1136 if (c == 0) {
1137 dest[j] = '\0';
1138 break;
1139 } else if (c < 0x80) {
1140 if (j+1 >= len)
1141 break;
1142 dest[j++] = (uint8_t) c;
1143 } else if (c < 0x800) {
1144 if (j+2 >= len)
1145 break;
1146 dest[j++] = (uint8_t) (0xc0 | (c >> 6));
1147 dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
1148 } else {
1149 if (j+3 >= len)
1150 break;
1151 dest[j++] = (uint8_t) (0xe0 | (c >> 12));
1152 dest[j++] = (uint8_t) (0x80 | ((c >> 6) & 0x3f));
1153 dest[j++] = (uint8_t) (0x80 | (c & 0x3f));
1154 }
1155 }
1156 dest[j] = '\0';
1157
1158 return dest;
1159 }
1160
1161 /*
1162 * List label partitions.
1163 * This function must currently exist to comply with standard fdisk
1164 * requirements, but once partition semantics are added to the fdisk
1165 * API it can be removed for custom implementation (see gpt_label struct).
1166 */
1167 static int gpt_list_disklabel(struct fdisk_context *cxt)
1168 {
1169 int rc, trunc = TT_FL_TRUNC;
1170 uint32_t i;
1171 struct fdisk_gpt_label *gpt;
1172 struct gpt_header *h;
1173 uint64_t fu;
1174 uint64_t lu;
1175 struct tt *tb = NULL;
1176
1177 assert(cxt);
1178 assert(cxt->label);
1179 assert(fdisk_is_disklabel(cxt, GPT));
1180
1181 gpt = self_label(cxt);
1182 h = gpt->pheader;
1183 fu = le64_to_cpu(gpt->pheader->first_usable_lba);
1184 lu = le64_to_cpu(gpt->pheader->last_usable_lba);
1185
1186 tb = tt_new_table(TT_FL_FREEDATA);
1187 if (!tb)
1188 return -ENOMEM;
1189
1190 /* don't trunc anything in expert mode */
1191 if (fdisk_context_display_details(cxt)) {
1192 trunc = 0;
1193 fdisk_colon(cxt, _("First LBA: %ju"), h->first_usable_lba);
1194 fdisk_colon(cxt, _("Last LBA: %ju"), h->last_usable_lba);
1195 fdisk_colon(cxt, _("Alternative LBA: %ju"), h->alternative_lba);
1196 fdisk_colon(cxt, _("Partitions entries LBA: %ju"), h->partition_entry_lba);
1197 fdisk_colon(cxt, _("Allocated partition entries: %ju"), h->npartition_entries);
1198 }
1199 tt_define_column(tb, _("Device"), 0.1, 0);
1200 tt_define_column(tb, _("Start"), 12, TT_FL_RIGHT);
1201 tt_define_column(tb, _("End"), 12, TT_FL_RIGHT);
1202 tt_define_column(tb, _("Size"), 6, TT_FL_RIGHT);
1203 tt_define_column(tb, _("Type"), 0.1, trunc);
1204
1205 if (fdisk_context_display_details(cxt)) {
1206 tt_define_column(tb, _("UUID"), 36, 0);
1207 tt_define_column(tb, _("Name"), 0.2, trunc);
1208 }
1209
1210 for (i = 0; i < le32_to_cpu(h->npartition_entries); i++) {
1211 struct gpt_entry *e = &gpt->ents[i];
1212 char *sizestr = NULL, *p;
1213 uint64_t start = gpt_partition_start(e);
1214 uint64_t size = gpt_partition_size(e);
1215 struct fdisk_parttype *t;
1216 struct tt_line *ln;
1217 char u_str[37];
1218
1219 if (partition_unused(&gpt->ents[i]) || start == 0)
1220 continue;
1221 /* the partition has to inside usable range */
1222 if (start < fu || start + size - 1 > lu)
1223 continue;
1224 ln = tt_add_line(tb, NULL);
1225 if (!ln)
1226 continue;
1227
1228 if (fdisk_context_display_details(cxt) &&
1229 asprintf(&p, "%ju", size * cxt->sector_size) > 0)
1230 sizestr = p;
1231 else
1232 sizestr = size_to_human_string(SIZE_SUFFIX_1LETTER,
1233 size * cxt->sector_size);
1234 t = fdisk_get_partition_type(cxt, i);
1235
1236 /* basic columns */
1237 p = fdisk_partname(cxt->dev_path, i + 1);
1238 if (p)
1239 tt_line_set_data(ln, 0, p);
1240 if (asprintf(&p, "%ju", start) > 0)
1241 tt_line_set_data(ln, 1, p);
1242 if (asprintf(&p, "%ju", gpt_partition_end(e)) > 0)
1243 tt_line_set_data(ln, 2, p);
1244 if (sizestr)
1245 tt_line_set_data(ln, 3, sizestr);
1246 if (t && t->name)
1247 tt_line_set_data(ln, 4, strdup(t->name));
1248
1249 /* expert menu column(s) */
1250 if (fdisk_context_display_details(cxt)) {
1251 char *name = encode_to_utf8(
1252 (unsigned char *)e->name,
1253 sizeof(e->name));
1254
1255 if (guid_to_string(&e->partition_guid, u_str))
1256 tt_line_set_data(ln, 5, strdup(u_str));
1257 if (name)
1258 tt_line_set_data(ln, 6, name);
1259 }
1260
1261 fdisk_warn_alignment(cxt, start, i);
1262 fdisk_free_parttype(t);
1263 }
1264
1265 rc = fdisk_print_table(cxt, tb);
1266 tt_free_table(tb);
1267
1268 return rc;
1269 }
1270
1271 /*
1272 * Write partitions.
1273 * Returns 0 on success, or corresponding error otherwise.
1274 */
1275 static int gpt_write_partitions(struct fdisk_context *cxt,
1276 struct gpt_header *header, struct gpt_entry *ents)
1277 {
1278 off_t offset = le64_to_cpu(header->partition_entry_lba) * cxt->sector_size;
1279 uint32_t nparts = le32_to_cpu(header->npartition_entries);
1280 uint32_t totwrite = nparts * le32_to_cpu(header->sizeof_partition_entry);
1281 ssize_t rc;
1282
1283 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1284 goto fail;
1285
1286 rc = write(cxt->dev_fd, ents, totwrite);
1287 if (rc > 0 && totwrite == (uint32_t) rc)
1288 return 0;
1289 fail:
1290 return -errno;
1291 }
1292
1293 /*
1294 * Write a GPT header to a specified LBA
1295 * Returns 0 on success, or corresponding error otherwise.
1296 */
1297 static int gpt_write_header(struct fdisk_context *cxt,
1298 struct gpt_header *header, uint64_t lba)
1299 {
1300 off_t offset = lba * cxt->sector_size;
1301
1302 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1303 goto fail;
1304 if (cxt->sector_size ==
1305 (size_t) write(cxt->dev_fd, header, cxt->sector_size))
1306 return 0;
1307 fail:
1308 return -errno;
1309 }
1310
1311 /*
1312 * Write the protective MBR.
1313 * Returns 0 on success, or corresponding error otherwise.
1314 */
1315 static int gpt_write_pmbr(struct fdisk_context *cxt)
1316 {
1317 off_t offset;
1318 struct gpt_legacy_mbr *pmbr = NULL;
1319
1320 assert(cxt);
1321 assert(cxt->firstsector);
1322
1323 pmbr = (struct gpt_legacy_mbr *) cxt->firstsector;
1324
1325 /* zero out the legacy partitions */
1326 memset(pmbr->partition_record, 0, sizeof(pmbr->partition_record));
1327
1328 pmbr->signature = cpu_to_le16(MSDOS_MBR_SIGNATURE);
1329 pmbr->partition_record[0].os_type = EFI_PMBR_OSTYPE;
1330 pmbr->partition_record[0].start_sector = 1;
1331 pmbr->partition_record[0].end_head = 0xFE;
1332 pmbr->partition_record[0].end_sector = 0xFF;
1333 pmbr->partition_record[0].end_track = 0xFF;
1334 pmbr->partition_record[0].starting_lba = cpu_to_le32(1);
1335
1336 /*
1337 * Set size_in_lba to the size of the disk minus one. If the size of the disk
1338 * is too large to be represented by a 32bit LBA (2Tb), set it to 0xFFFFFFFF.
1339 */
1340 if (cxt->total_sectors - 1 > 0xFFFFFFFFULL)
1341 pmbr->partition_record[0].size_in_lba = cpu_to_le32(0xFFFFFFFF);
1342 else
1343 pmbr->partition_record[0].size_in_lba =
1344 cpu_to_le32(cxt->total_sectors - 1UL);
1345
1346 offset = GPT_PMBR_LBA * cxt->sector_size;
1347 if (offset != lseek(cxt->dev_fd, offset, SEEK_SET))
1348 goto fail;
1349
1350 /* pMBR covers the first sector (LBA) of the disk */
1351 if (write_all(cxt->dev_fd, pmbr, cxt->sector_size))
1352 goto fail;
1353 return 0;
1354 fail:
1355 return -errno;
1356 }
1357
1358 /*
1359 * Writes in-memory GPT and pMBR data to disk.
1360 * Returns 0 if successful write, otherwise, a corresponding error.
1361 * Any indication of error will abort the operation.
1362 */
1363 static int gpt_write_disklabel(struct fdisk_context *cxt)
1364 {
1365 struct fdisk_gpt_label *gpt;
1366
1367 assert(cxt);
1368 assert(cxt->label);
1369 assert(fdisk_is_disklabel(cxt, GPT));
1370
1371 gpt = self_label(cxt);
1372
1373 /* we do not want to mess up hybrid MBRs by creating a valid pmbr */
1374 if (valid_pmbr(cxt) == GPT_MBR_HYBRID)
1375 goto err0;
1376
1377 /* check that disk is big enough to handle the backup header */
1378 if (le64_to_cpu(gpt->pheader->alternative_lba) > cxt->total_sectors)
1379 goto err0;
1380
1381 /* check that the backup header is properly placed */
1382 if (le64_to_cpu(gpt->pheader->alternative_lba) < cxt->total_sectors - 1)
1383 /* TODO: correct this (with user authorization) and write */
1384 goto err0;
1385
1386 if (partition_check_overlaps(gpt->pheader, gpt->ents))
1387 goto err0;
1388
1389 /* recompute CRCs for both headers */
1390 gpt_recompute_crc(gpt->pheader, gpt->ents);
1391 gpt_recompute_crc(gpt->bheader, gpt->ents);
1392
1393 /*
1394 * UEFI requires writing in this specific order:
1395 * 1) backup partition tables
1396 * 2) backup GPT header
1397 * 3) primary partition tables
1398 * 4) primary GPT header
1399 * 5) protective MBR
1400 *
1401 * If any write fails, we abort the rest.
1402 */
1403 if (gpt_write_partitions(cxt, gpt->bheader, gpt->ents) != 0)
1404 goto err1;
1405 if (gpt_write_header(cxt, gpt->bheader,
1406 le64_to_cpu(gpt->pheader->alternative_lba)) != 0)
1407 goto err1;
1408 if (gpt_write_partitions(cxt, gpt->pheader, gpt->ents) != 0)
1409 goto err1;
1410 if (gpt_write_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA) != 0)
1411 goto err1;
1412 if (gpt_write_pmbr(cxt) != 0)
1413 goto err1;
1414
1415 DBG(LABEL, dbgprint("GPT write success"));
1416 return 0;
1417 err0:
1418 DBG(LABEL, dbgprint("GPT write failed: incorrect input"));
1419 errno = EINVAL;
1420 return -EINVAL;
1421 err1:
1422 DBG(LABEL, dbgprint("GPT write failed: %m"));
1423 return -errno;
1424 }
1425
1426 /*
1427 * Verify data integrity and report any found problems for:
1428 * - primary and backup header validations
1429 * - paritition validations
1430 */
1431 static int gpt_verify_disklabel(struct fdisk_context *cxt)
1432 {
1433 int nerror = 0;
1434 unsigned int ptnum;
1435 struct fdisk_gpt_label *gpt;
1436
1437 assert(cxt);
1438 assert(cxt->label);
1439 assert(fdisk_is_disklabel(cxt, GPT));
1440
1441 gpt = self_label(cxt);
1442
1443 if (!gpt || !gpt->bheader) {
1444 nerror++;
1445 fdisk_warnx(cxt, _("Disk does not contain a valid backup header."));
1446 }
1447
1448 if (!gpt_check_header_crc(gpt->pheader, gpt->ents)) {
1449 nerror++;
1450 fdisk_warnx(cxt, _("Invalid primary header CRC checksum."));
1451 }
1452 if (gpt->bheader && !gpt_check_header_crc(gpt->bheader, gpt->ents)) {
1453 nerror++;
1454 fdisk_warnx(cxt, _("Invalid backup header CRC checksum."));
1455 }
1456
1457 if (!gpt_check_entryarr_crc(gpt->pheader, gpt->ents)) {
1458 nerror++;
1459 fdisk_warnx(cxt, _("Invalid partition entry checksum."));
1460 }
1461
1462 if (!gpt_check_lba_sanity(cxt, gpt->pheader)) {
1463 nerror++;
1464 fdisk_warnx(cxt, _("Invalid primary header LBA sanity checks."));
1465 }
1466 if (gpt->bheader && !gpt_check_lba_sanity(cxt, gpt->bheader)) {
1467 nerror++;
1468 fdisk_warnx(cxt, _("Invalid backup header LBA sanity checks."));
1469 }
1470
1471 if (le64_to_cpu(gpt->pheader->my_lba) != GPT_PRIMARY_PARTITION_TABLE_LBA) {
1472 nerror++;
1473 fdisk_warnx(cxt, _("MyLBA mismatch with real position at primary header."));
1474 }
1475 if (gpt->bheader && le64_to_cpu(gpt->bheader->my_lba) != last_lba(cxt)) {
1476 nerror++;
1477 fdisk_warnx(cxt, _("MyLBA mismatch with real position at backup header."));
1478
1479 }
1480 if (le64_to_cpu(gpt->pheader->alternative_lba) >= cxt->total_sectors) {
1481 nerror++;
1482 fdisk_warnx(cxt, _("Disk is too small to hold all data."));
1483 }
1484
1485 /*
1486 * if the GPT is the primary table, check the alternateLBA
1487 * to see if it is a valid GPT
1488 */
1489 if (gpt->bheader && (le64_to_cpu(gpt->pheader->my_lba) !=
1490 le64_to_cpu(gpt->bheader->alternative_lba))) {
1491 nerror++;
1492 fdisk_warnx(cxt, _("Primary and backup header mismatch."));
1493 }
1494
1495 ptnum = partition_check_overlaps(gpt->pheader, gpt->ents);
1496 if (ptnum) {
1497 nerror++;
1498 fdisk_warnx(cxt, _("Partition %u overlaps with partition %u."),
1499 ptnum, ptnum+1);
1500 }
1501
1502 ptnum = partition_check_too_big(gpt->pheader, gpt->ents, cxt->total_sectors);
1503 if (ptnum) {
1504 nerror++;
1505 fdisk_warnx(cxt, _("Partition %u is too big for the disk."),
1506 ptnum);
1507 }
1508
1509 ptnum = partition_start_after_end(gpt->pheader, gpt->ents);
1510 if (ptnum) {
1511 nerror++;
1512 fdisk_warnx(cxt, _("Partition %u ends before it starts."),
1513 ptnum);
1514 }
1515
1516 if (!nerror) { /* yay :-) */
1517 uint32_t nsegments = 0;
1518 uint64_t free_sectors = 0, largest_segment = 0;
1519
1520 fdisk_info(cxt, _("No errors detected."));
1521 fdisk_info(cxt, _("Header version: %s"), gpt_get_header_revstr(gpt->pheader));
1522 fdisk_info(cxt, _("Using %u out of %d partitions."),
1523 partitions_in_use(gpt->pheader, gpt->ents),
1524 le32_to_cpu(gpt->pheader->npartition_entries));
1525
1526 free_sectors = get_free_sectors(cxt, gpt->pheader, gpt->ents,
1527 &nsegments, &largest_segment);
1528 fdisk_info(cxt, _("A total of %ld free sectors available in %d segment(s) "
1529 "(largest %ld)."),
1530 free_sectors, nsegments, largest_segment);
1531 } else
1532 fdisk_warnx(cxt,
1533 P_("%d error detected.", "%s errors detected", nerror),
1534 nerror);
1535
1536 return 0;
1537 }
1538
1539 /* Delete a single GPT partition, specified by partnum. */
1540 static int gpt_delete_partition(struct fdisk_context *cxt,
1541 size_t partnum)
1542 {
1543 struct fdisk_gpt_label *gpt;
1544
1545 assert(cxt);
1546 assert(cxt->label);
1547 assert(fdisk_is_disklabel(cxt, GPT));
1548
1549 gpt = self_label(cxt);
1550
1551 if (partnum >= cxt->label->nparts_max
1552 || partition_unused(&gpt->ents[partnum]))
1553 return -EINVAL;
1554
1555 /* hasta la vista, baby! */
1556 memset(&gpt->ents[partnum], 0, sizeof(struct gpt_entry));
1557 if (!partition_unused(&gpt->ents[partnum]))
1558 return -EINVAL;
1559 else {
1560 gpt_recompute_crc(gpt->pheader, gpt->ents);
1561 gpt_recompute_crc(gpt->bheader, gpt->ents);
1562 cxt->label->nparts_cur--;
1563 fdisk_label_set_changed(cxt->label, 1);
1564 }
1565
1566 return 0;
1567 }
1568
1569 static void gpt_entry_set_type(struct gpt_entry *e, struct gpt_guid *uuid)
1570 {
1571 e->type = *uuid;
1572 DBG(LABEL, dbgprint_uuid("new type", &(e->type)));
1573 }
1574
1575 /*
1576 * Create a new GPT partition entry, specified by partnum, and with a range
1577 * of fsect to lsenct sectors, of type t.
1578 * Returns 0 on success, or negative upon failure.
1579 */
1580 static int gpt_create_new_partition(struct fdisk_context *cxt,
1581 size_t partnum, uint64_t fsect, uint64_t lsect,
1582 struct gpt_guid *type,
1583 struct gpt_entry *entries)
1584 {
1585 struct gpt_entry *e = NULL;
1586 struct fdisk_gpt_label *gpt;
1587
1588 assert(cxt);
1589 assert(cxt->label);
1590 assert(fdisk_is_disklabel(cxt, GPT));
1591
1592 gpt = self_label(cxt);
1593
1594 if (fsect > lsect || partnum >= cxt->label->nparts_max)
1595 return -EINVAL;
1596
1597 e = calloc(1, sizeof(*e));
1598 if (!e)
1599 return -ENOMEM;
1600 e->lba_end = cpu_to_le64(lsect);
1601 e->lba_start = cpu_to_le64(fsect);
1602
1603 gpt_entry_set_type(e, type);
1604
1605 /*
1606 * Any time a new partition entry is created a new GUID must be
1607 * generated for that partition, and every partition is guaranteed
1608 * to have a unique GUID.
1609 */
1610 uuid_generate_random((unsigned char *) &e->partition_guid);
1611 swap_efi_guid(&e->partition_guid);
1612
1613 memcpy(&entries[partnum], e, sizeof(*e));
1614
1615 gpt_recompute_crc(gpt->pheader, entries);
1616 gpt_recompute_crc(gpt->bheader, entries);
1617
1618 free(e);
1619 return 0;
1620 }
1621
1622 /* Performs logical checks to add a new partition entry */
1623 static int gpt_add_partition(
1624 struct fdisk_context *cxt,
1625 size_t partnum,
1626 struct fdisk_parttype *t)
1627 {
1628 uint64_t user_f, user_l; /* user input ranges for first and last sectors */
1629 uint64_t disk_f, disk_l; /* first and last available sector ranges on device*/
1630 uint64_t dflt_f, dflt_l; /* largest segment (default) */
1631 struct gpt_guid typeid;
1632 struct fdisk_gpt_label *gpt;
1633 struct gpt_header *pheader;
1634 struct gpt_entry *ents;
1635 struct fdisk_ask *ask = NULL;
1636 int rc;
1637
1638 assert(cxt);
1639 assert(cxt->label);
1640 assert(fdisk_is_disklabel(cxt, GPT));
1641
1642 gpt = self_label(cxt);
1643
1644 if (partnum >= cxt->label->nparts_max)
1645 return -EINVAL;
1646
1647 pheader = gpt->pheader;
1648 ents = gpt->ents;
1649
1650 if (!partition_unused(&ents[partnum])) {
1651 fdisk_warnx(cxt, _("Partition %zd is already defined. "
1652 "Delete it before re-adding it."), partnum +1);
1653 return -EINVAL;
1654 }
1655 if (le32_to_cpu(pheader->npartition_entries) ==
1656 partitions_in_use(pheader, ents)) {
1657 fdisk_warnx(cxt, _("All partitions are already in use."));
1658 return -EINVAL;
1659 }
1660
1661 if (!get_free_sectors(cxt, pheader, ents, NULL, NULL)) {
1662 fdisk_warnx(cxt, _("No free sectors available."));
1663 return -ENOSPC;
1664 }
1665
1666 disk_f = find_first_available(pheader, ents, 0);
1667 disk_l = find_last_free_sector(pheader, ents);
1668
1669 /* the default is the largest free space */
1670 dflt_f = find_first_in_largest(pheader, ents);
1671 dflt_l = find_last_free(pheader, ents, dflt_f);
1672
1673 /* align the default in range <dflt_f,dflt_l>*/
1674 dflt_f = fdisk_align_lba_in_range(cxt, dflt_f, dflt_f, dflt_l);
1675
1676 string_to_guid(t && t->typestr ? t->typestr : GPT_DEFAULT_ENTRY_TYPE, &typeid);
1677
1678 /* get user input for first and last sectors of the new partition */
1679 for (;;) {
1680 if (!ask)
1681 ask = fdisk_new_ask();
1682 else
1683 fdisk_reset_ask(ask);
1684
1685 /* First sector */
1686 fdisk_ask_set_query(ask, _("First sector"));
1687 fdisk_ask_set_type(ask, FDISK_ASKTYPE_NUMBER);
1688 fdisk_ask_number_set_low(ask, disk_f); /* minimal */
1689 fdisk_ask_number_set_default(ask, dflt_f); /* default */
1690 fdisk_ask_number_set_high(ask, disk_l); /* maximal */
1691
1692 rc = fdisk_do_ask(cxt, ask);
1693 if (rc)
1694 goto done;
1695
1696 user_f = fdisk_ask_number_get_result(ask);
1697 if (user_f != find_first_available(pheader, ents, user_f)) {
1698 fdisk_warnx(cxt, _("Sector %ju already used."), user_f);
1699 continue;
1700 }
1701
1702 fdisk_reset_ask(ask);
1703
1704 /* Last sector */
1705 dflt_l = find_last_free(pheader, ents, user_f);
1706
1707 fdisk_ask_set_query(ask, _("Last sector, +sectors or +size{K,M,G,T,P}"));
1708 fdisk_ask_set_type(ask, FDISK_ASKTYPE_OFFSET);
1709 fdisk_ask_number_set_low(ask, user_f); /* minimal */
1710 fdisk_ask_number_set_default(ask, dflt_l); /* default */
1711 fdisk_ask_number_set_high(ask, dflt_l); /* maximal */
1712 fdisk_ask_number_set_base(ask, user_f); /* base for relative input */
1713 fdisk_ask_number_set_unit(ask, cxt->sector_size);
1714
1715 rc = fdisk_do_ask(cxt, ask);
1716 if (rc)
1717 goto done;
1718
1719 user_l = fdisk_ask_number_get_result(ask);
1720 if (fdisk_ask_number_is_relative(ask))
1721 user_l = fdisk_align_lba_in_range(cxt, user_l, user_f, dflt_l) - 1;
1722 if (user_l > user_f && user_l <= disk_l)
1723 break;
1724 }
1725
1726 if (gpt_create_new_partition(cxt, partnum,
1727 user_f, user_l, &typeid, ents) != 0)
1728 fdisk_warnx(cxt, _("Could not create partition %zd"), partnum + 1);
1729 else {
1730 cxt->label->nparts_cur++;
1731 fdisk_label_set_changed(cxt->label, 1);
1732 fdisk_info_new_partition(cxt, partnum + 1,
1733 user_f, user_l,
1734 gpt_get_partition_type(cxt, partnum));
1735 }
1736
1737 rc = 0;
1738 done:
1739 fdisk_free_ask(ask);
1740 return rc;
1741 }
1742
1743 /*
1744 * Create a new GPT disklabel - destroys any previous data.
1745 */
1746 static int gpt_create_disklabel(struct fdisk_context *cxt)
1747 {
1748 int rc = 0;
1749 ssize_t esz = 0;
1750 char str[37];
1751 struct fdisk_gpt_label *gpt;
1752
1753 assert(cxt);
1754 assert(cxt->label);
1755 assert(fdisk_is_disklabel(cxt, GPT));
1756
1757 gpt = self_label(cxt);
1758
1759 /* label private stuff has to be empty, see gpt_deinit() */
1760 assert(gpt->pheader == NULL);
1761 assert(gpt->bheader == NULL);
1762
1763 /*
1764 * When no header, entries or pmbr is set, we're probably
1765 * dealing with a new, empty disk - so always allocate memory
1766 * to deal with the data structures whatever the case is.
1767 */
1768 rc = gpt_mknew_pmbr(cxt);
1769 if (rc < 0)
1770 goto done;
1771
1772 /* primary */
1773 gpt->pheader = calloc(1, sizeof(*gpt->pheader));
1774 if (!gpt->pheader) {
1775 rc = -ENOMEM;
1776 goto done;
1777 }
1778 rc = gpt_mknew_header(cxt, gpt->pheader, GPT_PRIMARY_PARTITION_TABLE_LBA);
1779 if (rc < 0)
1780 goto done;
1781
1782 /* backup ("copy" primary) */
1783 gpt->bheader = calloc(1, sizeof(*gpt->bheader));
1784 if (!gpt->bheader) {
1785 rc = -ENOMEM;
1786 goto done;
1787 }
1788 rc = gpt_mknew_header_from_bkp(cxt, gpt->bheader,
1789 last_lba(cxt), gpt->pheader);
1790 if (rc < 0)
1791 goto done;
1792
1793 esz = le32_to_cpu(gpt->pheader->npartition_entries) *
1794 le32_to_cpu(gpt->pheader->sizeof_partition_entry);
1795 gpt->ents = calloc(1, esz);
1796 if (!gpt->ents) {
1797 rc = -ENOMEM;
1798 goto done;
1799 }
1800 gpt_recompute_crc(gpt->pheader, gpt->ents);
1801 gpt_recompute_crc(gpt->bheader, gpt->ents);
1802
1803 cxt->label->nparts_max = le32_to_cpu(gpt->pheader->npartition_entries);
1804 cxt->label->nparts_cur = 0;
1805
1806 guid_to_string(&gpt->pheader->disk_guid, str);
1807 fdisk_label_set_changed(cxt->label, 1);
1808 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
1809 _("Created a new GPT disklabel (GUID: %s)"), str);
1810 done:
1811 return rc;
1812 }
1813
1814 static int gpt_get_disklabel_id(struct fdisk_context *cxt, char **id)
1815 {
1816 struct fdisk_gpt_label *gpt;
1817 char str[37];
1818
1819 assert(cxt);
1820 assert(id);
1821 assert(cxt->label);
1822 assert(fdisk_is_disklabel(cxt, GPT));
1823
1824 gpt = self_label(cxt);
1825 guid_to_string(&gpt->pheader->disk_guid, str);
1826
1827 *id = strdup(str);
1828 if (!*id)
1829 return -ENOMEM;
1830 return 0;
1831 }
1832
1833 static int gpt_set_disklabel_id(struct fdisk_context *cxt)
1834 {
1835 struct fdisk_gpt_label *gpt;
1836 struct gpt_guid uuid;
1837 char *str, *old, *new;
1838 int rc;
1839
1840 assert(cxt);
1841 assert(cxt->label);
1842 assert(fdisk_is_disklabel(cxt, GPT));
1843
1844 gpt = self_label(cxt);
1845 if (fdisk_ask_string(cxt,
1846 _("Enter new disk UUID (in 8-4-4-4-12 format)"), &str))
1847 return -EINVAL;
1848
1849 rc = string_to_guid(str, &uuid);
1850 free(str);
1851
1852 if (rc) {
1853 fdisk_warnx(cxt, _("Failed to parse your UUID."));
1854 return rc;
1855 }
1856
1857 gpt_get_disklabel_id(cxt, &old);
1858
1859 gpt->pheader->disk_guid = uuid;
1860 gpt->bheader->disk_guid = uuid;
1861
1862 gpt_recompute_crc(gpt->pheader, gpt->ents);
1863 gpt_recompute_crc(gpt->bheader, gpt->ents);
1864
1865 gpt_get_disklabel_id(cxt, &new);
1866
1867 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
1868 _("Disk identifier changed from %s to %s."), old, new);
1869
1870 free(old);
1871 free(new);
1872 fdisk_label_set_changed(cxt->label, 1);
1873 return 0;
1874 }
1875
1876
1877 static struct fdisk_parttype *gpt_get_partition_type(
1878 struct fdisk_context *cxt,
1879 size_t i)
1880 {
1881 struct fdisk_parttype *t;
1882 char str[37];
1883 struct fdisk_gpt_label *gpt;
1884
1885 assert(cxt);
1886 assert(cxt->label);
1887 assert(fdisk_is_disklabel(cxt, GPT));
1888
1889 gpt = self_label(cxt);
1890
1891 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
1892 return NULL;
1893
1894 guid_to_string(&gpt->ents[i].type, str);
1895 t = fdisk_get_parttype_from_string(cxt, str);
1896 if (!t)
1897 t = fdisk_new_unknown_parttype(0, str);
1898
1899 return t;
1900 }
1901
1902
1903 static int gpt_set_partition_type(
1904 struct fdisk_context *cxt,
1905 size_t i,
1906 struct fdisk_parttype *t)
1907 {
1908 struct gpt_guid uuid;
1909 struct fdisk_gpt_label *gpt;
1910
1911 assert(cxt);
1912 assert(cxt->label);
1913 assert(fdisk_is_disklabel(cxt, GPT));
1914
1915 gpt = self_label(cxt);
1916 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries)
1917 || !t || !t->typestr || string_to_guid(t->typestr, &uuid) != 0)
1918 return -EINVAL;
1919
1920 gpt_entry_set_type(&gpt->ents[i], &uuid);
1921 gpt_recompute_crc(gpt->pheader, gpt->ents);
1922 gpt_recompute_crc(gpt->bheader, gpt->ents);
1923
1924 fdisk_label_set_changed(cxt->label, 1);
1925 return 0;
1926 }
1927
1928 static int gpt_get_partition_status(
1929 struct fdisk_context *cxt,
1930 size_t i,
1931 int *status)
1932 {
1933 struct fdisk_gpt_label *gpt;
1934 struct gpt_entry *e;
1935
1936 assert(cxt);
1937 assert(cxt->label);
1938 assert(fdisk_is_disklabel(cxt, GPT));
1939
1940 gpt = self_label(cxt);
1941
1942 if (!status || (uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
1943 return -EINVAL;
1944
1945 e = &gpt->ents[i];
1946 *status = FDISK_PARTSTAT_NONE;
1947
1948 if (!partition_unused(e) || gpt_partition_start(e))
1949 *status = FDISK_PARTSTAT_USED;
1950
1951 return 0;
1952 }
1953
1954 int fdisk_gpt_partition_set_uuid(struct fdisk_context *cxt, size_t i)
1955 {
1956 struct fdisk_gpt_label *gpt;
1957 struct gpt_entry *e;
1958 struct gpt_guid uuid;
1959 char *str, new_u[37], old_u[37];
1960 int rc;
1961
1962 assert(cxt);
1963 assert(cxt->label);
1964 assert(fdisk_is_disklabel(cxt, GPT));
1965
1966 DBG(LABEL, dbgprint("UUID change requested partno=%zd", i));
1967
1968 gpt = self_label(cxt);
1969
1970 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
1971 return -EINVAL;
1972
1973 if (fdisk_ask_string(cxt,
1974 _("New UUID (in 8-4-4-4-12 format)"), &str))
1975 return -EINVAL;
1976
1977 rc = string_to_guid(str, &uuid);
1978 free(str);
1979
1980 if (rc) {
1981 fdisk_warnx(cxt, _("Failed to parse your UUID."));
1982 return rc;
1983 }
1984
1985 e = &gpt->ents[i];
1986
1987 guid_to_string(&e->partition_guid, old_u);
1988 guid_to_string(&uuid, new_u);
1989
1990 e->partition_guid = uuid;
1991 gpt_recompute_crc(gpt->pheader, gpt->ents);
1992 gpt_recompute_crc(gpt->bheader, gpt->ents);
1993 fdisk_label_set_changed(cxt->label, 1);
1994
1995 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
1996 _("Partition UUID changed from %s to %s"),
1997 old_u, new_u);
1998 return 0;
1999 }
2000
2001 int fdisk_gpt_partition_set_name(struct fdisk_context *cxt, size_t i)
2002 {
2003 struct fdisk_gpt_label *gpt;
2004 struct gpt_entry *e;
2005 char *str, *old, name[GPT_PART_NAME_LEN] = { 0 };
2006 size_t sz;
2007
2008 assert(cxt);
2009 assert(cxt->label);
2010 assert(fdisk_is_disklabel(cxt, GPT));
2011
2012 DBG(LABEL, dbgprint("NAME change requested partno=%zd", i));
2013
2014 gpt = self_label(cxt);
2015
2016 if ((uint32_t) i >= le32_to_cpu(gpt->pheader->npartition_entries))
2017 return -EINVAL;
2018
2019 if (fdisk_ask_string(cxt, _("New name"), &str))
2020 return -EINVAL;
2021
2022 e = &gpt->ents[i];
2023 old = encode_to_utf8((unsigned char *)e->name, sizeof(e->name));
2024
2025 sz = strlen(str);
2026 if (sz) {
2027 if (sz > GPT_PART_NAME_LEN)
2028 sz = GPT_PART_NAME_LEN;
2029 memcpy(name, str, sz);
2030 }
2031
2032 for (i = 0; i < GPT_PART_NAME_LEN; i++)
2033 e->name[i] = cpu_to_le16((uint16_t) name[i]);
2034
2035 gpt_recompute_crc(gpt->pheader, gpt->ents);
2036 gpt_recompute_crc(gpt->bheader, gpt->ents);
2037
2038 fdisk_label_set_changed(cxt->label, 1);
2039
2040 fdisk_sinfo(cxt, FDISK_INFO_SUCCESS,
2041 _("Partition name changed from '%s' to '%.*s'"),
2042 old, GPT_PART_NAME_LEN, str);
2043 free(str);
2044 free(old);
2045
2046 return 0;
2047 }
2048
2049
2050 /*
2051 * Deinitialize fdisk-specific variables
2052 */
2053 static void gpt_deinit(struct fdisk_label *lb)
2054 {
2055 struct fdisk_gpt_label *gpt = (struct fdisk_gpt_label *) lb;
2056
2057 if (!gpt)
2058 return;
2059
2060 free(gpt->ents);
2061 free(gpt->pheader);
2062 free(gpt->bheader);
2063
2064 gpt->ents = NULL;
2065 gpt->pheader = NULL;
2066 gpt->bheader = NULL;
2067 }
2068
2069 static const struct fdisk_label_operations gpt_operations =
2070 {
2071 .probe = gpt_probe_label,
2072 .write = gpt_write_disklabel,
2073 .verify = gpt_verify_disklabel,
2074 .create = gpt_create_disklabel,
2075 .list = gpt_list_disklabel,
2076 .locate = gpt_locate_disklabel,
2077 .get_id = gpt_get_disklabel_id,
2078 .set_id = gpt_set_disklabel_id,
2079
2080 .part_add = gpt_add_partition,
2081 .part_delete = gpt_delete_partition,
2082 .part_get_type = gpt_get_partition_type,
2083 .part_set_type = gpt_set_partition_type,
2084
2085 .part_get_status = gpt_get_partition_status,
2086
2087 .deinit = gpt_deinit
2088 };
2089
2090 /*
2091 * allocates GPT in-memory stuff
2092 */
2093 struct fdisk_label *fdisk_new_gpt_label(struct fdisk_context *cxt)
2094 {
2095 struct fdisk_label *lb;
2096 struct fdisk_gpt_label *gpt;
2097
2098 assert(cxt);
2099
2100 gpt = calloc(1, sizeof(*gpt));
2101 if (!gpt)
2102 return NULL;
2103
2104 /* initialize generic part of the driver */
2105 lb = (struct fdisk_label *) gpt;
2106 lb->name = "gpt";
2107 lb->id = FDISK_DISKLABEL_GPT;
2108 lb->op = &gpt_operations;
2109 lb->parttypes = gpt_parttypes;
2110 lb->nparttypes = ARRAY_SIZE(gpt_parttypes);
2111
2112 return lb;
2113 }