fiptool.c 24 KB
Newer Older
dp-arm's avatar
dp-arm committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
 * Copyright (c) 2016, ARM Limited and Contributors. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of ARM nor the names of its contributors may be used
 * to endorse or promote products derived from this software without specific
 * prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <sys/types.h>
#include <sys/stat.h>

#include <assert.h>
#include <errno.h>
#include <getopt.h>
#include <limits.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

45
46
#include <openssl/sha.h>

dp-arm's avatar
dp-arm committed
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include "fiptool.h"
#include "firmware_image_package.h"
#include "tbbr_config.h"

#define OPT_TOC_ENTRY 0
#define OPT_PLAT_TOC_FLAGS 1

static int info_cmd(int argc, char *argv[]);
static void info_usage(void);
static int create_cmd(int argc, char *argv[]);
static void create_usage(void);
static int update_cmd(int argc, char *argv[]);
static void update_usage(void);
static int unpack_cmd(int argc, char *argv[]);
static void unpack_usage(void);
static int remove_cmd(int argc, char *argv[]);
static void remove_usage(void);
static int version_cmd(int argc, char *argv[]);
static void version_usage(void);
static int help_cmd(int argc, char *argv[]);
static void usage(void);

/* Available subcommands. */
static cmd_t cmds[] = {
	{ .name = "info",    .handler = info_cmd,    .usage = info_usage    },
	{ .name = "create",  .handler = create_cmd,  .usage = create_usage  },
	{ .name = "update",  .handler = update_cmd,  .usage = update_usage  },
	{ .name = "unpack",  .handler = unpack_cmd,  .usage = unpack_usage  },
	{ .name = "remove",  .handler = remove_cmd,  .usage = remove_usage  },
	{ .name = "version", .handler = version_cmd, .usage = version_usage },
	{ .name = "help",    .handler = help_cmd,    .usage = NULL          },
};

static image_t *images[MAX_IMAGES];
static size_t nr_images;
static uuid_t uuid_null = { 0 };
static int verbose;

85
static void vlog(int prio, const char *msg, va_list ap)
dp-arm's avatar
dp-arm committed
86
87
88
89
90
91
92
93
{
	char *prefix[] = { "DEBUG", "WARN", "ERROR" };

	fprintf(stderr, "%s: ", prefix[prio]);
	vfprintf(stderr, msg, ap);
	fputc('\n', stderr);
}

94
static void log_dbgx(const char *msg, ...)
dp-arm's avatar
dp-arm committed
95
96
97
98
99
100
101
102
{
	va_list ap;

	va_start(ap, msg);
	vlog(LOG_DBG, msg, ap);
	va_end(ap);
}

103
static void log_warnx(const char *msg, ...)
dp-arm's avatar
dp-arm committed
104
105
106
107
108
109
110
111
{
	va_list ap;

	va_start(ap, msg);
	vlog(LOG_WARN, msg, ap);
	va_end(ap);
}

112
static void log_err(const char *msg, ...)
dp-arm's avatar
dp-arm committed
113
114
115
116
117
118
119
120
121
122
123
{
	char buf[512];
	va_list ap;

	va_start(ap, msg);
	snprintf(buf, sizeof(buf), "%s: %s", msg, strerror(errno));
	vlog(LOG_ERR, buf, ap);
	va_end(ap);
	exit(1);
}

124
static void log_errx(const char *msg, ...)
dp-arm's avatar
dp-arm committed
125
126
127
128
129
130
131
132
133
{
	va_list ap;

	va_start(ap, msg);
	vlog(LOG_ERR, msg, ap);
	va_end(ap);
	exit(1);
}

134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
static char *xstrdup(const char *s, const char *msg)
{
	char *d;

	d = strdup(s);
	if (d == NULL)
		log_errx("strdup: ", msg);
	return d;
}

static void *xmalloc(size_t size, const char *msg)
{
	void *d;

	d = malloc(size);
	if (d == NULL)
		log_errx("malloc: ", msg);
	return d;
}

dp-arm's avatar
dp-arm committed
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
static void add_image(image_t *image)
{
	if (nr_images + 1 > MAX_IMAGES)
		log_errx("Too many images");
	images[nr_images++] = image;
}

static void free_image(image_t *image)
{
	free(image->buffer);
	free(image);
}

static void replace_image(image_t *image_dst, image_t *image_src)
{
	int i;

	for (i = 0; i < nr_images; i++) {
		if (images[i] == image_dst) {
			free_image(images[i]);
			images[i] = image_src;
			break;
		}
	}
	assert(i != nr_images);
}

static void remove_image(image_t *image)
{
	int i;

	for (i = 0; i < nr_images; i++) {
		if (images[i] == image) {
			free_image(images[i]);
			images[i] = NULL;
			break;
		}
	}
	assert(i != nr_images);

	/* Compact array. */
	memmove(&images[i], &images[i + 1],
	    (nr_images - i - 1) * sizeof(*images));
	nr_images--;
}

static void free_images(void)
{
	int i;

	for (i = 0; i < nr_images; i++) {
		free_image(images[i]);
		images[i] = NULL;
	}
}

210
static toc_entry_t *lookup_entry_from_uuid(uuid_t *uuid)
dp-arm's avatar
dp-arm committed
211
212
213
214
215
216
217
218
219
{
	toc_entry_t *toc_entry = toc_entries;

	for (; toc_entry->cmdline_name != NULL; toc_entry++)
		if (memcmp(&toc_entry->uuid, uuid, sizeof(uuid_t)) == 0)
			return toc_entry;
	return NULL;
}

220
221
222
223
224
225
226
227
228
229
230
231
232
static image_t *lookup_image_from_uuid(uuid_t *uuid)
{
	image_t *image;
	int i;

	for (i = 0; i < nr_images; i++) {
		image = images[i];
		if (memcmp(&image->uuid, uuid, sizeof(uuid_t)) == 0)
			return image;
	}
	return NULL;
}

233
static int parse_fip(const char *filename, fip_toc_header_t *toc_header_out)
dp-arm's avatar
dp-arm committed
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
{
	struct stat st;
	FILE *fp;
	char *buf, *bufend;
	fip_toc_header_t *toc_header;
	fip_toc_entry_t *toc_entry;
	image_t *image;
	int terminated = 0;

	fp = fopen(filename, "r");
	if (fp == NULL)
		log_err("fopen %s", filename);

	if (fstat(fileno(fp), &st) == -1)
		log_err("fstat %s", filename);

250
	buf = xmalloc(st.st_size, "failed to load file into memory");
dp-arm's avatar
dp-arm committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
	if (fread(buf, 1, st.st_size, fp) != st.st_size)
		log_errx("Failed to read %s", filename);
	bufend = buf + st.st_size;
	fclose(fp);

	if (st.st_size < sizeof(fip_toc_header_t))
		log_errx("FIP %s is truncated", filename);

	toc_header = (fip_toc_header_t *)buf;
	toc_entry = (fip_toc_entry_t *)(toc_header + 1);

	if (toc_header->name != TOC_HEADER_NAME)
		log_errx("%s is not a FIP file", filename);

	/* Return the ToC header if the caller wants it. */
	if (toc_header_out != NULL)
		*toc_header_out = *toc_header;

	/* Walk through each ToC entry in the file. */
	while ((char *)toc_entry + sizeof(*toc_entry) - 1 < bufend) {
		/* Found the ToC terminator, we are done. */
		if (memcmp(&toc_entry->uuid, &uuid_null, sizeof(uuid_t)) == 0) {
			terminated = 1;
			break;
		}

		/*
		 * Build a new image out of the ToC entry and add it to the
		 * table of images.
		 */
281
282
		image = xmalloc(sizeof(*image),
		    "failed to allocate memory for image");
dp-arm's avatar
dp-arm committed
283
		memcpy(&image->uuid, &toc_entry->uuid, sizeof(uuid_t));
284
285
		image->buffer = xmalloc(toc_entry->size,
		    "failed to allocate image buffer, is FIP file corrupted?");
dp-arm's avatar
dp-arm committed
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
		/* Overflow checks before memory copy. */
		if (toc_entry->size > (uint64_t)-1 - toc_entry->offset_address)
			log_errx("FIP %s is corrupted", filename);
		if (toc_entry->size + toc_entry->offset_address > st.st_size)
			log_errx("FIP %s is corrupted", filename);

		memcpy(image->buffer, buf + toc_entry->offset_address,
		    toc_entry->size);
		image->size = toc_entry->size;

		add_image(image);

		toc_entry++;
	}

	if (terminated == 0)
		log_errx("FIP %s does not have a ToC terminator entry",
		    filename);
	free(buf);
	return 0;
}

308
static image_t *read_image_from_file(const uuid_t *uuid, const char *filename)
dp-arm's avatar
dp-arm committed
309
310
311
312
313
{
	struct stat st;
	image_t *image;
	FILE *fp;

314
315
	assert(uuid != NULL);

dp-arm's avatar
dp-arm committed
316
317
318
319
320
321
322
	fp = fopen(filename, "r");
	if (fp == NULL)
		log_err("fopen %s", filename);

	if (fstat(fileno(fp), &st) == -1)
		log_errx("fstat %s", filename);

323
	image = xmalloc(sizeof(*image), "failed to allocate memory for image");
324
	memcpy(&image->uuid, uuid, sizeof(uuid_t));
325
	image->buffer = xmalloc(st.st_size, "failed to allocate image buffer");
dp-arm's avatar
dp-arm committed
326
327
328
329
330
331
332
333
	if (fread(image->buffer, 1, st.st_size, fp) != st.st_size)
		log_errx("Failed to read %s", filename);
	image->size = st.st_size;

	fclose(fp);
	return image;
}

334
static int write_image_to_file(const image_t *image, const char *filename)
dp-arm's avatar
dp-arm committed
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
{
	FILE *fp;

	fp = fopen(filename, "w");
	if (fp == NULL)
		log_err("fopen");
	if (fwrite(image->buffer, 1, image->size, fp) != image->size)
		log_errx("Failed to write %s", filename);
	fclose(fp);
	return 0;
}

static int fill_common_opts(struct option *opts, int has_arg)
{
	int i;

	for (i = 0; toc_entries[i].cmdline_name != NULL; i++) {
		opts[i].name = toc_entries[i].cmdline_name;
		opts[i].has_arg = has_arg;
		opts[i].flag = NULL;
		opts[i].val = 0;
	}
	return i;
}

static void add_opt(struct option *opts, int idx, char *name,
    int has_arg, int val)
{
	opts[idx].name = name;
	opts[idx].has_arg = has_arg;
	opts[idx].flag = NULL;
	opts[idx].val = val;
}

369
370
371
372
373
374
375
376
static void md_print(unsigned char *md, size_t len)
{
	size_t i;

	for (i = 0; i < len; i++)
		printf("%02x", md[i]);
}

dp-arm's avatar
dp-arm committed
377
378
379
380
381
382
383
384
385
static int info_cmd(int argc, char *argv[])
{
	image_t *image;
	uint64_t image_offset;
	uint64_t image_size = 0;
	fip_toc_header_t toc_header;
	int i;

	if (argc != 2)
386
		info_usage();
dp-arm's avatar
dp-arm committed
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
	argc--, argv++;

	parse_fip(argv[0], &toc_header);

	if (verbose) {
		log_dbgx("toc_header[name]: 0x%llX",
		    (unsigned long long)toc_header.name);
		log_dbgx("toc_header[serial_number]: 0x%llX",
		    (unsigned long long)toc_header.serial_number);
		log_dbgx("toc_header[flags]: 0x%llX",
		    (unsigned long long)toc_header.flags);
	}

	image_offset = sizeof(fip_toc_header_t) +
	    (sizeof(fip_toc_entry_t) * (nr_images + 1));

	for (i = 0; i < nr_images; i++) {
404
405
		toc_entry_t *toc_entry;

dp-arm's avatar
dp-arm committed
406
		image = images[i];
407
408
409
		toc_entry = lookup_entry_from_uuid(&image->uuid);
		if (toc_entry != NULL)
			printf("%s: ", toc_entry->name);
dp-arm's avatar
dp-arm committed
410
411
412
413
414
415
		else
			printf("Unknown entry: ");
		image_size = image->size;
		printf("offset=0x%llX, size=0x%llX",
		    (unsigned long long)image_offset,
		    (unsigned long long)image_size);
416
		if (toc_entry != NULL)
417
			printf(", cmdline=\"--%s\"",
418
			    toc_entry->cmdline_name);
419
420
421
422
423
424
425
426
		if (verbose) {
			unsigned char md[SHA256_DIGEST_LENGTH];

			SHA256(image->buffer, image_size, md);
			printf(", sha256=");
			md_print(md, sizeof(md));
		}
		putchar('\n');
dp-arm's avatar
dp-arm committed
427
428
429
430
431
432
433
434
435
436
		image_offset += image_size;
	}

	free_images();
	return 0;
}

static void info_usage(void)
{
	printf("fiptool info FIP_FILENAME\n");
437
	exit(1);
dp-arm's avatar
dp-arm committed
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
}

static int pack_images(char *filename, uint64_t toc_flags)
{
	FILE *fp;
	image_t *image;
	fip_toc_header_t *toc_header;
	fip_toc_entry_t *toc_entry;
	char *buf;
	uint64_t entry_offset, buf_size, payload_size;
	int i;

	/* Calculate total payload size and allocate scratch buffer. */
	payload_size = 0;
	for (i = 0; i < nr_images; i++)
		payload_size += images[i]->size;

	buf_size = sizeof(fip_toc_header_t) +
	    sizeof(fip_toc_entry_t) * (nr_images + 1);
	buf = calloc(1, buf_size);
	if (buf == NULL)
		log_err("calloc");

	/* Build up header and ToC entries from the image table. */
	toc_header = (fip_toc_header_t *)buf;
	toc_header->name = TOC_HEADER_NAME;
	toc_header->serial_number = TOC_HEADER_SERIAL_NUMBER;
	toc_header->flags = toc_flags;

	toc_entry = (fip_toc_entry_t *)(toc_header + 1);

	entry_offset = buf_size;
	for (i = 0; i < nr_images; i++) {
		image = images[i];
		memcpy(&toc_entry->uuid, &image->uuid, sizeof(uuid_t));
		toc_entry->offset_address = entry_offset;
		toc_entry->size = image->size;
		toc_entry->flags = 0;
		entry_offset += toc_entry->size;
		toc_entry++;
	}

	/* Append a null uuid entry to mark the end of ToC entries. */
	memcpy(&toc_entry->uuid, &uuid_null, sizeof(uuid_t));
	toc_entry->offset_address = entry_offset;
	toc_entry->size = 0;
	toc_entry->flags = 0;

	/* Generate the FIP file. */
	fp = fopen(filename, "w");
	if (fp == NULL)
		log_err("fopen %s", filename);

	if (verbose)
		log_dbgx("Metadata size: %zu bytes", buf_size);

	if (fwrite(buf, 1, buf_size, fp) != buf_size)
		log_errx("Failed to write image to %s", filename);
	free(buf);

	if (verbose)
		log_dbgx("Payload size: %zu bytes", payload_size);

	for (i = 0; i < nr_images; i++) {
		image = images[i];
		if (fwrite(image->buffer, 1, image->size, fp) != image->size)
			log_errx("Failed to write image to %s", filename);
	}

	fclose(fp);
	return 0;
}

/*
 * This function is shared between the create and update subcommands.
 * The difference between the two subcommands is that when the FIP file
 * is created, the parsing of an existing FIP is skipped.  This results
 * in update_fip() creating the new FIP file from scratch because the
 * internal image table is not populated.
 */
static void update_fip(void)
{
	toc_entry_t *toc_entry;
521
	image_t *new_image, *old_image;
dp-arm's avatar
dp-arm committed
522
523
524
525
526
527
528
529

	/* Add or replace images in the FIP file. */
	for (toc_entry = toc_entries;
	     toc_entry->cmdline_name != NULL;
	     toc_entry++) {
		if (toc_entry->action != DO_PACK)
			continue;

530
531
532
533
		new_image = read_image_from_file(&toc_entry->uuid,
		    toc_entry->action_arg);
		old_image = lookup_image_from_uuid(&toc_entry->uuid);
		if (old_image != NULL) {
dp-arm's avatar
dp-arm committed
534
535
536
537
			if (verbose)
				log_dbgx("Replacing image %s.bin with %s",
				    toc_entry->cmdline_name,
				    toc_entry->action_arg);
538
			replace_image(old_image, new_image);
dp-arm's avatar
dp-arm committed
539
540
541
542
		} else {
			if (verbose)
				log_dbgx("Adding image %s",
				    toc_entry->action_arg);
543
			add_image(new_image);
dp-arm's avatar
dp-arm committed
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
		}

		free(toc_entry->action_arg);
		toc_entry->action_arg = NULL;
	}
}

static void parse_plat_toc_flags(char *arg, unsigned long long *toc_flags)
{
	unsigned long long flags;
	char *endptr;

	errno = 0;
	flags = strtoull(arg, &endptr, 16);
	if (*endptr != '\0' || flags > UINT16_MAX || errno != 0)
		log_errx("Invalid platform ToC flags: %s", arg);
	/* Platform ToC flags is a 16-bit field occupying bits [32-47]. */
	*toc_flags |= flags << 32;
}

static int create_cmd(int argc, char *argv[])
{
	struct option opts[toc_entries_len + 1];
	unsigned long long toc_flags = 0;
	int i;

	if (argc < 2)
571
		create_usage();
dp-arm's avatar
dp-arm committed
572
573
574
575
576
577
578

	i = fill_common_opts(opts, required_argument);
	add_opt(opts, i, "plat-toc-flags", required_argument,
	    OPT_PLAT_TOC_FLAGS);
	add_opt(opts, ++i, NULL, 0, 0);

	while (1) {
579
		int c, opt_index = 0;
dp-arm's avatar
dp-arm committed
580

581
		c = getopt_long(argc, argv, "", opts, &opt_index);
dp-arm's avatar
dp-arm committed
582
583
584
585
586
587
588
589
590
		if (c == -1)
			break;

		switch (c) {
		case OPT_TOC_ENTRY: {
			toc_entry_t *toc_entry;

			toc_entry = &toc_entries[opt_index];
			toc_entry->action = DO_PACK;
591
592
			toc_entry->action_arg = xstrdup(optarg,
			    "failed to allocate memory for argument");
dp-arm's avatar
dp-arm committed
593
594
595
596
597
598
			break;
		}
		case OPT_PLAT_TOC_FLAGS:
			parse_plat_toc_flags(optarg, &toc_flags);
			break;
		default:
599
			create_usage();
dp-arm's avatar
dp-arm committed
600
601
602
603
604
605
		}
	}
	argc -= optind;
	argv += optind;

	if (argc == 0)
606
		create_usage();
dp-arm's avatar
dp-arm committed
607
608
609
610
611
612
613
614
615
616
617
618

	update_fip();

	pack_images(argv[0], toc_flags);
	free_images();
	return 0;
}

static void create_usage(void)
{
	toc_entry_t *toc_entry = toc_entries;

619
	printf("fiptool create [--plat-toc-flags <value>] [opts] FIP_FILENAME\n");
dp-arm's avatar
dp-arm committed
620
621
622
623
624
625
626
	printf("  --plat-toc-flags <value>\t16-bit platform specific flag field "
	    "occupying bits 32-47 in 64-bit ToC header.\n");
	fputc('\n', stderr);
	printf("Specific images are packed with the following options:\n");
	for (; toc_entry->cmdline_name != NULL; toc_entry++)
		printf("  --%-16s FILENAME\t%s\n", toc_entry->cmdline_name,
		    toc_entry->name);
627
	exit(1);
dp-arm's avatar
dp-arm committed
628
629
630
631
632
633
634
635
636
637
638
639
}

static int update_cmd(int argc, char *argv[])
{
	struct option opts[toc_entries_len + 2];
	char outfile[FILENAME_MAX] = { 0 };
	fip_toc_header_t toc_header = { 0 };
	unsigned long long toc_flags = 0;
	int pflag = 0;
	int i;

	if (argc < 2)
640
		update_usage();
dp-arm's avatar
dp-arm committed
641
642
643
644
645
646
647
648

	i = fill_common_opts(opts, required_argument);
	add_opt(opts, i, "out", required_argument, 'o');
	add_opt(opts, ++i, "plat-toc-flags", required_argument,
	    OPT_PLAT_TOC_FLAGS);
	add_opt(opts, ++i, NULL, 0, 0);

	while (1) {
649
		int c, opt_index = 0;
dp-arm's avatar
dp-arm committed
650
651
652
653
654
655
656
657
658
659
660

		c = getopt_long(argc, argv, "o:", opts, &opt_index);
		if (c == -1)
			break;

		switch (c) {
		case OPT_TOC_ENTRY: {
			toc_entry_t *toc_entry;

			toc_entry = &toc_entries[opt_index];
			toc_entry->action = DO_PACK;
661
662
			toc_entry->action_arg = xstrdup(optarg,
			    "failed to allocate memory for argument");
dp-arm's avatar
dp-arm committed
663
664
665
666
667
668
669
670
671
672
673
			break;
		}
		case OPT_PLAT_TOC_FLAGS: {
			parse_plat_toc_flags(optarg, &toc_flags);
			pflag = 1;
			break;
		}
		case 'o':
			snprintf(outfile, sizeof(outfile), "%s", optarg);
			break;
		default:
674
			update_usage();
dp-arm's avatar
dp-arm committed
675
676
677
678
679
680
		}
	}
	argc -= optind;
	argv += optind;

	if (argc == 0)
681
		update_usage();
dp-arm's avatar
dp-arm committed
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703

	if (outfile[0] == '\0')
		snprintf(outfile, sizeof(outfile), "%s", argv[0]);

	if (access(outfile, F_OK) == 0)
		parse_fip(argv[0], &toc_header);

	if (pflag)
		toc_header.flags &= ~(0xffffULL << 32);
	toc_flags = (toc_header.flags |= toc_flags);

	update_fip();

	pack_images(outfile, toc_flags);
	free_images();
	return 0;
}

static void update_usage(void)
{
	toc_entry_t *toc_entry = toc_entries;

704
	printf("fiptool update [--out FIP_FILENAME] "
dp-arm's avatar
dp-arm committed
705
706
707
708
709
710
711
712
713
	    "[--plat-toc-flags <value>] [opts] FIP_FILENAME\n");
	printf("  --out FIP_FILENAME\t\tSet an alternative output FIP file.\n");
	printf("  --plat-toc-flags <value>\t16-bit platform specific flag field "
	    "occupying bits 32-47 in 64-bit ToC header.\n");
	fputc('\n', stderr);
	printf("Specific images are packed with the following options:\n");
	for (; toc_entry->cmdline_name != NULL; toc_entry++)
		printf("  --%-16s FILENAME\t%s\n", toc_entry->cmdline_name,
		    toc_entry->name);
714
	exit(1);
dp-arm's avatar
dp-arm committed
715
716
717
718
719
720
721
722
723
724
725
726
}

static int unpack_cmd(int argc, char *argv[])
{
	struct option opts[toc_entries_len + 3];
	char file[FILENAME_MAX], outdir[PATH_MAX] = { 0 };
	toc_entry_t *toc_entry;
	int fflag = 0;
	int unpack_all = 1;
	int i;

	if (argc < 2)
727
		unpack_usage();
dp-arm's avatar
dp-arm committed
728
729
730
731
732
733
734

	i = fill_common_opts(opts, required_argument);
	add_opt(opts, i, "force", no_argument, 'f');
	add_opt(opts, ++i, "out", required_argument, 'o');
	add_opt(opts, ++i, NULL, 0, 0);

	while (1) {
735
		int c, opt_index = 0;
dp-arm's avatar
dp-arm committed
736
737
738
739
740
741
742
743
744
745

		c = getopt_long(argc, argv, "fo:", opts, &opt_index);
		if (c == -1)
			break;

		switch (c) {
		case OPT_TOC_ENTRY:
			unpack_all = 0;
			toc_entry = &toc_entries[opt_index];
			toc_entry->action = DO_UNPACK;
746
747
			toc_entry->action_arg = xstrdup(optarg,
			    "failed to allocate memory for argument");
dp-arm's avatar
dp-arm committed
748
749
750
751
752
753
754
755
			break;
		case 'f':
			fflag = 1;
			break;
		case 'o':
			snprintf(outdir, sizeof(outdir), "%s", optarg);
			break;
		default:
756
			unpack_usage();
dp-arm's avatar
dp-arm committed
757
758
759
760
761
762
		}
	}
	argc -= optind;
	argv += optind;

	if (argc == 0)
763
		unpack_usage();
dp-arm's avatar
dp-arm committed
764
765
766
767
768
769
770
771
772
773
774

	parse_fip(argv[0], NULL);

	if (outdir[0] != '\0')
		if (chdir(outdir) == -1)
			log_err("chdir %s", outdir);

	/* Unpack all specified images. */
	for (toc_entry = toc_entries;
	     toc_entry->cmdline_name != NULL;
	     toc_entry++) {
775
776
777
		image_t *image;

		if (!unpack_all && toc_entry->action != DO_UNPACK)
dp-arm's avatar
dp-arm committed
778
779
780
781
782
783
784
785
786
787
			continue;

		/* Build filename. */
		if (toc_entry->action_arg == NULL)
			snprintf(file, sizeof(file), "%s.bin",
			    toc_entry->cmdline_name);
		else
			snprintf(file, sizeof(file), "%s",
			    toc_entry->action_arg);

788
789
790
791
792
		image = lookup_image_from_uuid(&toc_entry->uuid);
		if (image == NULL) {
			if (!unpack_all)
				log_warnx("Requested image %s is not in %s",
				    file, argv[0]);
dp-arm's avatar
dp-arm committed
793
794
795
796
797
798
799
800
			free(toc_entry->action_arg);
			toc_entry->action_arg = NULL;
			continue;
		}

		if (access(file, F_OK) != 0 || fflag) {
			if (verbose)
				log_dbgx("Unpacking %s", file);
801
			write_image_to_file(image, file);
dp-arm's avatar
dp-arm committed
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
		} else {
			log_warnx("File %s already exists, use --force to overwrite it",
			    file);
		}

		free(toc_entry->action_arg);
		toc_entry->action_arg = NULL;
	}

	free_images();
	return 0;
}

static void unpack_usage(void)
{
	toc_entry_t *toc_entry = toc_entries;

	printf("fiptool unpack [--force] [--out <path>] [opts] FIP_FILENAME\n");
	printf("  --force\tIf the output file already exists, use --force to "
	    "overwrite it.\n");
	printf("  --out path\tSet the output directory path.\n");
	fputc('\n', stderr);
	printf("Specific images are unpacked with the following options:\n");
	for (; toc_entry->cmdline_name != NULL; toc_entry++)
		printf("  --%-16s FILENAME\t%s\n", toc_entry->cmdline_name,
		    toc_entry->name);
	fputc('\n', stderr);
	printf("If no options are provided, all images will be unpacked.\n");
830
	exit(1);
dp-arm's avatar
dp-arm committed
831
832
833
834
835
836
837
838
839
840
841
842
}

static int remove_cmd(int argc, char *argv[])
{
	struct option opts[toc_entries_len + 2];
	char outfile[FILENAME_MAX] = { 0 };
	fip_toc_header_t toc_header;
	toc_entry_t *toc_entry;
	int fflag = 0;
	int i;

	if (argc < 2)
843
		remove_usage();
dp-arm's avatar
dp-arm committed
844
845
846
847
848
849
850

	i = fill_common_opts(opts, no_argument);
	add_opt(opts, i, "force", no_argument, 'f');
	add_opt(opts, ++i, "out", required_argument, 'o');
	add_opt(opts, ++i, NULL, 0, 0);

	while (1) {
851
		int c, opt_index = 0;
dp-arm's avatar
dp-arm committed
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868

		c = getopt_long(argc, argv, "fo:", opts, &opt_index);
		if (c == -1)
			break;

		switch (c) {
		case OPT_TOC_ENTRY:
			toc_entry = &toc_entries[opt_index];
			toc_entry->action = DO_REMOVE;
			break;
		case 'f':
			fflag = 1;
			break;
		case 'o':
			snprintf(outfile, sizeof(outfile), "%s", optarg);
			break;
		default:
869
			remove_usage();
dp-arm's avatar
dp-arm committed
870
871
872
873
874
875
		}
	}
	argc -= optind;
	argv += optind;

	if (argc == 0)
876
		remove_usage();
dp-arm's avatar
dp-arm committed
877
878
879
880
881
882
883
884
885
886
887
888
889

	if (outfile[0] != '\0' && access(outfile, F_OK) == 0 && !fflag)
		log_errx("File %s already exists, use --force to overwrite it",
		    outfile);

	if (outfile[0] == '\0')
		snprintf(outfile, sizeof(outfile), "%s", argv[0]);

	parse_fip(argv[0], &toc_header);

	for (toc_entry = toc_entries;
	     toc_entry->cmdline_name != NULL;
	     toc_entry++) {
890
891
		image_t *image;

dp-arm's avatar
dp-arm committed
892
893
		if (toc_entry->action != DO_REMOVE)
			continue;
894
895
		image = lookup_image_from_uuid(&toc_entry->uuid);
		if (image != NULL) {
dp-arm's avatar
dp-arm committed
896
897
898
			if (verbose)
				log_dbgx("Removing %s.bin",
				    toc_entry->cmdline_name);
899
			remove_image(image);
dp-arm's avatar
dp-arm committed
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
		} else {
			log_warnx("Requested image %s.bin is not in %s",
			    toc_entry->cmdline_name, argv[0]);
		}
	}

	pack_images(outfile, toc_header.flags);
	free_images();
	return 0;
}

static void remove_usage(void)
{
	toc_entry_t *toc_entry = toc_entries;

	printf("fiptool remove [--force] [--out FIP_FILENAME] [opts] FIP_FILENAME\n");
	printf("  --force\t\tIf the output FIP file already exists, use --force to "
	    "overwrite it.\n");
	printf("  --out FIP_FILENAME\tSet an alternative output FIP file.\n");
	fputc('\n', stderr);
	printf("Specific images are removed with the following options:\n");
	for (; toc_entry->cmdline_name != NULL; toc_entry++)
		printf("  --%-16s\t%s\n", toc_entry->cmdline_name,
		    toc_entry->name);
924
	exit(1);
dp-arm's avatar
dp-arm committed
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
}

static int version_cmd(int argc, char *argv[])
{
#ifdef VERSION
	puts(VERSION);
#else
	/* If built from fiptool directory, VERSION is not set. */
	puts("Unknown version");
#endif
	return 0;
}

static void version_usage(void)
{
	printf("fiptool version\n");
941
	exit(1);
dp-arm's avatar
dp-arm committed
942
943
944
945
946
947
948
949
950
951
952
953
}

static int help_cmd(int argc, char *argv[])
{
	int i;

	if (argc < 2)
		usage();
	argc--, argv++;

	for (i = 0; i < NELEM(cmds); i++) {
		if (strcmp(cmds[i].name, argv[0]) == 0 &&
954
		    cmds[i].usage != NULL)
dp-arm's avatar
dp-arm committed
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
			cmds[i].usage();
	}
	if (i == NELEM(cmds))
		printf("No help for subcommand '%s'\n", argv[0]);
	return 0;
}

static void usage(void)
{
	printf("usage: [--verbose] fiptool <command> [<args>]\n");
	printf("Global options supported:\n");
	printf("  --verbose\tEnable verbose output for all commands.\n");
	fputc('\n', stderr);
	printf("Commands supported:\n");
	printf("  info\t\tList images contained in FIP.\n");
	printf("  create\tCreate a new FIP with the given images.\n");
	printf("  update\tUpdate an existing FIP with the given images.\n");
	printf("  unpack\tUnpack images from FIP.\n");
	printf("  remove\tRemove images from FIP.\n");
	printf("  version\tShow fiptool version.\n");
	printf("  help\t\tShow help for given command.\n");
	exit(1);
}

int main(int argc, char *argv[])
{
	int i, ret = 0;

983
984
985
986
987
988
989
990
991
992
993
994
995
996
	while (1) {
		int c, opt_index = 0;
		static struct option opts[] = {
			{ "verbose", no_argument, NULL, 'v' },
			{ NULL, no_argument, NULL, 0 }
		};

		/*
		 * Set POSIX mode so getopt stops at the first non-option
		 * which is the subcommand.
		 */
		c = getopt_long(argc, argv, "+v", opts, &opt_index);
		if (c == -1)
			break;
dp-arm's avatar
dp-arm committed
997

998
999
1000
1001
1002
		switch (c) {
		case 'v':
			verbose = 1;
			break;
		default:
1003
			usage();
1004
		}
dp-arm's avatar
dp-arm committed
1005
	}
1006
1007
1008
1009
1010
1011
1012
	argc -= optind;
	argv += optind;
	/* Reset optind for subsequent getopt processing. */
	optind = 0;

	if (argc == 0)
		usage();
dp-arm's avatar
dp-arm committed
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023

	for (i = 0; i < NELEM(cmds); i++) {
		if (strcmp(cmds[i].name, argv[0]) == 0) {
			ret = cmds[i].handler(argc, argv);
			break;
		}
	}
	if (i == NELEM(cmds))
		usage();
	return ret;
}