fiptool.c 31.4 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
#include "fiptool.h"
#include "firmware_image_package.h"
#include "tbbr_config.h"

#define OPT_TOC_ENTRY 0
#define OPT_PLAT_TOC_FLAGS 1
53
#define OPT_ALIGN 2
dp-arm's avatar
dp-arm committed
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

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          },
};

81
82
83
static image_desc_t *image_desc_head;
static size_t nr_image_descs;
static image_t *image_head;
dp-arm's avatar
dp-arm committed
84
85
86
87
static size_t nr_images;
static uuid_t uuid_null = { 0 };
static int verbose;

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

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

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

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

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

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

115
static void log_err(const char *msg, ...)
dp-arm's avatar
dp-arm committed
116
117
118
119
120
121
122
123
124
125
126
{
	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);
}

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

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

137
138
139
140
141
142
static char *xstrdup(const char *s, const char *msg)
{
	char *d;

	d = strdup(s);
	if (d == NULL)
143
		log_errx("strdup: %s", msg);
144
145
146
147
148
149
150
151
152
	return d;
}

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

	d = malloc(size);
	if (d == NULL)
153
		log_errx("malloc: %s", msg);
154
155
156
	return d;
}

157
158
159
160
161
static void *xzalloc(size_t size, const char *msg)
{
	return memset(xmalloc(size, msg), 0, size);
}

162
163
164
165
166
167
static void xfwrite(void *buf, size_t size, FILE *fp, const char *filename)
{
	if (fwrite(buf, 1, size, fp) != size)
		log_errx("Failed to write %s", filename);
}

168
169
static image_desc_t *new_image_desc(const uuid_t *uuid,
    const char *name, const char *cmdline_name)
dp-arm's avatar
dp-arm committed
170
{
171
172
	image_desc_t *desc;

173
	desc = xzalloc(sizeof(*desc),
174
175
176
177
178
179
180
181
	    "failed to allocate memory for image descriptor");
	memcpy(&desc->uuid, uuid, sizeof(uuid_t));
	desc->name = xstrdup(name,
	    "failed to allocate memory for image name");
	desc->cmdline_name = xstrdup(cmdline_name,
	    "failed to allocate memory for image command line name");
	desc->action = DO_UNSPEC;
	return desc;
dp-arm's avatar
dp-arm committed
182
183
}

184
185
186
187
188
189
190
191
192
193
194
195
196
197
static void set_image_desc_action(image_desc_t *desc, int action,
    const char *arg)
{
	assert(desc != NULL);

	if (desc->action_arg != DO_UNSPEC)
		free(desc->action_arg);
	desc->action = action;
	desc->action_arg = NULL;
	if (arg != NULL)
		desc->action_arg = xstrdup(arg,
		    "failed to allocate memory for argument");
}

198
static void free_image_desc(image_desc_t *desc)
dp-arm's avatar
dp-arm committed
199
{
200
201
202
203
	free(desc->name);
	free(desc->cmdline_name);
	free(desc->action_arg);
	free(desc);
dp-arm's avatar
dp-arm committed
204
205
}

206
static void add_image_desc(image_desc_t *desc)
dp-arm's avatar
dp-arm committed
207
{
208
209
210
211
212
	image_desc_t **p = &image_desc_head;

	while (*p)
		p = &(*p)->next;

213
	assert(*p == NULL);
214
	*p = desc;
215
216
	nr_image_descs++;
}
dp-arm's avatar
dp-arm committed
217

218
219
220
221
222
223
224
225
226
static void free_image_descs(void)
{
	image_desc_t *desc = image_desc_head, *tmp;

	while (desc != NULL) {
		tmp = desc->next;
		free_image_desc(desc);
		desc = tmp;
		nr_image_descs--;
dp-arm's avatar
dp-arm committed
227
	}
228
	assert(nr_image_descs == 0);
dp-arm's avatar
dp-arm committed
229
230
}

231
static void fill_image_descs(void)
dp-arm's avatar
dp-arm committed
232
{
233
	toc_entry_t *toc_entry;
dp-arm's avatar
dp-arm committed
234

235
236
237
238
239
240
241
242
243
	for (toc_entry = toc_entries;
	     toc_entry->cmdline_name != NULL;
	     toc_entry++) {
		image_desc_t *desc;

		desc = new_image_desc(&toc_entry->uuid,
		    toc_entry->name,
		    toc_entry->cmdline_name);
		add_image_desc(desc);
dp-arm's avatar
dp-arm committed
244
	}
245
}
dp-arm's avatar
dp-arm committed
246

247
248
static void add_image(image_t *image)
{
249
250
251
252
253
	image_t **p = &image_head;

	while (*p)
		p = &(*p)->next;

254
	assert(*p == NULL);
255
256
	*p = image;

257
258
259
	nr_images++;
}

260
261
262
263
264
static void replace_image(image_t *image)
{
	image_t **p = &image_head;

	while (*p) {
265
266
		if (!memcmp(&(*p)->toc_e.uuid, &image->toc_e.uuid,
			    sizeof(image->toc_e.uuid)))
267
268
269
270
271
272
273
274
275
276
			break;
		p = &(*p)->next;
	}

	assert(*p != NULL);

	image->next = (*p)->next;
	*p = image;
}

277
278
279
280
281
282
283
284
static void free_image(image_t *image)
{
	free(image->buffer);
	free(image);
}

static void remove_image(image_t *image)
{
285
286
287
288
289
290
	image_t *tmp, **p = &image_head;

	while (*p) {
		if (*p == image)
			break;
		p = &(*p)->next;
291
	}
292
293
294
295
296
297
298

	assert(*p != NULL);

	tmp = *p;
	*p = tmp->next;
	free_image(tmp);

dp-arm's avatar
dp-arm committed
299
300
301
302
303
	nr_images--;
}

static void free_images(void)
{
304
	image_t *image = image_head, *tmp;
dp-arm's avatar
dp-arm committed
305

306
307
308
309
310
	while (image != NULL) {
		tmp = image->next;
		free_image(image);
		image = tmp;
		nr_images--;
dp-arm's avatar
dp-arm committed
311
	}
312
	assert(nr_images == 0);
dp-arm's avatar
dp-arm committed
313
314
}

315
static image_desc_t *lookup_image_desc_from_uuid(const uuid_t *uuid)
dp-arm's avatar
dp-arm committed
316
{
317
	image_desc_t *desc;
dp-arm's avatar
dp-arm committed
318

319
320
321
322
323
324
325
326
327
328
329
330
331
	for (desc = image_desc_head; desc != NULL; desc = desc->next)
		if (memcmp(&desc->uuid, uuid, sizeof(uuid_t)) == 0)
			return desc;
	return NULL;
}

static image_desc_t *lookup_image_desc_from_opt(const char *opt)
{
	image_desc_t *desc;

	for (desc = image_desc_head; desc != NULL; desc = desc->next)
		if (strcmp(desc->cmdline_name, opt) == 0)
			return desc;
dp-arm's avatar
dp-arm committed
332
333
334
	return NULL;
}

335
static image_t *lookup_image_from_uuid(const uuid_t *uuid)
336
337
338
{
	image_t *image;

339
	for (image = image_head; image != NULL; image = image->next)
340
		if (!memcmp(&image->toc_e.uuid, uuid, sizeof(*uuid)))
341
342
343
344
			return image;
	return NULL;
}

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
static void uuid_to_str(char *s, size_t len, const uuid_t *u)
{
	assert(len >= (_UUID_STR_LEN + 1));

	snprintf(s, len, "%08X-%04X-%04X-%04X-%04X%04X%04X",
	    u->time_low,
	    u->time_mid,
	    u->time_hi_and_version,
	    ((uint16_t)u->clock_seq_hi_and_reserved << 8) | u->clock_seq_low,
	    ((uint16_t)u->node[0] << 8) | u->node[1],
	    ((uint16_t)u->node[2] << 8) | u->node[3],
	    ((uint16_t)u->node[4] << 8) | u->node[5]);
}

static void uuid_from_str(uuid_t *u, const char *s)
{
	int n;

	if (s == NULL)
		log_errx("UUID cannot be NULL");
	if (strlen(s) != _UUID_STR_LEN)
		log_errx("Invalid UUID: %s", s);

	n = sscanf(s,
	    "%8x-%4hx-%4hx-%2hhx%2hhx-%2hhx%2hhx%2hhx%2hhx%2hhx%2hhx",
	    &u->time_low, &u->time_mid, &u->time_hi_and_version,
	    &u->clock_seq_hi_and_reserved, &u->clock_seq_low, &u->node[0],
	    &u->node[1], &u->node[2], &u->node[3], &u->node[4], &u->node[5]);
	/*
	 * Given the format specifier above, we expect 11 items to be scanned
	 * for a properly formatted UUID.
	 */
	if (n != 11)
		log_errx("Invalid UUID: %s", s);
}

381
static int parse_fip(const char *filename, fip_toc_header_t *toc_header_out)
dp-arm's avatar
dp-arm committed
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
{
	struct stat st;
	FILE *fp;
	char *buf, *bufend;
	fip_toc_header_t *toc_header;
	fip_toc_entry_t *toc_entry;
	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);

397
	buf = xmalloc(st.st_size, "failed to load file into memory");
dp-arm's avatar
dp-arm committed
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
	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) {
418
419
420
		image_t *image;
		image_desc_t *desc;

dp-arm's avatar
dp-arm committed
421
422
423
424
425
426
427
428
429
430
		/* 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.
		 */
431
		image = xzalloc(sizeof(*image),
432
		    "failed to allocate memory for image");
433
		image->toc_e = *toc_entry;
434
435
		image->buffer = xmalloc(toc_entry->size,
		    "failed to allocate image buffer, is FIP file corrupted?");
dp-arm's avatar
dp-arm committed
436
437
438
439
440
441
442
443
444
		/* 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);

445
		/* If this is an unknown image, create a descriptor for it. */
446
		desc = lookup_image_desc_from_uuid(&toc_entry->uuid);
447
448
449
		if (desc == NULL) {
			char name[_UUID_STR_LEN + 1], filename[PATH_MAX];

450
			uuid_to_str(name, sizeof(name), &toc_entry->uuid);
451
452
			snprintf(filename, sizeof(filename), "%s%s",
			    name, ".bin");
453
			desc = new_image_desc(&toc_entry->uuid, name, "blob");
454
455
456
457
458
459
			desc->action = DO_UNPACK;
			desc->action_arg = xstrdup(filename,
			    "failed to allocate memory for blob filename");
			add_image_desc(desc);
		}

dp-arm's avatar
dp-arm committed
460
461
462
463
464
465
466
467
468
469
470
471
		add_image(image);

		toc_entry++;
	}

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

472
static image_t *read_image_from_file(const uuid_t *uuid, const char *filename)
dp-arm's avatar
dp-arm committed
473
474
475
476
477
{
	struct stat st;
	image_t *image;
	FILE *fp;

478
479
	assert(uuid != NULL);

dp-arm's avatar
dp-arm committed
480
481
482
483
484
485
486
	fp = fopen(filename, "r");
	if (fp == NULL)
		log_err("fopen %s", filename);

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

487
	image = xzalloc(sizeof(*image), "failed to allocate memory for image");
488
	image->toc_e.uuid = *uuid;
489
	image->buffer = xmalloc(st.st_size, "failed to allocate image buffer");
dp-arm's avatar
dp-arm committed
490
491
	if (fread(image->buffer, 1, st.st_size, fp) != st.st_size)
		log_errx("Failed to read %s", filename);
492
	image->toc_e.size = st.st_size;
dp-arm's avatar
dp-arm committed
493
494
495
496
497

	fclose(fp);
	return image;
}

498
static int write_image_to_file(const image_t *image, const char *filename)
dp-arm's avatar
dp-arm committed
499
500
501
502
503
504
{
	FILE *fp;

	fp = fopen(filename, "w");
	if (fp == NULL)
		log_err("fopen");
505
	xfwrite(image->buffer, image->toc_e.size, fp, filename);
dp-arm's avatar
dp-arm committed
506
507
508
509
	fclose(fp);
	return 0;
}

510
511
static struct option *add_opt(struct option *opts, size_t *nr_opts,
    const char *name, int has_arg, int val)
dp-arm's avatar
dp-arm committed
512
{
513
514
515
516
517
518
519
520
521
	opts = realloc(opts, (*nr_opts + 1) * sizeof(*opts));
	if (opts == NULL)
		log_err("realloc");
	opts[*nr_opts].name = name;
	opts[*nr_opts].has_arg = has_arg;
	opts[*nr_opts].flag = NULL;
	opts[*nr_opts].val = val;
	++*nr_opts;
	return opts;
dp-arm's avatar
dp-arm committed
522
523
}

524
525
static struct option *fill_common_opts(struct option *opts, size_t *nr_opts,
    int has_arg)
dp-arm's avatar
dp-arm committed
526
{
527
528
529
530
531
532
	image_desc_t *desc;

	for (desc = image_desc_head; desc != NULL; desc = desc->next)
		opts = add_opt(opts, nr_opts, desc->cmdline_name, has_arg,
		    OPT_TOC_ENTRY);
	return opts;
dp-arm's avatar
dp-arm committed
533
534
}

535
static void md_print(const unsigned char *md, size_t len)
536
537
538
539
540
541
542
{
	size_t i;

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

dp-arm's avatar
dp-arm committed
543
544
545
546
547
548
static int info_cmd(int argc, char *argv[])
{
	image_t *image;
	fip_toc_header_t toc_header;

	if (argc != 2)
549
		info_usage();
dp-arm's avatar
dp-arm committed
550
551
552
553
554
555
556
557
558
559
560
561
562
	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);
	}

563
564
	for (image = image_head; image != NULL; image = image->next) {
		image_desc_t *desc;
565

566
		desc = lookup_image_desc_from_uuid(&image->toc_e.uuid);
567
		assert(desc != NULL);
568
569
570
571
		printf("%s: offset=0x%llX, size=0x%llX, cmdline=\"--%s\"",
		       desc->name,
		       (unsigned long long)image->toc_e.offset_address,
		       (unsigned long long)image->toc_e.size,
572
		       desc->cmdline_name);
573
574
575
		if (verbose) {
			unsigned char md[SHA256_DIGEST_LENGTH];

576
			SHA256(image->buffer, image->toc_e.size, md);
577
578
579
580
			printf(", sha256=");
			md_print(md, sizeof(md));
		}
		putchar('\n');
dp-arm's avatar
dp-arm committed
581
582
583
584
585
586
587
588
589
	}

	free_images();
	return 0;
}

static void info_usage(void)
{
	printf("fiptool info FIP_FILENAME\n");
590
	exit(1);
dp-arm's avatar
dp-arm committed
591
592
}

593
static int pack_images(const char *filename, uint64_t toc_flags, unsigned long align)
dp-arm's avatar
dp-arm committed
594
595
596
597
598
599
{
	FILE *fp;
	image_t *image;
	fip_toc_header_t *toc_header;
	fip_toc_entry_t *toc_entry;
	char *buf;
600
	uint64_t entry_offset, buf_size, payload_size = 0;
dp-arm's avatar
dp-arm committed
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616

	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;
617
	for (image = image_head; image != NULL; image = image->next) {
618
		payload_size += image->toc_e.size;
619
		entry_offset = (entry_offset + align - 1) & ~(align - 1);
620
621
622
		image->toc_e.offset_address = entry_offset;
		*toc_entry++ = image->toc_e;
		entry_offset += image->toc_e.size;
dp-arm's avatar
dp-arm committed
623
624
625
	}

	/* Append a null uuid entry to mark the end of ToC entries. */
626
	memset(toc_entry, 0, sizeof(*toc_entry));
dp-arm's avatar
dp-arm committed
627
628
629
630
631
632
633
634
635
636
	toc_entry->offset_address = entry_offset;

	/* 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);

637
	xfwrite(buf, buf_size, fp, filename);
dp-arm's avatar
dp-arm committed
638
639
640
641
642
	free(buf);

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

643
644
645
646
	for (image = image_head; image != NULL; image = image->next) {
		if (fseek(fp, image->toc_e.offset_address, SEEK_SET))
			log_errx("Failed to set file position");

647
		xfwrite(image->buffer, image->toc_e.size, fp, filename);
648
	}
dp-arm's avatar
dp-arm committed
649
650
651
652
653
654
655
656
657
658
659
660
661
662

	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)
{
663
	image_desc_t *desc;
dp-arm's avatar
dp-arm committed
664
665

	/* Add or replace images in the FIP file. */
666
	for (desc = image_desc_head; desc != NULL; desc = desc->next) {
667
668
		image_t *new_image, *old_image;

669
		if (desc->action != DO_PACK)
dp-arm's avatar
dp-arm committed
670
671
			continue;

672
673
674
		new_image = read_image_from_file(&desc->uuid,
		    desc->action_arg);
		old_image = lookup_image_from_uuid(&desc->uuid);
675
		if (old_image != NULL) {
676
			if (verbose) {
677
				log_dbgx("Replacing %s with %s",
678
679
680
				    desc->cmdline_name,
				    desc->action_arg);
			}
681
			replace_image(new_image);
dp-arm's avatar
dp-arm committed
682
683
684
		} else {
			if (verbose)
				log_dbgx("Adding image %s",
685
				    desc->action_arg);
686
			add_image(new_image);
dp-arm's avatar
dp-arm committed
687
688
689
690
		}
	}
}

691
static void parse_plat_toc_flags(const char *arg, unsigned long long *toc_flags)
dp-arm's avatar
dp-arm committed
692
693
694
695
696
697
698
699
700
701
702
703
{
	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;
}

704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
static int is_power_of_2(unsigned long x)
{
	return x && !(x & (x - 1));
}

static unsigned long get_image_align(char *arg)
{
	char *endptr;
	unsigned long align;

	errno = 0;
	align = strtoul(arg, &endptr, 10);
	if (*endptr != '\0' || !is_power_of_2(align) || errno != 0)
		log_errx("Invalid alignment: %s", arg);

	return align;
}

722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
static void parse_blob_opt(char *arg, uuid_t *uuid, char *filename, size_t len)
{
	char *p;

	for (p = strtok(arg, ","); p != NULL; p = strtok(NULL, ",")) {
		if (strncmp(p, "uuid=", strlen("uuid=")) == 0) {
			p += strlen("uuid=");
			uuid_from_str(uuid, p);
		} else if (strncmp(p, "file=", strlen("file=")) == 0) {
			p += strlen("file=");
			snprintf(filename, len, "%s", p);
		}
	}
}

dp-arm's avatar
dp-arm committed
737
738
static int create_cmd(int argc, char *argv[])
{
739
740
	struct option *opts = NULL;
	size_t nr_opts = 0;
dp-arm's avatar
dp-arm committed
741
	unsigned long long toc_flags = 0;
742
	unsigned long align = 1;
dp-arm's avatar
dp-arm committed
743
744

	if (argc < 2)
745
		create_usage();
dp-arm's avatar
dp-arm committed
746

747
748
	opts = fill_common_opts(opts, &nr_opts, required_argument);
	opts = add_opt(opts, &nr_opts, "plat-toc-flags", required_argument,
dp-arm's avatar
dp-arm committed
749
	    OPT_PLAT_TOC_FLAGS);
750
	opts = add_opt(opts, &nr_opts, "align", required_argument, OPT_ALIGN);
751
	opts = add_opt(opts, &nr_opts, "blob", required_argument, 'b');
752
	opts = add_opt(opts, &nr_opts, NULL, 0, 0);
dp-arm's avatar
dp-arm committed
753
754

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

757
		c = getopt_long(argc, argv, "b:", opts, &opt_index);
dp-arm's avatar
dp-arm committed
758
759
760
761
762
		if (c == -1)
			break;

		switch (c) {
		case OPT_TOC_ENTRY: {
763
764
765
			image_desc_t *desc;

			desc = lookup_image_desc_from_opt(opts[opt_index].name);
766
			set_image_desc_action(desc, DO_PACK, optarg);
dp-arm's avatar
dp-arm committed
767
768
769
770
771
			break;
		}
		case OPT_PLAT_TOC_FLAGS:
			parse_plat_toc_flags(optarg, &toc_flags);
			break;
772
773
774
		case OPT_ALIGN:
			align = get_image_align(optarg);
			break;
775
776
777
778
779
780
781
782
783
784
785
786
787
788
		case 'b': {
			char name[_UUID_STR_LEN + 1];
			char filename[PATH_MAX] = { 0 };
			uuid_t uuid = { 0 };
			image_desc_t *desc;

			parse_blob_opt(optarg, &uuid,
			    filename, sizeof(filename));

			if (memcmp(&uuid, &uuid_null, sizeof(uuid_t)) == 0 ||
			    filename[0] == '\0')
				create_usage();

			desc = lookup_image_desc_from_uuid(&uuid);
789
			if (desc == NULL) {
790
791
792
793
				uuid_to_str(name, sizeof(name), &uuid);
				desc = new_image_desc(&uuid, name, "blob");
				add_image_desc(desc);
			}
794
			set_image_desc_action(desc, DO_PACK, filename);
795
796
			break;
		}
dp-arm's avatar
dp-arm committed
797
		default:
798
			create_usage();
dp-arm's avatar
dp-arm committed
799
800
801
802
		}
	}
	argc -= optind;
	argv += optind;
803
	free(opts);
dp-arm's avatar
dp-arm committed
804
805

	if (argc == 0)
806
		create_usage();
dp-arm's avatar
dp-arm committed
807
808
809

	update_fip();

810
	pack_images(argv[0], toc_flags, align);
dp-arm's avatar
dp-arm committed
811
812
813
814
815
816
817
818
	free_images();
	return 0;
}

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

819
820
821
	printf("fiptool create [opts] FIP_FILENAME\n");
	printf("\n");
	printf("Options:\n");
822
	printf("  --align <value>\t\tEach image is aligned to <value> (default: 1).\n");
823
824
	printf("  --blob uuid=...,file=...\tAdd an image with the given UUID pointed to by file.\n");
	printf("  --plat-toc-flags <value>\t16-bit platform specific flag field occupying bits 32-47 in 64-bit ToC header.\n");
825
	printf("\n");
dp-arm's avatar
dp-arm committed
826
827
828
829
	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);
830
	exit(1);
dp-arm's avatar
dp-arm committed
831
832
833
834
}

static int update_cmd(int argc, char *argv[])
{
835
836
	struct option *opts = NULL;
	size_t nr_opts = 0;
837
	char outfile[PATH_MAX] = { 0 };
dp-arm's avatar
dp-arm committed
838
839
	fip_toc_header_t toc_header = { 0 };
	unsigned long long toc_flags = 0;
840
	unsigned long align = 1;
dp-arm's avatar
dp-arm committed
841
842
843
	int pflag = 0;

	if (argc < 2)
844
		update_usage();
dp-arm's avatar
dp-arm committed
845

846
	opts = fill_common_opts(opts, &nr_opts, required_argument);
847
	opts = add_opt(opts, &nr_opts, "align", required_argument, OPT_ALIGN);
848
	opts = add_opt(opts, &nr_opts, "blob", required_argument, 'b');
849
850
	opts = add_opt(opts, &nr_opts, "out", required_argument, 'o');
	opts = add_opt(opts, &nr_opts, "plat-toc-flags", required_argument,
dp-arm's avatar
dp-arm committed
851
	    OPT_PLAT_TOC_FLAGS);
852
	opts = add_opt(opts, &nr_opts, NULL, 0, 0);
dp-arm's avatar
dp-arm committed
853
854

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

857
		c = getopt_long(argc, argv, "b:o:", opts, &opt_index);
dp-arm's avatar
dp-arm committed
858
859
860
861
862
		if (c == -1)
			break;

		switch (c) {
		case OPT_TOC_ENTRY: {
863
864
865
			image_desc_t *desc;

			desc = lookup_image_desc_from_opt(opts[opt_index].name);
866
			set_image_desc_action(desc, DO_PACK, optarg);
dp-arm's avatar
dp-arm committed
867
868
			break;
		}
869
		case OPT_PLAT_TOC_FLAGS:
dp-arm's avatar
dp-arm committed
870
871
872
			parse_plat_toc_flags(optarg, &toc_flags);
			pflag = 1;
			break;
873
874
875
876
877
878
879
880
881
882
883
884
885
886
		case 'b': {
			char name[_UUID_STR_LEN + 1];
			char filename[PATH_MAX] = { 0 };
			uuid_t uuid = { 0 };
			image_desc_t *desc;

			parse_blob_opt(optarg, &uuid,
			    filename, sizeof(filename));

			if (memcmp(&uuid, &uuid_null, sizeof(uuid_t)) == 0 ||
			    filename[0] == '\0')
				update_usage();

			desc = lookup_image_desc_from_uuid(&uuid);
887
			if (desc == NULL) {
888
889
890
891
				uuid_to_str(name, sizeof(name), &uuid);
				desc = new_image_desc(&uuid, name, "blob");
				add_image_desc(desc);
			}
892
			set_image_desc_action(desc, DO_PACK, filename);
893
894
			break;
		}
895
896
897
		case OPT_ALIGN:
			align = get_image_align(optarg);
			break;
dp-arm's avatar
dp-arm committed
898
899
900
901
		case 'o':
			snprintf(outfile, sizeof(outfile), "%s", optarg);
			break;
		default:
902
			update_usage();
dp-arm's avatar
dp-arm committed
903
904
905
906
		}
	}
	argc -= optind;
	argv += optind;
907
	free(opts);
dp-arm's avatar
dp-arm committed
908
909

	if (argc == 0)
910
		update_usage();
dp-arm's avatar
dp-arm committed
911
912
913
914

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

915
	if (access(argv[0], F_OK) == 0)
dp-arm's avatar
dp-arm committed
916
917
918
919
920
921
922
923
		parse_fip(argv[0], &toc_header);

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

	update_fip();

924
	pack_images(outfile, toc_flags, align);
dp-arm's avatar
dp-arm committed
925
926
927
928
929
930
931
932
	free_images();
	return 0;
}

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

933
934
935
	printf("fiptool update [opts] FIP_FILENAME\n");
	printf("\n");
	printf("Options:\n");
936
	printf("  --align <value>\t\tEach image is aligned to <value> (default: 1).\n");
937
	printf("  --blob uuid=...,file=...\tAdd or update an image with the given UUID pointed to by file.\n");
dp-arm's avatar
dp-arm committed
938
	printf("  --out FIP_FILENAME\t\tSet an alternative output FIP file.\n");
939
	printf("  --plat-toc-flags <value>\t16-bit platform specific flag field occupying bits 32-47 in 64-bit ToC header.\n");
940
	printf("\n");
dp-arm's avatar
dp-arm committed
941
942
943
944
	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);
945
	exit(1);
dp-arm's avatar
dp-arm committed
946
947
948
949
}

static int unpack_cmd(int argc, char *argv[])
{
950
951
	struct option *opts = NULL;
	size_t nr_opts = 0;
952
	char outdir[PATH_MAX] = { 0 };
953
	image_desc_t *desc;
dp-arm's avatar
dp-arm committed
954
955
956
957
	int fflag = 0;
	int unpack_all = 1;

	if (argc < 2)
958
		unpack_usage();
dp-arm's avatar
dp-arm committed
959

960
	opts = fill_common_opts(opts, &nr_opts, required_argument);
961
	opts = add_opt(opts, &nr_opts, "blob", required_argument, 'b');
962
963
964
	opts = add_opt(opts, &nr_opts, "force", no_argument, 'f');
	opts = add_opt(opts, &nr_opts, "out", required_argument, 'o');
	opts = add_opt(opts, &nr_opts, NULL, 0, 0);
dp-arm's avatar
dp-arm committed
965
966

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

969
		c = getopt_long(argc, argv, "b:fo:", opts, &opt_index);
dp-arm's avatar
dp-arm committed
970
971
972
973
		if (c == -1)
			break;

		switch (c) {
974
975
976
977
		case OPT_TOC_ENTRY: {
			image_desc_t *desc;

			desc = lookup_image_desc_from_opt(opts[opt_index].name);
978
			set_image_desc_action(desc, DO_UNPACK, optarg);
979
			unpack_all = 0;
dp-arm's avatar
dp-arm committed
980
			break;
981
		}
982
983
984
985
986
987
988
989
990
991
992
993
994
995
		case 'b': {
			char name[_UUID_STR_LEN + 1];
			char filename[PATH_MAX] = { 0 };
			uuid_t uuid = { 0 };
			image_desc_t *desc;

			parse_blob_opt(optarg, &uuid,
			    filename, sizeof(filename));

			if (memcmp(&uuid, &uuid_null, sizeof(uuid_t)) == 0 ||
			    filename[0] == '\0')
				unpack_usage();

			desc = lookup_image_desc_from_uuid(&uuid);
996
			if (desc == NULL) {
997
998
999
1000
				uuid_to_str(name, sizeof(name), &uuid);
				desc = new_image_desc(&uuid, name, "blob");
				add_image_desc(desc);
			}
1001
			set_image_desc_action(desc, DO_UNPACK, filename);
1002
1003
1004
			unpack_all = 0;
			break;
		}
dp-arm's avatar
dp-arm committed
1005
1006
1007
1008
1009
1010
1011
		case 'f':
			fflag = 1;
			break;
		case 'o':
			snprintf(outdir, sizeof(outdir), "%s", optarg);
			break;
		default:
1012
			unpack_usage();
dp-arm's avatar
dp-arm committed
1013
1014
1015
1016
		}
	}
	argc -= optind;
	argv += optind;
1017
	free(opts);
dp-arm's avatar
dp-arm committed
1018
1019

	if (argc == 0)
1020
		unpack_usage();
dp-arm's avatar
dp-arm committed
1021
1022
1023
1024
1025
1026
1027
1028

	parse_fip(argv[0], NULL);

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

	/* Unpack all specified images. */
1029
	for (desc = image_desc_head; desc != NULL; desc = desc->next) {
1030
		char file[PATH_MAX];
1031
1032
		image_t *image;

1033
		if (!unpack_all && desc->action != DO_UNPACK)
dp-arm's avatar
dp-arm committed
1034
1035
1036
			continue;

		/* Build filename. */
1037
		if (desc->action_arg == NULL)
dp-arm's avatar
dp-arm committed
1038
			snprintf(file, sizeof(file), "%s.bin",
1039
			    desc->cmdline_name);
dp-arm's avatar
dp-arm committed
1040
1041
		else
			snprintf(file, sizeof(file), "%s",
1042
			    desc->action_arg);
dp-arm's avatar
dp-arm committed
1043

1044
		image = lookup_image_from_uuid(&desc->uuid);
1045
1046
		if (image == NULL) {
			if (!unpack_all)
1047
				log_warnx("%s does not exist in %s",
1048
				    file, argv[0]);
dp-arm's avatar
dp-arm committed
1049
1050
1051
1052
1053
1054
			continue;
		}

		if (access(file, F_OK) != 0 || fflag) {
			if (verbose)
				log_dbgx("Unpacking %s", file);
1055
			write_image_to_file(image, file);
dp-arm's avatar
dp-arm committed
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
		} else {
			log_warnx("File %s already exists, use --force to overwrite it",
			    file);
		}
	}

	free_images();
	return 0;
}

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

1070
1071
1072
	printf("fiptool unpack [opts] FIP_FILENAME\n");
	printf("\n");
	printf("Options:\n");
1073
1074
	printf("  --blob uuid=...,file=...\tUnpack an image with the given UUID to file.\n");
	printf("  --force\t\t\tIf the output file already exists, use --force to overwrite it.\n");
1075
	printf("  --out path\t\t\tSet the output directory path.\n");
1076
	printf("\n");
dp-arm's avatar
dp-arm committed
1077
1078
1079
1080
	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);
1081
	printf("\n");
dp-arm's avatar
dp-arm committed
1082
	printf("If no options are provided, all images will be unpacked.\n");
1083
	exit(1);
dp-arm's avatar
dp-arm committed
1084
1085
1086
1087
}

static int remove_cmd(int argc, char *argv[])
{
1088
1089
	struct option *opts = NULL;
	size_t nr_opts = 0;
1090
	char outfile[PATH_MAX] = { 0 };
dp-arm's avatar
dp-arm committed
1091
	fip_toc_header_t toc_header;
1092
	image_desc_t *desc;
1093
	unsigned long align = 1;
dp-arm's avatar
dp-arm committed
1094
1095
1096
	int fflag = 0;

	if (argc < 2)
1097
		remove_usage();
dp-arm's avatar
dp-arm committed
1098

1099
	opts = fill_common_opts(opts, &nr_opts, no_argument);
1100
	opts = add_opt(opts, &nr_opts, "align", required_argument, OPT_ALIGN);
1101
	opts = add_opt(opts, &nr_opts, "blob", required_argument, 'b');
1102
1103
1104
	opts = add_opt(opts, &nr_opts, "force", no_argument, 'f');
	opts = add_opt(opts, &nr_opts, "out", required_argument, 'o');
	opts = add_opt(opts, &nr_opts, NULL, 0, 0);
dp-arm's avatar
dp-arm committed
1105
1106

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

1109
		c = getopt_long(argc, argv, "b:fo:", opts, &opt_index);
dp-arm's avatar
dp-arm committed
1110
1111
1112
1113
		if (c == -1)
			break;

		switch (c) {
1114
1115
1116
1117
		case OPT_TOC_ENTRY: {
			image_desc_t *desc;

			desc = lookup_image_desc_from_opt(opts[opt_index].name);
1118
			set_image_desc_action(desc, DO_REMOVE, NULL);
dp-arm's avatar
dp-arm committed
1119
			break;
1120
		}
1121
1122
1123
		case OPT_ALIGN:
			align = get_image_align(optarg);
			break;
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
		case 'b': {
			char name[_UUID_STR_LEN + 1], filename[PATH_MAX];
			uuid_t uuid = { 0 };
			image_desc_t *desc;

			parse_blob_opt(optarg, &uuid,
			    filename, sizeof(filename));

			if (memcmp(&uuid, &uuid_null, sizeof(uuid_t)) == 0)
				remove_usage();

			desc = lookup_image_desc_from_uuid(&uuid);
1136
			if (desc == NULL) {
1137
1138
1139
1140
				uuid_to_str(name, sizeof(name), &uuid);
				desc = new_image_desc(&uuid, name, "blob");
				add_image_desc(desc);
			}
1141
			set_image_desc_action(desc, DO_REMOVE, NULL);
1142
1143
			break;
		}
dp-arm's avatar
dp-arm committed
1144
1145
1146
1147
1148
1149
1150
		case 'f':
			fflag = 1;
			break;
		case 'o':
			snprintf(outfile, sizeof(outfile), "%s", optarg);
			break;
		default:
1151
			remove_usage();
dp-arm's avatar
dp-arm committed
1152
1153
1154
1155
		}
	}
	argc -= optind;
	argv += optind;
1156
	free(opts);
dp-arm's avatar
dp-arm committed
1157
1158

	if (argc == 0)
1159
		remove_usage();
dp-arm's avatar
dp-arm committed
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169

	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);

1170
	for (desc = image_desc_head; desc != NULL; desc = desc->next) {
1171
1172
		image_t *image;

1173
		if (desc->action != DO_REMOVE)
dp-arm's avatar
dp-arm committed
1174
			continue;
1175

1176
		image = lookup_image_from_uuid(&desc->uuid);
1177
		if (image != NULL) {
dp-arm's avatar
dp-arm committed
1178
			if (verbose)
1179
				log_dbgx("Removing %s",
1180
				    desc->cmdline_name);
1181
			remove_image(image);
dp-arm's avatar
dp-arm committed
1182
		} else {
1183
			log_warnx("%s does not exist in %s",
1184
			    desc->cmdline_name, argv[0]);
dp-arm's avatar
dp-arm committed
1185
1186
1187
		}
	}

1188
	pack_images(outfile, toc_header.flags, align);
dp-arm's avatar
dp-arm committed
1189
1190
1191
1192
1193
1194
1195
1196
	free_images();
	return 0;
}

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

1197
1198
1199
	printf("fiptool remove [opts] FIP_FILENAME\n");
	printf("\n");
	printf("Options:\n");
1200
	printf("  --align <value>\tEach image is aligned to <value> (default: 1).\n");
1201
	printf("  --blob uuid=...\tRemove an image with the given UUID.\n");
1202
	printf("  --force\t\tIf the output FIP file already exists, use --force to overwrite it.\n");
dp-arm's avatar
dp-arm committed
1203
	printf("  --out FIP_FILENAME\tSet an alternative output FIP file.\n");
1204
	printf("\n");
dp-arm's avatar
dp-arm committed
1205
1206
1207
1208
	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);
1209
	exit(1);
dp-arm's avatar
dp-arm committed
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
}

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");
1226
	exit(1);
dp-arm's avatar
dp-arm committed
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
}

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 &&
1239
		    cmds[i].usage != NULL)
dp-arm's avatar
dp-arm committed
1240
1241
1242
1243
1244
1245
1246
1247
1248
			cmds[i].usage();
	}
	if (i == NELEM(cmds))
		printf("No help for subcommand '%s'\n", argv[0]);
	return 0;
}

static void usage(void)
{
1249
	printf("usage: fiptool [--verbose] <command> [<args>]\n");
dp-arm's avatar
dp-arm committed
1250
1251
	printf("Global options supported:\n");
	printf("  --verbose\tEnable verbose output for all commands.\n");
1252
	printf("\n");
dp-arm's avatar
dp-arm committed
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
	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;

1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
	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
1282

1283
1284
1285
1286
1287
		switch (c) {
		case 'v':
			verbose = 1;
			break;
		default:
1288
			usage();
1289
		}
dp-arm's avatar
dp-arm committed
1290
	}
1291
1292
1293
1294
1295
1296
1297
	argc -= optind;
	argv += optind;
	/* Reset optind for subsequent getopt processing. */
	optind = 0;

	if (argc == 0)
		usage();
dp-arm's avatar
dp-arm committed
1298

1299
	fill_image_descs();
dp-arm's avatar
dp-arm committed
1300
1301
1302
1303
1304
1305
1306
1307
	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();
1308
	free_image_descs();
dp-arm's avatar
dp-arm committed
1309
1310
	return ret;
}