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,
81 munmap(dest_blob, destfd_size);
86 munmap(ptr, sbuf.st_size);
92 * fit_calc_size() - Calculate the approximate size of the FIT we will generate
94 static int fit_calc_size(struct image_tool_params *params)
96 struct content_info *cont;
99 size = imagetool_get_filesize(params, params->datafile);
104 if (params->fit_ramdisk) {
105 size = imagetool_get_filesize(params, params->fit_ramdisk);
111 for (cont = params->content_head; cont; cont = cont->next) {
112 size = imagetool_get_filesize(params, cont->fname);
116 /* Add space for properties and hash node */
117 total_size += size + 300;
120 /* Add plenty of space for headers, properties, nodes, etc. */
126 static int fdt_property_file(struct image_tool_params *params,
127 void *fdt, const char *name, const char *fname)
134 fd = open(fname, O_RDWR | O_BINARY);
136 fprintf(stderr, "%s: Can't open %s: %s\n",
137 params->cmdname, fname, strerror(errno));
141 if (fstat(fd, &sbuf) < 0) {
142 fprintf(stderr, "%s: Can't stat %s: %s\n",
143 params->cmdname, fname, strerror(errno));
147 ret = fdt_property_placeholder(fdt, "data", sbuf.st_size, &ptr);
150 ret = read(fd, ptr, sbuf.st_size);
151 if (ret != sbuf.st_size) {
152 fprintf(stderr, "%s: Can't read %s: %s\n",
153 params->cmdname, fname, strerror(errno));
164 static int fdt_property_strf(void *fdt, const char *name, const char *fmt, ...)
170 vsnprintf(str, sizeof(str), fmt, ptr);
172 return fdt_property_string(fdt, name, str);
175 static void get_basename(char *str, int size, const char *fname)
177 const char *p, *start, *end;
181 * Use the base name as the 'name' field. So for example:
183 * "arch/arm/dts/sun7i-a20-bananapro.dtb"
184 * becomes "sun7i-a20-bananapro"
186 p = strrchr(fname, '/');
187 start = p ? p + 1 : fname;
188 p = strrchr(fname, '.');
189 end = p ? p : fname + strlen(fname);
193 memcpy(str, start, len);
198 * add_crc_node() - Add a hash node to request a CRC checksum for an image
200 * @fdt: Device tree to add to (in sequential-write mode)
202 static void add_crc_node(void *fdt)
204 fdt_begin_node(fdt, "hash-1");
205 fdt_property_string(fdt, FIT_ALGO_PROP, "crc32");
210 * fit_write_images() - Write out a list of images to the FIT
212 * We always include the main image (params->datafile). If there are device
213 * tree files, we include an fdt- node for each of those too.
215 static int fit_write_images(struct image_tool_params *params, char *fdt)
217 struct content_info *cont;
218 const char *typename;
223 fdt_begin_node(fdt, "images");
225 /* First the main image */
226 typename = genimg_get_type_short_name(params->fit_image_type);
227 snprintf(str, sizeof(str), "%s-1", typename);
228 fdt_begin_node(fdt, str);
229 fdt_property_string(fdt, FIT_DESC_PROP, params->imagename);
230 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
231 fdt_property_string(fdt, FIT_ARCH_PROP,
232 genimg_get_arch_short_name(params->arch));
233 fdt_property_string(fdt, FIT_OS_PROP,
234 genimg_get_os_short_name(params->os));
235 fdt_property_string(fdt, FIT_COMP_PROP,
236 genimg_get_comp_short_name(params->comp));
237 fdt_property_u32(fdt, FIT_LOAD_PROP, params->addr);
238 fdt_property_u32(fdt, FIT_ENTRY_PROP, params->ep);
241 * Put data last since it is large. SPL may only load the first part
242 * of the DT, so this way it can access all the above fields.
244 ret = fdt_property_file(params, fdt, FIT_DATA_PROP, params->datafile);
250 /* Now the device tree files if available */
252 for (cont = params->content_head; cont; cont = cont->next) {
253 if (cont->type != IH_TYPE_FLATDT)
255 typename = genimg_get_type_short_name(cont->type);
256 snprintf(str, sizeof(str), "%s-%d", FIT_FDT_PROP, ++upto);
257 fdt_begin_node(fdt, str);
259 get_basename(str, sizeof(str), cont->fname);
260 fdt_property_string(fdt, FIT_DESC_PROP, str);
261 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
265 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
266 fdt_property_string(fdt, FIT_ARCH_PROP,
267 genimg_get_arch_short_name(params->arch));
268 fdt_property_string(fdt, FIT_COMP_PROP,
269 genimg_get_comp_short_name(IH_COMP_NONE));
274 /* And a ramdisk file if available */
275 if (params->fit_ramdisk) {
276 fdt_begin_node(fdt, FIT_RAMDISK_PROP "-1");
278 fdt_property_string(fdt, FIT_TYPE_PROP, FIT_RAMDISK_PROP);
279 fdt_property_string(fdt, FIT_OS_PROP,
280 genimg_get_os_short_name(params->os));
281 fdt_property_string(fdt, FIT_ARCH_PROP,
282 genimg_get_arch_short_name(params->arch));
284 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
285 params->fit_ramdisk);
298 * fit_write_configs() - Write out a list of configurations to the FIT
300 * If there are device tree files, we include a configuration for each, which
301 * selects the main image (params->datafile) and its corresponding device
304 * Otherwise we just create a configuration with the main image in it.
306 static void fit_write_configs(struct image_tool_params *params, char *fdt)
308 struct content_info *cont;
309 const char *typename;
313 fdt_begin_node(fdt, "configurations");
314 fdt_property_string(fdt, FIT_DEFAULT_PROP, "conf-1");
317 for (cont = params->content_head; cont; cont = cont->next) {
318 if (cont->type != IH_TYPE_FLATDT)
320 typename = genimg_get_type_short_name(cont->type);
321 snprintf(str, sizeof(str), "conf-%d", ++upto);
322 fdt_begin_node(fdt, str);
324 get_basename(str, sizeof(str), cont->fname);
325 fdt_property_string(fdt, FIT_DESC_PROP, str);
327 typename = genimg_get_type_short_name(params->fit_image_type);
328 snprintf(str, sizeof(str), "%s-1", typename);
329 fdt_property_string(fdt, typename, str);
330 fdt_property_string(fdt, FIT_LOADABLE_PROP, str);
332 if (params->fit_ramdisk)
333 fdt_property_string(fdt, FIT_RAMDISK_PROP,
334 FIT_RAMDISK_PROP "-1");
336 snprintf(str, sizeof(str), FIT_FDT_PROP "-%d", upto);
337 fdt_property_string(fdt, FIT_FDT_PROP, str);
342 fdt_begin_node(fdt, "conf-1");
343 typename = genimg_get_type_short_name(params->fit_image_type);
344 snprintf(str, sizeof(str), "%s-1", typename);
345 fdt_property_string(fdt, typename, str);
347 if (params->fit_ramdisk)
348 fdt_property_string(fdt, FIT_RAMDISK_PROP,
349 FIT_RAMDISK_PROP "-1");
357 static int fit_build_fdt(struct image_tool_params *params, char *fdt, int size)
361 ret = fdt_create(fdt, size);
364 fdt_finish_reservemap(fdt);
365 fdt_begin_node(fdt, "");
366 fdt_property_strf(fdt, FIT_DESC_PROP,
367 "%s image with one or more FDT blobs",
368 genimg_get_type_name(params->fit_image_type));
369 fdt_property_strf(fdt, "creator", "U-Boot mkimage %s", PLAIN_VERSION);
370 fdt_property_u32(fdt, "#address-cells", 1);
371 ret = fit_write_images(params, fdt);
374 fit_write_configs(params, fdt);
376 ret = fdt_finish(fdt);
380 return fdt_totalsize(fdt);
383 static int fit_build(struct image_tool_params *params, const char *fname)
390 size = fit_calc_size(params);
393 buf = calloc(1, size);
395 fprintf(stderr, "%s: Out of memory (%d bytes)\n",
396 params->cmdname, size);
399 ret = fit_build_fdt(params, buf, size);
401 fprintf(stderr, "%s: Failed to build FIT image\n",
406 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
408 fprintf(stderr, "%s: Can't open %s: %s\n",
409 params->cmdname, fname, strerror(errno));
412 ret = write(fd, buf, size);
414 fprintf(stderr, "%s: Can't write %s: %s\n",
415 params->cmdname, fname, strerror(errno));
430 * fit_extract_data() - Move all data outside the FIT
432 * This takes a normal FIT file and removes all the 'data' properties from it.
433 * The data is placed in an area after the FIT so that it can be accessed
434 * using an offset into that area. The 'data' properties turn into
435 * 'data-offset' properties.
437 * This function cannot cope with FITs with 'data-offset' properties. All
438 * data must be in 'data' properties on entry.
440 static int fit_extract_data(struct image_tool_params *params, const char *fname)
444 int fit_size, new_size;
454 align_size = params->bl_len ? params->bl_len : 4;
455 fd = mmap_fdt(params->cmdname, fname, 0, &fdt, &sbuf, false, false);
458 fit_size = fdt_totalsize(fdt);
460 images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
462 debug("%s: Cannot find /images node: %d\n", __func__, images);
466 image_number = fdtdec_get_child_count(fdt, images);
469 * Allocate space to hold the image data we will extract,
470 * extral space allocate for image alignment to prevent overflow.
472 buf = calloc(1, fit_size + (align_size * image_number));
479 for (node = fdt_first_subnode(fdt, images);
481 node = fdt_next_subnode(fdt, node)) {
485 data = fdt_getprop(fdt, node, FIT_DATA_PROP, &len);
488 memcpy(buf + buf_ptr, data, len);
489 debug("Extracting data size %x\n", len);
491 ret = fdt_delprop(fdt, node, FIT_DATA_PROP);
496 if (params->external_offset > 0) {
497 /* An external offset positions the data absolutely. */
498 fdt_setprop_u32(fdt, node, FIT_DATA_POSITION_PROP,
499 params->external_offset + buf_ptr);
501 fdt_setprop_u32(fdt, node, FIT_DATA_OFFSET_PROP,
504 fdt_setprop_u32(fdt, node, FIT_DATA_SIZE_PROP, len);
505 buf_ptr += ALIGN(len, align_size);
508 /* Pack the FDT and place the data after it */
511 new_size = fdt_totalsize(fdt);
512 new_size = ALIGN(new_size, align_size);
513 fdt_set_totalsize(fdt, new_size);
514 debug("Size reduced from %x to %x\n", fit_size, fdt_totalsize(fdt));
515 debug("External data size %x\n", buf_ptr);
516 munmap(fdt, sbuf.st_size);
518 if (ftruncate(fd, new_size)) {
519 debug("%s: Failed to truncate file: %s\n", __func__,
525 /* Check if an offset for the external data was set. */
526 if (params->external_offset > 0) {
527 if (params->external_offset < new_size) {
529 "External offset %x overlaps FIT length %x\n",
530 params->external_offset, new_size);
534 new_size = params->external_offset;
536 if (lseek(fd, new_size, SEEK_SET) < 0) {
537 debug("%s: Failed to seek to end of file: %s\n", __func__,
542 if (write(fd, buf, buf_ptr) != buf_ptr) {
543 debug("%s: Failed to write external data to file %s\n",
544 __func__, strerror(errno));
553 munmap(fdt, sbuf.st_size);
560 static int fit_import_data(struct image_tool_params *params, const char *fname)
563 int fit_size, new_size, size, data_base;
570 fd = mmap_fdt(params->cmdname, fname, 0, &old_fdt, &sbuf, false, false);
573 fit_size = fdt_totalsize(old_fdt);
574 data_base = ALIGN(fit_size, 4);
576 /* Allocate space to hold the new FIT */
577 size = sbuf.st_size + 16384;
578 fdt = calloc(1, size);
580 fprintf(stderr, "%s: Failed to allocate memory (%d bytes)\n",
585 ret = fdt_open_into(old_fdt, fdt, size);
587 debug("%s: Failed to expand FIT: %s\n", __func__,
588 fdt_strerror(errno));
593 images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
595 debug("%s: Cannot find /images node: %d\n", __func__, images);
600 for (node = fdt_first_subnode(fdt, images);
602 node = fdt_next_subnode(fdt, node)) {
606 buf_ptr = fdtdec_get_int(fdt, node, "data-offset", -1);
607 len = fdtdec_get_int(fdt, node, "data-size", -1);
608 if (buf_ptr == -1 || len == -1)
610 debug("Importing data size %x\n", len);
612 ret = fdt_setprop(fdt, node, "data",
613 old_fdt + data_base + buf_ptr, len);
615 debug("%s: Failed to write property: %s\n", __func__,
622 munmap(old_fdt, sbuf.st_size);
624 /* Close the old fd so we can re-use it. */
627 /* Pack the FDT and place the data after it */
630 new_size = fdt_totalsize(fdt);
631 debug("Size expanded from %x to %x\n", fit_size, new_size);
633 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
635 fprintf(stderr, "%s: Can't open %s: %s\n",
636 params->cmdname, fname, strerror(errno));
640 if (write(fd, fdt, new_size) != new_size) {
641 debug("%s: Failed to write external data to file %s\n",
642 __func__, strerror(errno));
652 munmap(old_fdt, sbuf.st_size);
659 static int copyfile(const char *src, const char *dst)
661 int fd_src = -1, fd_dst = -1;
667 fd_src = open(src, O_RDONLY);
669 printf("Can't open file %s (%s)\n", src, strerror(errno));
673 fd_dst = open(dst, O_WRONLY | O_CREAT, 0666);
675 printf("Can't open file %s (%s)\n", dst, strerror(errno));
679 buf = calloc(1, 512);
681 printf("Can't allocate buffer to copy file\n");
686 size = read(fd_src, buf, 512);
688 printf("Can't read file %s\n", src);
695 size = write(fd_dst, buf, count);
697 printf("Can't write file %s\n", dst);
716 * fit_handle_file - main FIT file processing function
718 * fit_handle_file() runs dtc to convert .its to .itb, includes
719 * binary data, updates timestamp property and calculates hashes.
721 * datafile - .its file
722 * imagefile - .itb file
725 * only on success, otherwise calls exit (EXIT_FAILURE);
727 static int fit_handle_file(struct image_tool_params *params)
729 char tmpfile[MKIMAGE_MAX_TMPFILE_LEN];
730 char bakfile[MKIMAGE_MAX_TMPFILE_LEN + 4] = {0};
731 char cmd[MKIMAGE_MAX_DTC_CMDLINE_LEN];
735 /* Flattened Image Tree (FIT) format handling */
736 debug ("FIT format handling\n");
738 /* call dtc to include binary properties into the tmp file */
739 if (strlen (params->imagefile) +
740 strlen (MKIMAGE_TMPFILE_SUFFIX) + 1 > sizeof (tmpfile)) {
741 fprintf (stderr, "%s: Image file name (%s) too long, "
742 "can't create tmpfile.\n",
743 params->imagefile, params->cmdname);
744 return (EXIT_FAILURE);
746 sprintf (tmpfile, "%s%s", params->imagefile, MKIMAGE_TMPFILE_SUFFIX);
748 /* We either compile the source file, or use the existing FIT image */
749 if (params->auto_its) {
750 if (fit_build(params, tmpfile)) {
751 fprintf(stderr, "%s: failed to build FIT\n",
756 } else if (params->datafile) {
757 /* dtc -I dts -O dtb -p 500 -o tmpfile datafile */
758 snprintf(cmd, sizeof(cmd), "%s %s -o \"%s\" \"%s\"",
759 MKIMAGE_DTC, params->dtc, tmpfile, params->datafile);
760 debug("Trying to execute \"%s\"\n", cmd);
762 snprintf(cmd, sizeof(cmd), "cp \"%s\" \"%s\"",
763 params->imagefile, tmpfile);
765 if (strlen(cmd) >= MKIMAGE_MAX_DTC_CMDLINE_LEN - 1) {
766 fprintf(stderr, "WARNING: command-line for FIT creation might be truncated and will probably fail.\n");
769 if (*cmd && system(cmd) == -1) {
770 fprintf (stderr, "%s: system(%s) failed: %s\n",
771 params->cmdname, cmd, strerror(errno));
775 /* Move the data so it is internal to the FIT, if needed */
776 ret = fit_import_data(params, tmpfile);
781 * Copy the tmpfile to bakfile, then in the following loop
782 * we copy bakfile to tmpfile. So we always start from the
785 sprintf(bakfile, "%s%s", tmpfile, ".bak");
786 rename(tmpfile, bakfile);
789 * Set hashes for images in the blob. Unfortunately we may need more
790 * space in either FDT, so keep trying until we succeed.
792 * Note: this is pretty inefficient for signing, since we must
793 * calculate the signature every time. It would be better to calculate
794 * all the data and then store it in a separate step. However, this
795 * would be considerably more complex to implement. Generally a few
796 * steps of this loop is enough to sign with several keys.
798 for (size_inc = 0; size_inc < 64 * 1024; size_inc += 1024) {
799 if (copyfile(bakfile, tmpfile) < 0) {
800 printf("Can't copy %s to %s\n", bakfile, tmpfile);
804 ret = fit_add_file_data(params, size_inc, tmpfile);
805 if (!ret || ret != -ENOSPC)
810 fprintf(stderr, "%s Can't add hashes to FIT blob: %d\n",
811 params->cmdname, ret);
815 /* Move the data so it is external to the FIT, if requested */
816 if (params->external_data) {
817 ret = fit_extract_data(params, tmpfile);
822 if (rename (tmpfile, params->imagefile) == -1) {
823 fprintf (stderr, "%s: Can't rename %s to %s: %s\n",
824 params->cmdname, tmpfile, params->imagefile,
828 unlink (params->imagefile);
841 * fit_image_extract - extract a FIT component image
842 * @fit: pointer to the FIT format image header
843 * @image_noffset: offset of the component image node
844 * @file_name: name of the file to store the FIT sub-image
847 * zero in case of success or a negative value if fail.
849 static int fit_image_extract(
852 const char *file_name)
854 const void *file_data;
855 size_t file_size = 0;
858 /* get the data address and size of component at offset "image_noffset" */
859 ret = fit_image_get_data_and_size(fit, image_noffset, &file_data, &file_size);
861 fprintf(stderr, "Could not get component information\n");
865 /* save the "file_data" into the file specified by "file_name" */
866 return imagetool_save_subimage(file_name, (ulong) file_data, file_size);
870 * fit_extract_contents - retrieve a sub-image component from the FIT image
871 * @ptr: pointer to the FIT format image header
872 * @params: command line parameters
875 * zero in case of success or a negative value if fail.
877 static int fit_extract_contents(void *ptr, struct image_tool_params *params)
882 const void *fit = ptr;
886 /* Indent string is defined in header image.h */
887 p = IMAGE_INDENT_STRING;
889 /* Find images parent node offset */
890 images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
891 if (images_noffset < 0) {
892 printf("Can't find images parent node '%s' (%s)\n",
893 FIT_IMAGES_PATH, fdt_strerror(images_noffset));
897 /* Avoid any overrun */
898 count = fit_get_subimage_count(fit, images_noffset);
899 if ((params->pflag < 0) || (count <= params->pflag)) {
900 printf("No such component at '%d'\n", params->pflag);
904 /* Process its subnodes, extract the desired component from image */
905 for (ndepth = 0, count = 0,
906 noffset = fdt_next_node(fit, images_noffset, &ndepth);
907 (noffset >= 0) && (ndepth > 0);
908 noffset = fdt_next_node(fit, noffset, &ndepth)) {
911 * Direct child node of the images parent node,
912 * i.e. component image node.
914 if (params->pflag == count) {
915 printf("Extracted:\n%s Image %u (%s)\n", p,
916 count, fit_get_name(fit, noffset, NULL));
918 fit_image_print(fit, noffset, p);
920 return fit_image_extract(fit, noffset,
931 static int fit_check_params(struct image_tool_params *params)
933 if (params->auto_its)
935 return ((params->dflag && params->fflag) ||
936 (params->fflag && params->lflag) ||
937 (params->lflag && params->dflag));
943 sizeof(image_header_t),
949 fit_extract_contents,
950 fit_check_image_types,
952 NULL /* FIT images use DTB header */