Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(169)

Side by Side Diff: cgpt/cgpt_common.c

Issue 2719008: Nearly complete rewrite of cgpt tool. (Closed) Base URL: ssh://git@chromiumos-git//vboot_reference.git
Patch Set: Created 10 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « cgpt/cgpt.c ('k') | cgpt/cmd_add.c » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 /* Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
4 *
5 * Utility for ChromeOS-specific GPT partitions, Please see corresponding .c
6 * files for more details.
7 */
8
9 #include "cgpt.h"
10
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <getopt.h>
14 #include <stdint.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/ioctl.h>
19 #include <sys/mount.h>
20 #include <sys/stat.h>
21 #include <sys/types.h>
22 #include <unistd.h>
23 #include <assert.h>
24 #include <stdarg.h>
25
26 #include "cgptlib_internal.h"
27 #include "crc32.h"
28
29
30 void Error(const char *format, ...) {
31 va_list ap;
32 va_start(ap, format);
33 fprintf(stderr, "ERROR: %s %s: ", progname, command);
34 vfprintf(stderr, format, ap);
35 va_end(ap);
36 }
37
38
39 int CheckValid(const struct drive *drive) {
40 if ((drive->gpt.valid_headers != MASK_BOTH) ||
41 (drive->gpt.valid_entries != MASK_BOTH)) {
42 fprintf(stderr, "\nWARNING: one of the GPT header/entries is invalid, "
43 "please run '%s repair'\n", progname);
44 return CGPT_FAILED;
45 }
46 return CGPT_OK;
47 }
48
49 /* Loads sectors from 'fd'.
50 * *buf is pointed to an allocated memory when returned, and should be
51 * freed by cgpt_close().
52 *
53 * fd -- file descriptot.
54 * buf -- pointer to buffer pointer
55 * sector -- offset of starting sector (in sectors)
56 * sector_bytes -- bytes per sector
57 * sector_count -- number of sectors to load
58 *
59 * Returns CGPT_OK for successful. Aborts if any error occurs.
60 */
61 static int Load(const int fd, uint8_t **buf,
62 const uint64_t sector,
63 const uint64_t sector_bytes,
64 const uint64_t sector_count) {
65 int count; /* byte count to read */
66 int nread;
67
68 assert(buf);
69 count = sector_bytes * sector_count;
70 *buf = malloc(count);
71 assert(*buf);
72
73 if (-1 == lseek(fd, sector * sector_bytes, SEEK_SET))
74 goto error_free;
75
76 nread = read(fd, *buf, count);
77 if (nread < count)
78 goto error_free;
79
80 return CGPT_OK;
81
82 error_free:
83 free(*buf);
84 *buf = 0;
85 return CGPT_FAILED;
86 }
87
88
89 int ReadPMBR(struct drive *drive) {
90 if (-1 == lseek(drive->fd, 0, SEEK_SET))
91 return CGPT_FAILED;
92
93 int nread = read(drive->fd, &drive->pmbr, sizeof(struct pmbr));
94 if (nread != sizeof(struct pmbr))
95 return CGPT_FAILED;
96
97 return CGPT_OK;
98 }
99
100 int WritePMBR(struct drive *drive) {
101 if (-1 == lseek(drive->fd, 0, SEEK_SET))
102 return CGPT_FAILED;
103
104 int nwrote = write(drive->fd, &drive->pmbr, sizeof(struct pmbr));
105 if (nwrote != sizeof(struct pmbr))
106 return CGPT_FAILED;
107
108 return CGPT_OK;
109 }
110
111 /* Saves sectors to 'fd'.
112 *
113 * fd -- file descriptot.
114 * buf -- pointer to buffer
115 * sector -- starting sector offset
116 * sector_bytes -- bytes per sector
117 * sector_count -- number of sector to save
118 *
119 * Returns CGPT_OK for successful, CGPT_FAILED for failed.
120 */
121 static int Save(const int fd, const uint8_t *buf,
122 const uint64_t sector,
123 const uint64_t sector_bytes,
124 const uint64_t sector_count) {
125 int count; /* byte count to write */
126 int nwrote;
127
128 assert(buf);
129 count = sector_bytes * sector_count;
130
131 if (-1 == lseek(fd, sector * sector_bytes, SEEK_SET))
132 return CGPT_FAILED;
133
134 nwrote = write(fd, buf, count);
135 if (nwrote < count)
136 return CGPT_FAILED;
137
138 return CGPT_OK;
139 }
140
141
142 // Opens a block device or file, loads raw GPT data from it.
143 //
144 // Returns CGPT_FAILED if any error happens.
145 // Returns CGPT_OK if success and information are stored in 'drive'. */
146 int DriveOpen(const char *drive_path, struct drive *drive) {
147 struct stat stat;
148
149 assert(drive_path);
150 assert(drive);
151
152 // Clear struct for proper error handling.
153 memset(drive, 0, sizeof(struct drive));
154
155 drive->fd = open(drive_path, O_RDWR | O_LARGEFILE);
156 if (drive->fd == -1) {
157 Error("Can't open %s: %s\n", drive_path, strerror(errno));
158 return CGPT_FAILED;
159 }
160
161 if (fstat(drive->fd, &stat) == -1) {
162 goto error_close;
163 }
164 if ((stat.st_mode & S_IFMT) != S_IFREG) {
165 if (ioctl(drive->fd, BLKGETSIZE64, &drive->size) < 0) {
166 Error("Can't read drive size from %s: %s\n", drive_path, strerror(errno));
167 goto error_close;
168 }
169 if (ioctl(drive->fd, BLKSSZGET, &drive->gpt.sector_bytes) < 0) {
170 Error("Can't read sector size from %s: %s\n",
171 drive_path, strerror(errno));
172 goto error_close;
173 }
174 } else {
175 drive->gpt.sector_bytes = 512; /* bytes */
176 drive->size = stat.st_size;
177 }
178 if (drive->size % drive->gpt.sector_bytes) {
179 Error("Media size (%llu) is not a multiple of sector size(%d)\n",
180 (long long unsigned int)drive->size, drive->gpt.sector_bytes);
181 goto error_close;
182 }
183 drive->gpt.drive_sectors = drive->size / drive->gpt.sector_bytes;
184
185 // Read the data.
186 if (CGPT_OK != Load(drive->fd, &drive->gpt.primary_header,
187 GPT_PMBR_SECTOR,
188 drive->gpt.sector_bytes, GPT_HEADER_SECTOR)) {
189 goto error_close;
190 }
191 if (CGPT_OK != Load(drive->fd, &drive->gpt.secondary_header,
192 drive->gpt.drive_sectors - GPT_PMBR_SECTOR,
193 drive->gpt.sector_bytes, GPT_HEADER_SECTOR)) {
194 goto error_close;
195 }
196 if (CGPT_OK != Load(drive->fd, &drive->gpt.primary_entries,
197 GPT_PMBR_SECTOR + GPT_HEADER_SECTOR,
198 drive->gpt.sector_bytes, GPT_ENTRIES_SECTORS)) {
199 goto error_close;
200 }
201 if (CGPT_OK != Load(drive->fd, &drive->gpt.secondary_entries,
202 drive->gpt.drive_sectors - GPT_HEADER_SECTOR
203 - GPT_ENTRIES_SECTORS,
204 drive->gpt.sector_bytes, GPT_ENTRIES_SECTORS)) {
205 goto error_close;
206 }
207
208 // We just load the data. Caller must validate it.
209 return CGPT_OK;
210
211 error_close:
212 (void) DriveClose(drive, 0);
213 return CGPT_FAILED;
214 }
215
216
217 int DriveClose(struct drive *drive, int update_as_needed) {
218 int errors = 0;
219
220 if (update_as_needed) {
221 if (drive->gpt.modified & GPT_MODIFIED_HEADER1) {
222 if (CGPT_OK != Save(drive->fd, drive->gpt.primary_header,
223 GPT_PMBR_SECTOR,
224 drive->gpt.sector_bytes, GPT_HEADER_SECTOR)) {
225 errors++;
226 Error("Cannot write primary header: %s\n", strerror(errno));
227 }
228 }
229
230 if (drive->gpt.modified & GPT_MODIFIED_HEADER2) {
231 if(CGPT_OK != Save(drive->fd, drive->gpt.secondary_header,
232 drive->gpt.drive_sectors - GPT_PMBR_SECTOR,
233 drive->gpt.sector_bytes, GPT_HEADER_SECTOR)) {
234 errors++;
235 Error("Cannot write secondary header: %s\n", strerror(errno));
236 }
237 }
238 if (drive->gpt.modified & GPT_MODIFIED_ENTRIES1) {
239 if (CGPT_OK != Save(drive->fd, drive->gpt.primary_entries,
240 GPT_PMBR_SECTOR + GPT_HEADER_SECTOR,
241 drive->gpt.sector_bytes, GPT_ENTRIES_SECTORS)) {
242 errors++;
243 Error("Cannot write primary entries: %s\n", strerror(errno));
244 }
245 }
246 if (drive->gpt.modified & GPT_MODIFIED_ENTRIES2) {
247 if (CGPT_OK != Save(drive->fd, drive->gpt.secondary_entries,
248 drive->gpt.drive_sectors - GPT_HEADER_SECTOR
249 - GPT_ENTRIES_SECTORS,
250 drive->gpt.sector_bytes, GPT_ENTRIES_SECTORS)) {
251 errors++;
252 Error("Cannot write secondary entries: %s\n", strerror(errno));
253 }
254 }
255 }
256
257 close(drive->fd);
258
259 if (drive->gpt.primary_header)
260 free(drive->gpt.primary_header);
261 drive->gpt.primary_header = 0;
262 if (drive->gpt.primary_entries)
263 free(drive->gpt.primary_entries);
264 drive->gpt.primary_entries = 0;
265 if (drive->gpt.secondary_header)
266 free(drive->gpt.secondary_header);
267 drive->gpt.secondary_header = 0;
268 if (drive->gpt.secondary_entries)
269 free(drive->gpt.secondary_entries);
270 drive->gpt.secondary_entries = 0;
271
272 return errors ? CGPT_FAILED : CGPT_OK;
273 }
274
275
276
277 /* GUID conversion functions. Accepted format:
278 *
279 * "C12A7328-F81F-11D2-BA4B-00A0C93EC93B"
280 *
281 * Returns CGPT_OK if parsing is successful; otherwise CGPT_FAILED.
282 */
283 int StrToGuid(const char *str, Guid *guid) {
284 uint32_t time_low;
285 uint16_t time_mid;
286 uint16_t time_high_and_version;
287 unsigned int chunk[11];
288
289 if (11 != sscanf(str, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
290 chunk+0,
291 chunk+1,
292 chunk+2,
293 chunk+3,
294 chunk+4,
295 chunk+5,
296 chunk+6,
297 chunk+7,
298 chunk+8,
299 chunk+9,
300 chunk+10)) {
301 printf("FAILED\n");
302 return CGPT_FAILED;
303 }
304
305 time_low = chunk[0] & 0xffffffff;
306 time_mid = chunk[1] & 0xffff;
307 time_high_and_version = chunk[2] & 0xffff;
308
309 guid->u.Uuid.time_low = htole32(time_low);
310 guid->u.Uuid.time_mid = htole16(time_mid);
311 guid->u.Uuid.time_high_and_version = htole16(time_high_and_version);
312
313 guid->u.Uuid.clock_seq_high_and_reserved = chunk[3] & 0xff;
314 guid->u.Uuid.clock_seq_low = chunk[4] & 0xff;
315 guid->u.Uuid.node[0] = chunk[5] & 0xff;
316 guid->u.Uuid.node[1] = chunk[6] & 0xff;
317 guid->u.Uuid.node[2] = chunk[7] & 0xff;
318 guid->u.Uuid.node[3] = chunk[8] & 0xff;
319 guid->u.Uuid.node[4] = chunk[9] & 0xff;
320 guid->u.Uuid.node[5] = chunk[10] & 0xff;
321
322 return CGPT_OK;
323 }
324 void GuidToStr(const Guid *guid, char *str) {
325 sprintf(str, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
326 le32toh(guid->u.Uuid.time_low), le16toh(guid->u.Uuid.time_mid),
327 le16toh(guid->u.Uuid.time_high_and_version),
328 guid->u.Uuid.clock_seq_high_and_reserved, guid->u.Uuid.clock_seq_low,
329 guid->u.Uuid.node[0], guid->u.Uuid.node[1], guid->u.Uuid.node[2],
330 guid->u.Uuid.node[3], guid->u.Uuid.node[4], guid->u.Uuid.node[5]);
331 }
332
333 /* Convert UTF16 string to UTF8. Rewritten from gpt utility.
334 * Caller must prepare enough space for UTF8. The rough estimation is:
335 *
336 * utf8 length = bytecount(utf16) * 1.5
337 */
338 #define SIZEOF_GPTENTRY_NAME 36 /* sizeof(GptEntry.name[]) */
339 void UTF16ToUTF8(const uint16_t *utf16, uint8_t *utf8)
340 {
341 size_t s8idx, s16idx, s16len;
342 uint32_t utfchar;
343 unsigned int next_utf16;
344
345 for (s16len = 0; s16len < SIZEOF_GPTENTRY_NAME && utf16[s16len]; ++s16len);
346
347 *utf8 = s8idx = s16idx = 0;
348 while (s16idx < s16len) {
349 utfchar = le16toh(utf16[s16idx++]);
350 if ((utfchar & 0xf800) == 0xd800) {
351 next_utf16 = le16toh(utf16[s16idx]);
352 if ((utfchar & 0x400) != 0 || (next_utf16 & 0xfc00) != 0xdc00)
353 utfchar = 0xfffd;
354 else
355 s16idx++;
356 }
357 if (utfchar < 0x80) {
358 utf8[s8idx++] = utfchar;
359 } else if (utfchar < 0x800) {
360 utf8[s8idx++] = 0xc0 | (utfchar >> 6);
361 utf8[s8idx++] = 0x80 | (utfchar & 0x3f);
362 } else if (utfchar < 0x10000) {
363 utf8[s8idx++] = 0xe0 | (utfchar >> 12);
364 utf8[s8idx++] = 0x80 | ((utfchar >> 6) & 0x3f);
365 utf8[s8idx++] = 0x80 | (utfchar & 0x3f);
366 } else if (utfchar < 0x200000) {
367 utf8[s8idx++] = 0xf0 | (utfchar >> 18);
368 utf8[s8idx++] = 0x80 | ((utfchar >> 12) & 0x3f);
369 utf8[s8idx++] = 0x80 | ((utfchar >> 6) & 0x3f);
370 utf8[s8idx++] = 0x80 | (utfchar & 0x3f);
371 }
372 }
373 utf8[s8idx++] = 0;
374 }
375
376 /* Convert UTF8 string to UTF16. Rewritten from gpt utility.
377 * Caller must prepare enough space for UTF16. The conservative estimation is:
378 *
379 * utf16 bytecount = bytecount(utf8) / 3 * 4
380 */
381 void UTF8ToUTF16(const uint8_t *utf8, uint16_t *utf16)
382 {
383 size_t s16idx, s8idx, s8len;
384 uint32_t utfchar;
385 unsigned int c, utfbytes;
386
387 for (s8len = 0; utf8[s8len]; ++s8len);
388
389 s8idx = s16idx = 0;
390 utfbytes = 0;
391 do {
392 c = utf8[s8idx++];
393 if ((c & 0xc0) != 0x80) {
394 /* Initial characters. */
395 if (utfbytes != 0) {
396 /* Incomplete encoding. */
397 utf16[s16idx++] = 0xfffd;
398 }
399 if ((c & 0xf8) == 0xf0) {
400 utfchar = c & 0x07;
401 utfbytes = 3;
402 } else if ((c & 0xf0) == 0xe0) {
403 utfchar = c & 0x0f;
404 utfbytes = 2;
405 } else if ((c & 0xe0) == 0xc0) {
406 utfchar = c & 0x1f;
407 utfbytes = 1;
408 } else {
409 utfchar = c & 0x7f;
410 utfbytes = 0;
411 }
412 } else {
413 /* Followup characters. */
414 if (utfbytes > 0) {
415 utfchar = (utfchar << 6) + (c & 0x3f);
416 utfbytes--;
417 } else if (utfbytes == 0)
418 utfbytes = -1;
419 utfchar = 0xfffd;
420 }
421 if (utfbytes == 0) {
422 if (utfchar >= 0x10000) {
423 utf16[s16idx++] = htole16(0xd800 | ((utfchar>>10)-0x40));
424 if (s16idx >= SIZEOF_GPTENTRY_NAME) break;
425 utf16[s16idx++] = htole16(0xdc00 | (utfchar & 0x3ff));
426 } else {
427 utf16[s16idx++] = htole16(utfchar);
428 }
429 }
430 } while (c != 0 && s16idx < SIZEOF_GPTENTRY_NAME);
431 if (s16idx < SIZEOF_GPTENTRY_NAME)
432 utf16[s16idx++] = 0;
433 }
434
435 struct {
436 Guid type;
437 char *name;
438 char *description;
439 } supported_types[] = {
440 {GPT_ENT_TYPE_CHROMEOS_KERNEL, "kernel", "ChromeOS kernel"},
441 {GPT_ENT_TYPE_CHROMEOS_ROOTFS, "rootfs", "ChromeOS rootfs"},
442 {GPT_ENT_TYPE_LINUX_DATA, "data", "Linux data"},
443 {GPT_ENT_TYPE_CHROMEOS_RESERVED, "reserved", "ChromeOS reserved"},
444 {GPT_ENT_TYPE_EFI, "efi", "EFI System Partition"},
445 {GPT_ENT_TYPE_UNUSED, "unused", "Unused (nonexistent) partition"},
446 };
447
448 /* Resolves human-readable GPT type.
449 * Returns CGPT_OK if found.
450 * Returns CGPT_FAILED if no known type found. */
451 int ResolveType(const Guid *type, char *buf) {
452 int i;
453 for (i = 0; i < ARRAY_COUNT(supported_types); ++i) {
454 if (!memcmp(type, &supported_types[i].type, sizeof(Guid))) {
455 strcpy(buf, supported_types[i].description);
456 return CGPT_OK;
457 }
458 }
459 return CGPT_FAILED;
460 }
461
462 int SupportedType(const char *name, Guid *type) {
463 int i;
464 for (i = 0; i < ARRAY_COUNT(supported_types); ++i) {
465 if (!strcmp(name, supported_types[i].name)) {
466 memcpy(type, &supported_types[i].type, sizeof(Guid));
467 return CGPT_OK;
468 }
469 }
470 return CGPT_FAILED;
471 }
472
473 void PrintTypes(void) {
474 int i;
475 printf("The partition type may also be given as one of these aliases:\n\n");
476 for (i = 0; i < ARRAY_COUNT(supported_types); ++i) {
477 printf(" %-10s %s\n", supported_types[i].name,
478 supported_types[i].description);
479 }
480 printf("\n");
481 }
482
483 uint32_t GetNumberOfEntries(const GptData *gpt) {
484 GptHeader *header = 0;
485 if (gpt->valid_headers & MASK_PRIMARY)
486 header = (GptHeader*)gpt->primary_header;
487 else if (gpt->valid_headers & MASK_SECONDARY)
488 header = (GptHeader*)gpt->secondary_header;
489 else
490 return 0;
491 return header->number_of_entries;
492 }
493
494 static uint32_t GetSizeOfEntries(const GptData *gpt) {
495 GptHeader *header = 0;
496 if (gpt->valid_headers & MASK_PRIMARY)
497 header = (GptHeader*)gpt->primary_header;
498 else if (gpt->valid_headers & MASK_SECONDARY)
499 header = (GptHeader*)gpt->secondary_header;
500 else
501 return 0;
502 return header->number_of_entries;
503 }
504
505 GptEntry *GetEntry(GptData *gpt, int secondary, int entry_index) {
506 uint8_t *entries;
507 int stride = GetSizeOfEntries(gpt);
508 if (!stride)
509 return 0;
510
511 if (secondary == PRIMARY) {
512 entries = gpt->primary_entries;
513 } else {
514 entries = gpt->secondary_entries;
515 }
516
517 return (GptEntry*)(&entries[stride * entry_index]);
518 }
519
520 void SetPriority(GptData *gpt, int secondary, int entry_index, int priority) {
521 GptEntry *entry;
522 entry = GetEntry(gpt, secondary, entry_index);
523
524 assert(priority >= 0 && priority <= CGPT_ATTRIBUTE_MAX_PRIORITY);
525 entry->attributes &= ~CGPT_ATTRIBUTE_PRIORITY_MASK;
526 entry->attributes |= (uint64_t)priority << CGPT_ATTRIBUTE_PRIORITY_OFFSET;
527 }
528
529 int GetPriority(GptData *gpt, int secondary, int entry_index) {
530 GptEntry *entry;
531 entry = GetEntry(gpt, secondary, entry_index);
532 return (entry->attributes & CGPT_ATTRIBUTE_PRIORITY_MASK) >>
533 CGPT_ATTRIBUTE_PRIORITY_OFFSET;
534 }
535
536 void SetTries(GptData *gpt, int secondary, int entry_index, int tries) {
537 GptEntry *entry;
538 entry = GetEntry(gpt, secondary, entry_index);
539
540 assert(tries >= 0 && tries <= CGPT_ATTRIBUTE_MAX_TRIES);
541 entry->attributes &= ~CGPT_ATTRIBUTE_TRIES_MASK;
542 entry->attributes |= (uint64_t)tries << CGPT_ATTRIBUTE_TRIES_OFFSET;
543 }
544
545 int GetTries(GptData *gpt, int secondary, int entry_index) {
546 GptEntry *entry;
547 entry = GetEntry(gpt, secondary, entry_index);
548 return (entry->attributes & CGPT_ATTRIBUTE_TRIES_MASK) >>
549 CGPT_ATTRIBUTE_TRIES_OFFSET;
550 }
551
552 void SetSuccessful(GptData *gpt, int secondary, int entry_index, int success) {
553 GptEntry *entry;
554 entry = GetEntry(gpt, secondary, entry_index);
555
556 assert(success >= 0 && success <= CGPT_ATTRIBUTE_MAX_SUCCESSFUL);
557 entry->attributes &= ~CGPT_ATTRIBUTE_SUCCESSFUL_MASK;
558 entry->attributes |= (uint64_t)success << CGPT_ATTRIBUTE_SUCCESSFUL_OFFSET;
559 }
560
561 int GetSuccessful(GptData *gpt, int secondary, int entry_index) {
562 GptEntry *entry;
563 entry = GetEntry(gpt, secondary, entry_index);
564 return (entry->attributes & CGPT_ATTRIBUTE_SUCCESSFUL_MASK) >>
565 CGPT_ATTRIBUTE_SUCCESSFUL_OFFSET;
566 }
567
568
569 #define TOSTRING(A) #A
570 const char *GptError(int errnum) {
571 const char *error_string[] = {
572 TOSTRING(GPT_SUCCESS),
573 TOSTRING(GPT_ERROR_NO_VALID_KERNEL),
574 TOSTRING(GPT_ERROR_INVALID_HEADERS),
575 TOSTRING(GPT_ERROR_INVALID_ENTRIES),
576 TOSTRING(GPT_ERROR_INVALID_SECTOR_SIZE),
577 TOSTRING(GPT_ERROR_INVALID_SECTOR_NUMBER),
578 TOSTRING(GPT_ERROR_INVALID_UPDATE_TYPE)
579 };
580 if (errnum < 0 || errnum >= ARRAY_COUNT(error_string))
581 return "<illegal value>";
582 return error_string[errnum];
583 }
584
585 /* Update CRC value if necessary. */
586 void UpdateCrc(GptData *gpt) {
587 GptHeader *primary_header, *secondary_header;
588
589 primary_header = (GptHeader*)gpt->primary_header;
590 secondary_header = (GptHeader*)gpt->secondary_header;
591
592 if (gpt->modified & GPT_MODIFIED_ENTRIES1) {
593 primary_header->entries_crc32 =
594 Crc32(gpt->primary_entries, TOTAL_ENTRIES_SIZE);
595 }
596 if (gpt->modified & GPT_MODIFIED_ENTRIES2) {
597 secondary_header->entries_crc32 =
598 Crc32(gpt->secondary_entries, TOTAL_ENTRIES_SIZE);
599 }
600 if (gpt->modified & GPT_MODIFIED_HEADER1) {
601 primary_header->header_crc32 = 0;
602 primary_header->header_crc32 = Crc32(
603 (const uint8_t *)primary_header, primary_header->size);
604 }
605 if (gpt->modified & GPT_MODIFIED_HEADER2) {
606 secondary_header->header_crc32 = 0;
607 secondary_header->header_crc32 = Crc32(
608 (const uint8_t *)secondary_header, secondary_header->size);
609 }
610 }
611 /* Two headers are NOT bitwise identical. For example, my_lba pointers to header
612 * itself so that my_lba in primary and secondary is definitely different.
613 * Only the following fields should be identical.
614 *
615 * first_usable_lba
616 * last_usable_lba
617 * number_of_entries
618 * size_of_entry
619 * disk_uuid
620 *
621 * If any of above field are not matched, overwrite secondary with primary since
622 * we always trust primary.
623 * If any one of header is invalid, copy from another. */
624 int IsSynonymous(const GptHeader* a, const GptHeader* b) {
625 if ((a->first_usable_lba == b->first_usable_lba) &&
626 (a->last_usable_lba == b->last_usable_lba) &&
627 (a->number_of_entries == b->number_of_entries) &&
628 (a->size_of_entry == b->size_of_entry) &&
629 (!memcmp(&a->disk_uuid, &b->disk_uuid, sizeof(Guid))))
630 return 1;
631 return 0;
632 }
633
634 /* Primary entries and secondary entries should be bitwise identical.
635 * If two entries tables are valid, compare them. If not the same,
636 * overwrites secondary with primary (primary always has higher priority),
637 * and marks secondary as modified.
638 * If only one is valid, overwrites invalid one.
639 * If all are invalid, does nothing.
640 * This function returns bit masks for GptData.modified field.
641 * Note that CRC is NOT re-computed in this function.
642 */
643 uint8_t RepairEntries(GptData *gpt, const uint32_t valid_entries) {
644 if (valid_entries == MASK_BOTH) {
645 if (memcmp(gpt->primary_entries, gpt->secondary_entries,
646 TOTAL_ENTRIES_SIZE)) {
647 memcpy(gpt->secondary_entries, gpt->primary_entries, TOTAL_ENTRIES_SIZE);
648 return GPT_MODIFIED_ENTRIES2;
649 }
650 } else if (valid_entries == MASK_PRIMARY) {
651 memcpy(gpt->secondary_entries, gpt->primary_entries, TOTAL_ENTRIES_SIZE);
652 return GPT_MODIFIED_ENTRIES2;
653 } else if (valid_entries == MASK_SECONDARY) {
654 memcpy(gpt->primary_entries, gpt->secondary_entries, TOTAL_ENTRIES_SIZE);
655 return GPT_MODIFIED_ENTRIES1;
656 }
657
658 return 0;
659 }
660
661 /* The above five fields are shared between primary and secondary headers.
662 * We can recover one header from another through copying those fields. */
663 void CopySynonymousParts(GptHeader* target, const GptHeader* source) {
664 target->first_usable_lba = source->first_usable_lba;
665 target->last_usable_lba = source->last_usable_lba;
666 target->number_of_entries = source->number_of_entries;
667 target->size_of_entry = source->size_of_entry;
668 memcpy(&target->disk_uuid, &source->disk_uuid, sizeof(Guid));
669 }
670
671 /* This function repairs primary and secondary headers if possible.
672 * If both headers are valid (CRC32 is correct) but
673 * a) indicate inconsistent usable LBA ranges,
674 * b) inconsistent partition entry size and number,
675 * c) inconsistent disk_uuid,
676 * we will use the primary header to overwrite secondary header.
677 * If primary is invalid (CRC32 is wrong), then we repair it from secondary.
678 * If secondary is invalid (CRC32 is wrong), then we repair it from primary.
679 * This function returns the bitmasks for modified header.
680 * Note that CRC value is NOT re-computed in this function. UpdateCrc() will
681 * do it later.
682 */
683 uint8_t RepairHeader(GptData *gpt, const uint32_t valid_headers) {
684 GptHeader *primary_header, *secondary_header;
685
686 primary_header = (GptHeader*)gpt->primary_header;
687 secondary_header = (GptHeader*)gpt->secondary_header;
688
689 if (valid_headers == MASK_BOTH) {
690 if (!IsSynonymous(primary_header, secondary_header)) {
691 CopySynonymousParts(secondary_header, primary_header);
692 return GPT_MODIFIED_HEADER2;
693 }
694 } else if (valid_headers == MASK_PRIMARY) {
695 memcpy(secondary_header, primary_header, primary_header->size);
696 secondary_header->my_lba = gpt->drive_sectors - 1; /* the last sector */
697 secondary_header->alternate_lba = primary_header->my_lba;
698 secondary_header->entries_lba = secondary_header->my_lba -
699 GPT_ENTRIES_SECTORS;
700 return GPT_MODIFIED_HEADER2;
701 } else if (valid_headers == MASK_SECONDARY) {
702 memcpy(primary_header, secondary_header, secondary_header->size);
703 primary_header->my_lba = GPT_PMBR_SECTOR; /* the second sector on drive */
704 primary_header->alternate_lba = secondary_header->my_lba;
705 primary_header->entries_lba = primary_header->my_lba + GPT_HEADER_SECTOR;
706 return GPT_MODIFIED_HEADER1;
707 }
708
709 return 0;
710 }
711
712
713 int IsZero(const Guid *gp) {
714 return (0 == memcmp(gp, &guid_unused, sizeof(Guid)));
715 }
716
717 void PMBRToStr(struct pmbr *pmbr, char *str) {
718 char buf[256];
719 if (IsZero(&pmbr->boot_guid)) {
720 sprintf(str, "PMBR");
721 } else {
722 GuidToStr(&pmbr->boot_guid, buf);
723 sprintf(str, "PMBR (Boot GUID: %s)", buf);
724 }
725 }
726
OLDNEW
« no previous file with comments | « cgpt/cgpt.c ('k') | cgpt/cmd_add.c » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698