1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * (C) Copyright 2014
4 * DENX Software Engineering
5 * Heiko Schocher <hs@denx.de>
6 *
7 * (C) Copyright 2008 Semihalf
8 *
9 * (C) Copyright 2000-2004
10 * DENX Software Engineering
11 * Wolfgang Denk, wd@denx.de
12 *
13 * Updated-by: Prafulla Wadaskar <prafulla@marvell.com>
14 * FIT image specific code abstracted from mkimage.c
15 * some functions added to address abstraction
16 *
17 * All rights reserved.
18 */
19
20 #include "imagetool.h"
21 #include "mkimage.h"
22 #include "fit_common.h"
23 #include <image.h>
24 #include <u-boot/crc.h>
25
fit_verify_header(unsigned char * ptr,int image_size,struct image_tool_params * params)26 int fit_verify_header(unsigned char *ptr, int image_size,
27 struct image_tool_params *params)
28 {
29 if (fdt_check_header(ptr) != EXIT_SUCCESS ||
30 fit_check_format(ptr, IMAGE_SIZE_INVAL))
31 return EXIT_FAILURE;
32
33 return EXIT_SUCCESS;
34 }
35
fit_check_image_types(uint8_t type)36 int fit_check_image_types(uint8_t type)
37 {
38 if (type == IH_TYPE_FLATDT)
39 return EXIT_SUCCESS;
40 else
41 return EXIT_FAILURE;
42 }
43
mmap_fdt(const char * cmdname,const char * fname,size_t size_inc,void ** blobp,struct stat * sbuf,bool delete_on_error,bool read_only)44 int mmap_fdt(const char *cmdname, const char *fname, size_t size_inc,
45 void **blobp, struct stat *sbuf, bool delete_on_error,
46 bool read_only)
47 {
48 void *ptr;
49 int fd;
50
51 /* Load FIT blob into memory (we need to write hashes/signatures) */
52 fd = open(fname, (read_only ? O_RDONLY : O_RDWR) | O_BINARY);
53
54 if (fd < 0) {
55 fprintf(stderr, "%s: Can't open %s: %s\n",
56 cmdname, fname, strerror(errno));
57 goto err;
58 }
59
60 if (fstat(fd, sbuf) < 0) {
61 fprintf(stderr, "%s: Can't stat %s: %s\n",
62 cmdname, fname, strerror(errno));
63 goto err;
64 }
65
66 if (size_inc) {
67 sbuf->st_size += size_inc;
68 if (ftruncate(fd, sbuf->st_size)) {
69 fprintf(stderr, "%s: Can't expand %s: %s\n",
70 cmdname, fname, strerror(errno));
71 goto err;
72 }
73 }
74
75 errno = 0;
76 ptr = mmap(0, sbuf->st_size,
77 (read_only ? PROT_READ : PROT_READ | PROT_WRITE), MAP_SHARED,
78 fd, 0);
79 if ((ptr == MAP_FAILED) || (errno != 0)) {
80 fprintf(stderr, "%s: Can't read %s: %s\n",
81 cmdname, fname, strerror(errno));
82 goto err;
83 }
84
85 /* check if ptr has a valid blob */
86 if (fdt_check_header(ptr)) {
87 fprintf(stderr, "%s: Invalid FIT blob\n", cmdname);
88 goto err;
89 }
90
91 /* expand if needed */
92 if (size_inc) {
93 int ret;
94
95 ret = fdt_open_into(ptr, ptr, sbuf->st_size);
96 if (ret) {
97 fprintf(stderr, "%s: Cannot expand FDT: %s\n",
98 cmdname, fdt_strerror(ret));
99 goto err;
100 }
101 }
102
103 *blobp = ptr;
104 return fd;
105
106 err:
107 if (fd >= 0)
108 close(fd);
109 if (delete_on_error)
110 unlink(fname);
111
112 return -1;
113 }
114