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

비밀번호

댓글 작성자
 




... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12396정성태11/3/20208414VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/20209736오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/20208155오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/20208652오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202012760.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202011031디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202010768.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202010223오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202011009.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202011253Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/20209069오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202010272오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
12383정성태10/27/202011161.NET Framework: 956. C# 9.0 - (7) 패턴 일치 개선 사항(Pattern matching enhancements) [3]파일 다운로드1
12382정성태10/26/20208888오류 유형: 671. dotnet build - The local source '...' doesn't exist
12381정성태10/26/202010547VC++: 137. C++ stl map의 사용자 정의 타입을 key로 사용하는 방법 [1]파일 다운로드1
12380정성태10/26/20207971오류 유형: 670. Visual Studio - Squash_FailureCommitsReset
12379정성태10/21/202010972.NET Framework: 955. .NET 메서드의 Signature 바이트 코드 분석 [1]파일 다운로드2
12378정성태10/15/202010388.NET Framework: 954. C# - x86/x64 환경에 따라 달라지는 P/Invoke 함수의 export 이름파일 다운로드1
12377정성태10/15/202011683디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208400오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/20209782Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(¥)' 기호로 나오는 경우 [1]
12374정성태10/14/202014396.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
12373정성태10/14/20209686.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
12372정성태10/13/202011498.NET Framework: 951. C# 9.0 - (5) 로컬 함수에 특성 지정 가능(Attributes on local functions)파일 다운로드1
12371정성태10/13/202010283개발 환경 구성: 519. Visual Studio의 Ctrl+Shift+U (Edit.MakeUppercase) 단축키가 동작하지 않는 경우
12370정성태10/13/202011182Linux: 33. Linux - nmcli를 이용한 고정 IP 설정
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...