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