Skip to content

Commit 0afb508

Browse files
committed
fix lua stackoverflow on temp table
Signed-off-by: Emelia Lei <wlei29@bloomberg.net>
1 parent 46dd71f commit 0afb508

1 file changed

Lines changed: 15 additions & 8 deletions

File tree

lua/sp.c

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1205,6 +1205,10 @@ static struct sp_tmptbl *create_temp_table(Lua lua, const char **name)
12051205
sql = strbuf_new();
12061206
strbuf_appendf(sql, "CREATE TEMP TABLE \"%s\" (", n2);
12071207
size_t num = lua_objlen(lua, 2);
1208+
if (num > MAXCOLUMNS) {
1209+
luabb_error(lua, sp, "too many columns (max:%d)", MAXCOLUMNS);
1210+
goto out;
1211+
}
12081212
const char *comma = "";
12091213
for (size_t i = 1; i <= num; ++i) {
12101214
lua_rawgeti(lua, 2, i);
@@ -1218,20 +1222,23 @@ static struct sp_tmptbl *create_temp_table(Lua lua, const char **name)
12181222
}
12191223
lua_rawgeti(lua, -1, 1);
12201224
lua_rawgeti(lua, -2, 2);
1221-
char *quoted_col = sqlite3_mprintf("\"%w\"", lua_tostring(lua, -2));
1222-
strbuf_appendf(sql, "%s%s %s", comma, quoted_col,
1223-
lua_tostring(lua, -1));
1225+
const char *colname = lua_tostring(lua, -2);
1226+
const char *coltype = lua_tostring(lua, -1);
1227+
if (coltype == NULL || strlen(coltype) > 64) {
1228+
luabb_error(lua, sp, "bad column type in 'table'");
1229+
goto out;
1230+
}
1231+
char *quoted_col = sqlite3_mprintf("\"%w\"", colname);
1232+
strbuf_appendf(sql, "%s%s %s", comma, quoted_col, coltype);
12241233
sqlite3_free(quoted_col);
12251234
lua_pop(lua, 3);
12261235
comma = ", ";
12271236
}
12281237
strbuf_append(sql, ")");
12291238

1230-
// Following can throw exception which may leak strbuf.
1231-
// Copy DDL string onto stack instead.
1232-
int len = strbuf_len(sql) + 1;
1233-
char *ddl = alloca(len);
1234-
memcpy(ddl, strbuf_buf(sql), len);
1239+
// Lua-managed buffer: GC reclaims it if prepare throws.
1240+
lua_pushlstring(lua, strbuf_buf(sql), strbuf_len(sql));
1241+
const char *ddl = lua_tostring(lua, -1);
12351242
strbuf_free(sql);
12361243
sql = NULL;
12371244
sqlite3_stmt *stmt;

0 commit comments

Comments
 (0)