xref: /linux/lib/bootconfig.c (revision e84e60da22ea2fb48576d8d78def44fab677374e)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Extra Boot Config
4  * Masami Hiramatsu <mhiramat@kernel.org>
5  */
6 
7 /*
8  * NOTE: This is only for tools/bootconfig, because tools/bootconfig will
9  * run the parser sanity test.
10  * This does NOT mean lib/bootconfig.c is available in the user space.
11  * However, if you change this file, please make sure the tools/bootconfig
12  * has no issue on building and running.
13  */
14 #include <linux/bootconfig.h>
15 
16 #ifdef __KERNEL__
17 #include <linux/bug.h>
18 #include <linux/ctype.h>
19 #include <linux/errno.h>
20 #include <linux/cache.h>
21 #include <linux/compiler.h>
22 #include <linux/init.h>
23 #include <linux/moduleparam.h>
24 #include <linux/printk.h>
25 #include <linux/sprintf.h>
26 #include <linux/memblock.h>
27 #include <linux/string.h>
28 #include <asm/setup.h>		/* COMMAND_LINE_SIZE */
29 
30 #ifdef CONFIG_BOOT_CONFIG_EMBED
31 /* embedded_bootconfig_data is defined in bootconfig-data.S */
32 extern __visible const char embedded_bootconfig_data[];
33 extern __visible const char embedded_bootconfig_data_end[];
34 
35 const char * __init xbc_get_embedded_bootconfig(size_t *size)
36 {
37 	*size = embedded_bootconfig_data_end - embedded_bootconfig_data;
38 	return (*size) ? embedded_bootconfig_data : NULL;
39 }
40 #endif
41 
42 #ifdef CONFIG_CMDLINE_FROM_BOOTCONFIG
43 /* embedded_kernel_cmdline is defined in embedded-cmdline.S */
44 extern __visible const char embedded_kernel_cmdline[];
45 extern __visible const char embedded_kernel_cmdline_end[];
46 
47 /* Set once the embedded cmdline has actually been prepended. */
48 static bool xbc_cmdline_applied __initdata;
49 
50 /*
51  * str_prepend() - Prepend @src in front of the string in @dst, in place
52  * @dst: NUL-terminated destination buffer, currently @dst_len bytes long
53  * @dst_len: length of the current @dst string (excluding its NUL)
54  * @src: bytes to prepend (not NUL-terminated)
55  * @src_len: number of bytes from @src to prepend
56  *
57  * The caller must guarantee @dst has room for src_len + dst_len + 1 bytes.
58  * Moving dst_len + 1 bytes carries @dst's NUL terminator too, so an empty
59  * @dst needs no special case.
60  */
61 static void __init str_prepend(char *dst, size_t dst_len,
62 			       const char *src, size_t src_len)
63 {
64 	memmove(dst + src_len, dst, dst_len + 1);
65 	memcpy(dst, src, src_len);
66 }
67 
68 /**
69  * xbc_prepend_embedded_cmdline() - Prepend embedded bootconfig cmdline
70  * @dst: cmdline buffer to prepend into (must already contain a NUL byte)
71  * @size: total capacity of @dst in bytes
72  *
73  * Prepend the build-time-rendered "kernel" subtree of the embedded
74  * bootconfig to @dst. The rendered string already ends with a single
75  * space (the xbc_snprint_cmdline() invariant), which serves as the
76  * separator between the embedded keys and any existing content of @dst.
77  * On overflow, log an error and leave @dst untouched rather than
78  * silently truncating: booting without the embedded values is better
79  * than refusing to boot, and the error message tells the user why
80  * their embedded keys are missing.
81  *
82  * Intended to be called from setup_arch() before parse_early_param() so
83  * that early_param() handlers see the embedded values.
84  */
85 void __init xbc_prepend_embedded_cmdline(char *dst, size_t size)
86 {
87 	size_t embed_len = embedded_kernel_cmdline_end - embedded_kernel_cmdline;
88 	size_t dst_len;
89 
90 	if (!size || embed_len <= 1)	/* trailing NUL only */
91 		return;
92 	embed_len--;			/* exclude trailing NUL byte */
93 
94 	dst_len = strnlen(dst, size);
95 	if (embed_len + dst_len + 1 > size) {
96 		pr_err("embedded bootconfig cmdline (%zu bytes) does not fit in COMMAND_LINE_SIZE with %zu bytes already used; ignoring embedded values\n",
97 		       embed_len, dst_len);
98 		return;
99 	}
100 
101 	str_prepend(dst, dst_len, embedded_kernel_cmdline, embed_len);
102 	xbc_cmdline_applied = true;
103 }
104 
105 /**
106  * xbc_embedded_cmdline_applied() - Did the embedded cmdline get prepended?
107  *
108  * Return true if xbc_prepend_embedded_cmdline() actually prepended the
109  * embedded "kernel" subtree. setup_boot_config() uses this to avoid
110  * rendering the same keys a second time.
111  */
112 bool __init xbc_embedded_cmdline_applied(void)
113 {
114 	return xbc_cmdline_applied;
115 }
116 #endif	/* CONFIG_CMDLINE_FROM_BOOTCONFIG */
117 
118 /* parse_args() callback: flag when the "bootconfig" parameter is present. */
119 static int __init bootconfig_optin(char *param, char *val,
120 				   const char *unused, void *arg)
121 {
122 	if (!strcmp(param, "bootconfig"))
123 		*(bool *)arg = true;
124 	return 0;
125 }
126 
127 /**
128  * bootconfig_cmdline_requested() - Was "bootconfig" passed on the cmdline?
129  * @boot_cmdline: kernel command line to inspect (not modified)
130  * @end_offset: if non-NULL, set to the offset of the init arguments that
131  *		follow a "--" separator, or 0 when there is none
132  *
133  * Parse a private copy of @boot_cmdline (parse_args() is destructive) and
134  * report whether "bootconfig" is present before the "--" separator.
135  * setup_arch() uses this to gate prepending the build-time embedded cmdline;
136  * setup_boot_config() uses it for the runtime opt-in and to locate the init
137  * arguments via @end_offset. Sharing one parser keeps the early and late
138  * paths agreeing on what counts as opt-in. CONFIG_BOOT_CONFIG_FORCE is not
139  * folded in here; callers apply it where they need it.
140  */
141 bool __init bootconfig_cmdline_requested(const char *boot_cmdline, int *end_offset)
142 {
143 	static char tmp_cmdline[COMMAND_LINE_SIZE] __initdata;
144 	bool found = false;
145 	char *err;
146 
147 	if (end_offset)
148 		*end_offset = 0;
149 
150 	strscpy(tmp_cmdline, boot_cmdline, COMMAND_LINE_SIZE);
151 	err = parse_args("bootconfig", tmp_cmdline, NULL, 0, 0, 0,
152 			 &found, bootconfig_optin);
153 	if (IS_ERR(err))
154 		return false;
155 
156 	/* parse_args() stops at "--" and returns the address of the rest. */
157 	if (end_offset && err)
158 		*end_offset = err - tmp_cmdline;
159 
160 	return found;
161 }
162 
163 #endif	/* __KERNEL__ */
164 
165 /*
166  * Extra Boot Config (XBC) is given as tree-structured ascii text of
167  * key-value pairs on memory.
168  * xbc_parse() parses the text to build a simple tree. Each tree node is
169  * simply a key word or a value. A key node may have a next key node or/and
170  * a child node (both key and value). A value node may have a next value
171  * node (for array).
172  */
173 
174 static struct xbc_node *xbc_nodes __initdata;
175 static int xbc_node_num __initdata;
176 static char *xbc_data __initdata;
177 static size_t xbc_data_size __initdata;
178 static struct xbc_node *last_parent __initdata;
179 static const char *xbc_err_msg __initdata;
180 static int xbc_err_pos __initdata;
181 static int open_brace[XBC_DEPTH_MAX] __initdata;
182 static int brace_index __initdata;
183 
184 #ifdef __KERNEL__
185 static inline void * __init xbc_alloc_mem(size_t size)
186 {
187 	return memblock_alloc(size, SMP_CACHE_BYTES);
188 }
189 
190 static inline void __init xbc_free_mem(void *addr, size_t size)
191 {
192 	memblock_free(addr, size);
193 }
194 
195 #else /* !__KERNEL__ */
196 
197 static inline void *xbc_alloc_mem(size_t size)
198 {
199 	return calloc(1, size);
200 }
201 
202 static inline void xbc_free_mem(void *addr, size_t size)
203 {
204 	free(addr);
205 }
206 #endif
207 
208 /**
209  * xbc_get_info() - Get the information of loaded boot config
210  * @node_size: A pointer to store the number of nodes.
211  * @data_size: A pointer to store the size of bootconfig data.
212  *
213  * Get the number of used nodes in @node_size if it is not NULL,
214  * and the size of bootconfig data in @data_size if it is not NULL.
215  * Return 0 if the boot config is initialized, or return -ENODEV.
216  */
217 int __init xbc_get_info(int *node_size, size_t *data_size)
218 {
219 	if (!xbc_data)
220 		return -ENODEV;
221 
222 	if (node_size)
223 		*node_size = xbc_node_num;
224 	if (data_size)
225 		*data_size = xbc_data_size;
226 	return 0;
227 }
228 
229 static int __init xbc_parse_error(const char *msg, const char *p)
230 {
231 	xbc_err_msg = msg;
232 	xbc_err_pos = (int)(p - xbc_data);
233 
234 	return -EINVAL;
235 }
236 
237 /**
238  * xbc_root_node() - Get the root node of extended boot config
239  *
240  * Return the address of root node of extended boot config. If the
241  * extended boot config is not initialized, return NULL.
242  */
243 struct xbc_node * __init xbc_root_node(void)
244 {
245 	if (unlikely(!xbc_data))
246 		return NULL;
247 
248 	return xbc_nodes;
249 }
250 
251 /**
252  * xbc_node_index() - Get the index of XBC node
253  * @node: A target node of getting index.
254  *
255  * Return the index number of @node in XBC node list.
256  */
257 uint16_t __init xbc_node_index(struct xbc_node *node)
258 {
259 	return (uint16_t)(node - &xbc_nodes[0]);
260 }
261 
262 /**
263  * xbc_node_get_parent() - Get the parent XBC node
264  * @node: An XBC node.
265  *
266  * Return the parent node of @node. If the node is top node of the tree,
267  * return NULL.
268  */
269 struct xbc_node * __init xbc_node_get_parent(struct xbc_node *node)
270 {
271 	return node->parent == XBC_NODE_MAX ? NULL : &xbc_nodes[node->parent];
272 }
273 
274 /**
275  * xbc_node_get_child() - Get the child XBC node
276  * @node: An XBC node.
277  *
278  * Return the first child node of @node. If the node has no child, return
279  * NULL.
280  */
281 struct xbc_node * __init xbc_node_get_child(struct xbc_node *node)
282 {
283 	return node->child ? &xbc_nodes[node->child] : NULL;
284 }
285 
286 /**
287  * xbc_node_get_next() - Get the next sibling XBC node
288  * @node: An XBC node.
289  *
290  * Return the NEXT sibling node of @node. If the node has no next sibling,
291  * return NULL. Note that even if this returns NULL, it doesn't mean @node
292  * has no siblings. (You also has to check whether the parent's child node
293  * is @node or not.)
294  */
295 struct xbc_node * __init xbc_node_get_next(struct xbc_node *node)
296 {
297 	return node->next ? &xbc_nodes[node->next] : NULL;
298 }
299 
300 /**
301  * xbc_node_get_data() - Get the data of XBC node
302  * @node: An XBC node.
303  *
304  * Return the data (which is always a null terminated string) of @node.
305  * If the node has invalid data, warn and return NULL.
306  */
307 const char * __init xbc_node_get_data(struct xbc_node *node)
308 {
309 	size_t offset = node->data & ~XBC_VALUE;
310 
311 	if (WARN_ON(offset >= xbc_data_size))
312 		return NULL;
313 
314 	return xbc_data + offset;
315 }
316 
317 static bool __init
318 xbc_node_match_prefix(struct xbc_node *node, const char **prefix)
319 {
320 	const char *p = xbc_node_get_data(node);
321 	size_t len = strlen(p);
322 
323 	if (strncmp(*prefix, p, len))
324 		return false;
325 
326 	p = *prefix + len;
327 	if (*p == '.')
328 		p++;
329 	else if (*p != '\0')
330 		return false;
331 	*prefix = p;
332 
333 	return true;
334 }
335 
336 /**
337  * xbc_node_find_subkey() - Find a subkey node which matches given key
338  * @parent: An XBC node.
339  * @key: A key string.
340  *
341  * Search a key node under @parent which matches @key. The @key can contain
342  * several words jointed with '.'. If @parent is NULL, this searches the
343  * node from whole tree. Return NULL if no node is matched.
344  */
345 struct xbc_node * __init
346 xbc_node_find_subkey(struct xbc_node *parent, const char *key)
347 {
348 	struct xbc_node *node;
349 
350 	if (parent)
351 		node = xbc_node_get_subkey(parent);
352 	else
353 		node = xbc_root_node();
354 
355 	while (node && xbc_node_is_key(node)) {
356 		if (!xbc_node_match_prefix(node, &key))
357 			node = xbc_node_get_next(node);
358 		else if (*key != '\0')
359 			node = xbc_node_get_subkey(node);
360 		else
361 			break;
362 	}
363 
364 	return node;
365 }
366 
367 /**
368  * xbc_node_find_value() - Find a value node which matches given key
369  * @parent: An XBC node.
370  * @key: A key string.
371  * @vnode: A container pointer of found XBC node.
372  *
373  * Search a value node under @parent whose (parent) key node matches @key,
374  * store it in *@vnode, and returns the value string.
375  * The @key can contain several words jointed with '.'. If @parent is NULL,
376  * this searches the node from whole tree. Return the value string if a
377  * matched key found, return NULL if no node is matched.
378  * Note that this returns 0-length string and stores NULL in *@vnode if the
379  * key has no value. And also it will return the value of the first entry if
380  * the value is an array.
381  */
382 const char * __init
383 xbc_node_find_value(struct xbc_node *parent, const char *key,
384 		    struct xbc_node **vnode)
385 {
386 	struct xbc_node *node = xbc_node_find_subkey(parent, key);
387 
388 	if (!node || !xbc_node_is_key(node))
389 		return NULL;
390 
391 	node = xbc_node_get_child(node);
392 	if (node && !xbc_node_is_value(node))
393 		return NULL;
394 
395 	if (vnode)
396 		*vnode = node;
397 
398 	return node ? xbc_node_get_data(node) : "";
399 }
400 
401 /**
402  * xbc_node_compose_key_after() - Compose partial key string of the XBC node
403  * @root: Root XBC node
404  * @node: Target XBC node.
405  * @buf: A buffer to store the key.
406  * @size: The size of the @buf.
407  *
408  * Compose the partial key of the @node into @buf, which is starting right
409  * after @root (@root is not included.) If @root is NULL, this returns full
410  * key words of @node.
411  * Returns the total length of the key stored in @buf. Returns -EINVAL
412  * if @node is NULL or @root is not the ancestor of @node or @root is @node,
413  * or returns -ERANGE if the key depth is deeper than max depth.
414  * This is expected to be used with xbc_find_node() to list up all (child)
415  * keys under given key.
416  */
417 int __init xbc_node_compose_key_after(struct xbc_node *root,
418 				      struct xbc_node *node,
419 				      char *buf, size_t size)
420 {
421 	uint16_t keys[XBC_DEPTH_MAX];
422 	int depth = 0, ret = 0, total = 0;
423 
424 	if (!node || node == root)
425 		return -EINVAL;
426 
427 	if (xbc_node_is_value(node))
428 		node = xbc_node_get_parent(node);
429 
430 	while (node && node != root) {
431 		keys[depth++] = xbc_node_index(node);
432 		if (depth == XBC_DEPTH_MAX)
433 			return -ERANGE;
434 		node = xbc_node_get_parent(node);
435 	}
436 	if (!node && root)
437 		return -EINVAL;
438 
439 	while (--depth >= 0) {
440 		node = xbc_nodes + keys[depth];
441 		ret = snprintf(buf, size, "%s%s", xbc_node_get_data(node),
442 			       depth ? "." : "");
443 		if (ret < 0)
444 			return ret;
445 		if (ret >= size) {
446 			size = 0;
447 		} else {
448 			size -= ret;
449 			buf += ret;
450 		}
451 		total += ret;
452 	}
453 
454 	return total;
455 }
456 
457 /**
458  * xbc_node_find_next_leaf() - Find the next leaf node under given node
459  * @root: An XBC root node
460  * @node: An XBC node which starts from.
461  *
462  * Search the next leaf node (which means the terminal key node) of @node
463  * under @root node (including @root node itself).
464  * Return the next node or NULL if next leaf node is not found.
465  */
466 struct xbc_node * __init xbc_node_find_next_leaf(struct xbc_node *root,
467 						 struct xbc_node *node)
468 {
469 	struct xbc_node *next;
470 
471 	if (unlikely(!xbc_data))
472 		return NULL;
473 
474 	if (!node) {	/* First try */
475 		node = root;
476 		if (!node)
477 			node = xbc_nodes;
478 	} else {
479 		/* Leaf node may have a subkey */
480 		next = xbc_node_get_subkey(node);
481 		if (next) {
482 			node = next;
483 			goto found;
484 		}
485 
486 		if (node == root)	/* @root was a leaf, no child node. */
487 			return NULL;
488 
489 		while (!node->next) {
490 			node = xbc_node_get_parent(node);
491 			if (node == root)
492 				return NULL;
493 			/* User passed a node which is not under parent */
494 			if (WARN_ON(!node))
495 				return NULL;
496 		}
497 		node = xbc_node_get_next(node);
498 	}
499 
500 found:
501 	while (node && !xbc_node_is_leaf(node))
502 		node = xbc_node_get_child(node);
503 
504 	return node;
505 }
506 
507 /**
508  * xbc_node_find_next_key_value() - Find the next key-value pair nodes
509  * @root: An XBC root node
510  * @leaf: A container pointer of XBC node which starts from.
511  *
512  * Search the next leaf node (which means the terminal key node) of *@leaf
513  * under @root node. Returns the value and update *@leaf if next leaf node
514  * is found, or NULL if no next leaf node is found.
515  * Note that this returns 0-length string if the key has no value, or
516  * the value of the first entry if the value is an array.
517  */
518 const char * __init xbc_node_find_next_key_value(struct xbc_node *root,
519 						 struct xbc_node **leaf)
520 {
521 	/* tip must be passed */
522 	if (WARN_ON(!leaf))
523 		return NULL;
524 
525 	*leaf = xbc_node_find_next_leaf(root, *leaf);
526 	if (!*leaf)
527 		return NULL;
528 	if ((*leaf)->child)
529 		return xbc_node_get_data(xbc_node_get_child(*leaf));
530 	else
531 		return "";	/* No value key */
532 }
533 
534 static char xbc_namebuf[XBC_KEYLEN_MAX] __initdata;
535 
536 #define rest(dst, end) ((end) > (dst) ? (end) - (dst) : 0)
537 
538 /**
539  * xbc_snprint_cmdline_filter() - Render bootconfig keys as cmdline string
540  * @buf: Destination buffer (may be NULL when @size is 0 to query the length)
541  * @size: Size of @buf in bytes
542  * @root: Subtree root whose key=value pairs should be rendered
543  * @filter: Filter callback (returns true to include, false to skip; may be NULL)
544  * @data: Private context passed to @filter
545  *
546  * Walk all key/value pairs under @root and emit them as a space-separated
547  * cmdline string into @buf. Values containing whitespace are quoted with
548  * double quotes. Keys for which @filter returns false are omitted.
549  * Returns the number of bytes that would be written if @buf were large enough
550  * (matching snprintf semantics), or a negative errno on failure.
551  */
552 int __init xbc_snprint_cmdline_filter(char *buf, size_t size, struct xbc_node *root,
553 				      xbc_cmdline_filter_fn filter, void *data)
554 {
555 	struct xbc_node *knode, *vnode;
556 	const char *val, *q;
557 	size_t len = 0;
558 	int ret;
559 
560 	/*
561 	 * Track the running written length rather than advancing @buf, so we
562 	 * never form "buf + size" or "buf += ret" while @buf is NULL (the
563 	 * size-probe call passes buf=NULL, size=0). NULL pointer arithmetic
564 	 * is undefined behavior and trips host UBSan / FORTIFY_SOURCE when
565 	 * this renderer runs at kernel build time. snprintf(NULL, 0, ...)
566 	 * itself is well defined and returns the would-be length.
567 	 */
568 	xbc_node_for_each_key_value(root, knode, val) {
569 		/*
570 		 * An empty or value-only @root (e.g. "kernel {}" or
571 		 * "kernel = x", possibly alongside "kernel.foo = bar")
572 		 * yields @root itself here. Skip it: composing a key for it
573 		 * would fail with -EINVAL, yet any real descendant keys must
574 		 * still be rendered. An entirely empty subtree then renders
575 		 * nothing and returns 0 rather than an error.
576 		 */
577 		if (knode == root)
578 			continue;
579 
580 		ret = xbc_node_compose_key_after(root, knode,
581 					xbc_namebuf, XBC_KEYLEN_MAX);
582 		if (ret < 0)
583 			return ret;
584 
585 		if (filter && !filter(knode, xbc_namebuf, data))
586 			continue;
587 
588 		vnode = xbc_node_get_child(knode);
589 		if (!vnode) {
590 			ret = snprintf(buf ? buf + len : NULL, rest(len, size),
591 				       "%s ", xbc_namebuf);
592 			if (ret < 0)
593 				return ret;
594 			len += ret;
595 			continue;
596 		}
597 		xbc_array_for_each_value(vnode, val) {
598 			/*
599 			 * For prettier and more readable /proc/cmdline, only
600 			 * quote the value when necessary, i.e. when it contains
601 			 * whitespace.
602 			 */
603 			q = strpbrk(val, " \t\r\n") ? "\"" : "";
604 			ret = snprintf(buf ? buf + len : NULL, rest(len, size),
605 				       "%s=%s%s%s ", xbc_namebuf, q, val, q);
606 			if (ret < 0)
607 				return ret;
608 			len += ret;
609 		}
610 	}
611 
612 	return len;
613 }
614 #undef rest
615 
616 /* XBC parse and tree build */
617 
618 static int __init xbc_init_node(struct xbc_node *node, char *data, uint16_t flag)
619 {
620 	long offset = data - xbc_data;
621 
622 	if (WARN_ON(offset < 0 || offset >= XBC_DATA_MAX))
623 		return -EINVAL;
624 
625 	node->data = (uint16_t)offset | flag;
626 	node->child = 0;
627 	node->next = 0;
628 
629 	return 0;
630 }
631 
632 static struct xbc_node * __init xbc_add_node(char *data, uint16_t flag)
633 {
634 	struct xbc_node *node;
635 
636 	if (xbc_node_num == XBC_NODE_MAX)
637 		return NULL;
638 
639 	node = &xbc_nodes[xbc_node_num];
640 	if (xbc_init_node(node, data, flag) < 0)
641 		return NULL;
642 	xbc_node_num++;
643 
644 	return node;
645 }
646 
647 static inline __init struct xbc_node *xbc_last_sibling(struct xbc_node *node)
648 {
649 	while (node->next)
650 		node = xbc_node_get_next(node);
651 
652 	return node;
653 }
654 
655 static inline __init struct xbc_node *xbc_last_child(struct xbc_node *node)
656 {
657 	while (node->child)
658 		node = xbc_node_get_child(node);
659 
660 	return node;
661 }
662 
663 static struct xbc_node * __init __xbc_add_sibling(char *data, uint16_t flag, bool head)
664 {
665 	struct xbc_node *sib, *node = xbc_add_node(data, flag);
666 
667 	if (node) {
668 		if (!last_parent) {
669 			/* Ignore @head in this case */
670 			node->parent = XBC_NODE_MAX;
671 			sib = xbc_last_sibling(xbc_nodes);
672 			sib->next = xbc_node_index(node);
673 		} else {
674 			node->parent = xbc_node_index(last_parent);
675 			if (!last_parent->child || head) {
676 				node->next = last_parent->child;
677 				last_parent->child = xbc_node_index(node);
678 			} else {
679 				sib = xbc_node_get_child(last_parent);
680 				sib = xbc_last_sibling(sib);
681 				sib->next = xbc_node_index(node);
682 			}
683 		}
684 	} else {
685 		xbc_parse_error("Too many nodes", data);
686 	}
687 
688 	return node;
689 }
690 
691 static inline struct xbc_node * __init xbc_add_sibling(char *data, uint16_t flag)
692 {
693 	return __xbc_add_sibling(data, flag, false);
694 }
695 
696 static inline struct xbc_node * __init xbc_add_head_sibling(char *data, uint16_t flag)
697 {
698 	return __xbc_add_sibling(data, flag, true);
699 }
700 
701 static inline __init struct xbc_node *xbc_add_child(char *data, uint16_t flag)
702 {
703 	struct xbc_node *node = xbc_add_sibling(data, flag);
704 
705 	if (node)
706 		last_parent = node;
707 
708 	return node;
709 }
710 
711 static inline __init bool xbc_valid_keyword(char *key)
712 {
713 	if (key[0] == '\0')
714 		return false;
715 
716 	while (isalnum(*key) || *key == '-' || *key == '_')
717 		key++;
718 
719 	return *key == '\0';
720 }
721 
722 static char *skip_comment(char *p)
723 {
724 	char *ret;
725 
726 	ret = strchr(p, '\n');
727 	if (!ret)
728 		ret = p + strlen(p);
729 	else
730 		ret++;
731 
732 	return ret;
733 }
734 
735 static char *skip_spaces_until_newline(char *p)
736 {
737 	while (isspace(*p) && *p != '\n')
738 		p++;
739 	return p;
740 }
741 
742 static int __init __xbc_open_brace(char *p)
743 {
744 	/* Push the last key as open brace */
745 	if (brace_index >= XBC_DEPTH_MAX)
746 		return xbc_parse_error("Exceed max depth of braces", p);
747 	open_brace[brace_index++] = xbc_node_index(last_parent);
748 
749 	return 0;
750 }
751 
752 static int __init __xbc_close_brace(char *p)
753 {
754 	brace_index--;
755 	if (!last_parent || brace_index < 0 ||
756 	    (open_brace[brace_index] != xbc_node_index(last_parent)))
757 		return xbc_parse_error("Unexpected closing brace", p);
758 
759 	if (brace_index == 0)
760 		last_parent = NULL;
761 	else
762 		last_parent = &xbc_nodes[open_brace[brace_index - 1]];
763 
764 	return 0;
765 }
766 
767 /*
768  * Return delimiter or error, no node added. As same as lib/cmdline.c,
769  * you can use " around spaces, but can't escape " for value.
770  * *@__v must point real value string. (not including spaces before value.)
771  */
772 static int __init __xbc_parse_value(char **__v, char **__n)
773 {
774 	char *p, *v = *__v;
775 	int c, quotes = 0;
776 
777 	if (*v == '"' || *v == '\'') {
778 		quotes = *v;
779 		v++;
780 	}
781 	p = v - 1;
782 	while ((c = *++p)) {
783 		if (!isprint(c) && !isspace(c))
784 			return xbc_parse_error("Non printable value", p);
785 		if (quotes) {
786 			if (c != quotes)
787 				continue;
788 			quotes = 0;
789 			*p++ = '\0';
790 			p = skip_spaces_until_newline(p);
791 			c = *p;
792 			if (c && !strchr(",;\n#}", c))
793 				return xbc_parse_error("No value delimiter", p);
794 			if (*p)
795 				p++;
796 			break;
797 		}
798 		if (strchr(",;\n#}", c)) {
799 			*p++ = '\0';
800 			v = strim(v);
801 			break;
802 		}
803 	}
804 	if (quotes)
805 		return xbc_parse_error("No closing quotes", p);
806 	if (c == '#') {
807 		p = skip_comment(p);
808 		c = '\n';	/* A comment must be treated as a newline */
809 	}
810 	*__n = p;
811 	*__v = v;
812 
813 	return c;
814 }
815 
816 static int __init xbc_parse_array(char **__v)
817 {
818 	struct xbc_node *node;
819 	char *next;
820 	int c = 0;
821 
822 	if (last_parent->child)
823 		last_parent = xbc_node_get_child(last_parent);
824 
825 	do {
826 		/* Search the next array value beyond comments and empty lines */
827 		next = skip_spaces(*__v);
828 		while (*next == '#') {
829 			next = skip_comment(next);
830 			next = skip_spaces(next);
831 		}
832 		*__v = next;
833 		c = __xbc_parse_value(__v, &next);
834 		if (c < 0)
835 			return c;
836 
837 		node = xbc_add_child(*__v, XBC_VALUE);
838 		if (!node)
839 			return -ENOMEM;
840 		*__v = next;
841 	} while (c == ',');
842 
843 	return c;
844 }
845 
846 static inline __init
847 struct xbc_node *find_match_node(struct xbc_node *node, char *k)
848 {
849 	while (node) {
850 		if (!strcmp(xbc_node_get_data(node), k))
851 			break;
852 		node = xbc_node_get_next(node);
853 	}
854 	return node;
855 }
856 
857 static int __init __xbc_add_key(char *k)
858 {
859 	struct xbc_node *node, *child;
860 
861 	if (!xbc_valid_keyword(k))
862 		return xbc_parse_error("Invalid keyword", k);
863 
864 	if (unlikely(xbc_node_num == 0))
865 		goto add_node;
866 
867 	if (!last_parent) {	/* the first level */
868 		node = find_match_node(xbc_nodes, k);
869 	} else {
870 		child = xbc_node_get_child(last_parent);
871 		/* Since the value node is the first child, skip it. */
872 		if (child && xbc_node_is_value(child))
873 			child = xbc_node_get_next(child);
874 		node = find_match_node(child, k);
875 	}
876 
877 	if (node) {
878 		last_parent = node;
879 	} else {
880 add_node:
881 		node = xbc_add_child(k, XBC_KEY);
882 		if (!node)
883 			return -ENOMEM;
884 	}
885 	return 0;
886 }
887 
888 static int __init __xbc_parse_keys(char *k)
889 {
890 	char *p;
891 	int ret;
892 
893 	k = strim(k);
894 	while ((p = strchr(k, '.'))) {
895 		*p++ = '\0';
896 		ret = __xbc_add_key(k);
897 		if (ret)
898 			return ret;
899 		k = p;
900 	}
901 
902 	return __xbc_add_key(k);
903 }
904 
905 static int __init xbc_parse_kv(char **k, char *v, int op)
906 {
907 	struct xbc_node *prev_parent = last_parent;
908 	struct xbc_node *child;
909 	char *next;
910 	int c, ret;
911 
912 	ret = __xbc_parse_keys(*k);
913 	if (ret)
914 		return ret;
915 
916 	v = skip_spaces_until_newline(v);
917 	/* If there is a comment, this has an empty value. */
918 	if (*v == '#') {
919 		next = skip_comment(v);
920 		*v = '\0';
921 		c = '\n';
922 	} else {
923 		c = __xbc_parse_value(&v, &next);
924 		if (c < 0)
925 			return c;
926 	}
927 
928 	child = xbc_node_get_child(last_parent);
929 	if (child && xbc_node_is_value(child)) {
930 		if (op == '=')
931 			return xbc_parse_error("Value is redefined", v);
932 		if (op == ':') {
933 			unsigned short nidx = child->next;
934 
935 			if (xbc_init_node(child, v, XBC_VALUE) < 0)
936 				return xbc_parse_error("Failed to override value", v);
937 			child->next = nidx;	/* keep subkeys */
938 			goto array;
939 		}
940 		/* op must be '+' */
941 		last_parent = xbc_last_child(child);
942 	}
943 	/* The value node should always be the first child */
944 	if (!xbc_add_head_sibling(v, XBC_VALUE))
945 		return -ENOMEM;
946 
947 array:
948 	if (c == ',') {	/* Array */
949 		c = xbc_parse_array(&next);
950 		if (c < 0)
951 			return c;
952 	}
953 
954 	last_parent = prev_parent;
955 
956 	if (c == '}') {
957 		ret = __xbc_close_brace(next - 1);
958 		if (ret < 0)
959 			return ret;
960 	}
961 
962 	*k = next;
963 
964 	return 0;
965 }
966 
967 static int __init xbc_parse_key(char **k, char *n)
968 {
969 	struct xbc_node *prev_parent = last_parent;
970 	int ret;
971 
972 	*k = strim(*k);
973 	if (**k != '\0') {
974 		ret = __xbc_parse_keys(*k);
975 		if (ret)
976 			return ret;
977 		last_parent = prev_parent;
978 	}
979 	*k = n;
980 
981 	return 0;
982 }
983 
984 static int __init xbc_open_brace(char **k, char *n)
985 {
986 	int ret;
987 
988 	ret = __xbc_parse_keys(*k);
989 	if (ret)
990 		return ret;
991 	*k = n;
992 
993 	return __xbc_open_brace(n - 1);
994 }
995 
996 static int __init xbc_close_brace(char **k, char *n)
997 {
998 	int ret;
999 
1000 	ret = xbc_parse_key(k, n);
1001 	if (ret)
1002 		return ret;
1003 	/* k is updated in xbc_parse_key() */
1004 
1005 	return __xbc_close_brace(n - 1);
1006 }
1007 
1008 #ifndef __KERNEL__
1009 /* Sanity check for regression: node indices must be within bounds */
1010 static int __init xbc_sanity_check_tree(void)
1011 {
1012 	int i;
1013 
1014 	for (i = 0; i < xbc_node_num; i++) {
1015 		if (xbc_nodes[i].next >= xbc_node_num) {
1016 			return xbc_parse_error("No closing brace",
1017 				xbc_node_get_data(xbc_nodes + i));
1018 		}
1019 		if (xbc_nodes[i].child >= xbc_node_num) {
1020 			return xbc_parse_error("Broken child node",
1021 				xbc_node_get_data(xbc_nodes + i));
1022 		}
1023 	}
1024 
1025 	return 0;
1026 }
1027 #endif
1028 
1029 static int __init xbc_verify_tree(void)
1030 {
1031 	int depth;
1032 	size_t len, wlen;
1033 	struct xbc_node *n, *m;
1034 
1035 	/* Brace closing */
1036 	if (brace_index) {
1037 		n = &xbc_nodes[open_brace[brace_index - 1]];
1038 		return xbc_parse_error("Brace is not closed",
1039 					xbc_node_get_data(n));
1040 	}
1041 
1042 	/* Empty tree */
1043 	if (xbc_node_num == 0) {
1044 		xbc_parse_error("Empty config", xbc_data);
1045 		return -ENOENT;
1046 	}
1047 
1048 	/* Key tree limitation check */
1049 	n = &xbc_nodes[0];
1050 	depth = 1;
1051 	len = 0;
1052 
1053 	while (n) {
1054 		wlen = strlen(xbc_node_get_data(n)) + 1;
1055 		len += wlen;
1056 		if (len > XBC_KEYLEN_MAX)
1057 			return xbc_parse_error("Too long key length",
1058 				xbc_node_get_data(n));
1059 
1060 		m = xbc_node_get_child(n);
1061 		if (m && xbc_node_is_key(m)) {
1062 			n = m;
1063 			depth++;
1064 			if (depth > XBC_DEPTH_MAX)
1065 				return xbc_parse_error("Too many key words",
1066 						xbc_node_get_data(n));
1067 			continue;
1068 		}
1069 		len -= wlen;
1070 		m = xbc_node_get_next(n);
1071 		while (!m) {
1072 			n = xbc_node_get_parent(n);
1073 			if (!n)
1074 				break;
1075 			len -= strlen(xbc_node_get_data(n)) + 1;
1076 			depth--;
1077 			m = xbc_node_get_next(n);
1078 		}
1079 		n = m;
1080 	}
1081 
1082 	return 0;
1083 }
1084 
1085 /* Need to setup xbc_data and xbc_nodes before call this. */
1086 static int __init xbc_parse_tree(void)
1087 {
1088 	char *p, *q;
1089 	int ret = 0, c;
1090 
1091 	last_parent = NULL;
1092 	p = xbc_data;
1093 	do {
1094 		q = strpbrk(p, "{}=+;:\n#");
1095 		if (!q) {
1096 			p = skip_spaces(p);
1097 			if (*p != '\0')
1098 				ret = xbc_parse_error("No delimiter", p);
1099 			break;
1100 		}
1101 
1102 		c = *q;
1103 		*q++ = '\0';
1104 		switch (c) {
1105 		case ':':
1106 		case '+':
1107 			if (*q++ != '=') {
1108 				ret = xbc_parse_error(c == '+' ?
1109 						"Wrong '+' operator" :
1110 						"Wrong ':' operator",
1111 							q - 2);
1112 				break;
1113 			}
1114 			fallthrough;
1115 		case '=':
1116 			ret = xbc_parse_kv(&p, q, c);
1117 			break;
1118 		case '{':
1119 			ret = xbc_open_brace(&p, q);
1120 			break;
1121 		case '#':
1122 			q = skip_comment(q);
1123 			fallthrough;
1124 		case ';':
1125 		case '\n':
1126 			ret = xbc_parse_key(&p, q);
1127 			break;
1128 		case '}':
1129 			ret = xbc_close_brace(&p, q);
1130 			break;
1131 		}
1132 	} while (!ret);
1133 
1134 	if (!ret) {
1135 		while (p < xbc_data + xbc_data_size - 1 && *p == '\0')
1136 			p++;
1137 		if (p < xbc_data + xbc_data_size - 1)
1138 			ret = xbc_parse_error("Unexpected data after null character", p);
1139 	}
1140 
1141 	return ret;
1142 }
1143 
1144 /**
1145  * xbc_exit() - Clean up all parsed bootconfig
1146  *
1147  * This clears all data structures of parsed bootconfig on memory.
1148  * If you need to reuse xbc_init() with new boot config, you can
1149  * use this.
1150  */
1151 void __init xbc_exit(void)
1152 {
1153 	xbc_free_mem(xbc_data, xbc_data_size);
1154 	xbc_data = NULL;
1155 	xbc_data_size = 0;
1156 	xbc_node_num = 0;
1157 	xbc_free_mem(xbc_nodes, sizeof(struct xbc_node) * XBC_NODE_MAX);
1158 	xbc_nodes = NULL;
1159 	brace_index = 0;
1160 }
1161 
1162 /**
1163  * xbc_init() - Parse given XBC file and build XBC internal tree
1164  * @data: The boot config text original data
1165  * @size: The size of @data
1166  * @emsg: A pointer of const char * to store the error message
1167  * @epos: A pointer of int to store the error position
1168  *
1169  * This parses the boot config text in @data. @size must be smaller
1170  * than XBC_DATA_MAX.
1171  * Return the number of stored nodes (>0) if succeeded, or -errno
1172  * if there is any error.
1173  * In error cases, @emsg will be updated with an error message and
1174  * @epos will be updated with the error position which is the byte offset
1175  * of @buf. If the error is not a parser error, @epos will be -1.
1176  */
1177 int __init xbc_init(const char *data, size_t size, const char **emsg, int *epos)
1178 {
1179 	int ret;
1180 
1181 	if (epos)
1182 		*epos = -1;
1183 
1184 	if (xbc_data) {
1185 		if (emsg)
1186 			*emsg = "Bootconfig is already initialized";
1187 		return -EBUSY;
1188 	}
1189 	if (size > XBC_DATA_MAX || size == 0) {
1190 		if (emsg)
1191 			*emsg = size ? "Config data is too big" :
1192 				"Config data is empty";
1193 		return -ERANGE;
1194 	}
1195 
1196 	xbc_data = xbc_alloc_mem(size + 1);
1197 	if (!xbc_data) {
1198 		if (emsg)
1199 			*emsg = "Failed to allocate bootconfig data";
1200 		return -ENOMEM;
1201 	}
1202 	memcpy(xbc_data, data, size);
1203 	xbc_data[size] = '\0';
1204 	xbc_data_size = size + 1;
1205 
1206 	xbc_nodes = xbc_alloc_mem(sizeof(struct xbc_node) * XBC_NODE_MAX);
1207 	if (!xbc_nodes) {
1208 		if (emsg)
1209 			*emsg = "Failed to allocate bootconfig nodes";
1210 		xbc_exit();
1211 		return -ENOMEM;
1212 	}
1213 
1214 	ret = xbc_parse_tree();
1215 	if (!ret)
1216 		ret = xbc_verify_tree();
1217 #ifndef __KERNEL__
1218 	if (!ret)
1219 		ret = xbc_sanity_check_tree();
1220 #endif
1221 
1222 	if (ret < 0) {
1223 		if (epos)
1224 			*epos = xbc_err_pos;
1225 		if (emsg)
1226 			*emsg = xbc_err_msg;
1227 		xbc_exit();
1228 	} else {
1229 		ret = xbc_node_num;
1230 	}
1231 
1232 	return ret;
1233 }
1234