Invalid Handle (Using the Application Verifier) - c++

I have a problem I just can't find information for. The following code is causing the issue (I have left out a lot of code for brevity, but as I will explain, this code seems to work fine):
mHDC = GetDC(mHWnd);
int format = ChoosePixelFormat(mHDC, &pixelFormat);
SetPixelFormat(mHDC, format, &pixelFormat);
mHGLRC = wglCreateContext(mHDC);
wglMakeCurrent(mHDC, mHGLRC);
mHWnd is obtained through CreateWindow()
const HINSTANCE hInstance(static_cast<HINSTANCE>(::GetModuleHandle(NULL)));
mHWnd = CreateWindow(wndClass.lpszClassName, L"Test Application", style, CW_USEDEFAULT, CW_USEDEFAULT, clientRect.right, clientRect.bottom, NULL, NULL, hInstance, NULL);
ChoosePixelFormat() is causing an invalid handle first-chance exception in the debugger when I am using the Application Verifier with only Handles and Cuzz enabled. These two together cause the exception to trigger. Without both of these enabled (even if I just do one or the other), the exception isn't thrown and everything works okay. When I run the application without attaching to the debugger, the application crashes instead.
Even though the exception is raised, once I hit wglMakeCurrent() (by continuing debugging after and ignoring the exception), all the variables seem to end up with valid values anyway:
mHWnd == 0x1a1064e
mHDC == 0x440119c0
format == 7
mHGLRC == 0x10000
The stack trace looks like this:
ntdll.dll!00000000772012f7()
vfbasics.dll!000007feedaa81b4()
KernelBase.dll!000007fefd1610dc()
vfbasics.dll!000007feedaa7ce9()
vfcuzz.dll!000007fee5075179()
nvoglv64.dll!000000006979b732()
vfbasics.dll!000007feedaac1d5()
kernel32.dll!0000000076fa652d()
ntdll.dll!00000000771dc521()
And the active thread is a vfcuzz.dll thread, which is obviously allowing Cuzz to do it's business. vfbasics.dll in the stack trace is where the handle checker is, and as I said, only the handle checker is enabled.
For completion sake, here is the actual exception message:
First-chance exception at 0x00000000772012F7 (ntdll.dll) in Tests.exe: 0xC0000008: An invalid handle was specified.
I am assuming it isn't a bug in the Application Verifier that is causing it to throw an exception that shouldn't exist and crashing the program. I am just confused as to why it is throwing the exception when clearly I am getting valid values back from the function calls. I don't really want to ignore it until I understand what is going on.

It doesn't look like a problem with your code. The only handle ChoosePixelFormat takes is an HDC and the one you're giving it is presumably valid (although in the code you're showing there's no checking that GetDC succeeded, I assume you just left that out for brevity).
A first-chance exception isn't necessarily a problem. It simply means an exception occurred, and this is the first chance to handle it. My guess is the exception is most likely happening within the ChoosePixelFormat function itself (or within a function that ChoosePixelFormat calls) and being handled there - it's only because you are debugging that you actually find out about it. In every day usage the exception would be handled quietly and you'd never even know it had happened.

Related

Exception thrown: read access violation. std::shared_ptr<>::operator-><,0>(...)->**** was 0xFFFFFFFFFFFFFFE7

Good afternoon to all! I am writing a game engine using OpenGL + Win32 / GLFW. Therefore, I will say the project is large, but I have a problem that has led me to a dead end and I can't understand what the problem is. The problem is that I have a shared_ptr<Context> in the 'windows' class (it is platform-based) that is responsible for the context (GL, D3D). And everything works fine when I launch the application, everything is drawn normally, but when I start entering the cursor into the window, a crash occurs when any function calls from context, in my case is:
context->swapBuffers();
Here a crash:
std::shared_ptr<Context>::operator-><Context,0>(...)->**** was 0xFFFFFFFFFFFFFFE7.
Then I got into the callstack and saw that the context-> itself is non-zero, so the function should be called.
Then I searched for a long time for the problem and found that when I remove the Win32 message processing code, and when I remove it, errors do not occur when calling a function from context->. I removed everything unnecessary from the loop and left only the basic functions and tried to run it like this, because I thought that some other functions inside were causing this problem, but no.
while (PeekMessageW(&msg, NULL, NULL, NULL, PM_REMOVE) > 0) {
TranslateMessage(&msg);
DispatchMessageW(&msg);
}
That is, when I delete TranslateMessage() and DispatchMessage(), the error goes away. And then I finally got confused i.e I don't understand what is happening. And then I thought that maybe somehow the operating system itself affects that pointer, prohibits reading or something like that.
And then I paid attention to __vtptr in the call stack, and noticed that it is nullptr, and moreover it has the void** type. And also the strangest thing is that in the error I have ->**** was 0xffffffffffffffc7 as many as four consecutive pointers. What is it?
I understand I practically didn't throw off the code, because I have a big project and I think it doesn't make sense to throw everything, so I tried to explain the problem by roughly showing what is happening in my code. I will be grateful to everyone who will help :)

Visual Studio Graphics Debugger throws read access violation exception

I'm writing a simple renderer using the d3d11 library in Visual Studio 2019 and it builds and runs fine. However when I try running the Graphics Debugger it immediately throws a read access violation for address 0x0000000000000000 ( which is clearly incorrect ).
The exception is thrown from the DXCaptureReplay dll on the line
DeviceContext.PSSetShader(InShaderToBind.Shader.PS, NULL, 1);
Where InShaderToBind.Shader.PS is a pointer to ID3D11PixelShader
It got the most weird when I out of a lack of ideas tried
int X = 0;
ID3D11ClassInstance* FakedClassInstance = reinterpret_cast<ID3D11ClassInstance*>(&X);
DeviceContext.PSSetShader(InShaderToBind.Shader.PS, &FakedClassInstance, 1);
As this will make the exception not throw until I try to capture a frame ( Which I guess makes sense as that pointer will only be valid for the scope where X is still valid )
The MSDN documentation states that NULL should be a perfectly valid argument to pass to PSSetShader ( as noted here: https://learn.microsoft.com/en-us/windows/win32/api/d3d11/nf-d3d11-id3d11devicecontext-pssetshader )
Any ideas for what might be going wrong?
( If I comment out PSSetShader the exception is not thrown and I can take captures )
If you enable the Direct3D Debug Device, you would see in your debug output window:
D3D11 CORRUPTION: ID3D11DeviceContext::PSSetShader: Second parameter (ppClassInstances) corrupt or unexpectedly NULL. [ MISCELLANEOUS CORRUPTION #14: CORRUPTED_PARAMETER2]
NULL (or better yet nullptr) is fine for ppClassInstances only if NumClassInstances is 0. Try:
DeviceContext.PSSetShader(InShaderToBind.Shader.PS, NULL, 0);
Generally you should make sure your program runs without emitting ERROR or CORRUPTION messages from the debug layer before attempting to use PIX or the VSGS tool.
See Microsoft Docs and this blog post.

COleDispatchDriver::Invoke in MFC app causing 61706 "Insufficient Memory" Exception using VS2013?

I have an MFC C++ application running on Win7 rebuilt with VS2013. It uses a custom OCX control. On about the 4th call to the OCX the COleDispatchDriver::InvokeHelper method calls Invoke which results an exception 61706 "Insufficient Memory". This app has been built and run successfully for many years on previous version of Visual Studio (not sure which it was originally built with). The call from the application code which generates the exception is:
m_Sig1.LCDWriteString( 0, 2, 100, 100, 0, 0, 0, "Testing 123" );
I've stepped into this call and through the Invoke about 4 levels deep and get to this call in library dll oledisp2.cpp
void COleDispatchDriver::InvokeHelperV(DISPID dwDispID, WORD wFlags,
VARTYPE vtRet, void* pvRet, const BYTE* pbParamInfo, va_list argList)
. . .
// make the call
SCODE sc = m_lpDispatch->Invoke(dwDispID, IID_NULL, 0, wFlags,
&dispparams, pvarResult, &excepInfo, &nArgErr);
The status code sc is returned as 0x80020009 which is DISP_E_EXCEPTION which means "An exception occurred" and the exception info is:
exceptInfo
wCode = 61706
bstrSource = "SigPlus"
bstrDescription = "Insufficient memory to perform operation."
bstrHelpFile = 0
scode = 0
I've tried to step into the m_lpDispatch->Invoke call but the debugger is only showing assembly language saying there is no symbol info for the called module which seems strange as it is a member of the same class (or a parent) that the call is from. As I stepped though the InvokeHelper methods I observed that all of the 8 passed parameters are recognized and processed correctly up to the point of calling Invoke(). Not being able to step into Invoke makes it impossible to see where the memory allocation that is causing an "Insufficient Memory" issue.
I've also tried to build with VS2010 and get the same error.
Other things I've tried is switching from static MFC libs to DLL MFC but the results are the same. I still get "Insufficient Memory" error and can't debug with symbols into the Invoke() call.
I've tried to look up the 61706 error for a detailed description from Microsoft but only found this link which wasn't very informative.

Why are unhandled exceptions thrown in win32 timer callbacks not treated as unhandled exceptions by the debugger?

I've been tracking down a really insidious bug at work. The event that seems to cause the very strange behavior I've been tracking down appears to be an exception being thrown while processing a timer callback. The exception is NOT handled by any of my code, therefore I would expect the debugger to be notified of the unhandled exception and alert me with a nice obnoxous pop-up. No, instead the "first chance" exception message traces out to the debugger and everything silently moves on.
I've written up the following program that demonstrates this issue:
#include "stdafx.h"
#include <Windows.h>
class FooExcept
{
};
VOID CALLBACK Timer(HWND hwnd,
UINT uMsg,
UINT_PTR idEvent,
DWORD dwTime)
{
printf("Here\n");
throw FooExcept();
printf("Also Here\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
SetTimer(0, 0, 1000, Timer);
int bRet;
HWND hWnd;
MSG msg;
// Standard Win32 message pump
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return 0;
}
The output of this program to the Visual Studio Output window is this repeated:
First-chance exception at 0x76dbb9bc in TimerTest.exe: Microsoft C++ exception: FooExcept at memory location 0x0034f743..
Of course my project is MUCH more complicated and is printing out a lot of TRACE information to the debugger. Its easy for first-chance exception to get lost in the output.
HOWEVER
That's not my concern. This is clearly an exception Im not handling. Is Windows surreptitiously deciding to handle this for me? Why? If not, why isn't it giving me a blatant pop-up alerting me of the unhandled exception? Such a pop-up could have saved me days of debugging.
This behavior seems consistent between XP/VS 2008 and Win7/VS 2010.
This has been been fixed, to some degree (see below), in Windows 7 SP1.
In article http://support.microsoft.com/kb/976038 you will find mention of a bugfix and explanation how to use it to disable this behaviour. You have to either:
set process options in the registry or
call function SetProcessUserModeExceptionPolicy exported by kernel32.dll
I have verified in Updates in Win7 and WS08R2 SP1.xls that this bugfix is indeed included in Windows 7 Service Pack 1, so all you have to do is to enable it (assuming you are lucky enough to have Windows 7 SP1 already installed).
As for explanation why this has been done, well we can just guess some ill-advised attempt to prevent legacy application from crashing in the name of backwards compatibility.
For the message itself I don't know, but for the error path, this is because the callback comes from the OS. Then the exception returns to the OS and not to your program or to your debugger. It's same on Linux. In this case you can get a strange error. The solution to resolve that is to use a custom interface or an error callback to return the error to your program caller. The same problem also comes in multithreaded apps where the thread is created by the OS and the exceptions are also returned to the OS and not to your program. The OS knows nothing about your exception handlers.

Cairo error message on exit

I'm currently doing some tests using Cairo to replace some existing GDI/GDI+
code in Visual C++ 2010 and it seems to be working fine, but I'm getting
an error message each time I close down my application :
"First-chance exception at 0x68e629dc in CairoTest.exe: 0xC0000005:
Access violation reading location 0xabababa7"
This error only happens if I've called cairo_paint(cr) while the
application is running - if I comment this line out, it disappears. The
only Cairo code in my application so far is :
CChildView::CChildView()
{
testsurface = cairo_image_surface_create_from_png("BlackShinyBackground.png");
}
CChildView::~CChildView()
{
cairo_surface_destroy(testsurface);
}
void CChildView::OnPaint()
{
CPaintDC dc(this);
cairo_surface_t *surface = cairo_win32_surface_create(dc.m_hDC);
cairo_t *cr = cairo_create (surface);
cairo_set_source_surface(cr, testsurface, 0, 0);
cairo_paint(cr);
cairo_destroy (cr);
cairo_surface_destroy (surface);
}
Can anybody point me in the direction of what I'm doing wrong?
Like I said, the code appearsto be working fine, but I don't like just ploughing on regardless when I can see errors.
A first chance exception doesn't necessarily mean much -- they're a routine part of Windows' memory management. Basically, any time you access something that's in virtual memory (e.g., on the paging file) a first chance exception is created. The OS handles it by paging in the required data into physical memory, then your code can continue executing.
If/when you see a second-chance exception, it means the OS didn't handle the exception, so unless you have a handler for it in your code, chances are pretty good that is signals a real problem.