xref: /rk3399_ARM-atf/tools/fiptool/fiptool.c (revision 7a1b2794307bf18cdea975b8897f8cd7e0579fc9)
1 /*
2  * Copyright (c) 2016, ARM Limited and Contributors. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are met:
6  *
7  * Redistributions of source code must retain the above copyright notice, this
8  * list of conditions and the following disclaimer.
9  *
10  * Redistributions in binary form must reproduce the above copyright notice,
11  * this list of conditions and the following disclaimer in the documentation
12  * and/or other materials provided with the distribution.
13  *
14  * Neither the name of ARM nor the names of its contributors may be used
15  * to endorse or promote products derived from this software without specific
16  * prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 
34 #include <assert.h>
35 #include <errno.h>
36 #include <getopt.h>
37 #include <limits.h>
38 #include <stdarg.h>
39 #include <stdint.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 
45 #include <openssl/sha.h>
46 
47 #include "fiptool.h"
48 #include "firmware_image_package.h"
49 #include "tbbr_config.h"
50 
51 #define OPT_TOC_ENTRY 0
52 #define OPT_PLAT_TOC_FLAGS 1
53 
54 static int info_cmd(int argc, char *argv[]);
55 static void info_usage(void);
56 static int create_cmd(int argc, char *argv[]);
57 static void create_usage(void);
58 static int update_cmd(int argc, char *argv[]);
59 static void update_usage(void);
60 static int unpack_cmd(int argc, char *argv[]);
61 static void unpack_usage(void);
62 static int remove_cmd(int argc, char *argv[]);
63 static void remove_usage(void);
64 static int version_cmd(int argc, char *argv[]);
65 static void version_usage(void);
66 static int help_cmd(int argc, char *argv[]);
67 static void usage(void);
68 
69 /* Available subcommands. */
70 static cmd_t cmds[] = {
71 	{ .name = "info",    .handler = info_cmd,    .usage = info_usage    },
72 	{ .name = "create",  .handler = create_cmd,  .usage = create_usage  },
73 	{ .name = "update",  .handler = update_cmd,  .usage = update_usage  },
74 	{ .name = "unpack",  .handler = unpack_cmd,  .usage = unpack_usage  },
75 	{ .name = "remove",  .handler = remove_cmd,  .usage = remove_usage  },
76 	{ .name = "version", .handler = version_cmd, .usage = version_usage },
77 	{ .name = "help",    .handler = help_cmd,    .usage = NULL          },
78 };
79 
80 static image_t *images[MAX_IMAGES];
81 static size_t nr_images;
82 static uuid_t uuid_null = { 0 };
83 static int verbose;
84 
85 static void vlog(int prio, char *msg, va_list ap)
86 {
87 	char *prefix[] = { "DEBUG", "WARN", "ERROR" };
88 
89 	fprintf(stderr, "%s: ", prefix[prio]);
90 	vfprintf(stderr, msg, ap);
91 	fputc('\n', stderr);
92 }
93 
94 static void log_dbgx(char *msg, ...)
95 {
96 	va_list ap;
97 
98 	va_start(ap, msg);
99 	vlog(LOG_DBG, msg, ap);
100 	va_end(ap);
101 }
102 
103 static void log_warnx(char *msg, ...)
104 {
105 	va_list ap;
106 
107 	va_start(ap, msg);
108 	vlog(LOG_WARN, msg, ap);
109 	va_end(ap);
110 }
111 
112 static void log_err(char *msg, ...)
113 {
114 	char buf[512];
115 	va_list ap;
116 
117 	va_start(ap, msg);
118 	snprintf(buf, sizeof(buf), "%s: %s", msg, strerror(errno));
119 	vlog(LOG_ERR, buf, ap);
120 	va_end(ap);
121 	exit(1);
122 }
123 
124 static void log_errx(char *msg, ...)
125 {
126 	va_list ap;
127 
128 	va_start(ap, msg);
129 	vlog(LOG_ERR, msg, ap);
130 	va_end(ap);
131 	exit(1);
132 }
133 
134 static void add_image(image_t *image)
135 {
136 	if (nr_images + 1 > MAX_IMAGES)
137 		log_errx("Too many images");
138 	images[nr_images++] = image;
139 }
140 
141 static void free_image(image_t *image)
142 {
143 	free(image->buffer);
144 	free(image);
145 }
146 
147 static void replace_image(image_t *image_dst, image_t *image_src)
148 {
149 	int i;
150 
151 	for (i = 0; i < nr_images; i++) {
152 		if (images[i] == image_dst) {
153 			free_image(images[i]);
154 			images[i] = image_src;
155 			break;
156 		}
157 	}
158 	assert(i != nr_images);
159 }
160 
161 static void remove_image(image_t *image)
162 {
163 	int i;
164 
165 	for (i = 0; i < nr_images; i++) {
166 		if (images[i] == image) {
167 			free_image(images[i]);
168 			images[i] = NULL;
169 			break;
170 		}
171 	}
172 	assert(i != nr_images);
173 
174 	/* Compact array. */
175 	memmove(&images[i], &images[i + 1],
176 	    (nr_images - i - 1) * sizeof(*images));
177 	nr_images--;
178 }
179 
180 static void free_images(void)
181 {
182 	int i;
183 
184 	for (i = 0; i < nr_images; i++) {
185 		free_image(images[i]);
186 		images[i] = NULL;
187 	}
188 }
189 
190 static toc_entry_t *get_entry_lookup_from_uuid(const uuid_t *uuid)
191 {
192 	toc_entry_t *toc_entry = toc_entries;
193 
194 	for (; toc_entry->cmdline_name != NULL; toc_entry++)
195 		if (memcmp(&toc_entry->uuid, uuid, sizeof(uuid_t)) == 0)
196 			return toc_entry;
197 	return NULL;
198 }
199 
200 static int parse_fip(char *filename, fip_toc_header_t *toc_header_out)
201 {
202 	struct stat st;
203 	FILE *fp;
204 	char *buf, *bufend;
205 	fip_toc_header_t *toc_header;
206 	fip_toc_entry_t *toc_entry;
207 	image_t *image;
208 	int terminated = 0;
209 
210 	fp = fopen(filename, "r");
211 	if (fp == NULL)
212 		log_err("fopen %s", filename);
213 
214 	if (fstat(fileno(fp), &st) == -1)
215 		log_err("fstat %s", filename);
216 
217 	buf = malloc(st.st_size);
218 	if (buf == NULL)
219 		log_err("malloc");
220 
221 	if (fread(buf, 1, st.st_size, fp) != st.st_size)
222 		log_errx("Failed to read %s", filename);
223 	bufend = buf + st.st_size;
224 	fclose(fp);
225 
226 	if (st.st_size < sizeof(fip_toc_header_t))
227 		log_errx("FIP %s is truncated", filename);
228 
229 	toc_header = (fip_toc_header_t *)buf;
230 	toc_entry = (fip_toc_entry_t *)(toc_header + 1);
231 
232 	if (toc_header->name != TOC_HEADER_NAME)
233 		log_errx("%s is not a FIP file", filename);
234 
235 	/* Return the ToC header if the caller wants it. */
236 	if (toc_header_out != NULL)
237 		*toc_header_out = *toc_header;
238 
239 	/* Walk through each ToC entry in the file. */
240 	while ((char *)toc_entry + sizeof(*toc_entry) - 1 < bufend) {
241 		/* Found the ToC terminator, we are done. */
242 		if (memcmp(&toc_entry->uuid, &uuid_null, sizeof(uuid_t)) == 0) {
243 			terminated = 1;
244 			break;
245 		}
246 
247 		/*
248 		 * Build a new image out of the ToC entry and add it to the
249 		 * table of images.
250 		 */
251 		image = malloc(sizeof(*image));
252 		if (image == NULL)
253 			log_err("malloc");
254 
255 		memcpy(&image->uuid, &toc_entry->uuid, sizeof(uuid_t));
256 
257 		image->buffer = malloc(toc_entry->size);
258 		if (image->buffer == NULL)
259 			log_err("malloc");
260 
261 		/* Overflow checks before memory copy. */
262 		if (toc_entry->size > (uint64_t)-1 - toc_entry->offset_address)
263 			log_errx("FIP %s is corrupted", filename);
264 		if (toc_entry->size + toc_entry->offset_address > st.st_size)
265 			log_errx("FIP %s is corrupted", filename);
266 
267 		memcpy(image->buffer, buf + toc_entry->offset_address,
268 		    toc_entry->size);
269 		image->size = toc_entry->size;
270 
271 		image->toc_entry = get_entry_lookup_from_uuid(&toc_entry->uuid);
272 		if (image->toc_entry == NULL) {
273 			add_image(image);
274 			toc_entry++;
275 			continue;
276 		}
277 
278 		assert(image->toc_entry->image == NULL);
279 		/* Link backpointer from lookup entry. */
280 		image->toc_entry->image = image;
281 		add_image(image);
282 
283 		toc_entry++;
284 	}
285 
286 	if (terminated == 0)
287 		log_errx("FIP %s does not have a ToC terminator entry",
288 		    filename);
289 	free(buf);
290 	return 0;
291 }
292 
293 static image_t *read_image_from_file(toc_entry_t *toc_entry, char *filename)
294 {
295 	struct stat st;
296 	image_t *image;
297 	FILE *fp;
298 
299 	fp = fopen(filename, "r");
300 	if (fp == NULL)
301 		log_err("fopen %s", filename);
302 
303 	if (fstat(fileno(fp), &st) == -1)
304 		log_errx("fstat %s", filename);
305 
306 	image = malloc(sizeof(*image));
307 	if (image == NULL)
308 		log_err("malloc");
309 
310 	memcpy(&image->uuid, &toc_entry->uuid, sizeof(uuid_t));
311 
312 	image->buffer = malloc(st.st_size);
313 	if (image->buffer == NULL)
314 		log_err("malloc");
315 	if (fread(image->buffer, 1, st.st_size, fp) != st.st_size)
316 		log_errx("Failed to read %s", filename);
317 	image->size = st.st_size;
318 	image->toc_entry = toc_entry;
319 
320 	fclose(fp);
321 	return image;
322 }
323 
324 static int write_image_to_file(image_t *image, char *filename)
325 {
326 	FILE *fp;
327 
328 	fp = fopen(filename, "w");
329 	if (fp == NULL)
330 		log_err("fopen");
331 	if (fwrite(image->buffer, 1, image->size, fp) != image->size)
332 		log_errx("Failed to write %s", filename);
333 	fclose(fp);
334 	return 0;
335 }
336 
337 static int fill_common_opts(struct option *opts, int has_arg)
338 {
339 	int i;
340 
341 	for (i = 0; toc_entries[i].cmdline_name != NULL; i++) {
342 		opts[i].name = toc_entries[i].cmdline_name;
343 		opts[i].has_arg = has_arg;
344 		opts[i].flag = NULL;
345 		opts[i].val = 0;
346 	}
347 	return i;
348 }
349 
350 static void add_opt(struct option *opts, int idx, char *name,
351     int has_arg, int val)
352 {
353 	opts[idx].name = name;
354 	opts[idx].has_arg = has_arg;
355 	opts[idx].flag = NULL;
356 	opts[idx].val = val;
357 }
358 
359 static void md_print(unsigned char *md, size_t len)
360 {
361 	size_t i;
362 
363 	for (i = 0; i < len; i++)
364 		printf("%02x", md[i]);
365 }
366 
367 static int info_cmd(int argc, char *argv[])
368 {
369 	image_t *image;
370 	uint64_t image_offset;
371 	uint64_t image_size = 0;
372 	fip_toc_header_t toc_header;
373 	int i;
374 
375 	if (argc != 2)
376 		usage();
377 	argc--, argv++;
378 
379 	parse_fip(argv[0], &toc_header);
380 
381 	if (verbose) {
382 		log_dbgx("toc_header[name]: 0x%llX",
383 		    (unsigned long long)toc_header.name);
384 		log_dbgx("toc_header[serial_number]: 0x%llX",
385 		    (unsigned long long)toc_header.serial_number);
386 		log_dbgx("toc_header[flags]: 0x%llX",
387 		    (unsigned long long)toc_header.flags);
388 	}
389 
390 	image_offset = sizeof(fip_toc_header_t) +
391 	    (sizeof(fip_toc_entry_t) * (nr_images + 1));
392 
393 	for (i = 0; i < nr_images; i++) {
394 		image = images[i];
395 		if (image->toc_entry != NULL)
396 			printf("%s: ", image->toc_entry->name);
397 		else
398 			printf("Unknown entry: ");
399 		image_size = image->size;
400 		printf("offset=0x%llX, size=0x%llX",
401 		    (unsigned long long)image_offset,
402 		    (unsigned long long)image_size);
403 		if (image->toc_entry != NULL)
404 			printf(", cmdline=\"--%s\"",
405 			    image->toc_entry->cmdline_name);
406 		if (verbose) {
407 			unsigned char md[SHA256_DIGEST_LENGTH];
408 
409 			SHA256(image->buffer, image_size, md);
410 			printf(", sha256=");
411 			md_print(md, sizeof(md));
412 		}
413 		putchar('\n');
414 		image_offset += image_size;
415 	}
416 
417 	free_images();
418 	return 0;
419 }
420 
421 static void info_usage(void)
422 {
423 	printf("fiptool info FIP_FILENAME\n");
424 }
425 
426 static int pack_images(char *filename, uint64_t toc_flags)
427 {
428 	FILE *fp;
429 	image_t *image;
430 	fip_toc_header_t *toc_header;
431 	fip_toc_entry_t *toc_entry;
432 	char *buf;
433 	uint64_t entry_offset, buf_size, payload_size;
434 	int i;
435 
436 	/* Calculate total payload size and allocate scratch buffer. */
437 	payload_size = 0;
438 	for (i = 0; i < nr_images; i++)
439 		payload_size += images[i]->size;
440 
441 	buf_size = sizeof(fip_toc_header_t) +
442 	    sizeof(fip_toc_entry_t) * (nr_images + 1);
443 	buf = calloc(1, buf_size);
444 	if (buf == NULL)
445 		log_err("calloc");
446 
447 	/* Build up header and ToC entries from the image table. */
448 	toc_header = (fip_toc_header_t *)buf;
449 	toc_header->name = TOC_HEADER_NAME;
450 	toc_header->serial_number = TOC_HEADER_SERIAL_NUMBER;
451 	toc_header->flags = toc_flags;
452 
453 	toc_entry = (fip_toc_entry_t *)(toc_header + 1);
454 
455 	entry_offset = buf_size;
456 	for (i = 0; i < nr_images; i++) {
457 		image = images[i];
458 		memcpy(&toc_entry->uuid, &image->uuid, sizeof(uuid_t));
459 		toc_entry->offset_address = entry_offset;
460 		toc_entry->size = image->size;
461 		toc_entry->flags = 0;
462 		entry_offset += toc_entry->size;
463 		toc_entry++;
464 	}
465 
466 	/* Append a null uuid entry to mark the end of ToC entries. */
467 	memcpy(&toc_entry->uuid, &uuid_null, sizeof(uuid_t));
468 	toc_entry->offset_address = entry_offset;
469 	toc_entry->size = 0;
470 	toc_entry->flags = 0;
471 
472 	/* Generate the FIP file. */
473 	fp = fopen(filename, "w");
474 	if (fp == NULL)
475 		log_err("fopen %s", filename);
476 
477 	if (verbose)
478 		log_dbgx("Metadata size: %zu bytes", buf_size);
479 
480 	if (fwrite(buf, 1, buf_size, fp) != buf_size)
481 		log_errx("Failed to write image to %s", filename);
482 	free(buf);
483 
484 	if (verbose)
485 		log_dbgx("Payload size: %zu bytes", payload_size);
486 
487 	for (i = 0; i < nr_images; i++) {
488 		image = images[i];
489 		if (fwrite(image->buffer, 1, image->size, fp) != image->size)
490 			log_errx("Failed to write image to %s", filename);
491 	}
492 
493 	fclose(fp);
494 	return 0;
495 }
496 
497 /*
498  * This function is shared between the create and update subcommands.
499  * The difference between the two subcommands is that when the FIP file
500  * is created, the parsing of an existing FIP is skipped.  This results
501  * in update_fip() creating the new FIP file from scratch because the
502  * internal image table is not populated.
503  */
504 static void update_fip(void)
505 {
506 	toc_entry_t *toc_entry;
507 	image_t *image;
508 
509 	/* Add or replace images in the FIP file. */
510 	for (toc_entry = toc_entries;
511 	     toc_entry->cmdline_name != NULL;
512 	     toc_entry++) {
513 		if (toc_entry->action != DO_PACK)
514 			continue;
515 
516 		image = read_image_from_file(toc_entry, toc_entry->action_arg);
517 		if (toc_entry->image != NULL) {
518 			if (verbose)
519 				log_dbgx("Replacing image %s.bin with %s",
520 				    toc_entry->cmdline_name,
521 				    toc_entry->action_arg);
522 			replace_image(toc_entry->image, image);
523 		} else {
524 			if (verbose)
525 				log_dbgx("Adding image %s",
526 				    toc_entry->action_arg);
527 			add_image(image);
528 		}
529 		/* Link backpointer from lookup entry. */
530 		toc_entry->image = image;
531 
532 		free(toc_entry->action_arg);
533 		toc_entry->action_arg = NULL;
534 	}
535 }
536 
537 static void parse_plat_toc_flags(char *arg, unsigned long long *toc_flags)
538 {
539 	unsigned long long flags;
540 	char *endptr;
541 
542 	errno = 0;
543 	flags = strtoull(arg, &endptr, 16);
544 	if (*endptr != '\0' || flags > UINT16_MAX || errno != 0)
545 		log_errx("Invalid platform ToC flags: %s", arg);
546 	/* Platform ToC flags is a 16-bit field occupying bits [32-47]. */
547 	*toc_flags |= flags << 32;
548 }
549 
550 static int create_cmd(int argc, char *argv[])
551 {
552 	struct option opts[toc_entries_len + 1];
553 	unsigned long long toc_flags = 0;
554 	int i;
555 
556 	if (argc < 2)
557 		usage();
558 
559 	i = fill_common_opts(opts, required_argument);
560 	add_opt(opts, i, "plat-toc-flags", required_argument,
561 	    OPT_PLAT_TOC_FLAGS);
562 	add_opt(opts, ++i, NULL, 0, 0);
563 
564 	while (1) {
565 		int c, opt_index;
566 
567 		c = getopt_long(argc, argv, "o:", opts, &opt_index);
568 		if (c == -1)
569 			break;
570 
571 		switch (c) {
572 		case OPT_TOC_ENTRY: {
573 			toc_entry_t *toc_entry;
574 
575 			toc_entry = &toc_entries[opt_index];
576 			toc_entry->action = DO_PACK;
577 			toc_entry->action_arg = strdup(optarg);
578 			if (toc_entry->action_arg == NULL)
579 				log_err("strdup");
580 			break;
581 		}
582 		case OPT_PLAT_TOC_FLAGS:
583 			parse_plat_toc_flags(optarg, &toc_flags);
584 			break;
585 		default:
586 			usage();
587 		}
588 	}
589 	argc -= optind;
590 	argv += optind;
591 
592 	if (argc == 0)
593 		usage();
594 
595 	update_fip();
596 
597 	pack_images(argv[0], toc_flags);
598 	free_images();
599 	return 0;
600 }
601 
602 static void create_usage(void)
603 {
604 	toc_entry_t *toc_entry = toc_entries;
605 
606 	printf("fiptool create [--plat-toc-flags <value>] [opts] FIP_FILENAME\n");
607 	printf("  --plat-toc-flags <value>\t16-bit platform specific flag field "
608 	    "occupying bits 32-47 in 64-bit ToC header.\n");
609 	fputc('\n', stderr);
610 	printf("Specific images are packed with the following options:\n");
611 	for (; toc_entry->cmdline_name != NULL; toc_entry++)
612 		printf("  --%-16s FILENAME\t%s\n", toc_entry->cmdline_name,
613 		    toc_entry->name);
614 }
615 
616 static int update_cmd(int argc, char *argv[])
617 {
618 	struct option opts[toc_entries_len + 2];
619 	char outfile[FILENAME_MAX] = { 0 };
620 	fip_toc_header_t toc_header = { 0 };
621 	unsigned long long toc_flags = 0;
622 	int pflag = 0;
623 	int i;
624 
625 	if (argc < 2)
626 		usage();
627 
628 	i = fill_common_opts(opts, required_argument);
629 	add_opt(opts, i, "out", required_argument, 'o');
630 	add_opt(opts, ++i, "plat-toc-flags", required_argument,
631 	    OPT_PLAT_TOC_FLAGS);
632 	add_opt(opts, ++i, NULL, 0, 0);
633 
634 	while (1) {
635 		int c, opt_index;
636 
637 		c = getopt_long(argc, argv, "o:", opts, &opt_index);
638 		if (c == -1)
639 			break;
640 
641 		switch (c) {
642 		case OPT_TOC_ENTRY: {
643 			toc_entry_t *toc_entry;
644 
645 			toc_entry = &toc_entries[opt_index];
646 			toc_entry->action = DO_PACK;
647 			toc_entry->action_arg = strdup(optarg);
648 			if (toc_entry->action_arg == NULL)
649 				log_err("strdup");
650 			break;
651 		}
652 		case OPT_PLAT_TOC_FLAGS: {
653 			parse_plat_toc_flags(optarg, &toc_flags);
654 			pflag = 1;
655 			break;
656 		}
657 		case 'o':
658 			snprintf(outfile, sizeof(outfile), "%s", optarg);
659 			break;
660 		default:
661 			usage();
662 		}
663 	}
664 	argc -= optind;
665 	argv += optind;
666 
667 	if (argc == 0)
668 		usage();
669 
670 	if (outfile[0] == '\0')
671 		snprintf(outfile, sizeof(outfile), "%s", argv[0]);
672 
673 	if (access(outfile, F_OK) == 0)
674 		parse_fip(argv[0], &toc_header);
675 
676 	if (pflag)
677 		toc_header.flags &= ~(0xffffULL << 32);
678 	toc_flags = (toc_header.flags |= toc_flags);
679 
680 	update_fip();
681 
682 	pack_images(outfile, toc_flags);
683 	free_images();
684 	return 0;
685 }
686 
687 static void update_usage(void)
688 {
689 	toc_entry_t *toc_entry = toc_entries;
690 
691 	printf("fiptool update [--out FIP_FILENAME] "
692 	    "[--plat-toc-flags <value>] [opts] FIP_FILENAME\n");
693 	printf("  --out FIP_FILENAME\t\tSet an alternative output FIP file.\n");
694 	printf("  --plat-toc-flags <value>\t16-bit platform specific flag field "
695 	    "occupying bits 32-47 in 64-bit ToC header.\n");
696 	fputc('\n', stderr);
697 	printf("Specific images are packed with the following options:\n");
698 	for (; toc_entry->cmdline_name != NULL; toc_entry++)
699 		printf("  --%-16s FILENAME\t%s\n", toc_entry->cmdline_name,
700 		    toc_entry->name);
701 }
702 
703 static int unpack_cmd(int argc, char *argv[])
704 {
705 	struct option opts[toc_entries_len + 3];
706 	char file[FILENAME_MAX], outdir[PATH_MAX] = { 0 };
707 	toc_entry_t *toc_entry;
708 	int fflag = 0;
709 	int unpack_all = 1;
710 	int i;
711 
712 	if (argc < 2)
713 		usage();
714 
715 	i = fill_common_opts(opts, required_argument);
716 	add_opt(opts, i, "force", no_argument, 'f');
717 	add_opt(opts, ++i, "out", required_argument, 'o');
718 	add_opt(opts, ++i, NULL, 0, 0);
719 
720 	while (1) {
721 		int c, opt_index;
722 
723 		c = getopt_long(argc, argv, "fo:", opts, &opt_index);
724 		if (c == -1)
725 			break;
726 
727 		switch (c) {
728 		case OPT_TOC_ENTRY:
729 			unpack_all = 0;
730 			toc_entry = &toc_entries[opt_index];
731 			toc_entry->action = DO_UNPACK;
732 			toc_entry->action_arg = strdup(optarg);
733 			if (toc_entry->action_arg == NULL)
734 				log_err("strdup");
735 			break;
736 		case 'f':
737 			fflag = 1;
738 			break;
739 		case 'o':
740 			snprintf(outdir, sizeof(outdir), "%s", optarg);
741 			break;
742 		default:
743 			usage();
744 		}
745 	}
746 	argc -= optind;
747 	argv += optind;
748 
749 	if (argc == 0)
750 		usage();
751 
752 	parse_fip(argv[0], NULL);
753 
754 	if (outdir[0] != '\0')
755 		if (chdir(outdir) == -1)
756 			log_err("chdir %s", outdir);
757 
758 	/* Mark all images to be unpacked. */
759 	if (unpack_all) {
760 		for (toc_entry = toc_entries;
761 		     toc_entry->cmdline_name != NULL;
762 		     toc_entry++) {
763 			if (toc_entry->image != NULL) {
764 				toc_entry->action = DO_UNPACK;
765 				toc_entry->action_arg = NULL;
766 			}
767 		}
768 	}
769 
770 	/* Unpack all specified images. */
771 	for (toc_entry = toc_entries;
772 	     toc_entry->cmdline_name != NULL;
773 	     toc_entry++) {
774 		if (toc_entry->action != DO_UNPACK)
775 			continue;
776 
777 		/* Build filename. */
778 		if (toc_entry->action_arg == NULL)
779 			snprintf(file, sizeof(file), "%s.bin",
780 			    toc_entry->cmdline_name);
781 		else
782 			snprintf(file, sizeof(file), "%s",
783 			    toc_entry->action_arg);
784 
785 		if (toc_entry->image == NULL) {
786 			log_warnx("Requested image %s is not in %s",
787 			    file, argv[0]);
788 			free(toc_entry->action_arg);
789 			toc_entry->action_arg = NULL;
790 			continue;
791 		}
792 
793 		if (access(file, F_OK) != 0 || fflag) {
794 			if (verbose)
795 				log_dbgx("Unpacking %s", file);
796 			write_image_to_file(toc_entry->image, file);
797 		} else {
798 			log_warnx("File %s already exists, use --force to overwrite it",
799 			    file);
800 		}
801 
802 		free(toc_entry->action_arg);
803 		toc_entry->action_arg = NULL;
804 	}
805 
806 	free_images();
807 	return 0;
808 }
809 
810 static void unpack_usage(void)
811 {
812 	toc_entry_t *toc_entry = toc_entries;
813 
814 	printf("fiptool unpack [--force] [--out <path>] [opts] FIP_FILENAME\n");
815 	printf("  --force\tIf the output file already exists, use --force to "
816 	    "overwrite it.\n");
817 	printf("  --out path\tSet the output directory path.\n");
818 	fputc('\n', stderr);
819 	printf("Specific images are unpacked with the following options:\n");
820 	for (; toc_entry->cmdline_name != NULL; toc_entry++)
821 		printf("  --%-16s FILENAME\t%s\n", toc_entry->cmdline_name,
822 		    toc_entry->name);
823 	fputc('\n', stderr);
824 	printf("If no options are provided, all images will be unpacked.\n");
825 }
826 
827 static int remove_cmd(int argc, char *argv[])
828 {
829 	struct option opts[toc_entries_len + 2];
830 	char outfile[FILENAME_MAX] = { 0 };
831 	fip_toc_header_t toc_header;
832 	toc_entry_t *toc_entry;
833 	int fflag = 0;
834 	int i;
835 
836 	if (argc < 2)
837 		usage();
838 
839 	i = fill_common_opts(opts, no_argument);
840 	add_opt(opts, i, "force", no_argument, 'f');
841 	add_opt(opts, ++i, "out", required_argument, 'o');
842 	add_opt(opts, ++i, NULL, 0, 0);
843 
844 	while (1) {
845 		int c, opt_index;
846 
847 		c = getopt_long(argc, argv, "fo:", opts, &opt_index);
848 		if (c == -1)
849 			break;
850 
851 		switch (c) {
852 		case OPT_TOC_ENTRY:
853 			toc_entry = &toc_entries[opt_index];
854 			toc_entry->action = DO_REMOVE;
855 			break;
856 		case 'f':
857 			fflag = 1;
858 			break;
859 		case 'o':
860 			snprintf(outfile, sizeof(outfile), "%s", optarg);
861 			break;
862 		default:
863 			usage();
864 		}
865 	}
866 	argc -= optind;
867 	argv += optind;
868 
869 	if (argc == 0)
870 		usage();
871 
872 	if (outfile[0] != '\0' && access(outfile, F_OK) == 0 && !fflag)
873 		log_errx("File %s already exists, use --force to overwrite it",
874 		    outfile);
875 
876 	if (outfile[0] == '\0')
877 		snprintf(outfile, sizeof(outfile), "%s", argv[0]);
878 
879 	parse_fip(argv[0], &toc_header);
880 
881 	for (toc_entry = toc_entries;
882 	     toc_entry->cmdline_name != NULL;
883 	     toc_entry++) {
884 		if (toc_entry->action != DO_REMOVE)
885 			continue;
886 		if (toc_entry->image != NULL) {
887 			if (verbose)
888 				log_dbgx("Removing %s.bin",
889 				    toc_entry->cmdline_name);
890 			remove_image(toc_entry->image);
891 		} else {
892 			log_warnx("Requested image %s.bin is not in %s",
893 			    toc_entry->cmdline_name, argv[0]);
894 		}
895 	}
896 
897 	pack_images(outfile, toc_header.flags);
898 	free_images();
899 	return 0;
900 }
901 
902 static void remove_usage(void)
903 {
904 	toc_entry_t *toc_entry = toc_entries;
905 
906 	printf("fiptool remove [--force] [--out FIP_FILENAME] [opts] FIP_FILENAME\n");
907 	printf("  --force\t\tIf the output FIP file already exists, use --force to "
908 	    "overwrite it.\n");
909 	printf("  --out FIP_FILENAME\tSet an alternative output FIP file.\n");
910 	fputc('\n', stderr);
911 	printf("Specific images are removed with the following options:\n");
912 	for (; toc_entry->cmdline_name != NULL; toc_entry++)
913 		printf("  --%-16s\t%s\n", toc_entry->cmdline_name,
914 		    toc_entry->name);
915 }
916 
917 static int version_cmd(int argc, char *argv[])
918 {
919 #ifdef VERSION
920 	puts(VERSION);
921 #else
922 	/* If built from fiptool directory, VERSION is not set. */
923 	puts("Unknown version");
924 #endif
925 	return 0;
926 }
927 
928 static void version_usage(void)
929 {
930 	printf("fiptool version\n");
931 }
932 
933 static int help_cmd(int argc, char *argv[])
934 {
935 	int i;
936 
937 	if (argc < 2)
938 		usage();
939 	argc--, argv++;
940 
941 	for (i = 0; i < NELEM(cmds); i++) {
942 		if (strcmp(cmds[i].name, argv[0]) == 0 &&
943 		    cmds[i].usage != NULL) {
944 			cmds[i].usage();
945 			break;
946 		}
947 	}
948 	if (i == NELEM(cmds))
949 		printf("No help for subcommand '%s'\n", argv[0]);
950 	return 0;
951 }
952 
953 static void usage(void)
954 {
955 	printf("usage: [--verbose] fiptool <command> [<args>]\n");
956 	printf("Global options supported:\n");
957 	printf("  --verbose\tEnable verbose output for all commands.\n");
958 	fputc('\n', stderr);
959 	printf("Commands supported:\n");
960 	printf("  info\t\tList images contained in FIP.\n");
961 	printf("  create\tCreate a new FIP with the given images.\n");
962 	printf("  update\tUpdate an existing FIP with the given images.\n");
963 	printf("  unpack\tUnpack images from FIP.\n");
964 	printf("  remove\tRemove images from FIP.\n");
965 	printf("  version\tShow fiptool version.\n");
966 	printf("  help\t\tShow help for given command.\n");
967 	exit(1);
968 }
969 
970 int main(int argc, char *argv[])
971 {
972 	int i, ret = 0;
973 
974 	if (argc < 2)
975 		usage();
976 	argc--, argv++;
977 
978 	if (strcmp(argv[0], "-v") == 0 ||
979 	    strcmp(argv[0], "--verbose") == 0) {
980 		verbose = 1;
981 		argc--, argv++;
982 	}
983 
984 	for (i = 0; i < NELEM(cmds); i++) {
985 		if (strcmp(cmds[i].name, argv[0]) == 0) {
986 			ret = cmds[i].handler(argc, argv);
987 			break;
988 		}
989 	}
990 	if (i == NELEM(cmds))
991 		usage();
992 	return ret;
993 }
994