Skip to content

Commit

Permalink
fix(lua) avoid LuaJIT issue with FFI callback roundtrips
Browse files Browse the repository at this point in the history
The Kong Gateway CI started seeing intermittent crashes with "bad callback" errors:

See:
https://luajit.freelists.narkive.com/sdhSLJSr/how-to-make-bad-callback-more-deterministic
```
The bad callback error happens because some JIT-compiled Lua code calls a C
function which in turn calls an FFI callback.
```

https://lua-l.lua.narkive.com/qXJrNlpP/luajit-ffi-windows-bad-callback-error-in-msgwaitformultipleobjects-proof-of-concept
From Mike Pall:
```
The problem is that a FFI callback cannot safely be called from a
C function which is itself called via the FFI from JIT-compiled
code. In your case this is the call to MsgWaitForMultipleObjects.

I've put in a lot of heuristics to detect this, and it usually
succeeds in disabling compilation for such a function. However in
your case the loop is compiled before the callback is ever called,
so the detection fails.

The straighforward solution is to put the message loop into an
extra Lua function and use jit.off(func)
```

See
  • Loading branch information
hishamhm committed Oct 26, 2023
1 parent 26e91bd commit 669084d
Showing 1 changed file with 4 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/resty/wasmx/proxy_wasm.lua
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,9 @@ do
lval = ffi_str(cvalue.data, cvalue.len)
end

jit.off()
local pok, ok, lvalue, is_const = pcall(lua_prop_setter, lkey, lval)
jit.on()
if not pok then
ngx.log(ngx.ERR, "error setting property from Lua: ", ok)
return FFI_ERROR
Expand All @@ -133,7 +135,9 @@ do
cvalue)
local lkey = ffi_str(ckey.data, ckey.len)

jit.off()
local pok, ok, lvalue, is_const = pcall(lua_prop_getter, lkey)
jit.on()
if not pok then
ngx.log(ngx.ERR, "error getting property from Lua: ", ok)
return FFI_ERROR
Expand Down

0 comments on commit 669084d

Please sign in to comment.