1// SPDX-License-Identifier: GPL-2.0+
2/*
3 * (C) Copyright 2008 Semihalf
4 *
5 * (C) Copyright 2000-2009
6 * DENX Software Engineering
7 * Wolfgang Denk, wd@denx.de
8 */
9
10#include "imagetool.h"
11#include "mkimage.h"
12#include "imximage.h"
13#include <fit_common.h>
14#include <getopt.h>
15#include <image.h>
16#include <version.h>
17#ifdef __linux__
18#include <sys/ioctl.h>
19#endif
20
21static void copy_file(int, const char *, int);
22
23/* parameters initialized by core will be used by the image type code */
24static struct image_tool_params params = {
25	.os = IH_OS_LINUX,
26	.arch = IH_ARCH_PPC,
27	.type = IH_TYPE_KERNEL,
28	.comp = IH_COMP_GZIP,
29	.dtc = MKIMAGE_DEFAULT_DTC_OPTIONS,
30	.imagename = "",
31	.imagename2 = "",
32};
33
34static enum ih_category cur_category;
35
36static int h_compare_category_name(const void *vtype1, const void *vtype2)
37{
38	const int *type1 = vtype1;
39	const int *type2 = vtype2;
40	const char *name1 = genimg_get_cat_short_name(cur_category, *type1);
41	const char *name2 = genimg_get_cat_short_name(cur_category, *type2);
42
43	return strcmp(name1, name2);
44}
45
46static int show_valid_options(enum ih_category category)
47{
48	int *order;
49	int count;
50	int item;
51	int i;
52
53	count = genimg_get_cat_count(category);
54	order = calloc(count, sizeof(*order));
55	if (!order)
56		return -ENOMEM;
57
58	/* Sort the names in order of short name for easier reading */
59	for (i = 0, item = 0; i < count; i++, item++) {
60		while (!genimg_cat_has_id(category, item) && i < count) {
61			item++;
62			count--;
63		}
64		order[i] = item;
65	}
66	cur_category = category;
67	qsort(order, count, sizeof(int), h_compare_category_name);
68
69	fprintf(stderr, "\nInvalid %s, supported are:\n",
70		genimg_get_cat_desc(category));
71	for (i = 0; i < count; i++) {
72		item = order[i];
73		fprintf(stderr, "\t%-15s  %s\n",
74			genimg_get_cat_short_name(category, item),
75			genimg_get_cat_name(category, item));
76	}
77	fprintf(stderr, "\n");
78	free(order);
79
80	return 0;
81}
82
83static void usage(const char *msg)
84{
85	fprintf(stderr, "Error: %s\n", msg);
86	fprintf(stderr, "Usage: %s [-T type] -l image\n"
87			 "          -l ==> list image header information\n"
88			 "          -T ==> parse image file as 'type'\n"
89			 "          -q ==> quiet\n",
90		params.cmdname);
91	fprintf(stderr,
92		"       %s [-x] -A arch -O os -T type -C comp -a addr -e ep -n name -d data_file[:data_file...] image\n"
93		"          -A ==> set architecture to 'arch'\n"
94		"          -O ==> set operating system to 'os'\n"
95		"          -T ==> set image type to 'type'\n"
96		"          -C ==> set compression type 'comp'\n"
97		"          -a ==> set load address to 'addr' (hex)\n"
98		"          -e ==> set entry point to 'ep' (hex)\n"
99		"          -n ==> set image name to 'name'\n"
100		"          -R ==> set second image name to 'name'\n"
101		"          -d ==> use image data from 'datafile'\n"
102		"          -x ==> set XIP (execute in place)\n"
103		"          -s ==> create an image with no data\n"
104		"          -v ==> verbose\n",
105		params.cmdname);
106	fprintf(stderr,
107		"       %s [-D dtc_options] [-f fit-image.its|-f auto|-f auto-conf|-F] [-b <dtb> [-b <dtb>]] [-E] [-B size] [-i <ramdisk.cpio.gz>] fit-image\n"
108		"           <dtb> file is used with -f auto, it may occur multiple times.\n",
109		params.cmdname);
110	fprintf(stderr,
111		"          -D => set all options for device tree compiler\n"
112		"          -f => input filename for FIT source\n"
113		"          -i => input filename for ramdisk file\n"
114		"          -E => place data outside of the FIT structure\n"
115		"          -B => align size in hex for FIT structure and header\n"
116		"          -b => append the device tree binary to the FIT\n"
117		"          -t => update the timestamp in the FIT\n");
118#if CONFIG_IS_ENABLED(FIT_SIGNATURE)
119	fprintf(stderr,
120		"Signing / verified boot options: [-k keydir] [-K dtb] [ -c <comment>] [-p addr] [-r] [-N engine]\n"
121		"          -k => set directory containing private keys\n"
122		"          -K => write public keys to this .dtb file\n"
123		"          -g => set key name hint\n"
124		"          -G => use this signing key (in lieu of -k)\n"
125		"          -c => add comment in signature node\n"
126		"          -F => re-sign existing FIT image\n"
127		"          -p => place external data at a static position\n"
128		"          -r => mark keys used as 'required' in dtb\n"
129		"          -N => openssl engine to use for signing\n"
130		"          -o => algorithm to use for signing\n");
131#else
132	fprintf(stderr,
133		"Signing / verified boot not supported (CONFIG_TOOLS_FIT_SIGNATURE undefined)\n");
134#endif
135
136	fprintf(stderr, "       %s -V ==> print version information and exit\n",
137		params.cmdname);
138	fprintf(stderr, "Use '-T list' to see a list of available image types\n");
139	fprintf(stderr, "Long options are available; read the man page for details\n");
140
141	exit(EXIT_FAILURE);
142}
143
144static int add_content(int type, const char *fname)
145{
146	struct content_info *cont;
147
148	cont = calloc(1, sizeof(*cont));
149	if (!cont)
150		return -1;
151	cont->type = type;
152	cont->fname = fname;
153	if (params.content_tail)
154		params.content_tail->next = cont;
155	else
156		params.content_head = cont;
157	params.content_tail = cont;
158
159	return 0;
160}
161
162static const char optstring[] =
163	"a:A:b:B:c:C:d:D:e:Ef:Fg:G:i:k:K:ln:N:o:O:p:qrR:stT:vVx";
164
165static const struct option longopts[] = {
166	{ "load-address", required_argument, NULL, 'a' },
167	{ "architecture", required_argument, NULL, 'A' },
168	{ "device-tree", required_argument, NULL, 'b' },
169	{ "alignment", required_argument, NULL, 'B' },
170	{ "comment", required_argument, NULL, 'c' },
171	{ "compression", required_argument, NULL, 'C' },
172	{ "image", required_argument, NULL, 'd' },
173	{ "dtcopts", required_argument, NULL, 'D' },
174	{ "entry-point", required_argument, NULL, 'e' },
175	{ "external", no_argument, NULL, 'E' },
176	{ "fit", required_argument, NULL, 'f' },
177	{ "update", no_argument, NULL, 'F' },
178	{ "key-name-hint", required_argument, NULL, 'g' },
179	{ "key-file", required_argument, NULL, 'G' },
180	{ "help", no_argument, NULL, 'h' },
181	{ "initramfs", required_argument, NULL, 'i' },
182	{ "key-dir", required_argument, NULL, 'k' },
183	{ "key-dest", required_argument, NULL, 'K' },
184	{ "list", no_argument, NULL, 'l' },
185	{ "config", required_argument, NULL, 'n' },
186	{ "engine", required_argument, NULL, 'N' },
187	{ "algo", required_argument, NULL, 'o' },
188	{ "os", required_argument, NULL, 'O' },
189	{ "position", required_argument, NULL, 'p' },
190	{ "quiet", no_argument, NULL, 'q' },
191	{ "key-required", no_argument, NULL, 'r' },
192	{ "secondary-config", required_argument, NULL, 'R' },
193	{ "no-copy", no_argument, NULL, 's' },
194	{ "touch", no_argument, NULL, 't' },
195	{ "type", required_argument, NULL, 'T' },
196	{ "verbose", no_argument, NULL, 'v' },
197	{ "version", no_argument, NULL, 'V' },
198	{ "xip", no_argument, NULL, 'x' },
199};
200
201static void process_args(int argc, char **argv)
202{
203	char *ptr;
204	int type = IH_TYPE_INVALID;
205	char *datafile = NULL;
206	int opt;
207
208	while ((opt = getopt_long(argc, argv, optstring,
209				  longopts, NULL)) != -1) {
210		switch (opt) {
211		case 'a':
212			params.addr = strtoull(optarg, &ptr, 16);
213			if (*ptr) {
214				fprintf(stderr, "%s: invalid load address %s\n",
215					params.cmdname, optarg);
216				exit(EXIT_FAILURE);
217			}
218			break;
219		case 'A':
220			params.arch = genimg_get_arch_id(optarg);
221			if (params.arch < 0) {
222				show_valid_options(IH_ARCH);
223				usage("Invalid architecture");
224			}
225			params.Aflag = 1;
226			break;
227		case 'b':
228			if (add_content(IH_TYPE_FLATDT, optarg)) {
229				fprintf(stderr,
230					"%s: Out of memory adding content '%s'",
231					params.cmdname, optarg);
232				exit(EXIT_FAILURE);
233			}
234			break;
235		case 'B':
236			params.bl_len = strtoull(optarg, &ptr, 16);
237			if (*ptr) {
238				fprintf(stderr, "%s: invalid block length %s\n",
239					params.cmdname, optarg);
240				exit(EXIT_FAILURE);
241			}
242
243			break;
244		case 'c':
245			params.comment = optarg;
246			break;
247		case 'C':
248			params.comp = genimg_get_comp_id(optarg);
249			if (params.comp < 0) {
250				show_valid_options(IH_COMP);
251				usage("Invalid compression type");
252			}
253			break;
254		case 'd':
255			params.datafile = optarg;
256			params.dflag = 1;
257			break;
258		case 'D':
259			params.dtc = optarg;
260			break;
261		case 'e':
262			params.ep = strtoull(optarg, &ptr, 16);
263			if (*ptr) {
264				fprintf(stderr, "%s: invalid entry point %s\n",
265					params.cmdname, optarg);
266				exit(EXIT_FAILURE);
267			}
268			params.eflag = 1;
269			break;
270		case 'E':
271			params.external_data = true;
272			break;
273		case 'f':
274			datafile = optarg;
275			if (!strcmp(datafile, "auto"))
276				params.auto_fit = AF_HASHED_IMG;
277			else if (!strcmp(datafile, "auto-conf"))
278				params.auto_fit = AF_SIGNED_CONF;
279			/* fallthrough */
280		case 'F':
281			/*
282			 * The flattened image tree (FIT) format
283			 * requires a flattened device tree image type
284			 */
285			params.type = IH_TYPE_FLATDT;
286			params.fflag = 1;
287			break;
288		case 'g':
289			params.keyname = optarg;
290			break;
291		case 'G':
292			params.keyfile = optarg;
293			break;
294		case 'i':
295			params.fit_ramdisk = optarg;
296			break;
297		case 'k':
298			params.keydir = optarg;
299			break;
300		case 'K':
301			params.keydest = optarg;
302			break;
303		case 'l':
304			params.lflag = 1;
305			break;
306		case 'n':
307			params.imagename = optarg;
308			break;
309		case 'N':
310			params.engine_id = optarg;
311			break;
312		case 'o':
313			params.algo_name = optarg;
314			break;
315		case 'O':
316			params.os = genimg_get_os_id(optarg);
317			if (params.os < 0) {
318				show_valid_options(IH_OS);
319				usage("Invalid operating system");
320			}
321			break;
322		case 'p':
323			params.external_offset = strtoull(optarg, &ptr, 16);
324			if (*ptr) {
325				fprintf(stderr, "%s: invalid offset size %s\n",
326					params.cmdname, optarg);
327				exit(EXIT_FAILURE);
328			}
329			break;
330		case 'q':
331			params.quiet = 1;
332			break;
333		case 'r':
334			params.require_keys = 1;
335			break;
336		case 'R':
337			/*
338			 * This entry is for the second configuration
339			 * file, if only one is not enough.
340			 */
341			params.imagename2 = optarg;
342			break;
343		case 's':
344			params.skipcpy = 1;
345			break;
346		case 't':
347			params.reset_timestamp = 1;
348			break;
349		case 'T':
350			if (strcmp(optarg, "list") == 0) {
351				show_valid_options(IH_TYPE);
352				exit(EXIT_SUCCESS);
353			}
354			type = genimg_get_type_id(optarg);
355			if (type < 0) {
356				show_valid_options(IH_TYPE);
357				usage("Invalid image type");
358			}
359			break;
360		case 'v':
361			params.vflag++;
362			break;
363		case 'V':
364			printf("mkimage version %s\n", PLAIN_VERSION);
365			exit(EXIT_SUCCESS);
366		case 'x':
367			params.xflag++;
368			break;
369		default:
370			usage("Invalid option");
371		}
372	}
373
374	/* The last parameter is expected to be the imagefile */
375	if (optind < argc)
376		params.imagefile = argv[optind];
377
378	if (params.auto_fit == AF_SIGNED_CONF) {
379		if (!params.keyname || !params.algo_name)
380			usage("Missing key/algo for auto-FIT with signed configs (use -g -o)");
381	} else if (params.auto_fit == AF_HASHED_IMG && params.keyname) {
382		params.auto_fit = AF_SIGNED_IMG;
383		if (!params.algo_name)
384			usage("Missing algorithm for auto-FIT with signed images (use -g)");
385	}
386
387	/*
388	 * For auto-generated FIT images we need to know the image type to put
389	 * in the FIT, which is separate from the file's image type (which
390	 * will always be IH_TYPE_FLATDT in this case).
391	 */
392	if (params.type == IH_TYPE_FLATDT) {
393		params.fit_image_type = type ? type : IH_TYPE_KERNEL;
394		/* For auto-FIT, datafile has to be provided with -d */
395		if (!params.auto_fit)
396			params.datafile = datafile;
397		else if (!params.datafile)
398			usage("Missing data file for auto-FIT (use -d)");
399	} else if (params.lflag || type != IH_TYPE_INVALID) {
400		if (type == IH_TYPE_SCRIPT && !params.datafile)
401			usage("Missing data file for script (use -d)");
402		params.type = type;
403	}
404
405	if (!params.imagefile)
406		usage("Missing output filename");
407}
408
409static void verify_image(const struct image_type_params *tparams)
410{
411	struct stat sbuf;
412	void *ptr;
413	int ifd;
414
415	ifd = open(params.imagefile, O_RDONLY | O_BINARY);
416	if (ifd < 0) {
417		fprintf(stderr, "%s: Can't open %s: %s\n",
418			params.cmdname, params.imagefile,
419			strerror(errno));
420		exit(EXIT_FAILURE);
421	}
422
423	if (fstat(ifd, &sbuf) < 0) {
424		fprintf(stderr, "%s: Can't stat %s: %s\n",
425			params.cmdname, params.imagefile, strerror(errno));
426		exit(EXIT_FAILURE);
427	}
428	params.file_size = sbuf.st_size;
429
430	ptr = mmap(0, params.file_size, PROT_READ, MAP_SHARED, ifd, 0);
431	if (ptr == MAP_FAILED) {
432		fprintf(stderr, "%s: Can't map %s: %s\n",
433			params.cmdname, params.imagefile, strerror(errno));
434		exit(EXIT_FAILURE);
435	}
436
437	if (tparams->verify_header((unsigned char *)ptr, params.file_size, &params) != 0) {
438		fprintf(stderr, "%s: Failed to verify header of %s\n",
439			params.cmdname, params.imagefile);
440		exit(EXIT_FAILURE);
441	}
442
443	(void)munmap(ptr, params.file_size);
444	(void)close(ifd);
445}
446
447void copy_datafile(int ifd, char *file)
448{
449	if (!file)
450		return;
451	for (;;) {
452		char *sep = strchr(file, ':');
453
454		if (sep) {
455			*sep = '\0';
456			copy_file(ifd, file, 1);
457			*sep++ = ':';
458			file = sep;
459		} else {
460			copy_file(ifd, file, 0);
461			break;
462		}
463	}
464}
465
466int main(int argc, char **argv)
467{
468	int ifd = -1;
469	struct stat sbuf;
470	char *ptr;
471	int retval = 0;
472	struct image_type_params *tparams = NULL;
473	int pad_len = 0;
474	int dfd;
475	size_t map_len;
476
477	params.cmdname = *argv;
478	params.addr = 0;
479	params.ep = 0;
480
481	process_args(argc, argv);
482
483	/* set tparams as per input type_id */
484	tparams = imagetool_get_type(params.type);
485	if (tparams == NULL && !params.lflag) {
486		fprintf (stderr, "%s: unsupported type %s\n",
487			params.cmdname, genimg_get_type_name(params.type));
488		exit (EXIT_FAILURE);
489	}
490
491	/*
492	 * check the passed arguments parameters meets the requirements
493	 * as per image type to be generated/listed
494	 */
495	if (tparams && tparams->check_params)
496		if (tparams->check_params (&params))
497			usage("Bad parameters for image type");
498
499	if (!params.eflag) {
500		params.ep = params.addr;
501		/* If XIP, entry point must be after the U-Boot header */
502		if (params.xflag && tparams)
503			params.ep += tparams->header_size;
504	}
505
506	if (params.fflag){
507		if (!tparams) {
508			fprintf(stderr, "%s: Missing FIT support\n",
509				params.cmdname);
510			exit (EXIT_FAILURE);
511		}
512		if (tparams->fflag_handle)
513			/*
514			 * in some cases, some additional processing needs
515			 * to be done if fflag is defined
516			 *
517			 * For ex. fit_handle_file for Fit file support
518			 */
519			retval = tparams->fflag_handle(&params);
520
521		if (retval != EXIT_SUCCESS)
522			usage("Bad parameters for FIT image type");
523	}
524
525	if (params.lflag || params.fflag) {
526		ifd = open (params.imagefile, O_RDONLY|O_BINARY);
527	} else {
528		ifd = open (params.imagefile,
529			O_RDWR|O_CREAT|O_TRUNC|O_BINARY, 0666);
530	}
531
532	if (ifd < 0) {
533		fprintf (stderr, "%s: Can't open %s: %s\n",
534			params.cmdname, params.imagefile,
535			strerror(errno));
536		exit (EXIT_FAILURE);
537	}
538
539	if (params.lflag || params.fflag) {
540		uint64_t size;
541		/*
542		 * list header information of existing image
543		 */
544		if (fstat(ifd, &sbuf) < 0) {
545			fprintf (stderr, "%s: Can't stat %s: %s\n",
546				params.cmdname, params.imagefile,
547				strerror(errno));
548			exit (EXIT_FAILURE);
549		}
550
551		if ((sbuf.st_mode & S_IFMT) == S_IFBLK) {
552#ifdef __linux__
553#if defined(__linux__) && defined(_IOR) && !defined(BLKGETSIZE64)
554#define BLKGETSIZE64 _IOR(0x12,114,size_t)	/* return device size in bytes (u64 *arg) */
555#endif
556			if (ioctl(ifd, BLKGETSIZE64, &size) < 0) {
557				fprintf (stderr,
558					"%s: failed to get size of block device \"%s\"\n",
559					params.cmdname, params.imagefile);
560				exit (EXIT_FAILURE);
561			}
562#else
563			fprintf (stderr,
564				"%s: \"%s\" is block device, don't know how to get its size\n",
565				params.cmdname, params.imagefile);
566			exit (EXIT_FAILURE);
567#endif
568		} else if (tparams && sbuf.st_size < (off_t)tparams->header_size) {
569			fprintf (stderr,
570				"%s: Bad size: \"%s\" is not valid image: size %llu < %u\n",
571				params.cmdname, params.imagefile,
572				(unsigned long long) sbuf.st_size,
573				tparams->header_size);
574			exit (EXIT_FAILURE);
575		} else {
576			size = sbuf.st_size;
577		}
578
579		ptr = mmap(0, size, PROT_READ, MAP_SHARED, ifd, 0);
580		if (ptr == MAP_FAILED) {
581			fprintf (stderr, "%s: Can't read %s: %s\n",
582				params.cmdname, params.imagefile,
583				strerror(errno));
584			exit (EXIT_FAILURE);
585		}
586
587		/*
588		 * Verifies the header format based on the expected header for image
589		 * type in tparams. If tparams is NULL simply check all image types
590		 * to find one that matches our header.
591		 */
592		retval = imagetool_verify_print_header(ptr, &sbuf, tparams, &params);
593
594		(void) munmap((void *)ptr, sbuf.st_size);
595		(void) close (ifd);
596		if (!retval)
597			summary_show(&params.summary, params.imagefile,
598				     params.keydest);
599
600		exit (retval);
601	}
602
603	if (!params.skipcpy && params.type != IH_TYPE_MULTI && params.type != IH_TYPE_SCRIPT) {
604		if (!params.datafile) {
605			fprintf(stderr, "%s: Option -d with image data file was not specified\n",
606				params.cmdname);
607			exit(EXIT_FAILURE);
608		}
609		dfd = open(params.datafile, O_RDONLY | O_BINARY);
610		if (dfd < 0) {
611			fprintf(stderr, "%s: Can't open %s: %s\n",
612				params.cmdname, params.datafile,
613				strerror(errno));
614			exit(EXIT_FAILURE);
615		}
616
617		if (fstat(dfd, &sbuf) < 0) {
618			fprintf(stderr, "%s: Can't stat %s: %s\n",
619				params.cmdname, params.datafile,
620				strerror(errno));
621			exit(EXIT_FAILURE);
622		}
623
624		params.file_size = sbuf.st_size + tparams->header_size;
625		close(dfd);
626	}
627
628	/*
629	 * In case there an header with a variable
630	 * length will be added, the corresponding
631	 * function is called. This is responsible to
632	 * allocate memory for the header itself.
633	 */
634	if (tparams->vrec_header)
635		pad_len = tparams->vrec_header(&params, tparams);
636	else
637		memset(tparams->hdr, 0, tparams->header_size);
638
639	if (write(ifd, tparams->hdr, tparams->header_size)
640					!= tparams->header_size) {
641		fprintf (stderr, "%s: Write error on %s: %s\n",
642			params.cmdname, params.imagefile, strerror(errno));
643		exit (EXIT_FAILURE);
644	}
645
646	if (!params.skipcpy) {
647		if (params.type == IH_TYPE_MULTI ||
648		    params.type == IH_TYPE_SCRIPT) {
649			char *file = params.datafile;
650			uint32_t size;
651
652			for (;;) {
653				char *sep = NULL;
654
655				if (file) {
656					if ((sep = strchr(file, ':')) != NULL) {
657						*sep = '\0';
658					}
659
660					if (stat (file, &sbuf) < 0) {
661						fprintf (stderr, "%s: Can't stat %s: %s\n",
662							 params.cmdname, file, strerror(errno));
663						exit (EXIT_FAILURE);
664					}
665					size = cpu_to_uimage (sbuf.st_size);
666				} else {
667					size = 0;
668				}
669
670				if (write(ifd, (char *)&size, sizeof(size)) != sizeof(size)) {
671					fprintf (stderr, "%s: Write error on %s: %s\n",
672						 params.cmdname, params.imagefile,
673						 strerror(errno));
674					exit (EXIT_FAILURE);
675				}
676
677				if (!file) {
678					break;
679				}
680
681				if (sep) {
682					*sep = ':';
683					file = sep + 1;
684				} else {
685					file = NULL;
686				}
687			}
688			copy_datafile(ifd, params.datafile);
689		} else if (params.type == IH_TYPE_PBLIMAGE) {
690			/* PBL has special Image format, implements its' own */
691			pbl_load_uboot(ifd, &params);
692		} else if (params.type == IH_TYPE_ZYNQMPBIF) {
693			/* Image file is meta, walk through actual targets */
694			int ret;
695
696			ret = zynqmpbif_copy_image(ifd, &params);
697			if (ret)
698				return ret;
699		} else if (params.type == IH_TYPE_IMX8IMAGE) {
700			/* i.MX8/8X has special Image format */
701			int ret;
702
703			ret = imx8image_copy_image(ifd, &params);
704			if (ret)
705				return ret;
706		} else if (params.type == IH_TYPE_IMX8MIMAGE) {
707			/* i.MX8M has special Image format */
708			int ret;
709
710			ret = imx8mimage_copy_image(ifd, &params);
711			if (ret)
712				return ret;
713		} else if ((params.type == IH_TYPE_RKSD) ||
714				(params.type == IH_TYPE_RKSPI)) {
715			/* Rockchip has special Image format */
716			int ret;
717
718			ret = rockchip_copy_image(ifd, &params);
719			if (ret)
720				return ret;
721		} else {
722			copy_file(ifd, params.datafile, pad_len);
723		}
724		if (params.type == IH_TYPE_FIRMWARE_IVT) {
725			/* Add alignment and IVT */
726			uint32_t aligned_filesize = ALIGN(params.file_size,
727							  0x1000);
728			flash_header_v2_t ivt_header = { { 0xd1, 0x2000, 0x40 },
729					params.addr, 0, 0, 0, params.addr
730							+ aligned_filesize
731							- tparams->header_size,
732					params.addr + aligned_filesize
733							- tparams->header_size
734							+ 0x20, 0 };
735			int i = params.file_size;
736			for (; i < aligned_filesize; i++) {
737				if (write(ifd, (char *) &i, 1) != 1) {
738					fprintf(stderr,
739							"%s: Write error on %s: %s\n",
740							params.cmdname,
741							params.imagefile,
742							strerror(errno));
743					exit(EXIT_FAILURE);
744				}
745			}
746			if (write(ifd, &ivt_header, sizeof(flash_header_v2_t))
747					!= sizeof(flash_header_v2_t)) {
748				fprintf(stderr, "%s: Write error on %s: %s\n",
749						params.cmdname,
750						params.imagefile,
751						strerror(errno));
752				exit(EXIT_FAILURE);
753			}
754		}
755	}
756
757	/* We're a bit of paranoid */
758#if defined(_POSIX_SYNCHRONIZED_IO) && \
759   !defined(__sun__) && \
760   !defined(__FreeBSD__) && \
761   !defined(__OpenBSD__) && \
762   !defined(__APPLE__)
763	(void) fdatasync (ifd);
764#else
765	(void) fsync (ifd);
766#endif
767
768	if (fstat(ifd, &sbuf) < 0) {
769		fprintf (stderr, "%s: Can't stat %s: %s\n",
770			params.cmdname, params.imagefile, strerror(errno));
771		exit (EXIT_FAILURE);
772	}
773	params.file_size = sbuf.st_size;
774
775	map_len = sbuf.st_size;
776	ptr = mmap(0, map_len, PROT_READ | PROT_WRITE, MAP_SHARED, ifd, 0);
777	if (ptr == MAP_FAILED) {
778		fprintf (stderr, "%s: Can't map %s: %s\n",
779			params.cmdname, params.imagefile, strerror(errno));
780		exit (EXIT_FAILURE);
781	}
782
783	/* Setup the image header as per input image type*/
784	if (tparams->set_header)
785		tparams->set_header (ptr, &sbuf, ifd, &params);
786	else {
787		fprintf (stderr, "%s: Can't set header for %s\n",
788			params.cmdname, tparams->name);
789		exit (EXIT_FAILURE);
790	}
791
792	/* Print the image information by processing image header */
793	if (tparams->print_header)
794		tparams->print_header (ptr, &params);
795	else {
796		fprintf (stderr, "%s: Can't print header for %s\n",
797			params.cmdname, tparams->name);
798	}
799
800	(void)munmap((void *)ptr, map_len);
801
802	/* We're a bit of paranoid */
803#if defined(_POSIX_SYNCHRONIZED_IO) && \
804   !defined(__sun__) && \
805   !defined(__FreeBSD__) && \
806   !defined(__OpenBSD__) && \
807   !defined(__APPLE__)
808	(void) fdatasync (ifd);
809#else
810	(void) fsync (ifd);
811#endif
812
813	if (close(ifd)) {
814		fprintf (stderr, "%s: Write error on %s: %s\n",
815			params.cmdname, params.imagefile, strerror(errno));
816		exit (EXIT_FAILURE);
817	}
818
819	if (tparams->verify_header)
820		verify_image(tparams);
821
822	exit (EXIT_SUCCESS);
823}
824
825static void
826copy_file (int ifd, const char *datafile, int pad)
827{
828	int dfd;
829	struct stat sbuf;
830	unsigned char *ptr;
831	int tail;
832	int zero = 0;
833	uint8_t zeros[4096];
834	int offset = 0;
835	int size, ret;
836	struct image_type_params *tparams = imagetool_get_type(params.type);
837
838	memset(zeros, 0, sizeof(zeros));
839
840	if (params.vflag) {
841		fprintf (stderr, "Adding Image %s\n", datafile);
842	}
843
844	if ((dfd = open(datafile, O_RDONLY|O_BINARY)) < 0) {
845		fprintf (stderr, "%s: Can't open %s: %s\n",
846			params.cmdname, datafile, strerror(errno));
847		exit (EXIT_FAILURE);
848	}
849
850	if (fstat(dfd, &sbuf) < 0) {
851		fprintf (stderr, "%s: Can't stat %s: %s\n",
852			params.cmdname, datafile, strerror(errno));
853		exit (EXIT_FAILURE);
854	}
855
856	if (sbuf.st_size == 0) {
857		fprintf (stderr, "%s: Input file %s is empty, bailing out\n",
858			params.cmdname, datafile);
859		exit (EXIT_FAILURE);
860	}
861
862	ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, dfd, 0);
863	if (ptr == MAP_FAILED) {
864		fprintf (stderr, "%s: Can't read %s: %s\n",
865			params.cmdname, datafile, strerror(errno));
866		exit (EXIT_FAILURE);
867	}
868
869	if (params.xflag &&
870	    (((params.type > IH_TYPE_INVALID) && (params.type < IH_TYPE_FLATDT)) ||
871	     (params.type == IH_TYPE_KERNEL_NOLOAD) || (params.type == IH_TYPE_FIRMWARE_IVT))) {
872		unsigned char *p = NULL;
873		/*
874		 * XIP: do not append the struct legacy_img_hdr at the
875		 * beginning of the file, but consume the space
876		 * reserved for it.
877		 */
878
879		if ((unsigned)sbuf.st_size < tparams->header_size) {
880			fprintf (stderr,
881				"%s: Bad size: \"%s\" is too small for XIP\n",
882				params.cmdname, datafile);
883			exit (EXIT_FAILURE);
884		}
885
886		for (p = ptr; p < ptr + tparams->header_size; p++) {
887			if ( *p != 0xff ) {
888				fprintf (stderr,
889					"%s: Bad file: \"%s\" has invalid buffer for XIP\n",
890					params.cmdname, datafile);
891				exit (EXIT_FAILURE);
892			}
893		}
894
895		offset = tparams->header_size;
896	}
897
898	size = sbuf.st_size - offset;
899
900	ret = write(ifd, ptr + offset, size);
901	if (ret != size) {
902		if (ret < 0)
903			fprintf (stderr, "%s: Write error on %s: %s\n",
904				 params.cmdname, params.imagefile, strerror(errno));
905		else if (ret < size)
906			fprintf (stderr, "%s: Write only %d/%d bytes, "\
907				 "probably no space left on the device\n",
908				 params.cmdname, ret, size);
909		exit (EXIT_FAILURE);
910	}
911
912	tail = size % 4;
913	if ((pad == 1) && (tail != 0)) {
914
915		if (write(ifd, (char *)&zero, 4-tail) != 4-tail) {
916			fprintf (stderr, "%s: Write error on %s: %s\n",
917				params.cmdname, params.imagefile,
918				strerror(errno));
919			exit (EXIT_FAILURE);
920		}
921	} else if (pad > 1) {
922		while (pad > 0) {
923			int todo = sizeof(zeros);
924
925			if (todo > pad)
926				todo = pad;
927			if (write(ifd, (char *)&zeros, todo) != todo) {
928				fprintf(stderr, "%s: Write error on %s: %s\n",
929					params.cmdname, params.imagefile,
930					strerror(errno));
931				exit(EXIT_FAILURE);
932			}
933			pad -= todo;
934		}
935	}
936
937	(void) munmap((void *)ptr, sbuf.st_size);
938	(void) close (dfd);
939}
940