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

AllowPartiallyTrustedCallers 특성이 적용된 GAC 어셈블리에서 DynamicMethod의 calli 명령어 사용

calli 명령어 사용법에 대해 지난 글에서 대략 설명드렸는데요.

calli IL 호출이 DllImport 호출보다 빠를까요?
; https://www.sysnet.pe.kr/2/0/10808

OpenCover 코드 커버리지 도구의 동작방식을 통해 살펴보는 Calli IL 코드 사용법
; https://www.sysnet.pe.kr/2/0/2882

calli IL 코드를 사용하는 메서드를 만들기 위해 직접 DynamicMethod를 사용했습니다.

// x86 기준 calli IL 코드를 사용하는 동적 메서드 생성

long result = 0;

if (IntPtr.Size == 4)
{
    result = GetThisThreadId32();
}

var type = typeof(Class1);
DynamicMethod dynamicMethod = new DynamicMethod("", typeof(int), Type.EmptyTypes, type, true);

var iLGenerator = dynamicMethod.GetILGenerator();

if (IntPtr.Size == 4)
{
    iLGenerator.Emit(OpCodes.Ldc_I4, (int)result);
}

iLGenerator.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, typeof(int), Type.EmptyTypes);
iLGenerator.Emit(OpCodes.Ret);

GetThisThreadIdDelegate tempDelegate = dynamicMethod.CreateDelegate(typeof(GetThisThreadIdDelegate)) as GetThisThreadIdDelegate;
_GetThisThreadIdMethod = tempDelegate;

재미있는 것은 이 코드를 .NET 4.0 보안의 APTCA가 적용된 어셈블리 내에 두면,

.NET CLR4 보안 모델 - 3. CLR4 보안 모델에서의 APTCA 역할
; https://www.sysnet.pe.kr/2/0/1682

dynamicMethod.CreateDelegate 단계까지 정상적으로 실행은 되지만 그렇게 해서 생성한 _GetThisThreadIdMethod 메서드를 호출하면 다음과 같은 예외가 발생합니다.

System.Security.VerificationException was caught
  _HResult=-2146233075
  _message=Operation could destabilize the runtime.
  HResult=-2146233075
  IsTransient=false
  Message=Operation could destabilize the runtime.
  Source=ClassLibrary1
  StackTrace:
       at ()
       at ClassLibrary1.Class1.GetThisThreadId()
  InnerException: 

원인은 DynamicMethod 메서드의 추가를 APTCA가 적용된 어셈블리 내에 있는 타입을 기준으로 했기 때문입니다.

var type = typeof(Class1);
DynamicMethod dynamicMethod = new DynamicMethod("", typeof(int), Type.EmptyTypes, type, true);

따라서, 해당 타입 대신 APTCA가 적용되지 않은 어셈블리에 정의된 타입을 대신 넣어주면 됩니다. 가령, 이런 식이겠지요.

// GAC 어셈블리의 GetThisThreadId를 호출할 때 별도의 타입을 지정

class Program
{
    static void Main(string[] args)
    {
        ClassLibrary1.Class1.GetThisThreadId(typeof(Program));
    }
}

// ClassLibrary1.Class1.GetThisThreadId에서는 외부의 타입을 기반으로 동적 메서드 추가

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

namespace ClassLibrary1
{
    [System.Security.SecuritySafeCritical]
    public class Class1
    {
        // ...[생략]...

        public static int GetThisThreadId(Type type)
        {
            long result = 0;

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

            DynamicMethod dynamicMethod = new DynamicMethod("", typeof(int), Type.EmptyTypes, type, true);

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

            GetThisThreadIdDelegate tempDelegate = dynamicMethod.CreateDelegate(typeof(GetThisThreadIdDelegate)) as GetThisThreadIdDelegate;
            _GetThisThreadIdMethod = tempDelegate;

            return _GetThisThreadIdMethod();
        }
    }
}

근데... 이런 식은 좀 번거로우니 의존성을 제거하기 위해 아예 어셈블리 및 타입도 동적으로 생성해 주는 방법이 있습니다.

AssemblyName myAssemblyName = new AssemblyName();
myAssemblyName.Name = "EmittedAssembly_" + Guid.NewGuid().ToString();
AssemblyBuilder myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(myAssemblyName,
    AssemblyBuilderAccess.Run);

ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule");
TypeBuilder helperClass = myModule.DefineType("Helper", TypeAttributes.Public);
Type type = helperClass.CreateType();

DynamicMethod dynamicMethod = new DynamicMethod("", typeof(int), Type.EmptyTypes, type, true);

어떤 것을 사용하든... 취향에 맞게! ^^

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




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 5/27/2024]

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

비밀번호

댓글 작성자
 




... 121  122  123  124  125  126  [127]  128  129  130  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
2879정성태3/3/201526542개발 환경 구성: 259. Visual Studio 없이 Visual C++ 컴파일하는 방법
2878정성태2/28/201527398.NET Framework: 503. == 연산자보다는 Equals 메서드의 호출이 더 권장됩니다. [3]파일 다운로드1
2877정성태2/28/201521629.NET Framework: 502. 연산자 재정의(operator overloading)와 메서드 재정의(method overriding)의 다른 점 - 가상 함수 호출 여부 [3]파일 다운로드1
2876정성태2/27/201524105VS.NET IDE: 98. IntegraStudio - Visual Studio에서 Java 프로그램 개발
2875정성태2/26/201522712디버깅 기술: 72. Visual Studio 2013에서의 sos.dll 사용 제한
2874정성태2/26/201519452디버깅 기술: 71. windbg + 닷넷 디버깅 (2) - null 체크 패턴
2873정성태2/25/201536988.NET Framework: 501. FtpWebRequest 타입을 이용해 FTP 파일 업로드 [4]파일 다운로드1
2872정성태2/25/201521084디버깅 기술: 70. windbg + 닷넷 디버깅 (1) - 배열 인덱스 사용 패턴
2871정성태2/24/201525089개발 환경 구성: 258. 윈도우 8.1에서 방화벽과 함께 FTP 서버 여는 (하지만, 권장하지 않는) 방법 [1]
2870정성태2/24/201526178개발 환경 구성: 257. 윈도우 8.1에서 방화벽과 함께 FTP 서버 여는 방법
2869정성태2/23/201520172.NET Framework: 500. struct로 정의한 값 형식(Value Type)의 경우 Equals 재정의를 권장합니다.파일 다운로드1
2868정성태2/23/201524702VS.NET IDE: 97. Visual C++ 프로젝트 디버깅 시에 Step-Into(F11) 동작이 원치 않는 함수로 진입하는 것을 막는 방법 [2]
2867정성태2/23/201518369오류 유형: 273. File History - Failed to initiate user data backup (error 80070005)
2866정성태2/23/201520195오류 유형: 272. WAT080 : Failed to locate the Windows Azure SDK. Please make sure the Windows Azure SDK v2.1 is installed.
1868정성태2/20/201517514오류 유형: 271. The type '...' cannot be used as type parameter 'TContext' in the generic type or method 'System.ServiceModel.DomainServices.EntityFramework.LinqToEntitiesDomainService<T>
1866정성태2/20/201518407오류 유형: 270. "aspnet_regiis -i" 실행 시 0x00000006 오류 해결 방법
1865정성태2/20/201519785.NET Framework: 499. 특정 닷넷 프레임워크 버전 이후부터 제공되는 타입을 사용해야 한다면?
1864정성태2/18/201524719.NET Framework: 498. C#으로 간단하게 만들어 본 ASCII Art 프로그램 [2]파일 다운로드1
1862정성태2/18/201528574.NET Framework: 497. .NET Garbage Collection에 대한 정리 [6]
1861정성태2/18/201523935.NET Framework: 496. 마우스 커서가 놓인 지점의 문자열 얻는 방법 [1]파일 다운로드1
1860정성태2/18/201523746.NET Framework: 495. CorElementType의 요소 값 설명파일 다운로드1
1859정성태2/17/201524162Windows: 106. 컴퓨터를 재부팅하면 절전(Power Saver) 전원 모드로 돌아가는 경우
1858정성태2/16/201534163Windows: 105. 자동으로 로그아웃/잠김 화면 상태로 전환된다면? [2]
1857정성태2/16/201522121.NET Framework: 494. 값(struct) 형식의 제네릭(Generic) 타입이 박싱되는 경우의 메타데이터 토큰 값파일 다운로드1
1856정성태2/15/201521146.NET Framework: 493. TypeRef 메타테이블에 등록되는 타입의 조건파일 다운로드1
1855정성태2/10/201520682개발 환경 구성: 256. WebDAV Redirector - Sysinternals 폴더 연결 시 "The network path was not found" 오류 해결 방법
... 121  122  123  124  125  126  [127]  128  129  130  131  132  133  134  135  ...