Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use main thread of current Lua state for callbacks, when known #734

Merged
merged 1 commit into from
Nov 15, 2024

Conversation

mwild1
Copy link
Contributor

@mwild1 mwild1 commented Nov 14, 2024

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

@Bilal2453
Copy link
Contributor

So currently this does not work for PUC Lua 5.1 and for LuaJIT?

@mwild1
Copy link
Contributor Author

mwild1 commented Nov 14, 2024

The behaviour will not change for Lua 5.1.

I haven't tested with LuaJIT. If it implements LUA_RIDX_MAINTHREAD then it should work, otherwise the behaviour will remain unchanged with this PR.

@zhaozg
Copy link
Member

zhaozg commented Nov 15, 2024

Please add a test for this

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 luvit#503
@mwild1
Copy link
Contributor Author

mwild1 commented Nov 15, 2024

I have added a test. It will definitely fail on Lua 5.1, and probably LuaJIT, so it is skipped there (test always passes, comment is printed).

@zhaozg zhaozg merged commit 1532f44 into luvit:master Nov 15, 2024
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Incorrect references/usage of L causing invalid memory access
3 participants