0

Hello I have the following code:

extern GetStdHandle, WriteConsoleA, ExitProcess section .text _main: mov rcx, STD_OUTPUT_HANDLE call GetStdHandle mov rcx, rax ; hConsoleOutput mov rdx, msg ; *lpBuffer mov r8, len ; nNumberOfCharsToWrite ;mov r9, 0 ; lpNumberOfCharsWritten ;push 0 ; lpReserved call WriteConsoleA mov rcx, 0 call ExitProcess section .data STD_OUTPUT_HANDLE: dq -11 msg: db "Hello World!", 0x0A len equ $-msg 

It compiles and links correctly, however nothing prints out.

If I replace mov rcx, STD_OUTPUT_HANDLE with mov rcx, -11 then it work correctly, but I am not sure how to get it so I can use it as a variable.

Also if I change it to: mov rcx, [STD_OUTPUT_HANDLE]

Then the error changes to:

main.obj:main.asm:(.text+0x4): relocation truncated to fit: IMAGE_REL_AMD64_ADDR32 against '.data'

I am budling the code like so: nasm -fwin64 main.asm ld -LC:/Windows/System32 -lkernel32 -o main.exe main.obj

7
  • Use mov rcx, [rel STD_OUTPUT_HANDLE] or stick a default rel at the top of your file. Commented Apr 21, 2024 at 22:31
  • You are not following the Windows x86-64 calling convention correctly Commented Apr 21, 2024 at 22:49
  • @RaymondChen Can you expand upon that? Or what am I doing incorrectly? The commented out portion? Commented Apr 21, 2024 at 22:55
  • 1
    Stack not aligned on a 16 byte boundary, no home space for outbound calls, not enough parameters passed to WriteConsole, no unwind codes. Commented Apr 22, 2024 at 1:51
  • Or better, mov ecx, -11 (or make STD_OUTPUT_HANDLE an equ define). There's no reason to put a -11 in .data when you could just use it as an immediate. Raymond's correct about the calling convention, though: you need to pass a 0 at RSP+32, the first stack arg (above the callee's home space aka shadow space). You're calling ExitProcess instead of returning so it's sort of ok that you don't reserve more space, you can let it step on your function's return address as part of its shadow space, and it might happen to work with the stack misaligned. But better to learn to do it right. Commented Apr 22, 2024 at 3:44

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.