Merge tag 'u-boot-amlogic-20200428' of https://gitlab.denx.de/u-boot/custodians/u...
[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 <stdarg.h>
21 #include <version.h>
22 #include <u-boot/crc.h>
23
24 static image_header_t header;
25
26 static int fit_add_file_data(struct image_tool_params *params, size_t size_inc,
27                              const char *tmpfile)
28 {
29         int tfd, destfd = 0;
30         void *dest_blob = NULL;
31         off_t destfd_size = 0;
32         struct stat sbuf;
33         void *ptr;
34         int ret = 0;
35
36         tfd = mmap_fdt(params->cmdname, tmpfile, size_inc, &ptr, &sbuf, true,
37                        false);
38         if (tfd < 0)
39                 return -EIO;
40
41         if (params->keydest) {
42                 struct stat dest_sbuf;
43
44                 destfd = mmap_fdt(params->cmdname, params->keydest, size_inc,
45                                   &dest_blob, &dest_sbuf, false,
46                                   false);
47                 if (destfd < 0) {
48                         ret = -EIO;
49                         goto err_keydest;
50                 }
51                 destfd_size = dest_sbuf.st_size;
52         }
53
54         /* for first image creation, add a timestamp at offset 0 i.e., root  */
55         if (params->datafile) {
56                 time_t time = imagetool_get_source_date(params->cmdname,
57                                                         sbuf.st_mtime);
58                 ret = fit_set_timestamp(ptr, 0, time);
59         }
60
61         if (!ret) {
62                 ret = fit_cipher_data(params->keydir, dest_blob, ptr,
63                                       params->comment,
64                                       params->require_keys,
65                                       params->engine_id,
66                                       params->cmdname);
67         }
68
69         if (!ret) {
70                 ret = fit_add_verification_data(params->keydir, dest_blob, ptr,
71                                                 params->comment,
72                                                 params->require_keys,
73                                                 params->engine_id,
74                                                 params->cmdname);
75         }
76
77         if (dest_blob) {
78                 munmap(dest_blob, destfd_size);
79                 close(destfd);
80         }
81
82 err_keydest:
83         munmap(ptr, sbuf.st_size);
84         close(tfd);
85         return ret;
86 }
87
88 /**
89  * fit_calc_size() - Calculate the approximate size of the FIT we will generate
90  */
91 static int fit_calc_size(struct image_tool_params *params)
92 {
93         struct content_info *cont;
94         int size, total_size;
95
96         size = imagetool_get_filesize(params, params->datafile);
97         if (size < 0)
98                 return -1;
99         total_size = size;
100
101         if (params->fit_ramdisk) {
102                 size = imagetool_get_filesize(params, params->fit_ramdisk);
103                 if (size < 0)
104                         return -1;
105                 total_size += size;
106         }
107
108         for (cont = params->content_head; cont; cont = cont->next) {
109                 size = imagetool_get_filesize(params, cont->fname);
110                 if (size < 0)
111                         return -1;
112
113                 /* Add space for properties */
114                 total_size += size + 300;
115         }
116
117         /* Add plenty of space for headers, properties, nodes, etc. */
118         total_size += 4096;
119
120         return total_size;
121 }
122
123 static int fdt_property_file(struct image_tool_params *params,
124                              void *fdt, const char *name, const char *fname)
125 {
126         struct stat sbuf;
127         void *ptr;
128         int ret;
129         int fd;
130
131         fd = open(fname, O_RDWR | O_BINARY);
132         if (fd < 0) {
133                 fprintf(stderr, "%s: Can't open %s: %s\n",
134                         params->cmdname, fname, strerror(errno));
135                 return -1;
136         }
137
138         if (fstat(fd, &sbuf) < 0) {
139                 fprintf(stderr, "%s: Can't stat %s: %s\n",
140                         params->cmdname, fname, strerror(errno));
141                 goto err;
142         }
143
144         ret = fdt_property_placeholder(fdt, "data", sbuf.st_size, &ptr);
145         if (ret)
146                 goto err;
147         ret = read(fd, ptr, sbuf.st_size);
148         if (ret != sbuf.st_size) {
149                 fprintf(stderr, "%s: Can't read %s: %s\n",
150                         params->cmdname, fname, strerror(errno));
151                 goto err;
152         }
153         close(fd);
154
155         return 0;
156 err:
157         close(fd);
158         return -1;
159 }
160
161 static int fdt_property_strf(void *fdt, const char *name, const char *fmt, ...)
162 {
163         char str[100];
164         va_list ptr;
165
166         va_start(ptr, fmt);
167         vsnprintf(str, sizeof(str), fmt, ptr);
168         va_end(ptr);
169         return fdt_property_string(fdt, name, str);
170 }
171
172 static void get_basename(char *str, int size, const char *fname)
173 {
174         const char *p, *start, *end;
175         int len;
176
177         /*
178          * Use the base name as the 'name' field. So for example:
179          *
180          * "arch/arm/dts/sun7i-a20-bananapro.dtb"
181          * becomes "sun7i-a20-bananapro"
182          */
183         p = strrchr(fname, '/');
184         start = p ? p + 1 : fname;
185         p = strrchr(fname, '.');
186         end = p ? p : fname + strlen(fname);
187         len = end - start;
188         if (len >= size)
189                 len = size - 1;
190         memcpy(str, start, len);
191         str[len] = '\0';
192 }
193
194 /**
195  * fit_write_images() - Write out a list of images to the FIT
196  *
197  * We always include the main image (params->datafile). If there are device
198  * tree files, we include an fdt- node for each of those too.
199  */
200 static int fit_write_images(struct image_tool_params *params, char *fdt)
201 {
202         struct content_info *cont;
203         const char *typename;
204         char str[100];
205         int upto;
206         int ret;
207
208         fdt_begin_node(fdt, "images");
209
210         /* First the main image */
211         typename = genimg_get_type_short_name(params->fit_image_type);
212         snprintf(str, sizeof(str), "%s-1", typename);
213         fdt_begin_node(fdt, str);
214         fdt_property_string(fdt, FIT_DESC_PROP, params->imagename);
215         fdt_property_string(fdt, FIT_TYPE_PROP, typename);
216         fdt_property_string(fdt, FIT_ARCH_PROP,
217                             genimg_get_arch_short_name(params->arch));
218         fdt_property_string(fdt, FIT_OS_PROP,
219                             genimg_get_os_short_name(params->os));
220         fdt_property_string(fdt, FIT_COMP_PROP,
221                             genimg_get_comp_short_name(params->comp));
222         fdt_property_u32(fdt, FIT_LOAD_PROP, params->addr);
223         fdt_property_u32(fdt, FIT_ENTRY_PROP, params->ep);
224
225         /*
226          * Put data last since it is large. SPL may only load the first part
227          * of the DT, so this way it can access all the above fields.
228          */
229         ret = fdt_property_file(params, fdt, FIT_DATA_PROP, params->datafile);
230         if (ret)
231                 return ret;
232         fdt_end_node(fdt);
233
234         /* Now the device tree files if available */
235         upto = 0;
236         for (cont = params->content_head; cont; cont = cont->next) {
237                 if (cont->type != IH_TYPE_FLATDT)
238                         continue;
239                 typename = genimg_get_type_short_name(cont->type);
240                 snprintf(str, sizeof(str), "%s-%d", FIT_FDT_PROP, ++upto);
241                 fdt_begin_node(fdt, str);
242
243                 get_basename(str, sizeof(str), cont->fname);
244                 fdt_property_string(fdt, FIT_DESC_PROP, str);
245                 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
246                                         cont->fname);
247                 if (ret)
248                         return ret;
249                 fdt_property_string(fdt, FIT_TYPE_PROP, typename);
250                 fdt_property_string(fdt, FIT_ARCH_PROP,
251                                     genimg_get_arch_short_name(params->arch));
252                 fdt_property_string(fdt, FIT_COMP_PROP,
253                                     genimg_get_comp_short_name(IH_COMP_NONE));
254                 fdt_end_node(fdt);
255         }
256
257         /* And a ramdisk file if available */
258         if (params->fit_ramdisk) {
259                 fdt_begin_node(fdt, FIT_RAMDISK_PROP "-1");
260
261                 fdt_property_string(fdt, FIT_TYPE_PROP, FIT_RAMDISK_PROP);
262                 fdt_property_string(fdt, FIT_OS_PROP,
263                                     genimg_get_os_short_name(params->os));
264                 fdt_property_string(fdt, FIT_ARCH_PROP,
265                                     genimg_get_arch_short_name(params->arch));
266
267                 ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
268                                         params->fit_ramdisk);
269                 if (ret)
270                         return ret;
271
272                 fdt_end_node(fdt);
273         }
274
275         fdt_end_node(fdt);
276
277         return 0;
278 }
279
280 /**
281  * fit_write_configs() - Write out a list of configurations to the FIT
282  *
283  * If there are device tree files, we include a configuration for each, which
284  * selects the main image (params->datafile) and its corresponding device
285  * tree file.
286  *
287  * Otherwise we just create a configuration with the main image in it.
288  */
289 static void fit_write_configs(struct image_tool_params *params, char *fdt)
290 {
291         struct content_info *cont;
292         const char *typename;
293         char str[100];
294         int upto;
295
296         fdt_begin_node(fdt, "configurations");
297         fdt_property_string(fdt, FIT_DEFAULT_PROP, "conf-1");
298
299         upto = 0;
300         for (cont = params->content_head; cont; cont = cont->next) {
301                 if (cont->type != IH_TYPE_FLATDT)
302                         continue;
303                 typename = genimg_get_type_short_name(cont->type);
304                 snprintf(str, sizeof(str), "conf-%d", ++upto);
305                 fdt_begin_node(fdt, str);
306
307                 get_basename(str, sizeof(str), cont->fname);
308                 fdt_property_string(fdt, FIT_DESC_PROP, str);
309
310                 typename = genimg_get_type_short_name(params->fit_image_type);
311                 snprintf(str, sizeof(str), "%s-1", typename);
312                 fdt_property_string(fdt, typename, str);
313                 fdt_property_string(fdt, FIT_LOADABLE_PROP, str);
314
315                 if (params->fit_ramdisk)
316                         fdt_property_string(fdt, FIT_RAMDISK_PROP,
317                                             FIT_RAMDISK_PROP "-1");
318
319                 snprintf(str, sizeof(str), FIT_FDT_PROP "-%d", upto);
320                 fdt_property_string(fdt, FIT_FDT_PROP, str);
321                 fdt_end_node(fdt);
322         }
323
324         if (!upto) {
325                 fdt_begin_node(fdt, "conf-1");
326                 typename = genimg_get_type_short_name(params->fit_image_type);
327                 snprintf(str, sizeof(str), "%s-1", typename);
328                 fdt_property_string(fdt, typename, str);
329
330                 if (params->fit_ramdisk)
331                         fdt_property_string(fdt, FIT_RAMDISK_PROP,
332                                             FIT_RAMDISK_PROP "-1");
333
334                 fdt_end_node(fdt);
335         }
336
337         fdt_end_node(fdt);
338 }
339
340 static int fit_build_fdt(struct image_tool_params *params, char *fdt, int size)
341 {
342         int ret;
343
344         ret = fdt_create(fdt, size);
345         if (ret)
346                 return ret;
347         fdt_finish_reservemap(fdt);
348         fdt_begin_node(fdt, "");
349         fdt_property_strf(fdt, FIT_DESC_PROP,
350                           "%s image with one or more FDT blobs",
351                           genimg_get_type_name(params->fit_image_type));
352         fdt_property_strf(fdt, "creator", "U-Boot mkimage %s", PLAIN_VERSION);
353         fdt_property_u32(fdt, "#address-cells", 1);
354         ret = fit_write_images(params, fdt);
355         if (ret)
356                 return ret;
357         fit_write_configs(params, fdt);
358         fdt_end_node(fdt);
359         ret = fdt_finish(fdt);
360         if (ret)
361                 return ret;
362
363         return fdt_totalsize(fdt);
364 }
365
366 static int fit_build(struct image_tool_params *params, const char *fname)
367 {
368         char *buf;
369         int size;
370         int ret;
371         int fd;
372
373         size = fit_calc_size(params);
374         if (size < 0)
375                 return -1;
376         buf = malloc(size);
377         if (!buf) {
378                 fprintf(stderr, "%s: Out of memory (%d bytes)\n",
379                         params->cmdname, size);
380                 return -1;
381         }
382         ret = fit_build_fdt(params, buf, size);
383         if (ret < 0) {
384                 fprintf(stderr, "%s: Failed to build FIT image\n",
385                         params->cmdname);
386                 goto err_buf;
387         }
388         size = ret;
389         fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
390         if (fd < 0) {
391                 fprintf(stderr, "%s: Can't open %s: %s\n",
392                         params->cmdname, fname, strerror(errno));
393                 goto err_buf;
394         }
395         ret = write(fd, buf, size);
396         if (ret != size) {
397                 fprintf(stderr, "%s: Can't write %s: %s\n",
398                         params->cmdname, fname, strerror(errno));
399                 goto err;
400         }
401         close(fd);
402         free(buf);
403
404         return 0;
405 err:
406         close(fd);
407 err_buf:
408         free(buf);
409         return -1;
410 }
411
412 /**
413  * fit_extract_data() - Move all data outside the FIT
414  *
415  * This takes a normal FIT file and removes all the 'data' properties from it.
416  * The data is placed in an area after the FIT so that it can be accessed
417  * using an offset into that area. The 'data' properties turn into
418  * 'data-offset' properties.
419  *
420  * This function cannot cope with FITs with 'data-offset' properties. All
421  * data must be in 'data' properties on entry.
422  */
423 static int fit_extract_data(struct image_tool_params *params, const char *fname)
424 {
425         void *buf = NULL;
426         int buf_ptr;
427         int fit_size, new_size;
428         int fd;
429         struct stat sbuf;
430         void *fdt;
431         int ret;
432         int images;
433         int node;
434         int image_number;
435         int align_size;
436
437         align_size = params->bl_len ? params->bl_len : 4;
438         fd = mmap_fdt(params->cmdname, fname, 0, &fdt, &sbuf, false, false);
439         if (fd < 0)
440                 return -EIO;
441         fit_size = fdt_totalsize(fdt);
442
443         images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
444         if (images < 0) {
445                 debug("%s: Cannot find /images node: %d\n", __func__, images);
446                 ret = -EINVAL;
447                 goto err_munmap;
448         }
449         image_number = fdtdec_get_child_count(fdt, images);
450
451         /*
452          * Allocate space to hold the image data we will extract,
453          * extral space allocate for image alignment to prevent overflow.
454          */
455         buf = malloc(fit_size + (align_size * image_number));
456         if (!buf) {
457                 ret = -ENOMEM;
458                 goto err_munmap;
459         }
460         buf_ptr = 0;
461
462         for (node = fdt_first_subnode(fdt, images);
463              node >= 0;
464              node = fdt_next_subnode(fdt, node)) {
465                 const char *data;
466                 int len;
467
468                 data = fdt_getprop(fdt, node, FIT_DATA_PROP, &len);
469                 if (!data)
470                         continue;
471                 memcpy(buf + buf_ptr, data, len);
472                 debug("Extracting data size %x\n", len);
473
474                 ret = fdt_delprop(fdt, node, FIT_DATA_PROP);
475                 if (ret) {
476                         ret = -EPERM;
477                         goto err_munmap;
478                 }
479                 if (params->external_offset > 0) {
480                         /* An external offset positions the data absolutely. */
481                         fdt_setprop_u32(fdt, node, FIT_DATA_POSITION_PROP,
482                                         params->external_offset + buf_ptr);
483                 } else {
484                         fdt_setprop_u32(fdt, node, FIT_DATA_OFFSET_PROP,
485                                         buf_ptr);
486                 }
487                 fdt_setprop_u32(fdt, node, FIT_DATA_SIZE_PROP, len);
488                 buf_ptr += ALIGN(len, align_size);
489         }
490
491         /* Pack the FDT and place the data after it */
492         fdt_pack(fdt);
493
494         new_size = fdt_totalsize(fdt);
495         new_size = ALIGN(new_size, align_size);
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
748         if (*cmd && system(cmd) == -1) {
749                 fprintf (stderr, "%s: system(%s) failed: %s\n",
750                                 params->cmdname, cmd, strerror(errno));
751                 goto err_system;
752         }
753
754         /* Move the data so it is internal to the FIT, if needed */
755         ret = fit_import_data(params, tmpfile);
756         if (ret)
757                 goto err_system;
758
759         /*
760          * Copy the tmpfile to bakfile, then in the following loop
761          * we copy bakfile to tmpfile. So we always start from the
762          * beginning.
763          */
764         sprintf(bakfile, "%s%s", tmpfile, ".bak");
765         rename(tmpfile, bakfile);
766
767         /*
768          * Set hashes for images in the blob. Unfortunately we may need more
769          * space in either FDT, so keep trying until we succeed.
770          *
771          * Note: this is pretty inefficient for signing, since we must
772          * calculate the signature every time. It would be better to calculate
773          * all the data and then store it in a separate step. However, this
774          * would be considerably more complex to implement. Generally a few
775          * steps of this loop is enough to sign with several keys.
776          */
777         for (size_inc = 0; size_inc < 64 * 1024; size_inc += 1024) {
778                 if (copyfile(bakfile, tmpfile) < 0) {
779                         printf("Can't copy %s to %s\n", bakfile, tmpfile);
780                         ret = -EIO;
781                         break;
782                 }
783                 ret = fit_add_file_data(params, size_inc, tmpfile);
784                 if (!ret || ret != -ENOSPC)
785                         break;
786         }
787
788         if (ret) {
789                 fprintf(stderr, "%s Can't add hashes to FIT blob: %d\n",
790                         params->cmdname, ret);
791                 goto err_system;
792         }
793
794         /* Move the data so it is external to the FIT, if requested */
795         if (params->external_data) {
796                 ret = fit_extract_data(params, tmpfile);
797                 if (ret)
798                         goto err_system;
799         }
800
801         if (rename (tmpfile, params->imagefile) == -1) {
802                 fprintf (stderr, "%s: Can't rename %s to %s: %s\n",
803                                 params->cmdname, tmpfile, params->imagefile,
804                                 strerror (errno));
805                 unlink (tmpfile);
806                 unlink(bakfile);
807                 unlink (params->imagefile);
808                 return EXIT_FAILURE;
809         }
810         unlink(bakfile);
811         return EXIT_SUCCESS;
812
813 err_system:
814         unlink(tmpfile);
815         unlink(bakfile);
816         return -1;
817 }
818
819 /**
820  * fit_image_extract - extract a FIT component image
821  * @fit: pointer to the FIT format image header
822  * @image_noffset: offset of the component image node
823  * @file_name: name of the file to store the FIT sub-image
824  *
825  * returns:
826  *     zero in case of success or a negative value if fail.
827  */
828 static int fit_image_extract(
829         const void *fit,
830         int image_noffset,
831         const char *file_name)
832 {
833         const void *file_data;
834         size_t file_size = 0;
835         int ret;
836
837         /* get the data address and size of component at offset "image_noffset" */
838         ret = fit_image_get_data_and_size(fit, image_noffset, &file_data, &file_size);
839         if (ret) {
840                 fprintf(stderr, "Could not get component information\n");
841                 return ret;
842         }
843
844         /* save the "file_data" into the file specified by "file_name" */
845         return imagetool_save_subimage(file_name, (ulong) file_data, file_size);
846 }
847
848 /**
849  * fit_extract_contents - retrieve a sub-image component from the FIT image
850  * @ptr: pointer to the FIT format image header
851  * @params: command line parameters
852  *
853  * returns:
854  *     zero in case of success or a negative value if fail.
855  */
856 static int fit_extract_contents(void *ptr, struct image_tool_params *params)
857 {
858         int images_noffset;
859         int noffset;
860         int ndepth;
861         const void *fit = ptr;
862         int count = 0;
863         const char *p;
864
865         /* Indent string is defined in header image.h */
866         p = IMAGE_INDENT_STRING;
867
868         if (!fit_check_format(fit)) {
869                 printf("Bad FIT image format\n");
870                 return -1;
871         }
872
873         /* Find images parent node offset */
874         images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
875         if (images_noffset < 0) {
876                 printf("Can't find images parent node '%s' (%s)\n",
877                        FIT_IMAGES_PATH, fdt_strerror(images_noffset));
878                 return -1;
879         }
880
881         /* Avoid any overrun */
882         count = fit_get_subimage_count(fit, images_noffset);
883         if ((params->pflag < 0) || (count <= params->pflag)) {
884                 printf("No such component at '%d'\n", params->pflag);
885                 return -1;
886         }
887
888         /* Process its subnodes, extract the desired component from image */
889         for (ndepth = 0, count = 0,
890                 noffset = fdt_next_node(fit, images_noffset, &ndepth);
891                 (noffset >= 0) && (ndepth > 0);
892                 noffset = fdt_next_node(fit, noffset, &ndepth)) {
893                 if (ndepth == 1) {
894                         /*
895                          * Direct child node of the images parent node,
896                          * i.e. component image node.
897                          */
898                         if (params->pflag == count) {
899                                 printf("Extracted:\n%s Image %u (%s)\n", p,
900                                        count, fit_get_name(fit, noffset, NULL));
901
902                                 fit_image_print(fit, noffset, p);
903
904                                 return fit_image_extract(fit, noffset,
905                                                 params->outfile);
906                         }
907
908                         count++;
909                 }
910         }
911
912         return 0;
913 }
914
915 static int fit_check_params(struct image_tool_params *params)
916 {
917         if (params->auto_its)
918                 return 0;
919         return  ((params->dflag && params->fflag) ||
920                  (params->fflag && params->lflag) ||
921                  (params->lflag && params->dflag));
922 }
923
924 U_BOOT_IMAGE_TYPE(
925         fitimage,
926         "FIT Image support",
927         sizeof(image_header_t),
928         (void *)&header,
929         fit_check_params,
930         fit_verify_header,
931         fit_print_contents,
932         NULL,
933         fit_extract_contents,
934         fit_check_image_types,
935         fit_handle_file,
936         NULL /* FIT images use DTB header */
937 );