MASM console window creation troubles (maybe my stack frame??)

268 views Asked by At

I'm having trouble with the following code snippet. I'm compiling an asm file with a c++ file using visual studio express 2012.

I've tried debugging calculating the addresses of the stack pointers and memory locations (still learning assembly obviously), but can't find a fault. (As I'm new it's probably something obvious, but not obvious enough). The asm part is just a function called from the c++ file that is supposed to open a console window and print something in it. The SetConsoleTitleA works fine, it trips on the Writefile function. Here is the error itself :

First-chance exception at 0x00007FF8551A5B48 (KernelBase.dll) in
Troy2.exe: 0xC0000005: Access violation writing location 

0x00007FF700000000.
    Unhandled exception at 0x00007FF8551A5B48 (KernelBase.dll) in Troy2.exe: 
0xC0000005: 
    Access violation writing location 0x00007FF700000000.

And the code is here :

extrn GetStdHandle: PROC
extrn WriteFile: PROC
extrn AllocConsole: PROC
extrn FreeConsole: PROC
extrn SetConsoleTitleA: PROC
extrn SetConsoleCursorPosition: PROC
extrn Sleep: PROC
extrn ExitProcess: PROC
extrn MessageBoxA:PROC

.data
consoletitle db 'Console', 0
prompt db 'Oronco-> ', 0
handle dd ?

.code

myfunction proc
    call AllocConsole
    sub rsp, 20h
    lea rcx, consoletitle
    call SetConsoleTitleA
    add rsp, 20h

    sub rsp, 20h
    mov rcx, -11
    call GetStdHandle
    add rsp, 20h

    mov handle, eax

    sub rsp, 28h
    lea rcx, handle
    lea rdx, prompt
    mov r8, SIZEOF prompt
    mov r9, 0
    mov dword ptr [rsp + 20h], 0
    call WriteFile
    add rsp, 28h
    mov rcx, 2000
    call Sleep

    Call ExitProcess
myfunction endp
End
1

There are 1 answers

0
rkhb On BEST ANSWER
mov dword ptr [rsp + 20h], 0

is wrong. The last parameter has the type LPOVERLAPPED, which is here a 64-bit pointer. Change the line to

mov qword ptr [rsp + 20h], 0

Also,

lea rcx, handle

is wrong. WriteFile expects a value, not an address (pointer). Change it to

mov ecx, handle