Detecting infinite recursion in v8 - c++

I am using google's v8 javascript engine to have an embedded js interpreter in my project, which must be able to execute user-provided code, but I am wondering if it is possible to set something up in advance of calling any user code which ensures that if the code tries to recurse indefinitely (or even if it just executes for too long), that it can somehow be made to abort, throw an otherwise uncaught exception, and report the issue back to the caller.
Thank you all for responses so far... yes, I realized not long after I posted this that I was basically asking for some kind of solution to the halting problem, which I know is unsolvable, and is actually far more than what I really need.
What I'd need is either some mechanism for detecting when something running in the v8 environment is returning quickly enough, or else simply a mechanism to detect if recursion is happening at all... my use cases are such that the end user should not be utilizing any recursion anyways, and if I can possibly even detect that, then I could reject it at that point instead of blindly executing it. It would be allowed, however, for different threads, with different isolates to invoke the same functions at the same time, so I can't just use a static local variable to lock out another call to the same function.

A compiler [V8 is definitely a compiler in this context, even if it isn't "always" a compiler] can detect recursion, but if the code is clever enough (for example depending on variables that aren't known at compile time), it's not possible to detect whether it has infinite or finite recursion.
I would simply state that "execution over X seconds is disallowed", and if the execution takes more than that long, abort it. You can do this by having a "watchdog thread", that gets triggered when the code completes - and if the watchdog thread gets to run X seconds, kill the main thread and report back to user-code. No, I don't know EXACTLY how to write this code in conjunction with V8.

Related

Interrupt or cancel a long computation in DLL

I'm developing an SDK as a dynamic library (DLL/so). The user can set a lot of parameters prior to run the computation. But I would like to offer a way to dynamically change the parameters, which should stop the current computation and relaunch it with the new parameters. So a general usage should looks like:
Client Caller thread -----> Call my SDK -----> Computation code
^
|
|
Client UI Thread ----> Request cancelation ------------
I have a lot of questions about the mechanics and I'm wondering what are the good practices to do so.
1) How to handle the interrupt ?
Should I run my computation in an async thread, and just drop the results of that thread?
Should I use a std::atomic<bool> that the computation thread checks sometime to return to start point?
2) If using the second options, what is the best way to return to the launch point?
Is it okay to use C++ exceptions that case? (NOTE: I already use exception for really rare case in the computation code.)
Should it have Error code handling all along with early checks to avoid computing?
Could longjmp or something similar that can be used?
For proper object cleanup and resource reclamation, you need to either throw an exception or just stop the calculation and let the calculation functions return normally.
You should not abort the thread or use longjmp, as they will not destroy the objects your calculation has created, leading to leaks of memory and whatever other resources (like file handles) you may be using.
Using a std::atomic (that is easily accessible from everywhere) that your calculations poll periodically is one way to achieve this. You'll need to check this regularly, so the check will need to be in or near any loops you have. Short, quick loops don't need to check while they are looping, but there should be some sort of check at least several times a second. Once you detect the cancellation request, you can either throw your exception, or return from the current function (so the parent function would also need to check for cancellation).
One downside to all that is if you miss a check in a loop someplace, your cancellation may not happen right away.

How to end a C++ program after error?

I am refactoring an old code, and one of the things I'd like to address is the way that errors are handled. I'm well aware of exceptions and how they work, but I'm not entirely sure they're the best solution for the situations I'm trying to handle.
In this code, if things don't validate, there's really no reason or advantage to unwind the stack. We're done. There's no point in trying to save the ship, because it's a non-interactive code that runs in parallel through the Sun Grid Engine. The user can't intervene. What's more, these validation failures don't really represent exceptional circumstances. They're expected.
So how do I best deal with this? One thing I'm not sure I want is an exit point in every class method that can fail. That seems unmaintainable. Am I wrong? Is it acceptable practice to just call exit() or abort() at the failure point in codes like this? Or should I throw an exception all the way back to some generic catch statement in main? What's the advantage?
Throwing an exception to be caught in main and then exiting means your RAII resource objects get cleaned up. On most systems this isn't needed for a lot of resource types. The OS will clean up memory, file handles, etc. (though I've used a system where failing to free memory meant it remained allocated until system restart, so leaking on program exit wasn't a good idea.)
But there are other resource types that you may want to release cleanly such as network or database connections, or a mechanical device you're driving and need to shut down safely. If an application uses a lot of such things then you may prefer to throw an exception to unwind the stack back to main, and then exit.
So the appropriate method of exiting depends on the application. If an application knows it's safe then calling _Exit(), abort(), exit(), or quickexit() may be perfectly reasonable. (Library code shouldn't call these, since obviously the library has no idea whether its safe for every application that will ever use the library.) If there is some critical clean up that must be performed before an application exits but you know it's limited, then the application can register that clean up code via atexit() or at_quick_exit().
So basically decide what you need cleaned up, document it, implement it, and try to make sure it's tested.
It is acceptable to terminate the program if it cannot handle the error gracefully. There are few things you can do:
Call abort() if you need a core dump.
Call exit() if you want to give a chance to run to those routines registered with atexit() (that is most likely to call destructors for global C++ objects).
Call _exit() to terminate a process immediately.
There is nothing wrong with using those functions as long as you understand what you are doing, know your other choices, and choose that path willingly. After all, that's why those functions exist. So if you don't think it makes any sense to try to handle the error or do anything else when it happens - go ahead. What I would probably do is try to log some informative message (say, to syslog), and call _exit. If logging fails - call abort to get a core along the termination.
I'd suggest to call global function
void stopProgram() {
exit(1);
}
Later you can change it's behavior, so it is maintainable.
As you pointed out, having an exit or abort thrown around throughout your code is not maintainable ... additionally, there may be a mechanism in the future that could allow you to recover from an error, or handle an error in a more graceful manner than simply exiting, and if you've already hard-coded this functionality in, then it would be very hard to undo.
Throwing an exception that is caught in main() is your best-bet at this point that will also give you flexibility in the future should you run the code under a different scenario that will allow you to recover from errors, or handle them differently. Additionally, throwing exceptions could help should you decide to add more debugging support, etc., as it will give you spots to implement logging features and record the program state from isolated and maintainable points in the software before you decide let the program exit.

defining a behavior for each function c++

does anyone know of a way to define some behavior to be called on every function or line in a C++ program?
i would like to validate my software by essentially causing it to exit at certain points in the application, and make sure that the next boot up of the process can handle recovering in all of the points at which the process previously died.
essentially, im looking for a way to script failures in C++, so that I don't have to define points using some macros, and just tell the application to essentially cycle through all of these "Death points" and confirm that the process can recover from every single one of them, doing all of this in an automated fashion.
i could easily create a macro called DEATH_POINT() and it could essentially check whether or not it should exit the process or not, but I was hoping there was something a bit more elegant than having a bunch fo macros sitting in the code.
Depending on the compiler you are using there is probably a way to have it call a function automatically every time it enters a function. That might do what you need.
For Visual Studio there's info here: http://msdn.microsoft.com/en-us/library/c63a9b7h.aspx
And the top answer here has information about doing it in GCC: Automatically adding Enter/Exit Function Logs to a Project
I suggest you go one step beyond that, and test on an instruction-by-instruction basis, rather than entire expressions, statements, or lines.
You should be able to use the Debugger API to set a breakpoint programmatically (you'll need a helper process though, IIRC). The process will be suspended when the breakpoint is reached. And you can receive an event when the breakpoint is hit and terminate the process.

Multithreading: a blocking wait with timeout

I'm using TinyThread++ to get clean and simple platform independent control over threading features in my project. I just came upon a situation where I'd like to have responsive synchronized message passing without pegging the CPU, while allowing a thread to continue to do a bit of work on the side while it is idle. Sure, I could simply spawn a third thread to do this "other work" but all I'm missing is a condition variable wait(int ms) type function rather than the wait() that already works great. The idea is that I'd like for it to block only for up to ms milliseconds, so it will be able to time out and perform some actions periodically (during which the thread will not be actively waiting on the condition variable). The idea is that even though it's nice to have the thread sitting there waiting to pounce on any incoming messages, if I give it some task to do on the side which takes only 50 microseconds to execute, and I only need to run that once every second, it definitely shouldn't push me to make yet another thread (and message queue and other resources) to get it done.
Does any of this make sense? I'm looking for suggestions on how i might go about implementing this. I'm hoping adding a couple of lines to the TinyThread code can provide me with this functionality.
Well the source code for the wait function isn't very complicated so making the required modificiations looks simple enough:
The linux implementation relies on the pthread_cond_wait function
which can trivially be changed to the pthread_cond_timedwait
function. Do read the documentation carefully in case I forgot about any minutias.
On the windows side of things, it's a little more
complicated and I'm no expert on multithreading on windows. That
being said, if there's a timed version of the _wait function (I'm pretty sure there is),
changing that should work just fine. Again, read over the documentation carefully before doing any modifications.
Now before you go off and do these modifications, I don't think what you're trying to do is a good idea. The main advantage of using threads is to conceptually seperate different tasks. Trying to do multiple things in a single thread is a bit like trying to do multiple things in a single function: it complicates the design and makes things harder to debug. So unless the overhead of creating a new thread is provably too great or unless the resulting code remains simple and easy to understand, I'd split it up into multiple threads.
Finally, I get the feeling that you might not be aware that condition variables can return spuriously (returns without anybody having done any signalling or returns when the condition is still false). So just in case, I'd suggest reviewing the usage examples and making sure you understand why those loops are there.

Cross-thread exception throwing

I have an application that allows users to write their own code in a language of our own making that's somewhat like C++. We're getting problems, however, where sometimes our users will accidentally write an infinite loop into their script. Once the script gets into the infinite loop, the only way they can get out is to shut the application down and restart, potentially losing their work. I'd like to add some means where the user, when he realizes that his code is in an infinite loop, can hit a special key, like F10 or something, and the code will break out of the loop. But I'd like to do it without implementing a ton of checks within the script runtime. Optimally, I'd like to have a separate "debugger" thread that's mostly idle, but as one of its tasks it listens for that F10 key, and when it gets the F10 key, it will cause the script runtime thread to throw an exception, so that it will stop executing the script. So my question is, is there a way to have one thread cause another thread to throw an exception? My application is written in C++.
If the script is actually interpreted by your application then you can just tell the interpreter to stop executing whenever some user event occurs.
It's possible. Detect the keystroke in a separate thread, a hidden window and WM_HOTKEY for example. Call SuspendThread() to freeze the interpreter thread. Now use GetThreadContext() to get the CPU registers of the interpreter thread. Modify CONTEXT.Eip to the address of a function and call SetThreadContext(). Have that function call RaiseException() or throw a C++ exception. ResumeThread() and boom.
A short answer - no.
If your application runs on Windows, maybe you can send a message from this "debugger" tread and have a message loop in the main one?
The problem with that solution is, to do a message sending implementation, I'd have to set up a "listener" as part of the script interpreter. Right now, the interpreter just executes the function. The message loop is implemented outside of the interpreter. If within the function there is an infinite loop, then to break out of that script, I'd have to check for a message in between execution of each instruction in the interpreter, i.e. while(more instructions){check F10, execute script instruction}. That seems like a lot of extra unneeded checks that can slow down the script execution. But if that's the only solution, then I guess that's what it has to be. I still think there's got to be a better way. Maybe the script interpreter needs to be run on a child thread, while the main thread continues its message loop, and will then kill the script interpreter thread when it gets an F10.
Whether you code it explicitly or not, you will need to check a "interrupt" variable in the message loop. If you implement this by a simple volatile int, you will have both a very simple test and very little overhead.
It is unsafe to terminate a thread, as it is probably using resources shared across the entire process.
It is less unsafe to terminate an entire process, but that's not going to help you.
A more safe way to deal with this would be to have the interpreter check for events on a regular basis and treat the stop event as a case to terminate (or at least spill out to a higher loop).
For windows, you could also queue an APC to that thread that calls RaiseException(...) or throws an exception, (although I would avoid the latter, since that crosses API boundaries), but that also implies that the thread will put itself into an alertable state. And I don't really recommend it.