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 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_pre_load_data(params->keydir, dest_blob, ptr);
66 ret = fit_cipher_data(params->keydir, dest_blob, ptr,
74 ret = fit_add_verification_data(params->keydir,
75 params->keyfile, dest_blob, ptr,
85 munmap(dest_blob, destfd_size);
90 munmap(ptr, sbuf.st_size);
96 * fit_calc_size() - Calculate the approximate size of the FIT we will generate
98 static int fit_calc_size(struct image_tool_params *params)
100 struct content_info *cont;
101 int size, total_size;
103 size = imagetool_get_filesize(params, params->datafile);
108 if (params->fit_ramdisk) {
109 size = imagetool_get_filesize(params, params->fit_ramdisk);
115 for (cont = params->content_head; cont; cont = cont->next) {
116 size = imagetool_get_filesize(params, cont->fname);
120 /* Add space for properties and hash node */
121 total_size += size + 300;
124 /* Add plenty of space for headers, properties, nodes, etc. */
130 static int fdt_property_file(struct image_tool_params *params,
131 void *fdt, const char *name, const char *fname)
138 fd = open(fname, O_RDWR | O_BINARY);
140 fprintf(stderr, "%s: Can't open %s: %s\n",
141 params->cmdname, fname, strerror(errno));
145 if (fstat(fd, &sbuf) < 0) {
146 fprintf(stderr, "%s: Can't stat %s: %s\n",
147 params->cmdname, fname, strerror(errno));
151 ret = fdt_property_placeholder(fdt, "data", sbuf.st_size, &ptr);
154 ret = read(fd, ptr, sbuf.st_size);
155 if (ret != sbuf.st_size) {
156 fprintf(stderr, "%s: Can't read %s: %s\n",
157 params->cmdname, fname, strerror(errno));
168 static int fdt_property_strf(void *fdt, const char *name, const char *fmt, ...)
174 vsnprintf(str, sizeof(str), fmt, ptr);
176 return fdt_property_string(fdt, name, str);
179 static void get_basename(char *str, int size, const char *fname)
181 const char *p, *start, *end;
185 * Use the base name as the 'name' field. So for example:
187 * "arch/arm/dts/sun7i-a20-bananapro.dtb"
188 * becomes "sun7i-a20-bananapro"
190 p = strrchr(fname, '/');
191 start = p ? p + 1 : fname;
192 p = strrchr(fname, '.');
193 end = p ? p : fname + strlen(fname);
197 memcpy(str, start, len);
202 * add_crc_node() - Add a hash node to request a CRC checksum for an image
204 * @fdt: Device tree to add to (in sequential-write mode)
206 static void add_crc_node(void *fdt)
208 fdt_begin_node(fdt, "hash-1");
209 fdt_property_string(fdt, FIT_ALGO_PROP, "crc32");
214 * fit_write_images() - Write out a list of images to the FIT
216 * We always include the main image (params->datafile). If there are device
217 * tree files, we include an fdt- node for each of those too.
219 static int fit_write_images(struct image_tool_params *params, char *fdt)
221 struct content_info *cont;
222 const char *typename;
227 fdt_begin_node(fdt, "images");
229 /* First the main image */
230 typename = genimg_get_type_short_name(params->fit_image_type);
231 snprintf(str, sizeof(str), "%s-1", typename);
232 fdt_begin_node(fdt, str);
233 fdt_property_string(fdt, FIT_DESC_PROP, params->imagename);
234 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
235 fdt_property_string(fdt, FIT_ARCH_PROP,
236 genimg_get_arch_short_name(params->arch));
237 fdt_property_string(fdt, FIT_OS_PROP,
238 genimg_get_os_short_name(params->os));
239 fdt_property_string(fdt, FIT_COMP_PROP,
240 genimg_get_comp_short_name(params->comp));
241 fdt_property_u32(fdt, FIT_LOAD_PROP, params->addr);
242 fdt_property_u32(fdt, FIT_ENTRY_PROP, params->ep);
245 * Put data last since it is large. SPL may only load the first part
246 * of the DT, so this way it can access all the above fields.
248 ret = fdt_property_file(params, fdt, FIT_DATA_PROP, params->datafile);
254 /* Now the device tree files if available */
256 for (cont = params->content_head; cont; cont = cont->next) {
257 if (cont->type != IH_TYPE_FLATDT)
259 typename = genimg_get_type_short_name(cont->type);
260 snprintf(str, sizeof(str), "%s-%d", FIT_FDT_PROP, ++upto);
261 fdt_begin_node(fdt, str);
263 get_basename(str, sizeof(str), cont->fname);
264 fdt_property_string(fdt, FIT_DESC_PROP, str);
265 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
269 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
270 fdt_property_string(fdt, FIT_ARCH_PROP,
271 genimg_get_arch_short_name(params->arch));
272 fdt_property_string(fdt, FIT_COMP_PROP,
273 genimg_get_comp_short_name(IH_COMP_NONE));
278 /* And a ramdisk file if available */
279 if (params->fit_ramdisk) {
280 fdt_begin_node(fdt, FIT_RAMDISK_PROP "-1");
282 fdt_property_string(fdt, FIT_TYPE_PROP, FIT_RAMDISK_PROP);
283 fdt_property_string(fdt, FIT_OS_PROP,
284 genimg_get_os_short_name(params->os));
285 fdt_property_string(fdt, FIT_ARCH_PROP,
286 genimg_get_arch_short_name(params->arch));
288 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
289 params->fit_ramdisk);
302 * fit_write_configs() - Write out a list of configurations to the FIT
304 * If there are device tree files, we include a configuration for each, which
305 * selects the main image (params->datafile) and its corresponding device
308 * Otherwise we just create a configuration with the main image in it.
310 static void fit_write_configs(struct image_tool_params *params, char *fdt)
312 struct content_info *cont;
313 const char *typename;
317 fdt_begin_node(fdt, "configurations");
318 fdt_property_string(fdt, FIT_DEFAULT_PROP, "conf-1");
321 for (cont = params->content_head; cont; cont = cont->next) {
322 if (cont->type != IH_TYPE_FLATDT)
324 typename = genimg_get_type_short_name(cont->type);
325 snprintf(str, sizeof(str), "conf-%d", ++upto);
326 fdt_begin_node(fdt, str);
328 get_basename(str, sizeof(str), cont->fname);
329 fdt_property_string(fdt, FIT_DESC_PROP, str);
331 typename = genimg_get_type_short_name(params->fit_image_type);
332 snprintf(str, sizeof(str), "%s-1", typename);
333 fdt_property_string(fdt, typename, str);
334 fdt_property_string(fdt, FIT_LOADABLE_PROP, str);
336 if (params->fit_ramdisk)
337 fdt_property_string(fdt, FIT_RAMDISK_PROP,
338 FIT_RAMDISK_PROP "-1");
340 snprintf(str, sizeof(str), FIT_FDT_PROP "-%d", upto);
341 fdt_property_string(fdt, FIT_FDT_PROP, str);
346 fdt_begin_node(fdt, "conf-1");
347 typename = genimg_get_type_short_name(params->fit_image_type);
348 snprintf(str, sizeof(str), "%s-1", typename);
349 fdt_property_string(fdt, typename, str);
351 if (params->fit_ramdisk)
352 fdt_property_string(fdt, FIT_RAMDISK_PROP,
353 FIT_RAMDISK_PROP "-1");
361 static int fit_build_fdt(struct image_tool_params *params, char *fdt, int size)
365 ret = fdt_create(fdt, size);
368 fdt_finish_reservemap(fdt);
369 fdt_begin_node(fdt, "");
370 fdt_property_strf(fdt, FIT_DESC_PROP,
371 "%s image with one or more FDT blobs",
372 genimg_get_type_name(params->fit_image_type));
373 fdt_property_strf(fdt, "creator", "U-Boot mkimage %s", PLAIN_VERSION);
374 fdt_property_u32(fdt, "#address-cells", 1);
375 ret = fit_write_images(params, fdt);
378 fit_write_configs(params, fdt);
380 ret = fdt_finish(fdt);
384 return fdt_totalsize(fdt);
387 static int fit_build(struct image_tool_params *params, const char *fname)
394 size = fit_calc_size(params);
397 buf = calloc(1, size);
399 fprintf(stderr, "%s: Out of memory (%d bytes)\n",
400 params->cmdname, size);
403 ret = fit_build_fdt(params, buf, size);
405 fprintf(stderr, "%s: Failed to build FIT image\n",
410 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
412 fprintf(stderr, "%s: Can't open %s: %s\n",
413 params->cmdname, fname, strerror(errno));
416 ret = write(fd, buf, size);
418 fprintf(stderr, "%s: Can't write %s: %s\n",
419 params->cmdname, fname, strerror(errno));
434 * fit_extract_data() - Move all data outside the FIT
436 * This takes a normal FIT file and removes all the 'data' properties from it.
437 * The data is placed in an area after the FIT so that it can be accessed
438 * using an offset into that area. The 'data' properties turn into
439 * 'data-offset' properties.
441 * This function cannot cope with FITs with 'data-offset' properties. All
442 * data must be in 'data' properties on entry.
444 static int fit_extract_data(struct image_tool_params *params, const char *fname)
448 int fit_size, new_size;
458 align_size = params->bl_len ? params->bl_len : 4;
459 fd = mmap_fdt(params->cmdname, fname, 0, &fdt, &sbuf, false, false);
462 fit_size = fdt_totalsize(fdt);
464 images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
466 debug("%s: Cannot find /images node: %d\n", __func__, images);
470 image_number = fdtdec_get_child_count(fdt, images);
473 * Allocate space to hold the image data we will extract,
474 * extral space allocate for image alignment to prevent overflow.
476 buf = calloc(1, fit_size + (align_size * image_number));
483 for (node = fdt_first_subnode(fdt, images);
485 node = fdt_next_subnode(fdt, node)) {
489 data = fdt_getprop(fdt, node, FIT_DATA_PROP, &len);
492 memcpy(buf + buf_ptr, data, len);
493 debug("Extracting data size %x\n", len);
495 ret = fdt_delprop(fdt, node, FIT_DATA_PROP);
500 if (params->external_offset > 0) {
501 /* An external offset positions the data absolutely. */
502 fdt_setprop_u32(fdt, node, FIT_DATA_POSITION_PROP,
503 params->external_offset + buf_ptr);
505 fdt_setprop_u32(fdt, node, FIT_DATA_OFFSET_PROP,
508 fdt_setprop_u32(fdt, node, FIT_DATA_SIZE_PROP, len);
509 buf_ptr += ALIGN(len, align_size);
512 /* Pack the FDT and place the data after it */
515 new_size = fdt_totalsize(fdt);
516 new_size = ALIGN(new_size, align_size);
517 fdt_set_totalsize(fdt, new_size);
518 debug("Size reduced from %x to %x\n", fit_size, fdt_totalsize(fdt));
519 debug("External data size %x\n", buf_ptr);
520 munmap(fdt, sbuf.st_size);
522 if (ftruncate(fd, new_size)) {
523 debug("%s: Failed to truncate file: %s\n", __func__,
529 /* Check if an offset for the external data was set. */
530 if (params->external_offset > 0) {
531 if (params->external_offset < new_size) {
533 "External offset %x overlaps FIT length %x\n",
534 params->external_offset, new_size);
538 new_size = params->external_offset;
540 if (lseek(fd, new_size, SEEK_SET) < 0) {
541 debug("%s: Failed to seek to end of file: %s\n", __func__,
546 if (write(fd, buf, buf_ptr) != buf_ptr) {
547 debug("%s: Failed to write external data to file %s\n",
548 __func__, strerror(errno));
557 munmap(fdt, sbuf.st_size);
564 static int fit_import_data(struct image_tool_params *params, const char *fname)
567 int fit_size, new_size, size, data_base;
574 fd = mmap_fdt(params->cmdname, fname, 0, &old_fdt, &sbuf, false, false);
577 fit_size = fdt_totalsize(old_fdt);
578 data_base = ALIGN(fit_size, 4);
580 /* Allocate space to hold the new FIT */
581 size = sbuf.st_size + 16384;
582 fdt = calloc(1, size);
584 fprintf(stderr, "%s: Failed to allocate memory (%d bytes)\n",
589 ret = fdt_open_into(old_fdt, fdt, size);
591 debug("%s: Failed to expand FIT: %s\n", __func__,
592 fdt_strerror(errno));
597 images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
599 debug("%s: Cannot find /images node: %d\n", __func__, images);
604 for (node = fdt_first_subnode(fdt, images);
606 node = fdt_next_subnode(fdt, node)) {
610 buf_ptr = fdtdec_get_int(fdt, node, "data-offset", -1);
611 len = fdtdec_get_int(fdt, node, "data-size", -1);
612 if (buf_ptr == -1 || len == -1)
614 debug("Importing data size %x\n", len);
616 ret = fdt_setprop(fdt, node, "data",
617 old_fdt + data_base + buf_ptr, len);
619 debug("%s: Failed to write property: %s\n", __func__,
626 munmap(old_fdt, sbuf.st_size);
628 /* Close the old fd so we can re-use it. */
631 /* Pack the FDT and place the data after it */
634 new_size = fdt_totalsize(fdt);
635 debug("Size expanded from %x to %x\n", fit_size, new_size);
637 fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
639 fprintf(stderr, "%s: Can't open %s: %s\n",
640 params->cmdname, fname, strerror(errno));
644 if (write(fd, fdt, new_size) != new_size) {
645 debug("%s: Failed to write external data to file %s\n",
646 __func__, strerror(errno));
656 munmap(old_fdt, sbuf.st_size);
664 * fit_handle_file - main FIT file processing function
666 * fit_handle_file() runs dtc to convert .its to .itb, includes
667 * binary data, updates timestamp property and calculates hashes.
669 * datafile - .its file
670 * imagefile - .itb file
673 * only on success, otherwise calls exit (EXIT_FAILURE);
675 static int fit_handle_file(struct image_tool_params *params)
677 char tmpfile[MKIMAGE_MAX_TMPFILE_LEN];
678 char bakfile[MKIMAGE_MAX_TMPFILE_LEN + 4] = {0};
679 char cmd[MKIMAGE_MAX_DTC_CMDLINE_LEN];
683 /* Flattened Image Tree (FIT) format handling */
684 debug ("FIT format handling\n");
686 /* call dtc to include binary properties into the tmp file */
687 if (strlen (params->imagefile) +
688 strlen (MKIMAGE_TMPFILE_SUFFIX) + 1 > sizeof (tmpfile)) {
689 fprintf (stderr, "%s: Image file name (%s) too long, "
690 "can't create tmpfile.\n",
691 params->imagefile, params->cmdname);
692 return (EXIT_FAILURE);
694 sprintf (tmpfile, "%s%s", params->imagefile, MKIMAGE_TMPFILE_SUFFIX);
696 /* We either compile the source file, or use the existing FIT image */
697 if (params->auto_its) {
698 if (fit_build(params, tmpfile)) {
699 fprintf(stderr, "%s: failed to build FIT\n",
704 } else if (params->datafile) {
705 /* dtc -I dts -O dtb -p 500 -o tmpfile datafile */
706 snprintf(cmd, sizeof(cmd), "%s %s -o \"%s\" \"%s\"",
707 MKIMAGE_DTC, params->dtc, tmpfile, params->datafile);
708 debug("Trying to execute \"%s\"\n", cmd);
710 snprintf(cmd, sizeof(cmd), "cp \"%s\" \"%s\"",
711 params->imagefile, tmpfile);
713 if (strlen(cmd) >= MKIMAGE_MAX_DTC_CMDLINE_LEN - 1) {
714 fprintf(stderr, "WARNING: command-line for FIT creation might be truncated and will probably fail.\n");
717 if (*cmd && system(cmd) == -1) {
718 fprintf (stderr, "%s: system(%s) failed: %s\n",
719 params->cmdname, cmd, strerror(errno));
723 /* Move the data so it is internal to the FIT, if needed */
724 ret = fit_import_data(params, tmpfile);
729 * Copy the tmpfile to bakfile, then in the following loop
730 * we copy bakfile to tmpfile. So we always start from the
733 sprintf(bakfile, "%s%s", tmpfile, ".bak");
734 rename(tmpfile, bakfile);
737 * Set hashes for images in the blob. Unfortunately we may need more
738 * space in either FDT, so keep trying until we succeed.
740 * Note: this is pretty inefficient for signing, since we must
741 * calculate the signature every time. It would be better to calculate
742 * all the data and then store it in a separate step. However, this
743 * would be considerably more complex to implement. Generally a few
744 * steps of this loop is enough to sign with several keys.
746 for (size_inc = 0; size_inc < 64 * 1024; size_inc += 1024) {
747 if (copyfile(bakfile, tmpfile) < 0) {
748 printf("Can't copy %s to %s\n", bakfile, tmpfile);
752 ret = fit_add_file_data(params, size_inc, tmpfile);
753 if (!ret || ret != -ENOSPC)
758 fprintf(stderr, "%s Can't add hashes to FIT blob: %d\n",
759 params->cmdname, ret);
763 /* Move the data so it is external to the FIT, if requested */
764 if (params->external_data) {
765 ret = fit_extract_data(params, tmpfile);
770 if (rename (tmpfile, params->imagefile) == -1) {
771 fprintf (stderr, "%s: Can't rename %s to %s: %s\n",
772 params->cmdname, tmpfile, params->imagefile,
776 unlink (params->imagefile);
789 * fit_image_extract - extract a FIT component image
790 * @fit: pointer to the FIT format image header
791 * @image_noffset: offset of the component image node
792 * @file_name: name of the file to store the FIT sub-image
795 * zero in case of success or a negative value if fail.
797 static int fit_image_extract(
800 const char *file_name)
802 const void *file_data;
803 size_t file_size = 0;
806 /* get the data address and size of component at offset "image_noffset" */
807 ret = fit_image_get_data_and_size(fit, image_noffset, &file_data, &file_size);
809 fprintf(stderr, "Could not get component information\n");
813 /* save the "file_data" into the file specified by "file_name" */
814 return imagetool_save_subimage(file_name, (ulong) file_data, file_size);
818 * fit_extract_contents - retrieve a sub-image component from the FIT image
819 * @ptr: pointer to the FIT format image header
820 * @params: command line parameters
823 * zero in case of success or a negative value if fail.
825 static int fit_extract_contents(void *ptr, struct image_tool_params *params)
830 const void *fit = ptr;
834 /* Indent string is defined in header image.h */
835 p = IMAGE_INDENT_STRING;
837 /* Find images parent node offset */
838 images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
839 if (images_noffset < 0) {
840 printf("Can't find images parent node '%s' (%s)\n",
841 FIT_IMAGES_PATH, fdt_strerror(images_noffset));
845 /* Avoid any overrun */
846 count = fit_get_subimage_count(fit, images_noffset);
847 if ((params->pflag < 0) || (count <= params->pflag)) {
848 printf("No such component at '%d'\n", params->pflag);
852 /* Process its subnodes, extract the desired component from image */
853 for (ndepth = 0, count = 0,
854 noffset = fdt_next_node(fit, images_noffset, &ndepth);
855 (noffset >= 0) && (ndepth > 0);
856 noffset = fdt_next_node(fit, noffset, &ndepth)) {
859 * Direct child node of the images parent node,
860 * i.e. component image node.
862 if (params->pflag == count) {
863 printf("Extracted:\n%s Image %u (%s)\n", p,
864 count, fit_get_name(fit, noffset, NULL));
866 fit_image_print(fit, noffset, p);
868 return fit_image_extract(fit, noffset,
879 static int fit_check_params(struct image_tool_params *params)
881 if (params->auto_its)
883 return ((params->dflag && params->fflag) ||
884 (params->fflag && params->lflag) ||
885 (params->lflag && params->dflag));
891 sizeof(image_header_t),
897 fit_extract_contents,
898 fit_check_image_types,
900 NULL /* FIT images use DTB header */