Skip to content

Commit 54792e6

Browse files
committed
Common (Lua): detects circular reference in encode_json
1 parent b34e2a4 commit 54792e6

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

src/common/impl/lua.c

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,17 @@
55

66
struct FFLuaData luaData;
77

8-
static yyjson_mut_val* lua2yyjson(lua_State* L, int idx, yyjson_mut_doc* doc) {
8+
static yyjson_mut_val* lua2yyjson(lua_State* L, int idx, yyjson_mut_doc* doc, int depth) {
9+
if (__builtin_expect(depth > 15, false)) {
10+
yyjson_mut_doc_free(doc);
11+
lua_pushlstring(
12+
L, "yyjson: recursion depth exceeded; possible circular reference",
13+
strlen("yyjson: recursion depth exceeded; possible circular reference")
14+
);
15+
lua_error(L); // noreturn
16+
__builtin_unreachable();
17+
}
18+
919
if (idx < 0) {
1020
idx = lua_gettop(L) + idx + 1;
1121
}
@@ -66,7 +76,7 @@ static yyjson_mut_val* lua2yyjson(lua_State* L, int idx, yyjson_mut_doc* doc) {
6676
yyjson_mut_val* arr = yyjson_mut_arr(doc);
6777
for (lua_Unsigned i = 1; i <= len; i++) {
6878
lua_rawgeti(L, idx, (lua_Integer) i);
69-
yyjson_mut_val* val = lua2yyjson(L, -1, doc);
79+
yyjson_mut_val* val = lua2yyjson(L, -1, doc, depth + 1);
7080
yyjson_mut_arr_append(arr, val);
7181
lua_pop(L, 1);
7282
}
@@ -80,7 +90,7 @@ static yyjson_mut_val* lua2yyjson(lua_State* L, int idx, yyjson_mut_doc* doc) {
8090
yyjson_mut_val* key = yyjson_mut_strncpy(doc, key_str, klen);
8191
lua_pop(L, 1);
8292

83-
yyjson_mut_val* val = lua2yyjson(L, -1, doc);
93+
yyjson_mut_val* val = lua2yyjson(L, -1, doc, depth + 1);
8494
yyjson_mut_obj_add(obj, key, val);
8595
lua_pop(L, 1);
8696
}
@@ -107,7 +117,7 @@ static int yyjsonEncode(lua_State* L) {
107117
return lua_error(L);
108118
}
109119

110-
yyjson_mut_val* root = lua2yyjson(L, 1, doc);
120+
yyjson_mut_val* root = lua2yyjson(L, 1, doc, 0);
111121
yyjson_mut_doc_set_root(doc, root);
112122

113123
size_t jsonLen;

0 commit comments

Comments
 (0)