Thursday, March 9, 2023

Interactive Hello World Windows x64 Assembly MASM64

This interactive hello world creates minimum message box then prints text in console, reads input from user and prints the input back to console.

Create file hello.asm and put following code in it:

; Interactive Hello World Windows x64 Assembly MASM64

; ml64 hello.asm /link /subsystem:windows /defaultlib:kernel32.lib /defaultlib:user32.lib /entry:Start

; ivane5


extern ExitProcess: PROC

extern MessageBoxA: PROC

extern GetStdHandle: PROC

extern WriteConsoleA: PROC

extern FlushConsoleInputBuffer: PROC

extern ReadConsoleA: PROC


.data

caption db '64-bit hello!',0

message db 'Hello World!',10,0


STD_OUTPUT_HANDLE dq -11

OUTPUT_HANDLE     dq 0


STD_INPUT_HANDLE dq -10

INPUT_HANDLE     dq 0


ENABLE_LINE_INPUT dq 0002h


cWritten  dq 0


inputBuffer db 64 dup(0)

numberOfEventsRead dw 0


.code

Start PROC

  sub  rsp, 28h ; shadow space, for debugging

  mov  rcx, 0 ; hWnd = HWND_DESKTOP

  lea  rdx, message 

  lea  r8, caption 

  mov  r9d, 0  

  call MessageBoxA ; call MessageBox API function


  mov rcx, STD_OUTPUT_HANDLE

  call GetStdHandle

  mov OUTPUT_HANDLE, rax 


  mov rcx, STD_INPUT_HANDLE

  call GetStdHandle

  mov INPUT_HANDLE, rax 


  mov rcx, OUTPUT_HANDLE

  lea rdx, message

  mov r8, 13

  lea r9, cWritten

  push 0

  call WriteConsoleA ; Write the hello world message


  mov rcx, INPUT_HANDLE

  call FlushConsoleInputBuffer


  mov rcx, INPUT_HANDLE

  lea rdx, inputBuffer

  mov r8, 64

  lea r9, numberOfEventsRead

  call ReadConsoleA ; Read user input

  

  mov rcx, OUTPUT_HANDLE

  lea rdx, inputBuffer

  mov r8, 64

  lea r9, cWritten

  push 0

  call WriteConsoleA ; Write user input back to console

  

  mov ecx, 0 ; uExitCode = 0

  call ExitProcess

Start ENDP

End

Open, Visual Studio 2022 Developer Command Prompt, and within the prompt open the folder in which the hello.asm is located.

Run following command:

ml64 hello.asm /link /subsystem:windows /defaultlib:kernel32.lib /defaultlib:user32.lib /entry:Start

Then run: 

hello.exe