As a precursor to writing a compiler I'm trying to understand the Windows (32-bit) Portable Executable format. In particular I'd like to see an example of a bare-bones executable which does nothing except load correctly, run and exit.
I've tried writing and compiling a simple C main function which does nothing but the resulting .exe is ~22KB and contains many imports from KERNEL32.DLL (presumably used by LIBC to set up environment, heaps etc.). Even the DOS Header could probably be smaller (it currently prints the default 'This program cannot be run in DOS mode').
What is the structure of the smallest possible Windows 32-bit executable?
On Windows XP (x32) the smallest PE executable is 97 bytes. On 32bit versions of Vista and 7 the smallest PE executable is 252 bytes. On 64bit versions of Windows the smallest 32bit executable is 268 bytes. On this forum you find a bit-map of such executable.
The smallest x64 PE executable is 268 bytes. It is even possible to execute every byte in an executable of this size. You can find a link on this forum as well.
The code below is a x64 PE (aka PE32+) executable file of size 268 bytes.
BTW On this blog entry you find a small (316 bytes) x32 executable with assembler source code and many technical details.
As quoted from source (Creating the smallest possible PE executable): 1
This result was achieved with some clever NASM tricks, such as removing the step that links to C
stdlib
and removing a number of header fields and data directories.The full source code is below. It is effectively the same as the article with these modification:
sectalign
label renamed tosect_align
. Since the time this assembly code was writtensectalign
became a NASM keyword. Rename it to avoid warnings and errors.The code is as follows:
To build into an executable use:
For GNU/Linux ELF executables, See the article "Whirlwind Tutorial on Creating Really Teensy ELF Executables for Linux". TL;DR:
1340
bytes, using NASMNote: This answer is an expansion of J...'s comment on Dec 3 '16 at 17:31, in order to preserve the information found in the link (in case that too goes dead).