0

I made a simple MessageBox using nasm in Windows 7 and I was a bit unhappy with the size of the generated file: 2.51 kb.

extern MessageBoxA
extern ExitProcess

import MessageBoxA user32.dll 
import ExitProcess kernel32.dll

section .text use32 

..start: 

push 0
push sCapt
push sText
push 0
call [MessageBoxA]


push 0
call [ExitProcess] 

section .data 

sCapt db 'test', 0
sText db 'test2', 0

So I opened the executable in OllyDbg and it seems that it generated a lot of unnecessary stuff.

ollydbg

So to learn a little more I would like to make this program directly in hexadecimal to stay with the smallest possible size! I searched but found nothing teaching how to create a PE Executable manually.

If someone could give me links or explain how to do I would be grateful!

Jorge Rossi
  • 95
  • 1
  • 11
  • 2
    You might find [this](http://www.phreedom.org/research/tinype/) interesting. – 500 - Internal Server Error Oct 20 '14 at 22:10
  • Nasm didn't actually generate all those zeroes, it's just unused space in the load page. Since the page size is fixed (at 4K if memory serves), it must contain *something*. – Jongware Oct 20 '14 at 22:46
  • 1
    I'm not really sure what you are asking. I guess you know how to write bytes to a file. And the [PE specification](http://download.microsoft.com/download/e/b/a/eba1050f-a31d-436b-9281-92cdfeae4b45/pecoff.doc) tells you what bytes need to be where. And that's it. – arx Oct 21 '14 at 00:28

1 Answers1

5

You can make the program a bit smaller by fiddling with the section aligment options of the linker, but the result will probably not be strictly compliant with the alignment rules for Win32 PE images. The EXE will likely run anyway but someone - or some part of Windows or WINE or ReactOS - might actually rely on those rules, meaning you would be open to Heisenbugs.

That said, in What is the smallest possible Windows (PE) executable? you can find the info you need to make the tiniest possible working PE. The relevant page linked from there is Tiny PE, where Alexander Sotirov describes the tricks that go into making the tiniest possible EXE. Like overlaying header structures, folding them in on themselves and so on...

The wiki article on the PE format has an overview and quite a few useful links.

P.S.: some smaller executables might actually load a few microseconds more slowly than properly aligned ones, if mapping them into memory is more complicated than necessary. Apart from that there shouldn't be any appreciable difference in load time for anything up to one page in size (i.e. 4 KB on most Win32 systems), unless you're dealing with floppy disks and other media that have sectors smaller than the Windows page size. In any case it is bound to be dwarfed by the overhead of creating the process (address space and so on) and dynamic linking.

Community
  • 1
  • 1
DarthGizka
  • 4,347
  • 1
  • 24
  • 36