Checking and closing HANDLE - c++

I am working with HANDLES, the first one, nextColorFrameEvent is an event handler and the second one is a stream handler. They are being initialized in the following piece of code:
nextColorFrameEvent = CreateEvent( NULL, TRUE, FALSE, NULL );
hr = nui->NuiImageStreamOpen(
NUI_IMAGE_TYPE_COLOR,
NUI_IMAGE_RESOLUTION_640x480,
0,
2,
nextColorFrameEvent,
&videoStreamHandle);
I want to properly deal with them on destruction, while not creating errors at the same time. Sometimes the initializer wont be called, so both HANDLEs are still NULL when the software comes to an end. Thats why I want to check first if the HANDLEs are properly initialized etc. and if they are, I want to close them. I got my hands on the following piece of code for this:
if (nextColorFrameEvent && nextColorFrameEvent != INVALID_HANDLE_VALUE)CloseHandle(nextColorFrameEvent);
#ifdef QT_DEBUG
DWORD error = GetLastError();
qDebug()<< error;
#endif
if (videoStreamHandle && videoStreamHandle != INVALID_HANDLE_VALUE)CloseHandle(videoStreamHandle);
#ifdef QT_DEBUG
error = GetLastError();
qDebug()<< error;
#endif
But this is apperently incorrect: if I do not run the initializer and then close the software this piece of code runs and gives me a 6:
Starting C:\...\Qt\build-simpleKinectController-Desktop_Qt_5_0_2_MSVC2012_64bit-Debug\debug\simpleKinectController...
6
6
C:\...\Qt\build-simpleKinectController-Desktop_Qt_5_0_2_MSVC2012_64bit-Debug\debug\simpleKinectController exited with code 0
which means:
ERROR_INVALID_HANDLE 6 (0x6) The handle is invalid.
Which means that closeHandle ran anyway despite the tests. What tests should I do to prevent closing when the handle is not a valid HANDLE?
Bonus question: if I run the initializer this error will no longer appear when only closing colorFrameEvent, but will still appear when closing videoStreamHandle:
Starting C:\...\Qt\build-simpleKinectController-Desktop_Qt_5_0_2_MSVC2012_64bit-Debug\debug\simpleKinectController...
0
6
C:\...\Qt\build-simpleKinectController-Desktop_Qt_5_0_2_MSVC2012_64bit-Debug\debug\simpleKinectController exited with code 0
Do I need a diffent function to close a stream handler?

nui->NuiImageStreamOpen(...) does not create a valid Windows handle for the stream but instead it creates an internal handle inside the driver side.
So you can not use windows API to release/close stream handle !!!
To do that just call nui->NuiShutdown(). I have not yet used the callback event but I think its a valid windows handle and should be closed normally.
if you need just to change settings you can always call nui->NuiImageStreamOpen(...) with new settings. No need to shutdown ...
I would also welcome function nui->NuiImageStreamClose(...); because current state of API complicates things for long term running aps with changing sensor configurations.

CreateEvent (http://msdn.microsoft.com/en-us/library/windows/desktop/ms682396(v=vs.85).aspx) returns NULL if an event was not created.
You are checking against INVALID_HANDLE_VALID which is not NULL.

You are probably trying to double-close a handle. That is likely to generate ERROR_INVALID_HANDLE 6. You can't detect this with your test, because the first CloseHandle(nextColorFrameEvent); did not change nextColorFrameEvent.
The solution is to use C++ techniques, in particular RAII. There are plenty of examples around how to use shared_ptr with HANDLE. shared_ptr is the standard solution to run cleanup code at most once, after everyone is done, and only if anybody actually allocated a resource.

there is a good way of debugging that I'm particularly fond of, despite being all writen in macros, which are nasty, but in this case they work wonders.
Zed's Awesome Debug Macros
there are a couple of things I like to change though. They make extensive use of goto, which I tend to avoid, specially in c++ projects, because otherwise you wouldn't be able to declare variables mid-code. This is why I use exit(-1) instead, or, in some projects, I mod the code to try, throw, catch c++. Since you are working with Handles, a good thing would be setting a variable and telling the program to close itself.
here is what I mean. Take this piece of code from the macros (i assume you would read the exercise and familiarize with the macros):
#define check(A, M, ...) if(!(A)) { log_err(M, ##__VA_ARGS__); errno=0; goto error; }
i'd change
goto error;
to something like
error = true;
the syntax inside the program would be something like, and I took it from a multithread program I'm writing myself:
pRSemaphore = CreateSemaphore(NULL, 0, MAX_TAM_ARQ, (LPCWSTR) "p_read_semaphore");
check(pRSemaphore, "Impossible to create semaphore: %d\n", GetLastError());
As you can see, GetLastError is only called when pRSemaphore is set to null. There are somewhat fancy mechanisms behind the macro (at least they are fancy for me), but they are hidden inside the "check" mask, so you needn't worry about them.
next step is to treat the error with something like:
inline void ExitWithError(bool &err) {
//close all handles
//tell other related process to do the same if necessary
exit(-1);
}
or you could just call it inside the macro like
#define check(A, M, ...) if(!(A)) { log_err(M, ##__VA_ARGS__); errno=0; ExitWithError(); }
hope I could be of any help

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 :)

main: src/unix/core.c:117: uv_close: Assertion `!uv__is_closing(handle)' failed

When I try to use the function uv_close((uv_handle_t*)client,NULL) in libuv library to actively close the TCP connection with the client, the error
"main: src/unix/core.c:117: uv_close: Assertion `!uv__is_closing(handle)' failed."
was reported. I search a lot online, but I still cannot find the correct way to solve the problem. I wish someone can tell me why this problem resulted and how to solve it.
You are trying to close a handle that is either already closed or in a closing state (that is, somewhere along the process that brings the handle from being alive to being closed).
As you can see from the code of libuv, the uv_close function starts as:
void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
assert(!uv__is_closing(handle));
handle->flags |= UV_CLOSING;
// ...
Where uv__is_closing is defined as:
#define uv__is_closing(h) \
(((h)->flags & (UV_CLOSING | UV_CLOSED)) != 0)
To sum up, as soon as uv_close is invoked on a handle, the UV_CLOSING flag is set and it's checked on subsequent calls to avoid multiple runs of the close function. In other terms, you can close a handle only once.
The error comes out because you are probably invoking uv_close more than once for a handle. However, it's hard to say without looking at the real code.
As a side note, you can use uv_is_closing to test your handle if you are in doubt. It's a kind of alias for uv__is_closing.

DirectX - Error when pressing ctrl + alt + del

So far my program is working pretty well. Unfortunately when I press ctrl + alt + del it throws an error. Now I have read this question:
E_ACCESSDENED when using ctrl alt del
In which it is mentioned that the computer switches to a different screen (in which you don't have any writing permissions). It's just that I have no idea how to trace if I have writing permission in the current screen.
My code looks like:
void D3D::StartFrame() {
HRESULT result;
result = pDevice->Clear( 0,NULL,D3DCLEAR_TARGET,D3DCOLOR_XRGB(FRAME_BG_R,FRAME_BG_G,FRAME_BG_B),0.0f,0 );
assert( !FAILED( result ) );
result = pBackBuffer->LockRect( &backRect,NULL,NULL );
assert( !FAILED( result ) );
}
void D3D::EndFrame() {
HRESULT result;
result = pBackBuffer->UnlockRect();
assert( !FAILED( result ) );
result = pDevice->Present( NULL,NULL,NULL,NULL );
assert( !FAILED( result ) );
}
Currently I am running the "StartFrame()" function each frame followed by some actions that should be done during the frame. At the end it will call the "EndFrame()" function that will unlock the drawing rectangle.
Now the error that occurs comes from the last assert (the StartFrame() assert doesn't fail?). Should I change these functions to return booleans telling the program if it should continue or not? Should I make it stop the entire program (which feels a bit odd)? Perhaps I am handling the rectangle locking the wrong way (should it work with asserts)?
Error: Assertion failed! - !FAILED(result)
Any help/advice would be appriciated !
First of all, whenever you get an error, before doing somethig, and before even thinking about what happened, you must check what exactly error message said.
In case of DirectX 9, you must not only check if HRESULT variable FAILED but get detailed info from it. You can get details from it using DXGetErrorString() and/or DXGetErrorDescription() functions (dxerr.h + dxerr.lib). For example, you can handle you errors by writing a small helper function, that accepts HRESULT and shows MessageBox() with details if it FAILED. Also, there is a good DXTrace() macro as a quick solution. Or, as a quickest lazy solution, you can just set a breakpoint right after function fail, and inspect value of HRESULT variable in debug watcher.
In your case, because we don't have error description in your post, we can only guess what happened (that's what guys from SO doesn't like the most). And I suspect here Device Lost state. That state sometimes happens when your app looses focus (Alt+tab, Ctrl+Alt+Del, etc.). To prevent crashes you must handle such exceptional states as described on MSDN or this short tutorial.
Of course, my guess can be wrong here, because I dont't know, what exactly happened. Please add proper error handling and provide additional information to get concrete help.
Happy coding!

SwitchDesktop works momentarily but switches back after a moment

I've got some code to create a new desktop and launch a process into that desktop.
One a few select Windows XP machines, when this code runs, I can see it switch to the new desktop and start the process, but almost immediately, the desktop switches back to the normal desktop.
This code works fine on about 98% of machines, and I can't seem to isolate any reason for this not working on the others.
Should SwitchDesktop be reliable? Can I hook calls to SwitchDesktop that might be called from another application?
My code:
int DLL_EXP_IMP WINAPI Process_Desktop(char *szDesktopName, char *szPath)
{
HDESK hOriginalThread;
HDESK hOriginalInput;
HDESK hNewDesktop;
int procSuccess;
// Save original ...
hOriginalThread = GetThreadDesktop(GetCurrentThreadId());
hOriginalInput = OpenInputDesktop(0, FALSE, DESKTOP_SWITCHDESKTOP);
// Create a new Desktop and switch to it
hNewDesktop = CreateDesktop(szDesktopName, NULL, NULL, DF_ALLOWOTHERACCOUNTHOOK, GENERIC_ALL, NULL);
SetThreadDesktop(hNewDesktop);
SwitchDesktop(hNewDesktop);
// This call blocks until the process exits, and is confirmed to work on the affected machines
procSuccess = StartProcess(szDesktopName, szPath);
// Restore original ...
SwitchDesktop(hOriginalInput);
SetThreadDesktop(hOriginalThread);
// Close the Desktop
CloseDesktop(hNewDesktop);
if (procSuccess != 0)
{
return procSuccess;
}
else
{
return 0;
}
}
My guess is that SetThreadDesktop() fails.
From MSDN:
"The SetThreadDesktop function will fail if the calling thread has any windows or hooks on its current desktop (unless the hDesktop parameter is a handle to the current desktop)."
You mentioned that StartProcess() blocks until the process terminated.
So then there is nobody referencing the new desktop and thus the desktop will go away.
You may want to consider wrapping fallible system calls in C++
-- throwing an exception in case of they fail.
And certainly the pair CreateDesktop/CloseDesktop belongs into a C++ resource wrapper.
This is 2013!
Either SwitchDesktop is failing (most of the time is access denies, or error 170 because of existing handles in another desktop), or there is another program that switches back to the default desktop.
I know for a fact that Yahoo toolbar did this (versions 5-6-7, perhaps they fixed now); KABE4.exe (I don't know what this is), an Acronis program (backup scheduler, AFAIK), and more. All of these are calling SwitchDesktop without any user intervention (a big no-no).
I proved this for Yahoo toolbar; hooking the SwitchDesktop by injecting another dll into yt.dll (loaded by IE) and returning FALSE from the hooked call solved my problem.
The proof of concept sent almost 2 years ago to Yahoo remained unanswered to this day.
In your posted code, there is that part:
// Create a new Desktop and switch to it
hNewDesktop = CreateDesktop(szDesktopName, NULL, NULL, DF_ALLOWOTHERACCOUNTHOOK, GENERIC_ALL, NULL);
SetThreadDesktop(hNewDesktop);
SwitchDesktop(hNewDesktop);
// This call blocks until the process exits, and is confirmed to work on the affected machines
procSuccess = StartProcess(szDesktopName, szPath);
// Restore original ...
SwitchDesktop(hOriginalInput);
SetThreadDesktop(hOriginalThread);
Your call to StartProcess function is between two calls to SwitchDesktop.
No function in this code stop (pause) or delay the running code, thread or process, so as you switch to hNewDesktop, you immediately switch back to hOriginalInput. You should add a while loop with end condition, after the call to StartProcess, and before the second call to SwitchDesktop. I don't know what will be the end condition for the while loop, but you do know, you will choose, after all it is your program.
For example you can use either GetKeyState or GetAsyncKeyState function to check which key is pressed on the keyboard, and make it as the end condition for the while loop, so when you will press that key, you will return immediately to your original desktop!

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.