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

Binding JavaScript functions to WebViews frequently causes a VM Panic when the callback is triggered #154

Open
rdw-software opened this issue May 6, 2023 · 1 comment

Comments

@rdw-software
Copy link
Member

rdw-software commented May 6, 2023

AFAIK binding JS callbacks to the FFI usually fails with a VM panic, so that also has to be abstracted (and probably moved to C++).

Binding callbacks "sometimes" work, but generally it doesn't. I suspect the browser calling back to JIT-optimized code may be problematic, but I haven't spent much time debugging the issue. It could also just be a general incompatibility.

C_WebView.CreateWithoutDevTools()

local function myCallbackFunction(_, value)
	print("Callback called from JavaScript with value:", ffi.string(value))
end

C_WebView.BindCallbackFunction("myCallback", myCallbackFunction)

local onloadScript = [[
  document.addEventListener('DOMContentLoaded', function() {
    if (window.myCallback) {
      window.myCallback('Hello from JavaScript');
    }
  });
]]

C_WebView.SetOnLoadScript(onloadScript)
@rdw-software
Copy link
Member Author

I haven't worked with webviews in ages, but this is an excerpt from the LuaJIT docs:

One thing that's not allowed, is to let an FFI call into a C function get JIT-compiled, which in turn calls a callback, calling into Lua again. Usually this attempt is caught by the interpreter first and the C function is blacklisted for compilation.
However, this heuristic may fail under specific circumstances: e.g. a message polling function might not run Lua callbacks right away and the call gets JIT-compiled. If it later happens to call back into Lua (e.g. a rarely invoked error callback), you'll get a VM PANIC with the message "bad callback". Then you'll need to manually turn off JIT-compilation with jit.off() for the surrounding Lua function that invokes such a message polling function (or similar).

Source: http://luajit.org/ext_ffi_semantics.html#callback

So yeah, should be able to work around this via jit.off (on the surrounding function).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Soon™
Development

No branches or pull requests

1 participant