i have no ideal for initialization code c++ before windows shutdown. For protect algorithm of my code when running. Any ideal here?
I am not sorry to report you cannot do this reliably. You can handle WM_QUERYENDSESSION or WM_ENDSESSION Windows messages, but that really traps logoff not shutdown. Alternately you could try a Windows service and react to the stop signal. But that is exactly that, your service being stopped.
HOWEVER; none of this happens reliably. If you have some defenses best broken by the shutdown code not running, somebody who wants to break them will just power the machine off. If I thought you were writing software that needed to be fault tolerant I would now advise you on crash-only software.
To make a backing store that can survive being powered off without being corrupted, the cheapest way is to use sqlite.
I think you should create an object of your own class and write something inside the destructor (or ~YourClass()).
Related
I realise that this may be a silly question, and for that I apologise in advance...
I am developing an application that is going to run on a Windows 7 Embedded Standard device installed in a vehicle. As things currently stand, the device is powered off with the ignition however I am not sure that this is ideal as it means that there is no graceful shutdown.
I have been looking around the web and I cannot find anything that indicates whether Windows 7 Embedded Standard is a special case that does not require a graceful shutdown or whether I have just been lucky to date as I have never seen any "Windows was not shut down properly" messages or anything else to indicate that simply pulling the power has caused any problems. My gut feel (and that of my colleagues) is that we should be performing a graceful shutdown before powering off the device but it would be nice to have some evidence to base that upon.
Can anybody enlighten me here?
Thanks.
Well, we also use WES7 with ungracefull shutdowns, but we are protected from anything.
Have you heard about Enhanced Write Filter ? EWF is a program that prevents any modifications made to the Drive where Windows is installed. It actually writes any change made into the RAM so all these changes are discarded upon reboot.
This has a side effect: on reboot, Windows will not detect it has been shut down ungracefully.
This program is available in the ICE as a package (if I remember).
I programmed a Windows Service and it is running on a Windows 2000 machine. Sometimes the executable for this service dies, but the Windows service is still listed as "started" in the service manager. In this situation the restart behaviour defined for this service does not take effect.
Of course, the process needs to be debugged, but I am searching right now for a workaround.
How can I avoid this situation? How does the service manager in Windows 2000 determine if a windows 2000 process is still started or not?
That probably means that the service crashed. IIRC, older versions of windows didn't always recover when a service process abnormally terminates. But that was many years ago and my memory may be faulty.
The best way to avoid the situation is to figure out what's causing your service to crash and fix it.
Although Larry, being a Microsoft employee, probably knows better than anyone else, I dare say that you should give ChangeServiceConfig2 with SERVICE_CONFIG_FAILURE_ACTIONS a shot. I've worked on a legacy service that, before I did the refactoring, used to crash a lot. The remedy my predecessors chose was to use the failure action in order to invoke a program that (running under SYSTEM) would then restart the service as if nothing had happened.
All of this only works if your service is running in its own process, which I assumed given the way you describe it. If your service is implemented in a DLL this will not work.
But I wholeheartedly agree with Larry that you should investigate and fix the problem, rather than trying to conceal it. As mentioned above, I fixed the service in question and it's not crashing or very rarely crashing and everyone is happier with that solution ;)
How to reload a crashed process on Windows? Of course, I can run a custom monitoring Win service process. But, for example, Firefox: it doesn't seem to install such a thing, but still it can restart itself when it crashes.
On Vista and above, you can use the RegisterApplicationRestart API to automatically restart when it crashes or hangs.
Before Vista, you need to have a top level exception filter which will do the restart, but be aware that running code inside of a compromised process isn't entirely secure or reliable.
Firefox constantly saves its state to the hard disk, every time you open a tab or click a link, or perform some other action. It also saves a flag saying it shut down safely.
On startup, it reads this all back, and is able to "restore" based on that info.
Structured exception handling (SEH) allows you to catch program crashes and to do something when it happens.
See: __try and __except
SEH can be very dangerous though and could lead to your program hanging instead. Please see this article for more information.
If you write your program as an NT service then you can set the first, second and subsequent failure actions to "Restart the service".
For Windows 2008 server and Windows Vista and Windows 7 you can use the Win32 API RegisterApplicationRestart
Please see my answer here for more information about dealing with different types of program crashes.
If I recall correctly Windows implements at least some subset of POSIX and so "must" have the signal interface (things like SIGKILL, SIGSEGV, SIGQUIT etc.).
I've never done this but on linux, but you could try setting the unexpected termination trap with signal() (signal.h).
From quick scan of docs it seems that very few things can be done while handling signal, it may be possible that even starting a new process is on forbidden list.
Now that I've thought about it, I'd probably go with master/worker pattern, very simple parent thread that does nothing but spawns the worker (that does all the UI / other things). If it does not set a specific "I'm gonna die now" bit but still dies (parent process always gets message / notification that spawned process died) then master respawns the worker. The main theme is keep master very simple and hard to die due to own bugs.
I have a windows service that has a timer that fires a method every 30 seconds.
The method then calls thread.sleep() and when it finishes it calls thread.start();
All code in the method is wrapped in a try/catch except for the calls to the tread sleep/start.
For some reason the service stops working, but if I recycle it or set it to recycle upon a crash it works fine.
How can I diagnose the problem?
Is there other events like OnCrash or somethign that I can hook into to dig into the stack trace?
A windows service is just the same as a normal application, it's just executed differently. So ask yourself if your normal app didn't crash, but stopped working what could cause it? Lots of things spring to mind like locking issues, concurrency issues etc...
There is no OnCrash event though but what I do for Windows Services is put all logic in a seperate assembly with a simple start method and that way I can host it in a console application and do testing easily and moving to a windows service is also not too hard.
Your other option is to attach the Visual Studio debugger to the Windows service and debug as normal.
No, there aren't, but why not just put in a try/catch yourself and log the exception when it occurs?
Also, I find the call to Sleep and Start very dubious. You shouldn't be using these calls in general for synchronization. Why are you making these calls?
I think first and foremost you need to find the reasons why it is crashing. OnCrash? well, if it crashed it won't have much to say, I guess.
Its the timer!.
Get rid of it and your problem will be solved.
Check this post for more info .
You are better off doing the operation like this...
While (stopSignal = False)
'do your work'
Thread.Sleep(yourInterval)
End While
EDIT: If you want to debug a service and not have to suffer through attaching a debugger, then do this.
Whether you disagree with this or not, MS has confirmed that its a bug, and removing the timer is the only way to avoid this problem. You should also not be using exceptions as program flow control (Catch and Retry) if you can help it.
You can use Microsoft's Debug Diagnostic Tool v1.1 to monitor a service and create a dump when it crashes. Then you can debug the dump.
http://www.microsoft.com/download/en/details.aspx?id=24370
Just curious here: is it possible to invoke a Windows Blue Screen of Death using .net managed code under Windows XP/Vista? And if it is possible, what could the example code be?
Just for the record, this is not for any malicious purpose, I am just wondering what kind of code it would take to actually kill the operating system as specified.
The keyboard thing is probably a good option, but if you need to do it by code, continue reading...
You don't really need anything to barf, per se, all you need to do is find the KeBugCheck(Ex) function and invoke that.
http://msdn.microsoft.com/en-us/library/ms801640.aspx
http://msdn.microsoft.com/en-us/library/ms801645.aspx
For manually initiated crashes, you want to used 0xE2 (MANUALLY_INITIATED_CRASH) or 0xDEADDEAD (MANUALLY_INITIATED_CRASH1) as the bug check code. They are reserved explicitly for that use.
However, finding the function may prove to be a bit tricky. The Windows DDK may help (check Ntddk.h) - I don't have it available at the moment, and I can't seem to find decisive info right now - I think it's in ntoskrnl.exe or ntkrnlpa.exe, but I'm not sure, and don't currently have the tools to verify it.
You might find it easier to just write a simple C++ app or something that calls the function, and then just running that.
Mind you, I'm assuming that Windows doesn't block you from accessing the function from user-space (.NET might have some special provisions). I have not tested it myself.
I do not know if it really works and I am sure you need Admin rights, but you could set the CrashOnCtrlScroll Registry Key and then use a SendKeys to send CTRL+Scroll Lock+Scroll Lock.
But I believe that this HAS to come from the Keyboard Driver, so I guess a simple SendKeys is not good enough and you would either need to somehow hook into the Keyboard Driver (sounds really messy) or check of that CrashDump has an API that can be called with P/Invoke.
http://support.microsoft.com/kb/244139
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters
Name: CrashOnCtrlScroll
Data Type: REG_DWORD
Value: 1
Restart
I would have to say no. You'd have to p/invoke and interact with a driver or other code that lives in kernel space. .NET code lives far removed from this area, although there has been some talk about managed drivers in future versions of Windows. Just wait a few more years and you can crash away just like our unmanaged friends.
As far as I know a real BSOD requires failure in kernel mode code. Vista still has BSOD's but they're less frequent because the new driver model has less drivers in kernel mode. Any user-mode failures will just result in your application being killed.
You can't run managed code in kernel mode. So if you want to BSOD you need to use PInvoke. But even this is quite difficult. You need to do some really fancy PInvokes to get something in kernel mode to barf.
But among the thousands of SO users there is probably someone who has done this :-)
You could use OSR Online's tool that triggers a kernel crash. I've never tried it myself but I imagine you could just run it via the standard .net Process class:
http://www.osronline.com/article.cfm?article=153
I once managed to generate a BSOD on Windows XP using System.Net.Sockets in .NET 1.1 irresponsibly. I could repeat it fairly regularly, but unfortunately that was a couple of years ago and I don't remember exactly how I triggered it, or have the source code around anymore.
Try live videoinput using directshow in directx8 or directx9, most of the calls go to kernel mode video drivers. I succeded in lots of blue screens when running a callback procedure from live videocaptureing source, particulary if your callback takes a long time, can halt the entire Kernel driver.
It's possible for managed code to cause a bugcheck when it has access to faulty kernel drivers. However, it would be the kernel driver that directly causes the BSOD (for example, uffe's DirectShow BSODs, Terence Lewis's socket BSODs, or BSODs seen when using BitTorrent with certain network adapters).
Direct user-mode access to privileged low-level resources may cause a bugcheck (for example, scribbling on Device\PhysicalMemory, if it doesn't corrupt your hard disk first; Vista doesn't allow user-mode access to physical memory).
If you just want a dump file, Mendelt's suggestion of using WinDbg is a much better idea than exploiting a bug in a kernel driver. Unfortunately, the .dump command is not supported for local kernel debugging, so you would need a second PC connected over serial or 1394, or a VM connected over a virtual serial port. LiveKd may be a single-PC option, if you don't need the state of the memory dump to be completely self-consistent.
This one doesn't need any kernel-mode drivers, just a SeDebugPrivilege. You can set your process critical by NtSetInformationProcess, or RtlSetProcessIsCritical and just kill your process. You will see same bugcheck code as you kill csrss.exe, because you set same "critical" flag on your process.
Unfortunately, I know how to do this as a .NET service on our server was causing a blue screen. (Note: Windows Server 2008 R2, not XP/Vista).
I could hardly believe a .NET program was the culprit, but it was. Furthermore, I've just replicated the BSOD in a virtual machine.
The offending code, causes a 0x00000f4:
string name = string.Empty; // This is the cause of the problem, should check for IsNullOrWhiteSpace
foreach (Process process in Process.GetProcesses().Where(p => p.ProcessName.StartsWith(name, StringComparison.OrdinalIgnoreCase)))
{
Check.Logging.Write("FindAndKillProcess THIS SHOULD BLUE SCREEN " + process.ProcessName);
process.Kill();
r = true;
}
If anyone's wondering why I'd want to replicate the blue screen, it's nothing malicious. I've modified our logging class to take an argument telling it to write direct to disk as the actions prior to the BSOD weren't appearing in the log despite .Flush() being called. I replicated the server crash to test the logging change. The VM duly crashed but the logging worked.
EDIT: Killing csrss.exe appears to be what causes the blue screen. As per comments, this is likely happening in kernel code.
I found that if you run taskkill /F /IM svchost.exe as an Administrator, it tries to kill just about every service host at once.