[PATCH v2 04/10] lib/ucs2_string: Split out ucs2_as_utf8_l() taking a separate limit

From: Ard Biesheuvel

Date: Wed Sep 09 2026 - 08:16:02 EST


From: Ard Biesheuvel <ardb@xxxxxxxxxx>

ucs2_as_utf() takes a maxlength argument, which specifies how many bytes
the function is permitted to store into the destination buffer.

The same value is used as an upper bound for the ucs2_strnlen()
invocation, which is reasonable in the general case, as each UCS-2
character produces at least one byte of UTF-8 output, and so there is
never a need to process more than 'maxlength' UCS-2 characters.

However, if the UCS-2 string is not NUL terminated, ucs2_strnlen() may
read past the end of the buffer if 'maxlength' is set to a high value.

Current callers pass UCS-2 strings that are expected to be NUL
terminated, but for processing the load options in the EFI stub, a
version is needed that takes a separate limit argument. So split that
off from the current implementation.

Signed-off-by: Ard Biesheuvel <ardb@xxxxxxxxxx>
---
include/linux/ucs2_string.h | 11 ++++++++++-
lib/ucs2_string.c | 6 +++---
2 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/include/linux/ucs2_string.h b/include/linux/ucs2_string.h
index c499ae809c7d..74f23ca5a967 100644
--- a/include/linux/ucs2_string.h
+++ b/include/linux/ucs2_string.h
@@ -14,7 +14,16 @@ ssize_t ucs2_strscpy(ucs2_char_t *dst, const ucs2_char_t *src, size_t count);
int ucs2_strncmp(const ucs2_char_t *a, const ucs2_char_t *b, size_t len);

unsigned long ucs2_utf8size(const ucs2_char_t *src);
+unsigned long
+ucs2_as_utf8_l(u8 *dest, const ucs2_char_t *src, unsigned long limit,
+ unsigned long maxlength);
+
+static inline
unsigned long ucs2_as_utf8(u8 *dest, const ucs2_char_t *src,
- unsigned long maxlength);
+ unsigned long maxlength)
+{
+ return ucs2_as_utf8_l(dest, src, ucs2_strnlen(src, maxlength),
+ maxlength);
+}

#endif /* _LINUX_UCS2_STRING_H_ */
diff --git a/lib/ucs2_string.c b/lib/ucs2_string.c
index f75fb4f7961a..2df9bef79eea 100644
--- a/lib/ucs2_string.c
+++ b/lib/ucs2_string.c
@@ -132,11 +132,11 @@ EXPORT_SYMBOL(ucs2_utf8size);
* final NUL character.
*/
unsigned long
-ucs2_as_utf8(u8 *dest, const ucs2_char_t *src, unsigned long maxlength)
+ucs2_as_utf8_l(u8 *dest, const ucs2_char_t *src, unsigned long limit,
+ unsigned long maxlength)
{
unsigned int i;
unsigned long j = 0;
- unsigned long limit = ucs2_strnlen(src, maxlength);

for (i = 0; maxlength && i < limit; i++) {
u16 c = src[i];
@@ -163,7 +163,7 @@ ucs2_as_utf8(u8 *dest, const ucs2_char_t *src, unsigned long maxlength)
dest[j] = '\0';
return j;
}
-EXPORT_SYMBOL(ucs2_as_utf8);
+EXPORT_SYMBOL(ucs2_as_utf8_l);

#ifndef __DISABLE_EXPORTS
MODULE_DESCRIPTION("UCS2 string handling");
--
2.55.0.1003.g10538fe699-goog