how application handle exception in try catch in disassembly - c++

Hi
I am debugging such a program that call win32 api RaiseException().
I want to know how can i handle it manually not by debugger.
Tanx

Try reading up on Structured Exception Handling. Then check out Matt Pietrek's article: A Crash Course on the Depths of Win32™ Structured Exception Handling.

Related

Can I view an unhandled exception in the Visual Studio 2017 Debugger?

A library I am using (zmq) throws an exception. The debugger breaks and informs me.
How, if possible, can I see this exception. Specifically the what() message?
Without having to place try/catch around it and printing to the output stream.
It does not appear in the Autos or Locals watch lists. I have searched the stack frames around the point at which it occured.
Adding $exception to a manual watch list simply returns a value of "identifier $exception is undefined"
Using memory explorer to interrogate the exception's location does not show anything useful.
I have read this can be done when using the CLR - can I do it in regular C++?
Referencing this answer:
You'll get a window when the exception is thrown with the option to break/continue/ignore. Copy and paste the hex address this dialog reports, then click the break button. Now in a watch window, enter something like:
(std::exception*)0xXXXXXXXX
(1) Please check that whether the Exception messages was enabled in the output window under Tools->Options->Debugging->Output window.
(2)If it still no exception messages, one possible reason is that zmq really doesn't support the Exception throw feature of VS. Of course, you could write a general app like C# or VC++ which can prove it. If other apps have no this issue, we would think about the specific zmq.
Step 1. Identify the exception (it would be logged in the output window in VS)
Step 2. Put an exception breakpoint with the exception you saw from the output.
If this is ZeroMQ, I'd wager you're Sending 2 requests on a REQ socket without waiting for a reply.
your output window
(View/Output or click CTRL + ALT + O)
is where you should see the message, but you may need to check the exceptions option:
Look here for more detail
As far as I'm aware, this isn't currently possible. I've added a User Voice suggestion here but I'm not sure when, if ever, Microsoft will implement this feature.
For now, what you can do is take the Type and Location of the exception (from the message 'Exception thrown at Address in Module: Microsoft C++ exception: Type at memory location Location.', and then add to the Watch window the expression '(Type*)Location'. If Type is some internal exception type that you don't have access to, then you can hope it derives from std::exception and cast to that instead.

C++ / WIndows - Can't catch exceptions

I'm a beginner with the windows api so there must be something i don't understand here. In my main function i'm using a try-catch to catch all uncaught exceptions, but for some reason, exceptions i throw from somewhere else in the code are never caught. My application uses a single (main) thread.
I'm throwing like this :
throw "ClassName::methodName() - Error message";
And catching the exceptions outside of the message loop :
try {
while(GetMessage(args...)) {
TranslateMessage(args...);
DispatchMessage(args...);
}
}
catch( const char * sExc ) {
::MessageBox(args...);
}
I first thought it was a problem of types mismatching, but then i added a catch(...) with ellipsis and i still caught nothing. If you ask, yes, i'm sure the exception is thrown. Isn't it a problem related to some kind of asynchronousness or something like that ?
Thanks for your help !
It depends on the specific message that's getting dispatched. But no, not all of them allow the stack to be unwound through Windows internal code. Particularly the messages that involve the window manager, WM_CREATE for example. There's a backstop inside Windows that prevents the stack from being unwound past that critical code. There's also an issue with exceptions in 32-bit code that run on the 64-bit version of Windows 7, they can get swallowed when the message needs to traverse the Wow64 boundary several times. Fixed in Windows 8.
On later Windows versions this can also activate "self-healing" code, automatically activating an appcompat shim that swallows the exception. You'll get a notification for that, easy to dismiss. You'll then see the first-chance exception notification in the VS Output window but your program keeps running. Okayish for the user perhaps but not great while you are debugging of course. Run Regedit.exe and navigate to HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant\Persisted and check if your program is listed there. Just delete the entry.
Long story short, it is not safe to catch exceptions outside of the message loop. You have to do it inside the window procedure.
You are talking about "Windows Structured Exception Handling" (http://msdn.microsoft.com/en-us/library/windows/desktop/ms680657%28v=vs.85%29.aspx). C++ exceptions are not thrown.
If you want to go the troublesome route: _set_se_translator
See also: Can a C program handle C++ exceptions? (The windows API is not C++)

First-chance exception with Pantheios

My app was running fine until I tried to debug it with the Application Verifier. After that I started getting "First-chance exception... : An invalid handle was specified" and the issue seems to be in the "bailout.c" file in Pantheios:
hFile = CreateFileA("logging-bailout.txt"
, GENERIC_WRITE
, 0
, NULL
, OPEN_ALWAYS
, 0
, NULL); <--- this is where it crashes, line 442
And message:
First-chance exception at 0x7769f8cd in myapp.exe: 0xC0000008: An invalid handle was specified.
=======================================
VERIFIER STOP 0000000000000300: pid 0x3814: Invalid handle exception for current stack trace.
00000000C0000008 : Exception code.
00000000111DE950 : Exception record. Use .exr to display it.
00000000111DE460 : Context record. Use .cxr to display it.
0000000000000000 : Not used.
=======================================
This verifier stop is continuable.
After debugging it use `go' to continue.
=======================================
Before the console just logged the exceptions that I got with Pantheios and I didnt really care too much about. However, now when the app crashes on the first occurrence of logging using Pantheios it's time for me to deal with this, but I'm not too sure sure how to.
I was following this guide when setting up my Pantheios: http://www.codeproject.com/Articles/27119/Using-Callback-Back-ends-with-the-Pantheios-Loggin
In every file I have logging I have the following lines in the source file:
#include <pantheios/pantheios.hpp>
#include <pantheios/inserters/boolean.hpp>
#include <pantheios/inserters/integer.hpp>
#include <Shared/logs.h>
logs.h contains:
#include <pantheios/implicit_link/core.h>
#include <pantheios/implicit_link/fe.simple.h>
#include <pantheios/implicit_link/be.WindowsConsole.h>
I also call pantheios::init(); before doing any logging.
I'm using Visual studio 2010 and are including the following lib-files under "Additional Dependencies":
$(PANTHEIOS_ROOT)\lib\pantheios.1.core.vc10.mt.debug.lib
$(PANTHEIOS_ROOT)\lib\pantheios.1.be.WindowsConsole.vc10.mt.debug.lib
$(PANTHEIOS_ROOT)\lib\pantheios.1.fe.simple.vc10.mt.debug.lib
$(PANTHEIOS_ROOT)\lib\pantheios.1.util.vc10.mt.debug.lib
However, all my logging looks like this:
First-chance exception at 0x750bb9bc in myapp.exe: Microsoft C++ exception: stlsoft::winstl_project::windows_exception at memory location 0x1822bda0..
20120423-104817.497: failed to write message to log file; given message follows: [myapp.Qt.Framework.13424, 23/04/2012 10:48:17.496 a.m.; Debug]: "some logging"
when calling pantheios::log(pantheios::debug, "some logging");
Then, all my logging is written to a "bailout"file in the same folder as the project. This worked before but it was a big bullet on my "To-do-list" (but a bit further down than other things).
So now my question is, how do I fix this? Followed every tutorial I can find but with no success. And why did my app decide to not accept this anymore after running the Ms Application Verifier? Makes no sense.
First chance exceptions mean only that an exception was thrown. It does not mean you have a bug in your program, just that the debugger is showing you that an exception is being thrown, so you have a chance to examine it before it is propagated up the call chain. If the exception is caught by an exception handler (e.g. for logging), your application continues, otherwise the debugger gives you a second-chance exception notification to inform you that the application will exit due to an unhandled exception.
If you do not want to receive the first-chance exception notifications, you can turn it off in your debugger. This link may help on how to turn off exception handling in Application Verifier.
To work around this problem, turn off exceptions testing in Application Verifier. To do this, follow these steps:
1.Start Application Verifier.
2.Under Applications, click the GDI+ program that you want to test.
3.Under Tests, expand Basics.
4.Click to clear the Exceptions check box.
5.Run the GDI+ program that you want to test.
You can also configure the debugging tool to make sure that you do not experience a breakpoint in the debugging tool when an access violation occurs.
The alternative (turning off exception notification in MSVS) is via "Debug->Exceptions..."
Alternatively, if it is possible, make sure the exception does not get thrown in the first place. You will need to examine the nature of the exception (e.g. file not found) and fix the condition that is preventing the intended operation.
Given the nature/purpose of Application Verifier, I would suggest the latter approach: AV is telling you that something incorrect is going on that might have been ok previously, but can cause problems later on (depending on enviornment, circumstances, etc.)

64bit exceptions in WndProc silently fail

The following code will give a hard fail when run under Windows 7 32bit:
void CTestView::OnDraw(CDC* /*pDC*/)
{
*(int*)0 = 0; // Crash
CTestDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: add draw code for native data here
}
However, if I try this on Windows 7 64bit, I just get this in the output window:
First-chance exception at 0x13929384
in Test.exe: 0xC0000005: Access
violation writing location 0x00000000.
First-chance exception at 0x77c6ee42
in Test.exe: 0xC0150010: The
activation context being deactivated
is not active for the current thread
of execution.
What is the reason for this? I know it's a hardware exception (http://msdn.microsoft.com/en-us/library/aa363082.aspx), but why the difference when ran under 32bit and 64bit? And what can I do to correctly handle these kind of errors? Because they should really be trapped and fixed, as opposed to what currently happens which is Windows just carries on pumping messages to the application and let's it run (so the user and the developers are completely unaware any problems have actually occurred).
Update:
Our regular crash reporting software uses SetUnhandledExceptionFilter but that doesn't get called on x64 for hardware exceptions inside a WndProc. Does anyone have any information on this, or a workaround?
Update2:
I've reported the issue at Microsoft Connect:
https://connect.microsoft.com/VisualStudio/feedback/details/550944/hardware-exceptions-on-x64-machines-are-silently-caught-in-wndproc-messages
There's another exception being raised while the stack is being unwound for the Access Violation exception. Which is being swallowed, causing the AV to disappear. You'll need to find out what code is doing this. Debug + Exceptions, check the Thrown box for Win32 Exceptions. The debugger will stop on the first one, continue. Check out the call stack when it stop again. Add it to your question if you can't figure it out.
OK, I've received a reply from Microsoft:
Hello,
Thanks for the report. I've found out
that this is a Windows issue, and
there is a hot fix available. Please
see
http://support.microsoft.com/kb/976038
for a fix that you can install if you
wish.
#Skute: note that the Program
Compatibility Assistant will ask once
if the program should be allowed to
continue to execute, and after that it
will always be allowed, so that may be
the cause of the confusing behavior
you are seeing.
Pat Brenner Visual C++ Libraries
Development
So the workaround is either make sure the hotfix is installed, or wrap each WndProc in your application with a __try / __except block.
The only way we've managed to work around this problem is to put a __try / __except around each WndProc callback in the application. We then route the exception to our exception handler. Horrible, but looks like it's a problem with Windows itself. Still waiting on Microsoft to get back to us.
I would venture a guess that the problem is actually related to how SEH works in x64. If your exception has to go back up through kernel-mode while the stack is unwinding, then what you're stuck with is by-design behavior: The case of the disappearing OnLoad exception. Windows is "handling" your exception for you; the hot-fix is a workaround to make specific x64 apps crash just like x86 does.
I did some homework to find this:
the exception is caught by windows. Here are stacks and disassembling:

How can I debug a win32 process that unexpectedly terminates silently?

I have a Windows application written in C++ that occasionally evaporates. I use the word evaporate because there is nothing left behind: no "we're sorry" message from Windows, no crash dump from the Dr. Watson facility...
On the one occasion the crash occurred under the debugger, the debugger did not break---it showed the application still running. When I manually paused execution, I found that my process no longer had any threads.
How can I capture the reason this process is terminating?
You could try using the adplus utility in the windows debugging tool package.
adplus -crash -p yourprocessid
The auto dump tool provides mini dumps for exceptions and a full dump if the application crashes.
If you are using Visual Studio 2003 or later, you should enable the debuggers "First Chance Exception" handler feature by turning on ALL the Debug Exception Break options found under the Debug Menu | Exceptions Dialog. Turn on EVERY option before starting the debug build of the process within the debugger.
By default most of these First Chance Exception handlers in the debugger are turned off, so if Windows or your code throws an exception, the debugger expects your application to handle it.
The First Chance Exception system allows debuggers to intercept EVERY possible exception thrown by the Process and/or System.
http://support.microsoft.com/kb/105675
All the other ideas posted are good.
But it also sounds like the application is calling abort() or terminate().
If you run it in the debugger set a breakpoint on both these methods and exit() just for good measure.
Here is a list of situations that will cause terminate to be called because of exceptions going wrong.
See also:
Why destructor is not called on exception?
This shows that an application will terminate() if an exceptions is not caught. So stick a catch block in main() that reports the error (to a log file) then re-throw.
int main()
{
try
{
// Do your code here.
}
catch(...)
{
// Log Error;
throw; // re-throw the error for the de-bugger.
}
}
Well, the problem is you are getting an access violation. You may want to attach with WinDBG and turn on all of the exception filters. It may still not help - my guess is you are getting memory corruption that isn't throwing an exception.
You may want to look at enabling full pageheap checking
You might also want to check out this older question about heap corruption for some ideas on tools.
The most common cause for this kind of sudden disappearance is a stack overflow, usually caused by some kind of infinite recursion (which may, of course, involve a chain of several functions calling each other).
Is that a possibility in your app?
You could check the Windows Logs in Event Viewer on Windows.
First of all I want to say that I've only a moderate experience on windows development.
After that I think this is a typical case where a log may help.
Normally debugging and logging supply orthogonal info. If your debugger is useless probably the log will help you.
This could be a call to _exit() or some Windows equivalent. Try setting a breakpoint on _exit...
Have you tried PC Lint etc and run it over your code?
Try compiling with maximum warnings
If this is a .NET app - use FX Cop.
Possible causes come to mind.
TerminateProcess()
Stack overflow exception
Exception while handling an exception
The last one in particular results in immediate failure of the application.
The stack overflow - you may get a notification of this, but unlikely.
Drop into the debugger, change all exception notifications to "stop always" rather than "stop if not handled" then do what you do to cause the program failure. The debugger will stop if you get an exception and you can decide if this is the exception you are looking for.
I spent a couple hours trying to dig into this on Visual Studio 2017 running a 64-bit application on Windows 7. I ended up having to set a breakpoint on the RtlReportSilentProcessExit function, which lives in the ntdll.dll file. Just the base function name was enough for Visual Studio to find it.
That said, after I let Visual Studio automatically download symbols for the C standard library, it also automatically stopped on the runtime exception that caused the problem.