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