Microsoft MVP성태의 닷넷 이야기
오류 유형: 917. ClrMD - Linux 환경의 .NET 5 덤프 분석 시 hang 현상 [링크 복사], [링크+제목 복사],
조회: 7639
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13337정성태5/5/202312839Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/202312364.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/202313262.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/202312274Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/202310804Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/202311096Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/202310712오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/202311286Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/202311464Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/202311291VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/202311498VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/202314072.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/202312221스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/202312472.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/202312111개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/202313654VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/202311554개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/202311337개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/202312301개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/202311988개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/202312179오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/202310662오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/202311587Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/202312452개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치 [1]
13313정성태4/9/202311873개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/202311630Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...