Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 9개 있습니다.)
.NET Framework: 216. 라이선스까지도 뛰어넘는 .NET Profiler
; https://www.sysnet.pe.kr/2/0/1046

.NET Framework: 336. .NET Profiler가 COM 개체일까?
; https://www.sysnet.pe.kr/2/0/1352

.NET Framework: 576. 기본적인 CLR Profiler 소스 코드 설명
; https://www.sysnet.pe.kr/2/0/10950

.NET Framework: 582. CLR Profiler - 별도 정의한 .NET 코드를 호출하도록 IL 코드 변경
; https://www.sysnet.pe.kr/2/0/10959

.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
; https://www.sysnet.pe.kr/2/0/11810

오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
; https://www.sysnet.pe.kr/2/0/12384

.NET Framework: 987. .NET Profiler - FunctionID와 연관된 ClassID를 구할 수 없는 문제
; https://www.sysnet.pe.kr/2/0/12465

.NET Framework: 1041. C# - AssemblyID, ModuleID를 관리 코드에서 구하는 방법
; https://www.sysnet.pe.kr/2/0/12605

닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
; https://www.sysnet.pe.kr/2/0/13576




C# - AssemblyID, ModuleID를 관리 코드에서 구하는 방법

예전에 설명한 .NET Profiler에서,

기본적인 CLR Profiler 소스 코드 설명
; https://www.sysnet.pe.kr/2/0/10950

ModuleLoadFinished 콜백의 인자로 ModuleID가 있습니다.

HRESULT CBasicClrProfiler::ModuleLoadFinished(ModuleID moduleId, HRESULT hrStatus)
{
    // ...[생략]...
    return S_OK;
}

혹시 이 값을 관리 코드에서 구하는 것이 가능할까요? 위의 값을 로그로 남겨 보고 관리 코드에서 이거저거 살펴보니 값 자체는 구할 수 있지만 아쉽게도 private 필드에 저장이 되어 있습니다.

using System;
using System.Reflection;
using System.Runtime.InteropServices;

class Program
{
    static void Main(string[] args)
    {
        // System.EnterpriseServices 어셈블리를 로딩하기 위해!
        System.EnterpriseServices.ApplicationQueuingAttribute aqa = new System.EnterpriseServices.ApplicationQueuingAttribute();

        foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
        {
            foreach (Module mod in asm.GetModules())
            {
                PrintModuleHandle(mod.Name, mod);
            }

            Console.WriteLine();
        }
    }

    private static void PrintModuleHandle(string name, Module module)
    {
        string dataFieldName = (Environment.Version.Major == 2) ? "m__pData" : "m_pData";
        IntPtr pData = (IntPtr)GetPrivateFieldValue(module, dataFieldName);
        Console.WriteLine($"{name}, {pData.ToInt64().ToString("x")}");
    }

    private static object GetPrivateFieldValue(object instance, string fieldName)
    {
        Type type = instance.GetType();

        FieldInfo fi = type.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance);
        return fi.GetValue(instance);
    }
}

/* 출력 결과
mscorlib.dll, 7ffe89211000

ConsoleApp1.exe, 7ffe32084148

System.EnterpriseServices.dll, 7ffe4f061000
System.EnterpriseServices.Wrapper.dll, 7ffe4ecc1000

System.dll, 7ffe87ca1000
*/




위의 출력 결과를 이미지 로딩 주소와 비교해 볼까요? 간단하게 Visual Studio의 "Debug" / "Windows" / "Modules (Ctrl+Alt+U)" 창을 띄워,

managed_dll_info_1.png

값을 비교해 보면, C#의 출력 결과에 대해 0x1000(4096)만큼 뺀 값이 "Modules" 창의 "Address"에 나오고 있습니다. 즉, ModuleID가 dll의 로딩 주소를 정확하게 가리키고 있지는 않습니다.

그나저나 애매하군요, 저 0x1000 값의 기준을 알 수 없습니다. 그나마 엮어볼 수 있는 값이 mscorlib.dll의 IMAGE_NT_HEADERS.IMAGE_OPTIONAL_HEADER.BaseOfCode인데, 아쉽게도 PE Viewer 같은 도구로 보면 0x2000 값이 나옵니다. 게다가 Section Alignment도 0x2000이고.

이와 함께, ConsoleApp1.exe의 경우 로딩 주소가 0x5a0000으로 나오고, ModuleID는 7ffe32084148로 아예 다른 값이 나오는데요. 이것은 전에 설명했던,

CLR 4.0 환경에서 DLL 모듈의 로드 주소(Base address) 알아내는 방법
; https://www.sysnet.pe.kr/2/0/11325

Marshal.GetHINSTANCE의 반환값과 일치합니다.




하는 김에, AssemblyLoadStarted 콜백의 인자로 전달되는 AssemblyID도 찾아볼까요?

HRESULT CBasicClrProfiler::AssemblyLoadStarted(AssemblyID assemblyId)
{
    return S_OK;
}

애석하게도 이 값은 정확히 떨어지는 값으로는 Managed 코드에서 알 수 있는 방법이 없습니다. 관리 타입의 Assembly에는 AssemblyID를 나타내는 필드를 전혀 노출하지 않기 때문인데요.

ModuleID를 구했을 때와 약간 유사하게 Assembly 타입에서도 m__assembly/m_assembly 필드를 private으로 노출하고 있지만 실제로 값을 구해 보면 Profiler의 AssemblyID와는 다르다는 것을 알 수 있습니다. 대신 해당 값은 Unmanaged 측의 Assembly 인스턴스 값을 가리키고 있는데 .NET 4 + x64 환경의 경우 m_assembly가 가리키는 위치에서 [0x8 * 15]에 AssemblyID 값이 있다는 것을 실험적으로 알 수 있습니다.

foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
    IntPtr pAssemblyAddr = (IntPtr)GetPrivateFieldValue(asm, assemblyFieldName);
    long *ptrAssembly = (long *)(pAssemblyAddr + (0x8 * 15)).ToPointer();
    Console.WriteLine("Assembly.m_assembly: " + (*ptrAssembly).ToString("x"));
}

아시다시피, 이 방법으로 접근하는 것은 다양한 버전과 그것의 패치를 고려했을 때 안정성 측면에서 쓸만한 방법은 아닙니다.

어쩔 수 없습니다. 이런 경우에는 차선책으로 Profiler 측의 ICorProfilerInfo::GetModuleInfo Method를 호출하도록 pinvoke 호출을 만들어 ModuleId로부터 AssemblyID를 반환하는 GetModuleInfo 함수를 호출하는 것이 그나마 낫습니다.

ICorProfilerInfo::GetModuleInfo Method
; https://learn.microsoft.com/en-us/dotnet/framework/unmanaged-api/profiling/icorprofilerinfo-getmoduleinfo-method

{
    ULONG cchModule = _MAX_PATH;
    ULONG rCchModule = 0;
    AssemblyID assemblyId = 0;
    LPCBYTE pModuleBaseLoadAddress;
    wchar_t szModule[_MAX_PATH];

    HRESULT hr = m_pICorProfilerInfo2->GetModuleInfo(moduleId,
        &pModuleBaseLoadAddress, cchModule, &rCchModule, szModule, &assemblyId);

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

    return S_OK;
}

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/7/2023]

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)
13355정성태5/12/20233817.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20234074.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233686.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234174VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233463오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233771.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233674.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20234052.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
13346정성태5/10/20233892오류 유형: 858. RDP 원격 환경과 로컬 PC 간의 Ctrl+C, Ctrl+V 복사가 안 되는 문제
13345정성태5/9/20235268.NET Framework: 2117. C# - (OpenAI 기반의) Microsoft Semantic Kernel을 이용한 자연어 처리 [1]파일 다운로드1
13344정성태5/9/20236475.NET Framework: 2116. C# - OpenAI API 사용 - 지원 모델 목록 [1]파일 다운로드1
13343정성태5/9/20234332디버깅 기술: 192. Windbg - Hyper-V VM으로 이더넷 원격 디버깅 연결하는 방법
13342정성태5/8/20234250.NET Framework: 2115. System.Text.Json의 역직렬화 시 필드/속성 주의
13341정성태5/8/20233999닷넷: 2114. C# 12 - 모든 형식의 별칭(Using aliases for any type)
13340정성태5/8/20234071오류 유형: 857. Microsoft.Data.SqlClient.SqlException - 0x80131904
13339정성태5/6/20234730닷넷: 2113. C# 12 - 기본 생성자(Primary Constructors)
13338정성태5/6/20234242닷넷: 2112. C# 12 - 기본 람다 매개 변수파일 다운로드1
13337정성태5/5/20234751Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/20234557.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/20234662.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/20234288Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/20233739Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/20233838Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/20233846오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/20233483Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/20233706Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...