Skip to content

Commit e42b8de

Browse files
alerquesrl295
andauthored
fix(languages): Account for possible null termination in UTF-16 → 8 conversion (#2243)
Co-authored-by: Steven R. Loomis <srl295@gmail.com>
1 parent 7d770e7 commit e42b8de

1 file changed

Lines changed: 10 additions & 8 deletions

File tree

justenough/justenoughicu.c

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -249,19 +249,21 @@ int je_icu_bidi_runs(lua_State *L) {
249249
UBiDiDirection dir = ubidi_getVisualRun(bidi, i, &start, &length);
250250
lua_newtable(L);
251251
// Convert back to UTF8...
252-
int32_t l3 = 0;
253-
char* possibleOutbuf = malloc(4*length);
254-
if(!possibleOutbuf) {
252+
// Each UTF-16 code unit can expand to at most 4 UTF-8 bytes
253+
const int buflen = (length * 4) + 1;
254+
char* utf8buf = malloc(buflen);
255+
if(!utf8buf) {
255256
return luaL_error(L, "Couldn't malloc");
256257
}
257-
u_strToUTF8(possibleOutbuf, 4 * length, &l3, input_as_uchar+start, length, &err);
258+
int32_t utf8len;
259+
u_strToUTF8(utf8buf, buflen, &utf8len, input_as_uchar+start, length, &err);
258260
if (!U_SUCCESS(err)) {
259-
free(possibleOutbuf);
260-
return luaL_error(L, "Bidi run too big? %s", u_errorName(err));
261+
free(utf8buf);
262+
return luaL_error(L, "UTF-8 conversion failed: %s", u_errorName(err));
261263
}
262264
lua_pushstring(L, "run");
263-
lua_pushstring(L, possibleOutbuf);
264-
free(possibleOutbuf);
265+
lua_pushstring(L, utf8buf);
266+
free(utf8buf);
265267
lua_settable(L, -3);
266268

267269
lua_pushstring(L, "start");

0 commit comments

Comments
 (0)