Merge git://git.denx.de/u-boot-usb
[oweals/u-boot.git] / tools / fit_image.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2008 Semihalf
4  *
5  * (C) Copyright 2000-2004
6  * DENX Software Engineering
7  * Wolfgang Denk, wd@denx.de
8  *
9  * Updated-by: Prafulla Wadaskar <prafulla@marvell.com>
10  *              FIT image specific code abstracted from mkimage.c
11  *              some functions added to address abstraction
12  *
13  * All rights reserved.
14  */
15
16 #include "imagetool.h"
17 #include "fit_common.h"
18 #include "mkimage.h"
19 #include <image.h>
20 #include <string.h>
21 #include <stdarg.h>
22 #include <version.h>
23 #include <u-boot/crc.h>
24
25 static image_header_t header;
26
27 static int fit_add_file_data(struct image_tool_params *params, size_t size_inc,
28                              const char *tmpfile)
29 {
30         int tfd, destfd = 0;
31         void *dest_blob = NULL;
32         off_t destfd_size = 0;
33         struct stat sbuf;
34         void *ptr;
35         int ret = 0;
36
37         tfd = mmap_fdt(params->cmdname, tmpfile, size_inc, &ptr, &sbuf, true,
38                        false);
39         if (tfd < 0)
40                 return -EIO;
41
42         if (params->keydest) {
43                 struct stat dest_sbuf;
44
45                 destfd = mmap_fdt(params->cmdname, params->keydest, size_inc,
46                                   &dest_blob, &dest_sbuf, false,
47                                   false);
48                 if (destfd < 0) {
49                         ret = -EIO;
50                         goto err_keydest;
51                 }
52                 destfd_size = dest_sbuf.st_size;
53         }
54
55         /* for first image creation, add a timestamp at offset 0 i.e., root  */
56         if (params->datafile) {
57                 time_t time = imagetool_get_source_date(params->cmdname,
58                                                         sbuf.st_mtime);
59                 ret = fit_set_timestamp(ptr, 0, time);
60         }
61
62         if (!ret) {
63                 ret = fit_cipher_data(params->keydir, dest_blob, ptr,
64                                       params->comment,
65                                       params->require_keys,
66                                       params->engine_id,
67                                       params->cmdname);
68         }
69
70         if (!ret) {
71                 ret = fit_add_verification_data(params->keydir, dest_blob, ptr,
72                                                 params->comment,
73                                                 params->require_keys,
74                                                 params->engine_id,
75                                                 params->cmdname);
76         }
77
78         if (dest_blob) {
79                 munmap(dest_blob, destfd_size);
80                 close(destfd);
81         }
82
83 err_keydest:
84         munmap(ptr, sbuf.st_size);
85         close(tfd);
86         return ret;
87 }
88
89 /**
90  * fit_calc_size() - Calculate the approximate size of the FIT we will generate
91  */
92 static int fit_calc_size(struct image_tool_params *params)
93 {
94         struct content_info *cont;
95         int size, total_size;
96
97         size = imagetool_get_filesize(params, params->datafile);
98         if (size < 0)
99                 return -1;
100         total_size = size;
101
102         if (params->fit_ramdisk) {
103                 size = imagetool_get_filesize(params, params->fit_ramdisk);
104                 if (size < 0)
105                         return -1;
106                 total_size += size;
107         }
108
109         for (cont = params->content_head; cont; cont = cont->next) {
110                 size = imagetool_get_filesize(params, cont->fname);
111                 if (size < 0)
112                         return -1;
113
114                 /* Add space for properties */
115                 total_size += size + 300;
116         }
117
118         /* Add plenty of space for headers, properties, nodes, etc. */
119         total_size += 4096;
120
121         return total_size;
122 }
123
124 static int fdt_property_file(struct image_tool_params *params,
125                              void *fdt, const char *name, const char *fname)
126 {
127         struct stat sbuf;
128         void *ptr;
129         int ret;
130         int fd;
131
132         fd = open(fname, O_RDWR | O_BINARY);
133         if (fd < 0) {
134                 fprintf(stderr, "%s: Can't open %s: %s\n",
135                         params->cmdname, fname, strerror(errno));
136                 return -1;
137         }
138
139         if (fstat(fd, &sbuf) < 0) {
140                 fprintf(stderr, "%s: Can't stat %s: %s\n",
141                         params->cmdname, fname, strerror(errno));
142                 goto err;
143         }
144
145         ret = fdt_property_placeholder(fdt, "data", sbuf.st_size, &ptr);
146         if (ret)
147                 goto err;
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));
152                 goto err;
153         }
154         close(fd);
155
156         return 0;
157 err:
158         close(fd);
159         return -1;
160 }
161
162 static int fdt_property_strf(void *fdt, const char *name, const char *fmt, ...)
163 {
164         char str[100];
165         va_list ptr;
166
167         va_start(ptr, fmt);
168         vsnprintf(str, sizeof(str), fmt, ptr);
169         va_end(ptr);
170         return fdt_property_string(fdt, name, str);
171 }
172
173 static void get_basename(char *str, int size, const char *fname)
174 {
175         const char *p, *start, *end;
176         int len;
177
178         /*
179          * Use the base name as the 'name' field. So for example:
180          *
181          * "arch/arm/dts/sun7i-a20-bananapro.dtb"
182          * becomes "sun7i-a20-bananapro"
183          */
184         p = strrchr(fname, '/');
185         start = p ? p + 1 : fname;
186         p = strrchr(fname, '.');
187         end = p ? p : fname + strlen(fname);
188         len = end - start;
189         if (len >= size)
190                 len = size - 1;
191         memcpy(str, start, len);
192         str[len] = '\0';
193 }
194
195 /**
196  * fit_write_images() - Write out a list of images to the FIT
197  *
198  * We always include the main image (params->datafile). If there are device
199  * tree files, we include an fdt- node for each of those too.
200  */
201 static int fit_write_images(struct image_tool_params *params, char *fdt)
202 {
203         struct content_info *cont;
204         const char *typename;
205         char str[100];
206         int upto;
207         int ret;
208
209         fdt_begin_node(fdt, "images");
210
211         /* First the main image */
212         typename = genimg_get_type_short_name(params->fit_image_type);
213         snprintf(str, sizeof(str), "%s-1", typename);
214         fdt_begin_node(fdt, str);
215         fdt_property_string(fdt, FIT_DESC_PROP, params->imagename);
216         fdt_property_string(fdt, FIT_TYPE_PROP, typename);
217         fdt_property_string(fdt, FIT_ARCH_PROP,
218                             genimg_get_arch_short_name(params->arch));
219         fdt_property_string(fdt, FIT_OS_PROP,
220                             genimg_get_os_short_name(params->os));
221         fdt_property_string(fdt, FIT_COMP_PROP,
222                             genimg_get_comp_short_name(params->comp));
223         fdt_property_u32(fdt, FIT_LOAD_PROP, params->addr);
224         fdt_property_u32(fdt, FIT_ENTRY_PROP, params->ep);
225
226         /*
227          * Put data last since it is large. SPL may only load the first part
228          * of the DT, so this way it can access all the above fields.
229          */
230         ret = fdt_property_file(params, fdt, FIT_DATA_PROP, params->datafile);
231         if (ret)
232                 return ret;
233         fdt_end_node(fdt);
234
235         /* Now the device tree files if available */
236         upto = 0;
237         for (cont = params->content_head; cont; cont = cont->next) {
238                 if (cont->type != IH_TYPE_FLATDT)
239                         continue;
240                 typename = genimg_get_type_short_name(cont->type);
241                 snprintf(str, sizeof(str), "%s-%d", FIT_FDT_PROP, ++upto);
242                 fdt_begin_node(fdt, str);
243
244                 get_basename(str, sizeof(str), cont->fname);
245                 fdt_property_string(fdt, FIT_DESC_PROP, str);
246                 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
247                                         cont->fname);
248                 if (ret)
249                         return ret;
250                 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
251                 fdt_property_string(fdt, FIT_ARCH_PROP,
252                                     genimg_get_arch_short_name(params->arch));
253                 fdt_property_string(fdt, FIT_COMP_PROP,
254                                     genimg_get_comp_short_name(IH_COMP_NONE));
255                 fdt_end_node(fdt);
256         }
257
258         /* And a ramdisk file if available */
259         if (params->fit_ramdisk) {
260                 fdt_begin_node(fdt, FIT_RAMDISK_PROP "-1");
261
262                 fdt_property_string(fdt, FIT_TYPE_PROP, FIT_RAMDISK_PROP);
263                 fdt_property_string(fdt, FIT_OS_PROP,
264                                     genimg_get_os_short_name(params->os));
265                 fdt_property_string(fdt, FIT_ARCH_PROP,
266                                     genimg_get_arch_short_name(params->arch));
267
268                 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
269                                         params->fit_ramdisk);
270                 if (ret)
271                         return ret;
272
273                 fdt_end_node(fdt);
274         }
275
276         fdt_end_node(fdt);
277
278         return 0;
279 }
280
281 /**
282  * fit_write_configs() - Write out a list of configurations to the FIT
283  *
284  * If there are device tree files, we include a configuration for each, which
285  * selects the main image (params->datafile) and its corresponding device
286  * tree file.
287  *
288  * Otherwise we just create a configuration with the main image in it.
289  */
290 static void fit_write_configs(struct image_tool_params *params, char *fdt)
291 {
292         struct content_info *cont;
293         const char *typename;
294         char str[100];
295         int upto;
296
297         fdt_begin_node(fdt, "configurations");
298         fdt_property_string(fdt, FIT_DEFAULT_PROP, "conf-1");
299
300         upto = 0;
301         for (cont = params->content_head; cont; cont = cont->next) {
302                 if (cont->type != IH_TYPE_FLATDT)
303                         continue;
304                 typename = genimg_get_type_short_name(cont->type);
305                 snprintf(str, sizeof(str), "conf-%d", ++upto);
306                 fdt_begin_node(fdt, str);
307
308                 get_basename(str, sizeof(str), cont->fname);
309                 fdt_property_string(fdt, FIT_DESC_PROP, str);
310
311                 typename = genimg_get_type_short_name(params->fit_image_type);
312                 snprintf(str, sizeof(str), "%s-1", typename);
313                 fdt_property_string(fdt, typename, str);
314                 fdt_property_string(fdt, FIT_LOADABLE_PROP, str);
315
316                 if (params->fit_ramdisk)
317                         fdt_property_string(fdt, FIT_RAMDISK_PROP,
318                                             FIT_RAMDISK_PROP "-1");
319
320                 snprintf(str, sizeof(str), FIT_FDT_PROP "-%d", upto);
321                 fdt_property_string(fdt, FIT_FDT_PROP, str);
322                 fdt_end_node(fdt);
323         }
324
325         if (!upto) {
326                 fdt_begin_node(fdt, "conf-1");
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
331                 if (params->fit_ramdisk)
332                         fdt_property_string(fdt, FIT_RAMDISK_PROP,
333                                             FIT_RAMDISK_PROP "-1");
334
335                 fdt_end_node(fdt);
336         }
337
338         fdt_end_node(fdt);
339 }
340
341 static int fit_build_fdt(struct image_tool_params *params, char *fdt, int size)
342 {
343         int ret;
344
345         ret = fdt_create(fdt, size);
346         if (ret)
347                 return ret;
348         fdt_finish_reservemap(fdt);
349         fdt_begin_node(fdt, "");
350         fdt_property_strf(fdt, FIT_DESC_PROP,
351                           "%s image with one or more FDT blobs",
352                           genimg_get_type_name(params->fit_image_type));
353         fdt_property_strf(fdt, "creator", "U-Boot mkimage %s", PLAIN_VERSION);
354         fdt_property_u32(fdt, "#address-cells", 1);
355         ret = fit_write_images(params, fdt);
356         if (ret)
357                 return ret;
358         fit_write_configs(params, fdt);
359         fdt_end_node(fdt);
360         ret = fdt_finish(fdt);
361         if (ret)
362                 return ret;
363
364         return fdt_totalsize(fdt);
365 }
366
367 static int fit_build(struct image_tool_params *params, const char *fname)
368 {
369         char *buf;
370         int size;
371         int ret;
372         int fd;
373
374         size = fit_calc_size(params);
375         if (size < 0)
376                 return -1;
377         buf = malloc(size);
378         if (!buf) {
379                 fprintf(stderr, "%s: Out of memory (%d bytes)\n",
380                         params->cmdname, size);
381                 return -1;
382         }
383         ret = fit_build_fdt(params, buf, size);
384         if (ret < 0) {
385                 fprintf(stderr, "%s: Failed to build FIT image\n",
386                         params->cmdname);
387                 goto err_buf;
388         }
389         size = ret;
390         fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
391         if (fd < 0) {
392                 fprintf(stderr, "%s: Can't open %s: %s\n",
393                         params->cmdname, fname, strerror(errno));
394                 goto err_buf;
395         }
396         ret = write(fd, buf, size);
397         if (ret != size) {
398                 fprintf(stderr, "%s: Can't write %s: %s\n",
399                         params->cmdname, fname, strerror(errno));
400                 goto err;
401         }
402         close(fd);
403         free(buf);
404
405         return 0;
406 err:
407         close(fd);
408 err_buf:
409         free(buf);
410         return -1;
411 }
412
413 /**
414  * fit_extract_data() - Move all data outside the FIT
415  *
416  * This takes a normal FIT file and removes all the 'data' properties from it.
417  * The data is placed in an area after the FIT so that it can be accessed
418  * using an offset into that area. The 'data' properties turn into
419  * 'data-offset' properties.
420  *
421  * This function cannot cope with FITs with 'data-offset' properties. All
422  * data must be in 'data' properties on entry.
423  */
424 static int fit_extract_data(struct image_tool_params *params, const char *fname)
425 {
426         void *buf = NULL;
427         int buf_ptr;
428         int fit_size, new_size;
429         int fd;
430         struct stat sbuf;
431         void *fdt;
432         int ret;
433         int images;
434         int node;
435         int image_number;
436         int align_size;
437
438         align_size = params->bl_len ? params->bl_len : 1;
439         fd = mmap_fdt(params->cmdname, fname, 0, &fdt, &sbuf, false, false);
440         if (fd < 0)
441                 return -EIO;
442         fit_size = fdt_totalsize(fdt);
443
444         images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
445         if (images < 0) {
446                 debug("%s: Cannot find /images node: %d\n", __func__, images);
447                 ret = -EINVAL;
448                 goto err_munmap;
449         }
450         image_number = fdtdec_get_child_count(fdt, images);
451
452         /*
453          * Allocate space to hold the image data we will extract,
454          * extral space allocate for image alignment to prevent overflow.
455          */
456         buf = malloc(fit_size + (align_size * image_number));
457         if (!buf) {
458                 ret = -ENOMEM;
459                 goto err_munmap;
460         }
461         buf_ptr = 0;
462
463         for (node = fdt_first_subnode(fdt, images);
464              node >= 0;
465              node = fdt_next_subnode(fdt, node)) {
466                 const char *data;
467                 int len;
468
469                 data = fdt_getprop(fdt, node, FIT_DATA_PROP, &len);
470                 if (!data)
471                         continue;
472                 memcpy(buf + buf_ptr, data, len);
473                 debug("Extracting data size %x\n", len);
474
475                 ret = fdt_delprop(fdt, node, FIT_DATA_PROP);
476                 if (ret) {
477                         ret = -EPERM;
478                         goto err_munmap;
479                 }
480                 if (params->external_offset > 0) {
481                         /* An external offset positions the data absolutely. */
482                         fdt_setprop_u32(fdt, node, FIT_DATA_POSITION_PROP,
483                                         params->external_offset + buf_ptr);
484                 } else {
485                         fdt_setprop_u32(fdt, node, FIT_DATA_OFFSET_PROP,
486                                         buf_ptr);
487                 }
488                 fdt_setprop_u32(fdt, node, FIT_DATA_SIZE_PROP, len);
489                 buf_ptr += ALIGN(len, align_size);
490         }
491
492         /* Pack the FDT and place the data after it */
493         fdt_pack(fdt);
494
495         new_size = fdt_totalsize(fdt);
496         fdt_set_totalsize(fdt, new_size);
497         debug("Size reduced from %x to %x\n", fit_size, fdt_totalsize(fdt));
498         debug("External data size %x\n", buf_ptr);
499         munmap(fdt, sbuf.st_size);
500
501         if (ftruncate(fd, new_size)) {
502                 debug("%s: Failed to truncate file: %s\n", __func__,
503                       strerror(errno));
504                 ret = -EIO;
505                 goto err;
506         }
507
508         /* Check if an offset for the external data was set. */
509         if (params->external_offset > 0) {
510                 if (params->external_offset < new_size) {
511                         debug("External offset %x overlaps FIT length %x",
512                               params->external_offset, new_size);
513                         ret = -EINVAL;
514                         goto err;
515                 }
516                 new_size = params->external_offset;
517         }
518         if (lseek(fd, new_size, SEEK_SET) < 0) {
519                 debug("%s: Failed to seek to end of file: %s\n", __func__,
520                       strerror(errno));
521                 ret = -EIO;
522                 goto err;
523         }
524         if (write(fd, buf, buf_ptr) != buf_ptr) {
525                 debug("%s: Failed to write external data to file %s\n",
526                       __func__, strerror(errno));
527                 ret = -EIO;
528                 goto err;
529         }
530         free(buf);
531         close(fd);
532         return 0;
533
534 err_munmap:
535         munmap(fdt, sbuf.st_size);
536 err:
537         free(buf);
538         close(fd);
539         return ret;
540 }
541
542 static int fit_import_data(struct image_tool_params *params, const char *fname)
543 {
544         void *fdt, *old_fdt;
545         int fit_size, new_size, size, data_base;
546         int fd;
547         struct stat sbuf;
548         int ret;
549         int images;
550         int node;
551
552         fd = mmap_fdt(params->cmdname, fname, 0, &old_fdt, &sbuf, false, false);
553         if (fd < 0)
554                 return -EIO;
555         fit_size = fdt_totalsize(old_fdt);
556         data_base = ALIGN(fit_size, 4);
557
558         /* Allocate space to hold the new FIT */
559         size = sbuf.st_size + 16384;
560         fdt = malloc(size);
561         if (!fdt) {
562                 fprintf(stderr, "%s: Failed to allocate memory (%d bytes)\n",
563                         __func__, size);
564                 ret = -ENOMEM;
565                 goto err_munmap;
566         }
567         ret = fdt_open_into(old_fdt, fdt, size);
568         if (ret) {
569                 debug("%s: Failed to expand FIT: %s\n", __func__,
570                       fdt_strerror(errno));
571                 ret = -EINVAL;
572                 goto err_munmap;
573         }
574
575         images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
576         if (images < 0) {
577                 debug("%s: Cannot find /images node: %d\n", __func__, images);
578                 ret = -EINVAL;
579                 goto err_munmap;
580         }
581
582         for (node = fdt_first_subnode(fdt, images);
583              node >= 0;
584              node = fdt_next_subnode(fdt, node)) {
585                 int buf_ptr;
586                 int len;
587
588                 buf_ptr = fdtdec_get_int(fdt, node, "data-offset", -1);
589                 len = fdtdec_get_int(fdt, node, "data-size", -1);
590                 if (buf_ptr == -1 || len == -1)
591                         continue;
592                 debug("Importing data size %x\n", len);
593
594                 ret = fdt_setprop(fdt, node, "data", fdt + data_base + buf_ptr,
595                                   len);
596                 if (ret) {
597                         debug("%s: Failed to write property: %s\n", __func__,
598                               fdt_strerror(ret));
599                         ret = -EINVAL;
600                         goto err_munmap;
601                 }
602         }
603
604         munmap(old_fdt, sbuf.st_size);
605
606         /* Close the old fd so we can re-use it. */
607         close(fd);
608
609         /* Pack the FDT and place the data after it */
610         fdt_pack(fdt);
611
612         new_size = fdt_totalsize(fdt);
613         debug("Size expanded from %x to %x\n", fit_size, new_size);
614
615         fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
616         if (fd < 0) {
617                 fprintf(stderr, "%s: Can't open %s: %s\n",
618                         params->cmdname, fname, strerror(errno));
619                 ret = -EIO;
620                 goto err;
621         }
622         if (write(fd, fdt, new_size) != new_size) {
623                 debug("%s: Failed to write external data to file %s\n",
624                       __func__, strerror(errno));
625                 ret = -EIO;
626                 goto err;
627         }
628
629         free(fdt);
630         close(fd);
631         return 0;
632
633 err_munmap:
634         munmap(old_fdt, sbuf.st_size);
635 err:
636         free(fdt);
637         close(fd);
638         return ret;
639 }
640
641 static int copyfile(const char *src, const char *dst)
642 {
643         int fd_src = -1, fd_dst = -1;
644         void *buf = NULL;
645         ssize_t size;
646         size_t count;
647         int ret = -1;
648
649         fd_src = open(src, O_RDONLY);
650         if (fd_src < 0) {
651                 printf("Can't open file %s (%s)\n", src, strerror(errno));
652                 goto out;
653         }
654
655         fd_dst = open(dst, O_WRONLY | O_CREAT, 0666);
656         if (fd_dst < 0) {
657                 printf("Can't open file %s (%s)\n", dst, strerror(errno));
658                 goto out;
659         }
660
661         buf = malloc(512);
662         if (!buf) {
663                 printf("Can't allocate buffer to copy file\n");
664                 goto out;
665         }
666
667         while (1) {
668                 size = read(fd_src, buf, 512);
669                 if (size < 0) {
670                         printf("Can't read file %s\n", src);
671                         goto out;
672                 }
673                 if (!size)
674                         break;
675
676                 count = size;
677                 size = write(fd_dst, buf, count);
678                 if (size < 0) {
679                         printf("Can't write file %s\n", dst);
680                         goto out;
681                 }
682         }
683
684         ret = 0;
685
686  out:
687         if (fd_src >= 0)
688                 close(fd_src);
689         if (fd_dst >= 0)
690                 close(fd_dst);
691         if (buf)
692                 free(buf);
693
694         return ret;
695 }
696
697 /**
698  * fit_handle_file - main FIT file processing function
699  *
700  * fit_handle_file() runs dtc to convert .its to .itb, includes
701  * binary data, updates timestamp property and calculates hashes.
702  *
703  * datafile  - .its file
704  * imagefile - .itb file
705  *
706  * returns:
707  *     only on success, otherwise calls exit (EXIT_FAILURE);
708  */
709 static int fit_handle_file(struct image_tool_params *params)
710 {
711         char tmpfile[MKIMAGE_MAX_TMPFILE_LEN];
712         char bakfile[MKIMAGE_MAX_TMPFILE_LEN + 4] = {0};
713         char cmd[MKIMAGE_MAX_DTC_CMDLINE_LEN];
714         size_t size_inc;
715         int ret;
716
717         /* Flattened Image Tree (FIT) format  handling */
718         debug ("FIT format handling\n");
719
720         /* call dtc to include binary properties into the tmp file */
721         if (strlen (params->imagefile) +
722                 strlen (MKIMAGE_TMPFILE_SUFFIX) + 1 > sizeof (tmpfile)) {
723                 fprintf (stderr, "%s: Image file name (%s) too long, "
724                                 "can't create tmpfile",
725                                 params->imagefile, params->cmdname);
726                 return (EXIT_FAILURE);
727         }
728         sprintf (tmpfile, "%s%s", params->imagefile, MKIMAGE_TMPFILE_SUFFIX);
729
730         /* We either compile the source file, or use the existing FIT image */
731         if (params->auto_its) {
732                 if (fit_build(params, tmpfile)) {
733                         fprintf(stderr, "%s: failed to build FIT\n",
734                                 params->cmdname);
735                         return EXIT_FAILURE;
736                 }
737                 *cmd = '\0';
738         } else if (params->datafile) {
739                 /* dtc -I dts -O dtb -p 500 -o tmpfile datafile */
740                 snprintf(cmd, sizeof(cmd), "%s %s -o \"%s\" \"%s\"",
741                          MKIMAGE_DTC, params->dtc, tmpfile, params->datafile);
742                 debug("Trying to execute \"%s\"\n", cmd);
743         } else {
744                 snprintf(cmd, sizeof(cmd), "cp \"%s\" \"%s\"",
745                          params->imagefile, tmpfile);
746         }
747         if (strlen(cmd) >= MKIMAGE_MAX_DTC_CMDLINE_LEN - 1) {
748                 fprintf(stderr, "WARNING: command-line for FIT creation might be truncated and will probably fail.\n");
749         }
750
751         if (*cmd && system(cmd) == -1) {
752                 fprintf (stderr, "%s: system(%s) failed: %s\n",
753                                 params->cmdname, cmd, strerror(errno));
754                 goto err_system;
755         }
756
757         /* Move the data so it is internal to the FIT, if needed */
758         ret = fit_import_data(params, tmpfile);
759         if (ret)
760                 goto err_system;
761
762         /*
763          * Copy the tmpfile to bakfile, then in the following loop
764          * we copy bakfile to tmpfile. So we always start from the
765          * beginning.
766          */
767         sprintf(bakfile, "%s%s", tmpfile, ".bak");
768         rename(tmpfile, bakfile);
769
770         /*
771          * Set hashes for images in the blob. Unfortunately we may need more
772          * space in either FDT, so keep trying until we succeed.
773          *
774          * Note: this is pretty inefficient for signing, since we must
775          * calculate the signature every time. It would be better to calculate
776          * all the data and then store it in a separate step. However, this
777          * would be considerably more complex to implement. Generally a few
778          * steps of this loop is enough to sign with several keys.
779          */
780         for (size_inc = 0; size_inc < 64 * 1024; size_inc += 1024) {
781                 if (copyfile(bakfile, tmpfile) < 0) {
782                         printf("Can't copy %s to %s\n", bakfile, tmpfile);
783                         ret = -EIO;
784                         break;
785                 }
786                 ret = fit_add_file_data(params, size_inc, tmpfile);
787                 if (!ret || ret != -ENOSPC)
788                         break;
789         }
790
791         if (ret) {
792                 fprintf(stderr, "%s Can't add hashes to FIT blob: %d\n",
793                         params->cmdname, ret);
794                 goto err_system;
795         }
796
797         /* Move the data so it is external to the FIT, if requested */
798         if (params->external_data) {
799                 ret = fit_extract_data(params, tmpfile);
800                 if (ret)
801                         goto err_system;
802         }
803
804         if (rename (tmpfile, params->imagefile) == -1) {
805                 fprintf (stderr, "%s: Can't rename %s to %s: %s\n",
806                                 params->cmdname, tmpfile, params->imagefile,
807                                 strerror (errno));
808                 unlink (tmpfile);
809                 unlink(bakfile);
810                 unlink (params->imagefile);
811                 return EXIT_FAILURE;
812         }
813         unlink(bakfile);
814         return EXIT_SUCCESS;
815
816 err_system:
817         unlink(tmpfile);
818         unlink(bakfile);
819         return -1;
820 }
821
822 /**
823  * fit_image_extract - extract a FIT component image
824  * @fit: pointer to the FIT format image header
825  * @image_noffset: offset of the component image node
826  * @file_name: name of the file to store the FIT sub-image
827  *
828  * returns:
829  *     zero in case of success or a negative value if fail.
830  */
831 static int fit_image_extract(
832         const void *fit,
833         int image_noffset,
834         const char *file_name)
835 {
836         const void *file_data;
837         size_t file_size = 0;
838         int ret;
839
840         /* get the data address and size of component at offset "image_noffset" */
841         ret = fit_image_get_data_and_size(fit, image_noffset, &file_data, &file_size);
842         if (ret) {
843                 fprintf(stderr, "Could not get component information\n");
844                 return ret;
845         }
846
847         /* save the "file_data" into the file specified by "file_name" */
848         return imagetool_save_subimage(file_name, (ulong) file_data, file_size);
849 }
850
851 /**
852  * fit_extract_contents - retrieve a sub-image component from the FIT image
853  * @ptr: pointer to the FIT format image header
854  * @params: command line parameters
855  *
856  * returns:
857  *     zero in case of success or a negative value if fail.
858  */
859 static int fit_extract_contents(void *ptr, struct image_tool_params *params)
860 {
861         int images_noffset;
862         int noffset;
863         int ndepth;
864         const void *fit = ptr;
865         int count = 0;
866         const char *p;
867
868         /* Indent string is defined in header image.h */
869         p = IMAGE_INDENT_STRING;
870
871         if (!fit_check_format(fit)) {
872                 printf("Bad FIT image format\n");
873                 return -1;
874         }
875
876         /* Find images parent node offset */
877         images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
878         if (images_noffset < 0) {
879                 printf("Can't find images parent node '%s' (%s)\n",
880                        FIT_IMAGES_PATH, fdt_strerror(images_noffset));
881                 return -1;
882         }
883
884         /* Avoid any overrun */
885         count = fit_get_subimage_count(fit, images_noffset);
886         if ((params->pflag < 0) || (count <= params->pflag)) {
887                 printf("No such component at '%d'\n", params->pflag);
888                 return -1;
889         }
890
891         /* Process its subnodes, extract the desired component from image */
892         for (ndepth = 0, count = 0,
893                 noffset = fdt_next_node(fit, images_noffset, &ndepth);
894                 (noffset >= 0) && (ndepth > 0);
895                 noffset = fdt_next_node(fit, noffset, &ndepth)) {
896                 if (ndepth == 1) {
897                         /*
898                          * Direct child node of the images parent node,
899                          * i.e. component image node.
900                          */
901                         if (params->pflag == count) {
902                                 printf("Extracted:\n%s Image %u (%s)\n", p,
903                                        count, fit_get_name(fit, noffset, NULL));
904
905                                 fit_image_print(fit, noffset, p);
906
907                                 return fit_image_extract(fit, noffset,
908                                                 params->outfile);
909                         }
910
911                         count++;
912                 }
913         }
914
915         return 0;
916 }
917
918 static int fit_check_params(struct image_tool_params *params)
919 {
920         if (params->auto_its)
921                 return 0;
922         return  ((params->dflag && params->fflag) ||
923                  (params->fflag && params->lflag) ||
924                  (params->lflag && params->dflag));
925 }
926
927 U_BOOT_IMAGE_TYPE(
928         fitimage,
929         "FIT Image support",
930         sizeof(image_header_t),
931         (void *)&header,
932         fit_check_params,
933         fit_verify_header,
934         fit_print_contents,
935         NULL,
936         fit_extract_contents,
937         fit_check_image_types,
938         fit_handle_file,
939         NULL /* FIT images use DTB header */
940 );