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

비밀번호

댓글 작성자
 




1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13532정성태1/17/20242179닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242067닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242042닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241922닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242062Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242012오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242109닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242065오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242117오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20241933오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242094닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242154닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241892오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20241985닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242255닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242101스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242194닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242473닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242115개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242038닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242002개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242021닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20241956닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20241980오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242029오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242718닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...