Microsoft MVP성태의 닷넷 이야기
.NET Framework: 871. .NET AnyCPU로 빌드된 PE 헤더의 로딩 전/후 차이점 [링크 복사], [링크+제목 복사]
조회: 10450
글쓴 사람
정성태 (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)
13501정성태12/25/20232087개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232178디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20232822닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232294오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232307Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232317Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232500Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232546닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232261개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232232Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232345개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232133개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232067오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232381개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232194개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232088오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232161개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232296닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232817닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232266개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
13480정성태12/12/20232602개발 환경 구성: 692. Windows WSL 2 + Chrome 웹 브라우저 설치
13479정성태12/11/20232299개발 환경 구성: 691. WSL 2 (Ubuntu) + nginx 환경 설정
13477정성태12/8/20232480닷넷: 2182. C# - .NET 7부터 추가된 Int128, UInt128 [1]파일 다운로드1
13476정성태12/8/20232206닷넷: 2181. C# - .NET 8 JsonStringEnumConverter의 AOT를 위한 개선파일 다운로드1
13475정성태12/7/20232278닷넷: 2180. .NET 8 - 함수 포인터에 대한 Reflection 정보 조회파일 다운로드1
13474정성태12/6/20232133개발 환경 구성: 690. 닷넷 코어/5+ 버전의 ilasm/ildasm 실행 파일 구하는 방법 - 두 번째 이야기
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...