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)
13332정성태4/27/20233873Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233922오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233573Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233762Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/20233425VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/20233847VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/20235274.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/20234579스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/20234387.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/20234300개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/20235106VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/20233933개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/20233894개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/20234349개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/20234191개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/20234266오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/20233574오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/20233788Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/20233884개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치
13313정성태4/9/20233959개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/20233973Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
13311정성태4/7/20234474C/C++: 163. Visual Studio 2022 - DirectShow 예제 컴파일(WAV Dest)
13310정성태4/6/20234086C/C++: 162. Visual Studio - /NODEFAULTLIB 옵션 설정 후 수동으로 추가해야 할 library
13309정성태4/5/20234243.NET Framework: 2107. .NET 6+ FileStream의 구조 변화
13308정성태4/4/20234150스크립트: 47. 파이썬의 time.time() 실숫값을 GoLang / C#에서 사용하는 방법
13307정성태4/4/20233906.NET Framework: 2106. C# - .NET Core/5+ 환경의 Windows Forms 응용 프로그램에서 HINSTANCE 구하는 방법
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...