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

... 121  122  123  124  125  126  127  128  129  130  131  132  133  [134]  135  ...
NoWriterDateCnt.TitleFile(s)
1738정성태8/23/201423389.NET Framework: 456. C# - CAS를 이용한 Lock 래퍼 클래스파일 다운로드1
1737정성태8/20/201420842VS.NET IDE: 93. Visual Studio 2013 동기화 문제
1736정성태8/19/201426864VC++: 79. [부연] CAS Lock 알고리즘은 과연 빠른가? [2]파일 다운로드1
1735정성태8/19/201419375.NET Framework: 455. 닷넷 사용자 정의 예외 클래스의 최소 구현 코드 - 두 번째 이야기
1734정성태8/13/201421115오류 유형: 237. Windows Media Player cannot access the file. The file might be in use, you might not have access to the computer where the file is stored, or your proxy settings might not be correct.
1733정성태8/13/201427392.NET Framework: 454. EmptyWorkingSet Win32 API를 사용하는 C# 예제파일 다운로드1
1732정성태8/13/201435759Windows: 99. INetCache 폴더가 다르게 보이는 이유
1731정성태8/11/201428193개발 환경 구성: 235. 점(.)으로 시작하는 파일명을 탐색기에서 만드는 방법
1730정성태8/11/201423388개발 환경 구성: 234. Royal TS의 터미널(Terminal) 연결에서 한글이 깨지는 현상 해결 방법
1729정성태8/11/201419366오류 유형: 236. SqlConnection - The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
1728정성태8/8/201431612.NET Framework: 453. C# - 오피스 파워포인트(Powerpoint) 파일을 WinForm에서 보는 방법파일 다운로드1
1727정성태8/6/201421830오류 유형: 235. SignalR 오류 메시지 - Counter 'Messages Bus Messages Published Total' does not exist in the specified Category. [2]
1726정성태8/6/201420664오류 유형: 234. IIS Express에서 COM+ 사용 시 SecurityException - "Requested registry access is not allowed" 발생
1725정성태8/6/201422593오류 유형: 233. Visual Studio 2013 Update3 적용 후 Microsoft.VisualStudio.Web.PageInspector.Runtime 모듈에 대한 FileNotFoundException 예외 발생
1724정성태8/5/201427432.NET Framework: 452. .NET System.Threading.Thread 개체에서 Native Thread Id를 구하는 방법 - 두 번째 이야기 [1]파일 다운로드1
1723정성태7/29/201459816개발 환경 구성: 233. DirectX 9 예제 프로젝트 빌드하는 방법 [3]파일 다운로드1
1722정성태7/25/201422155오류 유형: 232. IIS 500 Internal Server Error - NTFS 암호화된 폴더에 웹 애플리케이션이 위치한 경우
1721정성태7/24/201425443.NET Framework: 451. 함수형 프로그래밍 개념 - 리스트 해석(List Comprehension)과 순수 함수 [2]
1720정성태7/23/201423417개발 환경 구성: 232. C:\WINDOWS\system32\LogFiles\HTTPERR 폴더에 로그 파일을 남기지 않는 설정
1719정성태7/22/201427264Math: 13. 동전을 여러 더미로 나누는 경우의 수 세기(Partition Number) - 두 번째 이야기파일 다운로드1
1718정성태7/19/201436695Math: 12. HTML에서 수학 관련 기호/수식을 표현하기 위한 방법 - MathJax.js [4]
1716정성태7/17/201436416개발 환경 구성: 231. PC 용 무료 안드로이드 에뮬레이터 - genymotion
1715정성태7/13/201431505기타: 47. 운영체제 종료 후에도 USB 외장 하드의 전원이 꺼지지 않는 경우 [3]
1714정성태7/11/201421558VS.NET IDE: 92. Visual Studio 2013을 지원하는 IL Support 확장 도구
1713정성태7/11/201445329Windows: 98. 윈도우 시스템 디스크 용량 확보를 위한 "Package Cache" 폴더 이동 [1]
1712정성태7/10/201433871.NET Framework: 450. 영문 윈도우에서 C# 콘솔 프로그램의 유니코드 출력 방법 [3]
... 121  122  123  124  125  126  127  128  129  130  131  132  133  [134]  135  ...