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