Unhandled Win32 exception - c++

At runtime, when myApp.exe crashes i receive "Unhandled Win32 exception" but how would i know which exception was occurred? where did something went wrong?

For a Native C++ app see my earlier answer here: Detect/Redirect core dumps (when a software crashes) on Windows for catching the unhandled exception (that also gives code for creating a crash dump that you can use to analyse the crash later. If the crash is happening on a development system then in Visual Studio (I'm assuming you're using that, if not other IDEs will have something similar), in Debug/Exceptions tick the 'Thrown' box for 'Win32 Exceptions'.

Typically, Windows will give you several hexadecimal numbers as well. Chances are that the exception code will be 0xC0000005. This is the code of an Access Violation. When that happens, you also will have three additional bits of information: the violating address, the violated address, and the type of violation (read, write or execute).
Windows won't narrow it down any further than that, and often it couldn't anyway. For instance, if you walk past the end of an array in your program, Windows likely won't realize that you were even iterating over an array. It just sees "read:OK, read:OK, read:out of bounds => page fault => ACCESS VIOLATION". You will have to figure that out from the violating address (your array iteration code) and the violated address (the out-of-bounds address behind your array).

If it's a .Net app you could try to put in a handledr for the UnhandledException event. You can find more information about it and some sample code here.
In general it's a good sign that your exception handling is broken though, so might be worth going through your code and finding places that could throw but where you don't handle exceptions.

Use the debugger. You can run the program and see what exception is been thrown that kills your application. It might be able to pinpoint the location of the throw. I have not used the VS debugger for this, but in gdb you can use catch throw to force a breakpoint when an exception is thrown, there should be something similar.

Related

Exception thrown at 0x00007FF93E507A7A (ntdll.dll) .Access violation reading location 0xFFFFFFFFFFFFFFFF

I'm using POCO lib to working network.
i use JSON data of POCO/JSON . my code:
User user(context.marshal_as<std::string>(tbUserName->Text),
context.marshal_as<std::string>(tbFullName->Text),
context.marshal_as<std::string>(tbDisplayName->Text),
context.marshal_as<std::string>(tbEmail->Text),
context.marshal_as<std::string>(tbPhoneNumber->Text),
context.marshal_as<std::string>(tbNamSinh->Text),
context.marshal_as<std::string>(tbPassword->Text),
context.marshal_as<std::string>(tbConfirm->Text)
);
string jsonString = user.serialize();
I have an error Exception thrown at 0x00007FF93E507A7A (ntdll.dll) in Client_Winform.exe:
0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
If there is a handler for this exception, the program may be safely continued.
Use Visual Studio's Code Analysis to track the exact place in your code where the bug is.
https://msdn.microsoft.com/en-us/library/ms182028.aspx
The problem with these kinds of error messages is not to understand the reason (bad handle) but to find the place. Since your code passed compilation with no errors, and in many cases, will run smoothly on several machines and crash only on one of them, you need to focus on the place of the crash.
You are using a handle which got returned as INVALID_HANDLE from some function (INVALID_HANDLE is -1 or 0xFFFFFFFFFFFFFFFF). When you try to use it, it gets used as an address and you don't have permissions to access that address (error 5 is access violation).
This could occur, when you do have multiplatform projects (i.e. assemblies). Meaning, if you do have one project of x86 and another project in x64. Issue occurs when you build project under wrong platform. For example, referred x64 assembly build under x86 and in the consumer code are trying to call specific function. Because, of this mixed platformed assemblies, reference calculation is resulting in x00000005 or xFFFFFFFF kind of location, which is restricted area in side RAM (i.e. OS part). Hence, it's throwing exception having message like "Access Violation exception reading location...". The solution I found is to identify and apply exact platform to relevant project. I retrieved entirely fresh code from the repo again and build under specific platform and this issue disappeared.
I was building a 10-year-old project with debug set as x64. When I changed to x86 for debug and Win32 in the configuration manager the "ntdll.dll can't find" error went away. Remaining issue is that malloc/free throws a runtime error is some places but not in others. Change to new/delete formats solved this issue.

Identify exact line on which application got crashed?

How can I identify exact line of program on which my application crashed? Is there any tool to tell me which line in which source file has crashed the application?
I am using C/C++, MFC, and VC++.
Use gdb to see where your application crash. For linux, use gdb --args (Application command line)
use breakpoints for stepping into various functions. And if you run into crash, use bt to backtrace the code.
Though there are many many things in gdb, my aim was to give just the pointer, where you can begin.
For run time (non-debugger attached) exceptions I like using "BOOST_EXCEPTIONS" because the BOOST_THROW_EXCEPTION macro attaches BOOST_CURRENT_FUNCTION, FILE and LINE to the exception.
But the best way is to compile in debug mode and run with a debugger attached. If you're using visual studio (which with VC++, you probably already are) move to debug mode and run it. When an un-handled exception is thrown, it should bring you right there.
If you want to catch handled exceptions, from the Menu bar, Debug->Exceptions. Checking all of these will make the exceptions caught by the debugger, even when they are handled. Though people using exceptions for non-fatal errors can make this SUPER ANNOYING...
It depends a lot by what you mean by 'crash'. But assuming that you mean an exception occured in your app, then the EXCEPTION_RECORD structure will contain the exact address where the exception occurred, in other words the IP that was executed when the exception was raised. On Windows C++ exception use SEH. Read the timeless A Crash Course on the Depths of Win32™ Structured Exception Handling to understand SEH.
You can retrieve the exception info from a crash dump (see ecxr Display Exception Context Record) or you can instruct debuggers to break on exception. Dr. Watson will create dumps for you when crash occurs.

Why catch an Access Violation?

Unlike C++ exceptions, an Access Violation indicates your applications runtime is compromised and the state of your application is, therefore, undefined. The best thing to do in that circumstance is to exit your application (generally done for you because it crashes).
I note that it is possible to catch one of these exceptions. In Microsoft Visual C++, for example, you can use /EHa or __try/__catch to do so.
So, what are the reasons you would want to catch them? As I understand it, there's no way for your application to recover.
You can recover from an access violation.
For example, you can create a dynamic array by allocating some address space with VirtualAlloc, but marking the memory it points at as not-present. Then, when you attempt to use some memory, you catch the access violation, map a page of memory where the access took place, then re-try the instruction that caused the violation.
One reason might be to write a crash dump file; you would have more control over it and be able to write the exact type you wanted. In Windows, for example, you could call MiniDumpWriteDump to do this.
Your app is not guaranteed to be stable after all access violations. But it can be stable or recover after some, so catching the access violation gives you the opportunity to:
Inform the user something went bad
Let the user attempt to save work
Attempt to recover
Log diagnostic information
Exit in the way you want, rather than disappearing.
A typical example of this is a host application that catches exceptions from a plugin. This way the host app (Photoshop, for example) can tell the user that "Plugin X crashed, and Photoshop is unstable... you should save your work, and restart Photoshop."
Note that this is different than C++ exception handling, which does not indicate unrecoverable errors at all, but is more of a stack unwinding feature.
I think it would be better to gracefully crash and let the user know what's going on, rather than just having the application disappear.
If your application gets an access violation you may or may not be able to recover. If your application is left in an undefined state, you clobber your stack for instance, you're done.
Read from a runaway pointer probably won't corrupt your application and from that you likely can recover.
Either way, the fact that it is occurring indicates a bug in your code so instead of trying to recover you should catch the error and dump what state you can to help you debug the problem.

What prevents an exception from being caught?

I have a Win32 C++ app developed in VS2005. There is a try {} catch (...) {} wrapped around a block of code, and yet 3 functions deep, when the algorithm breaks down and tries to reference off the end of a std::vector, instead of catching the exception, the program drops into the VS debugger, tells me I have an unhandled win32 exception, and the following is found on the call stack above my function:
msvcr80.dll!:inavlid_parameter_noinfo()
msvcr80.dll!:invoke_watson(....)
msvcr80.dll!:_crt_debugger_hook(...)
How can I prevent the debugger being called? This occurs at the end of a 30 minute simulation, at which point I lose all my results unless I can catch and log the exception. This and similar try/catch constructs have been working in the past - are there compiler settings which affect this? Help?
You may want to convert non-C++ exceptions into C++ exceptions. Here's an example of how to do it.
Apologies for the delay - unforeseen circumstances - but the real answer appears to be the following.
First, the application is also wrapped in a __try {} __except () {} construct, and uses unhandled exception filtering based on XCrashReport. This picks up the non C++ exceptions for the reasons many have pointed out above.
Second, however, as one can find here and elsewhere, since CRT 8.0, for security reasons Microsoft bypasses unhandled exception handling on buffer overruns (and certain other situations), and passes the issue directly to Dr Watson.
This is really annoying - I want to know where my buffer overruns are occurring, and why, and to fix them. I also want my program to crash, leave an audit trail, and then be automatically restarted, 24/7. Having MS Visual Studio on the PC seems to mean that Dr Watson will pause and offer me the option of using MSVC to debug the issue. However, until I respond to the dialog box, nothing will happen. Comments on workarounds greatly appreciated...
Just because you have a catch(...) doesn't mean you can catch and recover from all exceptions. Not all exceptions are recoverable.
You problem might be that the first exception that pin points the exact problem is getting obscured by your catch statement
You need to attach the debugger to the program and have it break on all exceptions and fix the code
Standard Library containers do not check for any logic errors and hence themselves never emit any exceptions.
Specifically, for std::vector only method that throws an exception is std::vector::at().
Any Undefined Behavior w.r.t to them will most likely lead your program to crash.
You will need to use Windows' SEH and C++ Exception Handling for catching Windows specific exceptions, which are non C++ standard btw.

Why won't my code segfault on Windows 7?

This is an unusual question to ask but here goes:
In my code, I accidentally dereference NULL somewhere. But instead of the application crashing with a segfault, it seems to stop execution of the current function and just return control back to the UI. This makes debugging difficult because I would normally like to be alerted to the crash so I can attach a debugger.
What could be causing this?
Specifically, my code is an ODBC Driver (ie. a DLL). My test application is ODBC Test (odbct32w.exe) which allows me to explicitly call the ODBC API functions in my DLL. When I call one of the functions which has a known segfault, instead of crashing the application, ODBC Test simply returns control to the UI without printing the result of the function call. I can then call any function in my driver again.
I do know that technically the application calls the ODBC driver manager which loads and calls the functions in my driver. But that is beside the point as my segfault (or whatever is happening) causes the driver manager function to not return either (as evidenced by the application not printing a result).
One of my co-workers with a similar machine experiences this same problem while another does not but we have not been able to determine any specific differences.
Windows has non-portable language extensions (known as "SEH") which allow you to catch page faults and segmentation violations as exceptions.
There are parts of the OS libraries (particularly inside the OS code that processes some window messages, if I remember correctly) which have a __try block and will make your code continue to run even in the face of such catastrophic errors. Likely you are being called inside one of these __try blocks. Sad but true.
Check out this blog post, for example: The case of the disappearing OnLoad exception – user-mode callback exceptions in x64
Update:
I find it kind of weird the kind of ideas that are being attributed to me in the comments. For the record:
I did not claim that SEH itself is bad.I said that it is "non-portable", which is true. I also claimed that using SEH to ignore STATUS_ACCESS_VIOLATION in user mode code is "sad". I stand by this. I should hope that I had the nerve to do this in new code and you were reviewing my code that you would yell at me, just as if I wrote catch (...) { /* Ignore this! */ }. It's a bad idea. It's especially bad for access violation because getting an AV typically means your process is in a bad state, and you shouldn't continue execution.
I did not argue that the existence of SEH means that you must swallow all errors.Of course SEH is a general mechanism and not to blame for every idiotic use of it. What I said was that some Windows binaries swallow STATUS_ACCESS_VIOLATION when calling into a function pointer, a true and observable fact, and that this is less than pretty. Note that they may have historical reasons or extenuating circumstances to justify this. Hence "sad but true."
I did not inject any "Windows vs. Unix" rhetoric here. A bad idea is a bad idea on any platform. Trying to recover from SIGSEGV on a Unix-type OS would be equally sketchy.
Dereferencing NULL pointer is an undefined behavior, which can produce almost anything -- a seg.fault, a letter to IRS, or a post to stackoverflow :)
Windows 7 also have its Fault Tollerant Heap (FTH) which sometimes does such things. In my case it was also a NULL-dereference. If you develop on Windows 7 you really want to turn it off!
What is Windows 7's Fault Tolerant Heap?
http://msdn.microsoft.com/en-us/library/dd744764%28v=vs.85%29.aspx
Read about the different kinds of exception handlers here -- they don't catch the same kind of exceptions.
Attach your debugger to all the apps that might call your dll, turn on the feature to break when an excption is thrown not just unhandled in the [debug]|[exceptions] menu.
ODBC is most (if not all) COM as such unhandled exceptions will cause issues, which could appear as exiting the ODBC function strangely or as bad as it hang and never return.