blob: c3edd0fc5897814372f4bc7f04d04d08e880ba5a [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>
Idwer Volleringb384db32021-05-10 21:15:45 +020012#if !defined(HAVE_MACOS) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
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
Mike Frysingerc60eb7e2016-09-07 20:23:46 -040054int check_int_parse(char option, const char *buf) {
55 if (!*optarg || (buf && *buf)) {
56 Error("invalid argument to -%c: \"%s\"\n", option, optarg);
57 return 1;
58 }
59 return 0;
60}
61
62int check_int_limit(char option, int val, int low, int high) {
63 if (val < low || val > high) {
64 Error("value for -%c must be between %d and %d", option, low, high);
65 return 1;
66 }
67 return 0;
68}
69
Bill Richardsonf1372d92010-06-11 09:15:55 -070070int CheckValid(const struct drive *drive) {
71 if ((drive->gpt.valid_headers != MASK_BOTH) ||
72 (drive->gpt.valid_entries != MASK_BOTH)) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -070073 Warning("One of the GPT headers/entries is invalid\n\n");
Bill Richardsonf1372d92010-06-11 09:15:55 -070074 return CGPT_FAILED;
75 }
76 return CGPT_OK;
77}
78
Julius Werner8e8f4b92019-10-28 16:26:18 -070079int Load(struct drive *drive, uint8_t *buf,
Bill Richardsonf1372d92010-06-11 09:15:55 -070080 const uint64_t sector,
81 const uint64_t sector_bytes,
82 const uint64_t sector_count) {
83 int count; /* byte count to read */
84 int nread;
85
Bill Richardsonc4e92af2010-10-12 07:33:15 -070086 require(buf);
87 if (!sector_count || !sector_bytes) {
Jacob Garber3e15a292019-08-05 11:49:35 -060088 Error("%s() failed at line %d: sector_count=%" PRIu64 ", sector_bytes=%" PRIu64 "\n",
Bill Richardsonc4e92af2010-10-12 07:33:15 -070089 __FUNCTION__, __LINE__, sector_count, sector_bytes);
90 return CGPT_FAILED;
91 }
92 /* Make sure that sector_bytes * sector_count doesn't roll over. */
93 if (sector_bytes > (UINT64_MAX / sector_count)) {
Jacob Garber3e15a292019-08-05 11:49:35 -060094 Error("%s() failed at line %d: sector_count=%" PRIu64 ", sector_bytes=%" PRIu64 "\n",
Bill Richardsonc4e92af2010-10-12 07:33:15 -070095 __FUNCTION__, __LINE__, sector_count, sector_bytes);
96 return CGPT_FAILED;
97 }
Bill Richardsonf1372d92010-06-11 09:15:55 -070098 count = sector_bytes * sector_count;
Bill Richardsonf1372d92010-06-11 09:15:55 -070099
Nam T. Nguyenab899592014-11-13 19:30:46 -0800100 if (-1 == lseek(drive->fd, sector * sector_bytes, SEEK_SET)) {
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -0700101 Error("Can't seek: %s\n", strerror(errno));
Julius Werner8e8f4b92019-10-28 16:26:18 -0700102 return CGPT_FAILED;
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700103 }
Bill Richardsonf1372d92010-06-11 09:15:55 -0700104
Julius Werner8e8f4b92019-10-28 16:26:18 -0700105 nread = read(drive->fd, buf, count);
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700106 if (nread < count) {
107 Error("Can't read enough: %d, not %d\n", nread, count);
Julius Werner8e8f4b92019-10-28 16:26:18 -0700108 return CGPT_FAILED;
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700109 }
Bill Richardsonf1372d92010-06-11 09:15:55 -0700110
111 return CGPT_OK;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700112}
113
114
115int ReadPMBR(struct drive *drive) {
Nam T. Nguyenab899592014-11-13 19:30:46 -0800116 if (-1 == lseek(drive->fd, 0, SEEK_SET))
Bill Richardsonf1372d92010-06-11 09:15:55 -0700117 return CGPT_FAILED;
118
Nam T. Nguyenab899592014-11-13 19:30:46 -0800119 int nread = read(drive->fd, &drive->pmbr, sizeof(struct pmbr));
Bill Richardsonf1372d92010-06-11 09:15:55 -0700120 if (nread != sizeof(struct pmbr))
121 return CGPT_FAILED;
122
123 return CGPT_OK;
124}
125
126int WritePMBR(struct drive *drive) {
Nam T. Nguyenab899592014-11-13 19:30:46 -0800127 if (-1 == lseek(drive->fd, 0, SEEK_SET))
Bill Richardsonf1372d92010-06-11 09:15:55 -0700128 return CGPT_FAILED;
129
Nam T. Nguyenab899592014-11-13 19:30:46 -0800130 int nwrote = write(drive->fd, &drive->pmbr, sizeof(struct pmbr));
Bill Richardsonf1372d92010-06-11 09:15:55 -0700131 if (nwrote != sizeof(struct pmbr))
132 return CGPT_FAILED;
133
134 return CGPT_OK;
135}
136
Albert Chaulk534723a2013-03-20 14:46:50 -0700137int Save(struct drive *drive, const uint8_t *buf,
Bill Richardsonf1372d92010-06-11 09:15:55 -0700138 const uint64_t sector,
139 const uint64_t sector_bytes,
140 const uint64_t sector_count) {
141 int count; /* byte count to write */
142 int nwrote;
143
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700144 require(buf);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700145 count = sector_bytes * sector_count;
146
Nam T. Nguyenab899592014-11-13 19:30:46 -0800147 if (-1 == lseek(drive->fd, sector * sector_bytes, SEEK_SET))
Bill Richardsonf1372d92010-06-11 09:15:55 -0700148 return CGPT_FAILED;
149
Nam T. Nguyenab899592014-11-13 19:30:46 -0800150 nwrote = write(drive->fd, buf, count);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700151 if (nwrote < count)
152 return CGPT_FAILED;
153
154 return CGPT_OK;
155}
156
Bill Richardson18e03702014-06-23 17:48:33 -0700157static int GptLoad(struct drive *drive, uint32_t sector_bytes) {
Albert Chaulk534723a2013-03-20 14:46:50 -0700158 drive->gpt.sector_bytes = sector_bytes;
159 if (drive->size % drive->gpt.sector_bytes) {
160 Error("Media size (%llu) is not a multiple of sector size(%d)\n",
161 (long long unsigned int)drive->size, drive->gpt.sector_bytes);
162 return -1;
163 }
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800164 drive->gpt.streaming_drive_sectors = drive->size / drive->gpt.sector_bytes;
Albert Chaulk534723a2013-03-20 14:46:50 -0700165
Julius Werner8e8f4b92019-10-28 16:26:18 -0700166 drive->gpt.primary_header = malloc(drive->gpt.sector_bytes);
167 drive->gpt.secondary_header = malloc(drive->gpt.sector_bytes);
168 drive->gpt.primary_entries = malloc(GPT_ENTRIES_ALLOC_SIZE);
169 drive->gpt.secondary_entries = malloc(GPT_ENTRIES_ALLOC_SIZE);
170 if (!drive->gpt.primary_header || !drive->gpt.secondary_header ||
171 !drive->gpt.primary_entries || !drive->gpt.secondary_entries)
172 return -1;
173
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -0700174 /* TODO(namnguyen): Remove this and totally trust gpt_drive_sectors. */
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800175 if (!(drive->gpt.flags & GPT_FLAG_EXTERNAL)) {
176 drive->gpt.gpt_drive_sectors = drive->gpt.streaming_drive_sectors;
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -0700177 } /* Else, we trust gpt.gpt_drive_sectors. */
178
Albert Chaulk534723a2013-03-20 14:46:50 -0700179 // Read the data.
Julius Werner8e8f4b92019-10-28 16:26:18 -0700180 if (CGPT_OK != Load(drive, drive->gpt.primary_header,
Nam T. Nguyen88458d92014-08-28 10:58:47 -0700181 GPT_PMBR_SECTORS,
182 drive->gpt.sector_bytes, GPT_HEADER_SECTORS)) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700183 Error("Cannot read primary GPT header\n");
Albert Chaulk534723a2013-03-20 14:46:50 -0700184 return -1;
185 }
Julius Werner8e8f4b92019-10-28 16:26:18 -0700186 if (CGPT_OK != Load(drive, drive->gpt.secondary_header,
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -0700187 drive->gpt.gpt_drive_sectors - GPT_PMBR_SECTORS,
Nam T. Nguyen88458d92014-08-28 10:58:47 -0700188 drive->gpt.sector_bytes, GPT_HEADER_SECTORS)) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700189 Error("Cannot read secondary GPT header\n");
Albert Chaulk534723a2013-03-20 14:46:50 -0700190 return -1;
191 }
Nam T. Nguyena2d72f72014-08-22 15:01:38 -0700192 GptHeader* primary_header = (GptHeader*)drive->gpt.primary_header;
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800193 if (CheckHeader(primary_header, 0, drive->gpt.streaming_drive_sectors,
Dan Ehrenberga524a3a2014-11-06 16:22:24 -0800194 drive->gpt.gpt_drive_sectors,
Sam Hurstd6f52a02018-04-11 08:50:58 -0700195 drive->gpt.flags,
196 drive->gpt.sector_bytes) == 0) {
Julius Werner8e8f4b92019-10-28 16:26:18 -0700197 if (CGPT_OK != Load(drive, drive->gpt.primary_entries,
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700198 primary_header->entries_lba,
Nam T. Nguyen32004012014-12-12 09:38:35 -0800199 drive->gpt.sector_bytes,
Sam Hurstd6f52a02018-04-11 08:50:58 -0700200 CalculateEntriesSectors(primary_header,
201 drive->gpt.sector_bytes))) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700202 Error("Cannot read primary partition entry array\n");
203 return -1;
204 }
205 } else {
Julius Werner39910d02016-04-19 16:55:36 -0700206 Warning("Primary GPT header is %s\n",
207 memcmp(primary_header->signature, GPT_HEADER_SIGNATURE_IGNORED,
208 GPT_HEADER_SIGNATURE_SIZE) ? "invalid" : "being ignored");
Albert Chaulk534723a2013-03-20 14:46:50 -0700209 }
Nam T. Nguyena2d72f72014-08-22 15:01:38 -0700210 GptHeader* secondary_header = (GptHeader*)drive->gpt.secondary_header;
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800211 if (CheckHeader(secondary_header, 1, drive->gpt.streaming_drive_sectors,
Dan Ehrenberga524a3a2014-11-06 16:22:24 -0800212 drive->gpt.gpt_drive_sectors,
Sam Hurstd6f52a02018-04-11 08:50:58 -0700213 drive->gpt.flags,
214 drive->gpt.sector_bytes) == 0) {
Julius Werner8e8f4b92019-10-28 16:26:18 -0700215 if (CGPT_OK != Load(drive, drive->gpt.secondary_entries,
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700216 secondary_header->entries_lba,
Nam T. Nguyen32004012014-12-12 09:38:35 -0800217 drive->gpt.sector_bytes,
Sam Hurstd6f52a02018-04-11 08:50:58 -0700218 CalculateEntriesSectors(secondary_header,
219 drive->gpt.sector_bytes))) {
Nam T. Nguyend92856d2014-10-16 15:02:40 -0700220 Error("Cannot read secondary partition entry array\n");
221 return -1;
222 }
223 } else {
Julius Werner39910d02016-04-19 16:55:36 -0700224 Warning("Secondary GPT header is %s\n",
225 memcmp(primary_header->signature, GPT_HEADER_SIGNATURE_IGNORED,
226 GPT_HEADER_SIGNATURE_SIZE) ? "invalid" : "being ignored");
Albert Chaulk534723a2013-03-20 14:46:50 -0700227 }
228 return 0;
229}
230
Bill Richardson18e03702014-06-23 17:48:33 -0700231static int GptSave(struct drive *drive) {
Albert Chaulk534723a2013-03-20 14:46:50 -0700232 int errors = 0;
Julius Werner5de00002016-04-19 13:20:52 -0700233
Julius Werner39910d02016-04-19 16:55:36 -0700234 if (!(drive->gpt.ignored & MASK_PRIMARY)) {
235 if (drive->gpt.modified & GPT_MODIFIED_HEADER1) {
236 if (CGPT_OK != Save(drive, drive->gpt.primary_header,
237 GPT_PMBR_SECTORS,
238 drive->gpt.sector_bytes, GPT_HEADER_SECTORS)) {
239 errors++;
240 Error("Cannot write primary header: %s\n", strerror(errno));
241 }
Julius Werner5de00002016-04-19 13:20:52 -0700242 }
Julius Werner39910d02016-04-19 16:55:36 -0700243 GptHeader* primary_header = (GptHeader*)drive->gpt.primary_header;
244 if (drive->gpt.modified & GPT_MODIFIED_ENTRIES1) {
245 if (CGPT_OK != Save(drive, drive->gpt.primary_entries,
246 primary_header->entries_lba,
247 drive->gpt.sector_bytes,
Sam Hurstd6f52a02018-04-11 08:50:58 -0700248 CalculateEntriesSectors(primary_header,
249 drive->gpt.sector_bytes))) {
Julius Werner39910d02016-04-19 16:55:36 -0700250 errors++;
251 Error("Cannot write primary entries: %s\n", strerror(errno));
252 }
253 }
254
255 // Sync primary GPT before touching secondary so one is always valid.
256 if (drive->gpt.modified & (GPT_MODIFIED_HEADER1 | GPT_MODIFIED_ENTRIES1))
257 if (fsync(drive->fd) < 0 && errno == EIO) {
258 errors++;
259 Error("I/O error when trying to write primary GPT\n");
260 }
261 }
Julius Werner5de00002016-04-19 13:20:52 -0700262
263 // Only start writing secondary GPT if primary was written correctly.
Julius Werner39910d02016-04-19 16:55:36 -0700264 if (!errors && !(drive->gpt.ignored & MASK_SECONDARY)) {
Julius Werner5de00002016-04-19 13:20:52 -0700265 if (drive->gpt.modified & GPT_MODIFIED_HEADER2) {
266 if(CGPT_OK != Save(drive, drive->gpt.secondary_header,
267 drive->gpt.gpt_drive_sectors - GPT_PMBR_SECTORS,
268 drive->gpt.sector_bytes, GPT_HEADER_SECTORS)) {
269 errors++;
270 Error("Cannot write secondary header: %s\n", strerror(errno));
271 }
272 }
273 GptHeader* secondary_header = (GptHeader*)drive->gpt.secondary_header;
274 if (drive->gpt.modified & GPT_MODIFIED_ENTRIES2) {
275 if (CGPT_OK != Save(drive, drive->gpt.secondary_entries,
276 secondary_header->entries_lba,
277 drive->gpt.sector_bytes,
Sam Hurstd6f52a02018-04-11 08:50:58 -0700278 CalculateEntriesSectors(secondary_header,
279 drive->gpt.sector_bytes))) {
Julius Werner5de00002016-04-19 13:20:52 -0700280 errors++;
281 Error("Cannot write secondary entries: %s\n", strerror(errno));
282 }
Albert Chaulk534723a2013-03-20 14:46:50 -0700283 }
284 }
285
Albert Chaulk534723a2013-03-20 14:46:50 -0700286 return errors ? -1 : 0;
287}
288
Nam T. Nguyenab899592014-11-13 19:30:46 -0800289/*
290 * Query drive size and bytes per sector. Return zero on success. On error,
291 * -1 is returned and errno is set appropriately.
292 */
293static int ObtainDriveSize(int fd, uint64_t* size, uint32_t* sector_bytes) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700294 struct stat stat;
Nam T. Nguyenab899592014-11-13 19:30:46 -0800295 if (fstat(fd, &stat) == -1) {
296 return -1;
297 }
Idwer Volleringb384db32021-05-10 21:15:45 +0200298#if !defined(HAVE_MACOS) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
Nam T. Nguyenab899592014-11-13 19:30:46 -0800299 if ((stat.st_mode & S_IFMT) != S_IFREG) {
300 if (ioctl(fd, BLKGETSIZE64, size) < 0) {
301 return -1;
302 }
303 if (ioctl(fd, BLKSSZGET, sector_bytes) < 0) {
304 return -1;
305 }
306 } else {
307 *sector_bytes = 512; /* bytes */
308 *size = stat.st_size;
309 }
David Riley05987b12015-02-05 19:22:49 -0800310#else
311 *sector_bytes = 512; /* bytes */
312 *size = stat.st_size;
313#endif
Nam T. Nguyenab899592014-11-13 19:30:46 -0800314 return 0;
315}
316
317int DriveOpen(const char *drive_path, struct drive *drive, int mode,
318 uint64_t drive_size) {
Albert Chaulk534723a2013-03-20 14:46:50 -0700319 uint32_t sector_bytes;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700320
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700321 require(drive_path);
322 require(drive);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700323
324 // Clear struct for proper error handling.
325 memset(drive, 0, sizeof(struct drive));
326
Julius Werner52fa8c12019-05-07 12:59:47 -0700327 drive->fd = open(drive_path, mode |
Idwer Volleringb384db32021-05-10 21:15:45 +0200328#if !defined(HAVE_MACOS) && !defined(__FreeBSD__) && !defined(__OpenBSD__)
David Riley05987b12015-02-05 19:22:49 -0800329 O_LARGEFILE |
330#endif
331 O_NOFOLLOW);
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800332 if (drive->fd == -1) {
333 Error("Can't open %s: %s\n", drive_path, strerror(errno));
334 return CGPT_FAILED;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700335 }
Bill Richardsonf1372d92010-06-11 09:15:55 -0700336
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800337 uint64_t gpt_drive_size;
338 if (ObtainDriveSize(drive->fd, &gpt_drive_size, &sector_bytes) != 0) {
339 Error("Can't get drive size and bytes per sector for %s: %s\n",
340 drive_path, strerror(errno));
341 goto error_close;
342 }
343
344 drive->gpt.gpt_drive_sectors = gpt_drive_size / sector_bytes;
345 if (drive_size == 0) {
346 drive->size = gpt_drive_size;
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800347 drive->gpt.flags = 0;
Albert Chaulk534723a2013-03-20 14:46:50 -0700348 } else {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800349 drive->size = drive_size;
Dan Ehrenbergb3d38f52014-12-09 13:42:15 -0800350 drive->gpt.flags = GPT_FLAG_EXTERNAL;
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800351 }
352
353
354 if (GptLoad(drive, sector_bytes)) {
355 goto error_close;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700356 }
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700357
Bill Richardsonf1372d92010-06-11 09:15:55 -0700358 // We just load the data. Caller must validate it.
359 return CGPT_OK;
360
361error_close:
362 (void) DriveClose(drive, 0);
363 return CGPT_FAILED;
364}
365
366
367int DriveClose(struct drive *drive, int update_as_needed) {
368 int errors = 0;
369
370 if (update_as_needed) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800371 if (GptSave(drive)) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700372 errors++;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700373 }
374 }
375
Fletcher Woodruff2f6381e2019-03-11 13:33:40 -0600376 free(drive->gpt.primary_header);
377 drive->gpt.primary_header = NULL;
378 free(drive->gpt.primary_entries);
379 drive->gpt.primary_entries = NULL;
380 free(drive->gpt.secondary_header);
381 drive->gpt.secondary_header = NULL;
382 free(drive->gpt.secondary_entries);
383 drive->gpt.secondary_entries = NULL;
384
Louis Yung-Chieh Lo57cdad32013-01-16 11:52:17 +0800385 // Sync early! Only sync file descriptor here, and leave the whole system sync
386 // outside cgpt because whole system sync would trigger tons of disk accesses
387 // and timeout tests.
Nam T. Nguyenab899592014-11-13 19:30:46 -0800388 fsync(drive->fd);
Louis Yung-Chieh Lo57cdad32013-01-16 11:52:17 +0800389
Nam T. Nguyenab899592014-11-13 19:30:46 -0800390 close(drive->fd);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700391
Bill Richardsonf1372d92010-06-11 09:15:55 -0700392 return errors ? CGPT_FAILED : CGPT_OK;
393}
394
395
Bill Richardsonf1372d92010-06-11 09:15:55 -0700396/* GUID conversion functions. Accepted format:
397 *
398 * "C12A7328-F81F-11D2-BA4B-00A0C93EC93B"
399 *
400 * Returns CGPT_OK if parsing is successful; otherwise CGPT_FAILED.
401 */
402int StrToGuid(const char *str, Guid *guid) {
403 uint32_t time_low;
404 uint16_t time_mid;
405 uint16_t time_high_and_version;
406 unsigned int chunk[11];
407
408 if (11 != sscanf(str, "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
409 chunk+0,
410 chunk+1,
411 chunk+2,
412 chunk+3,
413 chunk+4,
414 chunk+5,
415 chunk+6,
416 chunk+7,
417 chunk+8,
418 chunk+9,
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700419 chunk+10)) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700420 printf("FAILED\n");
421 return CGPT_FAILED;
422 }
423
424 time_low = chunk[0] & 0xffffffff;
425 time_mid = chunk[1] & 0xffff;
426 time_high_and_version = chunk[2] & 0xffff;
427
428 guid->u.Uuid.time_low = htole32(time_low);
429 guid->u.Uuid.time_mid = htole16(time_mid);
430 guid->u.Uuid.time_high_and_version = htole16(time_high_and_version);
431
432 guid->u.Uuid.clock_seq_high_and_reserved = chunk[3] & 0xff;
433 guid->u.Uuid.clock_seq_low = chunk[4] & 0xff;
434 guid->u.Uuid.node[0] = chunk[5] & 0xff;
435 guid->u.Uuid.node[1] = chunk[6] & 0xff;
436 guid->u.Uuid.node[2] = chunk[7] & 0xff;
437 guid->u.Uuid.node[3] = chunk[8] & 0xff;
438 guid->u.Uuid.node[4] = chunk[9] & 0xff;
439 guid->u.Uuid.node[5] = chunk[10] & 0xff;
440
441 return CGPT_OK;
442}
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700443void GuidToStr(const Guid *guid, char *str, unsigned int buflen) {
444 require(buflen >= GUID_STRLEN);
445 require(snprintf(str, buflen,
446 "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X",
447 le32toh(guid->u.Uuid.time_low),
448 le16toh(guid->u.Uuid.time_mid),
449 le16toh(guid->u.Uuid.time_high_and_version),
450 guid->u.Uuid.clock_seq_high_and_reserved,
451 guid->u.Uuid.clock_seq_low,
452 guid->u.Uuid.node[0], guid->u.Uuid.node[1],
453 guid->u.Uuid.node[2], guid->u.Uuid.node[3],
454 guid->u.Uuid.node[4], guid->u.Uuid.node[5]) == GUID_STRLEN-1);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700455}
456
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700457/* Convert possibly unterminated UTF16 string to UTF8.
458 * Caller must prepare enough space for UTF8, which could be up to
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800459 * twice the byte length of UTF16 string plus the terminating '\0'.
460 * See the following table for encoding lengths.
461 *
462 * Code point UTF16 UTF8
463 * 0x0000-0x007F 2 bytes 1 byte
464 * 0x0080-0x07FF 2 bytes 2 bytes
465 * 0x0800-0xFFFF 2 bytes 3 bytes
466 * 0x10000-0x10FFFF 4 bytes 4 bytes
467 *
468 * This function uses a simple state meachine to convert UTF-16 char(s) to
469 * a code point. Once a code point is parsed out, the state machine throws
470 * out sequencial UTF-8 chars in one time.
471 *
472 * Return: CGPT_OK --- all character are converted successfully.
473 * CGPT_FAILED --- convert error, i.e. output buffer is too short.
Bill Richardsonf1372d92010-06-11 09:15:55 -0700474 */
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800475int UTF16ToUTF8(const uint16_t *utf16, unsigned int maxinput,
476 uint8_t *utf8, unsigned int maxoutput)
Bill Richardsonf1372d92010-06-11 09:15:55 -0700477{
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700478 size_t s16idx, s8idx;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800479 uint32_t code_point = 0;
480 int code_point_ready = 1; // code point is ready to output.
481 int retval = CGPT_OK;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700482
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700483 if (!utf16 || !maxinput || !utf8 || !maxoutput)
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800484 return CGPT_FAILED;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700485
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700486 maxoutput--; /* plan for termination now */
487
488 for (s16idx = s8idx = 0;
489 s16idx < maxinput && utf16[s16idx] && maxoutput;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800490 s16idx++) {
491 uint16_t codeunit = le16toh(utf16[s16idx]);
492
493 if (code_point_ready) {
494 if (codeunit >= 0xD800 && codeunit <= 0xDBFF) {
495 /* high surrogate, need the low surrogate. */
496 code_point_ready = 0;
497 code_point = (codeunit & 0x03FF) + 0x0040;
498 } else {
499 /* BMP char, output it. */
500 code_point = codeunit;
501 }
502 } else {
503 /* expect the low surrogate */
504 if (codeunit >= 0xDC00 && codeunit <= 0xDFFF) {
505 code_point = (code_point << 10) | (codeunit & 0x03FF);
506 code_point_ready = 1;
507 } else {
508 /* the second code unit is NOT the low surrogate. Unexpected. */
509 code_point_ready = 0;
510 retval = CGPT_FAILED;
511 break;
512 }
513 }
514
515 /* If UTF code point is ready, output it. */
516 if (code_point_ready) {
517 require(code_point <= 0x10FFFF);
518 if (code_point <= 0x7F && maxoutput >= 1) {
519 maxoutput -= 1;
520 utf8[s8idx++] = code_point & 0x7F;
521 } else if (code_point <= 0x7FF && maxoutput >= 2) {
522 maxoutput -= 2;
523 utf8[s8idx++] = 0xC0 | (code_point >> 6);
524 utf8[s8idx++] = 0x80 | (code_point & 0x3F);
525 } else if (code_point <= 0xFFFF && maxoutput >= 3) {
526 maxoutput -= 3;
527 utf8[s8idx++] = 0xE0 | (code_point >> 12);
528 utf8[s8idx++] = 0x80 | ((code_point >> 6) & 0x3F);
529 utf8[s8idx++] = 0x80 | (code_point & 0x3F);
530 } else if (code_point <= 0x10FFFF && maxoutput >= 4) {
531 maxoutput -= 4;
532 utf8[s8idx++] = 0xF0 | (code_point >> 18);
533 utf8[s8idx++] = 0x80 | ((code_point >> 12) & 0x3F);
534 utf8[s8idx++] = 0x80 | ((code_point >> 6) & 0x3F);
535 utf8[s8idx++] = 0x80 | (code_point & 0x3F);
536 } else {
537 /* buffer underrun */
538 retval = CGPT_FAILED;
539 break;
540 }
541 }
Bill Richardsonf1372d92010-06-11 09:15:55 -0700542 }
543 utf8[s8idx++] = 0;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800544 return retval;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700545}
546
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700547/* Convert UTF8 string to UTF16. The UTF8 string must be null-terminated.
548 * Caller must prepare enough space for UTF16, including a terminating 0x0000.
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800549 * See the following table for encoding lengths. In any case, the caller
550 * just needs to prepare the byte length of UTF8 plus the terminating 0x0000.
551 *
552 * Code point UTF16 UTF8
553 * 0x0000-0x007F 2 bytes 1 byte
554 * 0x0080-0x07FF 2 bytes 2 bytes
555 * 0x0800-0xFFFF 2 bytes 3 bytes
556 * 0x10000-0x10FFFF 4 bytes 4 bytes
557 *
558 * This function converts UTF8 chars to a code point first. Then, convrts it
559 * to UTF16 code unit(s).
560 *
561 * Return: CGPT_OK --- all character are converted successfully.
562 * CGPT_FAILED --- convert error, i.e. output buffer is too short.
Bill Richardsonf1372d92010-06-11 09:15:55 -0700563 */
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800564int UTF8ToUTF16(const uint8_t *utf8, uint16_t *utf16, unsigned int maxoutput)
Bill Richardsonf1372d92010-06-11 09:15:55 -0700565{
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700566 size_t s16idx, s8idx;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800567 uint32_t code_point = 0;
568 unsigned int expected_units = 1;
569 unsigned int decoded_units = 1;
570 int retval = CGPT_OK;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700571
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700572 if (!utf8 || !utf16 || !maxoutput)
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800573 return CGPT_FAILED;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700574
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700575 maxoutput--; /* plan for termination */
576
577 for (s8idx = s16idx = 0;
578 utf8[s8idx] && maxoutput;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800579 s8idx++) {
580 uint8_t code_unit;
581 code_unit = utf8[s8idx];
582
583 if (expected_units != decoded_units) {
584 /* Trailing bytes of multi-byte character */
585 if ((code_unit & 0xC0) == 0x80) {
586 code_point = (code_point << 6) | (code_unit & 0x3F);
587 ++decoded_units;
588 } else {
589 /* Unexpected code unit. */
590 retval = CGPT_FAILED;
591 break;
592 }
593 } else {
594 /* parsing a new code point. */
595 decoded_units = 1;
596 if (code_unit <= 0x7F) {
597 code_point = code_unit;
598 expected_units = 1;
599 } else if (code_unit <= 0xBF) {
600 /* 0x80-0xBF must NOT be the heading byte unit of a new code point. */
601 retval = CGPT_FAILED;
602 break;
603 } else if (code_unit >= 0xC2 && code_unit <= 0xDF) {
604 code_point = code_unit & 0x1F;
605 expected_units = 2;
606 } else if (code_unit >= 0xE0 && code_unit <= 0xEF) {
607 code_point = code_unit & 0x0F;
608 expected_units = 3;
609 } else if (code_unit >= 0xF0 && code_unit <= 0xF4) {
610 code_point = code_unit & 0x07;
611 expected_units = 4;
612 } else {
613 /* illegal code unit: 0xC0-0xC1, 0xF5-0xFF */
614 retval = CGPT_FAILED;
615 break;
616 }
617 }
618
619 /* If no more unit is needed, output the UTF16 unit(s). */
620 if ((retval == CGPT_OK) &&
621 (expected_units == decoded_units)) {
622 /* Check if the encoding is the shortest possible UTF-8 sequence. */
623 switch (expected_units) {
624 case 2:
625 if (code_point <= 0x7F) retval = CGPT_FAILED;
626 break;
627 case 3:
628 if (code_point <= 0x7FF) retval = CGPT_FAILED;
629 break;
630 case 4:
631 if (code_point <= 0xFFFF) retval = CGPT_FAILED;
632 break;
633 }
634 if (retval == CGPT_FAILED) break; /* leave immediately */
635
636 if ((code_point <= 0xD7FF) ||
637 (code_point >= 0xE000 && code_point <= 0xFFFF)) {
638 utf16[s16idx++] = code_point;
639 maxoutput -= 1;
640 } else if (code_point >= 0x10000 && code_point <= 0x10FFFF &&
641 maxoutput >= 2) {
642 utf16[s16idx++] = 0xD800 | ((code_point >> 10) - 0x0040);
643 utf16[s16idx++] = 0xDC00 | (code_point & 0x03FF);
644 maxoutput -= 2;
645 } else {
646 /* Three possibilities fall into here. Both are failure cases.
647 * a. surrogate pair (non-BMP characters; 0xD800~0xDFFF)
648 * b. invalid code point > 0x10FFFF
649 * c. buffer underrun
650 */
651 retval = CGPT_FAILED;
652 break;
653 }
654 }
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700655 }
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800656
657 /* A null-terminator shows up before the UTF8 sequence ends. */
658 if (expected_units != decoded_units) {
659 retval = CGPT_FAILED;
660 }
661
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700662 utf16[s16idx++] = 0;
Louis Yung-Chieh Lo500b3c22010-11-22 18:19:11 +0800663 return retval;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700664}
665
Bill Richardson3430b322010-11-29 14:24:51 -0800666/* global types to compare against */
Gabe Black93cf15e2011-07-07 16:00:00 -0700667const Guid guid_chromeos_firmware = GPT_ENT_TYPE_CHROMEOS_FIRMWARE;
Bill Richardson3430b322010-11-29 14:24:51 -0800668const Guid guid_chromeos_kernel = GPT_ENT_TYPE_CHROMEOS_KERNEL;
669const Guid guid_chromeos_rootfs = GPT_ENT_TYPE_CHROMEOS_ROOTFS;
Hung-Te Lina60bf802019-03-22 11:05:30 +0800670const Guid guid_basic_data = GPT_ENT_TYPE_BASIC_DATA;
671const Guid guid_linux_data = GPT_ENT_TYPE_LINUX_FS;
Bill Richardson3430b322010-11-29 14:24:51 -0800672const Guid guid_chromeos_reserved = GPT_ENT_TYPE_CHROMEOS_RESERVED;
673const Guid guid_efi = GPT_ENT_TYPE_EFI;
674const Guid guid_unused = GPT_ENT_TYPE_UNUSED;
675
Albert Chaulkb334e652013-03-28 15:25:33 -0700676const static struct {
Bill Richardson3430b322010-11-29 14:24:51 -0800677 const Guid *type;
Julius Werner52fa8c12019-05-07 12:59:47 -0700678 const char *name;
679 const char *description;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700680} supported_types[] = {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800681 {&guid_chromeos_firmware, "firmware", "ChromeOS firmware"},
682 {&guid_chromeos_kernel, "kernel", "ChromeOS kernel"},
683 {&guid_chromeos_rootfs, "rootfs", "ChromeOS rootfs"},
684 {&guid_linux_data, "data", "Linux data"},
Hung-Te Lina60bf802019-03-22 11:05:30 +0800685 {&guid_basic_data, "basicdata", "Basic data"},
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800686 {&guid_chromeos_reserved, "reserved", "ChromeOS reserved"},
687 {&guid_efi, "efi", "EFI System Partition"},
688 {&guid_unused, "unused", "Unused (nonexistent) partition"},
Bill Richardsonf1372d92010-06-11 09:15:55 -0700689};
690
691/* Resolves human-readable GPT type.
692 * Returns CGPT_OK if found.
693 * Returns CGPT_FAILED if no known type found. */
694int ResolveType(const Guid *type, char *buf) {
695 int i;
696 for (i = 0; i < ARRAY_COUNT(supported_types); ++i) {
Bill Richardson3430b322010-11-29 14:24:51 -0800697 if (!memcmp(type, supported_types[i].type, sizeof(Guid))) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700698 strcpy(buf, supported_types[i].description);
699 return CGPT_OK;
700 }
701 }
702 return CGPT_FAILED;
703}
704
705int SupportedType(const char *name, Guid *type) {
706 int i;
707 for (i = 0; i < ARRAY_COUNT(supported_types); ++i) {
708 if (!strcmp(name, supported_types[i].name)) {
Bill Richardson3430b322010-11-29 14:24:51 -0800709 memcpy(type, supported_types[i].type, sizeof(Guid));
Bill Richardsonf1372d92010-06-11 09:15:55 -0700710 return CGPT_OK;
711 }
712 }
713 return CGPT_FAILED;
714}
715
716void PrintTypes(void) {
717 int i;
718 printf("The partition type may also be given as one of these aliases:\n\n");
719 for (i = 0; i < ARRAY_COUNT(supported_types); ++i) {
720 printf(" %-10s %s\n", supported_types[i].name,
721 supported_types[i].description);
722 }
723 printf("\n");
724}
725
Bill Richardson18e03702014-06-23 17:48:33 -0700726static GptHeader* GetGptHeader(const GptData *gpt) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700727 if (gpt->valid_headers & MASK_PRIMARY)
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700728 return (GptHeader*)gpt->primary_header;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700729 else if (gpt->valid_headers & MASK_SECONDARY)
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700730 return (GptHeader*)gpt->secondary_header;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700731 else
732 return 0;
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700733}
734
735uint32_t GetNumberOfEntries(const struct drive *drive) {
736 GptHeader *header = GetGptHeader(&drive->gpt);
737 if (!header)
738 return 0;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700739 return header->number_of_entries;
740}
741
Bill Richardsonf1372d92010-06-11 09:15:55 -0700742
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700743GptEntry *GetEntry(GptData *gpt, int secondary, uint32_t entry_index) {
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700744 GptHeader *header = GetGptHeader(gpt);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700745 uint8_t *entries;
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700746 uint32_t stride = header->size_of_entry;
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700747 require(stride);
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700748 require(entry_index < header->number_of_entries);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700749
750 if (secondary == PRIMARY) {
751 entries = gpt->primary_entries;
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +0800752 } else if (secondary == SECONDARY) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700753 entries = gpt->secondary_entries;
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +0800754 } else { /* ANY_VALID */
755 require(secondary == ANY_VALID);
756 if (gpt->valid_entries & MASK_PRIMARY) {
757 entries = gpt->primary_entries;
758 } else {
759 require(gpt->valid_entries & MASK_SECONDARY);
760 entries = gpt->secondary_entries;
761 }
Bill Richardsonf1372d92010-06-11 09:15:55 -0700762 }
763
764 return (GptEntry*)(&entries[stride * entry_index]);
765}
766
Ben Chana4a8c022018-01-31 11:39:14 -0800767void SetRequired(struct drive *drive, int secondary, uint32_t entry_index,
768 int required) {
769 require(required >= 0 && required <= CGPT_ATTRIBUTE_MAX_REQUIRED);
770 GptEntry *entry;
771 entry = GetEntry(&drive->gpt, secondary, entry_index);
772 SetEntryRequired(entry, required);
773}
774
775int GetRequired(struct drive *drive, int secondary, uint32_t entry_index) {
776 GptEntry *entry;
777 entry = GetEntry(&drive->gpt, secondary, entry_index);
778 return GetEntryRequired(entry);
779}
780
Mike Frysinger6c18af52016-09-07 16:45:48 -0400781void SetLegacyBoot(struct drive *drive, int secondary, uint32_t entry_index,
782 int legacy_boot) {
783 require(legacy_boot >= 0 && legacy_boot <= CGPT_ATTRIBUTE_MAX_LEGACY_BOOT);
784 GptEntry *entry;
785 entry = GetEntry(&drive->gpt, secondary, entry_index);
786 SetEntryLegacyBoot(entry, legacy_boot);
787}
788
789int GetLegacyBoot(struct drive *drive, int secondary, uint32_t entry_index) {
790 GptEntry *entry;
791 entry = GetEntry(&drive->gpt, secondary, entry_index);
792 return GetEntryLegacyBoot(entry);
793}
794
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700795void SetPriority(struct drive *drive, int secondary, uint32_t entry_index,
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700796 int priority) {
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700797 require(priority >= 0 && priority <= CGPT_ATTRIBUTE_MAX_PRIORITY);
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800798 GptEntry *entry;
799 entry = GetEntry(&drive->gpt, secondary, entry_index);
800 SetEntryPriority(entry, priority);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700801}
802
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700803int GetPriority(struct drive *drive, int secondary, uint32_t entry_index) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800804 GptEntry *entry;
805 entry = GetEntry(&drive->gpt, secondary, entry_index);
806 return GetEntryPriority(entry);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700807}
808
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700809void SetTries(struct drive *drive, int secondary, uint32_t entry_index,
810 int tries) {
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700811 require(tries >= 0 && tries <= CGPT_ATTRIBUTE_MAX_TRIES);
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800812 GptEntry *entry;
813 entry = GetEntry(&drive->gpt, secondary, entry_index);
814 SetEntryTries(entry, tries);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700815}
816
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700817int GetTries(struct drive *drive, int secondary, uint32_t entry_index) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800818 GptEntry *entry;
819 entry = GetEntry(&drive->gpt, secondary, entry_index);
820 return GetEntryTries(entry);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700821}
822
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700823void SetSuccessful(struct drive *drive, int secondary, uint32_t entry_index,
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700824 int success) {
Bill Richardsonc4e92af2010-10-12 07:33:15 -0700825 require(success >= 0 && success <= CGPT_ATTRIBUTE_MAX_SUCCESSFUL);
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800826 GptEntry *entry;
827 entry = GetEntry(&drive->gpt, secondary, entry_index);
828 SetEntrySuccessful(entry, success);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700829}
830
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700831int GetSuccessful(struct drive *drive, int secondary, uint32_t entry_index) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800832 GptEntry *entry;
833 entry = GetEntry(&drive->gpt, secondary, entry_index);
834 return GetEntrySuccessful(entry);
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700835}
836
837void SetRaw(struct drive *drive, int secondary, uint32_t entry_index,
Albert Chaulkb334e652013-03-28 15:25:33 -0700838 uint32_t raw) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800839 GptEntry *entry;
840 entry = GetEntry(&drive->gpt, secondary, entry_index);
841 entry->attrs.fields.gpt_att = (uint16_t)raw;
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700842}
843
844void UpdateAllEntries(struct drive *drive) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800845 RepairEntries(&drive->gpt, MASK_PRIMARY);
846 RepairHeader(&drive->gpt, MASK_PRIMARY);
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700847
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800848 drive->gpt.modified |= (GPT_MODIFIED_HEADER1 | GPT_MODIFIED_ENTRIES1 |
849 GPT_MODIFIED_HEADER2 | GPT_MODIFIED_ENTRIES2);
850 UpdateCrc(&drive->gpt);
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700851}
852
853int IsUnused(struct drive *drive, int secondary, uint32_t index) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800854 GptEntry *entry;
855 entry = GetEntry(&drive->gpt, secondary, index);
856 return GuidIsZero(&entry->type);
Albert Chaulkfa6b35c2013-03-26 13:43:02 -0700857}
858
859int IsKernel(struct drive *drive, int secondary, uint32_t index) {
Nam T. Nguyen8577b532014-11-25 13:26:53 -0800860 GptEntry *entry;
861 entry = GetEntry(&drive->gpt, secondary, index);
862 return GuidEqual(&entry->type, &guid_chromeos_kernel);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700863}
864
865
866#define TOSTRING(A) #A
867const char *GptError(int errnum) {
868 const char *error_string[] = {
869 TOSTRING(GPT_SUCCESS),
870 TOSTRING(GPT_ERROR_NO_VALID_KERNEL),
871 TOSTRING(GPT_ERROR_INVALID_HEADERS),
872 TOSTRING(GPT_ERROR_INVALID_ENTRIES),
873 TOSTRING(GPT_ERROR_INVALID_SECTOR_SIZE),
874 TOSTRING(GPT_ERROR_INVALID_SECTOR_NUMBER),
875 TOSTRING(GPT_ERROR_INVALID_UPDATE_TYPE)
876 };
877 if (errnum < 0 || errnum >= ARRAY_COUNT(error_string))
878 return "<illegal value>";
879 return error_string[errnum];
880}
881
882/* Update CRC value if necessary. */
883void UpdateCrc(GptData *gpt) {
884 GptHeader *primary_header, *secondary_header;
885
886 primary_header = (GptHeader*)gpt->primary_header;
887 secondary_header = (GptHeader*)gpt->secondary_header;
888
Stefan Reinauerb7b865c2012-08-23 15:06:25 -0700889 if (gpt->modified & GPT_MODIFIED_ENTRIES1 &&
890 memcmp(primary_header, GPT_HEADER_SIGNATURE2,
891 GPT_HEADER_SIGNATURE_SIZE)) {
Nam T. Nguyen32004012014-12-12 09:38:35 -0800892 size_t entries_size = primary_header->size_of_entry *
893 primary_header->number_of_entries;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700894 primary_header->entries_crc32 =
Nam T. Nguyen32004012014-12-12 09:38:35 -0800895 Crc32(gpt->primary_entries, entries_size);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700896 }
897 if (gpt->modified & GPT_MODIFIED_ENTRIES2) {
Nam T. Nguyen32004012014-12-12 09:38:35 -0800898 size_t entries_size = secondary_header->size_of_entry *
899 secondary_header->number_of_entries;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700900 secondary_header->entries_crc32 =
Nam T. Nguyen32004012014-12-12 09:38:35 -0800901 Crc32(gpt->secondary_entries, entries_size);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700902 }
903 if (gpt->modified & GPT_MODIFIED_HEADER1) {
904 primary_header->header_crc32 = 0;
905 primary_header->header_crc32 = Crc32(
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +0800906 (const uint8_t *)primary_header, sizeof(GptHeader));
Bill Richardsonf1372d92010-06-11 09:15:55 -0700907 }
908 if (gpt->modified & GPT_MODIFIED_HEADER2) {
909 secondary_header->header_crc32 = 0;
910 secondary_header->header_crc32 = Crc32(
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +0800911 (const uint8_t *)secondary_header, sizeof(GptHeader));
Bill Richardsonf1372d92010-06-11 09:15:55 -0700912 }
913}
914/* Two headers are NOT bitwise identical. For example, my_lba pointers to header
915 * itself so that my_lba in primary and secondary is definitely different.
916 * Only the following fields should be identical.
917 *
918 * first_usable_lba
919 * last_usable_lba
920 * number_of_entries
921 * size_of_entry
922 * disk_uuid
923 *
924 * If any of above field are not matched, overwrite secondary with primary since
925 * we always trust primary.
926 * If any one of header is invalid, copy from another. */
927int IsSynonymous(const GptHeader* a, const GptHeader* b) {
928 if ((a->first_usable_lba == b->first_usable_lba) &&
929 (a->last_usable_lba == b->last_usable_lba) &&
930 (a->number_of_entries == b->number_of_entries) &&
931 (a->size_of_entry == b->size_of_entry) &&
932 (!memcmp(&a->disk_uuid, &b->disk_uuid, sizeof(Guid))))
933 return 1;
934 return 0;
935}
936
937/* Primary entries and secondary entries should be bitwise identical.
938 * If two entries tables are valid, compare them. If not the same,
939 * overwrites secondary with primary (primary always has higher priority),
940 * and marks secondary as modified.
941 * If only one is valid, overwrites invalid one.
942 * If all are invalid, does nothing.
943 * This function returns bit masks for GptData.modified field.
944 * Note that CRC is NOT re-computed in this function.
945 */
946uint8_t RepairEntries(GptData *gpt, const uint32_t valid_entries) {
Stefan Reinauerb7b865c2012-08-23 15:06:25 -0700947 /* If we have an alternate GPT header signature, don't overwrite
948 * the secondary GPT with the primary one as that might wipe the
949 * partition table. Also don't overwrite the primary one with the
950 * secondary one as that will stop Windows from booting. */
951 GptHeader* h = (GptHeader*)(gpt->primary_header);
952 if (!memcmp(h->signature, GPT_HEADER_SIGNATURE2, GPT_HEADER_SIGNATURE_SIZE))
953 return 0;
954
Nam T. Nguyen32004012014-12-12 09:38:35 -0800955 if (gpt->valid_headers & MASK_PRIMARY) {
956 h = (GptHeader*)gpt->primary_header;
957 } else if (gpt->valid_headers & MASK_SECONDARY) {
958 h = (GptHeader*)gpt->secondary_header;
959 } else {
960 /* We cannot trust any header, don't update entries. */
961 return 0;
962 }
963
964 size_t entries_size = h->number_of_entries * h->size_of_entry;
Bill Richardsonf1372d92010-06-11 09:15:55 -0700965 if (valid_entries == MASK_BOTH) {
Nam T. Nguyen32004012014-12-12 09:38:35 -0800966 if (memcmp(gpt->primary_entries, gpt->secondary_entries, entries_size)) {
967 memcpy(gpt->secondary_entries, gpt->primary_entries, entries_size);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700968 return GPT_MODIFIED_ENTRIES2;
969 }
970 } else if (valid_entries == MASK_PRIMARY) {
Nam T. Nguyen32004012014-12-12 09:38:35 -0800971 memcpy(gpt->secondary_entries, gpt->primary_entries, entries_size);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700972 return GPT_MODIFIED_ENTRIES2;
973 } else if (valid_entries == MASK_SECONDARY) {
Nam T. Nguyen32004012014-12-12 09:38:35 -0800974 memcpy(gpt->primary_entries, gpt->secondary_entries, entries_size);
Bill Richardsonf1372d92010-06-11 09:15:55 -0700975 return GPT_MODIFIED_ENTRIES1;
976 }
977
978 return 0;
979}
980
981/* The above five fields are shared between primary and secondary headers.
982 * We can recover one header from another through copying those fields. */
Julius Werner52fa8c12019-05-07 12:59:47 -0700983static void CopySynonymousParts(GptHeader* target, const GptHeader* source) {
Bill Richardsonf1372d92010-06-11 09:15:55 -0700984 target->first_usable_lba = source->first_usable_lba;
985 target->last_usable_lba = source->last_usable_lba;
986 target->number_of_entries = source->number_of_entries;
987 target->size_of_entry = source->size_of_entry;
988 memcpy(&target->disk_uuid, &source->disk_uuid, sizeof(Guid));
989}
990
991/* This function repairs primary and secondary headers if possible.
992 * If both headers are valid (CRC32 is correct) but
993 * a) indicate inconsistent usable LBA ranges,
994 * b) inconsistent partition entry size and number,
995 * c) inconsistent disk_uuid,
996 * we will use the primary header to overwrite secondary header.
997 * If primary is invalid (CRC32 is wrong), then we repair it from secondary.
998 * If secondary is invalid (CRC32 is wrong), then we repair it from primary.
999 * This function returns the bitmasks for modified header.
1000 * Note that CRC value is NOT re-computed in this function. UpdateCrc() will
1001 * do it later.
1002 */
1003uint8_t RepairHeader(GptData *gpt, const uint32_t valid_headers) {
1004 GptHeader *primary_header, *secondary_header;
1005
1006 primary_header = (GptHeader*)gpt->primary_header;
1007 secondary_header = (GptHeader*)gpt->secondary_header;
1008
1009 if (valid_headers == MASK_BOTH) {
1010 if (!IsSynonymous(primary_header, secondary_header)) {
1011 CopySynonymousParts(secondary_header, primary_header);
1012 return GPT_MODIFIED_HEADER2;
1013 }
1014 } else if (valid_headers == MASK_PRIMARY) {
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +08001015 memcpy(secondary_header, primary_header, sizeof(GptHeader));
Nam T. Nguyen6ee52d92014-10-24 13:20:39 -07001016 secondary_header->my_lba = gpt->gpt_drive_sectors - 1; /* the last sector */
Bill Richardsonf1372d92010-06-11 09:15:55 -07001017 secondary_header->alternate_lba = primary_header->my_lba;
1018 secondary_header->entries_lba = secondary_header->my_lba -
Sam Hurstd6f52a02018-04-11 08:50:58 -07001019 CalculateEntriesSectors(primary_header, gpt->sector_bytes);
Bill Richardsonf1372d92010-06-11 09:15:55 -07001020 return GPT_MODIFIED_HEADER2;
1021 } else if (valid_headers == MASK_SECONDARY) {
Louis Yung-Chieh Lo2b23c022010-11-18 09:53:10 +08001022 memcpy(primary_header, secondary_header, sizeof(GptHeader));
Nam T. Nguyen88458d92014-08-28 10:58:47 -07001023 primary_header->my_lba = GPT_PMBR_SECTORS; /* the second sector on drive */
Bill Richardsonf1372d92010-06-11 09:15:55 -07001024 primary_header->alternate_lba = secondary_header->my_lba;
Nam T. Nguyena2d72f72014-08-22 15:01:38 -07001025 /* TODO (namnguyen): Preserve (header, entries) padding space. */
Nam T. Nguyen88458d92014-08-28 10:58:47 -07001026 primary_header->entries_lba = primary_header->my_lba + GPT_HEADER_SECTORS;
Bill Richardsonf1372d92010-06-11 09:15:55 -07001027 return GPT_MODIFIED_HEADER1;
1028 }
1029
1030 return 0;
1031}
1032
Bill Richardson78299022014-06-20 14:33:00 -07001033int CgptGetNumNonEmptyPartitions(CgptShowParams *params) {
1034 struct drive drive;
1035 int gpt_retval;
1036 int retval;
1037
1038 if (params == NULL)
1039 return CGPT_FAILED;
1040
Nam T. Nguyenab899592014-11-13 19:30:46 -08001041 if (CGPT_OK != DriveOpen(params->drive_name, &drive, O_RDONLY,
1042 params->drive_size))
Bill Richardson78299022014-06-20 14:33:00 -07001043 return CGPT_FAILED;
1044
Daisuke Nojiri053592b2020-08-12 15:46:30 -07001045 if (GPT_SUCCESS != (gpt_retval = GptValidityCheck(&drive.gpt))) {
1046 Error("GptValidityCheck() returned %d: %s\n",
Bill Richardson78299022014-06-20 14:33:00 -07001047 gpt_retval, GptError(gpt_retval));
1048 retval = CGPT_FAILED;
1049 goto done;
1050 }
1051
1052 params->num_partitions = 0;
1053 int numEntries = GetNumberOfEntries(&drive);
1054 int i;
1055 for(i = 0; i < numEntries; i++) {
1056 GptEntry *entry = GetEntry(&drive.gpt, ANY_VALID, i);
1057 if (GuidIsZero(&entry->type))
1058 continue;
1059
1060 params->num_partitions++;
1061 }
1062
1063 retval = CGPT_OK;
1064
1065done:
1066 DriveClose(&drive, 0);
1067 return retval;
1068}
1069
Bill Richardson3430b322010-11-29 14:24:51 -08001070int GuidEqual(const Guid *guid1, const Guid *guid2) {
1071 return (0 == memcmp(guid1, guid2, sizeof(Guid)));
1072}
Bill Richardsonf1372d92010-06-11 09:15:55 -07001073
Bill Richardson3f806a22013-03-20 15:02:34 -07001074int GuidIsZero(const Guid *gp) {
Bill Richardson3430b322010-11-29 14:24:51 -08001075 return GuidEqual(gp, &guid_unused);
Bill Richardsonf1372d92010-06-11 09:15:55 -07001076}
1077
Bill Richardsonc4e92af2010-10-12 07:33:15 -07001078void PMBRToStr(struct pmbr *pmbr, char *str, unsigned int buflen) {
1079 char buf[GUID_STRLEN];
Bill Richardson3f806a22013-03-20 15:02:34 -07001080 if (GuidIsZero(&pmbr->boot_guid)) {
Bill Richardsonc4e92af2010-10-12 07:33:15 -07001081 require(snprintf(str, buflen, "PMBR") < buflen);
Bill Richardsonf1372d92010-06-11 09:15:55 -07001082 } else {
Bill Richardsonc4e92af2010-10-12 07:33:15 -07001083 GuidToStr(&pmbr->boot_guid, buf, sizeof(buf));
1084 require(snprintf(str, buflen, "PMBR (Boot GUID: %s)", buf) < buflen);
Bill Richardsonf1372d92010-06-11 09:15:55 -07001085 }
1086}
Bill Richardson4cb54972014-06-20 14:33:00 -07001087
Julius Werner83b44732019-08-14 16:40:01 -07001088/*
1089 * This is here because some CGPT functionality is provided in libvboot_host.a
1090 * for other host utilities. GenerateGuid() is implemented (in cgpt.c which is
1091 * *not* linked into libvboot_host.a) by calling into libuuid. We don't want to
1092 * mandate libuuid as a dependency for every utilitity that wants to link
1093 * libvboot_host.a, since they usually don't use the functionality that needs
1094 * to generate new UUIDs anyway (just other functionality implemented in the
1095 * same files).
1096 */
David Riley05987b12015-02-05 19:22:49 -08001097#ifndef HAVE_MACOS
Julius Werner52fa8c12019-05-07 12:59:47 -07001098__attribute__((weak)) int GenerateGuid(Guid *newguid) { return CGPT_FAILED; };
David Riley05987b12015-02-05 19:22:49 -08001099#endif