xref: /rk3399_rockchip-uboot/tools/fit_image.c (revision fb4cce0f98ea0784130ff544d7c85d0841bea2e6)
1 /*
2  * (C) Copyright 2008 Semihalf
3  *
4  * (C) Copyright 2000-2004
5  * DENX Software Engineering
6  * Wolfgang Denk, wd@denx.de
7  *
8  * Updated-by: Prafulla Wadaskar <prafulla@marvell.com>
9  *		FIT image specific code abstracted from mkimage.c
10  *		some functions added to address abstraction
11  *
12  * All rights reserved.
13  *
14  * SPDX-License-Identifier:	GPL-2.0+
15  */
16 
17 #include "imagetool.h"
18 #include "fit_common.h"
19 #include "mkimage.h"
20 #include <image.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 	if (tfd < 0)
39 		return -EIO;
40 
41 	if (params->keydest) {
42 		struct stat dest_sbuf;
43 
44 		destfd = mmap_fdt(params->cmdname, params->keydest, size_inc,
45 				  &dest_blob, &dest_sbuf, false);
46 		if (destfd < 0) {
47 			ret = -EIO;
48 			goto err_keydest;
49 		}
50 		destfd_size = dest_sbuf.st_size;
51 	}
52 
53 	/* for first image creation, add a timestamp at offset 0 i.e., root  */
54 	if (params->datafile)
55 		ret = fit_set_timestamp(ptr, 0, sbuf.st_mtime);
56 
57 	if (!ret) {
58 		ret = fit_add_verification_data(params->keydir, dest_blob, ptr,
59 						params->comment,
60 						params->require_keys);
61 	}
62 
63 	if (dest_blob) {
64 		munmap(dest_blob, destfd_size);
65 		close(destfd);
66 	}
67 
68 err_keydest:
69 	munmap(ptr, sbuf.st_size);
70 	close(tfd);
71 
72 	return ret;
73 }
74 
75 /**
76  * fit_calc_size() - Calculate the approximate size of the FIT we will generate
77  */
78 static int fit_calc_size(struct image_tool_params *params)
79 {
80 	struct content_info *cont;
81 	int size, total_size;
82 
83 	size = imagetool_get_filesize(params, params->datafile);
84 	if (size < 0)
85 		return -1;
86 
87 	total_size = size;
88 	for (cont = params->content_head; cont; cont = cont->next) {
89 		size = imagetool_get_filesize(params, cont->fname);
90 		if (size < 0)
91 			return -1;
92 
93 		/* Add space for properties */
94 		total_size += size + 300;
95 	}
96 
97 	/* Add plenty of space for headers, properties, nodes, etc. */
98 	total_size += 4096;
99 
100 	return total_size;
101 }
102 
103 static int fdt_property_file(struct image_tool_params *params,
104 			     void *fdt, const char *name, const char *fname)
105 {
106 	struct stat sbuf;
107 	void *ptr;
108 	int ret;
109 	int fd;
110 
111 	fd = open(fname, O_RDWR | O_BINARY);
112 	if (fd < 0) {
113 		fprintf(stderr, "%s: Can't open %s: %s\n",
114 			params->cmdname, fname, strerror(errno));
115 		return -1;
116 	}
117 
118 	if (fstat(fd, &sbuf) < 0) {
119 		fprintf(stderr, "%s: Can't stat %s: %s\n",
120 			params->cmdname, fname, strerror(errno));
121 		goto err;
122 	}
123 
124 	ret = fdt_property_placeholder(fdt, "data", sbuf.st_size, &ptr);
125 	if (ret)
126 		return ret;
127 	ret = read(fd, ptr, sbuf.st_size);
128 	if (ret != sbuf.st_size) {
129 		fprintf(stderr, "%s: Can't read %s: %s\n",
130 			params->cmdname, fname, strerror(errno));
131 		goto err;
132 	}
133 
134 	return 0;
135 err:
136 	close(fd);
137 	return -1;
138 }
139 
140 static int fdt_property_strf(void *fdt, const char *name, const char *fmt, ...)
141 {
142 	char str[100];
143 	va_list ptr;
144 
145 	va_start(ptr, fmt);
146 	vsnprintf(str, sizeof(str), fmt, ptr);
147 	va_end(ptr);
148 	return fdt_property_string(fdt, name, str);
149 }
150 
151 static void get_basename(char *str, int size, const char *fname)
152 {
153 	const char *p, *start, *end;
154 	int len;
155 
156 	/*
157 	 * Use the base name as the 'name' field. So for example:
158 	 *
159 	 * "arch/arm/dts/sun7i-a20-bananapro.dtb"
160 	 * becomes "sun7i-a20-bananapro"
161 	 */
162 	p = strrchr(fname, '/');
163 	start = p ? p + 1 : fname;
164 	p = strrchr(fname, '.');
165 	end = p ? p : fname + strlen(fname);
166 	len = end - start;
167 	if (len >= size)
168 		len = size - 1;
169 	memcpy(str, start, len);
170 	str[len] = '\0';
171 }
172 
173 /**
174  * fit_write_images() - Write out a list of images to the FIT
175  *
176  * We always include the main image (params->datafile). If there are device
177  * tree files, we include an fdt@ node for each of those too.
178  */
179 static int fit_write_images(struct image_tool_params *params, char *fdt)
180 {
181 	struct content_info *cont;
182 	const char *typename;
183 	char str[100];
184 	int upto;
185 	int ret;
186 
187 	fdt_begin_node(fdt, "images");
188 
189 	/* First the main image */
190 	typename = genimg_get_type_short_name(params->fit_image_type);
191 	snprintf(str, sizeof(str), "%s@1", typename);
192 	fdt_begin_node(fdt, str);
193 	fdt_property_string(fdt, "description", params->imagename);
194 	fdt_property_string(fdt, "type", typename);
195 	fdt_property_string(fdt, "arch", genimg_get_arch_name(params->arch));
196 	fdt_property_string(fdt, "os", genimg_get_os_short_name(params->os));
197 	fdt_property_string(fdt, "compression",
198 			    genimg_get_comp_short_name(params->comp));
199 	fdt_property_u32(fdt, "load", params->addr);
200 	fdt_property_u32(fdt, "entry", params->ep);
201 
202 	/*
203 	 * Put data last since it is large. SPL may only load the first part
204 	 * of the DT, so this way it can access all the above fields.
205 	 */
206 	ret = fdt_property_file(params, fdt, "data", params->datafile);
207 	if (ret)
208 		return ret;
209 	fdt_end_node(fdt);
210 
211 	/* Now the device tree files if available */
212 	upto = 0;
213 	for (cont = params->content_head; cont; cont = cont->next) {
214 		if (cont->type != IH_TYPE_FLATDT)
215 			continue;
216 		snprintf(str, sizeof(str), "%s@%d", FIT_FDT_PROP, ++upto);
217 		fdt_begin_node(fdt, str);
218 
219 		get_basename(str, sizeof(str), cont->fname);
220 		fdt_property_string(fdt, "description", str);
221 		ret = fdt_property_file(params, fdt, "data", cont->fname);
222 		if (ret)
223 			return ret;
224 		fdt_property_string(fdt, "type", typename);
225 		fdt_property_string(fdt, "arch",
226 				    genimg_get_arch_short_name(params->arch));
227 		fdt_property_string(fdt, "compression",
228 				    genimg_get_comp_short_name(IH_COMP_NONE));
229 		fdt_end_node(fdt);
230 	}
231 
232 	fdt_end_node(fdt);
233 
234 	return 0;
235 }
236 
237 /**
238  * fit_write_configs() - Write out a list of configurations to the FIT
239  *
240  * If there are device tree files, we include a configuration for each, which
241  * selects the main image (params->datafile) and its corresponding device
242  * tree file.
243  *
244  * Otherwise we just create a configuration with the main image in it.
245  */
246 static void fit_write_configs(struct image_tool_params *params, char *fdt)
247 {
248 	struct content_info *cont;
249 	const char *typename;
250 	char str[100];
251 	int upto;
252 
253 	fdt_begin_node(fdt, "configurations");
254 	fdt_property_string(fdt, "default", "conf@1");
255 
256 	upto = 0;
257 	for (cont = params->content_head; cont; cont = cont->next) {
258 		if (cont->type != IH_TYPE_FLATDT)
259 			continue;
260 		typename = genimg_get_type_short_name(cont->type);
261 		snprintf(str, sizeof(str), "conf@%d", ++upto);
262 		fdt_begin_node(fdt, str);
263 
264 		get_basename(str, sizeof(str), cont->fname);
265 		fdt_property_string(fdt, "description", str);
266 
267 		typename = genimg_get_type_short_name(params->fit_image_type);
268 		snprintf(str, sizeof(str), "%s@1", typename);
269 		fdt_property_string(fdt, typename, str);
270 
271 		snprintf(str, sizeof(str), FIT_FDT_PROP "@%d", upto);
272 		fdt_property_string(fdt, FIT_FDT_PROP, str);
273 		fdt_end_node(fdt);
274 	}
275 	if (!upto) {
276 		fdt_begin_node(fdt, "conf@1");
277 		typename = genimg_get_type_short_name(params->fit_image_type);
278 		snprintf(str, sizeof(str), "%s@1", typename);
279 		fdt_property_string(fdt, typename, str);
280 		fdt_end_node(fdt);
281 	}
282 
283 	fdt_end_node(fdt);
284 }
285 
286 static int fit_build_fdt(struct image_tool_params *params, char *fdt, int size)
287 {
288 	int ret;
289 
290 	ret = fdt_create(fdt, size);
291 	if (ret)
292 		return ret;
293 	fdt_finish_reservemap(fdt);
294 	fdt_begin_node(fdt, "");
295 	fdt_property_strf(fdt, "description",
296 			  "%s image with one or more FDT blobs",
297 			  genimg_get_type_name(params->fit_image_type));
298 	fdt_property_strf(fdt, "creator", "U-Boot mkimage %s", PLAIN_VERSION);
299 	fdt_property_u32(fdt, "#address-cells", 1);
300 	ret = fit_write_images(params, fdt);
301 	if (ret)
302 		return ret;
303 	fit_write_configs(params, fdt);
304 	fdt_end_node(fdt);
305 	ret = fdt_finish(fdt);
306 	if (ret)
307 		return ret;
308 
309 	return fdt_totalsize(fdt);
310 }
311 
312 static int fit_build(struct image_tool_params *params, const char *fname)
313 {
314 	char *buf;
315 	int size;
316 	int ret;
317 	int fd;
318 
319 	size = fit_calc_size(params);
320 	if (size < 0)
321 		return -1;
322 	buf = malloc(size);
323 	if (!buf) {
324 		fprintf(stderr, "%s: Out of memory (%d bytes)\n",
325 			params->cmdname, size);
326 		return -1;
327 	}
328 	ret = fit_build_fdt(params, buf, size);
329 	if (ret < 0) {
330 		fprintf(stderr, "%s: Failed to build FIT image\n",
331 			params->cmdname);
332 		goto err;
333 	}
334 	size = ret;
335 	fd = open(fname, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0666);
336 	if (fd < 0) {
337 		fprintf(stderr, "%s: Can't open %s: %s\n",
338 			params->cmdname, fname, strerror(errno));
339 		goto err;
340 	}
341 	ret = write(fd, buf, size);
342 	if (ret != size) {
343 		fprintf(stderr, "%s: Can't write %s: %s\n",
344 			params->cmdname, fname, strerror(errno));
345 		close(fd);
346 		goto err;
347 	}
348 	close(fd);
349 
350 	return 0;
351 err:
352 	free(buf);
353 	return -1;
354 }
355 
356 /**
357  * fit_handle_file - main FIT file processing function
358  *
359  * fit_handle_file() runs dtc to convert .its to .itb, includes
360  * binary data, updates timestamp property and calculates hashes.
361  *
362  * datafile  - .its file
363  * imagefile - .itb file
364  *
365  * returns:
366  *     only on success, otherwise calls exit (EXIT_FAILURE);
367  */
368 static int fit_handle_file(struct image_tool_params *params)
369 {
370 	char tmpfile[MKIMAGE_MAX_TMPFILE_LEN];
371 	char cmd[MKIMAGE_MAX_DTC_CMDLINE_LEN];
372 	size_t size_inc;
373 	int ret;
374 
375 	/* Flattened Image Tree (FIT) format  handling */
376 	debug ("FIT format handling\n");
377 
378 	/* call dtc to include binary properties into the tmp file */
379 	if (strlen (params->imagefile) +
380 		strlen (MKIMAGE_TMPFILE_SUFFIX) + 1 > sizeof (tmpfile)) {
381 		fprintf (stderr, "%s: Image file name (%s) too long, "
382 				"can't create tmpfile",
383 				params->imagefile, params->cmdname);
384 		return (EXIT_FAILURE);
385 	}
386 	sprintf (tmpfile, "%s%s", params->imagefile, MKIMAGE_TMPFILE_SUFFIX);
387 
388 	/* We either compile the source file, or use the existing FIT image */
389 	if (params->auto_its) {
390 		if (fit_build(params, tmpfile)) {
391 			fprintf(stderr, "%s: failed to build FIT\n",
392 				params->cmdname);
393 			return EXIT_FAILURE;
394 		}
395 		*cmd = '\0';
396 	} else if (params->datafile) {
397 		/* dtc -I dts -O dtb -p 500 datafile > tmpfile */
398 		snprintf(cmd, sizeof(cmd), "%s %s %s > %s",
399 			 MKIMAGE_DTC, params->dtc, params->datafile, tmpfile);
400 		debug("Trying to execute \"%s\"\n", cmd);
401 	} else {
402 		snprintf(cmd, sizeof(cmd), "cp %s %s",
403 			 params->imagefile, tmpfile);
404 	}
405 	if (*cmd && system(cmd) == -1) {
406 		fprintf (stderr, "%s: system(%s) failed: %s\n",
407 				params->cmdname, cmd, strerror(errno));
408 		goto err_system;
409 	}
410 
411 	/*
412 	 * Set hashes for images in the blob. Unfortunately we may need more
413 	 * space in either FDT, so keep trying until we succeed.
414 	 *
415 	 * Note: this is pretty inefficient for signing, since we must
416 	 * calculate the signature every time. It would be better to calculate
417 	 * all the data and then store it in a separate step. However, this
418 	 * would be considerably more complex to implement. Generally a few
419 	 * steps of this loop is enough to sign with several keys.
420 	 */
421 	for (size_inc = 0; size_inc < 64 * 1024; size_inc += 1024) {
422 		ret = fit_add_file_data(params, size_inc, tmpfile);
423 		if (!ret || ret != -ENOSPC)
424 			break;
425 	}
426 
427 	if (ret) {
428 		fprintf(stderr, "%s Can't add hashes to FIT blob\n",
429 			params->cmdname);
430 		goto err_system;
431 	}
432 
433 	if (rename (tmpfile, params->imagefile) == -1) {
434 		fprintf (stderr, "%s: Can't rename %s to %s: %s\n",
435 				params->cmdname, tmpfile, params->imagefile,
436 				strerror (errno));
437 		unlink (tmpfile);
438 		unlink (params->imagefile);
439 		return EXIT_FAILURE;
440 	}
441 	return EXIT_SUCCESS;
442 
443 err_system:
444 	unlink(tmpfile);
445 	return -1;
446 }
447 
448 /**
449  * fit_image_extract - extract a FIT component image
450  * @fit: pointer to the FIT format image header
451  * @image_noffset: offset of the component image node
452  * @file_name: name of the file to store the FIT sub-image
453  *
454  * returns:
455  *     zero in case of success or a negative value if fail.
456  */
457 static int fit_image_extract(
458 	const void *fit,
459 	int image_noffset,
460 	const char *file_name)
461 {
462 	const void *file_data;
463 	size_t file_size = 0;
464 
465 	/* get the "data" property of component at offset "image_noffset" */
466 	fit_image_get_data(fit, image_noffset, &file_data, &file_size);
467 
468 	/* save the "file_data" into the file specified by "file_name" */
469 	return imagetool_save_subimage(file_name, (ulong) file_data, file_size);
470 }
471 
472 /**
473  * fit_extract_contents - retrieve a sub-image component from the FIT image
474  * @ptr: pointer to the FIT format image header
475  * @params: command line parameters
476  *
477  * returns:
478  *     zero in case of success or a negative value if fail.
479  */
480 static int fit_extract_contents(void *ptr, struct image_tool_params *params)
481 {
482 	int images_noffset;
483 	int noffset;
484 	int ndepth;
485 	const void *fit = ptr;
486 	int count = 0;
487 	const char *p;
488 
489 	/* Indent string is defined in header image.h */
490 	p = IMAGE_INDENT_STRING;
491 
492 	if (!fit_check_format(fit)) {
493 		printf("Bad FIT image format\n");
494 		return -1;
495 	}
496 
497 	/* Find images parent node offset */
498 	images_noffset = fdt_path_offset(fit, FIT_IMAGES_PATH);
499 	if (images_noffset < 0) {
500 		printf("Can't find images parent node '%s' (%s)\n",
501 		       FIT_IMAGES_PATH, fdt_strerror(images_noffset));
502 		return -1;
503 	}
504 
505 	/* Avoid any overrun */
506 	count = fit_get_subimage_count(fit, images_noffset);
507 	if ((params->pflag < 0) || (count <= params->pflag)) {
508 		printf("No such component at '%d'\n", params->pflag);
509 		return -1;
510 	}
511 
512 	/* Process its subnodes, extract the desired component from image */
513 	for (ndepth = 0, count = 0,
514 		noffset = fdt_next_node(fit, images_noffset, &ndepth);
515 		(noffset >= 0) && (ndepth > 0);
516 		noffset = fdt_next_node(fit, noffset, &ndepth)) {
517 		if (ndepth == 1) {
518 			/*
519 			 * Direct child node of the images parent node,
520 			 * i.e. component image node.
521 			 */
522 			if (params->pflag == count) {
523 				printf("Extracted:\n%s Image %u (%s)\n", p,
524 				       count, fit_get_name(fit, noffset, NULL));
525 
526 				fit_image_print(fit, noffset, p);
527 
528 				return fit_image_extract(fit, noffset,
529 						params->outfile);
530 			}
531 
532 			count++;
533 		}
534 	}
535 
536 	return 0;
537 }
538 
539 static int fit_check_params(struct image_tool_params *params)
540 {
541 	if (params->auto_its)
542 		return 0;
543 	return	((params->dflag && (params->fflag || params->lflag)) ||
544 		(params->fflag && (params->dflag || params->lflag)) ||
545 		(params->lflag && (params->dflag || params->fflag)));
546 }
547 
548 U_BOOT_IMAGE_TYPE(
549 	fitimage,
550 	"FIT Image support",
551 	sizeof(image_header_t),
552 	(void *)&header,
553 	fit_check_params,
554 	fit_verify_header,
555 	fit_print_contents,
556 	NULL,
557 	fit_extract_contents,
558 	fit_check_image_types,
559 	fit_handle_file,
560 	NULL /* FIT images use DTB header */
561 );
562