xref: /linux/lib/bootconfig.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
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 		if (depth == XBC_DEPTH_MAX)
432 			return -ERANGE;
433 		keys[depth++] = xbc_node_index(node);
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 			goto skip_trim;
797 		}
798 		if (strchr(",;\n#}", c)) {
799 			*p++ = '\0';
800 			break;
801 		}
802 	}
803 	if (quotes)
804 		return xbc_parse_error("No closing quotes", p);
805 	v = strim(v);
806 skip_trim:
807 	if (c == '#') {
808 		p = skip_comment(p);
809 		c = '\n';	/* A comment must be treated as a newline */
810 	}
811 	*__n = p;
812 	*__v = v;
813 
814 	return c;
815 }
816 
817 static int __init xbc_parse_array(char **__v)
818 {
819 	struct xbc_node *node;
820 	char *next;
821 	int c = 0;
822 
823 	if (last_parent->child)
824 		last_parent = xbc_node_get_child(last_parent);
825 
826 	do {
827 		/* Search the next array value beyond comments and empty lines */
828 		next = skip_spaces(*__v);
829 		while (*next == '#') {
830 			next = skip_comment(next);
831 			next = skip_spaces(next);
832 		}
833 		*__v = next;
834 		c = __xbc_parse_value(__v, &next);
835 		if (c < 0)
836 			return c;
837 
838 		node = xbc_add_child(*__v, XBC_VALUE);
839 		if (!node)
840 			return -ENOMEM;
841 		*__v = next;
842 	} while (c == ',');
843 
844 	return c;
845 }
846 
847 static inline __init
848 struct xbc_node *find_match_node(struct xbc_node *node, char *k)
849 {
850 	while (node) {
851 		if (!strcmp(xbc_node_get_data(node), k))
852 			break;
853 		node = xbc_node_get_next(node);
854 	}
855 	return node;
856 }
857 
858 static int __init __xbc_add_key(char *k)
859 {
860 	struct xbc_node *node, *child;
861 
862 	if (!xbc_valid_keyword(k))
863 		return xbc_parse_error("Invalid keyword", k);
864 
865 	if (unlikely(xbc_node_num == 0))
866 		goto add_node;
867 
868 	if (!last_parent) {	/* the first level */
869 		node = find_match_node(xbc_nodes, k);
870 	} else {
871 		child = xbc_node_get_child(last_parent);
872 		/* Since the value node is the first child, skip it. */
873 		if (child && xbc_node_is_value(child))
874 			child = xbc_node_get_next(child);
875 		node = find_match_node(child, k);
876 	}
877 
878 	if (node) {
879 		last_parent = node;
880 	} else {
881 add_node:
882 		node = xbc_add_child(k, XBC_KEY);
883 		if (!node)
884 			return -ENOMEM;
885 	}
886 	return 0;
887 }
888 
889 static int __init __xbc_parse_keys(char *k)
890 {
891 	char *p;
892 	int ret;
893 
894 	k = strim(k);
895 	while ((p = strchr(k, '.'))) {
896 		*p++ = '\0';
897 		ret = __xbc_add_key(k);
898 		if (ret)
899 			return ret;
900 		k = p;
901 	}
902 
903 	return __xbc_add_key(k);
904 }
905 
906 static int __init xbc_parse_kv(char **k, char *v, int op)
907 {
908 	struct xbc_node *prev_parent = last_parent;
909 	struct xbc_node *child;
910 	char *next;
911 	int c, ret;
912 
913 	ret = __xbc_parse_keys(*k);
914 	if (ret)
915 		return ret;
916 
917 	v = skip_spaces_until_newline(v);
918 	/* If there is a comment, this has an empty value. */
919 	if (*v == '#') {
920 		next = skip_comment(v);
921 		*v = '\0';
922 		c = '\n';
923 	} else {
924 		c = __xbc_parse_value(&v, &next);
925 		if (c < 0)
926 			return c;
927 	}
928 
929 	child = xbc_node_get_child(last_parent);
930 	if (child && xbc_node_is_value(child)) {
931 		if (op == '=')
932 			return xbc_parse_error("Value is redefined", v);
933 		if (op == ':') {
934 			unsigned short nidx = child->next;
935 
936 			if (xbc_init_node(child, v, XBC_VALUE) < 0)
937 				return xbc_parse_error("Failed to override value", v);
938 			child->next = nidx;	/* keep subkeys */
939 			goto array;
940 		}
941 		/* op must be '+' */
942 		last_parent = xbc_last_child(child);
943 	}
944 	/* The value node should always be the first child */
945 	if (!xbc_add_head_sibling(v, XBC_VALUE))
946 		return -ENOMEM;
947 
948 array:
949 	if (c == ',') {	/* Array */
950 		c = xbc_parse_array(&next);
951 		if (c < 0)
952 			return c;
953 	}
954 
955 	last_parent = prev_parent;
956 
957 	if (c == '}') {
958 		ret = __xbc_close_brace(next - 1);
959 		if (ret < 0)
960 			return ret;
961 	}
962 
963 	*k = next;
964 
965 	return 0;
966 }
967 
968 static int __init xbc_parse_key(char **k, char *n)
969 {
970 	struct xbc_node *prev_parent = last_parent;
971 	int ret;
972 
973 	*k = strim(*k);
974 	if (**k != '\0') {
975 		ret = __xbc_parse_keys(*k);
976 		if (ret)
977 			return ret;
978 		last_parent = prev_parent;
979 	}
980 	*k = n;
981 
982 	return 0;
983 }
984 
985 static int __init xbc_open_brace(char **k, char *n)
986 {
987 	int ret;
988 
989 	ret = __xbc_parse_keys(*k);
990 	if (ret)
991 		return ret;
992 	*k = n;
993 
994 	return __xbc_open_brace(n - 1);
995 }
996 
997 static int __init xbc_close_brace(char **k, char *n)
998 {
999 	int ret;
1000 
1001 	ret = xbc_parse_key(k, n);
1002 	if (ret)
1003 		return ret;
1004 	/* k is updated in xbc_parse_key() */
1005 
1006 	return __xbc_close_brace(n - 1);
1007 }
1008 
1009 #ifndef __KERNEL__
1010 /* Sanity check for regression: node indices must be within bounds */
1011 static int __init xbc_sanity_check_tree(void)
1012 {
1013 	int i;
1014 
1015 	for (i = 0; i < xbc_node_num; i++) {
1016 		if (xbc_nodes[i].next >= xbc_node_num) {
1017 			return xbc_parse_error("No closing brace",
1018 				xbc_node_get_data(xbc_nodes + i));
1019 		}
1020 		if (xbc_nodes[i].child >= xbc_node_num) {
1021 			return xbc_parse_error("Broken child node",
1022 				xbc_node_get_data(xbc_nodes + i));
1023 		}
1024 	}
1025 
1026 	return 0;
1027 }
1028 #endif
1029 
1030 static int __init xbc_verify_tree(void)
1031 {
1032 	int depth;
1033 	size_t len, wlen;
1034 	struct xbc_node *n, *m;
1035 
1036 	/* Brace closing */
1037 	if (brace_index) {
1038 		n = &xbc_nodes[open_brace[brace_index - 1]];
1039 		return xbc_parse_error("Brace is not closed",
1040 					xbc_node_get_data(n));
1041 	}
1042 
1043 	/* Empty tree */
1044 	if (xbc_node_num == 0) {
1045 		xbc_parse_error("Empty config", xbc_data);
1046 		return -ENOENT;
1047 	}
1048 
1049 	/* Key tree limitation check */
1050 	n = &xbc_nodes[0];
1051 	depth = 1;
1052 	len = 0;
1053 
1054 	while (n) {
1055 		wlen = strlen(xbc_node_get_data(n)) + 1;
1056 		len += wlen;
1057 		if (len > XBC_KEYLEN_MAX)
1058 			return xbc_parse_error("Too long key length",
1059 				xbc_node_get_data(n));
1060 
1061 		m = xbc_node_get_child(n);
1062 		if (m && xbc_node_is_key(m)) {
1063 			n = m;
1064 			depth++;
1065 			if (depth > XBC_DEPTH_MAX)
1066 				return xbc_parse_error("Too many key words",
1067 						xbc_node_get_data(n));
1068 			continue;
1069 		}
1070 		len -= wlen;
1071 		m = xbc_node_get_next(n);
1072 		while (!m) {
1073 			n = xbc_node_get_parent(n);
1074 			if (!n)
1075 				break;
1076 			len -= strlen(xbc_node_get_data(n)) + 1;
1077 			depth--;
1078 			m = xbc_node_get_next(n);
1079 		}
1080 		n = m;
1081 	}
1082 
1083 	return 0;
1084 }
1085 
1086 /* Need to setup xbc_data and xbc_nodes before call this. */
1087 static int __init xbc_parse_tree(void)
1088 {
1089 	char *p, *q;
1090 	int ret = 0, c;
1091 
1092 	last_parent = NULL;
1093 	p = xbc_data;
1094 	do {
1095 		q = strpbrk(p, "{}=+;:\n#");
1096 		if (!q) {
1097 			p = skip_spaces(p);
1098 			if (*p != '\0')
1099 				ret = xbc_parse_error("No delimiter", p);
1100 			break;
1101 		}
1102 
1103 		c = *q;
1104 		*q++ = '\0';
1105 		switch (c) {
1106 		case ':':
1107 		case '+':
1108 			if (*q++ != '=') {
1109 				ret = xbc_parse_error(c == '+' ?
1110 						"Wrong '+' operator" :
1111 						"Wrong ':' operator",
1112 							q - 2);
1113 				break;
1114 			}
1115 			fallthrough;
1116 		case '=':
1117 			ret = xbc_parse_kv(&p, q, c);
1118 			break;
1119 		case '{':
1120 			ret = xbc_open_brace(&p, q);
1121 			break;
1122 		case '#':
1123 			q = skip_comment(q);
1124 			fallthrough;
1125 		case ';':
1126 		case '\n':
1127 			ret = xbc_parse_key(&p, q);
1128 			break;
1129 		case '}':
1130 			ret = xbc_close_brace(&p, q);
1131 			break;
1132 		}
1133 	} while (!ret);
1134 
1135 	if (!ret) {
1136 		while (p < xbc_data + xbc_data_size - 1 && *p == '\0')
1137 			p++;
1138 		if (p < xbc_data + xbc_data_size - 1)
1139 			ret = xbc_parse_error("Unexpected data after null character", p);
1140 	}
1141 
1142 	return ret;
1143 }
1144 
1145 /**
1146  * xbc_exit() - Clean up all parsed bootconfig
1147  *
1148  * This clears all data structures of parsed bootconfig on memory.
1149  * If you need to reuse xbc_init() with new boot config, you can
1150  * use this.
1151  */
1152 void __init xbc_exit(void)
1153 {
1154 	xbc_free_mem(xbc_data, xbc_data_size);
1155 	xbc_data = NULL;
1156 	xbc_data_size = 0;
1157 	xbc_node_num = 0;
1158 	xbc_free_mem(xbc_nodes, sizeof(struct xbc_node) * XBC_NODE_MAX);
1159 	xbc_nodes = NULL;
1160 	brace_index = 0;
1161 }
1162 
1163 /**
1164  * xbc_init() - Parse given XBC file and build XBC internal tree
1165  * @data: The boot config text original data
1166  * @size: The size of @data
1167  * @emsg: A pointer of const char * to store the error message
1168  * @epos: A pointer of int to store the error position
1169  *
1170  * This parses the boot config text in @data. @size must be smaller
1171  * than XBC_DATA_MAX.
1172  * Return the number of stored nodes (>0) if succeeded, or -errno
1173  * if there is any error.
1174  * In error cases, @emsg will be updated with an error message and
1175  * @epos will be updated with the error position which is the byte offset
1176  * of @buf. If the error is not a parser error, @epos will be -1.
1177  */
1178 int __init xbc_init(const char *data, size_t size, const char **emsg, int *epos)
1179 {
1180 	int ret;
1181 
1182 	if (epos)
1183 		*epos = -1;
1184 
1185 	if (xbc_data) {
1186 		if (emsg)
1187 			*emsg = "Bootconfig is already initialized";
1188 		return -EBUSY;
1189 	}
1190 	if (size > XBC_DATA_MAX || size == 0) {
1191 		if (emsg)
1192 			*emsg = size ? "Config data is too big" :
1193 				"Config data is empty";
1194 		return -ERANGE;
1195 	}
1196 
1197 	xbc_data = xbc_alloc_mem(size + 1);
1198 	if (!xbc_data) {
1199 		if (emsg)
1200 			*emsg = "Failed to allocate bootconfig data";
1201 		return -ENOMEM;
1202 	}
1203 	memcpy(xbc_data, data, size);
1204 	xbc_data[size] = '\0';
1205 	xbc_data_size = size + 1;
1206 
1207 	xbc_nodes = xbc_alloc_mem(sizeof(struct xbc_node) * XBC_NODE_MAX);
1208 	if (!xbc_nodes) {
1209 		if (emsg)
1210 			*emsg = "Failed to allocate bootconfig nodes";
1211 		xbc_exit();
1212 		return -ENOMEM;
1213 	}
1214 
1215 	ret = xbc_parse_tree();
1216 	if (!ret)
1217 		ret = xbc_verify_tree();
1218 #ifndef __KERNEL__
1219 	if (!ret)
1220 		ret = xbc_sanity_check_tree();
1221 #endif
1222 
1223 	if (ret < 0) {
1224 		if (epos)
1225 			*epos = xbc_err_pos;
1226 		if (emsg)
1227 			*emsg = xbc_err_msg;
1228 		xbc_exit();
1229 	} else {
1230 		ret = xbc_node_num;
1231 	}
1232 
1233 	return ret;
1234 }
1235