xref: /linux/tools/bootconfig/main.c (revision 4f7e89065e41fd487e411d35b5caeac2a10af10e)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Boot config tool for initrd image
4  */
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <string.h>
12 #include <errno.h>
13 #include <endian.h>
14 #include <assert.h>
15 
16 #include <linux/bootconfig.h>
17 
18 #define pr_err(fmt, ...) fprintf(stderr, fmt, ##__VA_ARGS__)
19 
20 /* Bootconfig footer is [size][csum][BOOTCONFIG_MAGIC]. */
21 #define BOOTCONFIG_FOOTER_SIZE	\
22 	(sizeof(uint32_t) * 2 + BOOTCONFIG_MAGIC_LEN)
23 
24 static int xbc_show_value(struct xbc_node *node, bool semicolon)
25 {
26 	const char *val, *eol;
27 	char q;
28 	int i = 0;
29 
30 	eol = semicolon ? ";\n" : "\n";
31 	xbc_array_for_each_value(node, val) {
32 		if (strchr(val, '"'))
33 			q = '\'';
34 		else
35 			q = '"';
36 		printf("%c%s%c%s", q, val, q, xbc_node_is_array(node) ? ", " : eol);
37 		i++;
38 	}
39 	return i;
40 }
41 
42 static void xbc_show_compact_tree(void)
43 {
44 	struct xbc_node *node, *cnode = NULL, *vnode;
45 	int depth = 0, i;
46 
47 	node = xbc_root_node();
48 	while (node && xbc_node_is_key(node)) {
49 		for (i = 0; i < depth; i++)
50 			printf("\t");
51 		if (!cnode)
52 			cnode = xbc_node_get_child(node);
53 		while (cnode && xbc_node_is_key(cnode) && !cnode->next) {
54 			vnode = xbc_node_get_child(cnode);
55 			/*
56 			 * If @cnode has value and subkeys, this
57 			 * should show it as below.
58 			 *
59 			 * key(@node) {
60 			 *      key(@cnode) = value;
61 			 *      key(@cnode) {
62 			 *          subkeys;
63 			 *      }
64 			 * }
65 			 */
66 			if (vnode && xbc_node_is_value(vnode) && vnode->next)
67 				break;
68 			printf("%s.", xbc_node_get_data(node));
69 			node = cnode;
70 			cnode = vnode;
71 		}
72 		if (cnode && xbc_node_is_key(cnode)) {
73 			printf("%s {\n", xbc_node_get_data(node));
74 			depth++;
75 			node = cnode;
76 			cnode = NULL;
77 			continue;
78 		} else if (cnode && xbc_node_is_value(cnode)) {
79 			printf("%s = ", xbc_node_get_data(node));
80 			xbc_show_value(cnode, true);
81 			/*
82 			 * If @node has value and subkeys, continue
83 			 * looping on subkeys with same node.
84 			 */
85 			if (cnode->next) {
86 				cnode = xbc_node_get_next(cnode);
87 				continue;
88 			}
89 		} else {
90 			printf("%s;\n", xbc_node_get_data(node));
91 		}
92 		cnode = NULL;
93 
94 		if (node->next) {
95 			node = xbc_node_get_next(node);
96 			continue;
97 		}
98 		while (!node->next) {
99 			node = xbc_node_get_parent(node);
100 			if (!node)
101 				return;
102 			if (!xbc_node_get_child(node)->next)
103 				continue;
104 			if (depth) {
105 				depth--;
106 				for (i = 0; i < depth; i++)
107 					printf("\t");
108 				printf("}\n");
109 			}
110 		}
111 		node = xbc_node_get_next(node);
112 	}
113 }
114 
115 static void xbc_show_list(void)
116 {
117 	char key[XBC_KEYLEN_MAX];
118 	struct xbc_node *leaf;
119 	const char *val;
120 	int ret;
121 
122 	xbc_for_each_key_value(leaf, val) {
123 		ret = xbc_node_compose_key(leaf, key, XBC_KEYLEN_MAX);
124 		if (ret < 0) {
125 			fprintf(stderr, "Failed to compose key %d\n", ret);
126 			break;
127 		}
128 		printf("%s = ", key);
129 		if (!val || val[0] == '\0') {
130 			printf("\"\"\n");
131 			continue;
132 		}
133 		xbc_show_value(xbc_node_get_child(leaf), false);
134 	}
135 }
136 
137 #define PAGE_SIZE	4096
138 
139 static int load_xbc_fd(int fd, char **buf, int size)
140 {
141 	int ret;
142 
143 	*buf = malloc(size + 1);
144 	if (!*buf)
145 		return -ENOMEM;
146 
147 	ret = read(fd, *buf, size);
148 	if (ret < 0)
149 		return -errno;
150 	(*buf)[size] = '\0';
151 
152 	return ret;
153 }
154 
155 /* Return the read size or -errno */
156 static int load_xbc_file(const char *path, char **buf)
157 {
158 	struct stat stat;
159 	int fd, ret;
160 
161 	fd = open(path, O_RDONLY);
162 	if (fd < 0)
163 		return -errno;
164 	ret = fstat(fd, &stat);
165 	if (ret < 0) {
166 		ret = -errno;
167 		close(fd);
168 		return ret;
169 	}
170 
171 	ret = load_xbc_fd(fd, buf, stat.st_size);
172 
173 	close(fd);
174 
175 	return ret;
176 }
177 
178 static int pr_errno(const char *msg, int err)
179 {
180 	pr_err("%s: %d\n", msg, err);
181 	return err;
182 }
183 
184 static int load_xbc_from_initrd(int fd, char **buf)
185 {
186 	struct stat stat;
187 	int ret;
188 	uint32_t size = 0, csum = 0, rcsum;
189 	char magic[BOOTCONFIG_MAGIC_LEN];
190 	const char *msg;
191 
192 	ret = fstat(fd, &stat);
193 	if (ret < 0)
194 		return -errno;
195 
196 	if (stat.st_size < BOOTCONFIG_FOOTER_SIZE)
197 		return 0;
198 
199 	if (lseek(fd, -(off_t)BOOTCONFIG_MAGIC_LEN, SEEK_END) < 0)
200 		return pr_errno("Failed to lseek for magic", -errno);
201 
202 	if (read(fd, magic, BOOTCONFIG_MAGIC_LEN) < 0)
203 		return pr_errno("Failed to read", -errno);
204 
205 	/* Check the bootconfig magic bytes */
206 	if (memcmp(magic, BOOTCONFIG_MAGIC, BOOTCONFIG_MAGIC_LEN) != 0)
207 		return 0;
208 
209 	if (lseek(fd, -(off_t)BOOTCONFIG_FOOTER_SIZE, SEEK_END) < 0)
210 		return pr_errno("Failed to lseek for size", -errno);
211 
212 	if (read(fd, &size, sizeof(uint32_t)) < 0)
213 		return pr_errno("Failed to read size", -errno);
214 	size = le32toh(size);
215 
216 	if (read(fd, &csum, sizeof(uint32_t)) < 0)
217 		return pr_errno("Failed to read checksum", -errno);
218 	csum = le32toh(csum);
219 
220 	/* Wrong size error  */
221 	if (stat.st_size < size + BOOTCONFIG_FOOTER_SIZE) {
222 		pr_err("bootconfig size is too big\n");
223 		return -E2BIG;
224 	}
225 
226 	if (lseek(fd, stat.st_size - (size + BOOTCONFIG_FOOTER_SIZE),
227 		  SEEK_SET) < 0)
228 		return pr_errno("Failed to lseek", -errno);
229 
230 	ret = load_xbc_fd(fd, buf, size);
231 	if (ret < 0)
232 		return ret;
233 
234 	/* Wrong Checksum */
235 	rcsum = xbc_calc_checksum(*buf, size);
236 	if (csum != rcsum) {
237 		pr_err("checksum error: %u != %u\n", csum, rcsum);
238 		return -EINVAL;
239 	}
240 
241 	ret = xbc_init(*buf, size, &msg, NULL);
242 	/* Wrong data */
243 	if (ret < 0) {
244 		pr_err("parse error: %s.\n", msg);
245 		return ret;
246 	}
247 
248 	return size;
249 }
250 
251 static void show_xbc_error(const char *data, const char *msg, int pos)
252 {
253 	int lin = 1, col, i;
254 
255 	if (pos < 0) {
256 		pr_err("Error: %s.\n", msg);
257 		return;
258 	}
259 
260 	/* Note that pos starts from 0 but lin and col should start from 1. */
261 	col = pos + 1;
262 	for (i = 0; i < pos; i++) {
263 		if (data[i] == '\n') {
264 			lin++;
265 			col = pos - i;
266 		}
267 	}
268 	pr_err("Parse Error: %s at %d:%d\n", msg, lin, col);
269 
270 }
271 
272 static int init_xbc_with_error(char *buf, int len)
273 {
274 	char *copy = strdup(buf);
275 	const char *msg;
276 	int ret, pos;
277 
278 	if (!copy)
279 		return -ENOMEM;
280 
281 	ret = xbc_init(buf, len, &msg, &pos);
282 	if (ret < 0)
283 		show_xbc_error(copy, msg, pos);
284 	free(copy);
285 
286 	return ret;
287 }
288 
289 static int show_xbc_kernel_cmdline(void)
290 {
291 	struct xbc_node *root;
292 	char *buf = NULL;
293 	int len, ret;
294 
295 	root = xbc_find_node("kernel");
296 	if (!root)
297 		return 0;	/* no kernel.* keys: emit empty output */
298 
299 	len = xbc_snprint_cmdline(NULL, 0, root);
300 	if (len < 0) {
301 		pr_err("Failed to size cmdline output: %d\n", len);
302 		return len;
303 	}
304 	if (len == 0)
305 		return 0;
306 
307 	buf = malloc(len + 1);
308 	if (!buf)
309 		return -ENOMEM;
310 
311 	ret = xbc_snprint_cmdline(buf, len + 1, root);
312 	if (ret < 0) {
313 		pr_err("Failed to render cmdline output: %d\n", ret);
314 		free(buf);
315 		return ret;
316 	}
317 
318 	fputs(buf, stdout);
319 	free(buf);
320 	return 0;
321 }
322 
323 static int show_xbc(const char *path, bool list, bool render_cmdline)
324 {
325 	int ret, fd;
326 	char *buf = NULL;
327 	struct stat st;
328 
329 	ret = stat(path, &st);
330 	if (ret < 0) {
331 		ret = -errno;
332 		pr_err("Failed to stat %s: %d\n", path, ret);
333 		return ret;
334 	}
335 
336 	fd = open(path, O_RDONLY);
337 	if (fd < 0) {
338 		ret = -errno;
339 		pr_err("Failed to open initrd %s: %d\n", path, ret);
340 		return ret;
341 	}
342 
343 	ret = load_xbc_from_initrd(fd, &buf);
344 	close(fd);
345 	if (ret < 0) {
346 		pr_err("Failed to load a boot config from initrd: %d\n", ret);
347 		goto out;
348 	}
349 	/* Assume a bootconfig file if it is enough small */
350 	if (ret == 0 && st.st_size <= XBC_DATA_MAX) {
351 		ret = load_xbc_file(path, &buf);
352 		if (ret < 0) {
353 			pr_err("Failed to load a boot config: %d\n", ret);
354 			goto out;
355 		}
356 		if (init_xbc_with_error(buf, ret) < 0)
357 			goto out;
358 	}
359 	if (render_cmdline)
360 		ret = show_xbc_kernel_cmdline();
361 	else if (list)
362 		xbc_show_list();
363 	else
364 		xbc_show_compact_tree();
365 	if (ret > 0)
366 		ret = 0;
367 out:
368 	free(buf);
369 
370 	return ret;
371 }
372 
373 static int delete_xbc(const char *path)
374 {
375 	struct stat stat;
376 	int ret = 0, fd, size;
377 	char *buf = NULL;
378 
379 	fd = open(path, O_RDWR);
380 	if (fd < 0) {
381 		ret = -errno;
382 		pr_err("Failed to open initrd %s: %d\n", path, ret);
383 		return ret;
384 	}
385 
386 	size = load_xbc_from_initrd(fd, &buf);
387 	if (size < 0) {
388 		ret = size;
389 		pr_err("Failed to load a boot config from initrd: %d\n", ret);
390 	} else if (size > 0) {
391 		ret = fstat(fd, &stat);
392 		if (!ret)
393 			ret = ftruncate(fd, stat.st_size
394 					- size - BOOTCONFIG_FOOTER_SIZE);
395 		if (ret)
396 			ret = -errno;
397 	} /* Ignore if there is no boot config in initrd */
398 
399 	close(fd);
400 	free(buf);
401 
402 	return ret;
403 }
404 
405 static int apply_xbc(const char *path, const char *xbc_path)
406 {
407 	struct {
408 		uint32_t size;
409 		uint32_t csum;
410 		char magic[BOOTCONFIG_MAGIC_LEN];
411 	} footer;
412 	char *buf, *data;
413 	size_t total_size;
414 	struct stat stat;
415 	const char *msg;
416 	uint32_t size, csum;
417 	int pos, pad;
418 	int ret, fd;
419 
420 	ret = load_xbc_file(xbc_path, &buf);
421 	if (ret < 0) {
422 		pr_err("Failed to load %s : %d\n", xbc_path, ret);
423 		return ret;
424 	}
425 	size = strlen(buf) + 1;
426 	csum = xbc_calc_checksum(buf, size);
427 
428 	/* Backup the bootconfig data */
429 	data = calloc(size + BOOTCONFIG_ALIGN + BOOTCONFIG_FOOTER_SIZE, 1);
430 	if (!data) {
431 		free(buf);
432 		return -ENOMEM;
433 	}
434 	memcpy(data, buf, size);
435 
436 	/* Check the data format */
437 	ret = xbc_init(buf, size, &msg, &pos);
438 	if (ret < 0) {
439 		show_xbc_error(data, msg, pos);
440 		free(data);
441 		free(buf);
442 
443 		return ret;
444 	}
445 	printf("Apply %s to %s\n", xbc_path, path);
446 	xbc_get_info(&ret, NULL);
447 	printf("\tNumber of nodes: %d\n", ret);
448 	printf("\tSize: %u bytes\n", (unsigned int)size);
449 	printf("\tChecksum: %u\n", (unsigned int)csum);
450 
451 	/* TODO: Check the options by schema */
452 	xbc_exit();
453 	free(buf);
454 
455 	/* Remove old boot config if exists */
456 	ret = delete_xbc(path);
457 	if (ret < 0) {
458 		pr_err("Failed to delete previous boot config: %d\n", ret);
459 		free(data);
460 		return ret;
461 	}
462 
463 	/* Apply new one */
464 	fd = open(path, O_RDWR | O_APPEND);
465 	if (fd < 0) {
466 		ret = -errno;
467 		pr_err("Failed to open %s: %d\n", path, ret);
468 		free(data);
469 		return ret;
470 	}
471 	/* TODO: Ensure the @path is initramfs/initrd image */
472 	if (fstat(fd, &stat) < 0) {
473 		ret = -errno;
474 		pr_err("Failed to get the size of %s\n", path);
475 		goto out;
476 	}
477 
478 	/* To align up the total size to BOOTCONFIG_ALIGN, get padding size */
479 	total_size = stat.st_size + size + BOOTCONFIG_FOOTER_SIZE;
480 	pad = ((total_size + BOOTCONFIG_ALIGN - 1) & (~BOOTCONFIG_ALIGN_MASK)) - total_size;
481 	size += pad;
482 
483 	/* Add a footer */
484 	footer.size = htole32(size);
485 	footer.csum = htole32(csum);
486 	memcpy(footer.magic, BOOTCONFIG_MAGIC, BOOTCONFIG_MAGIC_LEN);
487 	static_assert(sizeof(footer) == BOOTCONFIG_FOOTER_SIZE);
488 	memcpy(data + size, &footer, BOOTCONFIG_FOOTER_SIZE);
489 
490 	total_size = size + BOOTCONFIG_FOOTER_SIZE;
491 
492 	ret = write(fd, data, total_size);
493 	if (ret < total_size) {
494 		if (ret < 0)
495 			ret = -errno;
496 		pr_err("Failed to apply a boot config: %d\n", ret);
497 		if (ret >= 0)
498 			goto out_rollback;
499 	} else
500 		ret = 0;
501 
502 out:
503 	close(fd);
504 	free(data);
505 
506 	return ret;
507 
508 out_rollback:
509 	/* Map the partial write to -ENOSPC */
510 	if (ret >= 0)
511 		ret = -ENOSPC;
512 	if (ftruncate(fd, stat.st_size) < 0) {
513 		ret = -errno;
514 		pr_err("Failed to rollback the write error: %d\n", ret);
515 		pr_err("The initrd %s may be corrupted. Recommend to rebuild.\n", path);
516 	}
517 	goto out;
518 }
519 
520 static int usage(void)
521 {
522 	printf("Usage: bootconfig [OPTIONS] <INITRD>\n"
523 		"Or     bootconfig <CONFIG>\n"
524 		" Apply, delete or show boot config to initrd.\n"
525 		" Options:\n"
526 		"		-a <config>: Apply boot config to initrd\n"
527 		"		-d : Delete boot config file from initrd\n"
528 		"		-l : list boot config in initrd or file\n"
529 		"		-C : render the kernel.* subtree as a flat cmdline\n"
530 		"		     string (suitable for embedding in a kernel image)\n"
531 		"		     and print it to stdout\n\n"
532 		" If no option is given, show the bootconfig in the given file.\n");
533 	return -1;
534 }
535 
536 int main(int argc, char **argv)
537 {
538 	char *path = NULL;
539 	char *apply = NULL;
540 	bool render_cmdline = false;
541 	bool delete = false, list = false;
542 	int opt;
543 
544 	while ((opt = getopt(argc, argv, "hda:lC")) != -1) {
545 		switch (opt) {
546 		case 'd':
547 			delete = true;
548 			break;
549 		case 'a':
550 			apply = optarg;
551 			break;
552 		case 'l':
553 			list = true;
554 			break;
555 		case 'C':
556 			render_cmdline = true;
557 			break;
558 		case 'h':
559 		default:
560 			return usage();
561 		}
562 	}
563 
564 	if ((!!apply + !!delete + !!list + !!render_cmdline) > 1) {
565 		pr_err("Error: You can give one of -a, -d, -l or -C at once.\n");
566 		return usage();
567 	}
568 
569 	if (optind >= argc) {
570 		pr_err("Error: No initrd is specified.\n");
571 		return usage();
572 	}
573 
574 	path = argv[optind];
575 
576 	if (apply)
577 		return apply_xbc(path, apply);
578 	else if (delete)
579 		return delete_xbc(path);
580 
581 	return show_xbc(path, list, render_cmdline);
582 }
583