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