Skip to content

Commit

Permalink
Use main thread of current Lua state for callbacks, when known
Browse files Browse the repository at this point in the history
If the library is opened from a Lua thread (coroutine) that is not the main
one, the stored L would be to that thread, which may become suspended (by
calling yield). It is unsafe to call functions on suspended Lua threads, which
luv does a lot (the stored L is used for callbacks).

The main thread of a Lua state can never yield, so it is always safe to call
callbacks on.

This commit ensures the main thread is stored in the luv context instead of
the current thread, when we are able to calculate it (LUA_RIDX_MAINTHREAD was
added in Lua 5.2, and I have not found a way to determine the main thread in
Lua 5.1).

This fixes #503
  • Loading branch information
mwild1 committed Nov 14, 2024
1 parent e2d3d18 commit 1c64f6c
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/luv.c
Original file line number Diff line number Diff line change
Expand Up @@ -835,6 +835,15 @@ static int loop_gc(lua_State *L) {
}

LUALIB_API int luaopen_luv (lua_State* L) {
#ifdef LUA_RIDX_MAINTHREAD
// Lua 5.2+ - resolve the main thread of the current Lua state, even if
// we were loaded from a different thread (which may become suspended/dead).
lua_geti(L, LUA_REGISTRYINDEX, LUA_RIDX_MAINTHREAD);
lua_State* ctxL = lua_tothread(L, -1);
lua_pop(L, 1);
#else
lua_State* ctxL = L;
#endif
luv_ctx_t* ctx = luv_context(L);

luaL_newlib(L, luv_functions);
Expand Down Expand Up @@ -862,7 +871,7 @@ LUALIB_API int luaopen_luv (lua_State* L) {
lua_rawset(L, -3);

ctx->loop = loop;
ctx->L = L;
ctx->L = ctxL;
ctx->mode = -1;

ret = uv_loop_init(loop);
Expand Down

0 comments on commit 1c64f6c

Please sign in to comment.