Cogs and Levers A blog full of technical stuff

Windows Development with NASM

In this post, I’ll walk through the steps required to bootstrap your development experience against the Win32 API using the Netwide Assembler.

Prerequisites

Before starting, you’ll need some software. I’ve used the following software set, however you can use any linker and resource compiler that you like.

You’ll use Nasm to reduce your assembly source code into COFF object files. Gorc will take your resource scripts and produce linkable object files from these. Finally, ALink will bind all of your object files into a windows executable.

Finally, you’re going to need a copy of the include file for the Win32 API. The API itself is huge; the number of constants and structures is mind boggling. The link above handles all of these for you.

Test program

Probably the easiest thing to accomplish, is showing a message box. You need to show the message box and then return control back to Windows. You do this with calls to MessageBoxA and ExitProcess. The “A” in MessageBoxA as we’re not dealing with the wide-char version of these functions.

Here’s the code.

%include "win32n.inc"

extern MessageBoxA
import MessageBoxA user32.dll

extern ExitProcess
import ExitProcess kernel32.dll

segment .data USE32

	title	db "A message for you", 0
	message db "This is your first message", 0

segment	.bss USE32

segment .code USE32

..start:

	; show the message box
	push MB_OK
	push title
	push message
	push 0
	call [MessageBoxA]

	; return control back to windows
	push 0
	call [ExitProcess]

Functions are imported from the api using import, and are called in a very assembler-traditional fashion here. Taking a look at the definition for the MessageBox function, we can see the order of parameters:

int WINAPI MessageBox(
  HWND    hWnd,
  LPCTSTR lpText,
  LPCTSTR lpCaption,
  UINT    uType
);

Arguments are pushed to the stack in reverse order.

Assembling and linking

Now that you’ve got your source file, hello.asm you can produce an object file with the following:

C:\src> nasm -i c:\nasm\include -f obj hello.asm

You can now link the object file into an executable with the following:

C:\src> alink -c -oPE -subsys gui hello

Ready to go.

Making things a little more high-level

You can make your assembly code a little more high-level by using the nagoa+.inc include file. This include file provides your programs with some really handy constructs (as well as the win32 api bindings), so function invocations now look like this:

call MessageBoxA, 0, message, title, MB_OK
call ExitProcess, 0

Conclusion

This will get you started at least with Nasm in Windows development. Here is a great resource, full of links on assembly development.