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