Skip to content

Commit 79739a6

Browse files
committed
Scope table collection and GC controls to each Lua state
1 parent 0be0225 commit 79739a6

5 files changed

Lines changed: 168 additions & 50 deletions

File tree

‎src/stdlib/lbaselib.js‎

Lines changed: 8 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -204,17 +204,9 @@ const luaB_rawset = function(L) {
204204
return 1;
205205
};
206206

207-
let gcRunning = true;
208-
209207
const hostGc = (typeof globalThis !== "undefined" && typeof globalThis.gc === "function")
210208
? globalThis.gc.bind(globalThis)
211209
: null;
212-
const hostMemoryInKb = function() {
213-
if (hostGc && typeof process !== "undefined" && process.memoryUsage) {
214-
return process.memoryUsage().heapUsed / 1024;
215-
}
216-
return 0;
217-
};
218210

219211
const opts = [
220212
"stop", "restart", "collect",
@@ -223,21 +215,14 @@ const opts = [
223215
].map((e) => to_luastring(e));
224216
const luaB_collectgarbage = function(L) {
225217
let o = luaL_checkoption(L, 1, "collect", opts);
226-
/* LuaNode-VM delegates object reclamation to the host JavaScript
227-
garbage collector (V8/SpiderMonkey/etc.), so there is no separate
228-
Lua-level collector to drive. We therefore implement every option
229-
as a benign no-op that returns the values mandated by the Lua 5.3
230-
reference manual, instead of raising "lua_gc not implemented" —
231-
which broke any script that called collectgarbage() (a very common
232-
idiom, e.g. between benchmark phases or in test suites). */
218+
/* LuaNode maintains a per-state Lua-level pass for weak references and
219+
table finalizers. The host collector remains optional and process-wide. */
233220
switch (o) {
234221
case 0: /* "stop" */
235-
gcRunning = false;
236-
ltable.luaH_setrunning(false);
222+
ltable.luaH_setrunning(L, false);
237223
return 0;
238224
case 1: /* "restart" */
239-
gcRunning = true;
240-
ltable.luaH_setrunning(true);
225+
ltable.luaH_setrunning(L, true);
241226
return 0;
242227
case 2: /* "collect" */
243228
const gcError = ltable.luaH_collectgarbage(L);
@@ -252,14 +237,14 @@ const luaB_collectgarbage = function(L) {
252237
lua_pushinteger(L, 0);
253238
return 1;
254239
case 3: /* "count" */
255-
lua_pushnumber(L, hostGc ? ltable.luaH_memory() : 0);
240+
lua_pushnumber(L, ltable.luaH_memory(L));
256241
return 1; /* simulated Lua heap size in KB */
257242
case 4: /* "countb" */
258-
lua_pushinteger(L, hostGc ? 0 : 0);
243+
lua_pushinteger(L, 0);
259244
return 1; /* remainder bytes */
260245
case 5: /* "step" */
261246
const stepSize = luaL_optinteger(L, 2, 0);
262-
if (!gcRunning && stepSize > 0) {
247+
if (!ltable.luaH_isrunning(L) && stepSize > 0) {
263248
const stoppedStepError = ltable.luaH_collectgarbage(L);
264249
if (stoppedStepError) {
265250
if (stoppedStepError.ttisstring())
@@ -278,7 +263,7 @@ const luaB_collectgarbage = function(L) {
278263
lua_pushinteger(L, 0);
279264
return 1;
280265
case 8: /* "isrunning" */
281-
lua_pushboolean(L, gcRunning);
266+
lua_pushboolean(L, ltable.luaH_isrunning(L));
282267
return 1;
283268
default:
284269
return 0;

‎src/vm/lstate.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,15 @@ class global_State {
8989
this.version = null;
9090
this.tmname = new Array(ltm.TMS.TM_N);
9191
this.mt = new Array(LUA_NUMTAGS);
92+
this.gc = {
93+
tables: new Set(),
94+
allocationsSinceCollection: 0,
95+
instructionsSinceCollection: 0,
96+
simulatedMemoryKb: 1,
97+
running: true,
98+
collecting: false,
99+
closed: false
100+
};
92101
}
93102

94103
}
@@ -180,7 +189,11 @@ const lua_newstate = function() {
180189
};
181190

182191
const close_state = function(L) {
192+
ltable.luaH_close(L);
193+
L.l_G.l_registry = new lobject.TValue(LUA_TNIL, null);
194+
L.l_G.mt.fill(null);
183195
freestack(L);
196+
L.l_G.mainthread = null;
184197
};
185198

186199
const lua_close = function(L) {

‎src/vm/ltable.js‎

Lines changed: 71 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,6 @@ const {
2323
} = require('../luaconf.js');
2424
const { lua_assert } = require('./llimits.js');
2525
const I64 = require('./lint64.js');
26-
const allTables = new Set();
27-
let allocationsSinceCollection = 0;
28-
let instructionsSinceCollection = 0;
29-
let simulatedMemoryKb = 1;
30-
let gcRunning = true;
31-
let collecting = false;
3226
const ldebug = require('./ldebug.js');
3327
const lobject = require('./lobject.js');
3428
const {
@@ -130,7 +124,7 @@ class Table {
130124
this.finalized = false;
131125
this.finalizerPending = false;
132126
this.flags = ~0;
133-
allTables.add(this);
127+
L.l_G.gc.tables.add(this);
134128
}
135129
}
136130

@@ -410,24 +404,31 @@ const needsDeferredFinalization = function(table) {
410404
return false;
411405
};
412406

413-
const luaH_setrunning = function(running) {
414-
gcRunning = !!running;
407+
const luaH_setrunning = function(L, running) {
408+
L.l_G.gc.running = !!running;
415409
};
416410

417-
const luaH_memory = function() {
418-
return simulatedMemoryKb;
411+
const luaH_isrunning = function(L) {
412+
return L.l_G.gc.running;
413+
};
414+
415+
const luaH_memory = function(L) {
416+
return L.l_G.gc.simulatedMemoryKb;
419417
};
420418

421419
const luaH_maybe_gc = function(L) {
422-
if (collecting || !gcRunning) return;
423-
instructionsSinceCollection++;
424-
if (instructionsSinceCollection >= 10000)
420+
const gc = L.l_G.gc;
421+
if (gc.collecting || !gc.running || gc.closed) return;
422+
gc.instructionsSinceCollection++;
423+
if (gc.instructionsSinceCollection >= 10000)
425424
luaH_collectgarbage(L);
426425
};
427426

428427
const luaH_collectgarbage = function(L) {
429-
if (collecting) return;
430-
collecting = true;
428+
const gc = L.l_G.gc;
429+
const allTables = gc.tables;
430+
if (gc.collecting || gc.closed) return;
431+
gc.collecting = true;
431432
const marked = new Set();
432433
const visitedTables = new Set();
433434
let firstFinalizerError = null;
@@ -637,18 +638,61 @@ const luaH_collectgarbage = function(L) {
637638
if (!marked.has(table) && !table.finalizerPending)
638639
allTables.delete(table);
639640
}
640-
simulatedMemoryKb = Math.max(1, visitedTables.size);
641+
gc.simulatedMemoryKb = Math.max(1, visitedTables.size);
641642
return firstFinalizerError;
642643
} finally {
643-
allocationsSinceCollection = 0;
644-
instructionsSinceCollection = 0;
645-
collecting = false;
644+
gc.allocationsSinceCollection = 0;
645+
gc.instructionsSinceCollection = 0;
646+
gc.collecting = false;
646647
if (typeof console !== "undefined" &&
647648
typeof process !== "undefined" && process.env.LUANODE_GC_DEBUG)
648649
console.error("GC_END", allTables.size, visitedTables.size);
649650
}
650651
};
651652

653+
/*
654+
** Release the VM-owned table graph when its main state closes. Lua finalizers
655+
** still run while the stack and registry are available; afterward all roots
656+
** and collector bookkeeping are detached from the state.
657+
*/
658+
const luaH_close = function(L) {
659+
const gc = L.l_G.gc;
660+
if (gc.closed) return;
661+
gc.collecting = true;
662+
const lapi = require('./lapi.js');
663+
const gcName = luaS_bless(L, to_luastring("__gc", true));
664+
665+
try {
666+
const finalizableTables = Array.from(gc.tables).reverse();
667+
for (const table of finalizableTables) {
668+
if (table.finalized || !table.metatable) continue;
669+
const finalizer = luaH_getstr(table.metatable, gcName);
670+
if (!finalizer.ttisfunction()) continue;
671+
672+
table.finalized = true;
673+
table.finalizerPending = false;
674+
const base = L.top;
675+
lobject.pushobj2s(L, finalizer);
676+
lobject.pushobj2s(L, new lobject.TValue(LUA_TTABLE, table));
677+
try {
678+
lapi.lua_pcall(L, 1, 0, 0);
679+
} catch (error) {
680+
L.status = 0;
681+
} finally {
682+
L.top = base;
683+
}
684+
}
685+
} finally {
686+
gc.tables.clear();
687+
gc.allocationsSinceCollection = 0;
688+
gc.instructionsSinceCollection = 0;
689+
gc.simulatedMemoryKb = 1;
690+
gc.running = false;
691+
gc.collecting = false;
692+
gc.closed = true;
693+
}
694+
};
695+
652696
/*
653697
** Try to find a boundary in table 't'. A 'boundary' is an integer index
654698
** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
@@ -721,17 +765,21 @@ module.exports.luaH_getint = luaH_getint;
721765
module.exports.luaH_getn = luaH_getn;
722766
module.exports.luaH_getstr = luaH_getstr;
723767
module.exports.luaH_collectgarbage = luaH_collectgarbage;
768+
module.exports.luaH_close = luaH_close;
724769
module.exports.luaH_maybe_gc = luaH_maybe_gc;
725770
module.exports.luaH_setrunning = luaH_setrunning;
771+
module.exports.luaH_isrunning = luaH_isrunning;
726772
module.exports.luaH_memory = luaH_memory;
727773
module.exports.luaH_setfrom = luaH_setfrom;
728774
module.exports.luaH_setint = luaH_setint;
729775
module.exports.luaH_setmeta = luaH_setmode;
730776
module.exports.luaH_new = function(L) {
777+
const gc = L.l_G.gc;
778+
if (gc.closed) throw new Error("cannot allocate a Lua table after lua_close");
731779
const table = new Table(L);
732-
simulatedMemoryKb++;
733-
allocationsSinceCollection++;
734-
if (!collecting && gcRunning && allocationsSinceCollection >= 100) {
780+
gc.simulatedMemoryKb++;
781+
gc.allocationsSinceCollection++;
782+
if (!gc.collecting && gc.running && gc.allocationsSinceCollection >= 100) {
735783
try {
736784
luaH_collectgarbage(L);
737785
} catch (e) {

‎tests/gc-state.test.js‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"use strict";
2+
3+
const F = require("../src/fengari.js");
4+
5+
const newOpenState = () => {
6+
const L = F.lauxlib.luaL_newstate();
7+
F.lualib.luaL_openlibs(L);
8+
return L;
9+
};
10+
11+
const run = (L, source, nresults = 0) => {
12+
const loadStatus = F.lauxlib.luaL_loadstring(L, F.to_luastring(source));
13+
if (loadStatus !== F.lua.LUA_OK)
14+
throw new Error(F.to_jsstring(F.lua.lua_tostring(L, -1)));
15+
const callStatus = F.lua.lua_pcall(L, 0, nresults, 0);
16+
if (callStatus !== F.lua.LUA_OK)
17+
throw new Error(F.to_jsstring(F.lua.lua_tostring(L, -1)));
18+
const result = nresults ? F.to_jsstring(F.lua.lua_tostring(L, -1)) : undefined;
19+
F.lua.lua_settop(L, 0);
20+
return result;
21+
};
22+
23+
describe("per-state table collector", () => {
24+
test("collecting one state preserves weak tables owned by another", () => {
25+
const first = newOpenState();
26+
const second = newOpenState();
27+
try {
28+
run(second,
29+
"local weak = setmetatable({}, {__mode='k'}); " +
30+
"local key = {}; weak[key] = 7; _G.weak, _G.key = weak, key");
31+
run(first, "collectgarbage('collect')");
32+
expect(run(second, "return weak[key]", 1)).toBe("7");
33+
} finally {
34+
F.lua.lua_close(first);
35+
F.lua.lua_close(second);
36+
}
37+
});
38+
39+
test("stop and restart affect only the selected state", () => {
40+
const first = newOpenState();
41+
const second = newOpenState();
42+
try {
43+
run(first, "collectgarbage('stop')");
44+
expect(run(first, "return tostring(collectgarbage('isrunning'))", 1)).toBe("false");
45+
expect(run(second, "return tostring(collectgarbage('isrunning'))", 1)).toBe("true");
46+
run(first, "collectgarbage('restart')");
47+
expect(run(first, "return tostring(collectgarbage('isrunning'))", 1)).toBe("true");
48+
} finally {
49+
F.lua.lua_close(first);
50+
F.lua.lua_close(second);
51+
}
52+
});
53+
54+
test("closing a state runs table finalizers and releases its registry", () => {
55+
const L = newOpenState();
56+
const gc = L.l_G.gc;
57+
const finalized = { count: 0 };
58+
F.lua.lua_pushcfunction(L, () => {
59+
finalized.count++;
60+
return 0;
61+
});
62+
F.lua.lua_setglobal(L, F.to_luastring("mark_finalized"));
63+
run(L, "do local object = setmetatable({}, {__gc=function() mark_finalized() end}) end");
64+
expect(gc.tables.size).toBeGreaterThan(0);
65+
66+
F.lua.lua_close(L);
67+
68+
expect(finalized.count).toBe(1);
69+
expect(gc.closed).toBe(true);
70+
expect(gc.tables.size).toBe(0);
71+
expect(L.l_G.l_registry.ttisnil()).toBe(true);
72+
expect(L.stack).toBeNull();
73+
});
74+
});

‎tests/lexer-buffer.test.js‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ describe("Lexer token-buffer growth (the 32-byte crash bug)", () => {
112112
});
113113
});
114114

115-
describe("collectgarbage (was: lua_gc not implemented)", () => {
115+
describe("collectgarbage", () => {
116116
test("collectgarbage('collect') returns 0 and does not raise", () => {
117117
const r = runLua(`return collectgarbage("collect")`);
118118
expect(r.ok).toBe(true);
@@ -122,9 +122,7 @@ describe("collectgarbage (was: lua_gc not implemented)", () => {
122122
test("collectgarbage('count') returns a number", () => {
123123
const r = runLua(`return collectgarbage("count")`);
124124
expect(r.ok).toBe(true);
125-
/* count returns KB as a float; stringifyValue uses tolstring which
126-
renders 0 as "0.0". Accept either form. */
127-
expect(["0", "0.0"]).toContain(r.value);
125+
expect(Number(r.value)).toBeGreaterThan(0);
128126
});
129127

130128
test("collectgarbage('isrunning') returns true", () => {

0 commit comments

Comments
 (0)