views:

398

answers:

5

I'm trying to write a program in assembly and make the resulting executable as small as possible. Some of what I'm doing requires windows API calls to functions such as WriteProcessMemory. I've had some success with calling these functions, but after compiling and linking, my program comes out in the range of 14-15 KB. (From a source of less than 1 KB) I was hoping for much, much less than that.

I'm very new to doing low level things like this so I don't really know what would need to be done to make the program smaller. I understand that the exe format itself takes up quite a bit of space. Can anything be done to minimize that?

I should mention that I'm using NASM and GCC but I can easily change if that would help.

A: 

I suggest using the DumpBin utility (or GNU's objdump) to determine what takes the most space. It may be resource files, huge global variables or something like that.

Bastien Léonard
+1  A: 

The default section alignment for most PE files is 4K to align with the natural system memory layout. If you have a .data, .text and .resource section - that's 12K already. Most of it will be 0's and a waste of space.

There are a few things you can do to minimize this waste. First, reduce the section alignment to 512 bytes (don't know the options needed for nasm/gcc). Second, merge the sections so that you only have a single .text section. This can be a problem though for modern machines with the NX bit turned on. This security feature prevents modification of executable sections of code from things like viruses.

There are also a slew of PE compression tools out there that will compact your PE and decompress it when executed.

Paul Alexander
+2  A: 

See Tiny PE for a bunch of tips and tricks you can use to reduce the final size of your executable. Be warned that some of the later techniques in that article are extremely fragile.

Adam Rosenfield
A: 

FWIW, the smallest programs I can assemble using ML or ML64 are on the order of 3kb. (That's just saying hello world and exiting.)

PhiS
A: 

Give me a small C program (not C++), and I'll show you how to make a 1 ko .exe with it. The smallest size of executable I recommend is 1K, because it will fail to run on some Windows if it's not at least this size.

You merely have to play with linker switches to make it happen! A good linker to do this is polink.

And if you do everything in Assembly, it's even easier. Just go to the MASM32 forum and you'll see plenty of programs like this.

toto
IMO FASM is much better suited for this pupose. It can create executables directly, and allows you to define sections yourself.
Bastien Léonard
Yea, FASM is nice. You can DB your whole executable and that's the best way of achieving these small executables.Heureusement, I have managed to stop my mental illness at 1ko :)
toto