Hello World in MASM
[Gemini]
Microsoft Macro Assembler (MASM) is the standard for writing assembly code on Windows. Modern MASM usually targets x64 (64-bit), which uses a specific calling convention and 64-bit registers.
Below is a classic “Hello World” example written for MASM x64, utilizing the Windows API (MessageBoxA).
1. MASM x64 “Hello World” Example
; --- External Windows API functions ---
extern MessageBoxA : proc
extern ExitProcess : proc
.data
window_title db "MASM x64", 0
message db "Hello from Microsoft Assembler!", 0
.code
main proc
; --- Shadow Space ---
; Windows x64 ABI requires 32 bytes of "shadow space" on the stack
; before calling a function.
sub rsp, 28h
; --- Setup Arguments for MessageBoxA ---
; RCX = hWnd (NULL = 0)
; RDX = lpText (Address of message)
; R8 = lpCaption (Address of title)
; R9 = uType (MB_OK = 0)
xor rcx, rcx ; Set RCX to 0
lea rdx, message ; Load effective address of message
lea r8, window_title ; Load effective address of title
xor r9, r9 ; Set R9 to 0
call MessageBoxA ; Call the API
; --- Cleanup and Exit ---
xor rcx, rcx ; Exit code 0
call ExitProcess
main endp
end2. Key Components Explained
The Registers (x64)
In the example above, we use 64-bit registers. The Windows calling convention uses specific registers for passing arguments:
- RCX: 1st Argument
- RDX: 2nd Argument
- R8: 3rd Argument
- R9: 4th Argument
Shadow Space (sub rsp, 28h)
One of the most common pitfalls in MASM for Windows is forgetting the Shadow Space. Even if a function takes fewer than 4 arguments, the caller must reserve 32 bytes ($20h$) plus an extra 8 bytes ($8h$) to maintain 16-byte stack alignment.
Directives
.data: Defines the section for initialized data (strings, constants)..code: Defines the section for executable instructions.proc/endp: Marks the beginning and end of a procedure (function).
3. How to Assemble and Link
To run this, you typically use the tools provided with Visual Studio (ml64.exe for the assembler and link.exe for the linker).
- Assemble:
ml64.exe /c my_file.asm - Link:
link.exe my_file.obj /subsystem:windows /defaultlib:user32.lib /defaultlib:kernel32.lib /entry:main
Would you like me to show you how to perform a simple mathematical calculation (like a Fibonacci sequence) using MASM instead?
