SwitchDesktop works momentarily but switches back after a moment - c++

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!

Related

linux c++: libaio callback function never called?

I'm on ubuntu 16.10 with g++ 6.2, testing libaio feature:
1. I was trying to test io_set_callback() function
2. I was using main thread and a child thread to talk by a pipe
3. child thread writes periodically (by alarm timer, signal), and main thread reads
I hope to use "callback" function to receive notifications. It didn't work as expected: callback function "read_done" is never called
My questions:
1. I expected my program should call "read_done" function, but actually not.
2. Why the output prints 2 "Enter while" each time?
I hope it only print together with "thread write msg:..."
3. I tried to comment out "io_getevents" line, same result.
I'm not sure if callback mode still need io_getevents? So how to fix my program so it work as I expected? Thanks.
You need to integrate io_queue_run(3) and io_queue_init(3) into your program. Though these aren't new functions, they don't seem to be in the manpages for a bunch of currently shipping distros. Here's a couple of the manpages:
http://manpages.ubuntu.com/manpages/precise/en/man3/io_queue_run.3.html
http://manpages.ubuntu.com/manpages/precise/en/man3/io_queue_init.3.html
And, of course, the manpages don't actually say it, but io_queue_run is what calls the callbacks that you set in io_set_callback.
UPDATED: Ugh. Here's the source for io_queue_run from libaio-0.3.109 on Centos/RHEL (LGPL license, Copyright 2002 Red Hat, Inc.)
int io_queue_run(io_context_t ctx)
{
static struct timespec timeout = { 0, 0 };
struct io_event event;
int ret;
/* FIXME: batch requests? */
while (1 == (ret = io_getevents(ctx, 0, 1, &event, &timeout))) {
io_callback_t cb = (io_callback_t)event.data;
struct iocb *iocb = event.obj;
cb(ctx, iocb, event.res, event.res2);
}
return ret;
}
You'd never want to actually call this without the io_queue_wait call. And, the io_queue_wait call is commented out in the header included with both Centos/RHEL 6 and 7. I don't think you should call this function.
Instead, I think you should incorporate this source into your own code, then modify it to do what you want. You could pretty trivially add a timeout argument to this io_queue_run and just replace your call to io_getevents with it, instead of bothering with io_queue_wait. There's even a patch here that makes io_queue_run MUCH better: https://lwn.net/Articles/39285/).

FindNextPrinterChangeNotification returns NULL for ppPrinterNotifyInfo

I'm stuck on problem were I would like to ask for some help:
I have the task to print some files of different types using ShellExecuteEx with the "print" verb and need to guarantee print order of all files. Therefore I use FindFirstPrinterChangeNotification and FindNextPrinterChangeNotification to monitor the events PRINTER_CHANGE_ADD_JOB and PRINTER_CHANGE_DELETE_JOB using two different threads in the background which I start before calling ShellExecuteEx as I don't know anything about the application which will print the files etc. The only thing I know is that I'm the only one printing and which file I print. My solution seems to work well, my program successfully recognizes the event PRINTER_CHANGE_ADD_JOB for my file, I even verify that this event is issued for my file by checking what is give to me as additional info by specifying JOB_NOTIFY_FIELD_DOCUMENT.
The problem now is with the event PRINTER_CHANGE_DELETE_JOB, where I don't get any addition info about the print job, though my logic is exactly the same for both events: I've written one generic thread function which simply gets executed with the event it is used for. My thread is recognizing the PRINTER_CHANGE_DELETE_JOB event, but on each call to FindNextPrinterChangeNotification whenever this event occured I don't get any addition data in ppPrinterNotifyInfo. This works for the start event, though, I verified using my logs and the debugger. But with PRINTER_CHANGE_DELETE_JOB the only thing I get is NULL.
I already searched the web and there are some similar questions, but most of the time related to VB or simply unanswered. I'm using a C++ project and as my code works for the ADD_JOB-event I don't think I'm doing something completely wrong. But even MSDN doesn't mention this behavior and I would really like to make sure that the DELETE_JOB event is the one for my document, which I can't without any information about the print job. After I get the DELETE_JOB event my code doesn't even recognize other events, which is OK because the print job is done afterwards.
The following is what I think is the relevant notification code:
WORD jobNotifyFields[1] = {JOB_NOTIFY_FIELD_DOCUMENT};
PRINTER_NOTIFY_OPTIONS_TYPE pnot[1] = {JOB_NOTIFY_TYPE, 0, 0, 0, 1, jobNotifyFields};
PRINTER_NOTIFY_OPTIONS pno = {2, 0, 1, pnot};
HANDLE defaultPrinter = PrintWaiter::openDefaultPrinter();
HANDLE changeNotification = FindFirstPrinterChangeNotification( defaultPrinter,
threadArgs->event,
0, &pno);
[...]
DWORD waitResult = WAIT_FAILED;
while ((waitResult = WaitForSingleObject(changeNotification, threadArgs->wfsoTimeout)) == WAIT_OBJECT_0)
{
LOG4CXX_DEBUG(logger, L"Irgendein Druckereignis im Thread zum Warten auf Ereignis " << LogStringConv(threadArgs->event) << L" erkannt.");
[...]
PPRINTER_NOTIFY_INFO notifyInfo = NULL;
DWORD events = 0;
FindNextPrinterChangeNotification(changeNotification, &events, NULL, (LPVOID*) &notifyInfo);
if (!(events & threadArgs->event) || !notifyInfo || !notifyInfo->Count)
{
LOG4CXX_DEBUG(logger, L"unpassendes Ereignis " << LogStringConv(events) << L" ignoriert");
FreePrinterNotifyInfo(notifyInfo);
continue;
}
[...]
I would really appreciate if anyone could give some hints on why I don't get any data regarding the print job. Thanks!
https://forums.embarcadero.com/thread.jspa?threadID=86657&stqc=true
Here's what I think is going on:
I observe two events in two different threads for the start and end of each print job. With some debugging and logging I recognized that FindNextPrinterChangeNotification doesn't always return only the two distinct events I've notified for, but some 0-events in general. In those cases FindNextPrinterChangeNotification returns 0 as the events in pdwChange. If I print a simple text file using notepad.exe I only get one event for creation of the print job with value 256 for pdwChange and the data I need in notifyInfo to compare my printed file name against and comparing both succeeds. If I print a pdf file using current Acrobat Reader 11 I get two events, one has pdwChange as 256, but gives something like "local printdatafile" as the name of the print job started, which is obviously not the file I printed. The second event has a pdwChange of 0, but the name of the print job provided in notifyInfo is the file name I used to print. As I use FreePDF for testing pruproses, I think the first printer event is something internal to my special setup.
The notifications for the deletion of a print job create 0 events, too. This time those are sent before FindNextPrinterChangeNotification returns 1024 in pdwChange, and timely very close after the start of the print job. In this case the exactly one generated 0 event contains notifyInfo with a document name which equals the file name I started printing. After the 0 event there's exactly one additional event with pdwChange of 1024, but without any data for notifyInfo.
I think Windows is using some mechanism which provides additional notifications for the same event as 0 events after the initial event has been fired with it's real value the user notified with, e.g. 256 for PRINTER_CHANGE_ADD_JOB. On the other hand it seems that some 0 events are simply fired to provide data for an upcoming event which then gets the real value of e.g. 1024 for PRINTER_CHANGE_DELETE_JOB, but without anymore data because that has already been delivered to the event consumer with a very early 0 event. Something like "Look, there's more for the last events." and "Look, something is going to happen with the data I already provide now." Implementing such an approach my prints now seem to work as expected.
Of course what I wrote doesn't fit to what is documented for FindNextPrinterChangeNotification, but it makes a bit of sense to me. ;-)
You're not checking for overflows or errors.
The documentation for FindNextPrinterChangeNotification says this:
If the PRINTER_NOTIFY_INFO_DISCARDED bit is set in the Flags member of
the PRINTER_NOTIFY_INFO structure, an overflow or error occurred, and
notifications may have been lost. In this case, no additional
notifications will be sent until you make a second
FindNextPrinterChangeNotification call that specifies
PRINTER_NOTIFY_OPTIONS_REFRESH.
You need to check for that flag and do as described above, and you should also be checking the return code from FindNextPrinterChangeNotification.

Checking and closing HANDLE

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

could stl set::insert cause BSOD?

I have written a 'filemon' utility which basically logs file being opened during a period of time. Now I have exact these two functions in my 'filemon' utility:
set<wstring> wstrSet;
// callback - get notified by callback filter driver on any file open operation
void CbFltOpenFileN(
CallbackFilter* Sender,
LPWSTR FileName,
ACCESS_MASK DesiredAccess,
WORD FileAttributes,
WORD ShareMode,
DWORD CreateOptions,
WORD CreateDisposition )
{
// don't log for directories
if (FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
return;
}
wstring wstr = FileName;
wstr.append(L"\n");
//wstrSet.insert(wstr); // as soon as I un-comment this line I start getting BSOD in multiple execution of this utility
}
// Read all paths stored in the set and write them into the log file
void WritePathsToLog() {
typedef set<wstring>::const_iterator CI;
printf("\nNo. of files touched ===> %d\n\n", wstrSet.size());
for (CI iter = wstrSet.begin(); iter != wstrSet.end(); iter++) {
fputws((*iter).c_str(), logFile);
}
}
Basically what this code does is that 'filemon' utility interacts with callback filter driver and whenever file is touched by any process the driver reports the respective filename to the 'filemon' utility via CbFltOpenFileN function.
Now the issue is that this 'filemon' utility runs fine on win7 x64 machine 4GB machine but as soon as I uncomment the last line in the CbFltOpenFileN function i.e. start inserting the reported filename in the set then I start getting BSOD mostly with BugCheck 0xCC and sometimes with BugCheck 0x50 which basically indicates that "system is trying to access already freed memory"
P.S. on win7 x64 with 8GB RAM I am not seeing any issue at all irrespective of whether last line in the CbFltOpenFileN function is commented or not.
Currently, 'wstrSet' is using default allocator so do I need to use a specific allocator while declaring set wstrSet; if yes can someone tell me how & why?
Let me share some more information here:
I am using VS2010
My utility is a 32 bit application targeted for x86 platform
The fileystem filter driver I am using is callabck filter driver provided by Eldos corp.
Now I am tetsing this utility using a simulator which generates lots of files and then starts the 'filemon' utility, then it touches all those files and at the end stops the 'filemon' utility. This simulator repeates this process 25 times.
Now for case where last line is commented I get empty log file created 25 times as I don't insert anything in set but 'filemon' utility also doesn't causes any BSOD
But for case where last line is NOT commented I get log file created each time with path enteries as now I am inserting paths in the set but then during first few iteration, say 2nd or 3rd or 6th, itself 'filemon' utility hits this BSOD scenario.
It's hard for me to repro this issue in debug mode as my simulator take cares of the start/stop of 'filemon' utility and i need to run it multiple time to repro the issue.
Hope this added info helps!!!
Thanks and Regards,
Sachin
If you CbFltOpenFileN is a callback function, does this means it has asynchron calls? in that case, you might want to protect the global variable (wstrSet) with a mutex...

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.