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)
13433정성태11/1/20232399스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232485오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232810스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232700닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232987닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233058닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233252닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233411스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233199닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233177스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233323닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233401닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235596스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233224스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233929닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233460닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233261오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233759닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233518디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233714닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20237002닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233507Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20235035닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233891닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233849Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233591닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...