Creating a tiny ‘Hello World’ executable in assembly

December 21st, 2009 at 6:53 am

By writing x86 assembly code and assembling it into a .COM file you can get very small executables. The .COM format, originated with 16-bit MS-DOS, is literally nothing except binary code. There’s no relocation information and no import tables, it is loaded by the OS at address 0×100 and starts executing from there. This executable format is still supported by modern Windows OSes, that run it inside a DOS emulator.

Here’s a basic ‘Hello, World!’:

org 100h
mov dx,msg
mov ah,9
int 21h
mov ah,4Ch
int 21h
msg db 'Hello, World!',0Dh,0Ah,'$'

The most interesting part of the code is the int 21h operations. These are software interrupts to call MS-DOS services. The code placed in the AH register prior to calling int 21h specifies the service to call into.

The first service is 9, which asks DOS to print the string pointed by DX into standard output, until a dollar ($) sign is encountered. This is what does the printing in this program. The second service is 4C, which asks DOS to terminate the program.

Assembling this code into a .COM file is easy with Nasm:

nasm -f bin helloworld.asm -o helloworld.com

This results in a 27-byte .COM file that executes and prints ‘Hello, World!’.

Related posts:

  1. Cool hack: creating custom subroutines on-the-fly in Perl

One Response to “Creating a tiny ‘Hello World’ executable in assembly”

  1. lorgNo Gravatar Says:

    You might be interested in the TinyPE challenge. It was published quite some time ago on securiteam by Gil Dabah.
    To see his posts on this, see http://www.ragestorm.net/blogs/?p=51 and http://www.ragestorm.net/blogs/?s=tiny
    In the last version I know of he got to 213 bytes for a PE file that downloads and runs an executable.

Leave a Reply

To post code with preserved formatting, enclose it in `backticks` (even multiple lines)