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, dest_blob, ptr,
79 munmap(dest_blob, destfd_size);
84 munmap(ptr, sbuf.st_size);
90 * fit_calc_size() - Calculate the approximate size of the FIT we will generate
92 static int fit_calc_size(struct image_tool_params *params)
94 struct content_info *cont;
97 size = imagetool_get_filesize(params, params->datafile);
102 if (params->fit_ramdisk) {
103 size = imagetool_get_filesize(params, params->fit_ramdisk);
109 for (cont = params->content_head; cont; cont = cont->next) {
110 size = imagetool_get_filesize(params, cont->fname);
114 /* Add space for properties and hash node */
115 total_size += size + 300;
118 /* Add plenty of space for headers, properties, nodes, etc. */
124 static int fdt_property_file(struct image_tool_params *params,
125 void *fdt, const char *name, const char *fname)
132 fd = open(fname, O_RDWR | O_BINARY);
134 fprintf(stderr, "%s: Can't open %s: %s\n",
135 params->cmdname, fname, strerror(errno));
139 if (fstat(fd, &sbuf) < 0) {
140 fprintf(stderr, "%s: Can't stat %s: %s\n",
141 params->cmdname, fname, strerror(errno));
145 ret = fdt_property_placeholder(fdt, "data", sbuf.st_size, &ptr);
148 ret = read(fd, ptr, sbuf.st_size);
149 if (ret != sbuf.st_size) {
150 fprintf(stderr, "%s: Can't read %s: %s\n",
151 params->cmdname, fname, strerror(errno));
162 static int fdt_property_strf(void *fdt, const char *name, const char *fmt, ...)
168 vsnprintf(str, sizeof(str), fmt, ptr);
170 return fdt_property_string(fdt, name, str);
173 static void get_basename(char *str, int size, const char *fname)
175 const char *p, *start, *end;
179 * Use the base name as the 'name' field. So for example:
181 * "arch/arm/dts/sun7i-a20-bananapro.dtb"
182 * becomes "sun7i-a20-bananapro"
184 p = strrchr(fname, '/');
185 start = p ? p + 1 : fname;
186 p = strrchr(fname, '.');
187 end = p ? p : fname + strlen(fname);
191 memcpy(str, start, len);
196 * add_crc_node() - Add a hash node to request a CRC checksum for an image
198 * @fdt: Device tree to add to (in sequential-write mode)
200 static void add_crc_node(void *fdt)
202 fdt_begin_node(fdt, "hash-1");
203 fdt_property_string(fdt, FIT_ALGO_PROP, "crc32");
208 * fit_write_images() - Write out a list of images to the FIT
210 * We always include the main image (params->datafile). If there are device
211 * tree files, we include an fdt- node for each of those too.
213 static int fit_write_images(struct image_tool_params *params, char *fdt)
215 struct content_info *cont;
216 const char *typename;
221 fdt_begin_node(fdt, "images");
223 /* First the main image */
224 typename = genimg_get_type_short_name(params->fit_image_type);
225 snprintf(str, sizeof(str), "%s-1", typename);
226 fdt_begin_node(fdt, str);
227 fdt_property_string(fdt, FIT_DESC_PROP, params->imagename);
228 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
229 fdt_property_string(fdt, FIT_ARCH_PROP,
230 genimg_get_arch_short_name(params->arch));
231 fdt_property_string(fdt, FIT_OS_PROP,
232 genimg_get_os_short_name(params->os));
233 fdt_property_string(fdt, FIT_COMP_PROP,
234 genimg_get_comp_short_name(params->comp));
235 fdt_property_u32(fdt, FIT_LOAD_PROP, params->addr);
236 fdt_property_u32(fdt, FIT_ENTRY_PROP, params->ep);
239 * Put data last since it is large. SPL may only load the first part
240 * of the DT, so this way it can access all the above fields.
242 ret = fdt_property_file(params, fdt, FIT_DATA_PROP, params->datafile);
248 /* Now the device tree files if available */
250 for (cont = params->content_head; cont; cont = cont->next) {
251 if (cont->type != IH_TYPE_FLATDT)
253 typename = genimg_get_type_short_name(cont->type);
254 snprintf(str, sizeof(str), "%s-%d", FIT_FDT_PROP, ++upto);
255 fdt_begin_node(fdt, str);
257 get_basename(str, sizeof(str), cont->fname);
258 fdt_property_string(fdt, FIT_DESC_PROP, str);
259 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
263 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
264 fdt_property_string(fdt, FIT_ARCH_PROP,
265 genimg_get_arch_short_name(params->arch));
266 fdt_property_string(fdt, FIT_COMP_PROP,
267 genimg_get_comp_short_name(IH_COMP_NONE));
272 /* And a ramdisk file if available */
273 if (params->fit_ramdisk) {
274 fdt_begin_node(fdt, FIT_RAMDISK_PROP "-1");
276 fdt_property_string(fdt, FIT_TYPE_PROP, FIT_RAMDISK_PROP);
277 fdt_property_string(fdt, FIT_OS_PROP,
278 genimg_get_os_short_name(params->os));
279 fdt_property_string(fdt, FIT_ARCH_PROP,
280 genimg_get_arch_short_name(params->arch));
282 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
283 params->fit_ramdisk);
296 * fit_write_configs() - Write out a list of configurations to the FIT
298 * If there are device tree files, we include a configuration for each, which
299 * selects the main image (params->datafile) and its corresponding device
302 * Otherwise we just create a configuration with the main image in it.
304 static void fit_write_configs(struct image_tool_params *params, char *fdt)
306 struct content_info *cont;
307 const char *typename;
311 fdt_begin_node(fdt, "configurations");
312 fdt_property_string(fdt, FIT_DEFAULT_PROP, "conf-1");
315 for (cont = params->content_head; cont; cont = cont->next) {
316 if (cont->type != IH_TYPE_FLATDT)
318 typename = genimg_get_type_short_name(cont->type);
319 snprintf(str, sizeof(str), "conf-%d", ++upto);
320 fdt_begin_node(fdt, str);
322 get_basename(str, sizeof(str), cont->fname);
323 fdt_property_string(fdt, FIT_DESC_PROP, str);
325 typename = genimg_get_type_short_name(params->fit_image_type);
326 snprintf(str, sizeof(str), "%s-1", typename);
327 fdt_property_string(fdt, typename, str);
328 fdt_property_string(fdt, FIT_LOADABLE_PROP, str);
330 if (params->fit_ramdisk)
331 fdt_property_string(fdt, FIT_RAMDISK_PROP,
332 FIT_RAMDISK_PROP "-1");
334 snprintf(str, sizeof(str), FIT_FDT_PROP "-%d", upto);
335 fdt_property_string(fdt, FIT_FDT_PROP, str);
340 fdt_begin_node(fdt, "conf-1");
341 typename = genimg_get_type_short_name(params->fit_image_type);
342 snprintf(str, sizeof(str), "%s-1", typename);
343 fdt_property_string(fdt, typename, str);
345 if (params->fit_ramdisk)
346 fdt_property_string(fdt, FIT_RAMDISK_PROP,
347 FIT_RAMDISK_PROP "-1");
355 static int fit_build_fdt(struct image_tool_params *params, char *fdt, int size)
359 ret = fdt_create(fdt, size);
362 fdt_finish_reservemap(fdt);
363 fdt_begin_node(fdt, "");
364 fdt_property_strf(fdt, FIT_DESC_PROP,
365 "%s image with one or more FDT blobs",
366 genimg_get_type_name(params->fit_image_type));
367 fdt_property_strf(fdt, "creator", "U-Boot mkimage %s", PLAIN_VERSION);
368 fdt_property_u32(fdt, "#address-cells", 1);
369 ret = fit_write_images(params, fdt);
372 fit_write_configs(params, fdt);
374 ret = fdt_finish(fdt);
378 return fdt_totalsize(fdt);
381 static int fit_build(struct image_tool_params *params, const char *fname)
388 size = fit_calc_size(params);
391 buf = calloc(1, size);
393 fprintf(stderr, "%s: Out of memory (%d bytes)\n",
394 params->cmdname, size);
397 ret = fit_build_fdt(params, buf, size);
399 fprintf(stderr, "%s: Failed to build FIT image\n",
404 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
406 fprintf(stderr, "%s: Can't open %s: %s\n",
407 params->cmdname, fname, strerror(errno));
410 ret = write(fd, buf, size);
412 fprintf(stderr, "%s: Can't write %s: %s\n",
413 params->cmdname, fname, strerror(errno));
428 * fit_extract_data() - Move all data outside the FIT
430 * This takes a normal FIT file and removes all the 'data' properties from it.
431 * The data is placed in an area after the FIT so that it can be accessed
432 * using an offset into that area. The 'data' properties turn into
433 * 'data-offset' properties.
435 * This function cannot cope with FITs with 'data-offset' properties. All
436 * data must be in 'data' properties on entry.
438 static int fit_extract_data(struct image_tool_params *params, const char *fname)
442 int fit_size, new_size;
452 align_size = params->bl_len ? params->bl_len : 4;
453 fd = mmap_fdt(params->cmdname, fname, 0, &fdt, &sbuf, false, false);
456 fit_size = fdt_totalsize(fdt);
458 images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
460 debug("%s: Cannot find /images node: %d\n", __func__, images);
464 image_number = fdtdec_get_child_count(fdt, images);
467 * Allocate space to hold the image data we will extract,
468 * extral space allocate for image alignment to prevent overflow.
470 buf = calloc(1, fit_size + (align_size * image_number));
477 for (node = fdt_first_subnode(fdt, images);
479 node = fdt_next_subnode(fdt, node)) {
483 data = fdt_getprop(fdt, node, FIT_DATA_PROP, &len);
486 memcpy(buf + buf_ptr, data, len);
487 debug("Extracting data size %x\n", len);
489 ret = fdt_delprop(fdt, node, FIT_DATA_PROP);
494 if (params->external_offset > 0) {
495 /* An external offset positions the data absolutely. */
496 fdt_setprop_u32(fdt, node, FIT_DATA_POSITION_PROP,
497 params->external_offset + buf_ptr);
499 fdt_setprop_u32(fdt, node, FIT_DATA_OFFSET_PROP,
502 fdt_setprop_u32(fdt, node, FIT_DATA_SIZE_PROP, len);
503 buf_ptr += ALIGN(len, align_size);
506 /* Pack the FDT and place the data after it */
509 new_size = fdt_totalsize(fdt);
510 new_size = ALIGN(new_size, align_size);
511 fdt_set_totalsize(fdt, new_size);
512 debug("Size reduced from %x to %x\n", fit_size, fdt_totalsize(fdt));
513 debug("External data size %x\n", buf_ptr);
514 munmap(fdt, sbuf.st_size);
516 if (ftruncate(fd, new_size)) {
517 debug("%s: Failed to truncate file: %s\n", __func__,
523 /* Check if an offset for the external data was set. */
524 if (params->external_offset > 0) {
525 if (params->external_offset < new_size) {
526 debug("External offset %x overlaps FIT length %x",
527 params->external_offset, new_size);
531 new_size = params->external_offset;
533 if (lseek(fd, new_size, SEEK_SET) < 0) {
534 debug("%s: Failed to seek to end of file: %s\n", __func__,
539 if (write(fd, buf, buf_ptr) != buf_ptr) {
540 debug("%s: Failed to write external data to file %s\n",
541 __func__, strerror(errno));
550 munmap(fdt, sbuf.st_size);
557 static int fit_import_data(struct image_tool_params *params, const char *fname)
560 int fit_size, new_size, size, data_base;
567 fd = mmap_fdt(params->cmdname, fname, 0, &old_fdt, &sbuf, false, false);
570 fit_size = fdt_totalsize(old_fdt);
571 data_base = ALIGN(fit_size, 4);
573 /* Allocate space to hold the new FIT */
574 size = sbuf.st_size + 16384;
575 fdt = calloc(1, size);
577 fprintf(stderr, "%s: Failed to allocate memory (%d bytes)\n",
582 ret = fdt_open_into(old_fdt, fdt, size);
584 debug("%s: Failed to expand FIT: %s\n", __func__,
585 fdt_strerror(errno));
590 images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
592 debug("%s: Cannot find /images node: %d\n", __func__, images);
597 for (node = fdt_first_subnode(fdt, images);
599 node = fdt_next_subnode(fdt, node)) {
603 buf_ptr = fdtdec_get_int(fdt, node, "data-offset", -1);
604 len = fdtdec_get_int(fdt, node, "data-size", -1);
605 if (buf_ptr == -1 || len == -1)
607 debug("Importing data size %x\n", len);
609 ret = fdt_setprop(fdt, node, "data",
610 old_fdt + data_base + buf_ptr, len);
612 debug("%s: Failed to write property: %s\n", __func__,
619 munmap(old_fdt, sbuf.st_size);
621 /* Close the old fd so we can re-use it. */
624 /* Pack the FDT and place the data after it */
627 new_size = fdt_totalsize(fdt);
628 debug("Size expanded from %x to %x\n", fit_size, new_size);
630 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
632 fprintf(stderr, "%s: Can't open %s: %s\n",
633 params->cmdname, fname, strerror(errno));
637 if (write(fd, fdt, new_size) != new_size) {
638 debug("%s: Failed to write external data to file %s\n",
639 __func__, strerror(errno));
649 munmap(old_fdt, sbuf.st_size);
656 static int copyfile(const char *src, const char *dst)
658 int fd_src = -1, fd_dst = -1;
664 fd_src = open(src, O_RDONLY);
666 printf("Can't open file %s (%s)\n", src, strerror(errno));
670 fd_dst = open(dst, O_WRONLY | O_CREAT, 0666);
672 printf("Can't open file %s (%s)\n", dst, strerror(errno));
676 buf = calloc(1, 512);
678 printf("Can't allocate buffer to copy file\n");
683 size = read(fd_src, buf, 512);
685 printf("Can't read file %s\n", src);
692 size = write(fd_dst, buf, count);
694 printf("Can't write file %s\n", dst);
713 * fit_handle_file - main FIT file processing function
715 * fit_handle_file() runs dtc to convert .its to .itb, includes
716 * binary data, updates timestamp property and calculates hashes.
718 * datafile - .its file
719 * imagefile - .itb file
722 * only on success, otherwise calls exit (EXIT_FAILURE);
724 static int fit_handle_file(struct image_tool_params *params)
726 char tmpfile[MKIMAGE_MAX_TMPFILE_LEN];
727 char bakfile[MKIMAGE_MAX_TMPFILE_LEN + 4] = {0};
728 char cmd[MKIMAGE_MAX_DTC_CMDLINE_LEN];
732 /* Flattened Image Tree (FIT) format handling */
733 debug ("FIT format handling\n");
735 /* call dtc to include binary properties into the tmp file */
736 if (strlen (params->imagefile) +
737 strlen (MKIMAGE_TMPFILE_SUFFIX) + 1 > sizeof (tmpfile)) {
738 fprintf (stderr, "%s: Image file name (%s) too long, "
739 "can't create tmpfile",
740 params->imagefile, params->cmdname);
741 return (EXIT_FAILURE);
743 sprintf (tmpfile, "%s%s", params->imagefile, MKIMAGE_TMPFILE_SUFFIX);
745 /* We either compile the source file, or use the existing FIT image */
746 if (params->auto_its) {
747 if (fit_build(params, tmpfile)) {
748 fprintf(stderr, "%s: failed to build FIT\n",
753 } else if (params->datafile) {
754 /* dtc -I dts -O dtb -p 500 -o tmpfile datafile */
755 snprintf(cmd, sizeof(cmd), "%s %s -o \"%s\" \"%s\"",
756 MKIMAGE_DTC, params->dtc, tmpfile, params->datafile);
757 debug("Trying to execute \"%s\"\n", cmd);
759 snprintf(cmd, sizeof(cmd), "cp \"%s\" \"%s\"",
760 params->imagefile, tmpfile);
762 if (strlen(cmd) >= MKIMAGE_MAX_DTC_CMDLINE_LEN - 1) {
763 fprintf(stderr, "WARNING: command-line for FIT creation might be truncated and will probably fail.\n");
766 if (*cmd && system(cmd) == -1) {
767 fprintf (stderr, "%s: system(%s) failed: %s\n",
768 params->cmdname, cmd, strerror(errno));
772 /* Move the data so it is internal to the FIT, if needed */
773 ret = fit_import_data(params, tmpfile);
778 * Copy the tmpfile to bakfile, then in the following loop
779 * we copy bakfile to tmpfile. So we always start from the
782 sprintf(bakfile, "%s%s", tmpfile, ".bak");
783 rename(tmpfile, bakfile);
786 * Set hashes for images in the blob. Unfortunately we may need more
787 * space in either FDT, so keep trying until we succeed.
789 * Note: this is pretty inefficient for signing, since we must
790 * calculate the signature every time. It would be better to calculate
791 * all the data and then store it in a separate step. However, this
792 * would be considerably more complex to implement. Generally a few
793 * steps of this loop is enough to sign with several keys.
795 for (size_inc = 0; size_inc < 64 * 1024; size_inc += 1024) {
796 if (copyfile(bakfile, tmpfile) < 0) {
797 printf("Can't copy %s to %s\n", bakfile, tmpfile);
801 ret = fit_add_file_data(params, size_inc, tmpfile);
802 if (!ret || ret != -ENOSPC)
807 fprintf(stderr, "%s Can't add hashes to FIT blob: %d\n",
808 params->cmdname, ret);
812 /* Move the data so it is external to the FIT, if requested */
813 if (params->external_data) {
814 ret = fit_extract_data(params, tmpfile);
819 if (rename (tmpfile, params->imagefile) == -1) {
820 fprintf (stderr, "%s: Can't rename %s to %s: %s\n",
821 params->cmdname, tmpfile, params->imagefile,
825 unlink (params->imagefile);
838 * fit_image_extract - extract a FIT component image
839 * @fit: pointer to the FIT format image header
840 * @image_noffset: offset of the component image node
841 * @file_name: name of the file to store the FIT sub-image
844 * zero in case of success or a negative value if fail.
846 static int fit_image_extract(
849 const char *file_name)
851 const void *file_data;
852 size_t file_size = 0;
855 /* get the data address and size of component at offset "image_noffset" */
856 ret = fit_image_get_data_and_size(fit, image_noffset, &file_data, &file_size);
858 fprintf(stderr, "Could not get component information\n");
862 /* save the "file_data" into the file specified by "file_name" */
863 return imagetool_save_subimage(file_name, (ulong) file_data, file_size);
867 * fit_extract_contents - retrieve a sub-image component from the FIT image
868 * @ptr: pointer to the FIT format image header
869 * @params: command line parameters
872 * zero in case of success or a negative value if fail.
874 static int fit_extract_contents(void *ptr, struct image_tool_params *params)
879 const void *fit = ptr;
883 /* Indent string is defined in header image.h */
884 p = IMAGE_INDENT_STRING;
886 if (!fit_check_format(fit)) {
887 printf("Bad FIT image format\n");
891 /* Find images parent node offset */
892 images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
893 if (images_noffset < 0) {
894 printf("Can't find images parent node '%s' (%s)\n",
895 FIT_IMAGES_PATH, fdt_strerror(images_noffset));
899 /* Avoid any overrun */
900 count = fit_get_subimage_count(fit, images_noffset);
901 if ((params->pflag < 0) || (count <= params->pflag)) {
902 printf("No such component at '%d'\n", params->pflag);
906 /* Process its subnodes, extract the desired component from image */
907 for (ndepth = 0, count = 0,
908 noffset = fdt_next_node(fit, images_noffset, &ndepth);
909 (noffset >= 0) && (ndepth > 0);
910 noffset = fdt_next_node(fit, noffset, &ndepth)) {
913 * Direct child node of the images parent node,
914 * i.e. component image node.
916 if (params->pflag == count) {
917 printf("Extracted:\n%s Image %u (%s)\n", p,
918 count, fit_get_name(fit, noffset, NULL));
920 fit_image_print(fit, noffset, p);
922 return fit_image_extract(fit, noffset,
933 static int fit_check_params(struct image_tool_params *params)
935 if (params->auto_its)
937 return ((params->dflag && params->fflag) ||
938 (params->fflag && params->lflag) ||
939 (params->lflag && params->dflag));
945 sizeof(image_header_t),
951 fit_extract_contents,
952 fit_check_image_types,
954 NULL /* FIT images use DTB header */