[PATCH] kconfig: preprocess: fix UAF and SEGV on self-referencing variables
From: Ruslan Semchenko
Date: Mon Nov 02 2026 - 04:08:56 EST
In variable_add(), when updating an existing simply expanded variable (:=),
v->value was freed before calling expand_string(value). If the value
referred to the variable itself (e.g. A := $(A)b), variable_expand()
accessed the already freed memory, causing a heap-use-after-free.
Furthermore, for a new variable definition, an uninitialized variable
struct was inserted into variable_list before expanding value. If value
referred to the variable itself (e.g. B := $(B)x), variable_lookup()
found the incomplete variable and dereferenced uninitialized v->value,
causing a segmentation fault.
Fix both issues by computing the new value before modifying the existing
variable or inserting a new one into variable_list.
Signed-off-by: Ruslan Semchenko <uncleruc2075@xxxxxxxxx>
---
scripts/kconfig/preprocess.c | 23 ++++++++++++++++-------
1 file changed, 16 insertions(+), 7 deletions(-)
diff --git a/scripts/kconfig/preprocess.c b/scripts/kconfig/preprocess.c
index 783abcaa5..d48791921 100644
--- a/scripts/kconfig/preprocess.c
+++ b/scripts/kconfig/preprocess.c
@@ -293,27 +293,35 @@ void variable_add(const char *name, const char *value,
if (flavor == VAR_APPEND) {
flavor = v->flavor;
append = true;
- } else {
- free(v->value);
}
} else {
/* For undefined variables, += assumes the recursive flavor */
if (flavor == VAR_APPEND)
flavor = VAR_RECURSIVE;
+ }
+
+ /*
+ * Compute the new value before touching the variable. Expanding it may
+ * refer to the variable itself, which must still see the old value.
+ */
+ if (flavor == VAR_SIMPLE)
+ new_value = expand_string(value);
+ else
+ new_value = xstrdup(value);
+ if (!v) {
+ /* A new variable is not visible until it is fully defined. */
v = xmalloc(sizeof(*v));
v->name = xstrdup(name);
+ v->value = new_value;
+ v->flavor = flavor;
v->exp_count = 0;
list_add_tail(&v->node, &variable_list);
+ return;
}
v->flavor = flavor;
- if (flavor == VAR_SIMPLE)
- new_value = expand_string(value);
- else
- new_value = xstrdup(value);
-
if (append) {
v->value = xrealloc(v->value,
strlen(v->value) + strlen(new_value) + 2);
@@ -321,6 +329,7 @@ void variable_add(const char *name, const char *value,
strcat(v->value, new_value);
free(new_value);
} else {
+ free(v->value);
v->value = new_value;
}
}
--
2.47.3