Debugging a Windows Service

There’s a nice guide on how to debug a service here: https://bugslasher.net/2010/10/14/how-to-debug-a-windows-service/, but in my experience trying to configure the registry with gflags has never actually worked. I also find using regedit to be clumsy and tedious. So here, I am sharing some 1 liners for setting up service debugging. This will cause the service to automatically be launched in x86 WinDbg every time is starts.

set TARGET=poop.exe
set DbgPath=C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\windbg.exe
set DbgPort=5005
reg delete "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\%TARGET%" /f
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\%TARGET%" /v Debugger /t REG_SZ /d "%DbgPath% -server tcp:port=%DbgPort%" /f

We can then connect to the debugger like this:

"C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\windbg.exe" -remote tcp:Port=5005,Server=127.0.0.1 -c "g"

There’s one more thing though. As described in the link above, if you start debugging, the service controller will complain about timeouts and kill the process. We can mitigate this by configuring the registry to set a very long timeout:

reg delete "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ServicesPipeTimeout" /f 
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control" /v ServicesPipeTimeout /t REG_DWORD /d 0x10000000 /f

This timeout will apply for every service on the system, so keep that in mind if you notice any other services actually differently. Also, this registry change will not have any effect until the OS is rebooted.