Tuesday, August 3, 2010

HOWTO Debug a Windows Service Using windbg

There are a lot of ways to debug a Windows service.

The simplest is to attach the debugger directly.
1. Use Task Manager to discover the PID for the service or service host. You can also use tlist.exe.
2. Use windbg and attach to that PID

Oftentimes you need to debug the service right from startup. Also it is a good idea to isolate the service in its own process since Windows generally runs several processes that have the same security context in the same host process.
1. Stop the service - 'net stop service_name'
2. Edit the following keys in the registry:
- HKLM\System\CurrentControlSet\Control - create new DWORD value - name = 'ServicesPipeTimeout', value = 86400000. The longer timeout gives you a chance to attach a debugger and set things up.
- HKLM\System\CurrentControlSet\Services\service_name - edit the ImagePath to launch myhost.exe instead of svchost.exe
- HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options - Add a new subkey called 'myhost.exe'. Under it, create a 'String' value called 'Debugger' and set the value to "C:\debuggers\ntsd.exe -server npipe:pipe=service_name_debug"
3. Make a copy of svchost.exe and name it myhost.exe ('copy \windows\system32\svchost.exe myhost.exe')
4. Enable the service to run in its own process - 'sc config service_name type= own'
5. You might need to reboot now if the service dll was in use still (was not unloaded on service stop). Also, it's better to mark the service as 'Manual' start so that it doesn't start automatically at boot - this way you can be ready when you launch the service.
6. Start the service – ‘net start service_name’
7. Attach the debugger ‘windbg –remote npipe:pipe=service_name_debug,server=localhost’. In the debugger, you can setup breakpoints, exceptions, and whatever else you need to do to debug the service, then type ‘g’ to let the service startup.

This article provides more ways to debug a Windows service.
http://support.microsoft.com/kb/824344

No comments:

Post a Comment