1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * (C) Copyright 2011 Free Electrons
4  * David Wagner <david.wagner@free-electrons.com>
5  *
6  * Inspired from envcrc.c:
7  * (C) Copyright 2001
8  * Paolo Scaffardi, AIRVENT SAM s.p.a - RIMINI(ITALY), arsenio@tin.it
9  */
10 
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <stdint.h>
16 #include <string.h>
17 #include <u-boot/crc.h>
18 #include <unistd.h>
19 #include <libgen.h>
20 #include <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/mman.h>
23 
24 #include "compiler.h"
25 #include <u-boot/crc.h>
26 #include <version.h>
27 
28 #define CRC_SIZE sizeof(uint32_t)
29 
usage(const char * exec_name)30 static void usage(const char *exec_name)
31 {
32 	fprintf(stderr, "%s [-h] [-r] [-b] [-p <byte>] -s <environment partition size> -o <output> <input file>\n"
33 	       "\n"
34 	       "This tool takes a key=value input file (same as would a `printenv' show) and generates the corresponding environment image, ready to be flashed.\n"
35 	       "\n"
36 	       "\tThe input file is in format:\n"
37 	       "\t\tkey1=value1\n"
38 	       "\t\tkey2=value2\n"
39 	       "\t\t...\n"
40 	       "\tEmpty lines are skipped, and lines with a # in the first\n"
41 	       "\tcolumn are treated as comments (also skipped).\n"
42 	       "\t-r : the environment has multiple copies in flash\n"
43 	       "\t-b : the target is big endian (default is little endian)\n"
44 	       "\t-p <byte> : fill the image with <byte> bytes instead of 0xff bytes\n"
45 	       "\t-V : print version information and exit\n"
46 	       "\n"
47 	       "If the input file is \"-\", data is read from standard input\n",
48 	       exec_name);
49 }
50 
xstrtol(const char * s)51 long int xstrtol(const char *s)
52 {
53 	long int tmp;
54 
55 	errno = 0;
56 	tmp = strtol(s, NULL, 0);
57 	if (!errno)
58 		return tmp;
59 
60 	if (errno == ERANGE)
61 		fprintf(stderr, "Bad integer format: %s\n",  s);
62 	else
63 		fprintf(stderr, "Error while parsing %s: %s\n", s,
64 				strerror(errno));
65 
66 	exit(EXIT_FAILURE);
67 }
68 
69 #define CHUNK_SIZE 4096
70 
main(int argc,char ** argv)71 int main(int argc, char **argv)
72 {
73 	uint32_t crc, targetendian_crc;
74 	const char *bin_filename = NULL;
75 	int txt_fd, bin_fd;
76 	unsigned char *dataptr, *envptr;
77 	unsigned char *filebuf = NULL;
78 	unsigned int filesize = 0, envsize = 0, datasize = 0;
79 	int bigendian = 0;
80 	int redundant = 0;
81 	unsigned char padbyte = 0xff;
82 	int readbytes = 0;
83 
84 	int option;
85 	int ret = EXIT_SUCCESS;
86 
87 	int fp, ep;
88 	const char *prg;
89 
90 	prg = basename(argv[0]);
91 
92 	/* Turn off getopt()'s internal error message */
93 	opterr = 0;
94 
95 	/* Parse the cmdline */
96 	while ((option = getopt(argc, argv, ":s:o:rbp:hV")) != -1) {
97 		switch (option) {
98 		case 's':
99 			datasize = xstrtol(optarg);
100 			break;
101 		case 'o':
102 			bin_filename = strdup(optarg);
103 			if (!bin_filename) {
104 				fprintf(stderr, "Can't strdup() the output filename\n");
105 				return EXIT_FAILURE;
106 			}
107 			break;
108 		case 'r':
109 			redundant = 1;
110 			break;
111 		case 'b':
112 			bigendian = 1;
113 			break;
114 		case 'p':
115 			padbyte = xstrtol(optarg);
116 			break;
117 		case 'h':
118 			usage(prg);
119 			return EXIT_SUCCESS;
120 		case 'V':
121 			printf("%s version %s\n", prg, PLAIN_VERSION);
122 			return EXIT_SUCCESS;
123 		case ':':
124 			fprintf(stderr, "Missing argument for option -%c\n",
125 				optopt);
126 			usage(prg);
127 			return EXIT_FAILURE;
128 		default:
129 			fprintf(stderr, "Wrong option -%c\n", optopt);
130 			usage(prg);
131 			return EXIT_FAILURE;
132 		}
133 	}
134 
135 	/* Check datasize and allocate the data */
136 	if (datasize == 0) {
137 		fprintf(stderr, "Please specify the size of the environment partition.\n");
138 		usage(prg);
139 		return EXIT_FAILURE;
140 	}
141 
142 	dataptr = malloc(datasize * sizeof(*dataptr));
143 	if (!dataptr) {
144 		fprintf(stderr, "Can't alloc %d bytes for dataptr.\n",
145 				datasize);
146 		return EXIT_FAILURE;
147 	}
148 
149 	/*
150 	 * envptr points to the beginning of the actual environment (after the
151 	 * crc and possible `redundant' byte
152 	 */
153 	envsize = datasize - (CRC_SIZE + redundant);
154 	envptr = dataptr + CRC_SIZE + redundant;
155 
156 	/* Pad the environment with the padding byte */
157 	memset(envptr, padbyte, envsize);
158 
159 	/* Open the input file ... */
160 	if (optind >= argc || strcmp(argv[optind], "-") == 0) {
161 		txt_fd = STDIN_FILENO;
162 	} else {
163 		txt_fd = open(argv[optind], O_RDONLY);
164 		if (txt_fd == -1) {
165 			fprintf(stderr, "Can't open \"%s\": %s\n",
166 					argv[optind], strerror(errno));
167 			return EXIT_FAILURE;
168 		}
169 	}
170 
171 	do {
172 		filebuf = realloc(filebuf, filesize + CHUNK_SIZE);
173 		if (!filebuf) {
174 			fprintf(stderr, "Can't realloc memory for the input file buffer\n");
175 			return EXIT_FAILURE;
176 		}
177 		readbytes = read(txt_fd, filebuf + filesize, CHUNK_SIZE);
178 		if (readbytes < 0) {
179 			fprintf(stderr, "Error while reading: %s\n",
180 				strerror(errno));
181 			return EXIT_FAILURE;
182 		}
183 		filesize += readbytes;
184 	} while (readbytes > 0);
185 
186 	if (txt_fd != STDIN_FILENO)
187 		ret = close(txt_fd);
188 
189 	/* Parse a byte at time until reaching the file OR until the environment fills
190 	 * up. Check ep against envsize - 1 to allow for extra trailing '\0'. */
191 	for (fp = 0, ep = 0 ; fp < filesize && ep < envsize - 1; fp++) {
192 		if (filebuf[fp] == '\n') {
193 			if (fp == 0 || filebuf[fp-1] == '\n') {
194 				/*
195 				 * Skip empty lines.
196 				 */
197 				continue;
198 			} else if (filebuf[fp-1] == '\\') {
199 				/*
200 				 * Embedded newline in a variable.
201 				 *
202 				 * The backslash was added to the envptr; rewind
203 				 * and replace it with a newline
204 				 */
205 				ep--;
206 				envptr[ep++] = '\n';
207 			} else {
208 				/* End of a variable */
209 				envptr[ep++] = '\0';
210 			}
211 		} else if ((fp == 0 || filebuf[fp-1] == '\n') && filebuf[fp] == '#') {
212 			/* Comment, skip the line. */
213 			while (++fp < filesize && filebuf[fp] != '\n')
214 			continue;
215 		} else {
216 			envptr[ep++] = filebuf[fp];
217 		}
218 	}
219 	/* If there are more bytes in the file still, it means the env filled up
220 	 * before parsing the whole file.  Eat comments & whitespace here to see if
221 	 * there was anything meaning full left in the file, and if so, throw a error
222 	 * and exit. */
223 	for( ; fp < filesize; fp++ )
224 	{
225 		if (filebuf[fp] == '\n') {
226 			if (fp == 0 || filebuf[fp-1] == '\n') {
227 				/* Ignore blank lines */
228 				continue;
229 			}
230 		} else if ((fp == 0 || filebuf[fp-1] == '\n') && filebuf[fp] == '#') {
231 			while (++fp < filesize && filebuf[fp] != '\n')
232 			continue;
233 		} else {
234 			fprintf(stderr, "The environment file is too large for the target environment storage\n");
235 			return EXIT_FAILURE;
236 		}
237 	}
238 	/*
239 	 * Make sure there is a final '\0'
240 	 * And do it again on the next byte to mark the end of the environment.
241 	 */
242 	if (envptr[ep-1] != '\0') {
243 		envptr[ep++] = '\0';
244 		/*
245 		 * The text file doesn't have an ending newline.  We need to
246 		 * check the env size again to make sure we have room for two \0
247 		 */
248 		if (ep >= envsize) {
249 			fprintf(stderr, "The environment file is too large for the target environment storage\n");
250 			return EXIT_FAILURE;
251 		}
252 		envptr[ep] = '\0';
253 	} else {
254 		envptr[ep] = '\0';
255 	}
256 
257 	/* Computes the CRC and put it at the beginning of the data */
258 	crc = crc32(0, envptr, envsize);
259 	targetendian_crc = bigendian ? cpu_to_be32(crc) : cpu_to_le32(crc);
260 
261 	memcpy(dataptr, &targetendian_crc, sizeof(targetendian_crc));
262 	if (redundant)
263 		dataptr[sizeof(targetendian_crc)] = 1;
264 
265 	if (!bin_filename || strcmp(bin_filename, "-") == 0) {
266 		bin_fd = STDOUT_FILENO;
267 	} else {
268 		bin_fd = creat(bin_filename, S_IRUSR | S_IWUSR | S_IRGRP |
269 					     S_IWGRP);
270 		if (bin_fd == -1) {
271 			fprintf(stderr, "Can't open output file \"%s\": %s\n",
272 					bin_filename, strerror(errno));
273 			return EXIT_FAILURE;
274 		}
275 	}
276 
277 	if (write(bin_fd, dataptr, sizeof(*dataptr) * datasize) !=
278 			sizeof(*dataptr) * datasize) {
279 		fprintf(stderr, "write() failed: %s\n", strerror(errno));
280 		return EXIT_FAILURE;
281 	}
282 
283 	ret = close(bin_fd);
284 
285 	return ret;
286 }
287