Skip to content

Commit

Permalink
CRE: avoid assert failure in sub-processes (#1766)
Browse files Browse the repository at this point in the history
Will allow frontend to disable CRE finalizers when
running code in a subprocess and explicitely exiting
quickly without any proper cleanup.
  • Loading branch information
poire-z committed Apr 10, 2024
1 parent 4991486 commit 781db25
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
10 changes: 10 additions & 0 deletions cre.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4108,6 +4108,13 @@ static int freeImage(lua_State *L) {
return 0;
}

static bool skip_teardown = false;

static int setSkipTearDown(lua_State *L) {
skip_teardown = lua_toboolean(L, 1);
return 0;
}

static const struct luaL_Reg cre_func[] = {
{"initCache", initCache},
{"initHyphDict", initHyphDict},
Expand All @@ -4133,6 +4140,7 @@ static const struct luaL_Reg cre_func[] = {
{"renderImageData", renderImageData},
{"smoothScaleBlitBuffer", smoothScaleBlitBuffer},
{"setImageReplacementChar", setImageReplacementChar},
{"setSkipTearDown", setSkipTearDown},
{NULL, NULL}
};

Expand Down Expand Up @@ -4302,6 +4310,8 @@ int luaopen_cre(lua_State *L) {

// Library finalizer (c.f., dlopen(3)). This serves no real purpose except making Valgrind's output slightly more useful.
__attribute__((destructor)) static void cre_teardown(void) {
if (skip_teardown)
return;
if (cre_callback_forwarder) {
delete cre_callback_forwarder;
cre_callback_forwarder = NULL;
Expand Down
13 changes: 13 additions & 0 deletions ffi/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,16 @@ function util.execute(...)
end
end

-- Frontend can register functions to be run in all subprocesses
-- just after the fork, ie. for some cleanup work.
local _run_in_subprocess_after_fork_funcs = {}
function util.addRunInSubProcessAfterForkFunc(id, func)
_run_in_subprocess_after_fork_funcs[id] = func
end
function util.removeRunInSubProcessAfterForkFunc(id)
_run_in_subprocess_after_fork_funcs[id] = nil
end

--- Run lua code (func) in a forked subprocess
--
-- With with_pipe=true, sets up a pipe for communication
Expand Down Expand Up @@ -329,6 +339,9 @@ function util.runInSubProcess(func, with_pipe, double_fork)
end
local pid = C.fork()
if pid == 0 then -- child process
for _, f in pairs(_run_in_subprocess_after_fork_funcs) do
f()
end
if double_fork then
pid = C.fork()
if pid ~= 0 then
Expand Down

0 comments on commit 781db25

Please sign in to comment.