{"id":29,"date":"2009-07-09T09:06:00","date_gmt":"2009-07-09T07:06:00","guid":{"rendered":"\/post\/2009\/07\/09\/Debugging-Service-Startup.aspx"},"modified":"2014-02-22T19:43:11","modified_gmt":"2014-02-22T18:43:11","slug":"debugging-service-startup","status":"publish","type":"post","link":"https:\/\/cymbeline.ch\/2009\/07\/09\/debugging-service-startup\/","title":{"rendered":"Debugging Service Startup"},"content":{"rendered":"

If you are like me working on server development you may run into the situation that a service fails early during startup, i.e. within the first couple of seconds. You’ll soon realize that manually attaching a debugger doesn’t work well, if at all. Even if you’ll be running<\/p>\n

\r\nwindbg -pn MyService.exe\r\n<\/pre>\n

you may not actually be fast enough. Or there are multiple instances of that image running (e.g. SvcHost.exe) and the above command becomes kind of useless. Now if you have been reading the ‘Debugging Tools for Windows’ documentation (or have debugged services before) you’ll already know what I am about to tell you here.<\/p>\n

As I mentioned above, the first problem you’re fighting with is that the failure happens very early. Another problem you may have is that your service is running e.g. as ‘NT AUTHORITY\\NETWORK SERVICE’ and thus may not be able to interact with your desktop. But Windows’ right here to help you out with ‘Image File Execution Options’. This basically allows you to execute a command when a particular image is being executed.<\/p>\n

You start by creating a key for the image file in the registry:<\/p>\n

\r\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\MyService.exe\r\n<\/pre>\n

There you create a new string value of the name ‘Debugger’ and set its value to the path of the debugger you want to invoke, e.g. something like ‘C:\\Debuggers\\cdb.exe’. To mitigate the problem of the non-interactive service, you’ll probably want to use the debugger remotely, so you’ll create a debugging server: ‘C:\\Debuggers\\cdb.exe -server npipe:pipe=MyDebuggingSession’. What you have now is a debugger which is attached as soon as the service starts and which is accessible remotely. Thus, you can either on the server itself or another machine which has access run for instance<\/p>\n

\r\nwindbg -remote npipe:server=my-machine,pipe=MyDebuggingSession\r\n<\/pre>\n

and there you go: you are now debugging the service. Use the various command line options for the debuggers to<\/p>\n