Microsoft MVP성태의 닷넷 이야기
.NET Framework: 575. SharedDomain과 JIT 컴파일 [링크 복사], [링크+제목 복사]
조회: 12684
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 6개 있습니다.)
.NET Framework: 574. .NET - 눈으로 확인하는 SharedDomain의 동작 방식
; https://www.sysnet.pe.kr/2/0/10948

.NET Framework: 575. SharedDomain과 JIT 컴파일
; https://www.sysnet.pe.kr/2/0/10949

.NET Framework: 577. CLR Profiler로 살펴보는 SharedDomain의 모듈 로드 동작
; https://www.sysnet.pe.kr/2/0/10951

.NET Framework: 578. 도메인 중립적인 어셈블리가 비-도메인 중립적인 어셈블리를 참조하는 경우
; https://www.sysnet.pe.kr/2/0/10952

닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법
; https://www.sysnet.pe.kr/2/0/13568

닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC
; https://www.sysnet.pe.kr/2/0/13569




SharedDomain과 JIT 컴파일

지난 글에서, SharedDomain에 대해 알아봤는데요.

.NET - 눈으로 확인하는 SharedDomain의 동작 방식
; https://www.sysnet.pe.kr/2/0/10948

기왕 하는 김에 JIT 컴파일된 코드의 공유 여부도 확인해 보겠습니다.

SharedDomain에 올라왔다는 것은, 곧 JIT 컴파일된 기계어 코드도 공유된다는 의미입니다. 확인을 위해 지난번 예제에서 메서드의 JITted 주소를 출력하도록 수정해 보겠습니다.

우선 Main 메서드의 코드는 테스트 결과의 구분을 위해 LoaderOptimization.MultiDomainHost 모드로 선택하고,

// ============== ConsoleApplication1 프로젝트의 Main 메서드 ======================
using System;

namespace ConsoleApplication1
{
    partial class Program
    {
        [LoaderOptimization(LoaderOptimization.MultiDomainHost)]
        static void Main(string[] args)
        {
            new StrongDLL.Class1().DoMethod();
            new WeakDLL.Class1().DoMethod(); 

            Console.WriteLine();

            AppDomain appDomain = AppDomain.CreateDomain("TestAppDomain 1");
            appDomain.DoCallBack(
                () =>
                {
                    new StrongDLL.Class1().DoMethod();
                    new WeakDLL.Class1().DoMethod();
                }
            );

            Console.WriteLine("Press any key to exit...");
            Console.ReadLine();
        }
    }
}

GAC에 등록될 StrongDLL 프로젝트와, 등록되지 않을 WeakDLL 프로젝트에서는 해당 메서드 내부에서 JITted 주소를 출력하도록 변경했습니다.

// ============== StrongDLL, WeakDLL 라이브러리 프로젝트의 DoMethod 메서드 ======================
using System;
using System.Diagnostics;

namespace StrongDLL // WeakDLL 라이브러리의 경우 네임스페이스만 "WeakDLL"로 변경
{
    public class Class1
    {
        public void DoMethod()
        {
            Console.WriteLine(typeof(Class1).FullName + ".DoMethod called");

            StackFrame sf = new StackFrame();
            Console.WriteLine("JIT Address: 0x{0}", sf.GetMethod().MethodHandle.GetFunctionPointer().ToInt64().ToString("x"));
        }
    }
}

이렇게 변경하고 실행하면 다음과 같은 결과를 얻을 수 있습니다.

StrongDLL.Class1.DoMethod called
JIT Address: 0x7ffab7150c30
WeakDLL.Class1.DoMethod called
JIT Address: 0x7ffab7150e10

StrongDLL.Class1.DoMethod called
JIT Address: 0x7ffab7150c30
WeakDLL.Class1.DoMethod called
JIT Address: 0x7ffab71c0630

보는 바와 같이 LoaderOptimization.MultiDomainHost 모드에서는 GAC에 등록된 DLL이 SharedDomain에 로드되기 때문에 출력된 "StrongDLL.Class1.DoMethod"의 "JIT Address" 값도 동일합니다. 반면, 각각의 AppDomain에 로드된 WeakDLL.Class1.DoMethod 메서드의 "JIT Address"는 0x7ffab7150e10, 0x7ffab71c0630로 틀립니다.




참고로, windbg에서 확인하려면 다음과 같이 할 수 있습니다.

0:007> .loadby sos clr

0:007> !name2ee StrongDLL.dll!StrongDLL.Class1.DoMethod
Module:      00007ffab7034780
Assembly:    StrongDLL.dll
Token:       0000000006000001
MethodDesc:  00007ffab7034dc8
Name:        StrongDLL.Class1.DoMethod()
JITTED Code Address: 00007ffab7150c30

0:007> !name2ee WeakDLL.dll!WeakDLL.Class1.DoMethod
Module:      00007ffab7045cb8
Assembly:    WeakDLL.dll
Token:       0000000006000001
MethodDesc:  00007ffab7046350
Name:        WeakDLL.Class1.DoMethod()
JITTED Code Address: 00007ffab7150e10
--------------------------------------
Module:      00007ffab71a5dc0
Assembly:    WeakDLL.dll
Token:       0000000006000001
MethodDesc:  00007ffab71a6458
Name:        WeakDLL.Class1.DoMethod()
JITTED Code Address: 00007ffab71c0630

C# 코드에서 보여준 것과 결과는 같습니다. StrongDLL.Class1.DoMethod의 결과는 JIT 주소를 하나만 보여주고, WeakDLL.Class1.DoMethod는 2개의 AppDomain에서 각각 JIT 컴파일된 주소를 보여주고 있습니다.

출력된 JIT 주소가 어떤 AppDomain에 속해 있는지도 한번 알아볼까요? ^^ 예를 들기 위해 WeakDLL.Class1.DoMethod의 두 번째 출력인 00007ffab71c0630 주소에 대해 확인하는 방법은 다음과 같습니다.

0:007> !dumpmodule 00007ffab71a5dc0
Name:       C:\shared_domain\jitted_shareddomain_sample\ConsoleApplication1\bin\Debug\WeakDLL.dll
Attributes: PEFile 
Assembly:   00000241dfe0b690
LoaderHeap:              0000000000000000
TypeDefToMethodTableMap: 00007ffab71910a0
TypeRefToMethodTableMap: 00007ffab71910b8
MethodDefToDescMap:      00007ffab7191188
FieldDefToDescMap:       00007ffab71911a0
MemberRefToDescMap:      0000000000000000
FileReferencesMap:       00007ffab71911b0
AssemblyReferencesMap:   00007ffab71911b8
MetaData start address:  00000241dff220c0 (1852 bytes)

0:007> !dumpassembly 00000241dfe0b690
Parent Domain:      00000241dfd9abc0
Name:               C:\shared_domain\jitted_shareddomain_sample\ConsoleApplication1\bin\Debug\WeakDLL.dll
ClassLoader:        00000241dfe1abb0
  Module Name
00007ffab71a5dc0            C:\shared_domain\jitted_shareddomain_sample\ConsoleApplication1\bin\Debug\WeakDLL.dll

0:007> !dumpdomain 00000241dfd9abc0
--------------------------------------
Domain 2:           00000241dfd9abc0
LowFrequencyHeap:   00000241dfd9b3b8
HighFrequencyHeap:  00000241dfd9b448
StubHeap:           00000241dfd9b4d8
Stage:              OPEN
SecurityDescriptor: 00000241dfd9cc70
Name:               TestAppDomain 1
...[생략]...




이처럼, SharedDomain에 올라오는 어셈블리들은 JIT 컴파일된 기계어 코드를 공유하게 되어 있습니다. 그런데, 여기에서 재미있는 점이 하나 부각되는데, 바로 클래스의 '정적 데이터'에 대한 접근 문제가 그것입니다. 이게 왜 문제가 되냐면? 관리 환경에서 클래스의 정적 데이터는 (C/C++에서처럼 .exe 단위가 아니라) AppDomain 별로 격리되어 보관됩니다. 확인을 위해, 예제 코드의 Class1 타입을 다음과 같이 변경해 봅니다.

// ============== StrongDLL, WeakDLL 라이브러리 프로젝트 ======================
using System;
using System.Diagnostics;

namespace StrongDLL // WeakDLL 라이브러리의 경우 네임스페이스만 "WeakDLL"로 변경
{
    public class Class1
    {
        static int _count = 0;

        public void DoMethod()
        {
            Console.WriteLine(typeof(Class1).FullName + ".DoMethod called (times: " + (_count++) + ")");

            StackFrame sf = new StackFrame();
            Console.WriteLine("JIT Address: 0x{0}", sf.GetMethod().MethodHandle.GetFunctionPointer().ToInt64().ToString("x"));
        }
    }
}

실행하면 출력 결과는 다음과 같습니다.

StrongDLL.Class1.DoMethod called (times: 0)
JIT Address: 0x7ffab7140c30
WeakDLL.Class1.DoMethod called (times: 0)
JIT Address: 0x7ffab7140f90

StrongDLL.Class1.DoMethod called (times: 0)
JIT Address: 0x7ffab7140c30
WeakDLL.Class1.DoMethod called (times: 0)
JIT Address: 0x7ffab71b0680

왜냐하면 정적 데이터는 AppDomain 별로 격리되어 저장되기 때문인데요. 그런데, 이상하군요. StrongDLL.Class1.DoMethod의 경우 JIT 컴파일된 기계어 코드가 공유되는데 어떻게 해서 각자가 실행되는 AppDomain의 정적 데이터의 값을 정확하게 접근하고 있는 걸까요? 이에 대해서는 다음의 문서에 간략하게 소개되어 있습니다.

Application Domains
; https://learn.microsoft.com/en-us/dotnet/framework/app-domains/application-domains

Access to static data and methods is slower for domain-neutral assemblies because of the need to isolate assemblies. Each application domain that accesses the assembly must have a separate copy of the static data, to prevent references to objects in static fields from crossing domain boundaries. As a result, the runtime contains additional logic to direct a caller to the appropriate copy of the static data or method. This extra logic slows down the call.


그렇습니다. SharedDomain에 공유되는 domain-neutral assembly의 JIT 컴파일된 코드는 정적 데이터를 접근하는 경우 공유되지 않은 어셈블리의 동일한 코드보다 느립니다. 왜냐하면 개별 AppDomain의 문맥으로부터 정적 데이터를 가져오는 작업을 추가해야 하기 때문입니다.

따라서 이 글의 예제에 이 원칙을 적용하면, StrongDLL.dll은 SharedDomain에 로드되어 코드가 공유되기 때문에 StrongDLL.Class1.DoMethod의 수행이 WeakDLL.Class1.DoMethod의 것보다 (같은 코드를 가진 메서드임에도 불구하고) 성능상 손해를 보게 되는 것입니다. 어디... 확인을 해볼까요? ^^

우선, 별다른 오버헤드가 없을 WeakDLL.Class1.DoMethod의 JIT 컴파일된 코드를 windbg에서 확인해 보겠습니다. 메서드 정보를 찾아,

0:006> !name2ee WeakDLL.dll!WeakDLL.Class1.DoMethod 
Module:      00007ffab7035cb8
Assembly:    WeakDLL.dll
Token:       0000000006000001
MethodDesc:  00007ffab7036378
Name:        WeakDLL.Class1.DoMethod()
JITTED Code Address: 00007ffab7140f90
--------------------------------------
Module:      00007ffab7195dc0
Assembly:    WeakDLL.dll
Token:       0000000006000001
MethodDesc:  00007ffab7196480
Name:        WeakDLL.Class1.DoMethod()
JITTED Code Address: 00007ffab71b0680

출력된 각각의 주소에서 _count 정적 변수를 접근하는 부분을 찾아보면 다음과 같습니다.

0:006> !U 00007ffab7140f90
Normal JIT generated code
WeakDLL.Class1.DoMethod()
Begin 00007ffab7140f90, size 239
>>> 00007ffa`b7140f90 55              push    rbp
00007ffa`b7140f91 57              push    rdi
00007ffa`b7140f92 56              push    rsi
00007ffa`b7140f93 4881ecc0000000  sub     rsp,0C0h
...[생략]...
00007ffa`b714104a e88106645f      call    clr+0x16d0 (00007ffb`167816d0) (JitHelp: CORINFO_HELP_ARRADDR_ST)
00007ffa`b714104f 8b0def52efff    mov     ecx,dword ptr [00007ffa`b7036344]
00007ffa`b7141055 894dc8          mov     dword ptr [rbp-38h],ecx
00007ffa`b7141058 8b4dc8          mov     ecx,dword ptr [rbp-38h]
00007ffa`b714105b ffc1            inc     ecx
00007ffa`b714105d 890de152efff    mov     dword ptr [00007ffa`b7036344],ecx
00007ffa`b7141063 48b960af9804fb7f0000 mov rcx,offset mscorlib_ni+0x6baf60 (00007ffb`0498af60) (MT: System.Int32)
00007ffa`b714106d e8ce37645f      call    clr+0x4840 (00007ffb`16784840) (JitHelp: CORINFO_HELP_NEWSFAST)
...[생략]...
00007ffa`b71411c7 5d              pop     rbp
00007ffa`b71411c8 c3              ret


0:006> !U 00007ffab71b0680
Normal JIT generated code
WeakDLL.Class1.DoMethod()
Begin 00007ffab71b0680, size 239
>>> 00007ffa`b71b0680 55              push    rbp
00007ffa`b71b0681 57              push    rdi
00007ffa`b71b0682 56              push    rsi
00007ffa`b71b0683 4881ecc0000000  sub     rsp,0C0h
...[생략]...
00007ffa`b71b073a e8910f5d5f      call    clr+0x16d0 (00007ffb`167816d0) (JitHelp: CORINFO_HELP_ARRADDR_ST)
00007ffa`b71b073f 8b0d075dfeff    mov     ecx,dword ptr [00007ffa`b719644c]
00007ffa`b71b0745 894dc8          mov     dword ptr [rbp-38h],ecx
00007ffa`b71b0748 8b4dc8          mov     ecx,dword ptr [rbp-38h]
00007ffa`b71b074b ffc1            inc     ecx
00007ffa`b71b074d 890df95cfeff    mov     dword ptr [00007ffa`b719644c],ecx
00007ffa`b71b0753 48b960af9804fb7f0000 mov rcx,offset mscorlib_ni+0x6baf60 (00007ffb`0498af60) (MT: System.Int32)
00007ffa`b71b075d e8de405d5f      call    clr+0x4840 (00007ffb`16784840) (JitHelp: CORINFO_HELP_NEWSFAST)
...[생략]...
00007ffa`b71b08b7 5d              pop     rbp
00007ffa`b71b08b8 c3              ret

보는 바와 같이 JIT 컴파일된 코드의 크기는 같으면서 정적 변수의 주소값만 "[00007ffa`b7036344]", "[00007ffa`b719644c]"로 바뀌어 처리되고 있는 차이만 있습니다.

반면, 동일한 JIT 코드를 AppDomain간에 공유하는 StrongDLL.Class1.DoMethod 메서드의 경우,

0:006> !name2ee StrongDLL.dll!StrongDLL.Class1.DoMethod 
Module:      00007ffab7024780
Assembly:    StrongDLL.dll
Token:       0000000006000001
MethodDesc:  00007ffab7024df0
Name:        StrongDLL.Class1.DoMethod()
JITTED Code Address: 00007ffab7140c30

0:006> !U 00007ffab7140c30
Normal JIT generated code
StrongDLL.Class1.DoMethod()
Begin 00007ffab7140c30, size 251
>>> 00007ffa`b7140c30 55              push    rbp
00007ffa`b7140c31 57              push    rdi
00007ffa`b7140c32 56              push    rsi
00007ffa`b7140c33 4881ecc0000000  sub     rsp,0C0h
...[생략]...
00007ffa`b7140cea e8e109645f      call    clr+0x16d0 (00007ffb`167816d0) (JitHelp: CORINFO_HELP_ARRADDR_ST)
00007ffa`b7140cef b905000000      mov     ecx,5
00007ffa`b7140cf4 ba01000000      mov     edx,1
00007ffa`b7140cf9 e89241645f      call    clr+0x4e90 (00007ffb`16784e90) (JitHelp: CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE)
00007ffa`b7140cfe 8b4834          mov     ecx,dword ptr [rax+34h]
00007ffa`b7140d01 894dc8          mov     dword ptr [rbp-38h],ecx
00007ffa`b7140d04 b905000000      mov     ecx,5
00007ffa`b7140d09 ba01000000      mov     edx,1
00007ffa`b7140d0e e87d41645f      call    clr+0x4e90 (00007ffb`16784e90) (JitHelp: CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE)
00007ffa`b7140d13 8b4dc8          mov     ecx,dword ptr [rbp-38h]
00007ffa`b7140d16 ffc1            inc     ecx
00007ffa`b7140d18 894834          mov     dword ptr [rax+34h],ecx
00007ffa`b7140d1b 48b960af9804fb7f0000 mov rcx,offset mscorlib_ni+0x6baf60 (00007ffb`0498af60) (MT: System.Int32)
00007ffa`b7140d25 e8163b645f      call    clr+0x4840 (00007ffb`16784840) (JitHelp: CORINFO_HELP_NEWSFAST)
...[생략]...
00007ffa`b7140e7f 5d              pop     rbp
00007ffa`b7140e80 c3              ret

정적 변수를 그 문맥에 해당하는 AppDomain으로부터 가져와야 하기 때문에 (CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE)로 표시된 작업들을 사전에 해주고 있습니다. 성능상 느릴 수밖에 없습니다. (물론, 대부분의 경우 체감할 정도는 아니겠지만.)

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 1/11/2024]

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)
12197정성태3/17/202010868VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/20208816오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202010509.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202012855오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/20209515개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202011973개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202012315개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/20208511오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202013320개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202015500Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/20208252오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/20209344오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/20209985오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202011454오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/20209792오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
12182정성태3/11/202011037.NET Framework: 901. C# Windows Forms - Vista/7 이후의 Progress Bar 업데이트가 느린 문제파일 다운로드1
12181정성태3/11/202011877기타: 76. 재현 가능한 최소한의 예제 프로젝트란? - 두 번째 예제파일 다운로드1
12180정성태3/10/20208475오류 유형: 600. "Docker Desktop for Windows" - EXPOSE 포트가 LISTENING 되지 않는 문제
12179정성태3/10/202019856개발 환경 구성: 481. docker - PostgreSQL 컨테이너 실행
12178정성태3/10/202011334개발 환경 구성: 480. Linux 운영체제의 docker를 위한 tcp 바인딩 추가 [1]
12177정성태3/9/202011015개발 환경 구성: 479. docker - MySQL 컨테이너 실행
12176정성태3/9/202010435개발 환경 구성: 478. 파일의 (sha256 등의) 해시 값(checksum) 확인하는 방법
12175정성태3/8/202010516개발 환경 구성: 477. "Docker Desktop for Windows"의 "Linux Container" 모드를 위한 tcp 바인딩 추가
12174정성태3/7/202010059개발 환경 구성: 476. DockerDesktopVM의 파일 시스템 접근 [3]
12173정성태3/7/202011056개발 환경 구성: 475. docker - SQL Server 2019 컨테이너 실행 [1]
12172정성태3/7/202015924개발 환경 구성: 474. docker - container에서 root 권한 명령어 실행(sudo)
... 46  47  48  49  50  51  52  53  54  55  56  [57]  58  59  60  ...