본문 바로가기

.NET/C#

(닷넷) 프로세스(EXE)에 디버거가 연결되어 있는지 아는 방법



http://sysnet.pe.kr/221108498013

[출처] (닷넷) 프로세스(EXE)에 디버거가 연결되어 있는지 아는 방법|작성자 techshare




닷넷의 경우 BCL에 Debugger.IsAttached 속성을 통해 디버거 연결 여부를 알아낼 수 있습니다.

Debugger.IsAttached Property
; https://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.isattached(v=vs.110).aspx


그런데 "Debug Diagnostic Tool"로 프로세스를 연결한 경우에는,

프로세스 비정상 종료 시 "Debug Diagnostic Tool"를 이용해 덤프를 남기는 방법
; http://www.sysnet.pe.kr/2/0/1786


Debugger.IsAttached가 false를 반환합니다. 이유를 찾아보니 다음의 글에 나오는 군요. ^^

#if (DEBUG) VS System.Diagnostics.Debugger.IsAttached
; https://stackoverflow.com/questions/7073266/if-debug-vs-system-diagnostics-debugger-isattached

C# Detect if Debugger is Attached
; https://www.codeproject.com/articles/670193/csharp-detect-if-debugger-is-attached


즉, Debugger.IsAttached는 'managed debugger'가 연결되었을 때만 True이고, 'native debugger'가 연결된 경우에는 false를 반환한다고 합니다. 따라서 이런 경우에는 IsDebuggerPresent Win32 API를 P/Invoke 호출로 사용하면 됩니다.

IsDebuggerPresent function
; https://msdn.microsoft.com/en-us/library/windows/desktop/ms680345(v=vs.85).aspx


이 함수는 managed/native 상관없이 디버거 연결 여부를 반환합니다.




이 외에 이름이 약간 혼란스러운 API도 있습니다.

CheckRemoteDebuggerPresent
; https://msdn.microsoft.com/en-us/library/windows/desktop/ms679280(v=vs.85).aspx

BOOL WINAPI CheckRemoteDebuggerPresent(
  _In_    HANDLE hProcess,
  _Inout_ PBOOL  pbDebuggerPresent
);


함수 이름만 보면, 왠지 "원격 디버깅"으로 연결된 것인지를 알려주는 API인 듯싶은데 그게 아니라 디버거 연결 여부를 알고 싶은 프로세스가 다를 때 사용하는 함수입니다.

가령, 자신이 만든 디버거로 다른 프로세스를 연결하고 싶을 때 해당 프로세스가 이미 다른 디버거에 의해 연결되어 있다면 이를 사용자에게 알려줘야 할 것입니다. 바로 이럴 때 CheckRemoteDebuggerPresent의 첫 번째 인자에 해당 프로세스의 핸들 값을 전달하면 되는 것입니다.

결국 IsDebuggerPresent API는 CheckRemoteDebuggerPresent로 다음과 같이 동일하게 구현할 수 있습니다.

BOOL pbIsPresent = FALSE;
CheckRemoteDebuggerPresent(GetCurrentProcess(), &pbIsPresent); // == IsDebuggerPresent