How do I install a signal handler for an access violation error on Windows, in C? - c

I have a bad application raising an access violation on windows. This pops up the "crash dialog" on windows and I don't want that to appear on the user's computers. On Linux, I would install a signal handler for SIGSEGV, and just exit() in the sighandler function, but I am on Windows, and I know close to nothing of the Windows API.
As far as I understand, Windows throws an exception ACCESS_VIOLATION when a segfault happens. I assume it's a regular C++ exception and one can catch it, but the program I need to patch is in C, not C++. How does one install a "signal handler" on windows? (assuming the concept of signal exists, considering that signal() and friends are a POSIX API)? Is this API implemented as a core API, or is it part of a POSIX compatibility layer that may not be present on a vanilla deployment?
I am working with VS2008 on Win7

It's not1 a "regular C++ exception". It's an OS trap.
On Linux and other Unix-like systems, OS traps are called "signals".
On Windows, they are called "Structured Exceptions". You'll find a ton on information online about SEH, which stands for structured exception handling. The official documentation is on MSDN
Windows C and C++ compilers have special keywords for working with structured exceptions
__try {
}
__except( MyExceptionFilter(GetExceptionCode(), GetExceptionInfo()) ) {
}
Inside the exception filter, you can inspect the exception code and discriminate between access violations, divide by zero, floating point signals, etc. You can find out where the exception happened and log a stack trace (with some extra work). And you can choose whether or not the handler code block runs.
Underneath, these keywords get translated into code that sets up trap handlers, using data structures like vectored exception handler tables. But you really want the compiler's help rather than doing it yourself. Seeing the internal implementation is only of interest to compiler developers or if something goes wrong and you have to debug through it.
1Depending on your compile options, in Visual C++ it's the /EHa and /EHs options, C++ exceptions might be built on top of SEH (there's one particular exception code which means "Microsoft C++ exception", and a pointer to the C++ exception object is stored in the SEH parameters). When that happens, stack unwinding of C++ try/catch and SEH __try/__except/__finally is unified -- both exceptions unwind through both handler styles. The __set_se_translator function is also interesting to people using both C++ exception and SEH in the same program.

Related

Mac OS equivalent of the Windows Fibers API?

I'm asking this out of curiosity.
Windows provides what they call a Fibers API, which is a API for lightweight user processes/threads.
I was interested in knowing if Mac OS provides such features as well. As far as I could find out, the closest Unix equivalent to that would be the setcontext family of functions. However, trying to call such API on a Mac program produces warnings saying that the functions have been deprecated since OSX 10.6. Also, when I attempt to compile and run the example provided in the Wikipedia link above, I get a seg fault on my machine at the first swapcontext.
So apparently the setcontext API is a no go for Mac. Not any longer at least. Is there any other way to achieve lightweight user-side threads on Mac OS? Does the system provide such functionality?
No, there is no equivalent on OS X (or most UNIX-based systems, for that matter). The ucontext series of functions were deprecated by the POSIX standard and no replacement was provided.
The closest you can get on OS X is Grand Central Dispatch, which allows you to create dispatch queues that execute 'blocks' (essentially functions). Processing of these queues can be suspended and resumed, similar to fibers, though you can't stop and resume execution in the middle of a block.
There's also Boost.Context, which provides similar functionality to ucontext (and perhaps even uses it internally), though it's a C++ library.

Create a Debugger using C

I have been asked to write a program in C which should debug another program in C language and then store the value of each variable of every line,loop or function in a log file.
I have been searching over the internet and I found articles on debugging using gdb.
Can I somehow use GDB in my program for this purpose and then store the values of each variable line by line.
I've got basic knowledge of C/C++ so please reply in simple terms.
Thanks
Debuggers depend on some special capability of the hardware, which must be exposed by the operating system (if any).
The basic idea is that the hardware is configured to transfer control to a debugger stub either after every instruction of the target program, or after certain types of instructions such system calls, or those meeting a hardware breakpoint condition. Typically this would look like an interrupt, supervisor exception, or the like - very platform-specific detail.
As mentioned in comments, on Linux, you use the ptrace functionality of the kernel to interact with the debugger support provided by the hardware and the kernel, abstracting away a lot of the hardware-unique detail and managing the permission issues. Typically you must either be the same user id as the process being debugged, or be the superuser (root). Linux's ptrace also gives you an indirect ability to do to things like access the memory (literally, address space) of the target application, something critical to debugger functionality which you cannot ordinarily do from another user-mode program on a multitasking operating system.
Other operating systems will have different methods. Some embedded targets use debug pods which connect your development machine to the embedded board by a few wires. In other cases, debug capability built into the hardware is managed by a small program running on the target processor, which then talks back over a serial or network port to the full debugger program residing on the development machine.
A program such as GDB can do more than just the basics of setting debug stop conditions, dumping registers, and dumping program instructions. Much of its code deals with annotating what it displays based on debug metadata optionally left behind by compilers, walking back through stack frames, and giving the user powerful tools to configure all of this - and of course it does most of this in a target-independent way, with the target-unique code mostly confined to a few interchangeable directories.
You can indeed "drive" GDB from another program - many, many GUI type debuggers do exactly that, existing as graphical front ends for GDB. However, if you were assigned to write a debugger, doing it that way may or may not by consistent with your assignment.

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

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.

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.

How to debug memory issues in embedded application

I'm new to embedded programming but I have to debug a quite complex application running on an embedded platform. I use GDB through a JTAG interface.
My program crashes at some point in an unexpected way. I suppose this happens due to some memory related issue. Does GDB allow me to inspect the memory after the system has crashed, thus being completely unresponsive?
It depends on your setup a bit. In particular, since you're using JTAG, you may be able to set your debugger up to halt the processor when it detects an exception (for example accessing protected memory illegally and so forth). If not, you can replace your exception handlers with infinite loops. Then you can manually unroll the exception to see what the processor was doing that caused the crash. Normally, you'll still have access to memory in that situation and you can either use GDB to look around directly, or just dump everything to a file so you can look around later.
It depends on what has crashed. If the system is only unresponsive (in some infinite loop, deadlock or similar), then it will normally respond to GDB and you will be able to see a backtrace (call stack), etc.
If the system/bus/cpu has actually crashed (on lower level), then it probably will not respond. In this case you can try setting breakpoints at suspicious places/variables and observe what is happening. Also simulator (ISS, RTL - if applicable) could come handy, to compare behavior with HW.

Resources