hippietrail
hippietrail

Reputation: 16974

How to detect if a Windows PE executable is for native code vs managed code?

I've been analysing Windows PE executables' binary file format.

I know how to differentiate PE32 (32 bit) vs PE32+ (64 bit) and how to differentiate x86 vs x64.

But I know that managed code uses the same PE executable format (.NET, C#, Mono, CLR, assembly etc) and I believe is documented to always set the architecture to "x86".

So what do I examine in the PE file to see if it's for native code or managed code?

I tried Looking at binary PE files, looking at official documentation and various blogs and repos. I didn't yet find what fields to look at. I may have missed it somewhere.

NOTE: I'm doing this programmatically on my Mac and don't currently have a working Windows machine. I'm looking for a programmatic answer so I can write my own analyser, not looking for a tool to analyse some PE files for me. In fact I can't run such tools if they're Windows apps.

Upvotes: 0

Views: 178

Answers (1)

shingo
shingo

Reputation: 27021

A PE file should be able to contain both native code and managed code. You can use PEReader to detect that. If HasMetadata is true, it means that the file contains managed code.

using var fs = File.OpenRead(FILEPATH);
using var reader = new PEReader(fs);
Console.WriteLine(reader.HasMetadata);

The field you want to look at is called CLR Runtime Header

Upvotes: 2

Related Questions