defining a behavior for each function c++ - 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.

Related

Is using popen() in C/C++ is a bad coding practise?

I want to change the timezone for Linux system. I know there are many ways.
One way is to use tzset() function and another is to call 'timedatectl' command from 'popen()' function.
I am using second approach i.e, using "popen()".
I just want to ask is it a good programming practice to use "popen()" in your code?
Also, I am carefully calling "pclose()" for every "popen()".
There is nothing wrong about popen in general, if you really need a child process to do a specific job for you.
popen creates a pipe allowing you to either read the output (what it wrote to stdout) of the child process or write input to its stdin - but not both at the same time.
If you are not interested in either option, you possibly might prefer calling system instead (however, system will wait for the process to terminate, in contrast to popen - pclose waits for).
But why would you want to create a separate process, if you can do the same job by simply calling an ordinary function (system call or not)? You are creating a lot of overhead using a process then (process must be initialised and hooked into OS, it needs its own memory for executable code, heap and stack, ...)!
It gets a little more complicated, if the job in question requires a considerable amount of time and you cannot afford to wait for the function to complete, but need to do some other stuff. However, in such a case, I'd rather create a thread only and again call the function from there...
popen() invokes a shell to run the command which is an extra unnecessary layer of indirection. Plus there are all sorts of security pitfalls, for instance, you don't have control over the environment - or which shell actually gets invoked.
I'd say it's fine for prototypes and proofs of concept, but for production code you should use fork(), one of the execs and pipes for IO.
EDIT
If there is a function equivalent to doinf something by invoking a command, always use that first. For example, if you can achieve what you want with tzset(), always use that in preference to spawning a new process.

Detecting infinite recursion in v8

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.

PTRACE_SYSCALL and orig_eax

I want to kill a child process if it does other system calls than read and write (and even filter these calls as well, but it's a different story) but there some system calls done by default.
I have compiled an empty test child (exits instantly) program and I also have a parent process which forks, enables ptracing and executes the child program. Parent process uses PTRACE_SYSCALL and checks orig_eax every time. My test program reports that the child was stopped 49 times (which, I assume, means 48 / 2 + 1 system calls).
I wanted to know whether the system calls sequence is always the same (initialization) and/or it's possible to know when I can start and when to stop kill-on-syscall in my parent?
I had a similar problem once (see my question on the topic). When a program starts, it executes a lot of system calls when initializing the application (such as loading shared libraries) before calling main(). What I did is to simply allow somewhat more system calls and use another means of security (such as chroot) to prevent the application from accessing undesired files.
A better option would be to somehow find the entry point of the main() function of the program (see this tutorial for writing debugging code) and disable system calls after that point. I don't know if it's possible to do in general case, but that's the way I would start to search.
After finding the entry point, there is another way of restricting the program from making certain system calls. Instead of using PTRACE_SYSCALL to check each system call done by the program, inject a prctl(PR_SET_SECCOMP, ...) call to the program (using ptrace()) then just leave the program running.

How to terminate program in C++

When I exit my C++ program it crashes with errors like:
EAccessViolation with mesage 'Access violation at address 0...
and
Abnormal Program Termination
It is probably caused by some destructor because it happens only when the application exits. I use a few external libraries and cannot find the code that causes it. Is there a function that forces immediate program exit (something like kill in Linux) so that memory would have to be freed by the operating system? I could use this function in app exit event.
I know that it would be a terrible solution because it'd just hide the problem.
I'm just asking out of sheer curiosity, so please don't give me -1 :)
I tried exit(0) from stdlib but it didn't help.
EDIT:
Thanks for your numerous replies:)
I use Builder C++ 6 (I know it's outdated but for some reasons I had to use it). My app uses library to neural networks (FANN). Using the debugger I found that program crashes in:
~neural_net()
{
destroy();
}
destroy() calls multiple time another function fann_safe_free(ptr), that is:
#define fann_safe_free(x) {if(x) { free(x); x = NULL; }}
The library works great, problem only appears when it does cleaning. That's why I asked about so brutal solution. My app is multi-threaded but other threads operate on different data.
I will analyze my code for the n-th time(the bug must be somewhere), thanks for all your tips :)
You should fix the problem.
First step: find at check all functions you register with atexit() (not many I hope)
Second step: find all global variables and check their destructors.
Third Step: find all static function variables check their destructors.
But otherwise you can abort.
Note: abort is for Abnormal program termination.
abort()
The difference: (note letting an application leave the main function is the equivalent of exit())
exit()
Call the functions registered with the atexit(3) function, in the reverse order of their registration. This includes the destruction of all global (static storage duration) variables.
Flush all open output streams.
Close all open streams.
Unlink all files created with the tmpfile(3) function.
abort()
Flush all open output streams.
Close all open streams.
It's a terrible solution for more than one reason. It will hide the problem (maybe), but it could also corrupt data, depending on the nature of your application.
Why don't you use a debugger and try to find out what is causing the error?
If your application is multi-threaded, you should make sure that all threads are properly shut down before exiting the application. This is a fairly common cause of that type of error on exit, when a background thread is attempting to use memory/objects that have already been destructed.
Edit:
based on your updated question, I have the following suggestions:
Try to find out more specifically what is causing the crash in the destructor.
The first thing I would do is make sure that it's not trying to destruct a NULL object. When you get your crash in ~neural_net in your debugger, check your "this" pointer to make sure it's not NULL. If it is, then check your call-stack and see where it's being destructed, and do a check to make sure it's not NULL before calling delete.
If it's not NULL, then I would unroll that macro in destroy, so you can see if it's crashing on the call to free.
You could try calling abort(); (declared in <stdlib.h> and in <process.h>)
The version in VisualC++, however, will print a warning message as it exits: "This application has requested the Runtime to terminate it in an unusual way. Please contact the application's support team for more information."
On Linux/UNIX you can use _exit:
#include <unistd.h>
void _exit(int status);
The function _exit() is like exit(), but does not call any functions registered with atexit() or on_exit(). Whether it flushes standard I/O buffers and removes temporary files created with tmpfile(3) is implementation dependent. On the other hand, _exit() does close open file descriptors, and this may cause an unknown delay, waiting for pending output to finish. If the delay is undesired, it may be useful to call functions like tcflush() before calling _exit(). Whether any pending I/O is cancelled, and which pending I/O may be cancelled upon _exit(), is implementation-dependent.
Have you tried the gruesome step by step? If you're project/solution is simply to large to do so maybe you could try segmenting it assuming you use a modular build and test each component indivdually. Without any code or visible destructors abstract advice is all I can give you I'm afraid. But nonetheless I hope trying to minimize the debugging field will help in some way.
Good luck with getting an answer :)
That immediate program exit (and yes, that's a terrible solution) is abort()
That happens most likely because a NULL pointer is being accessed. Depending on your OS try getting a stack trace and identify the culprit, don't just exit.
If you use linux, valgrind should solve your problem.
but if it is windows, try one of these: MemoryValidator, BoundsChecker or other tools like these.
Simply close your application is not the best way to deal with bugs ...

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.