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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
14027정성태10/15/2025474닷넷: 2371. C# - CRC64 (System.IO.Hashing의 약식 버전)파일 다운로드1
14026정성태10/15/2025500닷넷: 2370. 닷넷 지원 정보의 "package-provided" 의미
14025정성태10/14/2025777Linux: 126. eBPF (bpf2go) - tcp_sendmsg 예제
14024정성태10/14/2025812오류 유형: 984. Whisper.net - System.Exception: 'Cannot dispose while processing, please use DisposeAsync instead.'
14023정성태10/12/20251241닷넷: 2369. C# / Whisper 모델 - 동영상의 음성을 인식해 자동으로 SRT 자막 파일을 생성 [1]파일 다운로드1
14022정성태10/10/20252107닷넷: 2368. C# / NAudio - (AI 학습을 위해) 무음 구간을 반영한 오디오 파일 분할파일 다운로드1
14021정성태10/6/20252665닷넷: 2367. C# - Youtube 동영상 다운로드 (YoutubeExplode 패키지) [1]파일 다운로드1
14020정성태10/2/20252302Linux: 125. eBPF - __attribute__((preserve_access_index)) 활용 사례
14019정성태10/1/20252435Linux: 124. eBPF - __sk_buff / sk_buff 구조체
14018정성태9/30/20251799닷넷: 2366. C# - UIAutomationClient를 이용해 시스템 트레이의 아이콘을 열거하는 방법파일 다운로드1
14017정성태9/29/20252262Linux: 123. eBPF (bpf2go) - BPF_PROG_TYPE_SOCKET_FILTER 예제 - SEC("socket")
14016정성태9/28/20252539Linux: 122. eBPF - __attribute__((preserve_access_index)) 사용법
14015정성태9/22/20251982닷넷: 2365. C# - FFMpegCore를 이용한 MP4 동영상으로부터 MP3 음원 추출 예제파일 다운로드1
14014정성태9/17/20251968닷넷: 2364. C# - stun.l.google.com을 사용해 공용 IP 주소와 포트를 알아내는 방법파일 다운로드1
14013정성태9/14/20252610닷넷: 2363. C# - Whisper.NET Library를 이용해 음성을 텍스트로 변환 및 번역하는 예제파일 다운로드1
14012정성태9/9/20252862닷넷: 2362. C# - Windows.Media.Ocr: 윈도우 운영체제에 포함된 OCR(Optical Character Recognition)파일 다운로드1
14011정성태9/7/20253497닷넷: 2361. C# - Linux 환경의 readlink 호출
14010정성태9/1/20253314오류 유형: 983. apt update 시 "The repository 'http://deb.debian.org/debian buster Release' does not have a Release file." 오류
14009정성태8/28/20253776닷넷: 2360. C# 14 - (11) Expression Tree에 선택적 인수와 명명된 인수 허용파일 다운로드1
14008정성태8/26/20254354닷넷: 2359. C# 14 - (10) 복합 대입 연산자의 오버로드 지원파일 다운로드1
14007정성태8/25/20254762닷넷: 2358. C# - 현재 빌드에 적용 중인 컴파일러 버전 확인 방법 (#error version)
14006정성태8/23/20255053Linux: 121. Linux - snap 패키지 관리자로 설치한 소프트웨어의 디렉터리 접근 제한
14005정성태8/21/20254028오류 유형: 982. sudo: unable to load /usr/libexec/sudo/sudoers.so: libssl.so.3: cannot open shared object file: No such file or directory
14004정성태8/21/20254614오류 유형: 981. dotnet 실행 시 No usable version of the libssl was found
14003정성태8/21/20254879닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...