How can I catch this "This application has requested the Runtime to terminate it in an unusual way" error in my C program? - c

I have a C CLI program that crashes and generates this error in Windows 7:
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
First, I read somewhere that it could be caused assert statements triggering so as a first measure I replaced them with if statements to catch and log any potential failed asserts. Second, I sprayed the code with printf statements to see where the program exits. Third, I especially made sure that the code doesn't exit anywhere without first logging the exit. The program is threaded so there are quite a few things going on, but nothing too complex.
Now the problem is that the second time I got the error it showed that the program exited outside of my printf statements so I can't tell where it exited.
So two questions:
I suspect I would need to use a proper debugger to see more details regarding the exit, if so, which one?
Are there any other gotchas regarding this sort of error besides the assert statements? I find quite a few C++ blog entries regarding this error, but not too many C ones.
I am using Visual C++ 2008 Express Edition. Also, I am invoking the program in CMD.exe.

First of all, you removed calls to assert which are typically meant to help track down cases where the assumption the programmer makes don't hold? Really? Uhm...
Second of all, are you familiar with the debugger at all? Visual C++ should include an integrated debugger that can, when your program runs in debug mode, not only show you where your process exits from but it can also show you exactly where your program crashes, how it got to that point and what the values of variables where at the time of the crash. Imagine that!
This article mostly talks about C# but the principles are the same.

The message you are getting is from the VC runtime. It happens when an exception is thrown and not caught anywhere.
Compile your program with a debugging debugging configuration (that should be the default) and run in the debugger, and when you hit an unhandled exception, the debugger will break. Under the "Debug" menu, you will find an "Exceptions" item, which will help you fine tune how the debugger responds to exceptions.
Note that in the context of C++ and Windows, 'exception' can mean one of several things; there are the Win32 exceptions, the C++ exception, and VS Structured Exception Handling.
assertions are for fail conditions that you never expect to happen, but can't prove can't happen. You should always be surprised by an assertion. Many (most? all?) implementations of assert() are only compiled in debug configurations and not release configurations.

Related

How can I get meaningful error messages from Windows after C program crashes?

When running a program I've written in C, which contains a bug that causes a crash, I'll get the following message from Windows:
A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available.
This doesn't help me at all to find the problem. It can be an array out-of-bounds bug which causes a segfault, or a NULL-pointer dereference, or anything else.
At the end, I find the error by commenting-out code until the rouge code is found.
I'd like to have a faster way to track down these bugs. Is this possible with "Vanilla" Mingw GCC and Windows? Or do I have to install a fancy IDE to get meaningful error messages after crashes?

GLib/GObject intercept errors / structure code for testing, reporting or debugging

Situation:
I am working on upgrading some code at my work place. The code is for a process that is based off of GMime. We currently use GMime 2.2 and I recently upgraded our code to use GMime 2.4. The proces runs just fine and doesn't crash, but I get a
GLib-GObject-CRITICAL **: g_object_unref: assertion G_IS_OBJECT (object)' failed
every now and then when the program is running.
There are times that calls to g_object_unref fails and crashes my program. I'm trying to debug this, but unfortunately the person who made this program didn't add any testing or debugging features.
I know and understand how important embedding debugging information or setting up a testing framework is, when you have to go back into old code. I know how to set this up in pure C or pure C++, but as soon as other libararies get tossed in it becomes really difficult.
My problem is:
How how do I effectively setup debug code and/or a testing system with a program that relies on GLib or GObject?
My questions are:
How can I tell what's happening in the code? Should I be listening for "signals"? How do I setup those signals?
Functions like g_object_unref return void. That being the case how do I output debugging information related to these functions?
Does a GObject have a "property/class member", I don't know the proper term for this in relation to GLib, that has error information embedded in it?
(Related, but slightly off topic) Libraries like GLib and node.js ecetera have "extensive" documentation that amounts to:
function doSomethingThatShouldBeUsefulAndUnderstoodByAnyoneWhoReadsThis(WYSIWYG, FIY, BYOF, X, Y, Z) // this function does something that should be usefull and understood by anyone who reads the function this does something and can be called
How does one has a lot of programming experience (with languages in their pure form), go about making heads or tails of the library when most tutorials refer you back to the documents or are the documents themselves?
Is there a recommended tutorial for this?
Sites I have looked at:
http://arunchaganty.wordpress.com/2008/05/18/i-am-a-gobject/
create and emit gtk signal
https://developer.gnome.org/glib/2.28/glib-running.html
https://developer.gnome.org/gtk-tutorial/2.90/a2901.html
https://developer.gnome.org/gobject/unstable/gobject-Signals.html
Any and all comments, questions and suggestions are greatly appreciated!
Thank you.
The easiest way I know of to debug issues like this is to run the program under a debugger and break on g_logv (that error message was printed with g_logv) and when the debugger catches a call to g_logv, you can get a backtrace to see where in your program you are.
Usually these types of errors happen when a programmer tries to call g_object_unref() on a NULL pointer.
That said, is there a reason you only upgraded to GMime 2.4 instead of GMime 2.6? 2.6 has been out for several years now and is the series that is best maintained.

Dump call stack on error?

I'm debugging a program written in plain C (no C++, MFC, .NET, etc.) to the WIN32API. It must compile in both VS2005 (to run under Win 2K/XP) and VS2010 (to run under Win7.) I've been unable to duplicate a bug that my customer seems able to duplicate fairly reliably, so I'm looking for ways to have my program "debug itself" as-it-were. It is monitoring all of the key values that are changing, but what I'd really like to see is a stack dump when a value changes. Oh, I cannot run a "true" debug build (using the debug libraries) without installing the compiler on the customer's machine and that is not an option, so this must be built into my release build.
Is there any way to do this other than just adding my own function entry/exit calls to my own stack monitor? I'd especially like to be able to set a hardware breakpoint when a specific memory address changes unexpectedly (so I'd need to be able to disable/enable it around the few EXPECTED change locations.) Is this possible? In a Windows program?
I'd prefer something that doesn't require changing several thousand lines of code, if possible. And yes, I'm very underprivileged when it comes to development tools -- I consider myself lucky to have a pro version of the Visual Studio IDEs.
--edit--
In addition to the excellent answers provided below, I've found some info about using hardware breakpoints in your own code at http://www.codereversing.com/blog/?p=76. I think it was written with the idea of hacking other programs, but it looks like it might work find for my needs, allowing me to create a mini dump when an unexpected location writes to a variable. That would be cool and really useful, especially if I can generalize it. Thanks for the answers, now I'm off to see what I can create using all this new information!
You can use MiniDumpWriteDump function which creates a dump, which can be used for post-mortem debugging. In the case application crashes, you can call MiniDumpWriteDump from unhandled exception handler set by SetUnhandledExceptionFilter. If the bug you are talking about is not crash, you can call MiniDumpWriteDump from any place of the program, when some unexpected situation is detected. More about crash dumps and post-mortem debugging here: http://www.codeproject.com/Articles/1934/Post-Mortem-Debugging-Your-Application-with-Minidu
The main idea in this technique is that mini dump files produced on a client site are sent to developer, they can be debugged - threads, stack and variables information is available (with obvious restrictions caused by code optimizations).
There are a bunch of Win32 functions in dbghelp32.dll that can be used to produce a stack trace for a given thread: for an example of this see this code.
You can also look up the StackWalk64() and related functions on MSDN.
To get useful information out, you should turn on PDB file generation in the compiler for your release build: if you set up your installer so that on the customer's computer the PDB files are in the same place as the DLL, then you can get an intelligible stack trace out with function names, etc. Without that, you'll just get DLL names and hex addresses for functions.
I'm not sure how practical it would be to set up hardware breakpoints: you could write some sort of debugger that uses the Win32 debugging API, but that's probably more trouble than its worth.
If you can add limited instrumentation to raise an identifiable exception when the symptom recurs, you can use Process Dumper to generate a full process dump on any instance of that exception.
I find I cite this tool very frequently, it's a real godsend for hard-to-debug production problems but seems little-known.

Does attaching to a process make it behave differently?

While I am aware of the differences between debug and release builds, I am curious if attaching the debugger to a process (built release or debug) changes that processes behaviour?
For reference, I'm developing on HP 11.31 Itanium but still am curious for the general case.
http://en.wikipedia.org/wiki/Heisenbug#Heisenbug
Of course, attaching a debugger will change the timing (which can change e.g. thread race conditions), and also some system calls can detect if a debugger is attached.
It certainly can, depending on the platform and the method of debugging. For example, when debugging on Windows, there is actually the IsDebuggerPresent function. As noted that function can be circumvented, but then there are other means. So basically, it's complicated.
Yep, lots of things inside the Windows data structures change when a debugger is attached. It changes how memory is allocated/freed, it adds additional housekeeping code and "markers" on the stack (Ever noticed the F00D values in newly allocated memory) in fact many of the changes are used by anti-debuggers to detect if an application is being debugged.
In interpreted languages (Java, .NET) the runtime will often generate different machine instructions when running under a debugger to help it trap and display exceptions, show the original code, etc. It will usually generate unoptimized code as well when a debugger is attached.
Some of these changes affect the way the software behaves and can result complicate transient bugs that are caused by optimizations or extremely fine timinig dependencies.
Yes, I've often found that attaching a debugger to a process instantly makes bugs disappear, only to have them reappear when I compile my app in release mode. Unfortunately I usually can't really ask all my users to open a debugger just to run my app, so it can be quite frustrating.
Another thing to keep in mind is that for multithreaded apps attaching the debugger definitely can yield very different results. These are the kind of things referred to as "Heisenbugs."
Sure, in multithreaded apps, attaching a debugger can yield different result.
However, how about the codes which are not related to threads?
I have seen a release build, which has a debugger attached, doesn't have problems. But, when a debugger is not attached, it has problems.
If it is launched first and a debugger is attached to it, it also shows the same problems.

Under a debugger

How do I detect in my program that it's being run under a debugger? I am aware that this seems to indicate that I try to do something I shouldn't, and that is too messy. I think it is an interesting question tho. Specifically, is there a way to do it in a POSIX environment? For example using sigaction (2) to detect that some handler is installed? Even a worse thought; is there some inline assembly code I could use on an x86 architecture?
As we discuss it -- would it eventually be possible to launch a debugger, such as gdb (1), and break at the place where you perform this possible hack. Thanks for any dirty one-liners or unlikely references to standards related to this.
Does this article (archive link) help?
It suggests, amongst other things:
file descriptors leaking from the parent process
environment variables ($_)
process state (getsid(), etc).
Note that most (if not all) of these rely on the debugger spawning the process that's being debugged. They're not so effective if the debugger is attached to a process that's already running.
There is no reliable way to detect that you are running under a debugger. That's because a debugger may use any number of methods to actually debug your code, some of which will almost certainly not be caught by your method.
My question is, why would you care? Unless you're trying to hide something :-)

Resources