Unexpected IConnectionPointImpl::Unadvise call on Windows Embedded Compact 7 - c++

We have a bigger software running on Win CE6 without problems. The core functionality is implemented in a COM server DLL that provides connection points. The COM client program registers event handlers for the connection points on program startup to get status notifications etc. On program exit it unregisters the handlers by calling the corresponding IConnectionPointImpl::Unadvise methods.
Now, we are porting the program to run on Win EC 7. The new Board Support Package (BSP) for Win EC 7 works well. There are also different versions with different options, created at different times with different sources from Microsoft, but our software always show the same issue.
On program startup, ~10s after launch, IConnectionPointImpl::Unadvise is called unexpectedly on all registered event handlers. We only have one method in our source code that calls IConnectionPointImpl::Unadvise and this is definitely not executed.
The issue appears ~95%, but sometimes the program starts and runs without problems. We cannot use the Debugger because of the size of the program, the performance is very poor.
We guess, that the COM runtime calls the IConnectionPointImpl::Unadvise methods for some reasons. But we have no idea, how to prevent this.
Has anybody observed the same issue? Is there a solution/workaround available? Thanks.

So we finally found how solve this problem.
We remove our dependency on MarshalByReObject and replace it by a proper implementation of ISerializable.
That allow us to load properly inside custom AppDomain our assembly and events are not loose anymore.
But this has a side effect on path where assembly a configuration file are loaded. To solve this we also implement an AppDomain.AssemblyResolve event which allow us to redirect the loading in a proper place.
I hope this can help you ;)

Related

Understanding and managing c++ program crash handling in windows

I have a c++ program compiled with MinGW which links to libmicrohttpd to run a webserver. It normally functions correctly, but I am trying to do some robustness testing and for my current test I have tried to disable the network interface. This results in the program crashing with the dialog box: "MyProgram.exe has stopped working - A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available."
Rather than debug the program and potentially its dependencies, for my purposes, it would be fine if it would just crash silently without making the dialog box (I have another component that is meant to restart it). Is this possible to do via some sort of manifest or Windows API call?
It turns out there is a Windows API function called SetErrorMode. Passing the parameter SEM_NOGPFAULTERRORBOX will prevent the error dialog from being displayed on a crash.
There is also the RegisterApplicationRestart function which can be used to have Windows restart an application in the event of a crash (or other configurable reasons).

LoadLibrary fails sometimes when starting as service

We have a 64bit application running as service on Windows 7 64bit. When we start a service manually, it works fine everytime. When the service is started automatically with system startup, sometimes (like 1 in 10) it fails. Problem is with LoadLibrary function which is in fact the first thing it does. It is a load of our DLL where the most of the code is. I can't reproduce it on my computers, so I am just sending special testing binaries to colleague abroad. I added text outputs to file using unbuffered write operation so I can see exactly where it disappears. There is no crash dump, there is no exception, there is no NULL retrived, it just exits somewhere in LoadLibrary and service is not running after system startup. Our library does not have DllMain, but if I add it, it does not get there (in fail case). I tried delay loading of dependent system libraries, no success. It seems like sometimes something is not yet started in Windows and so the initialization fails, I am not sure. But adding sleep before LoadLibrary does not solve the problem (too late to sleep?). Do you have any ideas what is going on and how to proceed? I am currently going to remove the code from our DLL step by step to remove the lib dependencies one by one to see if in some moment it will start to work. I will be happy to provide additional information when needed.
Lenovo RapidBoot Shield app was the reason.
"RapidBoot Shield works by delaying non-critical applications and services to help your system boot faster. However, in some instances, RapidBoot Shield may delay an application and/or service that is critical to the system startup. This can cause the system to boot slower than expected or some applications may be unable to start normally."

Prevent McAfee Dlls injection

I have a process that doing some inline hooks on WinSock module (Send and Receive functions).
On a machine with McAfee I can see that two dlls are being injected into my process:
hipi.dll
hipqa.dll
Both are also doing probably inline hooking on those functions and I get collisions and unwanted behaviors. Is there an option to prevent/unload those dlls so they will not interfere?
10x,
Guy
There are many scenario to achieve DLL injection(Hooking), BTW, you must learn more about how stuff works behind every method, the most common one is by using CreateRemoteThread() API function, then you must to inject your security DLL on every process and hook/redirect/deny any call to CreateRemoteThread() or any "dangerous" API call.
PS: BUT keep in your mind:
user-mode hooking can NEVER be an option to apply additional security
checks in any safe manner. If you only want
to “sandbox” a dedicated process, you know well about, and the process in fact doesn’t know about
EasyHook, this might succeed! But don’t ever attempt to write any security software based on user
mode hooking. It won’t work, I promise you…
You have 2 options.
Add an exclusion for your process so that McAfee doesn't attempt to scan it. I don't use McAfee's products, but I would assume that this would be a relatively straightforward process.
Uninstall McAfee
The easiest solution is to just unhook the affected functions. I had to do the same to work around some Dell crapware. It's not excessively hard, even though it requires some understanding of x86 assembly. You have to disable DEP, make the patched code writeable, find the original instructions, and copy them back. Finding the original instructions probably means disassembling the patch.
Another alternative is simply to hook it at a different place. For example, hook the IAT instead and then when you are done with whatever you want, forward execution back to the real function where it will then go through McAfee's hook.
I've had to deal with something similar once. Read their own hook assembly stub, so you can figure out how to hook in a way you chain to their hook after yours.
I'd imagine that McAfee are performing DLL injection from kernel-mode. They are likely finding the address of the KeServiceDescriptorTable (exported by NTOSKRNL on 32-bit systems and the address to it is leaked on 64-bit environments by KiSystemServiceRepeat -> close to KiSystemCall64 found by the IA32_LSTAR Model Specific Register) and then locating NtCreateThreadEx from the service table, or they're using KeInitializeApc and KeInsertQueueApc (both exported by NTOSKRNL) for APC injection (custom NtQueueApcThread wrapper). That would be logical considering they are a security vendor with a lot of resources, I doubt they'd be injecting from user-mode.
The likelihood is they are abusing PsSetCreateProcessNotifyRoutineEx or PsSetLoadImageNotifyRoutineEx to detect new process creation. The first one is not as good as the latter, the latter is better for filtering of NTDLL.DLL since it is the first module loaded into every single process, and signifies the process has actually started up properly and is just about ready to execute its own code (after the Windows module loads, and because McAfee will need to wait for Win32 modules like kernel32.dll to be loaded otherwise they'll crash the process if they use the Win32 API at all in their injected modules).
You can try intercepting LdrInitializeThunk or KiUserApcDispatcher, but honestly, there's not much you can do. McAfee will find a way to inject into your process no matter what you do, because they have control from kernel-mode. If you develop process protection via a variety of kernel-mode callbacks from a driver, they'll bypass it using non-exported routines located via pattern match scanning of ntoskrnl.exe, or exported routines which don't invoke the callback notification APIs. If you locally patch routines invoked for thread creation/APC locally in your own process when performed by a remote attacker, they'll find ways to prevent this and bypass it (e.g. patch the patched routines in the address space of your process back to the original, inject, then re-patch the bytes back).
You're playing with fire if you want to stop security software with the privileges McAfee has. It is similar to how Anti-Cheat cannot stop game hackers who have kernel-mode access, and go do drastic measures of even flagging Debug Mode/Test Mode enabled nowadays.

Getting rid of the evil delay caused by ShellExecute

This is something that's been bothering me a while and there just has to be a solution to this. Every time I call ShellExecute to open an external file (be it a document, executable or a URL) this causes a very long lockup in my program before ShellExecute spawns the new process and returns. Does anyone know how to solve or work around this?
EDIT: And as the tags might indicate, this is on Win32 using C++.
I don't know what is causing it, but Mark Russinovich (of sysinternal's fame) has a really great blog where he explains how to debug these kinds of things. A good one to look at for you would be The Case of the Delayed Windows Vista File Open Dialogs, where he debugged a similar issue using only process explorer (it turned out to be a problem accessing the domain). You can of course do similar things using a regular windows debugger.
You problem is probably not the same as his, but using these techniques may help you get closer to the source of the problem. I suggest invoking the CreateProcess call and then capturing a few stack traces and seeing where it appears to be hung.
The Case of the Process Startup Delays might be even more relevant for you.
Are you multithreaded?
I've seen issues with opening files with ShellExecute. Not executables, but files associated an application - usually MS Office. Applications that used DDE to open their files did some of broadcast of a message to all threads in all (well, I don't know if it was all...) programs. Since I wasn't pumping messages in worker threads in my application I'd hang the shell (and the opening of the file) for some time. It eventually timed out waiting for me to process the message and the application would launch and open the file.
I recall using PeekMessage in a loop to just remove messages in the queue for that worker thread. I always assumed there was a way to avoid this in another way, maybe create the thread differently as to never be the target of messages?
Update
It must have not just been any thread that was doing this but one servicing a window. Raymond (link 1) knows all (link 2). I bet either CoInitialize (single threaded apartment) or something in MFC created a hidden window for the thread.

Logging/monitoring all function calls from an application

we have a problem with an application we're developing. Very seldom, like once in a hundred, the application crashes at start up. When the crash happens it brings down the whole system, the computer starts to beep and freezes up completely, the only way to recover is to turn off the power (we're using Windows XP). The rarity of the crash combined with the fact that we can't break into the debugger or even generate a stackdump when it occurs makes it extremely hard to debug.
I'm looking for something that logs all function calls to a file. Does such a tool exist? It shouldn't be impossible to implement, profilers like VTune does something very similar.
We're using visual studio 2008 (C++).
Thanks
A.B.
Logging function entries/exits is a low-level approach to your problem. I would suggest using automatic debugger instrumentation (using Debugger key under Image File Execution Options with regedit or using gflags from the package I provide a link to below) and trying to repro the problem until it crashes. Additionally, you can have the debugger log function call history of suspected module(s) using a script or have collect any other information.
But not knowing the details of your application it is very hard to suggest a solution. Is it a user app, service or a driver? What does "crashes at startup" mean - at windows startup or app's startup?
Use this debugger package to troubleshoot.
The only problem with the logging idea is that when the system crashes, the latest log entries might still be in the cache and have no chance to be written to disk...
If it was me I would try running the program on a different PC - it might be flaky hardware or drivers causing the problem. An application program "shouldn't" be able to bring down the system.
A few Ideas-
There is a good chance that just prior to your crash there is some sort of exception in the application. if you set you handler for all unhandled exceptions using SetUnhandledExceptionFilter() and write a stack trace to your log file, you might have a chance to catch the crash in action.
Just remember to flush the file after every write.
Another option is to use a tool such as strace which logs all of the system calls into the kernel (there are multiple flavors and implementations for that so pick your favorite). if you look at the log just before the crash you might find the culprit
Have you considered using a second machine as a remote debugger (via the network)? When the application (and system) crashes, the second machine should still show some useful information, if not the actual point of the problem. I believe VC++ has that ability, at least in some versions.
For Visual C++ _penter() and _pexit() can be used to instrument your code.
See also Method Call Interception in C++.
GCC (including the version MingGW for Windows development) has a code generation switch called -finstrument-functions that tells the compiler to emit special calls to functions called __cyg_profile_func_enter and __cyg_profile_func_exit around every function call. For Visual C++, there are similar options called /GH and /Gh. These cause the compiler to emit calls to __penter and __pexit around function calls.
These instrumentation modes can be used to implement a logging system, with you implementing the calls that the compiler generates to output to your local filesystem or to another computer on your network.
If possible, I'd also try running your system using valgrind or a similar checking tool. This might catch your problem before it gets out-of-hand.