Microsoft MVP성태의 닷넷 이야기
오류 유형: 917. ClrMD - Linux 환경의 .NET 5 덤프 분석 시 hang 현상 [링크 복사], [링크+제목 복사],
조회: 7624
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

ClrMD - Linux 환경의 .NET 5 덤프 분석 시 hang 현상

간단하게 .NET 5 콘솔 프로젝트를 만들고,

using System;

namespace ConsoleApp4
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"PID: {Environment.ProcessId}");
            Console.WriteLine("Hello, World!");
            Console.WriteLine("Press any key to exit...");

            Console.ReadLine();
        }
    }
}

Linux 환경에서 실행한 후, Microsoft.Diagnostics.NETCore.Client(혹은 dotnet-dump)를 이용해 메모리 덤프를 떴습니다. 그다음, ClrMD를 이용해 ClrVersions까지만 구했는데 hang 현상이 발생했습니다.

// Install-Package Microsoft.Diagnostics.Runtime

using (DataTarget target = DataTarget.LoadDump(dmpFilePath))
{
    ImmutableArray<ClrInfo> clrVersions = target.ClrVersions;
}

무엇이 문제인지 추적해 보면, 한창 hang 상태일 때 Break All을 걸어 실행을 멈추니 SingleFileClrInfoProvider.ProvideClrInfoForModule의 GetExportSymbolAddress에 걸려 있고,

// .\Microsoft.Diagnostics.Runtime\SingleFileClrInfoProvider.cs

// ...[생략]...

namespace Microsoft.Diagnostics.Runtime
{
    internal class SingleFileClrInfoProvider : DotNetClrInfoProvider
    {
        public override ClrInfo? ProvideClrInfoForModule(DataTarget dataTarget, ModuleInfo module)
        {
            ulong runtimeInfo = 0;
            if ((dataTarget.DataReader.TargetPlatform != OSPlatform.Windows) || Path.GetExtension(module.FileName).Equals(".exe", StringComparison.OrdinalIgnoreCase))
                runtimeInfo = module.GetExportSymbolAddress(ClrRuntimeInfo.SymbolValue);

            if (runtimeInfo == 0)
                return null;

            ClrInfo result = CreateClrInfo(dataTarget, module, runtimeInfo, ClrFlavor.Core);
            result.IsSingleFile = true;
            return result;
        }
    }
}

이때의 module은 "/usr/share/dotnet/shared/Microsoft.NETCore.App/5.0.17/System.Private.CoreLib.dll" 또는 "/usr/share/dotnet/shared/Microsoft.NETCore.App/5.0.17/System.Console.dll" 등에서 오래 걸려 있습니다. 이후 추적을 계속하면,

// .\Microsoft.Diagnostics.Runtime\Implementation\ElfModuleInfo.cs

public override ulong GetExportSymbolAddress(string symbol)
{
    if (_elf is null || !_elf.TryGetExportSymbol(symbol, out ulong address))
        return 0;

    return ImageBase + address;
}

실질적인 문제가 되는 for 루프에 다다르게 됩니다.

// .\Microsoft.Diagnostics.Runtime\Utilities\PEImage\PEImage.cs

public bool TryGetExportSymbol(string symbolName, out ulong offset)
{
    try
    {
        ImageDataDirectory exportTableDirectory = ExportDirectory;
        if (exportTableDirectory.VirtualAddress != 0 && exportTableDirectory.Size != 0)
        {
            if (TryRead(RvaToOffset(exportTableDirectory.VirtualAddress), out ImageExportDirectory exportDirectory))
            {
                for (int nameIndex = 0; nameIndex < exportDirectory.NumberOfNames; nameIndex++)
                {
                    int namePointerRVA = Read<int>(RvaToOffset(exportDirectory.AddressOfNames + (sizeof(uint) * nameIndex)));
                    if (namePointerRVA != 0)
                    {
                        string name = ReadNullTerminatedAscii(namePointerRVA, maxLength: 4096);
                        if (name == symbolName)
                        {
                            ushort ordinalForNamedExport = Read<ushort>(RvaToOffset(exportDirectory.AddressOfNameOrdinals + (sizeof(ushort) * nameIndex)));
                            int exportRVA = Read<int>(RvaToOffset(exportDirectory.AddressOfFunctions + (sizeof(uint) * ordinalForNamedExport)));
                            offset = (uint)RvaToOffset(exportRVA);
                            return true;
                        }
                    }
                }
            }
        }
    }
    catch (IOException)
    {
    }
    catch (InvalidDataException)
    {
    }

    offset = 0;
    return false;
}

nameIndex = 0으로 시작해, 이때의 NumberOfNames 값은 무려 1599230533이 나옵니다. 그러니까, 저 루프를 끝까지 도는 동안 외부에서는 hang 현상이 나온 듯 보인 것입니다.

다시 ProvideClrInfoForModule 메서드로 돌아가 이 상황을 종합해 볼까요?

// .\Microsoft.Diagnostics.Runtime\SingleFileClrInfoProvider.cs

public override ClrInfo? ProvideClrInfoForModule(DataTarget dataTarget, ModuleInfo module)
{
    ulong runtimeInfo = 0;
    if ((dataTarget.DataReader.TargetPlatform != OSPlatform.Windows) || Path.GetExtension(module.FileName).Equals(".exe", StringComparison.OrdinalIgnoreCase))
        runtimeInfo = module.GetExportSymbolAddress(ClrRuntimeInfo.SymbolValue); // SymbolValue == "DotNetRuntimeInfo"

    if (runtimeInfo == 0)
        return null;

    ClrInfo result = CreateClrInfo(dataTarget, module, runtimeInfo, ClrFlavor.Core);
    result.IsSingleFile = true;
    return result;
}

ClrInfo를 얻기 위해 Module의 ExportDirectory을 뒤져 DotNetRuntimeInfo에 해당하는 이름을 찾고 있습니다. 그래서 ExportDirectory 값을 디버거로 보니 이렇게 나오는데,

ImageDataDirectory exportTableDirectory = ExportDirectory;

// exportTableDirectory
//   .Size == 0x00000043
//   .VirtualAddress == 0x008f1d5c

제가 만든 WindowsPE 라이브러리를 사용해 저 "System.Private.CoreLib.dll" 파일을 덤프했더니 동일한 값이 나옵니다. ^^ (물론, windbg의 "!dh" 명령어로도 쉽게 확인할 수 있습니다.)

// Install-Package WindowsPE
PEImage pe = PEImage.ReadFromFile(@"c:\temp\System.Private.CoreLib.dll");
pe.ShowHeader();

/* 출력 결과:
...[생략]...
  8F1D5C [      43] address [size] of ExportTable Directory
       0 [       0] address [size] of ImportTable Directory
   42800 [     494] address [size] of ResourceTable Directory
...[생략]...
*/

그렇다면 이제 문제는 그다음 코드인,

// .\Microsoft.Diagnostics.Runtime\Utilities\PEImage\PEImage.cs

public bool TryGetExportSymbol(string symbolName, out ulong offset)
{
    int nameIndex = 0;
    try
    {
        ImageDataDirectory exportTableDirectory = ExportDirectory;
        if (exportTableDirectory.VirtualAddress != 0 && exportTableDirectory.Size != 0)
        {
            if (TryRead(RvaToOffset(exportTableDirectory.VirtualAddress), out ImageExportDirectory exportDirectory))
            {
                // ...[생략]...
}

TryRead에서 반환한 ImageExportDirectory 구조체의 값으로 넘어갑니다. 실제로 저 메서드에서 반환한 exportDirectory의 값은 그냥 봐도,

AddressOfFunctions  0x190a00ee  int
AddressOfNameOrdinals   0x1d526a09  int
AddressOfNames  0x23421009  int
Base    0x2651320b  int
Characteristics 0x2603043b  int
MajorVersion    0x5133  short
MinorVersion    0x4686  short
Name    0x51335b26  int
NumberOfFunctions   0xb3513183  int
NumberOfNames   0x035d5130  int
TimeDateStamp   0x2b5a2f63  int

문제가 있어 보입니다. 가령, .NET DLL의 경우 AddressOfFunctions는 대개 0인데 0x190a00ee와 같이 매우 큰 값이 나온 것입니다.




왜 저런 이상한 것이 나왔는지에 대한 이유는, TryRead를 하기 전 RvaToOffset을 호출해 RVA로부터 실제 주소를 구하는 단계에서 찾을 수 있습니다. 바로 여기에 문제가 있었는데요,

// .\Microsoft.Diagnostics.Runtime\Utilities\PEImage\PEImage.cs

public int RvaToOffset(int virtualAddress)
{
    if (virtualAddress < 4096)
        return virtualAddress;

    // 실행 상태 또는 메모리 덤프에는 아래의 코드에서 반환
    if (_isVirtual)
        return virtualAddress;

    // 파일 상태의 PE 데이터에서는 아래의 코드에서 반환
    ImageSectionHeader[] sections = ReadSections();
    for (int i = 0; i < sections.Length; i++)
    {
        ref ImageSectionHeader section = ref sections[i];
        if (section.VirtualAddress <= virtualAddress && virtualAddress < section.VirtualAddress + section.VirtualSize)
            return (int)(section.PointerToRawData + ((uint)virtualAddress - section.VirtualAddress));
    }

    return -1;
}

PE 파일은, 파일에 존재할 때는 Section으로부터 RVA를 이용한 file offset 위치를 구해야 하지만, 실행 시점에는, 즉 "_isVirtual" 필드가 "true"여야 해서 그 값 그대로를 반환해야 합니다. 그런데, 메모리 덤프를 분석하고 있는 ClrMD는 저 상태에서 _isVirtual이 false를 갖고 있습니다.

원인이 그것인지 간단하게 확인을 할 수 있는데요, 그냥 virtualAddress를 바로 반환하는 것입니다.

// .\Microsoft.Diagnostics.Runtime\Utilities\PEImage\PEImage.cs

public int RvaToOffset(int virtualAddress)
{
    return virtualAddress;
}

이후, 다시 .NET 5 덤프를 열어 TryRead가 반환한 ImageExportDirectory exportDirectory를 보면 정상적으로 값이 채워져 있습니다.

AddressOfFunctions	0x00000000	int
AddressOfNameOrdinals	0x00000000	int
AddressOfNames	0x00000000	int
Base	0x00000000	int
Characteristics	0x00000000	int
MajorVersion	0x0000	short
MinorVersion	0x0000	short
Name	0x008f1d84	int
NumberOfFunctions	0x00000000	int
NumberOfNames	0x00000000	int
TimeDateStamp	0x00000000	int

그렇다면, 왜 저런 문제가 .NET 6 이상의 메모리 덤프 분석에서는 발생하지 않는 걸까요? 이유는, .NET 6부터 포함된 DLL들은 아예 Export Data Directory가 없어 아래의 if 문 자체를 진입하지 않기 때문입니다.

public bool TryGetExportSymbol(string symbolName, out ulong offset)
{
    int nameIndex = 0;
    try
    {
        ImageDataDirectory exportTableDirectory = ExportDirectory;
        if (exportTableDirectory.VirtualAddress != 0 && exportTableDirectory.Size != 0)
        {




자, 원인을 알았으니 이제 해결책을 찾아보겠습니다. 우선, _isVirtual 필드를 설정하는 곳은 PEImage의 생성자인데,

// .\Microsoft.Diagnostics.Runtime\Utilities\PEImage\PEImage.cs

private PEImage(Stream stream, bool leaveOpen, bool isVirtual, ulong loadedImageBase)
{
    _isVirtual = isVirtual;

    // ...[생략]...
}

public PEImage(ReadVirtualStream stream, bool leaveOpen, bool isVirtual)
    : this(stream, leaveOpen, isVirtual, 0)
{
}

저 생성자는 PEModuleInfo에서 GetPEImage를 통해 호출되는데,

// .\Microsoft.Diagnostics.Runtime\Implementation\PEModuleInfo.cs

internal PEImage? GetPEImage()
{
    if (_peImage is not null || _loaded)
        return _peImage;

    try
    {
        PEImage image = new(new ReadVirtualStream(_dataReader, (long)ImageBase, int.MaxValue), leaveOpen: false, isVirtual: _isVirtual);
                
    // ...[생략]...
}

public PEModuleInfo(IDataReader dataReader, ulong imageBase, string fileName, bool isVirtualHint)
    : base(imageBase, fileName)
{
    if (dataReader is null)
        throw new ArgumentNullException(nameof(dataReader));

    if (fileName is null)
        throw new ArgumentNullException(nameof(fileName));

    _dataReader = dataReader;
    _isVirtual = isVirtualHint;
}

이상하게도, PEModuleInfo 생성자를 호출하는 CoreDumpReader 타입에서는 무조건 virtualHint를 false로 설정하고 있습니다.

// .\Microsoft.Diagnostics.Runtime\DataReaders\Core\CoreDumpReader.cs

private ModuleInfo CreateModuleInfo(ElfLoadedImage image)
{
    using ElfFile? file = image.Open();

    // We suppress the warning because the function it wants us to use is not available on all ClrMD platforms

    // This substitution is for unloaded modules for which Linux appends " (deleted)" to the module name.
    string path = image.FileName.Replace(" (deleted)", "");
    if (file is not null)
    {
        long size = image.Size > long.MaxValue ? long.MaxValue : unchecked((long)image.Size);
        return new ElfModuleInfo(this, file, image.BaseAddress, size, path);
    }

    return new PEModuleInfo(this, image.BaseAddress, path, false);
}

이름이 CoreDumpReader인 점을 감안하면, File로부터 직접 PE 이미지를 읽어들이는 것이 아니므로 virtualHint는 기본적으로 true여야 합니다.




혹시, 윈도우에서 뜬 .NET 5 덤프는 어떻게 분석하고 있을까요? 비교를 위해 보면 좋을 텐데, 바로 MinidumpReader.cs 파일이 그 역할을 담당하고 있습니다.

// .\Microsoft.Diagnostics.Runtime\DataReaders\Minidump\MinidumpReader.cs

public IEnumerable<ModuleInfo> EnumerateModules()
{
    // We set buildId to "Empty" since only PEImages exist where minidumps are created, and we do not
    // want to try to lazily evaluate the buildId later
    return from module in _minidump.EnumerateModuleInfo()
            select new PEModuleInfo(this, module.BaseOfImage, module.ModuleName ?? "", true, module.DateTimeStamp, module.SizeOfImage);
}

보는 바와 같이 저렇게 virtualHint를 고정으로 true를 주고 있으니... CoreDumpReader에서도 당연히 true로 설정하는 것이 맞습니다.

일단, 관련해서 이슈 제기와

_isVirtual has to be set as true in the context of DataTarget.LoadDump. #1279
; https://github.com/microsoft/clrmd/issues/1279

PR을 날렸는데 어떻게 될지 기다려야 할 듯합니다. ^^ (2024-08-14 업데이트: merge가 되었지만 nuget 릴리스는 아직 안 된 상태입니다.)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/14/2024]

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)
13917정성태4/30/202544VS.NET IDE: 199. Directory.Build.props에 정의한 속성에 대해 Condition 제약으로 값을 변경하는 방법
13916정성태4/23/2025446디버깅 기술: 221. WinDbg 분석 사례 - ASP.NET HttpCookieCollection을 다중 스레드에서 사용할 경우 무한 루프 현상 - 두 번째 이야기
13915정성태4/13/20251652닷넷: 2331. C# - 실행 시에 메서드 가로채기 (.NET 9)파일 다운로드1
13914정성태4/11/20251973디버깅 기술: 220. windbg 분석 사례 - x86 ASP.NET 웹 응용 프로그램의 CPU 100% 현상 (4)
13913정성태4/10/20251204오류 유형: 950. Process Explorer - 64비트 윈도우에서 32비트 프로세스의 덤프를 뜰 때 "Error writing dump file: Access is denied." 오류
13912정성태4/9/2025863닷넷: 2330. C# - 실행 시에 메서드 가로채기 (.NET 5 ~ .NET 8)파일 다운로드1
13911정성태4/8/20251091오류 유형: 949. WinDbg - .NET Core/5+ 응용 프로그램 디버깅 시 sos 확장을 자동으로 로드하지 못하는 문제
13910정성태4/8/20251257디버깅 기술: 219. WinDbg - 명령어 내에서 환경 변수 사용법
13909정성태4/7/20251725닷넷: 2329. C# - 실행 시에 메서드 가로채기 (.NET Framework 4.8)파일 다운로드1
13908정성태4/2/20252138닷넷: 2328. C# - MailKit: SMTP, POP3, IMAP 지원 라이브러리
13907정성태3/29/20251935VS.NET IDE: 198. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C# 프로젝트의 출력 경로 변경하기
13906정성태3/27/20252190닷넷: 2327. C# - 초기화되지 않은 메모리에 접근하는 버그?파일 다운로드1
13905정성태3/26/20252220Windows: 281. C++ - Windows / Critical Section의 안정화를 위해 도입된 "Keyed Event"파일 다운로드1
13904정성태3/25/20251902디버깅 기술: 218. Windbg로 살펴보는 Win32 Critical Section파일 다운로드1
13903정성태3/24/20251522VS.NET IDE: 197. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C++ 프로젝트의 출력 경로 변경하기
13902정성태3/24/20251737개발 환경 구성: 742. Oracle - 테스트용 hr 계정 및 데이터 생성파일 다운로드1
13901정성태3/9/20252112Windows: 280. Hyper-V의 3가지 Thread Scheduler (Classic, Core, Root)
13900정성태3/8/20252346스크립트: 72. 파이썬 - SQLAlchemy + oracledb 연동
13899정성태3/7/20251806스크립트: 71. 파이썬 - asyncio의 ContextVar 전달
13898정성태3/5/20252124오류 유형: 948. Visual Studio - Proxy Authentication Required: dotnetfeed.blob.core.windows.net
13897정성태3/5/20252367닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)파일 다운로드1
13896정성태3/5/20252178Windows: 279. Hyper-V Manager - VM 목록의 CPU Usage 항목이 항상 0%로 나오는 문제
13895정성태3/4/20252220Linux: 117. eBPF / bpf2go - Map에 추가된 요소의 개수를 확인하는 방법
13894정성태2/28/20252250Linux: 116. eBPF / bpf2go - BTF Style Maps 정의 구문과 데이터 정렬 문제
13893정성태2/27/20252197Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...