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