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