ExitProcess behaviour in Windows in relation to atexit handlers - windows

I want to be able to catch any attempts of executing exit()/ExitProcess()/TerminateProcess() or any other such calls.
I thought about registering a handler with atexit(). This works fine for normal program termination (return from main()) or exit() calls (regardless of the thread that calls exit()), but ExitProcess() and TerminateProcess() bypass the handler I registered.
ExitProcess() documentation states:
Note that returning from the main function of an application results
in a call to ExitProcess.
But the observed behaviour is at least different in this regard.
Is there a method of registering a handler for process exit/termination what will always be called (except for external calls to TerminateProcess(), unhandled exceptions thrown by one of my threads or __failfast() calls, I'm guessing these are really impossible to catch).
There is the dirty option of hooking ExitProcess(), but I'd rather not do that.
EDIT: just so this is clear: I'm interested in my own process, not monitoring / controlling another process.

There is a Kernel Mode Event a device driver can subscribe to in order to get notifications of terminations of processes. This is preferred over trying to inject a DLL into processes for API hooks due to the myriad number of internal and external ways that process may end.

Related

How global SetWindowsHookEx manages to inject dll into all threads?

I created 2 hooks in my host application. 1st is WH_MOUSE set specifically for Taskbar's thread. 2nd is global WH_KEYBOARD_LL hook (dwThreadId is set to 0).
As you can see in Process Explorer, the "local" hook actually injected my dll into specific explorer.exe thread. However, there is no indication that my 2nd global hook got injected into any other processes, yet it still works perfectly... Moreover, it also works for all the new processes I start, even after the hook was set! How SetWindowsHookEx manages that?
I read that it only applies to processes that load user32.dll. My weak suspicion is that in a case of global hook, Windows somehow injects my custom dll code into user32.dll "hook-chain". And then, when new process that loads user32.dll is started, it automatically loads my hook with it? Is this correct or is there some other mechanism at work?
_LL (low-level) hooks are not injected anywhere, win32k (the kernel part of the window manager) calls the hook callback function directly. This is why that thread needs a message loop. Low-level hooks are always "global".
MSDN says:
Be aware that the WH_MOUSE, WH_KEYBOARD, WH_JOURNAL*, WH_SHELL, and low-level hooks can be called on the thread that installed the hook rather than the thread processing the hook.
You should think of hooks as having 3 modes:
Low-level (keyboard and mouse only)
Thread specific
All threads
The last two might require Windows to inject the .dll.

Detect UI operation which will "hang" the application if running in service mode

Fellow experts!
I have faced the following dilemma: some of our tools (executables) are started as scheduled tasks, some are started as services and others as usual desktop apps with interactive Windows user. We are using the code sharing strategy for source management (this is not debatable for this question).
So the solution I want to find is the following:
Detect UI operation at run-time which leads to hanging service/background task (such as say call to Application.ShowException, ShowMessage, MessageDialog, TForm.Show etc.). And when such an action detected I want to raise the exception instead. Then the operation will fail, we will have stack trace etc. but the process will not hang up! The most problematic hang up is when some event processing is done in transaction and then in some of the code used to process event suddenly (because of error in code, design, whatever) there is UI code executed then the process hangs and the DB parts can be locked!
What I think I need to do is: Use DDetours library to intercept WinAPI calls to a certain routines and raise exception instead (so that the process does not hang, but just fail in some method). Also I know that the creation of forms and windows does not hang the app, but only the tries to show them to the user.
Is there some known method of handling this problem? Or maybe there is some list of WinAPI routine set which hangs in service mode?
Thank you in advance.

Catch App Terminate from LaunchDeamon

I've got a Cocoa foundation tool that I run as a LaunchDeamon. When the app is terminated by the system, either by a reboot or shutdown (or even launchctl unload), is there a way I can capture this event so that I can perform some finalizing functions?
All the cases you're discussing send SIGTERM to the process. You want to add a signal handler for that. See the man pages for signal and sigaction. Read the warnings carefully. Only certain functions are legal to call during a signal handler (and in principle you should never allocate heap memory). Generally it's best to just use the handler to set a flag that tells your main thread to terminate.
You may also want to look at PreLoginAgents for an example of how to handle SIGTERM using the run loop, if you're using a run loop.
See Terminating Processes in the Daemons and Services Programming Guide for full details on what signals will be sent to your process.
All NSObject subclasses call a method before dying: - finalize. There is also NSSetUncaughtExceptionHandler for dealing with crashes.

creating window in child thread in vc++

I want to create a window and show some image display (like animation based on SetTimer()) on window created using CreateWindow() function. But it should be created on separate thread and should remain alive until user closes this. I tried but was unsuccessful.
EDITED
I just googled I found this link How To Create Windows in a Multithreaded Application but one thing i want to know when Window Procedure get invoked. if it is invoked by system then how i can call it from my child thread.
Windows (represented by HWNDs) in Windows have a thread affinity. Their WindowProc is always invoked in the context of the thread they are created with.
As such, they are a convenient way to serialize calls between threads as the PostMessage and SendMessage APIs can be called from any thread in the application, but the WindowProc will get executed in the context of the original creating thread.
Because WM_TIMER messages posted to message queues are the mechanism by which SetTimer works, again you need to be careful when calling SetTimer in a multithreaded app - The timer messages will be processed by the calling thread (if the hwnd parameter is NULL) or the window's thread.
You also, as a result, have to be careful to put a message loop on every thread that might create windows, or want to process timers.
Keep your user-interface on the main Windows thread. Setting a timer using the Windows API doesn't require an additional thread (as your WndProc will get the timer message WM_TIMER).
Even if you have a long running task to perform that might necessitate the use of an additional thread, keep the window on the main thread, do your work in the worker-thread and post back to the main thread with updates.

Does Application.ApplicationExit event work to be notified of exit in non-Winforms apps?

Our code library needs to be notified when the application is exiting. So we have subscribed to the System.Window.Forms.Application.ApplicationExit event. This works nicely for Winforms apps, but does it also work for other types of applications such as console apps, services, and web apps (such as ASP.NET)? The namespace would suggest that it doesn't, and it presumably gets raised when Application.Exit() is called (explicitly or implictly), which may not be correct to call for these other cases.
Is there some other event which would be better in these other cases or which would be more universal (great if it works for Winforms, too)? For example, is there an event for when Environment.Exit() is called (console app)?
I found a mention of an Exited event in System.Diagnostic.Process, but this appears to be for monitoring the exit of another process, and it does not appear to be received by a process about itself (for example, Process.GetCurrentProcess().Exited += Process_Exited; Process.GetCurrentProcess().EnableRaisingEvents = true;). I would think it might only be raised after the process has actually exited, so that wouldn't work.
This is particularly for .NET 2.0 and C#.
We finally found more about this (but by then my machine had been rebuilt and lost the cookies to my unregistered profile here; hopefully, it will let met post this answer).
Further investigation eventually found a few more events which we have found helpful:
System.Windows.Forms.Application.ThreadExit - Fires when a message loop exits
System.Windows.Forms.Application.ApplicationExit - Fires when all message loops exit
System.AppDomain.CurrentDomain.DomainUnload - Fires when a domain other than the default exits
System.AppDomain.CurrentDomain.ProcessExit - Fires when the default app domain exits
System.AppDomain.CurrentDomain.UnhandledException - Fires when an uncaught exception occurs, ending the app.
Only one of the DomainUnload or ProcessExit events are possible for a given app domain, depending on whether it is the default (top-level) domain for the process or was created as a subdomain (eg. on a web server). If an application doesn't know which it might be (as in our case), it needs to subscribe to both if it wants to catch the actual unload for itself. Also, it appears that UnhandledException (which as of .NET2.0 is always fatal) may prevent the other two events, so that may be a third case to handle. These three events should work for any .NET application.
There is a caveat that the execution time for ProcessExit is bounded (about 4 seconds?), so it may not be possible to do extensive "final" work in that event handler. It needs to be something which can be done quickly.
The Application events only apply to WinForms applications (we suspect they may not apply in pure WPF applications, however). The naming can be misleading because they are named for their most basic normal usage which has certain assumptions. ThreadExit does not relate to the actual System.Threading.Thread but rather to the message loop (Application.Run())) of a UI thread, and ApplicationExit similarly relates to the collection of application Forms on one or more UI threads. Normally, once the call to Application.Run() returns, called from the entry method of a thread, the entry method quickly concludes and the thread itself then ends. And once all UI threads have exited, a WinForms app is usually all done and exits.
Another event of note is the System.Windows.Forms.Application.ThreadException event. A Windows message loop can be configured to catch exceptions which occur in handling a message and send this event rather than let them be uncaught (and thus fatal) exceptions. Catching these exceptions allows the message loop (and that UI thread) to continue running (after aborting the current message handler). There can be only one subscriber to this event at any time for a given thread (subscriptions overwrite any previous subscriber), and it must be configured before any Form is created and subscribed before entering the message loop. See the MSDN help for this event and System.Windows.Forms.Applicaton.SetUnhandledExceptionMode() for more info.

Resources