lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


I'm switching my current Qt Lua bindings to LuaJIT's FFI and am amazed at
how well it works. I can throw out loads of C++ binding code and replace
them with small and elegant Lua chunks.

However I just run into a nasty bug in error reporting that makes me a bit
worried because I can't quite oversee the scope of the problem.

To reproduce the bug first you need a piece of C code to export a simple
function to Lua (I'm giving a Windows example since that is my development
plartform):

	typedef struct { int x; int y; } point;

	__declspec(dllexport) point add(point* p1, point* p2) {
		point res;
		res.x = p1->x + p2->x;
		res.y = p1->y + p2->y;
		return res;
	}

Assuming the above code has been compiled in a dll called "lib.dll" you can
write the following Lua chunk:

	local ffi = require('ffi')
	ffi.cdef [[
		typedef struct { int x; int y; } point;
		point add(point* op1, point* op2); 
	]]

	local lib = ffi.load("lib")
	local point = ffi.metatype("point", { __add = lib.add })

	local p = point{ 3, 4 }
	local r = p + p
	print(r.x) 				--> 6
	r = p + 5				--> crash

If you run the above example in the LuaJIT2(beta9) shell (luajit.exe) it
prints out 6 as expected and then crashes with access violation.

It seems to be related to the fact that the error occurred inside an __add
metamethod. If you call the function directly:

	lib.add(p, 5)

you get the error message "test.lua:14: bad argument #2 to 'add' (cannot
convert 'number' to 'struct 95 *')" as expected and no crash.

Looking into the problem I traced it inside the function "debug_framepc" (in
file lj_debug.c) when it was being called from the debug.traceback from
luajit.exe. It looked like the instruction pointer (PC) in the Lua stack
frame was corrupted. 
This could be potentially serious, but in any case it prevents good error
reporting to my users, and I certainly need those metamethods in order to
make my bindings work.

Mike, could you please look into the problem? I would be happy to fix it
myself, but it goes way to deep in the JuaJIT VM for me to follow.

Janis

P.S. Can you explain what the letters PC stand for?