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