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

1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13641정성태6/11/20248673Linux: 71. Ubuntu 20.04를 22.04로 업데이트
13640정성태6/10/20248835Phone: 21. C# MAUI - Android 환경에서의 파일 다운로드(DownloadManager)
13639정성태6/8/20248443오류 유형: 906. C# MAUI - Android Emulator에서 "Waiting For Debugger"로 무한 대기
13638정성태6/8/20248525오류 유형: 905. C# MAUI - 추가한 layout XML 파일이 Resource.Layout 멤버로 나오지 않는 문제
13637정성태6/6/20248458Phone: 20. C# MAUI - 유튜브 동영상을 MediaElement로 재생하는 방법
13636정성태5/30/20248089닷넷: 2264. C# - 형식 인자로 인터페이스를 갖는 제네릭 타입으로의 형변환파일 다운로드1
13635정성태5/29/20248951Phone: 19. C# MAUI - 안드로이드 "Share" 대상으로 등록하는 방법
13634정성태5/24/20249433Phone: 18. C# MAUI - 안드로이드 플랫폼에서의 Activity 제어 [1]
13633정성태5/22/20248947스크립트: 64. 파이썬 - ASGI를 만족하는 최소한의 구현 코드
13632정성태5/20/20248573Phone: 17. C# MAUI - Android 내에 Web 서비스 호스팅
13631정성태5/19/20249328Phone: 16. C# MAUI - /Download 등의 공용 디렉터리에 접근하는 방법 [1]
13630정성태5/19/20248875닷넷: 2263. C# - Thread가 Task보다 더 빠르다는 어떤 예제(?)
13629정성태5/18/20249165개발 환경 구성: 710. Android - adb.exe를 이용한 파일 전송
13628정성태5/17/20248551개발 환경 구성: 709. Windows - WHPX(Windows Hypervisor Platform)를 이용한 Android Emulator 가속
13627정성태5/17/20248618오류 유형: 904. 파이썬 - UnicodeEncodeError: 'ascii' codec can't encode character '...' in position ...: ordinal not in range(128)
13626정성태5/15/20248883Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/20248929닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/20248724Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/20248430닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/20249221닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/20248638오류 유형: 903. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/20248556VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/20248874닷넷: 2259. C# - decimal 저장소의 비트 구조파일 다운로드1
13618정성태5/6/20248665닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/20249472닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/20248630닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
1  2  3  4  5  6  7  8  9  10  11  [12]  13  14  15  ...