성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>Windbg 확장 DLL 만들기 (1) - 스레드를 강제 종료시키는 명령어</h1> <p> 다소 황당한 기능이긴 하지만... 가끔 '문제 해결' 차원에서가 아니라 '문제 분석' 차원에서 '편의상' 필요할 때가 있더군요.<br /> <br /> 마침, 검색을 해보니 누군가 만들어 놓기도 했고 그동안 Windbg 확장에 대해서 실습을 해본적이 없던 터라 따라해 보았습니다.<br /> <br /> 우선, Windbg 확장에 대해서는 다음의 MSDN magazine 글에서 잘 설명해 주고 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Writing a Debugging Tools for Windows Extension ; <a target='tab' href='https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/march/msdn-magazine-debugger-apis-writing-a-debugging-tools-for-windows-extension'>https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/march/msdn-magazine-debugger-apis-writing-a-debugging-tools-for-windows-extension</a> Debugger Engine API: Writing a Debugging Tools for Windows Extension, Part 2: Output ; <a target='tab' href='https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/may/msdn-magazine-debugger-engine-api-writing-a-debugging-tools-for-windows-extension-part-2-output'>https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/may/msdn-magazine-debugger-engine-api-writing-a-debugging-tools-for-windows-extension-part-2-output</a> Debugger Engine API: Writing a Debugging Tools for Windows Extension, Part 3: Clients and Callbacks ; <a target='tab' href='https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/june/msdn-magazine-debugger-engine-api-writing-a-debugging-tools-for-windows-extension-part-3-clients-and-callbacks'>https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/june/msdn-magazine-debugger-engine-api-writing-a-debugging-tools-for-windows-extension-part-3-clients-and-callbacks</a> </pre> <br /> 그리고, 아래의 글에서 스레드를 강제 종료시키는 Windbg 확장 DLL 소스 코드가 포함되어 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Killing a target process/thread with WinDBG ; <a target='tab' href='http://www.osronline.com/showthread.cfm?link=209257'>http://www.osronline.com/showthread.cfm?link=209257</a> </pre> <br /> 자... 그럼 위의 소스 코드를 빌드까지 가능한 유형으로 바꿔볼까요? ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 우선, Visual Studio에서 Win32 DLL 유형으로 비어있는 프로젝트를 하나 만듭니다.<br /> <br /> 확장 DLL의 구색을 갖추기 위해 "<a target='tab' href='https://docs.microsoft.com/en-us/archive/msdn-magazine/2011/march/msdn-magazine-debugger-apis-writing-a-debugging-tools-for-windows-extension'>Writing a Debugging Tools for Windows Extension</a>" 글에 공개된 소스 코드에 맞춰 볼텐데요. 우선, stdafx.h 파일을 프로젝트에 추가하고 다음과 같은 코드를 포함시킵니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #include <windows.h> #include <dbgeng.h> #define EXT_MAJOR_VER 1 #define EXT_MINOR_VER 0 </pre> <br /> 다음으로, "dbgexts.cpp" 파일을 추가하고 확장 DLL이 기본적으로 export하는 3가지 함수를 작성합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #include "stdafx.h" extern "C" HRESULT CALLBACK <span style='color: blue; font-weight: bold'>DebugExtensionInitialize</span>(PULONG Version, PULONG Flags) { *Version = DEBUG_EXTENSION_VERSION(EXT_MAJOR_VER, EXT_MINOR_VER); *Flags = 0; // Reserved for future use. return S_OK; } extern "C" void CALLBACK <span style='color: blue; font-weight: bold'>DebugExtensionNotify</span>(ULONG Notify, ULONG64 Argument) { UNREFERENCED_PARAMETER(Argument); switch (Notify) { case DEBUG_NOTIFY_SESSION_ACTIVE: ::OutputDebugString(L"DEBUG_NOTIFY_SESSION_ACTIVE"); break; case DEBUG_NOTIFY_SESSION_INACTIVE: ::OutputDebugString(L"DEBUG_NOTIFY_SESSION_INACTIVE"); break; case DEBUG_NOTIFY_SESSION_ACCESSIBLE: ::OutputDebugString(L"DEBUG_NOTIFY_SESSION_ACCESSIBLE"); break; case DEBUG_NOTIFY_SESSION_INACCESSIBLE: ::OutputDebugString(L"DEBUG_NOTIFY_SESSION_INACCESSIBLE"); break; } return; } extern "C" void CALLBACK <span style='color: blue; font-weight: bold'>DebugExtensionUninitialize</span>(void) { return; } </pre> <br /> 당연히, 위의 3가지 함수를 export 해주는 .def파일을 작성해야겠지요. 이를 위해 Visual C++ 프로젝트 파일을 마우스 오른쪽 버튼으로 눌러 "Add" / "New Item..."을 선택하고 대화창에서 "Module-Definition File (.def)"를 선택해서 추가합니다. 내용은 다음과 같이 채워 넣고.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > LIBRARY ThreadKill EXPORTS DebugExtensionNotify DebugExtensionInitialize DebugExtensionUninitialize </pre> <br /> 이제 테스트 삼아서 빌드하고, "Depends.exe"로 확인한 경우 다음과 같이 3개의 함수가 정상적으로 export 되어 있어야 합니다.<br /> <br /> <img alt='windbg_extension_1.png' src='/SysWebRes/bbs/windbg_extension_1.png' /><br /> <br /> 여기까지 확인이 되었으면 windbg 내에서 로드해서 ".chain" 명령어로 확인할 수 있고, <br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > .load D:\...[확장 DLL 경로]...\ThreadKill.dll .chain Extension DLL search Path: C:\Program Files (x86)\...[생략]... Extension DLL chain: <span style='color: blue; font-weight: bold'> D:\My...[확장DLL 경로]...\Debug\ThreadKill.dll: API 1.0.0, built Fri Dec 09 15:14:55 2011 [path: D:\My\PublicTools\Sources\WinDbgExt\ThreadKill\Debug\ThreadKill.dll]</span> dbghelp: image 6.12.0002.633, API 6.1.6, built Tue Feb 02 05:08:26 2010 [path: C:\Program Files (x86)\Debugging Tools for Windows (x86)\dbghelp.dll] ext: image 6.12.0002.633, API 1.0.0, built Tue Feb 02 05:08:31 2010 [path: C:\Program Files (x86)\Debugging Tools for Windows (x86)\winext\ext.dll] wow64exts: image 6.1.7650.0, API 1.0.0, built Tue Feb 02 05:08:04 2010 [path: C:\Program Files (x86)\Debugging Tools for Windows (x86)\WINXP\wow64exts.dll] exts: image 6.12.0002.633, API 1.0.0, built Tue Feb 02 05:08:24 2010 [path: C:\Program Files (x86)\Debugging Tools for Windows (x86)\WINXP\exts.dll] uext: image 6.12.0002.633, API 1.0.0, built Tue Feb 02 05:08:23 2010 [path: C:\Program Files (x86)\Debugging Tools for Windows (x86)\winext\uext.dll] ntsdexts: image 6.1.7650.0, API 1.0.0, built Tue Feb 02 05:08:08 2010 [path: C:\Program Files (x86)\Debugging Tools for Windows (x86)\WINXP\ntsdexts.dll] </pre> <br /> <a name='output_debug'></a> 또한, 다음과 같이 OutputDebugString으로 출력되는 문자열로 확인할 수 있습니다.<br /> <br /> <img alt='windbg_extension_2.png' src='/SysWebRes/bbs/windbg_extension_2.png' /><br /> <br /> <hr style='width: 50%' /><br /> <br /> 그럼, 본격적으로 Thread 강제 종료를 해주는 확장 함수를 넣어볼까요? ^^<br /> <br /> dbgexts.cpp 파일에 "<a target='tab' href='http://www.osronline.com/showthread.cfm?link=209257'>Killing a target process/thread with WinDBG</a>" 글에 공개된 소스 코드를 거의 그대로 넣어주면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #include <cstdio> void dprintf(char *fmt, ...) { wchar_t chBuf[4096]; va_list ap; va_start(ap, fmt); vswprintf(chBuf, fmt, ap); va_end(ap); ::OutputDebugString(chBuf); } extern "C" HRESULT CALLBACK kt(PDEBUG_CLIENT pDebugClient, PCSTR args) { ULONG64 threadId; HANDLE result; DWORD errcode =0; <span style='color: blue; font-weight: bold'>threadId = atoi(args);</span> dprintf("the thread to be killed has an ID of %x\n", threadId); result = <span style='color: blue; font-weight: bold'>OpenThread(THREAD_ALL_ACCESS, FALSE, (DWORD)threadId);</span> if (result == 0) { errcode = GetLastError(); dprintf("gle = %x\n",errcode); } else { dprintf("HANDLE to thread is %x\n",result); if(<span style='color: blue; font-weight: bold'>TerminateThread(result,DBG_TERMINATE_THREAD)</span> == 0) { dprintf("Terminate Thread Failed"); } else { dprintf("<span style='color: blue; font-weight: bold'>issue a g then ~* and you will see a thread has been killed</span>\n" "if it was main thread the process would have gone\n" "pl read msdn for all the DANGEROUS FUNCTION caveats against using TerminateThread Function\n" "also read the need to define minimum platform _winnt_winxp???\n" "also iirc using win32apis in debugger extensions is not recommended you need to use idebug::whatever::went::somewhere::interfaces\n" "have fun terminating the process thread by thread\n"); } } return S_OK; } extern "C" HRESULT CALLBACK help(PDEBUG_CLIENT pDebugClient, PCSTR args) { dprintf("usage kt ThreadId Will kill The Thread"); return S_OK; } </pre> <br /> 잊지 말고, def 파일에 2개의 함수를 추가한 후 빌드해서 완성합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > LIBRARY ThreadKill EXPORTS DebugExtensionNotify DebugExtensionInitialize DebugExtensionUninitialize <span style='color: blue; font-weight: bold'> kt help</span> </pre> <br /> <hr style='width: 50%' /><br /> <br /> 그래도, 만들어 놨는데 잘 동작하는지 테스트는 해봐야겠지요. ^^<br /> <br /> windbg에서 로드한 후, 예제 프로세스를 하나 attatch 시킨 다음 스레드를 확인합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 0:004> <span style='color: blue; font-weight: bold'>.load D:\...[생략]...\ThreadKill.dll</span> 0:004> <span style='color: blue; font-weight: bold'>~*</span> 0 Id: 24ec.<span style='color: blue; font-weight: bold'>2630</span> Suspend: 1 Teb: 7efdd000 Unfrozen Start: *** WARNING: Unable to verify checksum for D:\...[생략]...\bin\Debug\ConsoleApplication1.exe ConsoleApplication1!COM+_Entry_Point <PERF> (ConsoleApplication1+0x27be) (00c627be) Priority: 0 Priority class: 32 Affinity: ff 1 Id: 24ec.<span style='color: blue; font-weight: bold'>2468</span> Suspend: 1 Teb: 7efda000 Unfrozen Start: *** ERROR: Symbol file could not be found. Defaulted to export symbols for C:\Windows\Microsoft.NET\Framework\v4.0.30319\clr.dll - clr!CreateApplicationContext+0xcab9 (7261b30c) Priority: 0 Priority class: 32 Affinity: ff 2 Id: 24ec.<span style='color: blue; font-weight: bold'>1c28</span> Suspend: 1 Teb: 7efd7000 Unfrozen Start: clr!GetMetaDataInternalInterfaceFromPublic+0x1e505 (726fc018) Priority: 2 Priority class: 32 Affinity: ff 3 Id: 24ec.<span style='color: blue; font-weight: bold'>f40</span> Suspend: 1 Teb: 7efaf000 Unfrozen Start: ntdll!RtlLoadString+0x430 (77a541f3) Priority: 0 Priority class: 32 Affinity: ff . 4 Id: 24ec.<span style='color: blue; font-weight: bold'>27c4</span> Suspend: 1 Teb: 7efac000 Unfrozen Start: ntdll!DbgUiRemoteBreakin (77aaf7ea) Priority: 0 Priority class: 32 Affinity: ff </pre> <br /> 어차피 테스트니까 별 기준없이 아무거나 스레드를 제거해 볼텐데요. 마지막인 ThreadId == 27c4인 것을 종료하기 위해 (kt 함수에서 atoi 함수를 사용했기 때문에) 10진수로는 10180이 되므로 다음과 같이 명령을 내립니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 0:004> <span style='color: blue; font-weight: bold'>!kt 10180</span> </pre> <br /> 실행되자마자 DebugView 출력 창에는 이에 대한 디버그 메시지를 볼 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > [6160] <span style='color: blue; font-weight: bold'>the thread to be killed has an ID of 27c4</span> [6160] HANDLE to thread is 2f4 [6160] <span style='color: blue; font-weight: bold'>issue a g then ~* and you will see a thread has been killed</span> [6160] if it was main thread the process would have gone [6160] pl read msdn for all the DANGEROUS FUNCTION caveats against using TerminateThread Function [6160] also read the need to define minimum platform _winnt_winxp??? [6160] also iirc using win32apis in debugger extensions is not recommended you need to use idebug::whatever::went::somewhere::interfaces [6160] have fun terminating the process thread by thread </pre> <br /> 실제로 해당 스레드가 제거되었는지 확인하기 위해 'g' 키로 스레드 스케쥴링이 될 수 있는 여유를 준 다음, <br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 0:004> <span style='color: blue; font-weight: bold'>g</span> (24ec.22e0): Break instruction exception - code 80000003 (first chance) eax=7efa3000 ebx=00000000 ecx=00000000 edx=77aaf7ea esi=00000000 edi=00000000 eip=77a2000c esp=0545f934 ebp=0545f960 iopl=0 nv up ei pl zr na pe nc cs=0023 ss=002b ds=002b es=002b fs=0053 gs=002b efl=00000246 ntdll!DbgBreakPoint: 77a2000c cc int 3 </pre> <br /> 다시 Ctrl+Break를 걸어 실행을 멈춘 후 확인하면 ThreadId == 27c4에 해당하는 스레드가 사라진 것을 확인할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 0:007> <span style='color: blue; font-weight: bold'>~*</span> 0 Id: 24ec.2630 Suspend: 1 Teb: 7efdd000 Unfrozen Start: ConsoleApplication1!COM+_Entry_Point <PERF> (ConsoleApplication1+0x27be) (00c627be) Priority: 0 Priority class: 32 Affinity: ff 1 Id: 24ec.2468 Suspend: 1 Teb: 7efda000 Unfrozen Start: clr!CreateApplicationContext+0xcab9 (7261b30c) Priority: 0 Priority class: 32 Affinity: ff 2 Id: 24ec.1c28 Suspend: 1 Teb: 7efd7000 Unfrozen Start: clr!GetMetaDataInternalInterfaceFromPublic+0x1e505 (726fc018) Priority: 2 Priority class: 32 Affinity: ff 3 Id: 24ec.f40 Suspend: 1 Teb: 7efaf000 Unfrozen Start: ntdll!RtlLoadString+0x430 (77a541f3) Priority: 0 Priority class: 32 Affinity: ff 4 Id: 24ec.1100 Suspend: 1 Teb: 7efac000 Unfrozen Start: ntdll!RtlDosSearchPath_Ustr+0x69a (77a56679) Priority: 0 Priority class: 32 Affinity: ff 5 Id: 24ec.30c Suspend: 1 Teb: 7efa9000 Unfrozen Start: ntdll!RtlDosSearchPath_Ustr+0x69a (77a56679) Priority: 0 Priority class: 32 Affinity: ff 6 Id: 24ec.968 Suspend: 1 Teb: 7efa6000 Unfrozen Start: ntdll!RtlDosSearchPath_Ustr+0x69a (77a56679) Priority: 0 Priority class: 32 Affinity: ff . 7 Id: 24ec.22e0 Suspend: 1 Teb: 7efa3000 Unfrozen Start: ntdll!DbgUiRemoteBreakin (77aaf7ea) Priority: 0 Priority class: 32 Affinity: ff </pre> <br /> 성공이군요. ^^<br /> <br /> <a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=662&boardid=331301885'>첨부된 파일은 위의 코드를 포함한 프로젝트</a>입니다.<br /> </p><br /> <br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1449
(왼쪽의 숫자를 입력해야 합니다.)