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 <david@gibson.dropbear.id.au>
Signed-off-by: Kelvin Zhang <zhangkelvin@google.com>
Message-ID: <CAOSmRzixCf479QyhmGuwBBZrRLTYqoaSUw88HKZnkPyEh6=gcw@mail.gmail.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
main
Kelvin Zhang 2026-11-01 20:50:05 -08:00 committed by David Gibson
parent 4e9e220985
commit acf7b28ec0
1 changed files with 10 additions and 0 deletions

View File

@ -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 */