blob: ea57223b293c7e6300123d888f5091878c403af2 [file] [log] [blame]
Bill Richardsonf1372d92010-06-11 09:15:55 -07001/* 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
Bill Richardsonf1372d92010-06-11 09:15:55 -07009#include <errno.h>
10#include <fcntl.h>
11#include <getopt.h>
David Riley05987b12015-02-05 19:22:49 -080012#ifndef HAVE_MACOS
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -070013#include <linux/major.h>
14#include <mtd/mtd-user.h>
David Riley05987b12015-02-05 19:22:49 -080015#endif
Bill Richardsonc4e92af2010-10-12 07:33:15 -070016#include <stdarg.h>
Bill Richardsonf1372d92010-06-11 09:15:55 -070017#include <stdint.h>
18#include <stdio.h>
19#include <stdlib.h>
20#include <string.h>
21#include <sys/ioctl.h>
22#include <sys/mount.h>
23#include <sys/stat.h>
24#include <sys/types.h>
25#include <unistd.h>
Bill Richardsonf1372d92010-06-11 09:15:55 -070026
Bill Richardson0c3ba242013-03-29 11:09:30 -070027#include "cgpt.h"
Bill Richardsonf1372d92010-06-11 09:15:55 -070028#include "cgptlib_internal.h"
29#include "crc32.h"
Bill Richardson0c3ba242013-03-29 11:09:30 -070030#include "vboot_host.h"
Bill Richardsonf1372d92010-06-11 09:15:55 -070031
Nam T. Nguyend92856d2014-10-16 15:02:40 -070032static const char kErrorTag[] = "ERROR";
33static const char kWarningTag[] = "WARNING";
34
Nam T. Nguyend92856d2014-10-16 15:02:40 -070035static void LogToStderr(const char *tag, const char *format, va_list ap) {
36 fprintf(stderr, "%s: ", tag);
37 vfprintf(stderr, format, ap);
38}
39
Bill Richardsonf1372d92010-06-11 09:15:55 -070040void Error(const char *format, ...) {
41 va_list ap;
42 va_start(ap, format);
Nam T. Nguyend92856d2014-10-16 15:02:40 -070043 LogToStderr(kErrorTag, format, ap);
44 va_end(ap);
45}
46
47void Warning(const char *format, ...) {
48 va_list ap;
49 va_start(ap, format);
50 LogToStderr(kWarningTag, format, ap);
Bill Richardsonf1372d92010-06-11 09:15:55 -070051 va_end(ap);
52}
53
Bill Richardsonf1372d92010-06-11 09:15:55 -070054int CheckValid(const struct drive *drive) {
55 if ((drive->gpt.valid_headers != MASK_BOTH) ||
56 (drive->gpt.valid_entries != MASK_BOTH)) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -070057 Warning("One of the GPT headers/entries is invalid\n\n");
Bill Richardsonf1372d92010-06-11 09:15:55 -070058 return CGPT_FAILED;
59 }
60 return CGPT_OK;
61}
62
Albert Chaulk534723a2013-03-20 14:46:50 -070063int Load(struct drive *drive, uint8_t **buf,
Bill Richardsonf1372d92010-06-11 09:15:55 -070064 const uint64_t sector,
65 const uint64_t sector_bytes,
66 const uint64_t sector_count) {
67 int count; /* byte count to read */
68 int nread;
69
Bill Richardsonc4e92af2010-10-12 07:33:15 -070070 require(buf);
71 if (!sector_count || !sector_bytes) {
Jinguang Dong945ebe92017-04-10 15:56:30 +080072 Error("%s() failed at line %d: sector_count=%ld, sector_bytes=%ld\n",
Bill Richardsonc4e92af2010-10-12 07:33:15 -070073 __FUNCTION__, __LINE__, sector_count, sector_bytes);
74 return CGPT_FAILED;
75 }
76 /* Make sure that sector_bytes * sector_count doesn't roll over. */
77 if (sector_bytes > (UINT64_MAX / sector_count)) {
78 Error("%s() failed at line %d: sector_count=%d, sector_bytes=%d\n",
79 __FUNCTION__, __LINE__, sector_count, sector_bytes);
80 return CGPT_FAILED;
81 }
Bill Richardsonf1372d92010-06-11 09:15:55 -070082 count = sector_bytes * sector_count;
83 *buf = malloc(count);
Bill Richardsonc4e92af2010-10-12 07:33:15 -070084 require(*buf);
Bill Richardsonf1372d92010-06-11 09:15:55 -070085
Nam T. Nguyenab899592014-11-13 19:30:46 -080086 if (-1 == lseek(drive->fd, sector * sector_bytes, SEEK_SET)) {
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -070087 Error("Can't seek: %s\n", strerror(errno));
Bill Richardsonf1372d92010-06-11 09:15:55 -070088 goto error_free;
Bill Richardsonc4e92af2010-10-12 07:33:15 -070089 }
Bill Richardsonf1372d92010-06-11 09:15:55 -070090
Nam T. Nguyenab899592014-11-13 19:30:46 -080091 nread = read(drive->fd, *buf, count);
Bill Richardsonc4e92af2010-10-12 07:33:15 -070092 if (nread < count) {
93 Error("Can't read enough: %d, not %d\n", nread, count);
Bill Richardsonf1372d92010-06-11 09:15:55 -070094 goto error_free;
Bill Richardsonc4e92af2010-10-12 07:33:15 -070095 }
Bill Richardsonf1372d92010-06-11 09:15:55 -070096
97 return CGPT_OK;
98
99error_free:
100 free(*buf);
101 *buf = 0;
102 return CGPT_FAILED;
103}
104
105
106int ReadPMBR(struct drive *drive) {
Nam T. Nguyenab899592014-11-13 19:30:46 -0800107 if (-1 == lseek(drive->fd, 0, SEEK_SET))
Bill Richardsonf1372d92010-06-11 09:15:55 -0700108 return CGPT_FAILED;
109
Nam T. Nguyenab899592014-11-13 19:30:46 -0800110 int nread = read(drive->fd, &drive->pmbr, sizeof(struct pmbr));
Bill Richardsonf1372d92010-06-11 09:15:55 -0700111 if (nread != sizeof(struct pmbr))
112 return CGPT_FAILED;
113
114 return CGPT_OK;
115}
116
117int WritePMBR(struct drive *drive) {
Nam T. Nguyenab899592014-11-13 19:30:46 -0800118 if (-1 == lseek(drive->fd, 0, SEEK_SET))
Bill Richardsonf1372d92010-06-11 09:15:55 -0700119 return CGPT_FAILED;
120
Nam T. Nguyenab899592014-11-13 19:30:46 -0800121 int nwrote = write(drive->fd, &drive->pmbr, sizeof(struct pmbr));
Bill Richardsonf1372d92010-06-11 09:15:55 -0700122 if (nwrote != sizeof(struct pmbr))
123 return CGPT_FAILED;
124
125 return CGPT_OK;
126}
127
Albert Chaulk534723a2013-03-20 14:46:50 -0700128int Save(struct drive *drive, const uint8_t *buf,
Bill Richardsonf1372d92010-06-11 09:15:55 -0700129 const uint64_t sector,
130 const uint64_t sector_bytes,
131 const uint64_t sector_count) {
132 int count; /* byte count to write */
133 int nwrote;
134
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700135 require(buf);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700136 count = sector_bytes * sector_count;
137
Nam T. Nguyenab899592014-11-13 19:30:46 -0800138 if (-1 == lseek(drive->fd, sector * sector_bytes, SEEK_SET))
Bill Richardsonf1372d92010-06-11 09:15:55 -0700139 return CGPT_FAILED;
140
Nam T. Nguyenab899592014-11-13 19:30:46 -0800141 nwrote = write(drive->fd, buf, count);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700142 if (nwrote < count)
143 return CGPT_FAILED;
144
145 return CGPT_OK;
146}
147
Bill Richardson18e03702014-06-23 17:48:33 -0700148static int GptLoad(struct drive *drive, uint32_t sector_bytes) {
Albert Chaulk534723a2013-03-20 14:46:50 -0700149 drive->gpt.sector_bytes = sector_bytes;
150 if (drive->size % drive->gpt.sector_bytes) {
151 Error("Media size (%llu) is not a multiple of sector size(%d)\n",
152 (long long unsigned int)drive->size, drive->gpt.sector_bytes);
153 return -1;
154 }
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800155 drive->gpt.streaming_drive_sectors = drive->size / drive->gpt.sector_bytes;
Albert Chaulk534723a2013-03-20 14:46:50 -0700156
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -0700157 /* TODO(namnguyen): Remove this and totally trust gpt_drive_sectors. */
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800158 if (!(drive->gpt.flags & GPT_FLAG_EXTERNAL)) {
159 drive->gpt.gpt_drive_sectors = drive->gpt.streaming_drive_sectors;
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -0700160 } /* Else, we trust gpt.gpt_drive_sectors. */
161
Albert Chaulk534723a2013-03-20 14:46:50 -0700162 // Read the data.
163 if (CGPT_OK != Load(drive, &drive->gpt.primary_header,
Nam T. Nguyen88458d92014-08-28 10:58:47 -0700164 GPT_PMBR_SECTORS,
165 drive->gpt.sector_bytes, GPT_HEADER_SECTORS)) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700166 Error("Cannot read primary GPT header\n");
Albert Chaulk534723a2013-03-20 14:46:50 -0700167 return -1;
168 }
169 if (CGPT_OK != Load(drive, &drive->gpt.secondary_header,
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -0700170 drive->gpt.gpt_drive_sectors - GPT_PMBR_SECTORS,
Nam T. Nguyen88458d92014-08-28 10:58:47 -0700171 drive->gpt.sector_bytes, GPT_HEADER_SECTORS)) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700172 Error("Cannot read secondary GPT header\n");
Albert Chaulk534723a2013-03-20 14:46:50 -0700173 return -1;
174 }
Nam T. Nguyena2d72f72014-08-22 15:01:38 -0700175 GptHeader* primary_header = (GptHeader*)drive->gpt.primary_header;
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800176 if (CheckHeader(primary_header, 0, drive->gpt.streaming_drive_sectors,
Dan Ehrenberga524a3a2014-11-06 16:22:24 -0800177 drive->gpt.gpt_drive_sectors,
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800178 drive->gpt.flags) == 0) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700179 if (CGPT_OK != Load(drive, &drive->gpt.primary_entries,
180 primary_header->entries_lba,
Nam T. Nguyen32004012014-12-12 09:38:35 -0800181 drive->gpt.sector_bytes,
182 CalculateEntriesSectors(primary_header))) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700183 Error("Cannot read primary partition entry array\n");
184 return -1;
185 }
186 } else {
187 Warning("Primary GPT header is invalid\n");
Albert Chaulk534723a2013-03-20 14:46:50 -0700188 }
Nam T. Nguyena2d72f72014-08-22 15:01:38 -0700189 GptHeader* secondary_header = (GptHeader*)drive->gpt.secondary_header;
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800190 if (CheckHeader(secondary_header, 1, drive->gpt.streaming_drive_sectors,
Dan Ehrenberga524a3a2014-11-06 16:22:24 -0800191 drive->gpt.gpt_drive_sectors,
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800192 drive->gpt.flags) == 0) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700193 if (CGPT_OK != Load(drive, &drive->gpt.secondary_entries,
194 secondary_header->entries_lba,
Nam T. Nguyen32004012014-12-12 09:38:35 -0800195 drive->gpt.sector_bytes,
196 CalculateEntriesSectors(secondary_header))) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700197 Error("Cannot read secondary partition entry array\n");
198 return -1;
199 }
200 } else {
201 Warning("Secondary GPT header is invalid\n");
Albert Chaulk534723a2013-03-20 14:46:50 -0700202 }
203 return 0;
204}
205
Bill Richardson18e03702014-06-23 17:48:33 -0700206static int GptSave(struct drive *drive) {
Albert Chaulk534723a2013-03-20 14:46:50 -0700207 int errors = 0;
208 if (drive->gpt.modified & GPT_MODIFIED_HEADER1) {
209 if (CGPT_OK != Save(drive, drive->gpt.primary_header,
Nam T. Nguyen88458d92014-08-28 10:58:47 -0700210 GPT_PMBR_SECTORS,
211 drive->gpt.sector_bytes, GPT_HEADER_SECTORS)) {
Albert Chaulk534723a2013-03-20 14:46:50 -0700212 errors++;
213 Error("Cannot write primary header: %s\n", strerror(errno));
214 }
215 }
216
217 if (drive->gpt.modified & GPT_MODIFIED_HEADER2) {
218 if(CGPT_OK != Save(drive, drive->gpt.secondary_header,
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -0700219 drive->gpt.gpt_drive_sectors - GPT_PMBR_SECTORS,
Nam T. Nguyen88458d92014-08-28 10:58:47 -0700220 drive->gpt.sector_bytes, GPT_HEADER_SECTORS)) {
Albert Chaulk534723a2013-03-20 14:46:50 -0700221 errors++;
222 Error("Cannot write secondary header: %s\n", strerror(errno));
223 }
224 }
Nam T. Nguyena2d72f72014-08-22 15:01:38 -0700225 GptHeader* primary_header = (GptHeader*)drive->gpt.primary_header;
Albert Chaulk534723a2013-03-20 14:46:50 -0700226 if (drive->gpt.modified & GPT_MODIFIED_ENTRIES1) {
227 if (CGPT_OK != Save(drive, drive->gpt.primary_entries,
Nam T. Nguyena2d72f72014-08-22 15:01:38 -0700228 primary_header->entries_lba,
Nam T. Nguyen32004012014-12-12 09:38:35 -0800229 drive->gpt.sector_bytes,
230 CalculateEntriesSectors(primary_header))) {
Albert Chaulk534723a2013-03-20 14:46:50 -0700231 errors++;
232 Error("Cannot write primary entries: %s\n", strerror(errno));
233 }
234 }
Nam T. Nguyena2d72f72014-08-22 15:01:38 -0700235 GptHeader* secondary_header = (GptHeader*)drive->gpt.secondary_header;
Albert Chaulk534723a2013-03-20 14:46:50 -0700236 if (drive->gpt.modified & GPT_MODIFIED_ENTRIES2) {
237 if (CGPT_OK != Save(drive, drive->gpt.secondary_entries,
Nam T. Nguyena2d72f72014-08-22 15:01:38 -0700238 secondary_header->entries_lba,
Nam T. Nguyen32004012014-12-12 09:38:35 -0800239 drive->gpt.sector_bytes,
240 CalculateEntriesSectors(secondary_header))) {
Albert Chaulk534723a2013-03-20 14:46:50 -0700241 errors++;
242 Error("Cannot write secondary entries: %s\n", strerror(errno));
243 }
244 }
245
246 if (drive->gpt.primary_header)
247 free(drive->gpt.primary_header);
248 drive->gpt.primary_header = 0;
249 if (drive->gpt.primary_entries)
250 free(drive->gpt.primary_entries);
251 drive->gpt.primary_entries = 0;
252 if (drive->gpt.secondary_header)
253 free(drive->gpt.secondary_header);
254 drive->gpt.secondary_header = 0;
255 if (drive->gpt.secondary_entries)
256 free(drive->gpt.secondary_entries);
257 drive->gpt.secondary_entries = 0;
258 return errors ? -1 : 0;
259}
260
Nam T. Nguyenab899592014-11-13 19:30:46 -0800261/*
262 * Query drive size and bytes per sector. Return zero on success. On error,
263 * -1 is returned and errno is set appropriately.
264 */
265static int ObtainDriveSize(int fd, uint64_t* size, uint32_t* sector_bytes) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700266 struct stat stat;
Nam T. Nguyenab899592014-11-13 19:30:46 -0800267 if (fstat(fd, &stat) == -1) {
268 return -1;
269 }
David Riley05987b12015-02-05 19:22:49 -0800270#ifndef HAVE_MACOS
Nam T. Nguyenab899592014-11-13 19:30:46 -0800271 if ((stat.st_mode & S_IFMT) != S_IFREG) {
272 if (ioctl(fd, BLKGETSIZE64, size) < 0) {
273 return -1;
274 }
275 if (ioctl(fd, BLKSSZGET, sector_bytes) < 0) {
276 return -1;
277 }
278 } else {
279 *sector_bytes = 512; /* bytes */
280 *size = stat.st_size;
281 }
David Riley05987b12015-02-05 19:22:49 -0800282#else
283 *sector_bytes = 512; /* bytes */
284 *size = stat.st_size;
285#endif
Nam T. Nguyenab899592014-11-13 19:30:46 -0800286 return 0;
287}
288
289int DriveOpen(const char *drive_path, struct drive *drive, int mode,
290 uint64_t drive_size) {
Albert Chaulk534723a2013-03-20 14:46:50 -0700291 uint32_t sector_bytes;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700292
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700293 require(drive_path);
294 require(drive);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700295
296 // Clear struct for proper error handling.
297 memset(drive, 0, sizeof(struct drive));
298
David Riley05987b12015-02-05 19:22:49 -0800299 drive->fd = open(drive_path, mode |
300#ifndef HAVE_MACOS
301 O_LARGEFILE |
302#endif
303 O_NOFOLLOW);
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800304 if (drive->fd == -1) {
305 Error("Can't open %s: %s\n", drive_path, strerror(errno));
306 return CGPT_FAILED;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700307 }
Bill Richardsonf1372d92010-06-11 09:15:55 -0700308
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800309 sector_bytes = 512;
310 uint64_t gpt_drive_size;
311 if (ObtainDriveSize(drive->fd, &gpt_drive_size, &sector_bytes) != 0) {
312 Error("Can't get drive size and bytes per sector for %s: %s\n",
313 drive_path, strerror(errno));
314 goto error_close;
315 }
316
317 drive->gpt.gpt_drive_sectors = gpt_drive_size / sector_bytes;
318 if (drive_size == 0) {
319 drive->size = gpt_drive_size;
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800320 drive->gpt.flags = 0;
Albert Chaulk534723a2013-03-20 14:46:50 -0700321 } else {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800322 drive->size = drive_size;
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800323 drive->gpt.flags = GPT_FLAG_EXTERNAL;
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800324 }
325
326
327 if (GptLoad(drive, sector_bytes)) {
328 goto error_close;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700329 }
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700330
Bill Richardsonf1372d92010-06-11 09:15:55 -0700331 // We just load the data. Caller must validate it.
332 return CGPT_OK;
333
334error_close:
335 (void) DriveClose(drive, 0);
336 return CGPT_FAILED;
337}
338
339
340int DriveClose(struct drive *drive, int update_as_needed) {
341 int errors = 0;
342
343 if (update_as_needed) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800344 if (GptSave(drive)) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700345 errors++;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700346 }
347 }
348
Louis Yung-Chieh Lo57cdad32013-01-16 11:52:17 +0800349 // Sync early! Only sync file descriptor here, and leave the whole system sync
350 // outside cgpt because whole system sync would trigger tons of disk accesses
351 // and timeout tests.
Nam T. Nguyenab899592014-11-13 19:30:46 -0800352 fsync(drive->fd);
Louis Yung-Chieh Lo57cdad32013-01-16 11:52:17 +0800353
Nam T. Nguyenab899592014-11-13 19:30:46 -0800354 close(drive->fd);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700355
Bill Richardsonf1372d92010-06-11 09:15:55 -0700356 return errors ? CGPT_FAILED : CGPT_OK;
357}
358
359
Bill Richardsonf1372d92010-06-11 09:15:55 -0700360/* GUID conversion functions. Accepted format:
361 *
362 * "C12A7328-F81F-11D2-BA4B-00A0C93EC93B"
363 *
364 * Returns CGPT_OK if parsing is successful; otherwise CGPT_FAILED.
365 */
366int StrToGuid(const char *str, Guid *guid) {
367 uint32_t time_low;
368 uint16_t time_mid;
369 uint16_t time_high_and_version;
370 unsigned int chunk[11];
371
372 if (11 != sscanf(str, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
373 chunk+0,
374 chunk+1,
375 chunk+2,
376 chunk+3,
377 chunk+4,
378 chunk+5,
379 chunk+6,
380 chunk+7,
381 chunk+8,
382 chunk+9,
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700383 chunk+10)) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700384 printf("FAILED\n");
385 return CGPT_FAILED;
386 }
387
388 time_low = chunk[0] & 0xffffffff;
389 time_mid = chunk[1] & 0xffff;
390 time_high_and_version = chunk[2] & 0xffff;
391
392 guid->u.Uuid.time_low = htole32(time_low);
393 guid->u.Uuid.time_mid = htole16(time_mid);
394 guid->u.Uuid.time_high_and_version = htole16(time_high_and_version);
395
396 guid->u.Uuid.clock_seq_high_and_reserved = chunk[3] & 0xff;
397 guid->u.Uuid.clock_seq_low = chunk[4] & 0xff;
398 guid->u.Uuid.node[0] = chunk[5] & 0xff;
399 guid->u.Uuid.node[1] = chunk[6] & 0xff;
400 guid->u.Uuid.node[2] = chunk[7] & 0xff;
401 guid->u.Uuid.node[3] = chunk[8] & 0xff;
402 guid->u.Uuid.node[4] = chunk[9] & 0xff;
403 guid->u.Uuid.node[5] = chunk[10] & 0xff;
404
405 return CGPT_OK;
406}
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700407void GuidToStr(const Guid *guid, char *str, unsigned int buflen) {
408 require(buflen >= GUID_STRLEN);
409 require(snprintf(str, buflen,
410 "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
411 le32toh(guid->u.Uuid.time_low),
412 le16toh(guid->u.Uuid.time_mid),
413 le16toh(guid->u.Uuid.time_high_and_version),
414 guid->u.Uuid.clock_seq_high_and_reserved,
415 guid->u.Uuid.clock_seq_low,
416 guid->u.Uuid.node[0], guid->u.Uuid.node[1],
417 guid->u.Uuid.node[2], guid->u.Uuid.node[3],
418 guid->u.Uuid.node[4], guid->u.Uuid.node[5]) == GUID_STRLEN-1);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700419}
420
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700421/* Convert possibly unterminated UTF16 string to UTF8.
422 * Caller must prepare enough space for UTF8, which could be up to
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800423 * twice the byte length of UTF16 string plus the terminating '\0'.
424 * See the following table for encoding lengths.
425 *
426 * Code point UTF16 UTF8
427 * 0x0000-0x007F 2 bytes 1 byte
428 * 0x0080-0x07FF 2 bytes 2 bytes
429 * 0x0800-0xFFFF 2 bytes 3 bytes
430 * 0x10000-0x10FFFF 4 bytes 4 bytes
431 *
432 * This function uses a simple state meachine to convert UTF-16 char(s) to
433 * a code point. Once a code point is parsed out, the state machine throws
434 * out sequencial UTF-8 chars in one time.
435 *
436 * Return: CGPT_OK --- all character are converted successfully.
437 * CGPT_FAILED --- convert error, i.e. output buffer is too short.
Bill Richardsonf1372d92010-06-11 09:15:55 -0700438 */
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800439int UTF16ToUTF8(const uint16_t *utf16, unsigned int maxinput,
440 uint8_t *utf8, unsigned int maxoutput)
Bill Richardsonf1372d92010-06-11 09:15:55 -0700441{
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700442 size_t s16idx, s8idx;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800443 uint32_t code_point = 0;
444 int code_point_ready = 1; // code point is ready to output.
445 int retval = CGPT_OK;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700446
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700447 if (!utf16 || !maxinput || !utf8 || !maxoutput)
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800448 return CGPT_FAILED;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700449
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700450 maxoutput--; /* plan for termination now */
451
452 for (s16idx = s8idx = 0;
453 s16idx < maxinput && utf16[s16idx] && maxoutput;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800454 s16idx++) {
455 uint16_t codeunit = le16toh(utf16[s16idx]);
456
457 if (code_point_ready) {
458 if (codeunit >= 0xD800 && codeunit <= 0xDBFF) {
459 /* high surrogate, need the low surrogate. */
460 code_point_ready = 0;
461 code_point = (codeunit & 0x03FF) + 0x0040;
462 } else {
463 /* BMP char, output it. */
464 code_point = codeunit;
465 }
466 } else {
467 /* expect the low surrogate */
468 if (codeunit >= 0xDC00 && codeunit <= 0xDFFF) {
469 code_point = (code_point << 10) | (codeunit & 0x03FF);
470 code_point_ready = 1;
471 } else {
472 /* the second code unit is NOT the low surrogate. Unexpected. */
473 code_point_ready = 0;
474 retval = CGPT_FAILED;
475 break;
476 }
477 }
478
479 /* If UTF code point is ready, output it. */
480 if (code_point_ready) {
481 require(code_point <= 0x10FFFF);
482 if (code_point <= 0x7F && maxoutput >= 1) {
483 maxoutput -= 1;
484 utf8[s8idx++] = code_point & 0x7F;
485 } else if (code_point <= 0x7FF && maxoutput >= 2) {
486 maxoutput -= 2;
487 utf8[s8idx++] = 0xC0 | (code_point >> 6);
488 utf8[s8idx++] = 0x80 | (code_point & 0x3F);
489 } else if (code_point <= 0xFFFF && maxoutput >= 3) {
490 maxoutput -= 3;
491 utf8[s8idx++] = 0xE0 | (code_point >> 12);
492 utf8[s8idx++] = 0x80 | ((code_point >> 6) & 0x3F);
493 utf8[s8idx++] = 0x80 | (code_point & 0x3F);
494 } else if (code_point <= 0x10FFFF && maxoutput >= 4) {
495 maxoutput -= 4;
496 utf8[s8idx++] = 0xF0 | (code_point >> 18);
497 utf8[s8idx++] = 0x80 | ((code_point >> 12) & 0x3F);
498 utf8[s8idx++] = 0x80 | ((code_point >> 6) & 0x3F);
499 utf8[s8idx++] = 0x80 | (code_point & 0x3F);
500 } else {
501 /* buffer underrun */
502 retval = CGPT_FAILED;
503 break;
504 }
505 }
Bill Richardsonf1372d92010-06-11 09:15:55 -0700506 }
507 utf8[s8idx++] = 0;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800508 return retval;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700509}
510
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700511/* Convert UTF8 string to UTF16. The UTF8 string must be null-terminated.
512 * Caller must prepare enough space for UTF16, including a terminating 0x0000.
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800513 * See the following table for encoding lengths. In any case, the caller
514 * just needs to prepare the byte length of UTF8 plus the terminating 0x0000.
515 *
516 * Code point UTF16 UTF8
517 * 0x0000-0x007F 2 bytes 1 byte
518 * 0x0080-0x07FF 2 bytes 2 bytes
519 * 0x0800-0xFFFF 2 bytes 3 bytes
520 * 0x10000-0x10FFFF 4 bytes 4 bytes
521 *
522 * This function converts UTF8 chars to a code point first. Then, convrts it
523 * to UTF16 code unit(s).
524 *
525 * Return: CGPT_OK --- all character are converted successfully.
526 * CGPT_FAILED --- convert error, i.e. output buffer is too short.
Bill Richardsonf1372d92010-06-11 09:15:55 -0700527 */
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800528int UTF8ToUTF16(const uint8_t *utf8, uint16_t *utf16, unsigned int maxoutput)
Bill Richardsonf1372d92010-06-11 09:15:55 -0700529{
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700530 size_t s16idx, s8idx;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800531 uint32_t code_point = 0;
532 unsigned int expected_units = 1;
533 unsigned int decoded_units = 1;
534 int retval = CGPT_OK;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700535
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700536 if (!utf8 || !utf16 || !maxoutput)
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800537 return CGPT_FAILED;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700538
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700539 maxoutput--; /* plan for termination */
540
541 for (s8idx = s16idx = 0;
542 utf8[s8idx] && maxoutput;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800543 s8idx++) {
544 uint8_t code_unit;
545 code_unit = utf8[s8idx];
546
547 if (expected_units != decoded_units) {
548 /* Trailing bytes of multi-byte character */
549 if ((code_unit & 0xC0) == 0x80) {
550 code_point = (code_point << 6) | (code_unit & 0x3F);
551 ++decoded_units;
552 } else {
553 /* Unexpected code unit. */
554 retval = CGPT_FAILED;
555 break;
556 }
557 } else {
558 /* parsing a new code point. */
559 decoded_units = 1;
560 if (code_unit <= 0x7F) {
561 code_point = code_unit;
562 expected_units = 1;
563 } else if (code_unit <= 0xBF) {
564 /* 0x80-0xBF must NOT be the heading byte unit of a new code point. */
565 retval = CGPT_FAILED;
566 break;
567 } else if (code_unit >= 0xC2 && code_unit <= 0xDF) {
568 code_point = code_unit & 0x1F;
569 expected_units = 2;
570 } else if (code_unit >= 0xE0 && code_unit <= 0xEF) {
571 code_point = code_unit & 0x0F;
572 expected_units = 3;
573 } else if (code_unit >= 0xF0 && code_unit <= 0xF4) {
574 code_point = code_unit & 0x07;
575 expected_units = 4;
576 } else {
577 /* illegal code unit: 0xC0-0xC1, 0xF5-0xFF */
578 retval = CGPT_FAILED;
579 break;
580 }
581 }
582
583 /* If no more unit is needed, output the UTF16 unit(s). */
584 if ((retval == CGPT_OK) &&
585 (expected_units == decoded_units)) {
586 /* Check if the encoding is the shortest possible UTF-8 sequence. */
587 switch (expected_units) {
588 case 2:
589 if (code_point <= 0x7F) retval = CGPT_FAILED;
590 break;
591 case 3:
592 if (code_point <= 0x7FF) retval = CGPT_FAILED;
593 break;
594 case 4:
595 if (code_point <= 0xFFFF) retval = CGPT_FAILED;
596 break;
597 }
598 if (retval == CGPT_FAILED) break; /* leave immediately */
599
600 if ((code_point <= 0xD7FF) ||
601 (code_point >= 0xE000 && code_point <= 0xFFFF)) {
602 utf16[s16idx++] = code_point;
603 maxoutput -= 1;
604 } else if (code_point >= 0x10000 && code_point <= 0x10FFFF &&
605 maxoutput >= 2) {
606 utf16[s16idx++] = 0xD800 | ((code_point >> 10) - 0x0040);
607 utf16[s16idx++] = 0xDC00 | (code_point & 0x03FF);
608 maxoutput -= 2;
609 } else {
610 /* Three possibilities fall into here. Both are failure cases.
611 * a. surrogate pair (non-BMP characters; 0xD800~0xDFFF)
612 * b. invalid code point > 0x10FFFF
613 * c. buffer underrun
614 */
615 retval = CGPT_FAILED;
616 break;
617 }
618 }
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700619 }
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800620
621 /* A null-terminator shows up before the UTF8 sequence ends. */
622 if (expected_units != decoded_units) {
623 retval = CGPT_FAILED;
624 }
625
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700626 utf16[s16idx++] = 0;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800627 return retval;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700628}
629
Bill Richardson3430b322010-11-29 14:24:51 -0800630/* global types to compare against */
Gabe Black93cf15e2011-07-07 16:00:00 -0700631const Guid guid_chromeos_firmware = GPT_ENT_TYPE_CHROMEOS_FIRMWARE;
Bill Richardson3430b322010-11-29 14:24:51 -0800632const Guid guid_chromeos_kernel = GPT_ENT_TYPE_CHROMEOS_KERNEL;
633const Guid guid_chromeos_rootfs = GPT_ENT_TYPE_CHROMEOS_ROOTFS;
634const Guid guid_linux_data = GPT_ENT_TYPE_LINUX_DATA;
635const Guid guid_chromeos_reserved = GPT_ENT_TYPE_CHROMEOS_RESERVED;
636const Guid guid_efi = GPT_ENT_TYPE_EFI;
637const Guid guid_unused = GPT_ENT_TYPE_UNUSED;
638
Albert Chaulkb334e652013-03-28 15:25:33 -0700639const static struct {
Bill Richardson3430b322010-11-29 14:24:51 -0800640 const Guid *type;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700641 char *name;
642 char *description;
643} supported_types[] = {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800644 {&guid_chromeos_firmware, "firmware", "ChromeOS firmware"},
645 {&guid_chromeos_kernel, "kernel", "ChromeOS kernel"},
646 {&guid_chromeos_rootfs, "rootfs", "ChromeOS rootfs"},
647 {&guid_linux_data, "data", "Linux data"},
648 {&guid_chromeos_reserved, "reserved", "ChromeOS reserved"},
649 {&guid_efi, "efi", "EFI System Partition"},
650 {&guid_unused, "unused", "Unused (nonexistent) partition"},
Bill Richardsonf1372d92010-06-11 09:15:55 -0700651};
652
653/* Resolves human-readable GPT type.
654 * Returns CGPT_OK if found.
655 * Returns CGPT_FAILED if no known type found. */
656int ResolveType(const Guid *type, char *buf) {
657 int i;
658 for (i = 0; i < ARRAY_COUNT(supported_types); ++i) {
Bill Richardson3430b322010-11-29 14:24:51 -0800659 if (!memcmp(type, supported_types[i].type, sizeof(Guid))) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700660 strcpy(buf, supported_types[i].description);
661 return CGPT_OK;
662 }
663 }
664 return CGPT_FAILED;
665}
666
667int SupportedType(const char *name, Guid *type) {
668 int i;
669 for (i = 0; i < ARRAY_COUNT(supported_types); ++i) {
670 if (!strcmp(name, supported_types[i].name)) {
Bill Richardson3430b322010-11-29 14:24:51 -0800671 memcpy(type, supported_types[i].type, sizeof(Guid));
Bill Richardsonf1372d92010-06-11 09:15:55 -0700672 return CGPT_OK;
673 }
674 }
675 return CGPT_FAILED;
676}
677
678void PrintTypes(void) {
679 int i;
680 printf("The partition type may also be given as one of these aliases:\n\n");
681 for (i = 0; i < ARRAY_COUNT(supported_types); ++i) {
682 printf(" %-10s %s\n", supported_types[i].name,
683 supported_types[i].description);
684 }
685 printf("\n");
686}
687
Bill Richardson18e03702014-06-23 17:48:33 -0700688static GptHeader* GetGptHeader(const GptData *gpt) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700689 if (gpt->valid_headers & MASK_PRIMARY)
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700690 return (GptHeader*)gpt->primary_header;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700691 else if (gpt->valid_headers & MASK_SECONDARY)
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700692 return (GptHeader*)gpt->secondary_header;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700693 else
694 return 0;
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700695}
696
697uint32_t GetNumberOfEntries(const struct drive *drive) {
698 GptHeader *header = GetGptHeader(&drive->gpt);
699 if (!header)
700 return 0;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700701 return header->number_of_entries;
702}
703
Bill Richardsonf1372d92010-06-11 09:15:55 -0700704
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700705GptEntry *GetEntry(GptData *gpt, int secondary, uint32_t entry_index) {
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700706 GptHeader *header = GetGptHeader(gpt);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700707 uint8_t *entries;
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700708 uint32_t stride = header->size_of_entry;
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700709 require(stride);
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700710 require(entry_index < header->number_of_entries);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700711
712 if (secondary == PRIMARY) {
713 entries = gpt->primary_entries;
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +0800714 } else if (secondary == SECONDARY) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700715 entries = gpt->secondary_entries;
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +0800716 } else { /* ANY_VALID */
717 require(secondary == ANY_VALID);
718 if (gpt->valid_entries & MASK_PRIMARY) {
719 entries = gpt->primary_entries;
720 } else {
721 require(gpt->valid_entries & MASK_SECONDARY);
722 entries = gpt->secondary_entries;
723 }
Bill Richardsonf1372d92010-06-11 09:15:55 -0700724 }
725
726 return (GptEntry*)(&entries[stride * entry_index]);
727}
728
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700729void SetPriority(struct drive *drive, int secondary, uint32_t entry_index,
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700730 int priority) {
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700731 require(priority >= 0 && priority <= CGPT_ATTRIBUTE_MAX_PRIORITY);
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800732 GptEntry *entry;
733 entry = GetEntry(&drive->gpt, secondary, entry_index);
734 SetEntryPriority(entry, priority);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700735}
736
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700737int GetPriority(struct drive *drive, int secondary, uint32_t entry_index) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800738 GptEntry *entry;
739 entry = GetEntry(&drive->gpt, secondary, entry_index);
740 return GetEntryPriority(entry);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700741}
742
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700743void SetTries(struct drive *drive, int secondary, uint32_t entry_index,
744 int tries) {
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700745 require(tries >= 0 && tries <= CGPT_ATTRIBUTE_MAX_TRIES);
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800746 GptEntry *entry;
747 entry = GetEntry(&drive->gpt, secondary, entry_index);
748 SetEntryTries(entry, tries);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700749}
750
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700751int GetTries(struct drive *drive, int secondary, uint32_t entry_index) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800752 GptEntry *entry;
753 entry = GetEntry(&drive->gpt, secondary, entry_index);
754 return GetEntryTries(entry);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700755}
756
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700757void SetSuccessful(struct drive *drive, int secondary, uint32_t entry_index,
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700758 int success) {
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700759 require(success >= 0 && success <= CGPT_ATTRIBUTE_MAX_SUCCESSFUL);
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800760 GptEntry *entry;
761 entry = GetEntry(&drive->gpt, secondary, entry_index);
762 SetEntrySuccessful(entry, success);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700763}
764
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700765int GetSuccessful(struct drive *drive, int secondary, uint32_t entry_index) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800766 GptEntry *entry;
767 entry = GetEntry(&drive->gpt, secondary, entry_index);
768 return GetEntrySuccessful(entry);
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700769}
770
771void SetRaw(struct drive *drive, int secondary, uint32_t entry_index,
Albert Chaulkb334e652013-03-28 15:25:33 -0700772 uint32_t raw) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800773 GptEntry *entry;
774 entry = GetEntry(&drive->gpt, secondary, entry_index);
775 entry->attrs.fields.gpt_att = (uint16_t)raw;
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700776}
777
778void UpdateAllEntries(struct drive *drive) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800779 RepairEntries(&drive->gpt, MASK_PRIMARY);
780 RepairHeader(&drive->gpt, MASK_PRIMARY);
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700781
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800782 drive->gpt.modified |= (GPT_MODIFIED_HEADER1 | GPT_MODIFIED_ENTRIES1 |
783 GPT_MODIFIED_HEADER2 | GPT_MODIFIED_ENTRIES2);
784 UpdateCrc(&drive->gpt);
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700785}
786
787int IsUnused(struct drive *drive, int secondary, uint32_t index) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800788 GptEntry *entry;
789 entry = GetEntry(&drive->gpt, secondary, index);
790 return GuidIsZero(&entry->type);
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700791}
792
793int IsKernel(struct drive *drive, int secondary, uint32_t index) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800794 GptEntry *entry;
795 entry = GetEntry(&drive->gpt, secondary, index);
796 return GuidEqual(&entry->type, &guid_chromeos_kernel);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700797}
798
799
800#define TOSTRING(A) #A
801const char *GptError(int errnum) {
802 const char *error_string[] = {
803 TOSTRING(GPT_SUCCESS),
804 TOSTRING(GPT_ERROR_NO_VALID_KERNEL),
805 TOSTRING(GPT_ERROR_INVALID_HEADERS),
806 TOSTRING(GPT_ERROR_INVALID_ENTRIES),
807 TOSTRING(GPT_ERROR_INVALID_SECTOR_SIZE),
808 TOSTRING(GPT_ERROR_INVALID_SECTOR_NUMBER),
809 TOSTRING(GPT_ERROR_INVALID_UPDATE_TYPE)
810 };
811 if (errnum < 0 || errnum >= ARRAY_COUNT(error_string))
812 return "<illegal value>";
813 return error_string[errnum];
814}
815
816/* Update CRC value if necessary. */
817void UpdateCrc(GptData *gpt) {
818 GptHeader *primary_header, *secondary_header;
819
820 primary_header = (GptHeader*)gpt->primary_header;
821 secondary_header = (GptHeader*)gpt->secondary_header;
822
Stefan Reinauerb7b865c2012-08-23 15:06:25 -0700823 if (gpt->modified & GPT_MODIFIED_ENTRIES1 &&
824 memcmp(primary_header, GPT_HEADER_SIGNATURE2,
825 GPT_HEADER_SIGNATURE_SIZE)) {
Nam T. Nguyen32004012014-12-12 09:38:35 -0800826 size_t entries_size = primary_header->size_of_entry *
827 primary_header->number_of_entries;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700828 primary_header->entries_crc32 =
Nam T. Nguyen32004012014-12-12 09:38:35 -0800829 Crc32(gpt->primary_entries, entries_size);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700830 }
831 if (gpt->modified & GPT_MODIFIED_ENTRIES2) {
Nam T. Nguyen32004012014-12-12 09:38:35 -0800832 size_t entries_size = secondary_header->size_of_entry *
833 secondary_header->number_of_entries;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700834 secondary_header->entries_crc32 =
Nam T. Nguyen32004012014-12-12 09:38:35 -0800835 Crc32(gpt->secondary_entries, entries_size);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700836 }
837 if (gpt->modified & GPT_MODIFIED_HEADER1) {
838 primary_header->header_crc32 = 0;
839 primary_header->header_crc32 = Crc32(
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +0800840 (const uint8_t *)primary_header, sizeof(GptHeader));
Bill Richardsonf1372d92010-06-11 09:15:55 -0700841 }
842 if (gpt->modified & GPT_MODIFIED_HEADER2) {
843 secondary_header->header_crc32 = 0;
844 secondary_header->header_crc32 = Crc32(
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +0800845 (const uint8_t *)secondary_header, sizeof(GptHeader));
Bill Richardsonf1372d92010-06-11 09:15:55 -0700846 }
847}
848/* Two headers are NOT bitwise identical. For example, my_lba pointers to header
849 * itself so that my_lba in primary and secondary is definitely different.
850 * Only the following fields should be identical.
851 *
852 * first_usable_lba
853 * last_usable_lba
854 * number_of_entries
855 * size_of_entry
856 * disk_uuid
857 *
858 * If any of above field are not matched, overwrite secondary with primary since
859 * we always trust primary.
860 * If any one of header is invalid, copy from another. */
861int IsSynonymous(const GptHeader* a, const GptHeader* b) {
862 if ((a->first_usable_lba == b->first_usable_lba) &&
863 (a->last_usable_lba == b->last_usable_lba) &&
864 (a->number_of_entries == b->number_of_entries) &&
865 (a->size_of_entry == b->size_of_entry) &&
866 (!memcmp(&a->disk_uuid, &b->disk_uuid, sizeof(Guid))))
867 return 1;
868 return 0;
869}
870
871/* Primary entries and secondary entries should be bitwise identical.
872 * If two entries tables are valid, compare them. If not the same,
873 * overwrites secondary with primary (primary always has higher priority),
874 * and marks secondary as modified.
875 * If only one is valid, overwrites invalid one.
876 * If all are invalid, does nothing.
877 * This function returns bit masks for GptData.modified field.
878 * Note that CRC is NOT re-computed in this function.
879 */
880uint8_t RepairEntries(GptData *gpt, const uint32_t valid_entries) {
Stefan Reinauerb7b865c2012-08-23 15:06:25 -0700881 /* If we have an alternate GPT header signature, don't overwrite
882 * the secondary GPT with the primary one as that might wipe the
883 * partition table. Also don't overwrite the primary one with the
884 * secondary one as that will stop Windows from booting. */
885 GptHeader* h = (GptHeader*)(gpt->primary_header);
886 if (!memcmp(h->signature, GPT_HEADER_SIGNATURE2, GPT_HEADER_SIGNATURE_SIZE))
887 return 0;
888
Nam T. Nguyen32004012014-12-12 09:38:35 -0800889 if (gpt->valid_headers & MASK_PRIMARY) {
890 h = (GptHeader*)gpt->primary_header;
891 } else if (gpt->valid_headers & MASK_SECONDARY) {
892 h = (GptHeader*)gpt->secondary_header;
893 } else {
894 /* We cannot trust any header, don't update entries. */
895 return 0;
896 }
897
898 size_t entries_size = h->number_of_entries * h->size_of_entry;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700899 if (valid_entries == MASK_BOTH) {
Nam T. Nguyen32004012014-12-12 09:38:35 -0800900 if (memcmp(gpt->primary_entries, gpt->secondary_entries, entries_size)) {
901 memcpy(gpt->secondary_entries, gpt->primary_entries, entries_size);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700902 return GPT_MODIFIED_ENTRIES2;
903 }
904 } else if (valid_entries == MASK_PRIMARY) {
Nam T. Nguyen32004012014-12-12 09:38:35 -0800905 memcpy(gpt->secondary_entries, gpt->primary_entries, entries_size);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700906 return GPT_MODIFIED_ENTRIES2;
907 } else if (valid_entries == MASK_SECONDARY) {
Nam T. Nguyen32004012014-12-12 09:38:35 -0800908 memcpy(gpt->primary_entries, gpt->secondary_entries, entries_size);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700909 return GPT_MODIFIED_ENTRIES1;
910 }
911
912 return 0;
913}
914
915/* The above five fields are shared between primary and secondary headers.
916 * We can recover one header from another through copying those fields. */
917void CopySynonymousParts(GptHeader* target, const GptHeader* source) {
918 target->first_usable_lba = source->first_usable_lba;
919 target->last_usable_lba = source->last_usable_lba;
920 target->number_of_entries = source->number_of_entries;
921 target->size_of_entry = source->size_of_entry;
922 memcpy(&target->disk_uuid, &source->disk_uuid, sizeof(Guid));
923}
924
925/* This function repairs primary and secondary headers if possible.
926 * If both headers are valid (CRC32 is correct) but
927 * a) indicate inconsistent usable LBA ranges,
928 * b) inconsistent partition entry size and number,
929 * c) inconsistent disk_uuid,
930 * we will use the primary header to overwrite secondary header.
931 * If primary is invalid (CRC32 is wrong), then we repair it from secondary.
932 * If secondary is invalid (CRC32 is wrong), then we repair it from primary.
933 * This function returns the bitmasks for modified header.
934 * Note that CRC value is NOT re-computed in this function. UpdateCrc() will
935 * do it later.
936 */
937uint8_t RepairHeader(GptData *gpt, const uint32_t valid_headers) {
938 GptHeader *primary_header, *secondary_header;
939
940 primary_header = (GptHeader*)gpt->primary_header;
941 secondary_header = (GptHeader*)gpt->secondary_header;
942
943 if (valid_headers == MASK_BOTH) {
944 if (!IsSynonymous(primary_header, secondary_header)) {
945 CopySynonymousParts(secondary_header, primary_header);
946 return GPT_MODIFIED_HEADER2;
947 }
948 } else if (valid_headers == MASK_PRIMARY) {
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +0800949 memcpy(secondary_header, primary_header, sizeof(GptHeader));
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -0700950 secondary_header->my_lba = gpt->gpt_drive_sectors - 1; /* the last sector */
Bill Richardsonf1372d92010-06-11 09:15:55 -0700951 secondary_header->alternate_lba = primary_header->my_lba;
952 secondary_header->entries_lba = secondary_header->my_lba -
Nam T. Nguyen32004012014-12-12 09:38:35 -0800953 CalculateEntriesSectors(primary_header);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700954 return GPT_MODIFIED_HEADER2;
955 } else if (valid_headers == MASK_SECONDARY) {
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +0800956 memcpy(primary_header, secondary_header, sizeof(GptHeader));
Nam T. Nguyen88458d92014-08-28 10:58:47 -0700957 primary_header->my_lba = GPT_PMBR_SECTORS; /* the second sector on drive */
Bill Richardsonf1372d92010-06-11 09:15:55 -0700958 primary_header->alternate_lba = secondary_header->my_lba;
Nam T. Nguyena2d72f72014-08-22 15:01:38 -0700959 /* TODO (namnguyen): Preserve (header, entries) padding space. */
Nam T. Nguyen88458d92014-08-28 10:58:47 -0700960 primary_header->entries_lba = primary_header->my_lba + GPT_HEADER_SECTORS;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700961 return GPT_MODIFIED_HEADER1;
962 }
963
964 return 0;
965}
966
Bill Richardson78299022014-06-20 14:33:00 -0700967int CgptGetNumNonEmptyPartitions(CgptShowParams *params) {
968 struct drive drive;
969 int gpt_retval;
970 int retval;
971
972 if (params == NULL)
973 return CGPT_FAILED;
974
Nam T. Nguyenab899592014-11-13 19:30:46 -0800975 if (CGPT_OK != DriveOpen(params->drive_name, &drive, O_RDONLY,
976 params->drive_size))
Bill Richardson78299022014-06-20 14:33:00 -0700977 return CGPT_FAILED;
978
979 if (GPT_SUCCESS != (gpt_retval = GptSanityCheck(&drive.gpt))) {
980 Error("GptSanityCheck() returned %d: %s\n",
981 gpt_retval, GptError(gpt_retval));
982 retval = CGPT_FAILED;
983 goto done;
984 }
985
986 params->num_partitions = 0;
987 int numEntries = GetNumberOfEntries(&drive);
988 int i;
989 for(i = 0; i < numEntries; i++) {
990 GptEntry *entry = GetEntry(&drive.gpt, ANY_VALID, i);
991 if (GuidIsZero(&entry->type))
992 continue;
993
994 params->num_partitions++;
995 }
996
997 retval = CGPT_OK;
998
999done:
1000 DriveClose(&drive, 0);
1001 return retval;
1002}
1003
Bill Richardson3430b322010-11-29 14:24:51 -08001004int GuidEqual(const Guid *guid1, const Guid *guid2) {
1005 return (0 == memcmp(guid1, guid2, sizeof(Guid)));
1006}
Bill Richardsonf1372d92010-06-11 09:15:55 -07001007
Bill Richardson3f806a22013-03-20 15:02:34 -07001008int GuidIsZero(const Guid *gp) {
Bill Richardson3430b322010-11-29 14:24:51 -08001009 return GuidEqual(gp, &guid_unused);
Bill Richardsonf1372d92010-06-11 09:15:55 -07001010}
1011
Bill Richardsonc4e92af2010-10-12 07:33:15 -07001012void PMBRToStr(struct pmbr *pmbr, char *str, unsigned int buflen) {
1013 char buf[GUID_STRLEN];
Bill Richardson3f806a22013-03-20 15:02:34 -07001014 if (GuidIsZero(&pmbr->boot_guid)) {
Bill Richardsonc4e92af2010-10-12 07:33:15 -07001015 require(snprintf(str, buflen, "PMBR") < buflen);
Bill Richardsonf1372d92010-06-11 09:15:55 -07001016 } else {
Bill Richardsonc4e92af2010-10-12 07:33:15 -07001017 GuidToStr(&pmbr->boot_guid, buf, sizeof(buf));
1018 require(snprintf(str, buflen, "PMBR (Boot GUID: %s)", buf) < buflen);
Bill Richardsonf1372d92010-06-11 09:15:55 -07001019 }
1020}
Bill Richardson4cb54972014-06-20 14:33:00 -07001021
1022/* Optional */
1023int __GenerateGuid(Guid *newguid) { return CGPT_FAILED; };
David Riley05987b12015-02-05 19:22:49 -08001024#ifndef HAVE_MACOS
Bill Richardson4cb54972014-06-20 14:33:00 -07001025int GenerateGuid(Guid *newguid) __attribute__((weak, alias("__GenerateGuid")));
David Riley05987b12015-02-05 19:22:49 -08001026#endif