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)
13484정성태12/14/20232176개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232317닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232918닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232293개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232664개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232347개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232542닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232276닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232343닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232185개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
13473정성태12/5/20232396닷넷: 2179. C# - 값 형식(Blittable)을 메모리 복사를 이용해 바이트 배열로 직렬화/역직렬화파일 다운로드1
13472정성태12/4/20232218C/C++: 164. Visual C++ - InterlockedCompareExchange128 사용 방법
13471정성태12/4/20232295Copilot - To enable GitHub Copilot, authorize this extension using GitHub's device flow
13470정성태12/2/20232599닷넷: 2178. C# - .NET 8부터 COM Interop에 대한 자동 소스 코드 생성 도입파일 다운로드1
13469정성태12/1/20232318닷넷: 2177. C# - (Interop DLL 없이) CoClass를 이용한 COM 개체 생성 방법파일 다운로드1
13468정성태12/1/20232258닷넷: 2176. C# - .NET Core/5+부터 달라진 RCW(Runtime Callable Wrapper) 대응 방식파일 다운로드1
13467정성태11/30/20232354오류 유형: 882. C# - Unhandled exception. System.Runtime.InteropServices.COMException (0x800080A5)파일 다운로드1
13466정성태11/29/20232522닷넷: 2175. C# - DllImport 메서드의 AOT 지원을 위한 LibraryImport 옵션
13465정성태11/28/20232294개발 환경 구성: 689. MSBuild - CopyToOutputDirectory가 "dotnet publish" 시에는 적용되지 않는 문제파일 다운로드1
13464정성태11/28/20232423닷넷: 2174. C# - .NET 7부터 UnmanagedCallersOnly 함수 export 기능을 AOT 빌드에 통합파일 다운로드1
13463정성태11/27/20232379오류 유형: 881. Visual Studio - NU1605: Warning As Error: Detected package downgrade
13462정성태11/27/20232394오류 유형: 880. Visual Studio - error CS0246: The type or namespace name '...' could not be found
13461정성태11/26/20232418닷넷: 2173. .NET Core 3/5+ 기반의 COM Server를 registry 등록 없이 사용하는 방법파일 다운로드1
13460정성태11/26/20232366닷넷: 2172. .NET 6+ 기반의 COM Server 내에 Type Library를 내장하는 방법파일 다운로드1
13459정성태11/26/20232334닷넷: 2171. .NET Core 3/5+ 기반의 COM Server를 기존의 regasm처럼 등록하는 방법파일 다운로드1
13458정성태11/26/20232360닷넷: 2170. .NET Core/5+ 기반의 COM Server를 tlb 파일을 생성하는 방법(tlbexp)
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...