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/
정성태

... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12856정성태11/23/20218900.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [2]
12855정성태11/13/20216246개발 환경 구성: 605. Azure App Service - Kudu SSH 환경에서 FTP를 이용한 파일 전송
12854정성태11/13/20217802개발 환경 구성: 604. Azure - 윈도우 VM에서 FTP 여는 방법
12853정성태11/10/20216168오류 유형: 766. Azure App Service - JBoss 호스팅 생성 시 "This region has quota of 0 PremiumV3 instances for your subscription. Try selecting different region or SKU."
12851정성태11/1/20217558스크립트: 34. 파이썬 - MySQLdb 기본 예제 코드
12850정성태10/27/20218704오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
12849정성태10/17/20217852스크립트: 33. JavaScript와 C#의 시간 변환 [1]
12848정성태10/17/20218818스크립트: 32. 파이썬 - sqlite3 기본 예제 코드 [1]
12847정성태10/14/20218664스크립트: 31. 파이썬 gunicorn - WORKER TIMEOUT 오류 발생
12846정성태10/7/20218418스크립트: 30. 파이썬 __debug__ 플래그 변수에 따른 코드 실행 제어
12845정성태10/6/20218246.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
12844정성태10/3/20216250오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/20216698스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202125053오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/20218521스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/20218621.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/20219672.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/20219325.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/20218231VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/20217838Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/20219078.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/20217479오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/20216918VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/20217780VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/20216318VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/20218579오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...