xref: /rk3399_ARM-atf/tools/fiptool/fiptool.c (revision 85ee27786897e1a470ca7b564c3abf01a8a230ca)
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 		info_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 	exit(1);
409 }
410 
411 static int pack_images(char *filename, uint64_t toc_flags)
412 {
413 	FILE *fp;
414 	image_t *image;
415 	fip_toc_header_t *toc_header;
416 	fip_toc_entry_t *toc_entry;
417 	char *buf;
418 	uint64_t entry_offset, buf_size, payload_size;
419 	int i;
420 
421 	/* Calculate total payload size and allocate scratch buffer. */
422 	payload_size = 0;
423 	for (i = 0; i < nr_images; i++)
424 		payload_size += images[i]->size;
425 
426 	buf_size = sizeof(fip_toc_header_t) +
427 	    sizeof(fip_toc_entry_t) * (nr_images + 1);
428 	buf = calloc(1, buf_size);
429 	if (buf == NULL)
430 		log_err("calloc");
431 
432 	/* Build up header and ToC entries from the image table. */
433 	toc_header = (fip_toc_header_t *)buf;
434 	toc_header->name = TOC_HEADER_NAME;
435 	toc_header->serial_number = TOC_HEADER_SERIAL_NUMBER;
436 	toc_header->flags = toc_flags;
437 
438 	toc_entry = (fip_toc_entry_t *)(toc_header + 1);
439 
440 	entry_offset = buf_size;
441 	for (i = 0; i < nr_images; i++) {
442 		image = images[i];
443 		memcpy(&toc_entry->uuid, &image->uuid, sizeof(uuid_t));
444 		toc_entry->offset_address = entry_offset;
445 		toc_entry->size = image->size;
446 		toc_entry->flags = 0;
447 		entry_offset += toc_entry->size;
448 		toc_entry++;
449 	}
450 
451 	/* Append a null uuid entry to mark the end of ToC entries. */
452 	memcpy(&toc_entry->uuid, &uuid_null, sizeof(uuid_t));
453 	toc_entry->offset_address = entry_offset;
454 	toc_entry->size = 0;
455 	toc_entry->flags = 0;
456 
457 	/* Generate the FIP file. */
458 	fp = fopen(filename, "w");
459 	if (fp == NULL)
460 		log_err("fopen %s", filename);
461 
462 	if (verbose)
463 		log_dbgx("Metadata size: %zu bytes", buf_size);
464 
465 	if (fwrite(buf, 1, buf_size, fp) != buf_size)
466 		log_errx("Failed to write image to %s", filename);
467 	free(buf);
468 
469 	if (verbose)
470 		log_dbgx("Payload size: %zu bytes", payload_size);
471 
472 	for (i = 0; i < nr_images; i++) {
473 		image = images[i];
474 		if (fwrite(image->buffer, 1, image->size, fp) != image->size)
475 			log_errx("Failed to write image to %s", filename);
476 	}
477 
478 	fclose(fp);
479 	return 0;
480 }
481 
482 /*
483  * This function is shared between the create and update subcommands.
484  * The difference between the two subcommands is that when the FIP file
485  * is created, the parsing of an existing FIP is skipped.  This results
486  * in update_fip() creating the new FIP file from scratch because the
487  * internal image table is not populated.
488  */
489 static void update_fip(void)
490 {
491 	toc_entry_t *toc_entry;
492 	image_t *image;
493 
494 	/* Add or replace images in the FIP file. */
495 	for (toc_entry = toc_entries;
496 	     toc_entry->cmdline_name != NULL;
497 	     toc_entry++) {
498 		if (toc_entry->action != DO_PACK)
499 			continue;
500 
501 		image = read_image_from_file(toc_entry, toc_entry->action_arg);
502 		if (toc_entry->image != NULL) {
503 			if (verbose)
504 				log_dbgx("Replacing image %s.bin with %s",
505 				    toc_entry->cmdline_name,
506 				    toc_entry->action_arg);
507 			replace_image(toc_entry->image, image);
508 		} else {
509 			if (verbose)
510 				log_dbgx("Adding image %s",
511 				    toc_entry->action_arg);
512 			add_image(image);
513 		}
514 		/* Link backpointer from lookup entry. */
515 		toc_entry->image = image;
516 
517 		free(toc_entry->action_arg);
518 		toc_entry->action_arg = NULL;
519 	}
520 }
521 
522 static void parse_plat_toc_flags(char *arg, unsigned long long *toc_flags)
523 {
524 	unsigned long long flags;
525 	char *endptr;
526 
527 	errno = 0;
528 	flags = strtoull(arg, &endptr, 16);
529 	if (*endptr != '\0' || flags > UINT16_MAX || errno != 0)
530 		log_errx("Invalid platform ToC flags: %s", arg);
531 	/* Platform ToC flags is a 16-bit field occupying bits [32-47]. */
532 	*toc_flags |= flags << 32;
533 }
534 
535 static int create_cmd(int argc, char *argv[])
536 {
537 	struct option opts[toc_entries_len + 1];
538 	unsigned long long toc_flags = 0;
539 	int i;
540 
541 	if (argc < 2)
542 		create_usage();
543 
544 	i = fill_common_opts(opts, required_argument);
545 	add_opt(opts, i, "plat-toc-flags", required_argument,
546 	    OPT_PLAT_TOC_FLAGS);
547 	add_opt(opts, ++i, NULL, 0, 0);
548 
549 	while (1) {
550 		int c, opt_index;
551 
552 		c = getopt_long(argc, argv, "o:", opts, &opt_index);
553 		if (c == -1)
554 			break;
555 
556 		switch (c) {
557 		case OPT_TOC_ENTRY: {
558 			toc_entry_t *toc_entry;
559 
560 			toc_entry = &toc_entries[opt_index];
561 			toc_entry->action = DO_PACK;
562 			toc_entry->action_arg = strdup(optarg);
563 			if (toc_entry->action_arg == NULL)
564 				log_err("strdup");
565 			break;
566 		}
567 		case OPT_PLAT_TOC_FLAGS:
568 			parse_plat_toc_flags(optarg, &toc_flags);
569 			break;
570 		default:
571 			create_usage();
572 		}
573 	}
574 	argc -= optind;
575 	argv += optind;
576 
577 	if (argc == 0)
578 		create_usage();
579 
580 	update_fip();
581 
582 	pack_images(argv[0], toc_flags);
583 	free_images();
584 	return 0;
585 }
586 
587 static void create_usage(void)
588 {
589 	toc_entry_t *toc_entry = toc_entries;
590 
591 	printf("fiptool create [--plat-toc-flags <value>] [opts] FIP_FILENAME\n");
592 	printf("  --plat-toc-flags <value>\t16-bit platform specific flag field "
593 	    "occupying bits 32-47 in 64-bit ToC header.\n");
594 	fputc('\n', stderr);
595 	printf("Specific images are packed with the following options:\n");
596 	for (; toc_entry->cmdline_name != NULL; toc_entry++)
597 		printf("  --%-16s FILENAME\t%s\n", toc_entry->cmdline_name,
598 		    toc_entry->name);
599 	exit(1);
600 }
601 
602 static int update_cmd(int argc, char *argv[])
603 {
604 	struct option opts[toc_entries_len + 2];
605 	char outfile[FILENAME_MAX] = { 0 };
606 	fip_toc_header_t toc_header = { 0 };
607 	unsigned long long toc_flags = 0;
608 	int pflag = 0;
609 	int i;
610 
611 	if (argc < 2)
612 		update_usage();
613 
614 	i = fill_common_opts(opts, required_argument);
615 	add_opt(opts, i, "out", required_argument, 'o');
616 	add_opt(opts, ++i, "plat-toc-flags", required_argument,
617 	    OPT_PLAT_TOC_FLAGS);
618 	add_opt(opts, ++i, NULL, 0, 0);
619 
620 	while (1) {
621 		int c, opt_index;
622 
623 		c = getopt_long(argc, argv, "o:", opts, &opt_index);
624 		if (c == -1)
625 			break;
626 
627 		switch (c) {
628 		case OPT_TOC_ENTRY: {
629 			toc_entry_t *toc_entry;
630 
631 			toc_entry = &toc_entries[opt_index];
632 			toc_entry->action = DO_PACK;
633 			toc_entry->action_arg = strdup(optarg);
634 			if (toc_entry->action_arg == NULL)
635 				log_err("strdup");
636 			break;
637 		}
638 		case OPT_PLAT_TOC_FLAGS: {
639 			parse_plat_toc_flags(optarg, &toc_flags);
640 			pflag = 1;
641 			break;
642 		}
643 		case 'o':
644 			snprintf(outfile, sizeof(outfile), "%s", optarg);
645 			break;
646 		default:
647 			update_usage();
648 		}
649 	}
650 	argc -= optind;
651 	argv += optind;
652 
653 	if (argc == 0)
654 		update_usage();
655 
656 	if (outfile[0] == '\0')
657 		snprintf(outfile, sizeof(outfile), "%s", argv[0]);
658 
659 	if (access(outfile, F_OK) == 0)
660 		parse_fip(argv[0], &toc_header);
661 
662 	if (pflag)
663 		toc_header.flags &= ~(0xffffULL << 32);
664 	toc_flags = (toc_header.flags |= toc_flags);
665 
666 	update_fip();
667 
668 	pack_images(outfile, toc_flags);
669 	free_images();
670 	return 0;
671 }
672 
673 static void update_usage(void)
674 {
675 	toc_entry_t *toc_entry = toc_entries;
676 
677 	printf("fiptool update [--out FIP_FILENAME] "
678 	    "[--plat-toc-flags <value>] [opts] FIP_FILENAME\n");
679 	printf("  --out FIP_FILENAME\t\tSet an alternative output FIP file.\n");
680 	printf("  --plat-toc-flags <value>\t16-bit platform specific flag field "
681 	    "occupying bits 32-47 in 64-bit ToC header.\n");
682 	fputc('\n', stderr);
683 	printf("Specific images are packed with the following options:\n");
684 	for (; toc_entry->cmdline_name != NULL; toc_entry++)
685 		printf("  --%-16s FILENAME\t%s\n", toc_entry->cmdline_name,
686 		    toc_entry->name);
687 	exit(1);
688 }
689 
690 static int unpack_cmd(int argc, char *argv[])
691 {
692 	struct option opts[toc_entries_len + 3];
693 	char file[FILENAME_MAX], outdir[PATH_MAX] = { 0 };
694 	toc_entry_t *toc_entry;
695 	int fflag = 0;
696 	int unpack_all = 1;
697 	int i;
698 
699 	if (argc < 2)
700 		unpack_usage();
701 
702 	i = fill_common_opts(opts, required_argument);
703 	add_opt(opts, i, "force", no_argument, 'f');
704 	add_opt(opts, ++i, "out", required_argument, 'o');
705 	add_opt(opts, ++i, NULL, 0, 0);
706 
707 	while (1) {
708 		int c, opt_index;
709 
710 		c = getopt_long(argc, argv, "fo:", opts, &opt_index);
711 		if (c == -1)
712 			break;
713 
714 		switch (c) {
715 		case OPT_TOC_ENTRY:
716 			unpack_all = 0;
717 			toc_entry = &toc_entries[opt_index];
718 			toc_entry->action = DO_UNPACK;
719 			toc_entry->action_arg = strdup(optarg);
720 			if (toc_entry->action_arg == NULL)
721 				log_err("strdup");
722 			break;
723 		case 'f':
724 			fflag = 1;
725 			break;
726 		case 'o':
727 			snprintf(outdir, sizeof(outdir), "%s", optarg);
728 			break;
729 		default:
730 			unpack_usage();
731 		}
732 	}
733 	argc -= optind;
734 	argv += optind;
735 
736 	if (argc == 0)
737 		unpack_usage();
738 
739 	parse_fip(argv[0], NULL);
740 
741 	if (outdir[0] != '\0')
742 		if (chdir(outdir) == -1)
743 			log_err("chdir %s", outdir);
744 
745 	/* Mark all images to be unpacked. */
746 	if (unpack_all) {
747 		for (toc_entry = toc_entries;
748 		     toc_entry->cmdline_name != NULL;
749 		     toc_entry++) {
750 			if (toc_entry->image != NULL) {
751 				toc_entry->action = DO_UNPACK;
752 				toc_entry->action_arg = NULL;
753 			}
754 		}
755 	}
756 
757 	/* Unpack all specified images. */
758 	for (toc_entry = toc_entries;
759 	     toc_entry->cmdline_name != NULL;
760 	     toc_entry++) {
761 		if (toc_entry->action != DO_UNPACK)
762 			continue;
763 
764 		/* Build filename. */
765 		if (toc_entry->action_arg == NULL)
766 			snprintf(file, sizeof(file), "%s.bin",
767 			    toc_entry->cmdline_name);
768 		else
769 			snprintf(file, sizeof(file), "%s",
770 			    toc_entry->action_arg);
771 
772 		if (toc_entry->image == NULL) {
773 			log_warnx("Requested image %s is not in %s",
774 			    file, argv[0]);
775 			free(toc_entry->action_arg);
776 			toc_entry->action_arg = NULL;
777 			continue;
778 		}
779 
780 		if (access(file, F_OK) != 0 || fflag) {
781 			if (verbose)
782 				log_dbgx("Unpacking %s", file);
783 			write_image_to_file(toc_entry->image, file);
784 		} else {
785 			log_warnx("File %s already exists, use --force to overwrite it",
786 			    file);
787 		}
788 
789 		free(toc_entry->action_arg);
790 		toc_entry->action_arg = NULL;
791 	}
792 
793 	free_images();
794 	return 0;
795 }
796 
797 static void unpack_usage(void)
798 {
799 	toc_entry_t *toc_entry = toc_entries;
800 
801 	printf("fiptool unpack [--force] [--out <path>] [opts] FIP_FILENAME\n");
802 	printf("  --force\tIf the output file already exists, use --force to "
803 	    "overwrite it.\n");
804 	printf("  --out path\tSet the output directory path.\n");
805 	fputc('\n', stderr);
806 	printf("Specific images are unpacked with the following options:\n");
807 	for (; toc_entry->cmdline_name != NULL; toc_entry++)
808 		printf("  --%-16s FILENAME\t%s\n", toc_entry->cmdline_name,
809 		    toc_entry->name);
810 	fputc('\n', stderr);
811 	printf("If no options are provided, all images will be unpacked.\n");
812 	exit(1);
813 }
814 
815 static int remove_cmd(int argc, char *argv[])
816 {
817 	struct option opts[toc_entries_len + 2];
818 	char outfile[FILENAME_MAX] = { 0 };
819 	fip_toc_header_t toc_header;
820 	toc_entry_t *toc_entry;
821 	int fflag = 0;
822 	int i;
823 
824 	if (argc < 2)
825 		remove_usage();
826 
827 	i = fill_common_opts(opts, no_argument);
828 	add_opt(opts, i, "force", no_argument, 'f');
829 	add_opt(opts, ++i, "out", required_argument, 'o');
830 	add_opt(opts, ++i, NULL, 0, 0);
831 
832 	while (1) {
833 		int c, opt_index;
834 
835 		c = getopt_long(argc, argv, "fo:", opts, &opt_index);
836 		if (c == -1)
837 			break;
838 
839 		switch (c) {
840 		case OPT_TOC_ENTRY:
841 			toc_entry = &toc_entries[opt_index];
842 			toc_entry->action = DO_REMOVE;
843 			break;
844 		case 'f':
845 			fflag = 1;
846 			break;
847 		case 'o':
848 			snprintf(outfile, sizeof(outfile), "%s", optarg);
849 			break;
850 		default:
851 			remove_usage();
852 		}
853 	}
854 	argc -= optind;
855 	argv += optind;
856 
857 	if (argc == 0)
858 		remove_usage();
859 
860 	if (outfile[0] != '\0' && access(outfile, F_OK) == 0 && !fflag)
861 		log_errx("File %s already exists, use --force to overwrite it",
862 		    outfile);
863 
864 	if (outfile[0] == '\0')
865 		snprintf(outfile, sizeof(outfile), "%s", argv[0]);
866 
867 	parse_fip(argv[0], &toc_header);
868 
869 	for (toc_entry = toc_entries;
870 	     toc_entry->cmdline_name != NULL;
871 	     toc_entry++) {
872 		if (toc_entry->action != DO_REMOVE)
873 			continue;
874 		if (toc_entry->image != NULL) {
875 			if (verbose)
876 				log_dbgx("Removing %s.bin",
877 				    toc_entry->cmdline_name);
878 			remove_image(toc_entry->image);
879 		} else {
880 			log_warnx("Requested image %s.bin is not in %s",
881 			    toc_entry->cmdline_name, argv[0]);
882 		}
883 	}
884 
885 	pack_images(outfile, toc_header.flags);
886 	free_images();
887 	return 0;
888 }
889 
890 static void remove_usage(void)
891 {
892 	toc_entry_t *toc_entry = toc_entries;
893 
894 	printf("fiptool remove [--force] [--out FIP_FILENAME] [opts] FIP_FILENAME\n");
895 	printf("  --force\t\tIf the output FIP file already exists, use --force to "
896 	    "overwrite it.\n");
897 	printf("  --out FIP_FILENAME\tSet an alternative output FIP file.\n");
898 	fputc('\n', stderr);
899 	printf("Specific images are removed with the following options:\n");
900 	for (; toc_entry->cmdline_name != NULL; toc_entry++)
901 		printf("  --%-16s\t%s\n", toc_entry->cmdline_name,
902 		    toc_entry->name);
903 	exit(1);
904 }
905 
906 static int version_cmd(int argc, char *argv[])
907 {
908 #ifdef VERSION
909 	puts(VERSION);
910 #else
911 	/* If built from fiptool directory, VERSION is not set. */
912 	puts("Unknown version");
913 #endif
914 	return 0;
915 }
916 
917 static void version_usage(void)
918 {
919 	printf("fiptool version\n");
920 	exit(1);
921 }
922 
923 static int help_cmd(int argc, char *argv[])
924 {
925 	int i;
926 
927 	if (argc < 2)
928 		usage();
929 	argc--, argv++;
930 
931 	for (i = 0; i < NELEM(cmds); i++) {
932 		if (strcmp(cmds[i].name, argv[0]) == 0 &&
933 		    cmds[i].usage != NULL)
934 			cmds[i].usage();
935 	}
936 	if (i == NELEM(cmds))
937 		printf("No help for subcommand '%s'\n", argv[0]);
938 	return 0;
939 }
940 
941 static void usage(void)
942 {
943 	printf("usage: [--verbose] fiptool <command> [<args>]\n");
944 	printf("Global options supported:\n");
945 	printf("  --verbose\tEnable verbose output for all commands.\n");
946 	fputc('\n', stderr);
947 	printf("Commands supported:\n");
948 	printf("  info\t\tList images contained in FIP.\n");
949 	printf("  create\tCreate a new FIP with the given images.\n");
950 	printf("  update\tUpdate an existing FIP with the given images.\n");
951 	printf("  unpack\tUnpack images from FIP.\n");
952 	printf("  remove\tRemove images from FIP.\n");
953 	printf("  version\tShow fiptool version.\n");
954 	printf("  help\t\tShow help for given command.\n");
955 	exit(1);
956 }
957 
958 int main(int argc, char *argv[])
959 {
960 	int i, ret = 0;
961 
962 	if (argc < 2)
963 		usage();
964 	argc--, argv++;
965 
966 	if (strcmp(argv[0], "-v") == 0 ||
967 	    strcmp(argv[0], "--verbose") == 0) {
968 		verbose = 1;
969 		argc--, argv++;
970 	}
971 
972 	for (i = 0; i < NELEM(cmds); i++) {
973 		if (strcmp(cmds[i].name, argv[0]) == 0) {
974 			ret = cmds[i].handler(argc, argv);
975 			break;
976 		}
977 	}
978 	if (i == NELEM(cmds))
979 		usage();
980 	return ret;
981 }
982