From 9253a8cc549e862a9f997b18f060a9ecb1335b03 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustaf=20Alh=C3=A4ll?= Date: Fri, 2 Jun 2023 18:49:37 +0200 Subject: [PATCH] Fix use-after-free when calling v.drawString in Lua --- src/lua_hudlib_drawlist.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/lua_hudlib_drawlist.c b/src/lua_hudlib_drawlist.c index 6f83094ac..c518ba525 100644 --- a/src/lua_hudlib_drawlist.c +++ b/src/lua_hudlib_drawlist.c @@ -177,9 +177,18 @@ static const char *CopyString(huddrawlist_h list, const char* str) lenstr = strlen(str); if (list->strbuf_capacity <= list->strbuf_len + lenstr + 1) { + const char *old_offset = list->strbuf; + size_t i; if (list->strbuf_capacity == 0) list->strbuf_capacity = 256; else list->strbuf_capacity *= 2; list->strbuf = (char*) Z_Realloc(list->strbuf, sizeof(char) * list->strbuf_capacity, PU_STATIC, NULL); + + // align the string pointers to make sure old pointers don't point towards invalid addresses + // this is necessary since Z_ReallocAlign might actually move the string buffer in memory + for (i = 0; i < list->items_len; i++) + { + list->items[i].str += list->strbuf - old_offset; + } } const char *result = (const char *) &list->strbuf[list->strbuf_len]; strncpy(&list->strbuf[list->strbuf_len], str, lenstr + 1);