Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

COR_PRF_USE_PROFILE_IMAGES 옵션과 NGen의 "profiler-enhanced images"

.NET Profiler를 만드는 경우, 설정하는 옵션 중에 COR_PRF_USE_PROFILE_IMAGES라는 것이 있습니다. 문서 상의 설명을 보면,

COR_PRF_MONITOR Enumeration
; https://learn.microsoft.com/en-us/dotnet/framework/unmanaged-api/profiling/cor-prf-monitor-enumeration

Causes the native image search to look for profiler-enhanced images. If no profiler-enhanced image is found for a given assembly, the common language runtime falls back to JIT for that assembly. If this flag and the COR_PRF_DISABLE_ALL_NGEN_IMAGES flag are both specified, COR_PRF_DISABLE_ALL_NGEN_IMAGES is used.


COR_PRF_USE_PROFILE_IMAGES 옵션을 설정하게 되면 CLR에게 (일반적인 NGen 이미지를 로드하지 말고) "profiler-enhanced images"(또는 "image with Profile flavor")를 로드하도록 만들고, 만약 없다면 원본 어셈블리로부터 JIT하라는 것으로 나옵니다.

여기서 말하는 "profiler-enhanced image"에 대한 설명은 다음의 문서들에서 찾아 볼 수 있습니다.

Creating an IL-rewriting profiler - What about NGEN?
; https://learn.microsoft.com/en-us/archive/blogs/davbr/creating-an-il-rewriting-profiler

Enter, Leave, Tailcall Hooks Part 1: The Basics
; https://learn.microsoft.com/en-us/archive/blogs/davbr/enter-leave-tailcall-hooks-part-1-the-basics

정리해 보면, 일반적으로 NGen 이미지들은 해당 머신의 환경에 최적화된 기계어로 컴파일되어 있습니다. 그런데, 문제는 .NET Profiler로 해당 어셈블리들을 프로파일링하려면 IL 코드가 기계어로 jit되는 시점에 뭔가를 조작해야 하는데 NGen된 이미지들은 그럴 수가 없기 때문에 Profiler 입장에서는 할 수 있는 것이 없습니다. 따라서 프로파일러로 하여금 제어가 가능하도록 생성한 NGen 이미지들을 가리켜 "profiler-enhanced image"라고 하는 것입니다.

일반적으로, 마이크로소프트는 새로운 .NET Framework 버전 또는 업데이트를 설치하는 경우 BCL을 NGen시켜 둡니다. 이를 확인하는 방법은 다음과 같이 명령을 내려보면 됩니다.

c:\temp>ngen display mscorlib /verbose

...[생략]...

Native Images:

mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        Source MVID:    {97707D7E-03B0-454F-ADE5-26C74B667F46}
        Source HASH:    9e5ef9b3a78b8eecec12d101fed42ad3f7ed8c0d
        NGen GUID sign: {5057723C-3845-D0BB-8882-AF5AFEFB29A3}
        OS:             WinNT
        Processor:      amd64
        Runtime:        2.0.50727.8762
        mscorwks.dll:   TimeStamp=58E462F0, CheckSum=00994AA9
        Flags:
        Scenarios:              <no debug info> <no debugger> <no profiler> <no instrumentation>
        Granted set:    <PermissionSet class="System.Security.PermissionSet" version="1"/>

        File:           C:\Windows\assembly\NativeImages_v2.0.50727_64\mscorlib\3c7257504538bbd08882af5afefb29a3\mscorlib.ni.dll
        Dependencies:
                mscorlib, Version=2.0.0.0, PublicKeyToken=b77a5c561934e089:
                        Guid:{97707D7E-03B0-454F-ADE5-26C74B667F46}
                        Sign:9e5ef9b3a78b8eecec12d101fed42ad3f7ed8c0d

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
        Source MVID:    {19E40EE1-9924-457B-A371-5254132FC075}
        NGen GUID sign: {202CF701-7ECA-50F7-5AA3-E474EB475713}
        OS:             WinNT
        Processor:      amd64
        Runtime:        4.0.30319.0
        clr.dll:        TimeStamp=59A63E48, VirtualSize=009DF000
        Flags:
        Scenarios:              <no debug info> <no debugger> <no profiler> <no instrumentation>
        File:           C:\Windows\assembly\NativeImages_v4.0.30319_64\mscorlib\01f72c20ca7ef7505aa3e474eb475713\mscorlib.ni.dll
        No dependencies

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 <debug>
        Source MVID:    {2A8D77DF-0308-4EE3-8039-AD703E62FC78}
        NGen GUID sign: {B5B834D2-D442-D558-C658-964842CA41A3}
        OS:             WinNT
        Processor:      x86(Pentium 4) (features: 00008001)
        Runtime:        4.0.30319.0
        clr.dll:        TimeStamp=597BD742, VirtualSize=006E6000
        Flags:          <debug>
        Scenarios:              <debugger> <no profiler> <no instrumentation>
        File:           C:\WINDOWS\assembly\NativeImages_v4.0.30319_32\mscorlib\d234b8b542d458d5c658964842ca41a3\mscorlib.ni.dll
        No dependencies

위의 결과를 보면, mscorlib.dll의 경우 .NET 2.0 버전은 "C:\Windows\assembly\NativeImages_v2.0.50727_64\mscorlib\3c7257504538bbd08882af5afefb29a3\mscorlib.ni.dll" 파일로 ngen되어 있고 순수하게 기계어 변환 작업만 한 것입니다.

반면, .NET 4.0 버전의 mscorlib.dll은 ngen된 이미지가 2개가 있는데, "C:\Windows\assembly\NativeImages_v4.0.30319_64\mscorlib\01f72c20ca7ef7505aa3e474eb475713\mscorlib.ni.dll"은 release 버전의 ngen 이미지인 반면 "C:\WINDOWS\assembly\NativeImages_v4.0.30319_32\mscorlib\d234b8b542d458d5c658964842ca41a3\mscorlib.ni.dll" 파일은 debug 버전의 ngen 이미지임을 알 수 있습니다. (debug 버전의 경우, 제가 알기로는 Visual Studio가 생성합니다.)

이렇게, 마이크로소프트는 새로운 버전의 닷넷이나 그에 대한 업데이트를 설치하는 경우 기본적으로 "profiler-enhanced image"는 생성해 두지 않습니다.




물론, 원한다면 "profiler-enhanced image"를 생성하는 것이 가능합니다. 예를 들어, 다음의 명령은 "mscorlib.dll"을 대상으로 "profiler-enhanced image"를 생성하게 됩니다.

//  관리자 권한으로 실행한 cmd.exe

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>ngen install mscorlib.dll /Profile
Microsoft (R) CLR Native Image Generator - Version 4.7.2046.0
Copyright (c) Microsoft Corporation.  All rights reserved.
1>    Compiling assembly C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll (CLR v4.0.30319) ...

그런 다음 다시 "ngen display mscorlib /verbose" 명령어로 확인해 보면 다음과 같은 항목이 추가된 것을 볼 수 있습니다.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>ngen display mscorlib /verbose
Microsoft (R) CLR Native Image Generator - Version 4.7.2046.0
Copyright (c) Microsoft Corporation.  All rights reserved.

NGEN Roots:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll
    ScenarioProfile, Runtime version = v4.0.30319
        C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll
            DisplayName = mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
            Native image = {B94A5D4E-67C3-3334-F48D-732F7F3F719F}
            Hard Dependencies:
            Soft Dependencies:

NGEN Roots that depend on "mscorlib":

...[생략]...

mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 <profiling>
        Source MVID:    {9FACBD76-75F5-45B1-86B6-BE0E55785D7F}
        NGen GUID sign: {B94A5D4E-67C3-3334-F48D-732F7F3F719F}
        OS:             WinNT
        Processor:      amd64
        Runtime:        4.0.30319.0
        clr.dll:        TimeStamp=597BD642, VirtualSize=009DF000
        Flags:          <profiling>
        Scenarios:              <no debug info> <no debugger> <instrumenting profiler> <no instrumentation>
        File:           C:\WINDOWS\assembly\NativeImages_v4.0.30319_64\mscorlib\354feb5569398af61314e480a5b8d7ad\mscorlib.ni.dll
        No dependencies

이렇게 "profiler-enhanced image"가 있으면 (COR_PRF_USE_PROFILE_IMAGES 옵션을 사용하는) .NET Profiler의 동작이 다음과 같이 달라집니다.

// COR_PRF_USE_PROFILE_IMAGES + "No profiler-enhanced image" == 새로 JIT
C:\Windows\Microsoft.NET\assembly\GAC_64\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll

// COR_PRF_USE_PROFILE_IMAGES + "profiler-enhanced image" == instrumenting profiler로 지정된 native image 로드
C:\Windows\assembly\NativeImages_v4.0.30319_64\mscorlib\354feb5569398af61314e480a5b8d7ad\mscorlib.ni.dll

"profiler-enhanced image"가 없을 때는 원본 mscorlib.dll로부터 JIT를 다시 했지만, "profiler-enhanced image"가 있을 때는 NGen 처리된 그 모듈을 로드해 처리하기 때문에 JIT로 인한 로딩 시간이 그만큼 감소하는 효과를 보게 됩니다.




그런데, 여기서 궁금한 것이 있습니다. 그렇다면 닷넷 BCL의 경우 ngen을 이용해 "profiler-enhanced image"를 한번 생성해 두었는데 이후 보안 업데이트나 기능 업데이트로 인해 원본 파일이 바뀐다면 어떻게 되는 걸까요?

제 짐작으로는 다시 풀려서 그에 맞게 새로 생성해야 할 거라고 생각했는데요. 확인을 위해 Windows 7 VM을 올려 테스트해 봤습니다.

우선 .NET Framework 4를 설치 후 ngen /profile을 한 다음 .NET Framework 4.7을 설치해 본 것인데요. 예상과는 달리 닷넷 프레임워크 설치 프로그램은 똑똑했습니다. ^^ /profile 이미지가 있는 경우 새로운 버전의 닷넷 프레임워크가 설치되는 경우 그에 대해서도 함께 생성해 주었습니다. (혹시, 이렇게 동작한다는 문서 상의 기록을 찾으신 분 있으면 덧글 부탁드립니다. ^^)
일단 기존 생성한 /profile 이미지가 삭제되지 않은 체로 남아 있게 되지만 새로 설치된 .NET DLL들과 맞지 않으므로 사용이 안됩니다. 따라서 이런 경우 새롭게 /profile 이미지를 생성해야 합니다.




참고로, ngen display 결과가 너무 많은데 profiler-enhanced image가 생성되었음을 확인하는 정도의 용도라면 다음과 같이 하는 것이 더 간결한 출력 결과를 얻을 수 있습니다.

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>ngen display | find "<profiling>"
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 <profiling>




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

[연관 글]






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

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-05-24 01시51분
Conversation about PGO
; https://devblogs.microsoft.com/dotnet/conversation-about-pgo/

.NET 7.0's Performance Improvements with Dynamic PGO are Incredible
; https://petabridge.com/blog/dotnet7-pgo-performance-improvements/
정성태

... 91  92  93  94  95  96  97  98  [99]  100  101  102  103  104  105  ...
NoWriterDateCnt.TitleFile(s)
11163정성태3/25/201713434VC++: 110. CreateThread Win32 API에 C++ 클래스의 멤버 함수를 전달하는 방법파일 다운로드1
11162정성태3/24/201716955오류 유형: 380. Visual Studio 빌드 실패 - The OutputPath property is not set for project
11161정성태3/24/201711283오류 유형: 379. ICOMAdminCatalog.GetCollection 호출 시 0x80070422 예외 발생
11160정성태3/23/201714788.NET Framework: 649. ASP.NET - Server cannot append header after HTTP headers have been sent. (HTTP 헤더를 보낸 후에는 서버에서 헤더를 추가할 수 없습니다.)파일 다운로드1
11159정성태3/23/201712096Windows: 136. Memory-mapped File은 Private Bytes 크기에 포함될까요?파일 다운로드1
11158정성태3/22/201712374디버깅 기술: 85. Windbg - SOS 디버깅 사례 System.NullReferenceException 예외 추적
11157정성태3/22/201714829.NET Framework: 648. Dictionary<TKey, TValue>를 deep copy하는 방법파일 다운로드1
11156정성태3/21/201714937.NET Framework: 647. 닷넷(C#) 코드로 인증서 요청 코드 만드는 방법파일 다운로드1
11155정성태3/21/201715280.NET Framework: 646. SslStream의 CipherAlgorithm 선택이 가능할까요?파일 다운로드1
11154정성태3/5/201723063VC++: 109. DLL에서 STL 객체를 인자/반환값으로 갖는 함수를 제공할 때, 그 함수를 외부에서 사용하는 경우 비정상 종료한다면? [2]파일 다운로드1
11153정성태3/5/201722734VC++: 108. DLL에 정의된 C++ template 클래스의 복사 생성자 문제파일 다운로드1
11152정성태3/4/201715339VC++: 107. VirtualAlloc, HeapAlloc, GlobalAlloc, LocalAlloc, malloc, new의 차이점파일 다운로드1
11151정성태3/3/201715950VC++: 106. DLL 개발자가 주의해야 할 Secure CRT 함수 사용 [1]파일 다운로드1
11150정성태2/21/201712265.NET Framework: 645. Visual Studio Fakes 기능에서 Shim... 클래스가 생성되지 않는 경우 [5]
11149정성태2/21/201715464오류 유형: 378. A 64-bit test cannot run in a 32-bit process. Specify platform as X64 to force test run in X64 mode on X64 machine.
11148정성태2/20/201714213.NET Framework: 644. AppDomain에 대한 단위 테스트 시 알아야 할 사항
11147정성태2/19/201714609오류 유형: 377. Windows 10에서 Fake 어셈블리를 생성하는 경우 빌드 시 The type or namespace name '...' does not exist in the namespace 컴파일 오류 발생
11146정성태2/19/201712801오류 유형: 376. Error VSP1033: The file '...' does not contain a recognized executable image. [2]
11145정성태2/16/201713975.NET Framework: 643. 작업자 프로세스(w3wp.exe)가 재시작되는 시점을 알 수 있는 방법 - 두 번째 이야기 [4]파일 다운로드1
11144정성태2/6/201717618.NET Framework: 642. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (부록 1) - CallingConvention.StdCall, CallingConvention.Cdecl에 상관없이 왜 호출이 잘 될까요?파일 다운로드1
11143정성태2/5/201714702.NET Framework: 641. [Out] 형식의 int * 인자를 가진 함수에 대한 P/Invoke 호출 방법파일 다운로드1
11142정성태2/5/201722014.NET Framework: 640. 닷넷 - 배열 크기의 한계 [2]파일 다운로드1
11141정성태1/31/201716785.NET Framework: 639. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (4) - CLR JIT 컴파일러의 P/Invoke 호출 규약 [1]파일 다운로드1
11140정성태1/27/201713233.NET Framework: 638. RSAParameters와 RSA파일 다운로드1
11139정성태1/22/201715295.NET Framework: 637. C# 개발자를 위한 Win32 DLL export 함수의 호출 규약 (3) - x64 환경의 __fastcall과 Name mangling [1]파일 다운로드1
11138정성태1/20/201714082VS.NET IDE: 113. 프로젝트 생성 시부터 "Enable the Visual Studio hosting process" 옵션을 끄는 방법 - 두 번째 이야기 [3]
... 91  92  93  94  95  96  97  98  [99]  100  101  102  103  104  105  ...