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