Skip to contentSkip to conversation

utf8: fixed bit shift larger than type size

PATCH Applied James Prestwood 2 participants 2 messages Feb 23, 2022 – Feb 24, 2022

lore
Share & tools
lore

James Prestwood

author
#0 lore raw

PATCH v2 1/1 utf8: fixed bit shift larger than type size

The C standard requires the bit shift result value width to be greater than or equal to the number of bits being shifted, otherwise the behavior is undefined. In this case str[0] was being cast to an unsigned char (1 byte) but being shifted 24 bits. This resulted, on some compilers, with a runtime error:

runtime error: left shift of 255 by 24 places cannot be represented in type 'int'

Casting str[0] to an unsigned int satisfies the width requirements for this bit shift.

Fixes 9843abcd84bc ("utf8: cast to avoid left shift of negative value (ubsan)")
---
 ell/utf8.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

v2:
* Added Fixes tag

ell/utf8.c +1 -1
index 84ab774..ceda1de 100644
@@ -98,7 +98,7 @@ LIB_EXPORT int l_utf8_get_codepoint(const char *str, size_t len, wchar_t *cp)
 		return 1;
 	}
 
-	expect_bytes = __builtin_clz(~((unsigned char)str[0] << 24));
+	expect_bytes = __builtin_clz(~((unsigned int)str[0] << 24));
 
 	if (expect_bytes < 2 || expect_bytes > 4)
 		goto error;
Signature · 1 line
2.34.1
Applied
#1 lore raw

Hi James,

Quoted 11 lines · James Prestwood

The C standard requires the bit shift result value width to be greater than or equal to the number of bits being shifted, otherwise the behavior is undefined. In this case str[0] was being cast to an unsigned char (1 byte) but being shifted 24 bits. This resulted, on some compilers, with a runtime error:

runtime error: left shift of 255 by 24 places cannot be represented in type 'int'

Casting str[0] to an unsigned int satisfies the width requirements for this bit shift.

Quoted 8 lines
Fixes 9843abcd84bc ("utf8: cast to avoid left shift of negative value (ubsan)")
---
  ell/utf8.c | 2 +-
  1 file changed, 1 insertion(+), 1 deletion(-)

v2:
* Added Fixes tag

Applied, thanks.

Regards,
-Denis