From acf7b28ec09b998c8c75ffbbfdeb565ee9156c08 Mon Sep 17 00:00:00 2001 From: Kelvin Zhang Date: Sun, 1 Nov 2026 20:50:05 -0800 Subject: [PATCH] libfdt: Don't search for the terminator in fdt_get_string() Unless FDT_ASSUME_MASK includes ASSUME_VALID_INPUT, fdt_get_string() finds the end of the string with memchr(), bounded by the end of the string block, which also checks that the string is terminated. A string block normally ends with a NUL, and then every string in it is terminated. When the caller does not ask for the string's length, check that byte instead, so that fdt_string() doesn't scan the string at all. This helps callers that look up many property names. With a 612 KiB tree on x86-64, built with gcc -O2 and the default FDT_ASSUME_MASK, calling fdt_string() for the name of each of its 17,899 properties takes 108 us instead of 160 us, not counting the walk that finds them. libufdt, which Android bootloaders use to apply overlays, calls fdt_string() at least once for every property it reads: tens of thousands of times to apply one overlay to a 445 KiB tree. Reviewed-by: David Gibson Signed-off-by: Kelvin Zhang Message-ID: Signed-off-by: David Gibson --- libfdt/fdt_ro.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/libfdt/fdt_ro.c b/libfdt/fdt_ro.c index ddfb8b9..fed2f9f 100644 --- a/libfdt/fdt_ro.c +++ b/libfdt/fdt_ro.c @@ -80,6 +80,16 @@ const char *fdt_get_string(const void *fdt, int stroffset, int *lenp) } s = (const char *)fdt + absoffset; + + /* + * If the range ends with a NUL (always the case for a string block made + * of NUL-terminated strings), the string is terminated within it, so + * there is no need to search for the terminator unless the caller + * wants the length. + */ + if (!lenp && len && s[len - 1] == '\0') + return s; + n = memchr(s, '\0', len); if (!n) { /* missing terminating NULL */