Skip to contentSkip to conversation

utf8: fixed bit shift larger than type size

PATCH Superseded James Prestwood 1 participant 1 message Feb 23, 2022

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

James Prestwood

author
#0 lore raw

PATCH 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.

---
 ell/utf8.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
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