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

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13231정성태1/27/20233743오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234107개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235104.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235237.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20234931개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234603.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
13225정성태1/21/20233849개발 환경 구성: 658. Windows에서 실행 중인 소켓 서버를 다른 PC 또는 WSL에서 접속할 수 없는 경우
13224정성태1/21/20234209Windows: 221. Windows - Private/Public/Domain이 아닌 네트워크 어댑터 단위로 방화벽을 on/off하는 방법
13223정성태1/20/20234410오류 유형: 838. RDP 연결 오류 - The two computers couldn't connect in the amount of time allotted
13222정성태1/20/20234096개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234323Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234443오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20234011Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233948VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234529디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234782디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236348Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235883.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235429오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235179기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235209웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234300Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234203Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20234182.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224446.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224683.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...