Prerequisites
Be familiar with the “Programming in Assembler for x64” chapter, where an introduction to writing assembler programs for the Windows OS is presented. Have the programming tools configured and ready.
Scenario
First, a Hello World type program written purely in assembler.
Result
The “Hello World!” text is displayed in a console.
Start
Create a new assembler source file.
Step 1
It will not be very surprising that the first code example will be the “Hello world!”. This program uses three system functions:
The functions are implemented in a library file, kernel32.lib, which, in our case, is statically linked. We use the “includelib” directive to inform the linker where to search for functions. To inform the assembler about the names of functions, we declare them with the set of “extern” directives.
The details of each statement of the program are explained in comments.
option casemap:none ; recognising small and capital letters includelib kernel32.lib ; statically linked library with system functions EXTERN GetStdHandle:PROC ; declaration of system functions for use EXTERN WriteConsoleA:PROC EXTERN ExitProcess:PROC STD_OUTPUT_HANDLE equ -11 ; STD_OUTPUT_HANDLE costant ; In the data section of our program, there is a string to be displayed .data message db "Hello, World!", 13, 10 msgLen equ $ - message ; constant calculation containing string length ; In the code section of our program, there are instructions for execution .code main PROC ; main function - entry point sub rsp, 28h ; shadow space + align ; HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE) mov ecx, STD_OUTPUT_HANDLE call GetStdHandle ; this function returns the handle of the console window ; WriteConsoleA(hConsole, message, msgLen, &written, NULL) mov rcx, rax ; console window handle lea rdx, message ; pointer to the buffer mov r8d, msgLen ; length lea r9, written ; pointer to a var with a real number of chars written mov qword ptr [rsp+20h], 0 ; 5th argument (lpReserved = NULL) call WriteConsoleA ; this function displays text in the console ; ExitProcess(0) xor ecx, ecx ; value to be returned call ExitProcess ; return to operating system main ENDP ; end of the main function ; In the uninitialised data section of our program, there is a "written" variable .data? written dq ? ; variable which holds the number of written chars END ; end of source file
Step 2
Assemble the program and observe results.
Result validation
The program should print the “Hello World!” text in a console window.
If it does not assemble?
Observe the messages passed by the assembler and linker programs. Refer to the documentation and instruction set. Be sure that all library files are accessible in the environment.