C++ and Lua - Unprotected Error (bad callback)? How is this possible - c++

I'm working with LuaJIT's FFI and I'm getting very strange results. This returns a PANIC: Unprotected Error (bad callback):
function idle(ms)
myDLL.myDLL_idle(session, ms)
end
But this simple print has fixed the problem.
function idle(ms)
print("anything")
myDLL.myDLL_idle(session, ms)
end
Another extremely odd solution is to use myDLL.myDLL_idle() inside the main function. How can this even be possible? It's not like I can just do any arbitrary function either if I put the call in a function, the only ones guaranteed to work are a print and sleep.
function idle(ms)
myDLL.myDLL_idle(session, ms)
end
myDLL.myDLL_idle(session, ms) -- works
idle(ms) -- doesn't work (unless first line of idle() is a print statement)
It's doing the same thing but just in another function. And the print fixing it if I try putting it in a function method just add to the complete weirdness of this. This is a huge problem.

According to the documentation, LuaJIT doesn't allow an FFI-call to be JIT-compiled if the FFI-code calls a C function that calls back into Lua via a stored callback. In most cases LuaJIT will detect those calls and avoid compilation, but if it doesn't, it aborts with the "bad callback" error message. The extra print helped, because it prevented JIT-compilation (print is not compiled atm.).
The proposed solution (instead of calling print) is to explicitly stop the FFI-call from being JIT-compiled using the jit.off function.

Related

Dummy call makes a difference in Fortran program?

I'm working on a Fortran program and running into a strange bug with some Heisenbug-type characteristics, and looking for some insight into what might be going on. The code is too large to post in full but I hopefully I can the general idea.
What's basically going on is I have a subroutine that reads a list of numerical parameters from a text file,
call read_parameters(filename, parameter_array)
and then this list of parameters is sent into another subroutine that runs a program using those parameter values.
call run_program(parameter_array)
These calls are part of a loop that calls run_program with slightly different parameters each time through the loop---the intention is to find better parameter sets.
I've found that on the first pass through this loop, run_program gives bizarre results, which seems to indicate that something is going wrong with the first call to read_parameters. But all the subsequent passes behave normally and I haven't been able to understand what's going wrong with that first pass despite a lot of investigating, including for example printing the values of the parameters themselves within the actual run_program code.
While testing, I realized that if I put another call to read_parameters right above the call to run_program, then the first pass of the program runs normally, but here's the thing: this new call to read_parameters is just a dummy call, with an output array parameter_array2 that doesn't even get used! As in,
call read_parameters(parameter_array)
call read_parameters(parameter_array2)
call run_program(parameter_array)
If the second line is present, the program runs just fine, even though parameter_array2 isn't used anywhere, while if it's absent the program gives erroneous results for the first pass through the loop.
Does anyone have any ideas about what might be going on?
Thanks.

How to interpret a GDB backtrace?

0x004069f1 in Space::setPosition (this=0x77733cee, x=-65, y=-49) at space.h:44
0x00402679 in Checkers::make_move (this=0x28cbb8, move=...) at checkers.cc:351
0x00403fd2 in main_savitch_14::game::make_computer_move (this=0x28cbb8) at game.cc:153
0x00403b70 in main_savitch_14::game::play (this=0x28cbb8) at game.cc:33
0x004015fb in _fu0___ZSt4cout () at checkers.cc:96
0x004042a7 in main () at main.cc:34
Hello, I am coding a game for a class and I am running into a segfault. The checker pieces are held in a two dimensional array, so the offending bit appears to be invalid x/y for the array. The moves are passed as strings, which are converted to integers, thus for the x and y were somehow ASCII NULL. I noticed that in the function call make_move it says move=...
Why does it say move=...? Also, any other quick tips of solving a segfault? I am kind of new to GDB.
Basically, the backtrace is trace of the calls that lead to the crash. In this case:
game::play called game::make_computer_move which called Checkers::make_move which called Space::setPosition which crashed in line 44 in file space.h.
Taking a look at this backtrace, it looks like you passed -65 and -49 to Space::setPosition, which if they happen to be invalid coordinates (sure look suspicious to me being negative and all). Then you should look in the calling functions to see why they have the values that they do and correct them.
I would suggest using assert liberally in the code to enforce contracts, pretty much any time you can say "this parameter or variable should only have values which meet certain criteria", then you should assert that it is the case.
A common example is if I have a function which takes a pointer (or more likely smart pointer) which is not allowed to be NULL. I'll have the first line of the function assert(p);. If a NULL pointer is ever passed, I know right away and can investigate.
Finally, run the application in gdb, when it crashes. Type up to inspect the calling stack frame and see what the variables looked like: (you can usually write things like print x in the console). likewise, down will move down the call stack if you need to as well.
As for SEGFAULT, I would recommend runnning the application in valgrind. If you compile with debugging information -g, then it often can tell you the line of code that is causing the error (and can even catch errors that for unfortunate reasons don't crash right away).
I am not allowed to comment, but just wanted to reply for anyone looking more recently on the issue trying to find where the variables become (-65, -49). If you are getting a segfault you can get a core dump. Here is a pretty good source for making sure you can set up gdb to get a core dump. Then you can open your core file with gdb:
gdb -c myCoreFile
Then set a breakpoint on your function call you'd like to step into:
b MyClass::myFunctionCall
Then step through with next or step to maneuver through lines of code:
step
or
next
When you are at a place in your code that you'd like to evaluate a variable you can print it:
p myVariable
or you can print all arguments:
info args
I hope this helps someone else looking to debug!

stack problem

I got a working program compiled with gcc 3.44 but when I compiled it again using 4.44 there's something wrong. Some of the local variables in a function seems to be modified by unknown so that a for loop will not terminate because variable in its condition is constantly changing to 0 even if it's incremented. Calling a function under the loop seems to be okay because it returned to a correct address. I tried tracing the value of the variable in which the loop is affected, I found out the the value is modified after calling a print function under an if branch, removing or adding more print call solves it but I think it has nothing to do with the print function and there's no code that modify that variable except only the increment in the loop. I also tried tracing esp at the beginning and end of the loop, it is the same. What could have caused the problem?
You stated that you're going from GCC v3.44 (where the code works) to v4.44 where the code is broken.
Make sure that all other parts of the program (all source files and library files) are also compiled with GCC v4.44. You're calling a print function, so I'm guessing you're referring to the standard printf function in glibc. So make sure that glibc is also compiled under v4.44.
If this is really a problem with your print functions, maybe you are corrupting the stack with some of the parameters of the variadic list? Maybe an assumption that you had about one of the standard data types or enumeration constants doesn't hold any more? Are these your own print functions? Then try to use the __attribute__ extension of gcc to have compile time type checks.

Current function address - x64

I am working on this small project where I'd like to generate the call graph of an application - I am not planning to do anything complex, it is mainly for fun/experience. I am working on x64 platform.
The first goal I set myself is to be able to measure the time spent in each function of my test application. So far my strategy has been to use __penter()_ and __pexit()_ - __penter()_ is a function that will get called at the start of every method or function and conversely __pexit()_ will get called at the end of every method or function.
With these two functions I can record each function call as well as the time spent in each of them. What I'd like to do next is get the address of each function being called.
For example if we consider the following callstack (very simplified):
main()
....myFunction()
........_penter()
I am in __penter_ and I want to get the address of the calling function, myFunction(). I already found a way to do it in the case of non-leaf functions, I simply use RtlLookupFunctionEntry. However this solution doesn't seem to work for leaf functions because they don't provide any unwind data.
One thing I was thinking about is to go up one more level in the callstack, in main(), and decode the CALL procedure manually - that would involve getting a pointer to the instruction calling myFunction().
I was wondering if any of you would know how to get the address of the current function in the case of leaf functions. I have this gut feeling that my current approach is a bit overcomplicated.
Thanks,
Clem
I believe SymGetSymFromAddr64, probably along with StackWalk64 should get you (most of?) what you want.
Hmm, x64 code, no assembly hacks at your disposal unless you use ml64.exe. There's one intrinsic that ought to help here, _ReturnAddress() gives you the code location of the call to your __penter() function. The instruction after it btw. That should be enough to help you identify the caller.

How do I abort a MATLAB m-file function from C/C++?

I deployed a MATLAB project into a DLL, to be called from C++, and it works just fine. Happy days.
But what happens when the user asks to cancel an operation?
I tried creating a global variable named UserAborted. I initialize it to 0 before running the long function in MATLAB. I also wrote the following two functions:
function AbortIfUserRequested
global UserAborted
if (UserAborted == 1)
error('User Abort');
end
end
function UserAbortLongFunction
global UserAborted
UserAborted = 1;
end
I call upon AbortIfUserRequested in every iteration of the loop in my long function. I also exported UserAbortLongFunction.
I expected that pretty soon after called UserAbortLongFunction, the long function would reach a call to AbortIfUserRequested, and throw an error.
Instead, the long function keeps running until the end, and only then does the value of UserAborted get changed.
All I want to do is abort that long function when the user asks me to! Is there any way to do that?
Try calling the DRAWNOW function in AbortIfUserRequested. Although Matlab is single-threaded (from an API perspective), it does allow for interrupts. I've had success by calling this function with pure M-code where user input (like Ctrl-C) otherwise gets locked out.
Matlab needs to provide callback functions to show execution progress and possibly halt it. A Google search shows lots of people wanting this but no implementation from Mathworks.
Matlab's single-threaded nature might be preventing the update to the global variable's value from propagating while the first function is executing. You could try sticking the abort flag in a Java object, like a HashMap, for a layer of indirection. Since Java objects are passed by reference, an update to its state may be visible immediately, without requiring a change to the Matlab variable itself.
Here's a snippet to do so. (Sorry, I don't have a Matlab Compiler license to test this out in a deployed DLL.)
function AbortIfUserRequested
global SharedState
if SharedState.get('UserAborted')
error('User Abort');
end
end
function UserAbortLongFunction
global SharedState
SharedState.put('UserAborted', 1);
end
function InitUserAbort
global SharedState
SharedState = java.util.Collections.synchronizedMap(java.util.HashMap());
SharedState.put('UserAborted', 0);
end
Matlab app data is also effectively passed by reference. Putting the abort flag in appdata instead of a global variable might work, too. If your library works with a Matlab GUI, you can put the app data on its figure handle instead of the global handle 0. This would be more idiomatic Matlab than the Java object, if it works.
function AbortIfUserRequested
if getappdata(0, 'UserAborted')
error('User Abort');
end
end
function UserAbortLongFunction
setappdata(0, 'UserAborted', 1);
end