Invokation of system functions on 64bit Windows requires to mark the function name as imported from its DLL, align RSP, push or load its arguments, create shadow space, call the function name and finally restore RSP to equilibrum (to the same value which it had before the invokation).
Function OpenFile is deprecated, MS recommends CreateFileA instead.
Look at Example: Fast version of invokation WinABI:
The following example is in Intel-syntax, asm-able on Windows with euroasm.exe example.asm
. It may need some modifications for other assemblers: SPL
is called SPB
in some other assemblers, which also may require default rel
to prefer RIP-relative encoding of LEA
and ADD qword [RSP],8
rather than ADDQ [RSP],8
.
If your tool prefers AT&T syntax instead of Intel syntax, change the order of ASM operands and prefix register names with %.
IMPORT CreateFileA, LIB="kernel32.dll"
PUSH RSP ; Store original stack pointer value (equilibrum).
TEST SPL,1000b ; Test RSP OWORD alignment at run-time.
JNZ .WinABI1 ; Skip to the label when not aligned.
PUSH RSP ; Store and update 2nd copy of original RSP (equilibrum).
ADDQ [RSP],8 ; Those two instructions aren't executed if RSP was properly aligned.
.WinABI1: ; Local label.
PUSHQ 0 ; Push 7th argument.
PUSHQ FILE_ATTRIBUTE_NORMAL ; Push 6th argument.
PUSHQ OPEN_EXISTING ; Push 5th argument.
MOV R9,0 ; Load 4th argument.
MOV R8,FILE_SHARE_READ ; Load 3rd argument.
MOV RDX,GENERIC_READ ; Load 2nd argument.
LEA RCX,[FileName] ; Load 1st argument.
SUB RSP,4*8 ; Make room for shadow space in fast mode. RSP is OWORD-aligned.
CALL CreateFileA ; Call the imported function.
LEA RSP,[RSP+7*8] ; Discard transferred arguments, keep RFlags.
POP RSP ; Restore RSP to equilibrum from 1st or 2nd copy.
Unlike on Linux, if you want to allow nonASCII characters in FileName
, they are expected in wide (UTF-16) encoding, and CreateFileW
should be invoked instead of CreateFileA
.
Although the calling convention is very different in 64bit version of Windows, functions are still being imported from %SystemRoot%\System32\kernel32.dll
, %SystemRoot%\System32\user32.dll
etc.