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 struct legacy_img_hdr header;
26 
fit_estimate_hash_sig_size(struct image_tool_params * params,const char * fname)27 static int fit_estimate_hash_sig_size(struct image_tool_params *params, const char *fname)
28 {
29 	bool signing = IMAGE_ENABLE_SIGN && (params->keydir || params->keyfile);
30 	struct stat sbuf;
31 	void *fdt;
32 	int fd;
33 	int estimate = 0;
34 	int depth, noffset;
35 	const char *name;
36 
37 	fd = mmap_fdt(params->cmdname, fname, 0, &fdt, &sbuf, false, true);
38 	if (fd < 0)
39 		return -EIO;
40 
41 	/*
42 	 * Walk the FIT image, looking for nodes named hash* and
43 	 * signature*. Since the interesting nodes are subnodes of an
44 	 * image or configuration node, we are only interested in
45 	 * those at depth exactly 3.
46 	 *
47 	 * The estimate for a hash node is based on a sha512 digest
48 	 * being 64 bytes, with another 64 bytes added to account for
49 	 * fdt structure overhead (the tags and the name of the
50 	 * "value" property).
51 	 *
52 	 * The estimate for a signature node is based on an rsa4096
53 	 * signature being 512 bytes, with another 512 bytes to
54 	 * account for fdt overhead and the various other properties
55 	 * (hashed-nodes etc.) that will also be filled in.
56 	 *
57 	 * One could try to be more precise in the estimates by
58 	 * looking at the "algo" property and, in the case of
59 	 * configuration signatures, the sign-images property. Also,
60 	 * when signing an already created FIT image, the hash nodes
61 	 * already have properly sized value properties, so one could
62 	 * also take pre-existence of "value" properties in hash nodes
63 	 * into account. But this rather simple approach should work
64 	 * well enough in practice.
65 	 */
66 	for (depth = 0, noffset = fdt_next_node(fdt, 0, &depth);
67 	     noffset >= 0 && depth > 0;
68 	     noffset = fdt_next_node(fdt, noffset, &depth)) {
69 		if (depth != 3)
70 			continue;
71 
72 		name = fdt_get_name(fdt, noffset, NULL);
73 		if (!strncmp(name, FIT_HASH_NODENAME, strlen(FIT_HASH_NODENAME)))
74 			estimate += 128;
75 
76 		if (signing && !strncmp(name, FIT_SIG_NODENAME, strlen(FIT_SIG_NODENAME)))
77 			estimate += 1024;
78 	}
79 
80 	munmap(fdt, sbuf.st_size);
81 	close(fd);
82 
83 	return estimate;
84 }
85 
fit_add_file_data(struct image_tool_params * params,size_t size_inc,const char * tmpfile)86 static int fit_add_file_data(struct image_tool_params *params, size_t size_inc,
87 			     const char *tmpfile)
88 {
89 	int tfd, destfd = 0;
90 	void *dest_blob = NULL;
91 	off_t destfd_size = 0;
92 	struct stat sbuf;
93 	void *ptr;
94 	int ret = 0;
95 
96 	tfd = mmap_fdt(params->cmdname, tmpfile, size_inc, &ptr, &sbuf, true,
97 		       false);
98 	if (tfd < 0) {
99 		fprintf(stderr, "Cannot map FDT file '%s'\n", tmpfile);
100 		return -EIO;
101 	}
102 
103 	if (params->keydest) {
104 		struct stat dest_sbuf;
105 
106 		destfd = mmap_fdt(params->cmdname, params->keydest, size_inc,
107 				  &dest_blob, &dest_sbuf, false,
108 				  false);
109 		if (destfd < 0) {
110 			ret = -EIO;
111 			goto err_keydest;
112 		}
113 		destfd_size = dest_sbuf.st_size;
114 	}
115 
116 	/* for first image creation, add a timestamp at offset 0 i.e., root  */
117 	if (params->datafile || params->reset_timestamp) {
118 		time_t time = imagetool_get_source_date(params->cmdname,
119 							sbuf.st_mtime);
120 		ret = fit_set_timestamp(ptr, 0, time);
121 	}
122 
123 	if (CONFIG_IS_ENABLED(FIT_SIGNATURE) && !ret)
124 		ret = fit_pre_load_data(params->keydir, dest_blob, ptr);
125 
126 	if (!ret) {
127 		ret = fit_cipher_data(params->keydir, dest_blob, ptr,
128 				      params->comment,
129 				      params->require_keys,
130 				      params->engine_id,
131 				      params->cmdname);
132 	}
133 
134 	if (!ret) {
135 		ret = fit_add_verification_data(params->keydir,
136 						params->keyfile, dest_blob, ptr,
137 						params->comment,
138 						params->require_keys,
139 						params->engine_id,
140 						params->cmdname,
141 						params->algo_name,
142 						&params->summary);
143 	}
144 
145 	if (dest_blob) {
146 		munmap(dest_blob, destfd_size);
147 		close(destfd);
148 	}
149 
150 err_keydest:
151 	munmap(ptr, sbuf.st_size);
152 	close(tfd);
153 	return ret;
154 }
155 
156 /**
157  * fit_calc_size() - Calculate the approximate size of the FIT we will generate
158  */
fit_calc_size(struct image_tool_params * params)159 static int fit_calc_size(struct image_tool_params *params)
160 {
161 	struct content_info *cont;
162 	int size, total_size;
163 
164 	size = imagetool_get_filesize(params, params->datafile);
165 	if (size < 0)
166 		return -1;
167 	total_size = size;
168 
169 	if (params->fit_ramdisk) {
170 		size = imagetool_get_filesize(params, params->fit_ramdisk);
171 		if (size < 0)
172 			return -1;
173 		total_size += size;
174 	}
175 
176 	for (cont = params->content_head; cont; cont = cont->next) {
177 		size = imagetool_get_filesize(params, cont->fname);
178 		if (size < 0)
179 			return -1;
180 
181 		/* Add space for properties and hash node */
182 		total_size += size + 300;
183 	}
184 
185 	/* Add plenty of space for headers, properties, nodes, etc. */
186 	total_size += 4096;
187 
188 	return total_size;
189 }
190 
fdt_property_file(struct image_tool_params * params,void * fdt,const char * name,const char * fname)191 static int fdt_property_file(struct image_tool_params *params,
192 			     void *fdt, const char *name, const char *fname)
193 {
194 	struct stat sbuf;
195 	void *ptr;
196 	int ret;
197 	int fd;
198 
199 	fd = open(fname, O_RDONLY | O_BINARY);
200 	if (fd < 0) {
201 		fprintf(stderr, "%s: Can't open %s: %s\n",
202 			params->cmdname, fname, strerror(errno));
203 		return -1;
204 	}
205 
206 	if (fstat(fd, &sbuf) < 0) {
207 		fprintf(stderr, "%s: Can't stat %s: %s\n",
208 			params->cmdname, fname, strerror(errno));
209 		goto err;
210 	}
211 
212 	ret = fdt_property_placeholder(fdt, "data", sbuf.st_size, &ptr);
213 	if (ret)
214 		goto err;
215 	ret = read(fd, ptr, sbuf.st_size);
216 	if (ret != sbuf.st_size) {
217 		fprintf(stderr, "%s: Can't read %s: %s\n",
218 			params->cmdname, fname, strerror(errno));
219 		goto err;
220 	}
221 	close(fd);
222 
223 	return 0;
224 err:
225 	close(fd);
226 	return -1;
227 }
228 
fdt_property_strf(void * fdt,const char * name,const char * fmt,...)229 static int fdt_property_strf(void *fdt, const char *name, const char *fmt, ...)
230 {
231 	char str[100];
232 	va_list ptr;
233 
234 	va_start(ptr, fmt);
235 	vsnprintf(str, sizeof(str), fmt, ptr);
236 	va_end(ptr);
237 	return fdt_property_string(fdt, name, str);
238 }
239 
get_basename(char * str,int size,const char * fname)240 static void get_basename(char *str, int size, const char *fname)
241 {
242 	const char *p, *start, *end;
243 	int len;
244 
245 	/*
246 	 * Use the base name as the 'name' field. So for example:
247 	 *
248 	 * "arch/arm/dts/sun7i-a20-bananapro.dtb"
249 	 * becomes "sun7i-a20-bananapro"
250 	 */
251 	p = strrchr(fname, '/');
252 	start = p ? p + 1 : fname;
253 	p = strrchr(fname, '.');
254 	end = p ? p : fname + strlen(fname);
255 	len = end - start;
256 	if (len >= size)
257 		len = size - 1;
258 	memcpy(str, start, len);
259 	str[len] = '\0';
260 }
261 
262 /**
263  * fit_add_hash_or_sign() - Add a hash or signature node
264  *
265  * @params: Image parameters
266  * @fdt: Device tree to add to (in sequential-write mode)
267  * @is_images_subnode: true to add hash even if key name hint is provided
268  *
269  * If do_add_hash is false (default) and there is a key name hint, try to add
270  * a sign node to parent. Otherwise, just add a CRC. Rationale: if conf have
271  * to be signed, image/dt have to be hashed even if there is a key name hint.
272  */
fit_add_hash_or_sign(struct image_tool_params * params,void * fdt,bool is_images_subnode)273 static void fit_add_hash_or_sign(struct image_tool_params *params, void *fdt,
274 				 bool is_images_subnode)
275 {
276 	const char *hash_algo = "crc32";
277 	bool do_hash = false;
278 	bool do_sign = false;
279 
280 	switch (params->auto_fit) {
281 	case AF_OFF:
282 		break;
283 	case AF_HASHED_IMG:
284 		do_hash = is_images_subnode;
285 		break;
286 	case AF_SIGNED_IMG:
287 		do_sign = is_images_subnode;
288 		break;
289 	case AF_SIGNED_CONF:
290 		if (is_images_subnode) {
291 			do_hash = true;
292 			hash_algo = "sha1";
293 		} else {
294 			do_sign = true;
295 		}
296 		break;
297 	default:
298 		fprintf(stderr,
299 			"%s: Unsupported auto FIT mode %u\n",
300 			params->cmdname, params->auto_fit);
301 		break;
302 	}
303 
304 	if (do_hash) {
305 		fdt_begin_node(fdt, FIT_HASH_NODENAME);
306 		fdt_property_string(fdt, FIT_ALGO_PROP, hash_algo);
307 		fdt_end_node(fdt);
308 	}
309 
310 	if (do_sign) {
311 		fdt_begin_node(fdt, FIT_SIG_NODENAME);
312 		fdt_property_string(fdt, FIT_ALGO_PROP, params->algo_name);
313 		fdt_property_string(fdt, FIT_KEY_HINT, params->keyname);
314 		fdt_end_node(fdt);
315 	}
316 }
317 
318 /**
319  * fit_write_images() - Write out a list of images to the FIT
320  *
321  * We always include the main image (params->datafile). If there are device
322  * tree files, we include an fdt- node for each of those too.
323  */
fit_write_images(struct image_tool_params * params,char * fdt)324 static int fit_write_images(struct image_tool_params *params, char *fdt)
325 {
326 	struct content_info *cont;
327 	const char *typename;
328 	char str[100];
329 	int upto;
330 	int ret;
331 
332 	fdt_begin_node(fdt, "images");
333 
334 	/* First the main image */
335 	typename = genimg_get_type_short_name(params->fit_image_type);
336 	snprintf(str, sizeof(str), "%s-1", typename);
337 	fdt_begin_node(fdt, str);
338 	fdt_property_string(fdt, FIT_DESC_PROP, params->imagename);
339 	fdt_property_string(fdt, FIT_TYPE_PROP, typename);
340 	fdt_property_string(fdt, FIT_ARCH_PROP,
341 			    genimg_get_arch_short_name(params->arch));
342 	fdt_property_string(fdt, FIT_OS_PROP,
343 			    genimg_get_os_short_name(params->os));
344 	fdt_property_string(fdt, FIT_COMP_PROP,
345 			    genimg_get_comp_short_name(params->comp));
346 	fdt_property_u32(fdt, FIT_LOAD_PROP, params->addr);
347 	fdt_property_u32(fdt, FIT_ENTRY_PROP, params->ep);
348 
349 	/*
350 	 * Put data last since it is large. SPL may only load the first part
351 	 * of the DT, so this way it can access all the above fields.
352 	 */
353 	ret = fdt_property_file(params, fdt, FIT_DATA_PROP, params->datafile);
354 	if (ret)
355 		return ret;
356 	fit_add_hash_or_sign(params, fdt, true);
357 	fdt_end_node(fdt);
358 
359 	/* Now the device tree files if available */
360 	upto = 0;
361 	for (cont = params->content_head; cont; cont = cont->next) {
362 		if (cont->type != IH_TYPE_FLATDT)
363 			continue;
364 		typename = genimg_get_type_short_name(cont->type);
365 		snprintf(str, sizeof(str), "%s-%d", FIT_FDT_PROP, ++upto);
366 		fdt_begin_node(fdt, str);
367 
368 		get_basename(str, sizeof(str), cont->fname);
369 		fdt_property_string(fdt, FIT_DESC_PROP, str);
370 		ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
371 					cont->fname);
372 		if (ret)
373 			return ret;
374 		fdt_property_string(fdt, FIT_TYPE_PROP, typename);
375 		fdt_property_string(fdt, FIT_ARCH_PROP,
376 				    genimg_get_arch_short_name(params->arch));
377 		fdt_property_string(fdt, FIT_COMP_PROP,
378 				    genimg_get_comp_short_name(IH_COMP_NONE));
379 		fit_add_hash_or_sign(params, fdt, true);
380 		if (ret)
381 			return ret;
382 		fdt_end_node(fdt);
383 	}
384 
385 	/* And a ramdisk file if available */
386 	if (params->fit_ramdisk) {
387 		fdt_begin_node(fdt, FIT_RAMDISK_PROP "-1");
388 
389 		fdt_property_string(fdt, FIT_TYPE_PROP, FIT_RAMDISK_PROP);
390 		fdt_property_string(fdt, FIT_OS_PROP,
391 				    genimg_get_os_short_name(params->os));
392 		fdt_property_string(fdt, FIT_ARCH_PROP,
393 				    genimg_get_arch_short_name(params->arch));
394 
395 		ret = fdt_property_file(params, fdt, FIT_DATA_PROP,
396 					params->fit_ramdisk);
397 		if (ret)
398 			return ret;
399 		fit_add_hash_or_sign(params, fdt, true);
400 		if (ret)
401 			return ret;
402 		fdt_end_node(fdt);
403 	}
404 
405 	fdt_end_node(fdt);
406 
407 	return 0;
408 }
409 
410 /**
411  * fit_write_configs() - Write out a list of configurations to the FIT
412  *
413  * If there are device tree files, we include a configuration for each, which
414  * selects the main image (params->datafile) and its corresponding device
415  * tree file.
416  *
417  * Otherwise we just create a configuration with the main image in it.
418  */
fit_write_configs(struct image_tool_params * params,char * fdt)419 static void fit_write_configs(struct image_tool_params *params, char *fdt)
420 {
421 	struct content_info *cont;
422 	const char *typename;
423 	char str[100];
424 	int upto;
425 
426 	fdt_begin_node(fdt, "configurations");
427 	fdt_property_string(fdt, FIT_DEFAULT_PROP, "conf-1");
428 
429 	upto = 0;
430 	for (cont = params->content_head; cont; cont = cont->next) {
431 		if (cont->type != IH_TYPE_FLATDT)
432 			continue;
433 		typename = genimg_get_type_short_name(cont->type);
434 		snprintf(str, sizeof(str), "conf-%d", ++upto);
435 		fdt_begin_node(fdt, str);
436 
437 		get_basename(str, sizeof(str), cont->fname);
438 		fdt_property_string(fdt, FIT_DESC_PROP, str);
439 
440 		typename = genimg_get_type_short_name(params->fit_image_type);
441 		snprintf(str, sizeof(str), "%s-1", typename);
442 		fdt_property_string(fdt, typename, str);
443 		fdt_property_string(fdt, FIT_LOADABLE_PROP, str);
444 
445 		if (params->fit_ramdisk)
446 			fdt_property_string(fdt, FIT_RAMDISK_PROP,
447 					    FIT_RAMDISK_PROP "-1");
448 
449 		snprintf(str, sizeof(str), FIT_FDT_PROP "-%d", upto);
450 		fdt_property_string(fdt, FIT_FDT_PROP, str);
451 		fit_add_hash_or_sign(params, fdt, false);
452 		fdt_end_node(fdt);
453 	}
454 
455 	if (!upto) {
456 		fdt_begin_node(fdt, "conf-1");
457 		typename = genimg_get_type_short_name(params->fit_image_type);
458 		snprintf(str, sizeof(str), "%s-1", typename);
459 		fdt_property_string(fdt, typename, str);
460 
461 		if (params->fit_ramdisk)
462 			fdt_property_string(fdt, FIT_RAMDISK_PROP,
463 					    FIT_RAMDISK_PROP "-1");
464 		fit_add_hash_or_sign(params, fdt, false);
465 
466 		fdt_end_node(fdt);
467 	}
468 
469 	fdt_end_node(fdt);
470 }
471 
fit_build_fdt(struct image_tool_params * params,char * fdt,int size)472 static int fit_build_fdt(struct image_tool_params *params, char *fdt, int size)
473 {
474 	int ret;
475 
476 	ret = fdt_create(fdt, size);
477 	if (ret)
478 		return ret;
479 	fdt_finish_reservemap(fdt);
480 	fdt_begin_node(fdt, "");
481 	fdt_property_strf(fdt, FIT_DESC_PROP,
482 			  "%s image with one or more FDT blobs",
483 			  genimg_get_type_name(params->fit_image_type));
484 	fdt_property_strf(fdt, "creator", "U-Boot mkimage %s", PLAIN_VERSION);
485 	fdt_property_u32(fdt, "#address-cells", 1);
486 	ret = fit_write_images(params, fdt);
487 	if (ret)
488 		return ret;
489 	fit_write_configs(params, fdt);
490 	fdt_end_node(fdt);
491 	ret = fdt_finish(fdt);
492 	if (ret)
493 		return ret;
494 
495 	return fdt_totalsize(fdt);
496 }
497 
fit_build(struct image_tool_params * params,const char * fname)498 static int fit_build(struct image_tool_params *params, const char *fname)
499 {
500 	char *buf;
501 	int size;
502 	int ret;
503 	int fd;
504 
505 	size = fit_calc_size(params);
506 	if (size < 0)
507 		return -1;
508 	buf = calloc(1, size);
509 	if (!buf) {
510 		fprintf(stderr, "%s: Out of memory (%d bytes)\n",
511 			params->cmdname, size);
512 		return -1;
513 	}
514 	ret = fit_build_fdt(params, buf, size);
515 	if (ret < 0) {
516 		fprintf(stderr, "%s: Failed to build FIT image\n",
517 			params->cmdname);
518 		goto err_buf;
519 	}
520 	size = ret;
521 	fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
522 	if (fd < 0) {
523 		fprintf(stderr, "%s: Can't open %s: %s\n",
524 			params->cmdname, fname, strerror(errno));
525 		goto err_buf;
526 	}
527 	ret = write(fd, buf, size);
528 	if (ret != size) {
529 		fprintf(stderr, "%s: Can't write %s: %s\n",
530 			params->cmdname, fname, strerror(errno));
531 		goto err;
532 	}
533 	close(fd);
534 	free(buf);
535 
536 	return 0;
537 err:
538 	close(fd);
539 err_buf:
540 	free(buf);
541 	return -1;
542 }
543 
544 /**
545  * fit_extract_data() - Move all data outside the FIT
546  *
547  * This takes a normal FIT file and removes all the 'data' properties from it.
548  * The data is placed in an area after the FIT so that it can be accessed
549  * using an offset into that area. The 'data' properties turn into
550  * 'data-offset' properties.
551  *
552  * This function cannot cope with FITs with 'data-offset' properties. All
553  * data must be in 'data' properties on entry.
554  */
fit_extract_data(struct image_tool_params * params,const char * fname)555 static int fit_extract_data(struct image_tool_params *params, const char *fname)
556 {
557 	void *buf = NULL;
558 	int buf_ptr;
559 	int fit_size, unpadded_size, new_size, pad_boundary;
560 	int fd;
561 	struct stat sbuf;
562 	void *fdt;
563 	int ret;
564 	int images;
565 	int node;
566 	int image_number;
567 	int align_size;
568 
569 	align_size = params->bl_len ? params->bl_len : 4;
570 	fd = mmap_fdt(params->cmdname, fname, 0, &fdt, &sbuf, false, false);
571 	if (fd < 0)
572 		return -EIO;
573 	fit_size = fdt_totalsize(fdt);
574 
575 	images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
576 	if (images < 0) {
577 		debug("%s: Cannot find /images node: %d\n", __func__, images);
578 		ret = -EINVAL;
579 		goto err_munmap;
580 	}
581 	image_number = fdtdec_get_child_count(fdt, images);
582 
583 	/*
584 	 * Allocate space to hold the image data we will extract,
585 	 * extral space allocate for image alignment to prevent overflow.
586 	 */
587 	buf = calloc(1, fit_size + (align_size * image_number));
588 	if (!buf) {
589 		ret = -ENOMEM;
590 		goto err_munmap;
591 	}
592 	buf_ptr = 0;
593 
594 	for (node = fdt_first_subnode(fdt, images);
595 	     node >= 0;
596 	     node = fdt_next_subnode(fdt, node)) {
597 		const char *data;
598 		int len;
599 
600 		data = fdt_getprop(fdt, node, FIT_DATA_PROP, &len);
601 		if (!data)
602 			continue;
603 		memcpy(buf + buf_ptr, data, len);
604 		debug("Extracting data size %x\n", len);
605 
606 		ret = fdt_delprop(fdt, node, FIT_DATA_PROP);
607 		if (ret) {
608 			ret = -EPERM;
609 			goto err_munmap;
610 		}
611 		if (params->external_offset > 0) {
612 			/* An external offset positions the data absolutely. */
613 			fdt_setprop_u32(fdt, node, FIT_DATA_POSITION_PROP,
614 					params->external_offset + buf_ptr);
615 		} else {
616 			fdt_setprop_u32(fdt, node, FIT_DATA_OFFSET_PROP,
617 					buf_ptr);
618 		}
619 		fdt_setprop_u32(fdt, node, FIT_DATA_SIZE_PROP, len);
620 		buf_ptr += ALIGN(len, align_size);
621 	}
622 
623 	/* Pack the FDT and place the data after it */
624 	fdt_pack(fdt);
625 
626 	unpadded_size = fdt_totalsize(fdt);
627 	new_size = ALIGN(unpadded_size, align_size);
628 	fdt_set_totalsize(fdt, new_size);
629 	if (unpadded_size < fit_size) {
630 		pad_boundary = new_size < fit_size ? new_size : fit_size;
631 		memset(fdt + unpadded_size, 0, pad_boundary - unpadded_size);
632 	}
633 	debug("Size reduced from %x to %x\n", fit_size, fdt_totalsize(fdt));
634 	debug("External data size %x\n", buf_ptr);
635 	munmap(fdt, sbuf.st_size);
636 
637 	if (ftruncate(fd, new_size)) {
638 		debug("%s: Failed to truncate file: %s\n", __func__,
639 		      strerror(errno));
640 		ret = -EIO;
641 		goto err;
642 	}
643 
644 	/* Check if an offset for the external data was set. */
645 	if (params->external_offset > 0) {
646 		if (params->external_offset < new_size) {
647 			fprintf(stderr,
648 				"External offset %x overlaps FIT length %x\n",
649 				params->external_offset, new_size);
650 			ret = -EINVAL;
651 			goto err;
652 		}
653 		new_size = params->external_offset;
654 	}
655 	if (lseek(fd, new_size, SEEK_SET) < 0) {
656 		debug("%s: Failed to seek to end of file: %s\n", __func__,
657 		      strerror(errno));
658 		ret = -EIO;
659 		goto err;
660 	}
661 	if (write(fd, buf, buf_ptr) != buf_ptr) {
662 		debug("%s: Failed to write external data to file %s\n",
663 		      __func__, strerror(errno));
664 		ret = -EIO;
665 		goto err;
666 	}
667 	free(buf);
668 	close(fd);
669 	return 0;
670 
671 err_munmap:
672 	munmap(fdt, sbuf.st_size);
673 err:
674 	free(buf);
675 	close(fd);
676 	return ret;
677 }
678 
fit_import_data(struct image_tool_params * params,const char * fname)679 static int fit_import_data(struct image_tool_params *params, const char *fname)
680 {
681 	void *fdt, *old_fdt;
682 	void *data = NULL;
683 	const char *ext_data_prop = NULL;
684 	int fit_size, new_size, size, data_base;
685 	int fd;
686 	struct stat sbuf;
687 	int ret;
688 	int images;
689 	int confs;
690 	int node;
691 
692 	fd = mmap_fdt(params->cmdname, fname, 0, &old_fdt, &sbuf, false, false);
693 	if (fd < 0)
694 		return -EIO;
695 	fit_size = fdt_totalsize(old_fdt);
696 	data_base = ALIGN(fit_size, 4);
697 
698 	/* Allocate space to hold the new FIT */
699 	size = sbuf.st_size + 16384;
700 	fdt = calloc(1, size);
701 	if (!fdt) {
702 		fprintf(stderr, "%s: Failed to allocate memory (%d bytes)\n",
703 			__func__, size);
704 		ret = -ENOMEM;
705 		goto err_munmap;
706 	}
707 	ret = fdt_open_into(old_fdt, fdt, size);
708 	if (ret) {
709 		debug("%s: Failed to expand FIT: %s\n", __func__,
710 		      fdt_strerror(errno));
711 		ret = -EINVAL;
712 		goto err_munmap;
713 	}
714 
715 	images = fdt_path_offset(fdt, FIT_IMAGES_PATH);
716 	if (images < 0) {
717 		debug("%s: Cannot find /images node: %d\n", __func__, images);
718 		ret = -EINVAL;
719 		goto err_munmap;
720 	}
721 
722 	for (node = fdt_first_subnode(fdt, images);
723 	     node >= 0;
724 	     node = fdt_next_subnode(fdt, node)) {
725 		int buf_ptr;
726 		int len;
727 
728 		/*
729 		 * FIT_DATA_OFFSET_PROP and FIT_DATA_POSITION_PROP are never both present,
730 		 *  but if they are, prefer FIT_DATA_OFFSET_PROP as it was there first
731 		 */
732 		buf_ptr = fdtdec_get_int(fdt, node, FIT_DATA_POSITION_PROP, -1);
733 		if (buf_ptr != -1) {
734 			ext_data_prop = FIT_DATA_POSITION_PROP;
735 			data = old_fdt + buf_ptr;
736 		}
737 		buf_ptr = fdtdec_get_int(fdt, node, FIT_DATA_OFFSET_PROP, -1);
738 		if (buf_ptr != -1) {
739 			ext_data_prop = FIT_DATA_OFFSET_PROP;
740 			data = old_fdt + data_base + buf_ptr;
741 		}
742 		len = fdtdec_get_int(fdt, node, FIT_DATA_SIZE_PROP, -1);
743 		if (!data || len == -1)
744 			continue;
745 		debug("Importing data size %x\n", len);
746 
747 		ret = fdt_setprop(fdt, node, FIT_DATA_PROP, data, len);
748 		ret = fdt_delprop(fdt, node, ext_data_prop);
749 
750 		if (ret) {
751 			debug("%s: Failed to write property: %s\n", __func__,
752 			      fdt_strerror(ret));
753 			ret = -EINVAL;
754 			goto err_munmap;
755 		}
756 	}
757 
758 	confs = fdt_path_offset(fdt, FIT_CONFS_PATH);
759 	const char *default_conf =
760 		(char *)fdt_getprop(fdt, confs, FIT_DEFAULT_PROP, NULL);
761 	static const char * const props[] = { FIT_KERNEL_PROP,
762 					      FIT_RAMDISK_PROP,
763 					      FIT_FDT_PROP,
764 					      FIT_LOADABLE_PROP,
765 					      FIT_FPGA_PROP,
766 					      FIT_FIRMWARE_PROP,
767 					      FIT_SCRIPT_PROP};
768 
769 	if (default_conf && fdt_subnode_offset(fdt, confs, default_conf) < 0) {
770 		fprintf(stderr,
771 			"Error: Default configuration '%s' not found under /configurations\n",
772 			default_conf);
773 		ret = FDT_ERR_NOTFOUND;
774 		goto err_munmap;
775 	}
776 
777 	fdt_for_each_subnode(node, fdt, confs) {
778 		const char *conf_name = fdt_get_name(fdt, node, NULL);
779 
780 		for (int i = 0; i < ARRAY_SIZE(props); i++) {
781 			int count = fdt_stringlist_count(fdt, node, props[i]);
782 
783 			if (count < 0)
784 				continue;
785 
786 			for (int j = 0; j < count; j++) {
787 				const char *img_name =
788 					fdt_stringlist_get(fdt, node, props[i], j, NULL);
789 				if (!img_name || !*img_name)
790 					continue;
791 
792 				int img = fdt_subnode_offset(fdt, images, img_name);
793 
794 				if (img < 0) {
795 					fprintf(stderr,
796 						"Error: configuration '%s' references undefined image '%s' in property '%s'\n",
797 						conf_name, img_name, props[i]);
798 					ret = FDT_ERR_NOTFOUND;
799 					goto err_munmap;
800 				}
801 			}
802 		}
803 	}
804 
805 	munmap(old_fdt, sbuf.st_size);
806 
807 	/* Close the old fd so we can re-use it. */
808 	close(fd);
809 
810 	/* Pack the FDT and place the data after it */
811 	fdt_pack(fdt);
812 
813 	new_size = fdt_totalsize(fdt);
814 	debug("Size expanded from %x to %x\n", fit_size, new_size);
815 
816 	fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
817 	if (fd < 0) {
818 		fprintf(stderr, "%s: Can't open %s: %s\n",
819 			params->cmdname, fname, strerror(errno));
820 		ret = -EIO;
821 		goto err;
822 	}
823 	if (write(fd, fdt, new_size) != new_size) {
824 		debug("%s: Failed to write external data to file %s\n",
825 		      __func__, strerror(errno));
826 		ret = -EIO;
827 		goto err;
828 	}
829 
830 	free(fdt);
831 	close(fd);
832 	return 0;
833 
834 err_munmap:
835 	munmap(old_fdt, sbuf.st_size);
836 err:
837 	free(fdt);
838 	close(fd);
839 	return ret;
840 }
841 
842 /**
843  * fit_handle_file - main FIT file processing function
844  *
845  * fit_handle_file() runs dtc to convert .its to .itb, includes
846  * binary data, updates timestamp property and calculates hashes.
847  *
848  * datafile  - .its file
849  * imagefile - .itb file
850  *
851  * returns:
852  *     only on success, otherwise calls exit (EXIT_FAILURE);
853  */
fit_handle_file(struct image_tool_params * params)854 static int fit_handle_file(struct image_tool_params *params)
855 {
856 	char tmpfile[MKIMAGE_MAX_TMPFILE_LEN];
857 	char bakfile[MKIMAGE_MAX_TMPFILE_LEN + 4] = {0};
858 	char cmd[MKIMAGE_MAX_DTC_CMDLINE_LEN];
859 	int size_inc;
860 	int ret = EXIT_FAILURE;
861 
862 	/* Flattened Image Tree (FIT) format  handling */
863 	debug ("FIT format handling\n");
864 
865 	/* call dtc to include binary properties into the tmp file */
866 	if (strlen (params->imagefile) +
867 		strlen (MKIMAGE_TMPFILE_SUFFIX) + 1 > sizeof (tmpfile)) {
868 		fprintf (stderr, "%s: Image file name (%s) too long, "
869 				"can't create tmpfile.\n",
870 				params->imagefile, params->cmdname);
871 		return (EXIT_FAILURE);
872 	}
873 	sprintf (tmpfile, "%s%s", params->imagefile, MKIMAGE_TMPFILE_SUFFIX);
874 
875 	/* We either compile the source file, or use the existing FIT image */
876 	if (params->auto_fit) {
877 		if (fit_build(params, tmpfile)) {
878 			fprintf(stderr, "%s: failed to build FIT\n",
879 				params->cmdname);
880 			return EXIT_FAILURE;
881 		}
882 		*cmd = '\0';
883 	} else if (params->datafile) {
884 		/* dtc -I dts -O dtb -p 500 -o tmpfile datafile */
885 		snprintf(cmd, sizeof(cmd), "%s %s -o \"%s\" \"%s\"",
886 			 MKIMAGE_DTC, params->dtc, tmpfile, params->datafile);
887 		debug("Trying to execute \"%s\"\n", cmd);
888 	} else {
889 		snprintf(cmd, sizeof(cmd), "cp \"%s\" \"%s\"",
890 			 params->imagefile, tmpfile);
891 	}
892 	if (strlen(cmd) >= MKIMAGE_MAX_DTC_CMDLINE_LEN - 1) {
893 		fprintf(stderr, "WARNING: command-line for FIT creation might be truncated and will probably fail.\n");
894 	}
895 
896 	if (*cmd && system(cmd) == -1) {
897 		fprintf (stderr, "%s: system(%s) failed: %s\n",
898 				params->cmdname, cmd, strerror(errno));
899 		goto err_system;
900 	}
901 
902 	/* Move the data so it is internal to the FIT, if needed */
903 	ret = fit_import_data(params, tmpfile);
904 	if (ret)
905 		goto err_system;
906 
907 	/*
908 	 * Copy the tmpfile to bakfile, then in the following loop
909 	 * we copy bakfile to tmpfile. So we always start from the
910 	 * beginning.
911 	 */
912 	sprintf(bakfile, "%s%s", tmpfile, ".bak");
913 	rename(tmpfile, bakfile);
914 
915 	/*
916 	 * Set hashes for images in the blob and compute
917 	 * signatures. We do an attempt at estimating the expected
918 	 * extra size, but just in case that is not sufficient, keep
919 	 * trying adding 1K, with a reasonable upper bound of 64K
920 	 * total, until we succeed.
921 	 */
922 	size_inc = fit_estimate_hash_sig_size(params, bakfile);
923 	if (size_inc < 0)
924 		goto err_system;
925 	do {
926 		if (copyfile(bakfile, tmpfile) < 0) {
927 			printf("Can't copy %s to %s\n", bakfile, tmpfile);
928 			ret = -EIO;
929 			break;
930 		}
931 		ret = fit_add_file_data(params, size_inc, tmpfile);
932 		if (!ret || ret != -ENOSPC)
933 			break;
934 		size_inc += 1024;
935 	} while (size_inc < 64 * 1024);
936 
937 	if (ret) {
938 		fprintf(stderr, "%s Can't add hashes to FIT blob: %d\n",
939 			params->cmdname, ret);
940 		goto err_system;
941 	}
942 
943 	/* Move the data so it is external to the FIT, if requested */
944 	if (params->external_data) {
945 		ret = fit_extract_data(params, tmpfile);
946 		if (ret)
947 			goto err_system;
948 	}
949 
950 	if (rename (tmpfile, params->imagefile) == -1) {
951 		fprintf (stderr, "%s: Can't rename %s to %s: %s\n",
952 				params->cmdname, tmpfile, params->imagefile,
953 				strerror (errno));
954 		unlink (tmpfile);
955 		unlink(bakfile);
956 		unlink (params->imagefile);
957 		return EXIT_FAILURE;
958 	}
959 	unlink(bakfile);
960 	return EXIT_SUCCESS;
961 
962 err_system:
963 	unlink(tmpfile);
964 	unlink(bakfile);
965 	return ret;
966 }
967 
968 /**
969  * fit_image_extract - extract a FIT component image
970  * @fit: pointer to the FIT format image header
971  * @image_noffset: offset of the component image node
972  * @file_name: name of the file to store the FIT sub-image
973  *
974  * returns:
975  *     zero in case of success or a negative value if fail.
976  */
fit_image_extract(const void * fit,int image_noffset,const char * file_name)977 static int fit_image_extract(
978 	const void *fit,
979 	int image_noffset,
980 	const char *file_name)
981 {
982 	const void *file_data;
983 	size_t file_size = 0;
984 	int ret;
985 
986 	/* get the data address and size of component at offset "image_noffset" */
987 	ret = fit_image_get_data(fit, image_noffset, &file_data, &file_size);
988 	if (ret) {
989 		fprintf(stderr, "Could not get component information\n");
990 		return ret;
991 	}
992 
993 	/* save the "file_data" into the file specified by "file_name" */
994 	return imagetool_save_subimage(file_name, (ulong) file_data, file_size);
995 }
996 
997 /**
998  * fit_extract_contents - retrieve a sub-image component from the FIT image
999  * @ptr: pointer to the FIT format image header
1000  * @params: command line parameters
1001  *
1002  * returns:
1003  *     zero in case of success or a negative value if fail.
1004  */
fit_extract_contents(void * ptr,struct image_tool_params * params)1005 static int fit_extract_contents(void *ptr, struct image_tool_params *params)
1006 {
1007 	int images_noffset;
1008 	int noffset;
1009 	int ndepth;
1010 	const void *fit = ptr;
1011 	int count = 0;
1012 	const char *p;
1013 
1014 	/* Indent string is defined in header image.h */
1015 	p = IMAGE_INDENT_STRING;
1016 
1017 	/* Find images parent node offset */
1018 	images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
1019 	if (images_noffset < 0) {
1020 		printf("Can't find images parent node '%s' (%s)\n",
1021 		       FIT_IMAGES_PATH, fdt_strerror(images_noffset));
1022 		return -1;
1023 	}
1024 
1025 	/* Avoid any overrun */
1026 	count = fit_get_subimage_count(fit, images_noffset);
1027 	if ((params->pflag < 0) || (count <= params->pflag)) {
1028 		printf("No such component at '%d'\n", params->pflag);
1029 		return -1;
1030 	}
1031 
1032 	/* Process its subnodes, extract the desired component from image */
1033 	for (ndepth = 0, count = 0,
1034 		noffset = fdt_next_node(fit, images_noffset, &ndepth);
1035 		(noffset >= 0) && (ndepth > 0);
1036 		noffset = fdt_next_node(fit, noffset, &ndepth)) {
1037 		if (ndepth == 1) {
1038 			/*
1039 			 * Direct child node of the images parent node,
1040 			 * i.e. component image node.
1041 			 */
1042 			if (params->pflag == count) {
1043 				printf("Extracted:\n%s Image %u (%s)\n", p,
1044 				       count, fit_get_name(fit, noffset, NULL));
1045 
1046 				fit_image_print(fit, noffset, p);
1047 
1048 				return fit_image_extract(fit, noffset,
1049 						params->outfile);
1050 			}
1051 
1052 			count++;
1053 		}
1054 	}
1055 
1056 	return 0;
1057 }
1058 
fit_check_params(struct image_tool_params * params)1059 static int fit_check_params(struct image_tool_params *params)
1060 {
1061 	if (params->auto_fit)
1062 		return 0;
1063 	return	((params->dflag && params->fflag) ||
1064 		 (params->fflag && params->lflag) ||
1065 		 (params->lflag && params->dflag));
1066 }
1067 
1068 U_BOOT_IMAGE_TYPE(
1069 	fitimage,
1070 	"FIT Image support",
1071 	sizeof(struct legacy_img_hdr),
1072 	(void *)&header,
1073 	fit_check_params,
1074 	fit_verify_header,
1075 	fit_print_header,
1076 	NULL,
1077 	fit_extract_contents,
1078 	fit_check_image_types,
1079 	fit_handle_file,
1080 	NULL /* FIT images use DTB header */
1081 );
1082