Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 4개 있습니다.)
.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면?
; https://www.sysnet.pe.kr/2/0/12733

.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션
; https://www.sysnet.pe.kr/2/0/13159

.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
; https://www.sysnet.pe.kr/2/0/13160

.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성)
; https://www.sysnet.pe.kr/2/0/13161




C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션

지난 글에 설명한,

C# - PublishSingleFile과 관련된 옵션
; https://www.sysnet.pe.kr/2/0/13159

PublishSingleFile 옵션을 .NET 5 프로젝트에 적용하면,

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net5.0</TargetFramework>

        <RuntimeIdentifier>win-x64</RuntimeIdentifier>
        <PublishSingleFile>true</PublishSingleFile>

    </PropertyGroup>

</Project>

배포 빌드(dotnet publish) 시,

E:\net5_pubone_sample> dir /b .\bin\Debug\net5.0\win-x64\publish
clrcompression.dll
clrjit.dll
coreclr.dll
mscordaccore.dll
net5_pubone_sample.exe
net5_pubone_sample.pdb

이렇게 닷넷 5 런타임의 native 모듈들이 (닷넷 6와는 달리) 함께 생성됩니다. 이러한 native 모듈을 단일 모듈에 합치고 싶다면 IncludeNativeLibrariesForSelfExtract 옵션을 주면 됩니다.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net5.0</TargetFramework>

        <RuntimeIdentifier>win-x64</RuntimeIdentifier>
        <PublishSingleFile>true</PublishSingleFile>

        <IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
    </PropertyGroup>

</Project>

이후 다시 배포 빌드(dotnet publish)하면 EXE와 PDB 파일만 생성됩니다. 이하 DebugType, SelfContained, PublishReadyToRun, PublishTrimmed 옵션은 모두 동일하게 적용됩니다. 단지, EnableCompressionInSingleFile 옵션은 .NET 6 전용이므로 .NET 5 프로젝트에는 사용할 수 없습니다.




참고로, IncludeNativeLibrariesForSelfExtract 옵션의 숨겨진 역할이 하나 더 있습니다. 닷넷 5는, 실행 파일에 native module을 포함하긴 하지만, IncludeNativeLibrariesForSelfExtract 옵션이 의미하는 바에 따라 실행 시점에 해당 native 모듈을 추출해 로컬 파일로 저장합니다.

제가 만든 예제 프로젝트의 경우 아래의 경로에 파일이 추출돼 실행 시 해당 바이너리가 로드됩니다.

%TEMP%\.net\net5_pubone_sample\0rfKH9kewXipt7yvr_cSn+1Wk35Knq8=

* 이 경로는 DOTNET_BUNDLE_EXTRACT_BASE_DIR 환경 변수로 재정의할 수 있습니다.

재미있는 건, IncludeNativeLibrariesForSelfExtract 옵션이 닷넷 6 프로젝트에서는 아예 동작을 안 한다는 점입니다. 그 옵션을 false로 설정하고 닷넷 6 프로젝트를 publish하면 설정하지 않았던 때와 동일하게 단일 파일로 생성됩니다. 더더욱 재미있는 점은, 닷넷 6의 경우 닷넷 런타임의 native 코드를 완벽하게 실행 모듈 하나에 병합한다는 점입니다.

그래서, .NET 6에서는 IncludeNativeLibrariesForSelfExtract (값에 상관없이) "%TEMP%\.net\...[생략]..." 디렉터리가 생성되지 않습니다. 즉, "SelfExtract" 시킬 필요가 없는 것입니다.

이와 비슷한 옵션으로 IncludeAllContentForSelfExtract가 있습니다. 옵션에 "All"이 의미하는 것처럼, 이것은 IncludeNativeLibrariesForSelfExtract 옵션까지도 기본적으로 true로 설정한 빌드를 합니다. 따라서 닷넷 5 프로젝트에서 true로 설정하고 빌드하면,

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net5.0</TargetFramework>

        <RuntimeIdentifier>win-x64</RuntimeIdentifier>
        <PublishSingleFile>true</PublishSingleFile>

        <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
        <DebugType>embedded</DebugType>

        <PublishTrimmed>true</PublishTrimmed>
    </PropertyGroup>

</Project>

생성한 단일 배포 파일은 실행 시 "%TEMP%\.net\...[생략]..." 디렉터리에 닷넷 BCL에 해당했던 managed 모듈과 native 모듈을 모두 추출한 다음 실행 모듈은 그것들을 로드해서 사용합니다.

반면, 닷넷 6 프로젝트에서는 어차피 IncludeNativeLibrariesForSelfExtract 옵션은 동작하지 않으므로 IncludeAllContentForSelfExtract 옵션을 true로 설정한 경우, managed 모듈들만 "%TEMP%\.net\...[생략]..." 디렉터리에 추출하고 로딩해 사용합니다.




이러한 점 때문에 재미있는 효과가 하나 있습니다. 즉, .NET 6에서 다음과 같이 설정한 프로젝트를 배포하는 경우,

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net6.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>

        <PublishSingleFile>true</PublishSingleFile>
        <RuntimeIdentifier>win-x64</RuntimeIdentifier>
        <DebugType>embedded</DebugType>
        <EnableCompressionInSingleFile>true</EnableCompressionInSingleFile>
    </PropertyGroup>

</Project>

이 실행 파일을 Process Explorer 등을 통해 로드된 모듈 목록을 확인하면,

net_single_file_2.png

과연 이 프로세스가 닷넷 managed인지, C/C++로 만든 Native 실행 프로세스인지 구분할 수가 없습니다. 닷넷 런타임에 해당하는 clrjit.dll같은 모듈들이 실행 모듈 자체에 완벽하게 녹아들었고 managed DLL 조차도 메모리 내에 압축 해제한 후 매핑을 시키기 때문입니다.

그나마 추측해 볼 수 있다면, 위의 화면에서 EXE 모듈이 2개가 나오는 것으로 알 수 있는 정도입니다. 하지만 이것조차도 PublishReadyToRun 옵션을 주면 EXE 모듈이 하나만 나오므로 기대할 수 없습니다.

혹은, PE 포맷의 Section에 "CLR_UEF" 항목을 보고 알 수도 있습니다.

net_single_file_0.png

아니면, "dotnet-dump ps" 명령어를 이용하면 됩니다.




IncludeAllContentForSelfExtract 옵션은 IncludeNativeLibrariesForSelfExtract 옵션이 true일 것을 강요하므로, 만약 다음과 같이 강제로 어긋나게 설정하면,

<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
<IncludeNativeLibrariesForSelfExtract>false</IncludeNativeLibrariesForSelfExtract>

빌드 시 이런 오류가 발생합니다.

C:\Program Files\dotnet\sdk\6.0.402\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Publish.targets(895,5): error NETSDK1143:
Including all content in a single file bundle also includes native libraries. If IncludeAllContentForSelfExtract is true, IncludeNativeLibrariesForSelfExtract must not be false. [E:\net6_pubone_sample\net6_pubone_sample.csproj]




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







[최초 등록일: ]
[최종 수정일: 11/11/2022]

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

비밀번호

댓글 작성자
 




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