Microsoft MVP성태의 닷넷 이야기
.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [링크 복사], [링크+제목 복사]
조회: 10479
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

.NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점

잠시 지난 글의 코드를 실습하고 있는데,

해당 DLL이 Managed인지 / Unmanaged인지 확인하는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/1296

AnyCPU의 PE 헤더가 로딩 전/후에 따라 달라지는 것을 알게 되었습니다.

예를 들어, AnyCPU로 빌드한 콘솔 프로그램의 경우 디스크 상의 파일을 기반으로 "CFF Explorer"를 이용해 로딩해 보면 다음과 같은 PE Header 정보를 볼 수 있습니다.

anycpu_pe_header_1.png

anycpu_pe_header_2.png

즉, 완벽하게 32bit 규격의 PE header를 가지고 있습니다. 하지만 이것을 windbg로 로딩해 보면,

Microsoft (R) Windows Debugger Version 10.0.17763.132 AMD64
Copyright (c) Microsoft Corporation. All rights reserved.

CommandLine: C:\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe

************* Path validation summary **************
Response                         Time (ms)     Location
Deferred                                       SRV*c:\Symbols*http://msdl.microsoft.com/download/symbols
Symbol search path is: SRV*c:\Symbols*http://msdl.microsoft.com/download/symbols
Executable search path is: 
ModLoad: 00000000`00ef0000 00000000`00ef8000   ConsoleApplication1.exe
ModLoad: 00007ffe`19c60000 00007ffe`19e50000   ntdll.dll
ModLoad: 00007ffe`022f0000 00007ffe`02354000   C:\WINDOWS\SYSTEM32\MSCOREE.DLL
ModLoad: 00007ffe`18e20000 00007ffe`18ed2000   C:\WINDOWS\System32\KERNEL32.dll
ModLoad: 00007ffe`16e70000 00007ffe`17113000   C:\WINDOWS\System32\KERNELBASE.dll
(5abc.5564): Break instruction exception - code 80000003 (first chance)
ntdll!LdrpDoDebuggerBreak+0x30:
00007ffe`19d311dc cc              int     3

0:000> dt _IMAGE_DOS_HEADER 00000000`00ef0000 
ntdll!_IMAGE_DOS_HEADER
   +0x000 e_magic          : 0x5a4d
   +0x002 e_cblp           : 0x90
   +0x004 e_cp             : 3
   +0x006 e_crlc           : 0
   +0x008 e_cparhdr        : 4
   +0x00a e_minalloc       : 0
   +0x00c e_maxalloc       : 0xffff
   +0x00e e_ss             : 0
   +0x010 e_sp             : 0xb8
   +0x012 e_csum           : 0
   +0x014 e_ip             : 0
   +0x016 e_cs             : 0
   +0x018 e_lfarlc         : 0x40
   +0x01a e_ovno           : 0
   +0x01c e_res            : [4] 0
   +0x024 e_oemid          : 0
   +0x026 e_oeminfo        : 0
   +0x028 e_res2           : [10] 0
   +0x03c e_lfanew         : 0n128

0:000> ? 00000000`00ef0000 + 0n128 + 0n4
Evaluate expression: 15663236 = 00000000`00ef0084

0:000> dt _IMAGE_FILE_HEADER 00000000`00ef0084
ntdll!_IMAGE_FILE_HEADER
   +0x000 Machine          : 0x14c
   +0x002 NumberOfSections : 3
   +0x004 TimeDateStamp    : 0x5e022dd0
   +0x008 PointerToSymbolTable : 0
   +0x00c NumberOfSymbols  : 0
   +0x010 SizeOfOptionalHeader : 0xf0
   +0x012 Characteristics  : 0x22

보는 바와 같이 _IMAGE_FILE_HEADER의 Machine 값이 (현재 x64 프로세스 공간임에도 불구하고) 0x14c(IMAGE_FILE_MACHINE_I386) 값을 갖고 있기 때문에 AnyCPU 이미지인 경우에는 Machine 필드의 값으로 타겟 플랫폼을 판단해서는 안 됩니다.

그런데, 재미있는 변화가 있습니다. 바로 SizeOfOptionalHeader의 값이 디스크 상에서는 0xe0이었던 것과는 달리 DLL 메모리 매핑이 이뤄진 시점에는 0xf0으로 변경되었다는 점입니다. 따라서 이 값을 기반으로 현재 로딩된 이미지를 x86 또는 x64 중 어떤 것으로 다뤄야 하는지 판단할 수 있습니다.

혹은, IMAGE_FILE_HEADER의 바로 다음 int16 값을 읽어보는 것도 방법일 수 있습니다. 즉, IMAGE_OPTIONAL_HEADER 영역의 Magic 필드 값을 읽어보는 건데요. 이 값도 디스크 상에 있을 때는 0x010B로 "PE32" 유형을 의미하지만 DLL 메모리 매핑이 이뤄진 시점에는,

0:000> dw 00000000`00ef0084+0x14 L1
00000000`00ef0098  020b

0x020b로 PE64를 의미하는 값으로 바뀌어 있습니다.




그런데 좀 미심쩍은 면이 있습니다. windbg에 로딩하자마자, 다음과 같이 mscoree.dll이 로드된 것을 볼 수 있습니다.

ModLoad: 00000000`00ef0000 00000000`00ef8000   ConsoleApplication1.exe
ModLoad: 00007ffe`19c60000 00007ffe`19e50000   ntdll.dll
ModLoad: 00007ffe`022f0000 00007ffe`02354000   C:\WINDOWS\SYSTEM32\MSCOREE.DLL
ModLoad: 00007ffe`18e20000 00007ffe`18ed2000   C:\WINDOWS\System32\KERNEL32.dll
ModLoad: 00007ffe`16e70000 00007ffe`17113000   C:\WINDOWS\System32\KERNELBASE.dll

혹시 저 DLL에서 PE 헤더의 값을 동적으로 바꾸는 것일까요? 이를 확인하기 위해 windbg의 "Debug" / "Event Filters..." 메뉴를 선택하고, "Load module" 이벤트 항목에 대해 "Execution"을 "Enabled"로, "Continue"를 "Not Handled"로 바꿔준 다음,

anycpu_pe_header_3.png

다시 AnyCPU 실행 파일을 로드해 보면 이렇게 2개만 로드된 것을 확인할 수 있습니다.

ModLoad: 00000000`00380000 00000000`00388000   ConsoleApplication1.exe
ModLoad: 00007ffe`19c60000 00007ffe`19e50000   ntdll.dll

이제 다시 PE Header 관련 값을 덤프해 보면,

0:000> ? 00000000`00380000 + 0n128 + 0n4
Evaluate expression: 3670148 = 00000000`00380084

0:000> dt _IMAGE_FILE_HEADER 00000000`00380084
ntdll!_IMAGE_FILE_HEADER
   +0x000 Machine          : 0x14c
   +0x002 NumberOfSections : 3
   +0x004 TimeDateStamp    : 0x5e022dd0
   +0x008 PointerToSymbolTable : 0
   +0x00c NumberOfSymbols  : 0
   +0x010 SizeOfOptionalHeader : 0xe0
   +0x012 Characteristics  : 0x22

0:000> dw 00000000`00380084+0x14 L1
00000000`00380098  010b

오호... 놀랍군요. ^^ 이 시점까지는 디스크 상의 PE 파일 내용과 동일하게 값을 유지하고 있습니다. 그렇다면 이러한 PE Header를 동적으로 변경하는 것은 운영체제가 아니고 mscoree.dll일 수 있다는 것입니다. 실제로 위의 상태에서 디버깅을 진행해 "mscoree.dll"을 로딩한 다음,

0:000> g
ModLoad: 00007ffe`022f0000 00007ffe`02354000   C:\WINDOWS\SYSTEM32\MSCOREE.DLL
ntdll!NtMapViewOfSection+0x14:
00007ffe`19cfc5c4 c3              ret
0:000> 

다시 PE Header 값을 확인해 보면,

0:000> dt _IMAGE_FILE_HEADER 00000000`00380084
ntdll!_IMAGE_FILE_HEADER
   +0x000 Machine          : 0x14c
   +0x002 NumberOfSections : 3
   +0x004 TimeDateStamp    : 0x5e022dd0
   +0x008 PointerToSymbolTable : 0
   +0x00c NumberOfSymbols  : 0
   +0x010 SizeOfOptionalHeader : 0xf0
   +0x012 Characteristics  : 0x22

0:000> dw 00000000`00380084+0x14 L1
00000000`00380098  020b

값이 바뀌어 있습니다. (DllMain 함수 내에서 바꾸는 코드가 호출되는 걸까요? ^^)




관련해서 검색해 보면,

The Relationship Between .NET And The Windows Kernel
; http://debugandconquer.blogspot.com/2015/04/the-relationship-between-net-and.html

다음의 내용을 볼 수 있습니다.

AnyCPU Executables - How Does It Work?

The documentation of mscoree’s _CorValidateImage refers to changing 32-bit (PE32) executable image to 64-bit (PE32+) executable image in memory (an executable in memory is called an Image) on 64-bit Windows, and you might think that it's all to it, However that's a user mode function that is supposed to be called in the newly created process by the NTDLL Loader, the decision about the architecture of a process happens earlier, and in kernel mode (kernel structures like EPROCESS depend on it), so there has to be some kernel mode code knowing about .NET which decides which architecture to use.

Note: I debugged and _CorValidateImage isn't getting called on Windows 8.1 (on Windows 7 it does), its responsibility seems to have moved to the Loader's LdrpCorValidateImage and LdrpCorFixupImage functions.


여기서 재미있는 점이 있습니다. 운영체제는 PE32 header를 갖는 AnyCPU 이미지를 x64 시스템에서는 64bit 프로세스로 실행해 주는데 결국 위의 링크에서도 언급하고 있지만 EPROCESS 커널 자료 구조를 위해서라도 Kernel 레벨에서 32비트 이미지와 동일하게 빌드되어 있는 AnyCPU 이미지를 판단해야 한다는 것입니다.

아마도, Kernel 측의 Loader에서는 PE32 header만으로는 판단하지 못하고 "Data Directory"까지 내려가 CLR Runtime Header를 가지고 있는지, 만약 가지고 있다면 그 안에 "ILONLY", "32BITPREF"가 설정되었는지를 보고 AnyCPU로서의 적절한 프로세스 구성을 하게 될 것입니다.

참고로 _CorValidateImage 함수에 대한 마이크로소프트의 공식 문서를 보면,

_CorValidateImage Function
; https://learn.microsoft.com/en-us/dotnet/framework/unmanaged-api/hosting/corvalidateimage-function

웬만큼 궁금했던 내용들을 다 설명하고 있군요. ^^

In Windows XP and later versions, the operating system loader checks for managed modules by examining the COM Descriptor Directory bit in the common object file format (COFF) header. A set bit indicates a managed module. If the loader detects a managed module, it loads MsCorEE.dll and calls _CorValidateImage, which performs the following actions:

  • Confirms that the image is a valid managed module.
  • Changes the entry point in the image to an entry point in the common language runtime (CLR).
  • For 64-bit versions of Windows, modifies the image that is in memory by transforming it from PE32 to PE32+ format.
  • Returns to the loader when the managed module images are loaded.

For executable images, the operating system loader then calls the _CorExeMain function, regardless of the entry point specified in the executable. For DLL assembly images, the loader calls the _CorDllMain function.

_CorExeMain or _CorDllMain performs the following actions:

  • Initializes the CLR.
  • Locates the managed entry point from the assembly's CLR header.
  • Begins execution.

The loader calls the _CorImageUnloading function when managed module images are unloaded. However, this function does not perform any action; it just returns.




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







[최초 등록일: ]
[최종 수정일: 4/15/2024]

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

비밀번호

댓글 작성자
 



2022-07-21 09시01분
정성태

1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13526정성태1/14/20242048닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242018오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242064오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20241888오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242026닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242108닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241858오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20241937닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242172닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242016스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242103닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242374닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242064개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242004닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20241979개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20241995닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20241936닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20241966오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242013오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242696닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232188닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232704닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232321닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232189Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232289닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232087개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...