Program crashes with 0xC000000D and no exceptions - how do I debug it? - c++

I have a Visual C++ 9 Win32 application that uses a third-party library. When a function from that library is called with a certain set of parameters the program crashes with "exception code 0xC000000D".
I tried to attach Visual Studio debugger - no exceptions are thrown (neither C++ nor structured like access violations) and terminate() is not called either. Still the program just ends silently.
How does it happen that the program just ends abnormally but without stopping in the debugger? How can I localize the problem?

That's STATUS_INVALID_PARAMETER, use WinDbg to track down who threw it (i.e. attach WinDbg, sxe eh then g.

Other answers and comments to the question helped a lot. Here's what I did.
I notices that if I run the program under Visual Studio debugger it just ends silently, but if I run it without debugger it crashes with a message box (usual Windows message box saying that I lost my unsaved data and everyone is sooo sorry).
So I started the program wihtout debugger, let it crash and then - while the message box was still there - attached the debugger and hit "Break". Here's the call stack:
ntdll.dll!_KiFastSystemCallRet#0()
ntdll.dll!_ZwWaitForMultipleObjects#20() + 0xc bytes
kernel32.dll!_WaitForMultipleObjectsEx#20() - 0x48 bytes
kernel32.dll!_WaitForMultipleObjects#16() + 0x18 bytes
faultrep.dll!StartDWException() + 0x5df bytes
faultrep.dll!ReportFault() + 0x533 bytes
kernel32.dll!_UnhandledExceptionFilter#4() + 0x55c bytes
//SomeThirdPartyLibraryFunctionAddress
//SomeThirdPartyLibraryFunctionAddress
//SomeThirdPartyLibraryFunctionAddress
//SomeThirdPartyLibraryFunctionAddress
//OurCodeInvokingThirdPartyLibraryCode
so obviously that's some problem inside the trird-party library. According to MSDN, UnhandledExceptionFilter() is called in fatal situations and clearly the call is done because of some problem in the library code. So we'll try to work the problem out with the library vendor first.

If you don't have source and debugging information for your 3rd party library, you will not be able to step into it with the debugger. As I see it, your choices are;
Put together a simple test case illustrating the crash and send it onto the library developer
Wrap that library function in your own code that checks for illegal parameters and throw an exception / return an error code when they are passed by your own application
Rewrite the parts of the library that do not work or use an alternative
Very difficult to fix code that is provided as object only
Edit You might also be able to exit more gracefully using __try __finally around your main message loop, something like
int CMyApp::Run()
{
__try
{
int i = CWinApp::Run();
m_Exitok = MAGIC_EXIT_NO;
return i;
}
__finally
{
if (m_Exitok != MAGIC_EXIT_NO)
FaultHandler();
}
}

Related

MATLAB API for C exception using matGetDir: matrix::serialize::EndOfFile at memory location

I try to read a mat file in a c++ Visual Studio 2017 project on Windows 7. I use the MATLAB API for C from Matlab R2017b.
I am able to run the matdgns.c example in Matlab using mex.
It's also possible to run the application in my c++ project and open the mat file using
pmat = matOpen(file, "r");
However, when I try to read the array list using matGetDir
dir = (const char **)matGetDir(pmat, &ndir);
I get an exception:
Exception thrown at 0x000007FEFCF4A06D in project_gTest.exe:
Microsoft C++ exception: matrix::serialize::EndOfFile at memory
location 0x000000000031F1D0.
How can I solve this issue? Am I missing another library?
Thank you!
I received the following answer from Matlab support which "solves" the "issue":
I assume that this Exception which you "get" is basically just a line of text shown in the "Output" Window of Microsoft Visual Studio 2017, right? And this is not actually crashing your application, correct?
If that is indeed the case, please note that MSVS 2017 does in fact show first chance exceptions in "Output". If such an exception is caught and handled, where in this particular case I do expect that the MATLAB libraries handled this, there is no actual issue though. It is perfectly valid to throw exceptions and then handle them. Only unhandled (second chance) exceptions would lead to real problems.
It should normally be perfectly safe to ignore that line which is shown in the Output and it is in fact expected that this Exception is thrown (and caught internally) when working with matGetDir.

Qt SIGABRT alternative message?

I'm using Qt5.9, a simple check:
assert(pobjNode != NULL);
Will cause the Qt Signal Received error dialog to be displayed which doesn't give any helpful information about where the problem is or what it is.
Is there a way to replace this useless information with something a bit more helpful?
What I'm thinking of is a way to set-up the dialog to display what could be an error in the event of an error.
Q_ASSERT is a custom assert macro which supposedly enhances the standard assert function.
The error message is handled by qFatal(), which can behave slightly better on some platforms than the standard assert macro. For example on Windows it will trigger the Visual Studio debugger at the point where the assertion fails instead of just calling abort().
You can also redirect the output of Qt error message functions such as qFatalto your custom message handler ( with qInstallMessageHandler() ). It can be useful for example if you want to redirect the errors message to a file.
Also note that Q_ASSERT is disabled with the macro QT_NO_DEBUG(while assert is disabled by NDEBUG) : this can be used to separate your asserts between Qt-related code and the rest.
Q_ASSERT_X Prints the message what together with the location where, the source file name and line number if test is false.
Prints the message what together with the location where, the source file name and line number if test is false.
Example:
// File: div.cpp
#include <QtGlobal>
int divide(int a, int b)
{
Q_ASSERT_X(b != 0, "divide", "division by zero");
return a / b;
}
to read more on test and debug.
You might define your own MY_ASSERT macro. On Linux it could even call another function which uses Glibc backtrace functions or Ian Taylor's libbacktrace library (provided your code is compiled with DWARF debug information using g++ -g) and perhaps display such information in a modal dialog, or on stderr. However, it should probably not return. Read also about Qt and Unix signals and signal-safety(7).
But assert detects a bug which you should correct. Try hard to avoid shipping code with such programmer bugs.
On Linux, the usual assert -it is a macro defined in /usr/include/assert.h- will call on failure __assert_fail (in your C library, but you might redefine it yourself) which would indirectly call abort which indirectly makes a core dump which you can inspect post-mortem using the gdb debugger. You only need to enable core dumps (using ulimit -c builtin in your bash terminal).

static lib call error: Exception: "A null reference pointer was passed to the stub." (using winsock2 Win32)

I created a windows-console application that works fine but trying to use Winsock2 (Ws2_32.lib) in another static-library (as part of a larger project) throws an exception.
The code compiles fine and the exe runs all is well, calls to WSAStartup() and gethostbyname() work as expected but then calling gethostbyname()
causes :
First-chance exception at 0x76e1c41f in TestApp.exe: 0x000006F4: A null reference pointer was passed to the stub.
which leads to:
First-chance exception at 0x7505cd99 (rpcrt4.dll) in TestApp.exe: 0xC0020043: An internal error occurred in RPC.
Ive double checked the calling code is the same and checked that the correct versions of the *.h *.dll and *.lib are being used by the linker - as far as i can tell they are.
I've compared the project settings for the two apps and cant see anything out of the ordinary.
Ive also made sure that all the libraries in the Project are using the same Character-Set.
[EDIT : chages after discovering the difference in the two apps is just the debugger exceptions being turned on or not ]
I can continue past the exceptions and the code appears to run, but I no longer have valid debugging symbols in the function. It isnt a crash but of course id rather not have the exceptions every time I call the function - I can obviously turn the exception-breaks off but aren't they there to tell me something is wrong ?
I am currently trying to get the up-to-date symbols for the ws2_32.lib and other modules from the MSDN symbol server / SymChk.exe
[EDIT 2 - finally got symbols for the stack]
> rpcrt4.dll!_NdrClientCall2() + 0x301 bytes
FWPUCLNT.DLL!_FwppProxyEngineOpen#24() + 0x19 bytes
FWPUCLNT.DLL!_FwppSessionCreate#20() + 0xd1 bytes
FWPUCLNT.DLL!_FwpmEngineOpen0#20() + 0x29 bytes
FWPUCLNT.DLL!_FwpIsNameCacheEnabledForProcess#4() + 0x7778 bytes
FWPUCLNT.DLL!_FwpmProcessNameResolutionEvent0#16() + 0x74 bytes
FWPUCLNT.DLL!_NamespaceCallout#12() + 0x72 bytes
ws2_32.dll!PrepareNamespaceCalloutBlob() + 0x153 bytes
ws2_32.dll!getxyDataEnt() + 0x74a7 bytes
ws2_32.dll!_gethostbyname#4() + 0xe7 bytes
I was getting this exception "0x000006F4: A null reference pointer was passed to the stub."
Turns out disabling my 3rd party firewall stopped the exception being thrown. Perhaps the firewall is intercepting the request and messing something up.
Might be worth a try for you :)

Make main() "uncrashable"

I want to program a daemon-manager that takes care that all daemons are running, like so (simplified pseudocode):
void watchMe(filename)
{
while (true)
{
system(filename); //freezes as long as filename runs
//oh, filename must be crashed. Nevermind, will be restarted
}
}
int main()
{
_beginThread(watchMe, "foo.exe");
_beginThread(watchMe, "bar.exe");
}
This part is already working - but now I am facing the problem that when an observed application - say foo.exe - crashes, the corresponding system-call freezes until I confirm this beautiful message box:
This makes the daemon useless.
What I think might be a solution is to make the main() of the observed programs (which I control) "uncrashable" so they are shutting down gracefully without showing this ugly message box.
Like so:
try
{
char *p = NULL;
*p = 123; //nice null pointer exception
}
catch (...)
{
cout << "Caught Exception. Terminating gracefully" << endl;
return 0;
}
But this doesn't work as it still produces this error message:
("Untreated exception ... Write access violation ...")
I've tried SetUnhandledExceptionFilter and all other stuff, but without effect.
Any help would be highly appreciated.
Greets
This seems more like a SEH exception than a C++ exception, and needs to be handled differently, try the following code:
__try
{
char *p = NULL;
*p = 123; //nice null pointer exception
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
cout << "Caught Exception. Terminating gracefully" << endl;
return 0;
}
But thats a remedy and not a cure, you might have better luck running the processes within a sandbox.
You can change the /EHsc to /EHa flag in your compiler command line (Properties/ C/C++ / Code Generation/ Enable C++ exceptions).
See this for a similar question on SO.
You can run the watched process a-synchronously, and use kernel objects to communicate with it. For instance, you can:
Create a named event.
Start the target process.
Wait on the created event
In the target process, when the crash is encountered, open the named event, and set it.
This way, your monitor will continue to run as soon as the crash is encountered in the watched process, even if the watched process has not ended yet.
BTW, you might be able to control the appearance of the first error message using drwtsn32 (or whatever is used in Win7), and I'm not sure, but the second error message might only appear in debug builds. Building in release mode might make it easier for you, though the most important thing, IMHO, is solving the cause of the crashes in the first place - which will be easier in debug builds.
I did this a long time ago (in the 90s, on NT4). I don't expect the principles to have changed.
The basic approach is once you have started the process to inject a DLL that duplicates the functionality of UnhandledExceptionFilter() from KERNEL32.DLL. Rummaging around my old code, I see that I patched GetProcAddress, LoadLibraryA, LoadLibraryW, LoadLibraryExA, LoadLibraryExW and UnhandledExceptionFilter.
The hooking of the LoadLibrary* functions dealt with making sure the patching was present for all modules. The revised GetProcAddress had provide addresses of the patched versions of the functions rather than the KERNEL32.DLL versions.
And, of course, the UnhandledExceptionFilter() replacement does what you want. For example, start a just in time debugger to take a process dump (core dumps are implemented in user mode on NT and successors) and then kill the process.
My implementation had the patched functions implemented with __declspec(naked), and dealt with all the registered by hand because the compiler can destroy the contents of some registers that callers from assembly might not expect to be destroyed.
Of course there was a bunch more detail, but that is the essential outline.

process termination C++

I have the following problem: I have an application (server that never ends) written in C++ running as a service containing inside the main thread also 3 threads (mainly doing IO).
In the main loop I CATCH all possible exceptions.
The process terminated and nothing was printed either by the main loop or by the threads themselves. I saw in the event log that the process stopped with code 1000.
Does Windows creates Core files like in unix ?
If from the event log I get a memory address, is there any way of knowing in which part in the application it occurred?
Maybe this is a clue: at the same time that it happened I started another application (not the same type).
try to set windbg as the postmortem debugger.
install windbg
from commandline execute "windbg -I"
start you application, then you when your application get an unhandled exception,
the windbg will be activated .
from windbg use "kb" or "!uniqstack" to see the stacktrace.
look here for more commands.
and look here for how to analysis.
and try use SEH:
#include "windows.h"
#include "stdio.h"
DWORD FilterFunction()
{
printf("you will see this message first.\n");
return EXCEPTION_EXECUTE_HANDLER;
}
int main(char** argv, int c)
{
__try
{
int this_will_be_zero = (c == 9999);
int blowup = 1 / this_will_be_zero;
}
__except ( FilterFunction())
{
printf("you will see this message\n");
}
return 0;
}
Bear in mind that catch(...) does not intercept everything that can go wrong in your code, unless you are using Structured Exception Handling. Eg
#include "stdio.h"
int main(char** argv, int c)
{
try {
int this_will_be_zero = (c == 9999);
int blowup = 1 / this_will_be_zero;
} catch (...) {
printf("you won't see this message\n");
}
}
You need to use the /EHa compiler switch when building your application in order to catch windows structured exceptions (such as access violation) with the C++ try/catch constructs.
In Visual Studio this is in project properties Configuration Properties -> C/C++ -> Code Generation -> Enable C++ Exceptions. You want "Yes With SEH Exceptions (/EHa)". I remember reading setting this has some significant drawbacks, although I cannot recall what they were exactly.
Link: MSDN on C++ exception handling model
Edit: As whunmr suggests, directly using structured exceptions is probably better idea than /EHa
Does Windows creates Core files like in unix ?
it does not, automatically. however you can enable such a files by
either implementing it in your code or by using external application
as windbg, or Dr. Watson
If from the event log I get a memory address, is there any way of knowing in which part in the application it occurred?
There is no way if in general, if you don't keep debug information files (pdb)
Maybe this is a clue: at the same time that it happened I started another application (not the same type).
this is not helpful information, unless both of the applications are interacted each other
Windows will whatever program you are using as a debugger depending on the setting in:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug]
"Auto"="0"
"Debugger"="My_Debugger" -p %ld -e %ld"
"UserDebuggerHotKey"=dword:00000000
You can change My_Debugger to the full path of whatever program/IDE you are using for debugging.
This is often set to Dr Watson which will create a log entry of the crash which is not what you want.