1 // SPDX-License-Identifier: GPL-2.0+
3 * (C) Copyright 2008 Semihalf
5 * (C) Copyright 2000-2004
6 * DENX Software Engineering
7 * Wolfgang Denk, wd@denx.de
9 * Updated-by: Prafulla Wadaskar <prafulla@marvell.com>
10 * FIT image specific code abstracted from mkimage.c
11 * some functions added to address abstraction
13 * All rights reserved.
16 #include "imagetool.h"
17 #include "fit_common.h"
23 #include <u-boot/crc.h>
25 static image_header_t header;
27 static int fit_add_file_data(struct image_tool_params *params, size_t size_inc,
31 void *dest_blob = NULL;
32 off_t destfd_size = 0;
37 tfd = mmap_fdt(params->cmdname, tmpfile, size_inc, &ptr, &sbuf, true,
42 if (params->keydest) {
43 struct stat dest_sbuf;
45 destfd = mmap_fdt(params->cmdname, params->keydest, size_inc,
46 &dest_blob, &dest_sbuf, false,
52 destfd_size = dest_sbuf.st_size;
55 /* for first image creation, add a timestamp at offset 0 i.e., root */
56 if (params->datafile || params->reset_timestamp) {
57 time_t time = imagetool_get_source_date(params->cmdname,
59 ret = fit_set_timestamp(ptr, 0, time);
63 ret = fit_cipher_data(params->keydir, dest_blob, ptr,
71 ret = fit_add_verification_data(params->keydir,
72 params->keyfile, dest_blob, ptr,
80 munmap(dest_blob, destfd_size);
85 munmap(ptr, sbuf.st_size);
91 * fit_calc_size() - Calculate the approximate size of the FIT we will generate
93 static int fit_calc_size(struct image_tool_params *params)
95 struct content_info *cont;
98 size = imagetool_get_filesize(params, params->datafile);
103 if (params->fit_ramdisk) {
104 size = imagetool_get_filesize(params, params->fit_ramdisk);
110 for (cont = params->content_head; cont; cont = cont->next) {
111 size = imagetool_get_filesize(params, cont->fname);
115 /* Add space for properties and hash node */
116 total_size += size + 300;
119 /* Add plenty of space for headers, properties, nodes, etc. */
125 static int fdt_property_file(struct image_tool_params *params,
126 void *fdt, const char *name, const char *fname)
133 fd = open(fname, O_RDWR | O_BINARY);
135 fprintf(stderr, "%s: Can't open %s: %s\n",
136 params->cmdname, fname, strerror(errno));
140 if (fstat(fd, &sbuf) < 0) {
141 fprintf(stderr, "%s: Can't stat %s: %s\n",
142 params->cmdname, fname, strerror(errno));
146 ret = fdt_property_placeholder(fdt, "data", sbuf.st_size, &ptr);
149 ret = read(fd, ptr, sbuf.st_size);
150 if (ret != sbuf.st_size) {
151 fprintf(stderr, "%s: Can't read %s: %s\n",
152 params->cmdname, fname, strerror(errno));
163 static int fdt_property_strf(void *fdt, const char *name, const char *fmt, ...)
169 vsnprintf(str, sizeof(str), fmt, ptr);
171 return fdt_property_string(fdt, name, str);
174 static void get_basename(char *str, int size, const char *fname)
176 const char *p, *start, *end;
180 * Use the base name as the 'name' field. So for example:
182 * "arch/arm/dts/sun7i-a20-bananapro.dtb"
183 * becomes "sun7i-a20-bananapro"
185 p = strrchr(fname, '/');
186 start = p ? p + 1 : fname;
187 p = strrchr(fname, '.');
188 end = p ? p : fname + strlen(fname);
192 memcpy(str, start, len);
197 * add_crc_node() - Add a hash node to request a CRC checksum for an image
199 * @fdt: Device tree to add to (in sequential-write mode)
201 static void add_crc_node(void *fdt)
203 fdt_begin_node(fdt, "hash-1");
204 fdt_property_string(fdt, FIT_ALGO_PROP, "crc32");
209 * fit_write_images() - Write out a list of images to the FIT
211 * We always include the main image (params->datafile). If there are device
212 * tree files, we include an fdt- node for each of those too.
214 static int fit_write_images(struct image_tool_params *params, char *fdt)
216 struct content_info *cont;
217 const char *typename;
222 fdt_begin_node(fdt, "images");
224 /* First the main image */
225 typename = genimg_get_type_short_name(params->fit_image_type);
226 snprintf(str, sizeof(str), "%s-1", typename);
227 fdt_begin_node(fdt, str);
228 fdt_property_string(fdt, FIT_DESC_PROP, params->imagename);
229 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
230 fdt_property_string(fdt, FIT_ARCH_PROP,
231 genimg_get_arch_short_name(params->arch));
232 fdt_property_string(fdt, FIT_OS_PROP,
233 genimg_get_os_short_name(params->os));
234 fdt_property_string(fdt, FIT_COMP_PROP,
235 genimg_get_comp_short_name(params->comp));
236 fdt_property_u32(fdt, FIT_LOAD_PROP, params->addr);
237 fdt_property_u32(fdt, FIT_ENTRY_PROP, params->ep);
240 * Put data last since it is large. SPL may only load the first part
241 * of the DT, so this way it can access all the above fields.
243 ret = fdt_property_file(params, fdt, FIT_DATA_PROP, params->datafile);
249 /* Now the device tree files if available */
251 for (cont = params->content_head; cont; cont = cont->next) {
252 if (cont->type != IH_TYPE_FLATDT)
254 typename = genimg_get_type_short_name(cont->type);
255 snprintf(str, sizeof(str), "%s-%d", FIT_FDT_PROP, ++upto);
256 fdt_begin_node(fdt, str);
258 get_basename(str, sizeof(str), cont->fname);
259 fdt_property_string(fdt, FIT_DESC_PROP, str);
260 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
264 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
265 fdt_property_string(fdt, FIT_ARCH_PROP,
266 genimg_get_arch_short_name(params->arch));
267 fdt_property_string(fdt, FIT_COMP_PROP,
268 genimg_get_comp_short_name(IH_COMP_NONE));
273 /* And a ramdisk file if available */
274 if (params->fit_ramdisk) {
275 fdt_begin_node(fdt, FIT_RAMDISK_PROP "-1");
277 fdt_property_string(fdt, FIT_TYPE_PROP, FIT_RAMDISK_PROP);
278 fdt_property_string(fdt, FIT_OS_PROP,
279 genimg_get_os_short_name(params->os));
280 fdt_property_string(fdt, FIT_ARCH_PROP,
281 genimg_get_arch_short_name(params->arch));
283 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
284 params->fit_ramdisk);
297 * fit_write_configs() - Write out a list of configurations to the FIT
299 * If there are device tree files, we include a configuration for each, which
300 * selects the main image (params->datafile) and its corresponding device
303 * Otherwise we just create a configuration with the main image in it.
305 static void fit_write_configs(struct image_tool_params *params, char *fdt)
307 struct content_info *cont;
308 const char *typename;
312 fdt_begin_node(fdt, "configurations");
313 fdt_property_string(fdt, FIT_DEFAULT_PROP, "conf-1");
316 for (cont = params->content_head; cont; cont = cont->next) {
317 if (cont->type != IH_TYPE_FLATDT)
319 typename = genimg_get_type_short_name(cont->type);
320 snprintf(str, sizeof(str), "conf-%d", ++upto);
321 fdt_begin_node(fdt, str);
323 get_basename(str, sizeof(str), cont->fname);
324 fdt_property_string(fdt, FIT_DESC_PROP, str);
326 typename = genimg_get_type_short_name(params->fit_image_type);
327 snprintf(str, sizeof(str), "%s-1", typename);
328 fdt_property_string(fdt, typename, str);
329 fdt_property_string(fdt, FIT_LOADABLE_PROP, str);
331 if (params->fit_ramdisk)
332 fdt_property_string(fdt, FIT_RAMDISK_PROP,
333 FIT_RAMDISK_PROP "-1");
335 snprintf(str, sizeof(str), FIT_FDT_PROP "-%d", upto);
336 fdt_property_string(fdt, FIT_FDT_PROP, str);
341 fdt_begin_node(fdt, "conf-1");
342 typename = genimg_get_type_short_name(params->fit_image_type);
343 snprintf(str, sizeof(str), "%s-1", typename);
344 fdt_property_string(fdt, typename, str);
346 if (params->fit_ramdisk)
347 fdt_property_string(fdt, FIT_RAMDISK_PROP,
348 FIT_RAMDISK_PROP "-1");
356 static int fit_build_fdt(struct image_tool_params *params, char *fdt, int size)
360 ret = fdt_create(fdt, size);
363 fdt_finish_reservemap(fdt);
364 fdt_begin_node(fdt, "");
365 fdt_property_strf(fdt, FIT_DESC_PROP,
366 "%s image with one or more FDT blobs",
367 genimg_get_type_name(params->fit_image_type));
368 fdt_property_strf(fdt, "creator", "U-Boot mkimage %s", PLAIN_VERSION);
369 fdt_property_u32(fdt, "#address-cells", 1);
370 ret = fit_write_images(params, fdt);
373 fit_write_configs(params, fdt);
375 ret = fdt_finish(fdt);
379 return fdt_totalsize(fdt);
382 static int fit_build(struct image_tool_params *params, const char *fname)
389 size = fit_calc_size(params);
392 buf = calloc(1, size);
394 fprintf(stderr, "%s: Out of memory (%d bytes)\n",
395 params->cmdname, size);
398 ret = fit_build_fdt(params, buf, size);
400 fprintf(stderr, "%s: Failed to build FIT image\n",
405 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
407 fprintf(stderr, "%s: Can't open %s: %s\n",
408 params->cmdname, fname, strerror(errno));
411 ret = write(fd, buf, size);
413 fprintf(stderr, "%s: Can't write %s: %s\n",
414 params->cmdname, fname, strerror(errno));
429 * fit_extract_data() - Move all data outside the FIT
431 * This takes a normal FIT file and removes all the 'data' properties from it.
432 * The data is placed in an area after the FIT so that it can be accessed
433 * using an offset into that area. The 'data' properties turn into
434 * 'data-offset' properties.
436 * This function cannot cope with FITs with 'data-offset' properties. All
437 * data must be in 'data' properties on entry.
439 static int fit_extract_data(struct image_tool_params *params, const char *fname)
443 int fit_size, new_size;
453 align_size = params->bl_len ? params->bl_len : 4;
454 fd = mmap_fdt(params->cmdname, fname, 0, &fdt, &sbuf, false, false);
457 fit_size = fdt_totalsize(fdt);
459 images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
461 debug("%s: Cannot find /images node: %d\n", __func__, images);
465 image_number = fdtdec_get_child_count(fdt, images);
468 * Allocate space to hold the image data we will extract,
469 * extral space allocate for image alignment to prevent overflow.
471 buf = calloc(1, fit_size + (align_size * image_number));
478 for (node = fdt_first_subnode(fdt, images);
480 node = fdt_next_subnode(fdt, node)) {
484 data = fdt_getprop(fdt, node, FIT_DATA_PROP, &len);
487 memcpy(buf + buf_ptr, data, len);
488 debug("Extracting data size %x\n", len);
490 ret = fdt_delprop(fdt, node, FIT_DATA_PROP);
495 if (params->external_offset > 0) {
496 /* An external offset positions the data absolutely. */
497 fdt_setprop_u32(fdt, node, FIT_DATA_POSITION_PROP,
498 params->external_offset + buf_ptr);
500 fdt_setprop_u32(fdt, node, FIT_DATA_OFFSET_PROP,
503 fdt_setprop_u32(fdt, node, FIT_DATA_SIZE_PROP, len);
504 buf_ptr += ALIGN(len, align_size);
507 /* Pack the FDT and place the data after it */
510 new_size = fdt_totalsize(fdt);
511 new_size = ALIGN(new_size, align_size);
512 fdt_set_totalsize(fdt, new_size);
513 debug("Size reduced from %x to %x\n", fit_size, fdt_totalsize(fdt));
514 debug("External data size %x\n", buf_ptr);
515 munmap(fdt, sbuf.st_size);
517 if (ftruncate(fd, new_size)) {
518 debug("%s: Failed to truncate file: %s\n", __func__,
524 /* Check if an offset for the external data was set. */
525 if (params->external_offset > 0) {
526 if (params->external_offset < new_size) {
527 debug("External offset %x overlaps FIT length %x\n",
528 params->external_offset, new_size);
532 new_size = params->external_offset;
534 if (lseek(fd, new_size, SEEK_SET) < 0) {
535 debug("%s: Failed to seek to end of file: %s\n", __func__,
540 if (write(fd, buf, buf_ptr) != buf_ptr) {
541 debug("%s: Failed to write external data to file %s\n",
542 __func__, strerror(errno));
551 munmap(fdt, sbuf.st_size);
558 static int fit_import_data(struct image_tool_params *params, const char *fname)
561 int fit_size, new_size, size, data_base;
568 fd = mmap_fdt(params->cmdname, fname, 0, &old_fdt, &sbuf, false, false);
571 fit_size = fdt_totalsize(old_fdt);
572 data_base = ALIGN(fit_size, 4);
574 /* Allocate space to hold the new FIT */
575 size = sbuf.st_size + 16384;
576 fdt = calloc(1, size);
578 fprintf(stderr, "%s: Failed to allocate memory (%d bytes)\n",
583 ret = fdt_open_into(old_fdt, fdt, size);
585 debug("%s: Failed to expand FIT: %s\n", __func__,
586 fdt_strerror(errno));
591 images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
593 debug("%s: Cannot find /images node: %d\n", __func__, images);
598 for (node = fdt_first_subnode(fdt, images);
600 node = fdt_next_subnode(fdt, node)) {
604 buf_ptr = fdtdec_get_int(fdt, node, "data-offset", -1);
605 len = fdtdec_get_int(fdt, node, "data-size", -1);
606 if (buf_ptr == -1 || len == -1)
608 debug("Importing data size %x\n", len);
610 ret = fdt_setprop(fdt, node, "data",
611 old_fdt + data_base + buf_ptr, len);
613 debug("%s: Failed to write property: %s\n", __func__,
620 munmap(old_fdt, sbuf.st_size);
622 /* Close the old fd so we can re-use it. */
625 /* Pack the FDT and place the data after it */
628 new_size = fdt_totalsize(fdt);
629 debug("Size expanded from %x to %x\n", fit_size, new_size);
631 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
633 fprintf(stderr, "%s: Can't open %s: %s\n",
634 params->cmdname, fname, strerror(errno));
638 if (write(fd, fdt, new_size) != new_size) {
639 debug("%s: Failed to write external data to file %s\n",
640 __func__, strerror(errno));
650 munmap(old_fdt, sbuf.st_size);
657 static int copyfile(const char *src, const char *dst)
659 int fd_src = -1, fd_dst = -1;
665 fd_src = open(src, O_RDONLY);
667 printf("Can't open file %s (%s)\n", src, strerror(errno));
671 fd_dst = open(dst, O_WRONLY | O_CREAT, 0666);
673 printf("Can't open file %s (%s)\n", dst, strerror(errno));
677 buf = calloc(1, 512);
679 printf("Can't allocate buffer to copy file\n");
684 size = read(fd_src, buf, 512);
686 printf("Can't read file %s\n", src);
693 size = write(fd_dst, buf, count);
695 printf("Can't write file %s\n", dst);
714 * fit_handle_file - main FIT file processing function
716 * fit_handle_file() runs dtc to convert .its to .itb, includes
717 * binary data, updates timestamp property and calculates hashes.
719 * datafile - .its file
720 * imagefile - .itb file
723 * only on success, otherwise calls exit (EXIT_FAILURE);
725 static int fit_handle_file(struct image_tool_params *params)
727 char tmpfile[MKIMAGE_MAX_TMPFILE_LEN];
728 char bakfile[MKIMAGE_MAX_TMPFILE_LEN + 4] = {0};
729 char cmd[MKIMAGE_MAX_DTC_CMDLINE_LEN];
733 /* Flattened Image Tree (FIT) format handling */
734 debug ("FIT format handling\n");
736 /* call dtc to include binary properties into the tmp file */
737 if (strlen (params->imagefile) +
738 strlen (MKIMAGE_TMPFILE_SUFFIX) + 1 > sizeof (tmpfile)) {
739 fprintf (stderr, "%s: Image file name (%s) too long, "
740 "can't create tmpfile.\n",
741 params->imagefile, params->cmdname);
742 return (EXIT_FAILURE);
744 sprintf (tmpfile, "%s%s", params->imagefile, MKIMAGE_TMPFILE_SUFFIX);
746 /* We either compile the source file, or use the existing FIT image */
747 if (params->auto_its) {
748 if (fit_build(params, tmpfile)) {
749 fprintf(stderr, "%s: failed to build FIT\n",
754 } else if (params->datafile) {
755 /* dtc -I dts -O dtb -p 500 -o tmpfile datafile */
756 snprintf(cmd, sizeof(cmd), "%s %s -o \"%s\" \"%s\"",
757 MKIMAGE_DTC, params->dtc, tmpfile, params->datafile);
758 debug("Trying to execute \"%s\"\n", cmd);
760 snprintf(cmd, sizeof(cmd), "cp \"%s\" \"%s\"",
761 params->imagefile, tmpfile);
763 if (strlen(cmd) >= MKIMAGE_MAX_DTC_CMDLINE_LEN - 1) {
764 fprintf(stderr, "WARNING: command-line for FIT creation might be truncated and will probably fail.\n");
767 if (*cmd && system(cmd) == -1) {
768 fprintf (stderr, "%s: system(%s) failed: %s\n",
769 params->cmdname, cmd, strerror(errno));
773 /* Move the data so it is internal to the FIT, if needed */
774 ret = fit_import_data(params, tmpfile);
779 * Copy the tmpfile to bakfile, then in the following loop
780 * we copy bakfile to tmpfile. So we always start from the
783 sprintf(bakfile, "%s%s", tmpfile, ".bak");
784 rename(tmpfile, bakfile);
787 * Set hashes for images in the blob. Unfortunately we may need more
788 * space in either FDT, so keep trying until we succeed.
790 * Note: this is pretty inefficient for signing, since we must
791 * calculate the signature every time. It would be better to calculate
792 * all the data and then store it in a separate step. However, this
793 * would be considerably more complex to implement. Generally a few
794 * steps of this loop is enough to sign with several keys.
796 for (size_inc = 0; size_inc < 64 * 1024; size_inc += 1024) {
797 if (copyfile(bakfile, tmpfile) < 0) {
798 printf("Can't copy %s to %s\n", bakfile, tmpfile);
802 ret = fit_add_file_data(params, size_inc, tmpfile);
803 if (!ret || ret != -ENOSPC)
808 fprintf(stderr, "%s Can't add hashes to FIT blob: %d\n",
809 params->cmdname, ret);
813 /* Move the data so it is external to the FIT, if requested */
814 if (params->external_data) {
815 ret = fit_extract_data(params, tmpfile);
820 if (rename (tmpfile, params->imagefile) == -1) {
821 fprintf (stderr, "%s: Can't rename %s to %s: %s\n",
822 params->cmdname, tmpfile, params->imagefile,
826 unlink (params->imagefile);
839 * fit_image_extract - extract a FIT component image
840 * @fit: pointer to the FIT format image header
841 * @image_noffset: offset of the component image node
842 * @file_name: name of the file to store the FIT sub-image
845 * zero in case of success or a negative value if fail.
847 static int fit_image_extract(
850 const char *file_name)
852 const void *file_data;
853 size_t file_size = 0;
856 /* get the data address and size of component at offset "image_noffset" */
857 ret = fit_image_get_data_and_size(fit, image_noffset, &file_data, &file_size);
859 fprintf(stderr, "Could not get component information\n");
863 /* save the "file_data" into the file specified by "file_name" */
864 return imagetool_save_subimage(file_name, (ulong) file_data, file_size);
868 * fit_extract_contents - retrieve a sub-image component from the FIT image
869 * @ptr: pointer to the FIT format image header
870 * @params: command line parameters
873 * zero in case of success or a negative value if fail.
875 static int fit_extract_contents(void *ptr, struct image_tool_params *params)
880 const void *fit = ptr;
884 /* Indent string is defined in header image.h */
885 p = IMAGE_INDENT_STRING;
887 if (fit_check_format(fit, IMAGE_SIZE_INVAL)) {
888 printf("Bad FIT image format\n");
892 /* Find images parent node offset */
893 images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
894 if (images_noffset < 0) {
895 printf("Can't find images parent node '%s' (%s)\n",
896 FIT_IMAGES_PATH, fdt_strerror(images_noffset));
900 /* Avoid any overrun */
901 count = fit_get_subimage_count(fit, images_noffset);
902 if ((params->pflag < 0) || (count <= params->pflag)) {
903 printf("No such component at '%d'\n", params->pflag);
907 /* Process its subnodes, extract the desired component from image */
908 for (ndepth = 0, count = 0,
909 noffset = fdt_next_node(fit, images_noffset, &ndepth);
910 (noffset >= 0) && (ndepth > 0);
911 noffset = fdt_next_node(fit, noffset, &ndepth)) {
914 * Direct child node of the images parent node,
915 * i.e. component image node.
917 if (params->pflag == count) {
918 printf("Extracted:\n%s Image %u (%s)\n", p,
919 count, fit_get_name(fit, noffset, NULL));
921 fit_image_print(fit, noffset, p);
923 return fit_image_extract(fit, noffset,
934 static int fit_check_params(struct image_tool_params *params)
936 if (params->auto_its)
938 return ((params->dflag && params->fflag) ||
939 (params->fflag && params->lflag) ||
940 (params->lflag && params->dflag));
946 sizeof(image_header_t),
952 fit_extract_contents,
953 fit_check_image_types,
955 NULL /* FIT images use DTB header */