How to check if an object file is in COFF or ELF format from C?

I would like to be able to check the object file format from my C code so that I can use different functions to read the file based on whether it is COFF or ELF format.

Is this possible, and if so, how can I do this?

This is on Linux btw, if that matters.

+4
source share
3 answers

Read the first four bytes. If they are equal to \x7fELF , this is an ELF file. Otherwise, you should analyze it as COFF and see if it makes sense. (Note that COFF magic is much more complicated, I get at least 42 magic entries in /usr/share/file/magic for it).

+10
source

Check the magic number. ELF magic number is 0x7f454C46 (0x7f + "ELF") and COFF is 0x14c . Take care of this anyway, because there are different magic numbers for COFF.

Keep an eye on the content as you read these values.

+4
source

Try the file command. It tells you the file type.

+2
source

Source: https://habr.com/ru/post/1438943/


All Articles