1 // SPDX-License-Identifier: GPL-2.0+
3 * (C) Copyright 2008 Semihalf
5 * (C) Copyright 2000-2004
6 * DENX Software Engineering
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 struct legacy_img_hdr 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,
40 fprintf(stderr, "Cannot map FDT file '%s'\n", tmpfile);
44 if (params->keydest) {
45 struct stat dest_sbuf;
47 destfd = mmap_fdt(params->cmdname, params->keydest, size_inc,
48 &dest_blob, &dest_sbuf, false,
54 destfd_size = dest_sbuf.st_size;
57 /* for first image creation, add a timestamp at offset 0 i.e., root */
58 if (params->datafile || params->reset_timestamp) {
59 time_t time = imagetool_get_source_date(params->cmdname,
61 ret = fit_set_timestamp(ptr, 0, time);
65 ret = fit_pre_load_data(params->keydir, dest_blob, ptr);
68 ret = fit_cipher_data(params->keydir, dest_blob, ptr,
76 ret = fit_add_verification_data(params->keydir,
77 params->keyfile, dest_blob, ptr,
87 munmap(dest_blob, destfd_size);
92 munmap(ptr, sbuf.st_size);
98 * fit_calc_size() - Calculate the approximate size of the FIT we will generate
100 static int fit_calc_size(struct image_tool_params *params)
102 struct content_info *cont;
103 int size, total_size;
105 size = imagetool_get_filesize(params, params->datafile);
110 if (params->fit_ramdisk) {
111 size = imagetool_get_filesize(params, params->fit_ramdisk);
117 for (cont = params->content_head; cont; cont = cont->next) {
118 size = imagetool_get_filesize(params, cont->fname);
122 /* Add space for properties and hash node */
123 total_size += size + 300;
126 /* Add plenty of space for headers, properties, nodes, etc. */
132 static int fdt_property_file(struct image_tool_params *params,
133 void *fdt, const char *name, const char *fname)
140 fd = open(fname, O_RDWR | O_BINARY);
142 fprintf(stderr, "%s: Can't open %s: %s\n",
143 params->cmdname, fname, strerror(errno));
147 if (fstat(fd, &sbuf) < 0) {
148 fprintf(stderr, "%s: Can't stat %s: %s\n",
149 params->cmdname, fname, strerror(errno));
153 ret = fdt_property_placeholder(fdt, "data", sbuf.st_size, &ptr);
156 ret = read(fd, ptr, sbuf.st_size);
157 if (ret != sbuf.st_size) {
158 fprintf(stderr, "%s: Can't read %s: %s\n",
159 params->cmdname, fname, strerror(errno));
170 static int fdt_property_strf(void *fdt, const char *name, const char *fmt, ...)
176 vsnprintf(str, sizeof(str), fmt, ptr);
178 return fdt_property_string(fdt, name, str);
181 static void get_basename(char *str, int size, const char *fname)
183 const char *p, *start, *end;
187 * Use the base name as the 'name' field. So for example:
189 * "arch/arm/dts/sun7i-a20-bananapro.dtb"
190 * becomes "sun7i-a20-bananapro"
192 p = strrchr(fname, '/');
193 start = p ? p + 1 : fname;
194 p = strrchr(fname, '.');
195 end = p ? p : fname + strlen(fname);
199 memcpy(str, start, len);
204 * add_hash_node() - Add a hash or signature node
206 * @params: Image parameters
207 * @fdt: Device tree to add to (in sequential-write mode)
209 * If there is a key name hint, try to sign the images. Otherwise, just add a
212 * Return: 0 on success, or -1 on failure
214 static int add_hash_node(struct image_tool_params *params, void *fdt)
216 if (params->keyname) {
217 if (!params->algo_name) {
219 "%s: Algorithm name must be specified\n",
224 fdt_begin_node(fdt, "signature-1");
225 fdt_property_string(fdt, FIT_ALGO_PROP, params->algo_name);
226 fdt_property_string(fdt, FIT_KEY_HINT, params->keyname);
228 fdt_begin_node(fdt, "hash-1");
229 fdt_property_string(fdt, FIT_ALGO_PROP, "crc32");
237 * fit_write_images() - Write out a list of images to the FIT
239 * We always include the main image (params->datafile). If there are device
240 * tree files, we include an fdt- node for each of those too.
242 static int fit_write_images(struct image_tool_params *params, char *fdt)
244 struct content_info *cont;
245 const char *typename;
250 fdt_begin_node(fdt, "images");
252 /* First the main image */
253 typename = genimg_get_type_short_name(params->fit_image_type);
254 snprintf(str, sizeof(str), "%s-1", typename);
255 fdt_begin_node(fdt, str);
256 fdt_property_string(fdt, FIT_DESC_PROP, params->imagename);
257 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
258 fdt_property_string(fdt, FIT_ARCH_PROP,
259 genimg_get_arch_short_name(params->arch));
260 fdt_property_string(fdt, FIT_OS_PROP,
261 genimg_get_os_short_name(params->os));
262 fdt_property_string(fdt, FIT_COMP_PROP,
263 genimg_get_comp_short_name(params->comp));
264 fdt_property_u32(fdt, FIT_LOAD_PROP, params->addr);
265 fdt_property_u32(fdt, FIT_ENTRY_PROP, params->ep);
268 * Put data last since it is large. SPL may only load the first part
269 * of the DT, so this way it can access all the above fields.
271 ret = fdt_property_file(params, fdt, FIT_DATA_PROP, params->datafile);
274 ret = add_hash_node(params, fdt);
279 /* Now the device tree files if available */
281 for (cont = params->content_head; cont; cont = cont->next) {
282 if (cont->type != IH_TYPE_FLATDT)
284 typename = genimg_get_type_short_name(cont->type);
285 snprintf(str, sizeof(str), "%s-%d", FIT_FDT_PROP, ++upto);
286 fdt_begin_node(fdt, str);
288 get_basename(str, sizeof(str), cont->fname);
289 fdt_property_string(fdt, FIT_DESC_PROP, str);
290 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
294 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
295 fdt_property_string(fdt, FIT_ARCH_PROP,
296 genimg_get_arch_short_name(params->arch));
297 fdt_property_string(fdt, FIT_COMP_PROP,
298 genimg_get_comp_short_name(IH_COMP_NONE));
299 ret = add_hash_node(params, fdt);
305 /* And a ramdisk file if available */
306 if (params->fit_ramdisk) {
307 fdt_begin_node(fdt, FIT_RAMDISK_PROP "-1");
309 fdt_property_string(fdt, FIT_TYPE_PROP, FIT_RAMDISK_PROP);
310 fdt_property_string(fdt, FIT_OS_PROP,
311 genimg_get_os_short_name(params->os));
312 fdt_property_string(fdt, FIT_ARCH_PROP,
313 genimg_get_arch_short_name(params->arch));
315 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
316 params->fit_ramdisk);
319 ret = add_hash_node(params, fdt);
331 * fit_write_configs() - Write out a list of configurations to the FIT
333 * If there are device tree files, we include a configuration for each, which
334 * selects the main image (params->datafile) and its corresponding device
337 * Otherwise we just create a configuration with the main image in it.
339 static void fit_write_configs(struct image_tool_params *params, char *fdt)
341 struct content_info *cont;
342 const char *typename;
346 fdt_begin_node(fdt, "configurations");
347 fdt_property_string(fdt, FIT_DEFAULT_PROP, "conf-1");
350 for (cont = params->content_head; cont; cont = cont->next) {
351 if (cont->type != IH_TYPE_FLATDT)
353 typename = genimg_get_type_short_name(cont->type);
354 snprintf(str, sizeof(str), "conf-%d", ++upto);
355 fdt_begin_node(fdt, str);
357 get_basename(str, sizeof(str), cont->fname);
358 fdt_property_string(fdt, FIT_DESC_PROP, str);
360 typename = genimg_get_type_short_name(params->fit_image_type);
361 snprintf(str, sizeof(str), "%s-1", typename);
362 fdt_property_string(fdt, typename, str);
363 fdt_property_string(fdt, FIT_LOADABLE_PROP, str);
365 if (params->fit_ramdisk)
366 fdt_property_string(fdt, FIT_RAMDISK_PROP,
367 FIT_RAMDISK_PROP "-1");
369 snprintf(str, sizeof(str), FIT_FDT_PROP "-%d", upto);
370 fdt_property_string(fdt, FIT_FDT_PROP, str);
375 fdt_begin_node(fdt, "conf-1");
376 typename = genimg_get_type_short_name(params->fit_image_type);
377 snprintf(str, sizeof(str), "%s-1", typename);
378 fdt_property_string(fdt, typename, str);
380 if (params->fit_ramdisk)
381 fdt_property_string(fdt, FIT_RAMDISK_PROP,
382 FIT_RAMDISK_PROP "-1");
390 static int fit_build_fdt(struct image_tool_params *params, char *fdt, int size)
394 ret = fdt_create(fdt, size);
397 fdt_finish_reservemap(fdt);
398 fdt_begin_node(fdt, "");
399 fdt_property_strf(fdt, FIT_DESC_PROP,
400 "%s image with one or more FDT blobs",
401 genimg_get_type_name(params->fit_image_type));
402 fdt_property_strf(fdt, "creator", "U-Boot mkimage %s", PLAIN_VERSION);
403 fdt_property_u32(fdt, "#address-cells", 1);
404 ret = fit_write_images(params, fdt);
407 fit_write_configs(params, fdt);
409 ret = fdt_finish(fdt);
413 return fdt_totalsize(fdt);
416 static int fit_build(struct image_tool_params *params, const char *fname)
423 size = fit_calc_size(params);
426 buf = calloc(1, size);
428 fprintf(stderr, "%s: Out of memory (%d bytes)\n",
429 params->cmdname, size);
432 ret = fit_build_fdt(params, buf, size);
434 fprintf(stderr, "%s: Failed to build FIT image\n",
439 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
441 fprintf(stderr, "%s: Can't open %s: %s\n",
442 params->cmdname, fname, strerror(errno));
445 ret = write(fd, buf, size);
447 fprintf(stderr, "%s: Can't write %s: %s\n",
448 params->cmdname, fname, strerror(errno));
463 * fit_extract_data() - Move all data outside the FIT
465 * This takes a normal FIT file and removes all the 'data' properties from it.
466 * The data is placed in an area after the FIT so that it can be accessed
467 * using an offset into that area. The 'data' properties turn into
468 * 'data-offset' properties.
470 * This function cannot cope with FITs with 'data-offset' properties. All
471 * data must be in 'data' properties on entry.
473 static int fit_extract_data(struct image_tool_params *params, const char *fname)
477 int fit_size, new_size;
487 align_size = params->bl_len ? params->bl_len : 4;
488 fd = mmap_fdt(params->cmdname, fname, 0, &fdt, &sbuf, false, false);
491 fit_size = fdt_totalsize(fdt);
493 images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
495 debug("%s: Cannot find /images node: %d\n", __func__, images);
499 image_number = fdtdec_get_child_count(fdt, images);
502 * Allocate space to hold the image data we will extract,
503 * extral space allocate for image alignment to prevent overflow.
505 buf = calloc(1, fit_size + (align_size * image_number));
512 for (node = fdt_first_subnode(fdt, images);
514 node = fdt_next_subnode(fdt, node)) {
518 data = fdt_getprop(fdt, node, FIT_DATA_PROP, &len);
521 memcpy(buf + buf_ptr, data, len);
522 debug("Extracting data size %x\n", len);
524 ret = fdt_delprop(fdt, node, FIT_DATA_PROP);
529 if (params->external_offset > 0) {
530 /* An external offset positions the data absolutely. */
531 fdt_setprop_u32(fdt, node, FIT_DATA_POSITION_PROP,
532 params->external_offset + buf_ptr);
534 fdt_setprop_u32(fdt, node, FIT_DATA_OFFSET_PROP,
537 fdt_setprop_u32(fdt, node, FIT_DATA_SIZE_PROP, len);
538 buf_ptr += ALIGN(len, align_size);
541 /* Pack the FDT and place the data after it */
544 new_size = fdt_totalsize(fdt);
545 new_size = ALIGN(new_size, align_size);
546 fdt_set_totalsize(fdt, new_size);
547 debug("Size reduced from %x to %x\n", fit_size, fdt_totalsize(fdt));
548 debug("External data size %x\n", buf_ptr);
549 munmap(fdt, sbuf.st_size);
551 if (ftruncate(fd, new_size)) {
552 debug("%s: Failed to truncate file: %s\n", __func__,
558 /* Check if an offset for the external data was set. */
559 if (params->external_offset > 0) {
560 if (params->external_offset < new_size) {
562 "External offset %x overlaps FIT length %x\n",
563 params->external_offset, new_size);
567 new_size = params->external_offset;
569 if (lseek(fd, new_size, SEEK_SET) < 0) {
570 debug("%s: Failed to seek to end of file: %s\n", __func__,
575 if (write(fd, buf, buf_ptr) != buf_ptr) {
576 debug("%s: Failed to write external data to file %s\n",
577 __func__, strerror(errno));
586 munmap(fdt, sbuf.st_size);
593 static int fit_import_data(struct image_tool_params *params, const char *fname)
596 int fit_size, new_size, size, data_base;
603 fd = mmap_fdt(params->cmdname, fname, 0, &old_fdt, &sbuf, false, false);
606 fit_size = fdt_totalsize(old_fdt);
607 data_base = ALIGN(fit_size, 4);
609 /* Allocate space to hold the new FIT */
610 size = sbuf.st_size + 16384;
611 fdt = calloc(1, size);
613 fprintf(stderr, "%s: Failed to allocate memory (%d bytes)\n",
618 ret = fdt_open_into(old_fdt, fdt, size);
620 debug("%s: Failed to expand FIT: %s\n", __func__,
621 fdt_strerror(errno));
626 images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
628 debug("%s: Cannot find /images node: %d\n", __func__, images);
633 for (node = fdt_first_subnode(fdt, images);
635 node = fdt_next_subnode(fdt, node)) {
639 buf_ptr = fdtdec_get_int(fdt, node, "data-offset", -1);
640 len = fdtdec_get_int(fdt, node, "data-size", -1);
641 if (buf_ptr == -1 || len == -1)
643 debug("Importing data size %x\n", len);
645 ret = fdt_setprop(fdt, node, "data",
646 old_fdt + data_base + buf_ptr, len);
648 debug("%s: Failed to write property: %s\n", __func__,
655 munmap(old_fdt, sbuf.st_size);
657 /* Close the old fd so we can re-use it. */
660 /* Pack the FDT and place the data after it */
663 new_size = fdt_totalsize(fdt);
664 debug("Size expanded from %x to %x\n", fit_size, new_size);
666 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
668 fprintf(stderr, "%s: Can't open %s: %s\n",
669 params->cmdname, fname, strerror(errno));
673 if (write(fd, fdt, new_size) != new_size) {
674 debug("%s: Failed to write external data to file %s\n",
675 __func__, strerror(errno));
685 munmap(old_fdt, sbuf.st_size);
693 * fit_handle_file - main FIT file processing function
695 * fit_handle_file() runs dtc to convert .its to .itb, includes
696 * binary data, updates timestamp property and calculates hashes.
698 * datafile - .its file
699 * imagefile - .itb file
702 * only on success, otherwise calls exit (EXIT_FAILURE);
704 static int fit_handle_file(struct image_tool_params *params)
706 char tmpfile[MKIMAGE_MAX_TMPFILE_LEN];
707 char bakfile[MKIMAGE_MAX_TMPFILE_LEN + 4] = {0};
708 char cmd[MKIMAGE_MAX_DTC_CMDLINE_LEN];
712 /* Flattened Image Tree (FIT) format handling */
713 debug ("FIT format handling\n");
715 /* call dtc to include binary properties into the tmp file */
716 if (strlen (params->imagefile) +
717 strlen (MKIMAGE_TMPFILE_SUFFIX) + 1 > sizeof (tmpfile)) {
718 fprintf (stderr, "%s: Image file name (%s) too long, "
719 "can't create tmpfile.\n",
720 params->imagefile, params->cmdname);
721 return (EXIT_FAILURE);
723 sprintf (tmpfile, "%s%s", params->imagefile, MKIMAGE_TMPFILE_SUFFIX);
725 /* We either compile the source file, or use the existing FIT image */
726 if (params->auto_its) {
727 if (fit_build(params, tmpfile)) {
728 fprintf(stderr, "%s: failed to build FIT\n",
733 } else if (params->datafile) {
734 /* dtc -I dts -O dtb -p 500 -o tmpfile datafile */
735 snprintf(cmd, sizeof(cmd), "%s %s -o \"%s\" \"%s\"",
736 MKIMAGE_DTC, params->dtc, tmpfile, params->datafile);
737 debug("Trying to execute \"%s\"\n", cmd);
739 snprintf(cmd, sizeof(cmd), "cp \"%s\" \"%s\"",
740 params->imagefile, tmpfile);
742 if (strlen(cmd) >= MKIMAGE_MAX_DTC_CMDLINE_LEN - 1) {
743 fprintf(stderr, "WARNING: command-line for FIT creation might be truncated and will probably fail.\n");
746 if (*cmd && system(cmd) == -1) {
747 fprintf (stderr, "%s: system(%s) failed: %s\n",
748 params->cmdname, cmd, strerror(errno));
752 /* Move the data so it is internal to the FIT, if needed */
753 ret = fit_import_data(params, tmpfile);
758 * Copy the tmpfile to bakfile, then in the following loop
759 * we copy bakfile to tmpfile. So we always start from the
762 sprintf(bakfile, "%s%s", tmpfile, ".bak");
763 rename(tmpfile, bakfile);
766 * Set hashes for images in the blob. Unfortunately we may need more
767 * space in either FDT, so keep trying until we succeed.
769 * Note: this is pretty inefficient for signing, since we must
770 * calculate the signature every time. It would be better to calculate
771 * all the data and then store it in a separate step. However, this
772 * would be considerably more complex to implement. Generally a few
773 * steps of this loop is enough to sign with several keys.
775 for (size_inc = 0; size_inc < 64 * 1024; size_inc += 1024) {
776 if (copyfile(bakfile, tmpfile) < 0) {
777 printf("Can't copy %s to %s\n", bakfile, tmpfile);
781 ret = fit_add_file_data(params, size_inc, tmpfile);
782 if (!ret || ret != -ENOSPC)
787 fprintf(stderr, "%s Can't add hashes to FIT blob: %d\n",
788 params->cmdname, ret);
792 /* Move the data so it is external to the FIT, if requested */
793 if (params->external_data) {
794 ret = fit_extract_data(params, tmpfile);
799 if (rename (tmpfile, params->imagefile) == -1) {
800 fprintf (stderr, "%s: Can't rename %s to %s: %s\n",
801 params->cmdname, tmpfile, params->imagefile,
805 unlink (params->imagefile);
818 * fit_image_extract - extract a FIT component image
819 * @fit: pointer to the FIT format image header
820 * @image_noffset: offset of the component image node
821 * @file_name: name of the file to store the FIT sub-image
824 * zero in case of success or a negative value if fail.
826 static int fit_image_extract(
829 const char *file_name)
831 const void *file_data;
832 size_t file_size = 0;
835 /* get the data address and size of component at offset "image_noffset" */
836 ret = fit_image_get_data_and_size(fit, image_noffset, &file_data, &file_size);
838 fprintf(stderr, "Could not get component information\n");
842 /* save the "file_data" into the file specified by "file_name" */
843 return imagetool_save_subimage(file_name, (ulong) file_data, file_size);
847 * fit_extract_contents - retrieve a sub-image component from the FIT image
848 * @ptr: pointer to the FIT format image header
849 * @params: command line parameters
852 * zero in case of success or a negative value if fail.
854 static int fit_extract_contents(void *ptr, struct image_tool_params *params)
859 const void *fit = ptr;
863 /* Indent string is defined in header image.h */
864 p = IMAGE_INDENT_STRING;
866 /* Find images parent node offset */
867 images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
868 if (images_noffset < 0) {
869 printf("Can't find images parent node '%s' (%s)\n",
870 FIT_IMAGES_PATH, fdt_strerror(images_noffset));
874 /* Avoid any overrun */
875 count = fit_get_subimage_count(fit, images_noffset);
876 if ((params->pflag < 0) || (count <= params->pflag)) {
877 printf("No such component at '%d'\n", params->pflag);
881 /* Process its subnodes, extract the desired component from image */
882 for (ndepth = 0, count = 0,
883 noffset = fdt_next_node(fit, images_noffset, &ndepth);
884 (noffset >= 0) && (ndepth > 0);
885 noffset = fdt_next_node(fit, noffset, &ndepth)) {
888 * Direct child node of the images parent node,
889 * i.e. component image node.
891 if (params->pflag == count) {
892 printf("Extracted:\n%s Image %u (%s)\n", p,
893 count, fit_get_name(fit, noffset, NULL));
895 fit_image_print(fit, noffset, p);
897 return fit_image_extract(fit, noffset,
908 static int fit_check_params(struct image_tool_params *params)
910 if (params->auto_its)
912 return ((params->dflag && params->fflag) ||
913 (params->fflag && params->lflag) ||
914 (params->lflag && params->dflag));
920 sizeof(struct legacy_img_hdr),
926 fit_extract_contents,
927 fit_check_image_types,
929 NULL /* FIT images use DTB header */