Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 3개 있습니다.)
(시리즈 글이 6개 있습니다.)
Linux: 26. .NET Core 응용 프로그램을 위한 메모리 덤프 방법
; https://www.sysnet.pe.kr/2/0/12078

Linux: 27. linux - lldb를 이용한 .NET Core 응용 프로그램의 메모리 덤프 분석 방법
; https://www.sysnet.pe.kr/2/0/12083

.NET Framework: 2053. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프를 분석하는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/13135

.NET Framework: 2054. .NET Core/5+ SDK 설치 없이 dotnet-dump 사용하는 방법
; https://www.sysnet.pe.kr/2/0/13136

.NET Framework: 2055. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
; https://www.sysnet.pe.kr/2/0/13137

.NET Framework: 2057. 리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법
; https://www.sysnet.pe.kr/2/0/13139




리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 모든 닷넷 모듈을 추출하는 방법

지난 글을 통해 개별 모듈을 파일로 저장하는 방법을 설명했으니,

리눅스 환경의 .NET Core 3/5+ 메모리 덤프로부터 닷넷 모듈을 추출하는 방법
; https://www.sysnet.pe.kr/2/0/13137

이제 순서에 따라 ^^ .NET Framework에서 그랬던 것처럼 모든 닷넷 모듈을 파일로 자동 저장하는 방법을,

windbg - 풀 덤프에 포함된 모든 닷넷 모듈을 파일로 저장하는 방법
; https://www.sysnet.pe.kr/2/0/11297

알아보겠습니다. ^^




windbg의 경우, plug-in 규약이 잘 돼 있어 파이썬 스크립트를 쓸 수 있는 pykd 확장이 있었고, 그것의 힘을 빌려 메모리 덤프에 포함된 모든 닷넷 모듈을 자동으로 추출하는데 그다지 어려움이 없었습니다.

반면, dotnet-dump는 아직 딱히 확장 기술이 없는 것 같습니다. 더군다나, windbg의 ".writemem" 같은 명령어도 제공하지 않으므로 이러한 과정을 매끄럽게 할 수 있는 방법이 없습니다. 그리고 이 와중에 예전에 살펴봤던 ClrMD가 눈에 들어오는군요. ^^

.NET 스레드 콜 스택 덤프 (7) - ClrMD(Microsoft.Diagnostics.Runtime)를 이용한 방법
; https://www.sysnet.pe.kr/2/0/11043

ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
; https://www.sysnet.pe.kr/2/0/11809

자, 그럼 우선 우리가 해야 할 것은 닷넷 모듈을 찾는 것입니다.

// Install-Package Microsoft.Diagnostics.Runtime

// nuget - Microsoft.Diagnostics.Runtime 
// ; https://www.nuget.org/packages/Microsoft.Diagnostics.Runtime/

using Microsoft.Diagnostics.Runtime;

string dumpFilePath = @"C:\temp\core_20221007_000149.dmp";

using (DataTarget target = DataTarget.LoadDump(dumpFilePath))
{
    foreach (var module in target.EnumerateModules())
    {
        if (module.IsManaged == false)
        {
            continue;
        }

        Console.WriteLine($"{module.ImageBase:x} {module.ImageSize:x} {module.IsManaged} {module.FileName}");
    }    
}

출력 결과를 보면,

...[생략]...
7faa1c093000 64000 True /app/System.Configuration.ConfigurationManager.dll
7fb6d0020000 42000 True /app/log4net.dll
7fb6d7c20000 55200 True /usr/share/dotnet/shared/Microsoft.NETCore.App/3.1.22/System.Net.WebClient.dll
...[생략]...

지난 글에 설명한 lm과 clrmodules의 결과와 비교해 또 다른 값이 나오고 있습니다. 다행히 ImageBase 주소는 같고, 단지 ImageSize가 경우에 따라 lm 출력보다 큰 값을 보입니다. (값이 크니 차라리 다행입니다.)

그럼, 이제 게임 끝이군요. 주소와 크기를 구했으니, 그에 해당하는 바이트 스트림을 구해 파일로 출력하기만 하면 됩니다. 아래는 그 모든 코드를 다 합친 결과입니다.

using Microsoft.Diagnostics.Runtime;

string dumpFilePath = @"C:\temp\core_20221007_000149.dmp";
string outputDir = @"C:\temp\output";

using (DataTarget target = DataTarget.LoadDump(dumpFilePath))
{
    foreach (var module in target.EnumerateModules())
    {
        if (module.IsManaged == false)
        {
            continue;
        }

        Console.WriteLine($"{module.ImageBase:x} {module.ImageSize:x} {module.IsManaged} {module.FileName}");
        Span<byte> buffer = new byte[module.ImageSize];
        target.DataReader.Read(module.ImageBase, buffer);

        string fileName = Path.GetFileName(module.FileName);
        string outputFilePath = Path.Combine(outputDir, fileName);

        File.WriteAllBytes(outputFilePath, buffer.ToArray());
    }    
}

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




참고로, dotnet-dump의 확장이 없는 것을 아쉬운 대로 redirection을 이용해 우회하는 방법이 있습니다.

How can we script dotnet dump analyze commands?
; https://stackoverflow.com/questions/71803641/how-can-we-script-dotnet-dump-analyze-commands

가령, 닷넷 모듈 주소를 구하는 결과를 다음과 같은 식으로 얻는 것도 가능합니다.

c:\temp> type cmds.txt
clrmodules
quit

c:\temp> dotnet-dump analyze core_20221007_000149.dmp < cmds.txt > output.txt

그럼, output.txt에는 대충 다음과 같은 출력을 얻을 수 있겠고!

Loading core dump: core_20221007_000149.dmp ...
Ready to process analysis commands. Type 'help' to list available commands or 'help [command]' to get detailed help on a command.
Type 'quit' or 'exit' to exit the session.
<END_COMMAND_OUTPUT>
> clrmodules
...[생략]...
00007FAA1C093000 00060A68 /app/System.Configuration.ConfigurationManager.dll
00007FB6D0020000 0003F000 /app/log4net.dll
00007FB6D7C20000 00055200 /usr/share/dotnet/shared/Microsoft.NETCore.App/3.1.22/System.Net.WebClient.dll
...[생략]...




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/20/2022]

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

비밀번호

댓글 작성자
 




... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
11842정성태3/13/201910264개발 환경 구성: 433. 마이크로소프트의 CoreCLR 프로파일러 예제를 Visual Studio CMake로 빌드하는 방법 [1]파일 다운로드1
11841정성태3/13/201910228VS.NET IDE: 132. Visual Studio 2019 - CMake의 컴파일러를 기본 g++에서 clang++로 변경
11840정성태3/13/201911335오류 유형: 526. 윈도우 10 Ubuntu App 환경에서는 USB 외장 하드 접근 불가
11839정성태3/12/201914102디버깅 기술: 124. .NET Core 웹 앱을 호스팅하는 Azure App Services의 프로세스 메모리 덤프 및 windbg 분석 개요 [3]
11838정성태3/7/201916843.NET Framework: 811. (번역글) .NET Internals Cookbook Part 1 - Exceptions, filters and corrupted processes [1]파일 다운로드1
11837정성태3/6/201926545기타: 74. 도서: 시작하세요! C# 7.3 프로그래밍 [10]
11836정성태3/5/201914398오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201914173.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201913066개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201913827개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201910852오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201910447오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201910238오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201912139개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201918526개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201912406오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201912283오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201917181개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201911984오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201913479오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201911608오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201912082오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201915211오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201913878Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201912794VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/20199957오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...