Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 5개 있습니다.)
.NET Framework: 431. .NET EXE 파일을 닷넷 프레임워크 버전에 상관없이 실행할 수 있을까요?
; https://www.sysnet.pe.kr/2/0/1659

.NET Framework: 461. .NET EXE 파일을 닷넷 프레임워크 버전에 상관없이 실행할 수 있을까요? - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1746

VC++: 129. EXE를 LoadLibrary로 로딩해 PE 헤더에 있는 EntryPoint를 직접 호출하는 방법
; https://www.sysnet.pe.kr/2/0/11858

디버깅 기술: 126. windbg - .NET x86 CLR2/CLR4 EXE의 EntryPoint
; https://www.sysnet.pe.kr/2/0/11861

디버깅 기술: 127. windbg - .NET x64 EXE의 EntryPoint
; https://www.sysnet.pe.kr/2/0/11863




.NET EXE 파일을 닷넷 프레임워크 버전에 상관없이 실행할 수 있을까요?

Visual Studio 2013 환경에서 간단하게 EXE를 생성하는 코드를 만들어 .NET 2.0으로 컴파일 한 후,

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Environment.Version);
        }
    }
}

ildasm.exe를 이용해 역 어셈블을 해보면,

ildasm ConsoleApplication1.exe /OUTPUT=test.il

다음과 같은 결과를 얻을 수 있습니다.

.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 2:0:0:0
}
.assembly ConsoleApplication1
{
  .custom instance void [mscorlib]System.Reflection.AssemblyTitleAttribute::.ctor(string) = ( 01 00 13 43 6F 6E 73 6F 6C 65 41 70 70 6C 69 63   // ...ConsoleApplic
                                                                                              61 74 69 6F 6E 31 00 00 )                         // ation1..
  .custom instance void [mscorlib]System.Reflection.AssemblyDescriptionAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Reflection.AssemblyConfigurationAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Reflection.AssemblyCompanyAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Reflection.AssemblyProductAttribute::.ctor(string) = ( 01 00 13 43 6F 6E 73 6F 6C 65 41 70 70 6C 69 63   // ...ConsoleApplic
                                                                                                61 74 69 6F 6E 31 00 00 )                         // ation1..
  .custom instance void [mscorlib]System.Reflection.AssemblyCopyrightAttribute::.ctor(string) = ( 01 00 12 43 6F 70 79 72 69 67 68 74 20 C2 A9 20   // ...Copyright .. 
                                                                                                  20 32 30 31 34 00 00 )                            //  2014..
  .custom instance void [mscorlib]System.Reflection.AssemblyTrademarkAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Runtime.InteropServices.ComVisibleAttribute::.ctor(bool) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 62 66 33 62 34 35 65 2D 36 65 31 30   // ..$1bf3b45e-6e10
                                                                                                  2D 34 32 33 38 2D 38 62 31 34 2D 33 65 30 36 63   // -4238-8b14-3e06c
                                                                                                  39 63 36 31 64 31 37 00 00 )                      // 9c61d17..
  .custom instance void [mscorlib]System.Reflection.AssemblyFileVersionAttribute::.ctor(string) = ( 01 00 07 31 2E 30 2E 30 2E 30 00 00 )             // ...1.0.0.0..

  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78   // ....T..WrapNonEx
                                                                                                             63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 )       // ceptionThrows.
  .hash algorithm 0x00008004
  .ver 1:0:0:0
}
.module ConsoleApplication1.exe
.imagebase 0x00400000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003       // WINDOWS_CUI
.corflags 0x00000001    //  ILONLY

.class private auto ansi beforefieldinit ConsoleApplication1.Program
       extends [mscorlib]System.Object
{
  .method private hidebysig static void  Main(string[] args) cil managed
  {
    .entrypoint
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  call       class [mscorlib]System.Version [mscorlib]System.Environment::get_Version()
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(object)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Program::Main

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       7 (0x7)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  ret
  } // end of method Program::.ctor

} // end of class ConsoleApplication1.Program

결국 mscorlib.dll에 대한 의존성에서 2.0 버전으로 맞춰져 있기 때문에 자연스럽게 .NET Framework 2.0에 대한 환경이 요구되는 것입니다. 그럼 버전 표시를 삭제하고,

.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 2:0:0:0
}

ilasm.exe로 다시 빌드해 보면 어떻게 될까요?

ilasm test.il /OUTPUT=test.exe

실행은 잘 되지만 Environment.Version 출력 결과가 4.0으로 나옵니다.

D:\ConsoleApplication1\bin\Debug>test
4.0.30319.34014

이렇게 생성된 test.exe를 다시 ildasm.exe로 역어셈블하면 버전이 0으로 맞춰져 있는 것을 확인할 수 있습니다.

.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 0:0:0:0
}

결과적으로 보면, 해당 어셈블리를 컴파일한 ilasm.exe가 .NET 4.0에 설치된 버전으로 컴파일 되었기 때문에 test.il 코드의 mscorlib에 대한 버전을 명시하지 않은 경우 ilasm.exe는 자동으로 그 환경의 .NET 버전으로 일치시켜 .NET 어셈블리를 만들게 됩니다.

실제로 .NET 2.0에 포함된 ilasm.exe로 (mscorlib의 버전 번호를 삭제한) test.il 코드를 컴파일 하면 출력 결과는 .NET 2.0의 버전이 나옵니다.

D:\ConsoleApplication1\bin\Debug>c:\Windows\Microsoft.NET\Framework\v2.0.50727\ilasm.exe test.il /OUTPUT=test.exe

D:\ConsoleApplication1\bin\Debug>test
2.0.50727.8000

.NET 2.0/4.0에 포함된 ilasm.exe로 컴파일된 각각의 바이너리를 HxD와 같은 헥사 에디터로 비교해 보면 결국 다음과 같이 프레임워크 버전이 포함되는 것을 볼 수 있습니다.

target_framework_depends_1.png

테스트를 위해 0x279~0x281 사이의 값을 서로 바꿔보면 대응되는 .NET 버전도 달라집니다.




이제 다음과 같은 질문에 답을 해볼까요?

app.config 파일 관련 질문 있습니다.
; https://www.sysnet.pe.kr/3/0/1249

다양한 닷넷 프레임워크상에서 단일 EXE를 실행하기 위해 app.config에 supportedRuntime을 적용하는 것을 지난번에 이미 설명했었습니다.

supportedRuntime 옵션과 System.BadImageFormatException 예외
; https://www.sysnet.pe.kr/2/0/1233

하지만, 이것을 app.config 없이 적용하는 것이 가능할까요? 여기에서 "닭이 먼저냐? 달걀이 먼저냐?"라는 문제가 발생합니다. EXE 실행 시 닷넷 버전을 결정하고 싶은데, 해당 EXE를 실행하기 위해서는 먼저 닷넷 버전이 결정되어야 합니다. 바로 이런 문제를 해결하기 위해 .NET 런타임이 올라오기 전에 설정값들을 읽어낼 수 있도록 app.config이 존재하는 것입니다.

이렇게 설득하면서도 ^^ 사실 저도 약간 아쉬움이 있습니다. supportedRuntime 같은 것은 app.config보다는 .manifest에 넣는 것이 더 낫지 않았을까... 하는 생각을 하기 때문입니다. 어쨌든, app.config의 도움없이 .NET 런타임 버전을 결정할 수는 없기 때문에 질문자의 바람대로 단일 EXE를 배포할 수는 없습니다.

대신... 이런 방법은 어떨까요? Visual C++로 exe를 만들고 그 안에 닷넷 EXE + app.config을 리소스로 포함하는 것입니다. 실행 시에 Visual C++ EXE는 리소스로 보관되어 있는 닷넷 EXE와 app.config을 풀어내어 재차 실행하는 것을 고려해 볼 수 있습니다. (실제로, Sysinternals의 process explorer와 같은 도구에서 x86/x64 문제를 해결하기 위해 이와 비슷한 방법을 채택하고 있습니다.)

어쨌든, 그 이상의 좋은 답이 떠오르질 않는군요. ^^





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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/10/2021]

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

비밀번호

댓글 작성자
 



2014-04-22 08시54분
[spowner] 궁금한 내용이였는데 포스팅 해주셔서 감사합니다~
[guest]
2014-06-30 01시06분
정성태
2014-08-01 06시31분
[[손님]] 근데 XNA게임 바이너리 보면 app.config없어도 여러 버전에서 잘 돌아가던데요
[guest]
2014-08-05 03시27분
@손님 혹시 "XNA Game Studio 4.0"으로 만든 프로그램을 PC에서 사용하는 것에 대한 언급인가요?

Microsoft XNA Game Studio 4.0
; http://www.microsoft.com/en-us/download/details.aspx?id=23714

만약, 그렇다면 제가 쓴 글을 다시 한번 정독해 주세요. (그래도 모르시겠다면 테스트까지 해보시면 됩니다. ^^)
정성태
2017-08-31 01시47분
.NET EXE 파일을 닷넷 프레임워크 버전에 상관없이 실행할 수 있을까요? - 두 번째 이야기
; http://www.sysnet.pe.kr/2/0/1746
정성태

... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
11842정성태3/13/201910232개발 환경 구성: 433. 마이크로소프트의 CoreCLR 프로파일러 예제를 Visual Studio CMake로 빌드하는 방법 [1]파일 다운로드1
11841정성태3/13/201910211VS.NET IDE: 132. Visual Studio 2019 - CMake의 컴파일러를 기본 g++에서 clang++로 변경
11840정성태3/13/201911306오류 유형: 526. 윈도우 10 Ubuntu App 환경에서는 USB 외장 하드 접근 불가
11839정성태3/12/201914039디버깅 기술: 124. .NET Core 웹 앱을 호스팅하는 Azure App Services의 프로세스 메모리 덤프 및 windbg 분석 개요 [3]
11838정성태3/7/201916817.NET Framework: 811. (번역글) .NET Internals Cookbook Part 1 - Exceptions, filters and corrupted processes [1]파일 다운로드1
11837정성태3/6/201926425기타: 74. 도서: 시작하세요! C# 7.3 프로그래밍 [10]
11836정성태3/5/201914377오류 유형: 525. Visual Studio 2019 Preview 4/RC - C# 8.0 Missing compiler required member 'System.Range..ctor' [1]
11835정성태3/5/201914127.NET Framework: 810. C# 8.0의 Index/Range 연산자를 .NET Framework에서 사용하는 방법 및 비동기 스트림의 컴파일 방법 [3]파일 다운로드1
11834정성태3/4/201913030개발 환경 구성: 432. Visual Studio 없이 최신 C# (8.0) 컴파일러를 사용하는 방법
11833정성태3/4/201913781개발 환경 구성: 431. Visual Studio 2019 - CMake를 이용한 공유/실행(so/out) 리눅스 프로젝트 설정파일 다운로드1
11832정성태3/4/201910821오류 유형: 524. Visual Studio CMake - rsync: connection unexpectedly closed
11831정성태3/4/201910411오류 유형: 523. Visual Studio 2019 - 새 창으로 뜬 윈도우를 닫을 때 비정상 종료
11830정성태2/26/201910206오류 유형: 522. 이벤트 로그 - Error opening event log file State. Log will not be processed. Return code from OpenEventLog is 87.
11829정성태2/26/201912115개발 환경 구성: 430. 마이크로소프트의 CoreCLR 프로파일러 예제 빌드 방법 - 리눅스 환경 [1]
11828정성태2/26/201918501개발 환경 구성: 429. Component Services 관리자의 RuntimeBroker 설정이 2개 있는 경우 [8]
11827정성태2/26/201912395오류 유형: 521. Visual Studio - Could not start the 'rsync' command on the remote host, please install it using your system package manager.
11826정성태2/26/201912275오류 유형: 520. 우분투에 .NET Core SDK 설치 시 패키지 의존성 오류
11825정성태2/25/201917144개발 환경 구성: 428. Visual Studio 2019 - CMake를 이용한 리눅스 빌드 환경 설정 [1]
11824정성태2/25/201911950오류 유형: 519. The SNMP Service encountered an error while accessing the registry key SYSTEM\CurrentControlSet\Services\SNMP\Parameters\TrapConfiguration. [1]
11823정성태2/21/201913424오류 유형: 518. IIS 관리 콘솔이 뜨지 않는 문제
11822정성태2/20/201911563오류 유형: 517. docker에 설치한 MongoDB 서버로 연결이 안 되는 경우
11821정성태2/20/201912036오류 유형: 516. Visual Studio 2019 - This extension uses deprecated APIs and is at risk of not functioning in a future VS update. [1]
11820정성태2/20/201915173오류 유형: 515. 윈도우 10 1809 업데이트 후 "User Profiles Service" 1534 경고 발생
11819정성태2/20/201913834Windows: 158. 컴퓨터와 사용자의 SID(security identifier) 확인 방법
11818정성태2/20/201912748VS.NET IDE: 131. Visual Studio 2019 Preview의 닷넷 프로젝트 빌드가 20초 이상 걸리는 경우 [2]
11817정성태2/17/20199923오류 유형: 514. WinDbg Preview 실행 오류 - Error : DbgX.dll : WindowsDebugger.WindowsDebuggerException: Could not load dbgeng.dll
... 61  62  63  64  65  66  67  68  69  70  71  [72]  73  74  75  ...