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

... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11224정성태6/13/201718145.NET Framework: 661. Json.NET의 DeserializeObject 수행 시 속성 이름을 동적으로 바꾸는 방법파일 다운로드1
11223정성태6/12/201716829개발 환경 구성: 318. WCF Service Application과 WCFTestClient.exe
11222정성태6/10/201720552오류 유형: 399. WCF - A property with the name 'UriTemplateMatchResults' already exists.파일 다운로드1
11221정성태6/10/201717519오류 유형: 398. Fakes - Assembly 'Jennifer5.Fakes' with identity '[...].Fakes, [...]' uses '[...]' which has a higher version than referenced assembly '[...]' with identity '[...]'
11220정성태6/10/201722908.NET Framework: 660. Shallow Copy와 Deep Copy [1]파일 다운로드2
11219정성태6/7/201718217.NET Framework: 659. 닷넷 - TypeForwardedFrom / TypeForwardedTo 특성의 사용법
11218정성태6/1/201721021개발 환경 구성: 317. Hyper-V 내의 VM에서 다시 Hyper-V를 설치: Nested Virtualization
11217정성태6/1/201716914오류 유형: 397. initerrlog: Could not open error log file 'C:\...\MSSQL12.MSSQLSERVER\MSSQL\Log\ERRORLOG'
11216정성태6/1/201719021오류 유형: 396. Activation context generation failed
11215정성태6/1/201719956오류 유형: 395. 관리 콘솔을 실행하면 "This app has been blocked for your protection" 오류 발생 [1]
11214정성태6/1/201717697오류 유형: 394. MSDTC 서비스 시작 시 -1073737712(0xC0001010) 오류와 함께 종료되는 문제 [1]
11213정성태5/26/201722478오류 유형: 393. TFS - The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
11212정성태5/26/201721816오류 유형: 392. Windows Server 2016에 KB4019472 업데이트가 실패하는 경우
11211정성태5/26/201720855오류 유형: 391. BeginInvoke에 전달한 람다 함수에 CS1660 에러가 발생하는 경우
11210정성태5/25/201721299기타: 65. ActiveX 없는 전자 메일에 사용된 "개인정보 보호를 위해 암호화된 보안메일"의 암호화 방법
11209정성태5/25/201768220Windows: 143. Windows 10의 Recovery 파티션을 삭제 및 새로 생성하는 방법 [16]
11208정성태5/25/201727944오류 유형: 390. diskpart의 set id 명령어에서 "The specified type is not in the correct format." 오류 발생
11207정성태5/24/201728255Windows: 142. Windows 10의 복구 콘솔로 부팅하는 방법
11206정성태5/24/201721548오류 유형: 389. DISM.exe - The specified image in the specified wim is already mounted for read/write access.
11205정성태5/24/201721269.NET Framework: 658. C#의 tail call 구현은? [1]
11204정성태5/22/201730806개발 환경 구성: 316. 간단하게 살펴보는 Docker for Windows [7]
11203정성태5/19/201718738오류 유형: 388. docker - Host does not exist: "default"
11202정성태5/19/201719809오류 유형: 387. WPF - There is no registered CultureInfo with the IetfLanguageTag 'ug'.
11201정성태5/16/201722553오류 유형: 386. WPF - .NET 3.5 이하에서 TextBox에 한글 입력 시 TextChanged 이벤트의 비정상 종료 문제 [1]파일 다운로드1
11200정성태5/16/201719331오류 유형: 385. WPF - 폰트가 없어 System.IO.FileNotFoundException 예외가 발생하는 경우
11199정성태5/16/201721155.NET Framework: 657. CultureInfo.GetCultures가 반환하는 값
... 106  107  [108]  109  110  111  112  113  114  115  116  117  118  119  120  ...