Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

NT 서비스 시작 단계에서 닷넷 메서드에 BP를 걸어 디버깅하는 방법

NT 서비스에 Visual Studio를 연결하는 방법을 알아 봤는데요.

NT 서비스가 시작하자마자 디버거를 연결시키는 방법 (1)
; https://www.sysnet.pe.kr/2/0/1586

NT 서비스가 시작하자마자 디버거를 연결시키는 방법 (2)
; https://www.sysnet.pe.kr/2/0/1587

그렇게 연결한 서비스의 닷넷 메서드에 BP를 걸어보는 것도 마저 해봐야겠지요. ^^ 참고로, 방식은 예전의 Main 메서드 거는 것과 크게 다르지 않습니다.

.NET 4.0 응용 프로그램의 Main 함수에 BreakPoint 걸기
; https://www.sysnet.pe.kr/2/0/1021

자, 그럼 레지스트리의 "Image File Execution Options"에 windbg로 "SQL Server Reporting Services" 서비스를 디버깅하는 것으로 시작해 볼까요? ^^

일단 디버거가 로드되면,

Microsoft (R) Windows Debugger Version 6.12.0002.633 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

CommandLine: "C:\Program Files\Microsoft SQL Server\MSRS11.MSSQLSERVER\Reporting Services\ReportServer\bin\ReportingServicesService.exe"
Symbol search path is: SRV*d:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is: 
ModLoad: 00000000`00330000 00000000`007ea000   ReportingServicesService.exe
...[생략]...
ModLoad: 00000000`50000000 00000000`50007000   C:\Program Files\Microsoft SQL Server\MSRS11.MSSQLSERVER\Reporting Services\ReportServer\bin\SQLRSOS.dll
...[생략]...
ModLoad: 00007ff8`2c770000 00007ff8`2c796000   C:\Windows\SYSTEM32\DEVOBJ.dll
(1b50.107c): Break instruction exception - code 80000003 (first chance)
ntdll!LdrInitShimEngineDynamic+0x330:
00007ff8`305e7710 cc              int     3

NT 서비스 로드의 제약 시간에 걸리지 않게 mscorlib까지만 빠르게 진행을 시켜줍니다. (아니면, ServicesPipeTimeout을 변경해 주어 시간을 늘리는 것도 좋겠고.)

0:013> sxe ld mscorlib

0:013> g
Profiler Initialize - End!
ModLoad: 00000000`068f0000 00000000`06d4e000   mscorlib.dll
ntdll!NtMapViewOfSection+0xa:
00007ff8`305b67fa c3              ret

이제 sos를 로드하고 BP를 걸어볼까요?

0:013> .loadby sos mscorwks

0:013> !bpmd mscorlib System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage
PDB symbol for mscorwks.dll not loaded
Adding pending breakpoints...

위와 같이 메시지가 나오면 pending이라고는 되어 있지만 BP가 안 걸린 것입니다. 따라서 BP가 걸릴 수 있을 정도로 좀 더 진행해야 할 필요가 있는데요. System.Data까지 해보았습니다. (어디까지 할지는 몇번 시행 착오를 거쳐야 합니다.)

0:013> sxe ld system.data
0:013> g

ModLoad: 00000000`1b6d0000 00000000`1b9dc000   System.Data.dll
ntdll!NtMapViewOfSection+0xa:
00007ff8`305b67fa c3              ret

이제서야 BP가 제대로 걸립니다. ^^

0:010> !bpmd mscorlib System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage
Found 2 methods...
MethodDesc = 00007ff7c02e9fa8
MethodDesc = 00007ff7c02e9fb0
Adding pending breakpoints...

같은 pending이라도 위와 같이 "Found" 메시지가 나와줘야 BP가 걸린 것입니다. 이렇게 하고 진행을 하면 다음과 같이 해당 메서드의 실행 순간에 멈춥니다.

0:010> g
(c4c.1408): CLR notification exception - code e0444143 (first chance)
JITTED mscorlib!System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage)
Setting breakpoint: bp 00007FF7C0C4DA70 [System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage)]
Breakpoint 0 hit
00007ff7`c0c4da70 53              push    rbx

BP로 걸린 메서드의 MethodDesc 값을 알아내어,

0:010> !name2ee mscorlib!System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage
Module: 00007ff7c0172020 (mscorlib.dll)
Token: 0x0000000006004510
MethodDesc: 00007ff7c02e9fa8
Name: System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage)
JITTED Code Address: 00007ff7c0c4da70

sos.dll의 !U 명령어를 통해 역어셈블할 수 있습니다.

0:010> !U 00007ff7c02e9fa8
Normal JIT generated code
System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(System.Runtime.Remoting.Messaging.IMessage)
Begin 00007ff7c0c4da70, size cf
00007ff7`c0c4da70 53              push    rbx
00007ff7`c0c4da71 55              push    rbp
00007ff7`c0c4da72 57              push    rdi
...[생략]...
00007ff7`c0c4db2a e8a1a9225f      call    mscorwks!PreBindAssembly+0x5cad0 (00007ff8`1fe784d0) (JitHelp: CORINFO_HELP_RETHROW)
00007ff7`c0c4db2f 488d05a3ffffff  lea     rax,[00007ff7`c0c4dad9]
00007ff7`c0c4db36 4883c430        add     rsp,30h
00007ff7`c0c4db3a 5f              pop     rdi
00007ff7`c0c4db3b 5d              pop     rbp
00007ff7`c0c4db3c 5b              pop     rbx
00007ff7`c0c4db3d f3c3            rep ret

sos.dll의 !U 명령어말고 windbg 자체의 u(nassemble)도 있는데요. 2개의 출력 결과가 다소 다릅니다. !U로 한 경우에는 내부에 닷넷 메서드 호출들의 표시가 추가되므로 로직 파악이 더 쉽습니다.




참고로, 실패했지만 한 가지 더 설명해 보겠습니다.

위의 방법대로하면 Local SYSTEM 설정 및 데스크톱 보안 문제로 디버깅이 다소 불편한데요. 이것 때문에 아예 VM을 대상으로 커널 디버깅으로 해볼까... 시도를 해봤습니다.

아래의 문서대로 환경 구성을 하고,

Windbg - Hyper-V 윈도우 7 원격 디버깅 구성
; https://www.sysnet.pe.kr/2/0/938

Hyper-V 호스트 컴퓨터에 windbg를 설치해,

Debugging Tools for Windows 독립 설치 버전
; https://www.sysnet.pe.kr/2/0/1447

VM 자체를 커널 디버깅으로 연결을 했습니다.

Microsoft (R) Windows Debugger Version 6.12.0002.633 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

Opened \\.\pipe\windbg_port
Waiting to reconnect...
Connected to Windows 7 9600 x64 target at (Fri Jan 17 21:04:16.771 2014 (UTC + 9:00)), ptr64 TRUE
Kernel Debugger connection established.
Symbol search path is: SRV*d:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is: 
Windows 7 Kernel Version 9600 MP (6 procs) Free x64
Product: Server, suite: TerminalServer SingleUserTS
Built by: 9600.16452.amd64fre.winblue_gdr.131030-1505
Machine Name:
Kernel base = 0xfffff803`0e40f000 PsLoadedModuleList = 0xfffff803`0e6d3990
Debug session time: Fri Jan 17 21:04:12.158 2014 (UTC + 9:00)
System Uptime: 0 days 0:21:53.376
Break instruction exception - code 80000003 (first chance)

nt!DbgBreakPointWithStatus:
fffff803`0e563890 cc              int     3

프로세스 생성에 대해 BP를 잡고,

bp nt!PspInsertProcess

g로 시작해 NT 서비스를 실행하니 services.exe에서 잡혔습니다. 그래서 한번 더 g를 거치고 나서야 정상적으로 ReportingServicesService.exe에 잡혔습니다.

0: kd> g
Breakpoint 1 hit
nt!PspInsertProcess:
fffff803`0e840a78 48895c2420      mov     qword ptr [rsp+20h],rbx

0: kd> kc
Call Site
nt!PspInsertProcess
nt!NtCreateUserProcess

0: kd> !process -1 0 
PROCESS ffffe000013d8940
    SessionId: 0  Cid: 0298    Peb: 7ff7e527e000  ParentCid: 0238
    DirBase: 10b32b000  ObjectTable: ffffc0000270f0c0  HandleCount: <Data Not Accessible>
    Image: services.exe

0: kd> g
Breakpoint 1 hit
nt!PspInsertProcess:
fffff803`0e840a78 48895c2420      mov     qword ptr [rsp+20h],rbx

1: kd> !process -1 0 
PROCESS ffffe00003f44940
    SessionId: 0  Cid: 1100    Peb: 7ff5ff4fa000  ParentCid: 0298
    DirBase: 13a79c000  ObjectTable: ffffc000132ace00  HandleCount: <Data Not Accessible>
    Image: ReportingServicesService.exe

** 이미 실행중인 process라면, 해당 프로세스 정보를 얻어서 유저 모드로 내려갈 수 있습니다.

!process 0 0 ReportingServicesService.exe
.process /i ffffe00003f44940

이후, LoadLibrary에 BP를 거는 방식을 통해 적절한 닷넷 DLL이 로드되었을때

bp /p @$proc kernel32!LoadLibraryW

SOS를 로드하고 !name2ee와 같은 확장 명령어를 실행해 봤지만 정상적으로 동작하지 않았습니다. 제가 잘못한 건지는 알수 없으나 어쨌든 커널 모드의 windbg에서는 sos.dll을 동작시키는 것에 실패했습니다. (혹시 이에 대해 아시는 분은 덧글 좀 부탁드립니다. ^^)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13600정성태4/18/2024249닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024271닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024284닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024361닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024714닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024839닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241000닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241049닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241202C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241164닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241071Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241140닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241191닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241149오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241293Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241094Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241046개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241149Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241407Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241585개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241136닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241628닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241870닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...