mkenvimage.c 8.19 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * (C) Copyright 2011 Free Electrons
 * David Wagner <david.wagner@free-electrons.com>
 *
 * Inspired from envcrc.c:
 * (C) Copyright 2001
 * Paolo Scaffardi, AIRVENT SAM s.p.a - RIMINI(ITALY), arsenio@tin.it
 *
9
 * SPDX-License-Identifier:	GPL-2.0+
10 11 12 13 14
 */

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
15
#include <stdlib.h>
16 17 18
#include <stdint.h>
#include <string.h>
#include <unistd.h>
19
#include <libgen.h>
20 21
#include <sys/types.h>
#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 29 30 31

#define CRC_SIZE sizeof(uint32_t)

static void usage(const char *exec_name)
{
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 36 37 38 39
	       "\n"
	       "\tThe input file is in format:\n"
	       "\t\tkey1=value1\n"
	       "\t\tkey2=value2\n"
	       "\t\t...\n"
40 41
	       "\tEmpty lines are skipped, and lines with a # in the first\n"
	       "\tcolumn are treated as comments (also skipped).\n"
42 43
	       "\t-r : the environment has multiple copies in flash\n"
	       "\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 47 48 49 50
	       "\n"
	       "If the input file is \"-\", data is read from standard input\n",
	       exec_name);
}

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
long int xstrtol(const char *s)
{
	long int tmp;

	errno = 0;
	tmp = strtol(s, NULL, 0);
	if (!errno)
		return tmp;

	if (errno == ERANGE)
		fprintf(stderr, "Bad integer format: %s\n",  s);
	else
		fprintf(stderr, "Error while parsing %s: %s\n", s,
				strerror(errno));

	exit(EXIT_FAILURE);
}

69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
int main(int argc, char **argv)
{
	uint32_t crc, targetendian_crc;
	const char *txt_filename = NULL, *bin_filename = NULL;
	int txt_fd, bin_fd;
	unsigned char *dataptr, *envptr;
	unsigned char *filebuf = NULL;
	unsigned int filesize = 0, envsize = 0, datasize = 0;
	int bigendian = 0;
	int redundant = 0;
	unsigned char padbyte = 0xff;

	int option;
	int ret = EXIT_SUCCESS;

	struct stat txt_file_stat;

	int fp, ep;
87 88 89
	const char *prg;

	prg = basename(argv[0]);
90

91 92 93
	/* Turn off getopt()'s internal error message */
	opterr = 0;

94
	/* Parse the cmdline */
95
	while ((option = getopt(argc, argv, ":s:o:rbp:hV")) != -1) {
96 97
		switch (option) {
		case 's':
98
			datasize = xstrtol(optarg);
99 100 101 102
			break;
		case 'o':
			bin_filename = strdup(optarg);
			if (!bin_filename) {
103
				fprintf(stderr, "Can't strdup() the output filename\n");
104 105 106 107 108 109 110 111 112 113
				return EXIT_FAILURE;
			}
			break;
		case 'r':
			redundant = 1;
			break;
		case 'b':
			bigendian = 1;
			break;
		case 'p':
114
			padbyte = xstrtol(optarg);
115 116
			break;
		case 'h':
117
			usage(prg);
118
			return EXIT_SUCCESS;
119 120 121
		case 'V':
			printf("%s version %s\n", prg, PLAIN_VERSION);
			return EXIT_SUCCESS;
122 123
		case ':':
			fprintf(stderr, "Missing argument for option -%c\n",
124
				optopt);
125
			usage(prg);
126
			return EXIT_FAILURE;
127
		default:
128
			fprintf(stderr, "Wrong option -%c\n", optopt);
129
			usage(prg);
130 131 132 133 134 135
			return EXIT_FAILURE;
		}
	}

	/* Check datasize and allocate the data */
	if (datasize == 0) {
136
		fprintf(stderr, "Please specify the size of the environment partition.\n");
137
		usage(prg);
138 139 140 141 142
		return EXIT_FAILURE;
	}

	dataptr = malloc(datasize * sizeof(*dataptr));
	if (!dataptr) {
143 144
		fprintf(stderr, "Can't alloc %d bytes for dataptr.\n",
				datasize);
145 146 147 148 149
		return EXIT_FAILURE;
	}

	/*
	 * envptr points to the beginning of the actual environment (after the
150
	 * crc and possible `redundant' byte
151 152 153 154 155 156 157 158
	 */
	envsize = datasize - (CRC_SIZE + redundant);
	envptr = dataptr + CRC_SIZE + redundant;

	/* Pad the environment with the padding byte */
	memset(envptr, padbyte, envsize);

	/* Open the input file ... */
159
	if (optind >= argc || strcmp(argv[optind], "-") == 0) {
160
		int readbytes = 0;
161
		int readlen = sizeof(*envptr) * 4096;
162 163 164 165
		txt_fd = STDIN_FILENO;

		do {
			filebuf = realloc(filebuf, readlen);
166 167 168 169
			if (!filebuf) {
				fprintf(stderr, "Can't realloc memory for the input file buffer\n");
				return EXIT_FAILURE;
			}
170
			readbytes = read(txt_fd, filebuf + filesize, readlen);
171 172 173 174 175
			if (errno) {
				fprintf(stderr, "Error while reading stdin: %s\n",
						strerror(errno));
				return EXIT_FAILURE;
			}
176 177 178 179
			filesize += readbytes;
		} while (readbytes == readlen);

	} else {
180
		txt_filename = argv[optind];
181 182 183 184 185 186 187 188 189
		txt_fd = open(txt_filename, O_RDONLY);
		if (txt_fd == -1) {
			fprintf(stderr, "Can't open \"%s\": %s\n",
					txt_filename, strerror(errno));
			return EXIT_FAILURE;
		}
		/* ... and check it */
		ret = fstat(txt_fd, &txt_file_stat);
		if (ret == -1) {
190 191
			fprintf(stderr, "Can't stat() on \"%s\": %s\n",
					txt_filename, strerror(errno));
192 193 194 195
			return EXIT_FAILURE;
		}

		filesize = txt_file_stat.st_size;
196 197 198 199

		filebuf = mmap(NULL, sizeof(*envptr) * filesize, PROT_READ,
			       MAP_PRIVATE, txt_fd, 0);
		if (filebuf == MAP_FAILED) {
200
			fprintf(stderr, "mmap (%zu bytes) failed: %s\n",
201 202 203 204 205 206 207
					sizeof(*envptr) * filesize,
					strerror(errno));
			fprintf(stderr, "Falling back to read()\n");

			filebuf = malloc(sizeof(*envptr) * filesize);
			ret = read(txt_fd, filebuf, sizeof(*envptr) * filesize);
			if (ret != sizeof(*envptr) * filesize) {
208
				fprintf(stderr, "Can't read the whole input file (%zu bytes): %s\n",
209 210 211 212 213
					sizeof(*envptr) * filesize,
					strerror(errno));

				return EXIT_FAILURE;
			}
214 215 216 217
		}
		ret = close(txt_fd);
	}

218 219 220
	/* Parse a byte at time until reaching the file OR until the environment fills
	 * up. Check ep against envsize - 1 to allow for extra trailing '\0'. */
	for (fp = 0, ep = 0 ; fp < filesize && ep < envsize - 1; fp++) {
221
		if (filebuf[fp] == '\n') {
222
			if (fp == 0 || filebuf[fp-1] == '\n') {
223
				/*
224
				 * Skip empty lines.
225 226 227 228 229 230
				 */
				continue;
			} else if (filebuf[fp-1] == '\\') {
				/*
				 * Embedded newline in a variable.
				 *
231 232
				 * The backslash was added to the envptr; rewind
				 * and replace it with a newline
233 234 235 236 237 238 239
				 */
				ep--;
				envptr[ep++] = '\n';
			} else {
				/* End of a variable */
				envptr[ep++] = '\0';
			}
240 241 242 243
		} else if ((fp == 0 || filebuf[fp-1] == '\n') && filebuf[fp] == '#') {
			/* Comment, skip the line. */
			while (++fp < filesize && filebuf[fp] != '\n')
			continue;
244 245 246 247
		} else {
			envptr[ep++] = filebuf[fp];
		}
	}
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
	/* If there are more bytes in the file still, it means the env filled up
	 * before parsing the whole file.  Eat comments & whitespace here to see if
	 * there was anything meaning full left in the file, and if so, throw a error
	 * and exit. */
	for( ; fp < filesize; fp++ )
	{
		if (filebuf[fp] == '\n') {
			if (fp == 0 || filebuf[fp-1] == '\n') {
				/* Ignore blank lines */
				continue;
			}
		} else if ((fp == 0 || filebuf[fp-1] == '\n') && filebuf[fp] == '#') {
			while (++fp < filesize && filebuf[fp] != '\n')
			continue;
		} else {
			fprintf(stderr, "The environment file is too large for the target environment storage\n");
			return EXIT_FAILURE;
		}
	}
267 268 269 270 271 272 273 274 275 276 277
	/*
	 * Make sure there is a final '\0'
	 * And do it again on the next byte to mark the end of the environment.
	 */
	if (envptr[ep-1] != '\0') {
		envptr[ep++] = '\0';
		/*
		 * The text file doesn't have an ending newline.  We need to
		 * check the env size again to make sure we have room for two \0
		 */
		if (ep >= envsize) {
278
			fprintf(stderr, "The environment file is too large for the target environment storage\n");
279 280 281 282 283 284 285 286 287 288 289
			return EXIT_FAILURE;
		}
		envptr[ep] = '\0';
	} else {
		envptr[ep] = '\0';
	}

	/* Computes the CRC and put it at the beginning of the data */
	crc = crc32(0, envptr, envsize);
	targetendian_crc = bigendian ? cpu_to_be32(crc) : cpu_to_le32(crc);

290 291 292
	memcpy(dataptr, &targetendian_crc, sizeof(targetendian_crc));
	if (redundant)
		dataptr[sizeof(targetendian_crc)] = 1;
293

294 295 296
	if (!bin_filename || strcmp(bin_filename, "-") == 0) {
		bin_fd = STDOUT_FILENO;
	} else {
297 298
		bin_fd = creat(bin_filename, S_IRUSR | S_IWUSR | S_IRGRP |
					     S_IWGRP);
299 300 301 302 303
		if (bin_fd == -1) {
			fprintf(stderr, "Can't open output file \"%s\": %s\n",
					bin_filename, strerror(errno));
			return EXIT_FAILURE;
		}
304 305 306 307 308 309 310 311 312 313 314 315
	}

	if (write(bin_fd, dataptr, sizeof(*dataptr) * datasize) !=
			sizeof(*dataptr) * datasize) {
		fprintf(stderr, "write() failed: %s\n", strerror(errno));
		return EXIT_FAILURE;
	}

	ret = close(bin_fd);

	return ret;
}