I'm using MASM and Visual C++, and I'm compiling in x64. This is my C++ code:
// include directive
#include "stdafx.h"
// external functions
extern "C" int Asm();
// main function
int main()
{
// call asm
Asm();
// get char, return success
_getch();
return EXIT_SUCCESS;
}
and my assembly code:
extern Sleep : proc
; code segment
.code
; assembly procedure
Asm proc
; sleep for 1 second
mov ecx, 1000 ; ecx = sleep time
sub rsp, 8 ; 8 bytes of shadow space
call Sleep ; call sleep
add rsp, 8 ; get rid of shadow space
; return
ret
Asm endp
end
Using breakpoints, I've pinpointed the line of code where the access violation occurs: right after the ret
statement in my assembly code.
Extra info:
I'm using the fastcall convention to pass my parameters into
Sleep
(even though it is declared as stdcall), because from what I have read, x64 will always use the fastcall convention.My
Asm
procedure compiles and executes with no errors when I get rid of theSleep
related code.Even when I try to call
Sleep
with the stdcall convention, I still get an access violation error.
So obviously, my question is, how do I get rid of the access violation error, what am I doing wrong?
Edit:
This is the generated assembly for Sleep(500);
in C++:
mov ecx,1F4h
call qword ptr [__imp_Sleep (13F54B308h)]
This generated assembly is confusing me... it looks like fastcall because it moves the parameter into ecx, but at the same time it doesn't create any shadow space. And I have no clue what this means:
qword ptr [__imp_Sleep (13F54B308h)]
.
And again, edit, the full disassembly for main
.
int main()
{
000000013F991020 push rdi
000000013F991022 sub rsp,20h
000000013F991026 mov rdi,rsp
000000013F991029 mov ecx,8
000000013F99102E mov eax,0CCCCCCCCh
000000013F991033 rep stos dword ptr [rdi]
Sleep(500); // this here is the asm generated by the compiler!
000000013F991035 mov ecx,1F4h
000000013F99103A call qword ptr [__imp_Sleep (13F99B308h)]
// call asm
Asm();
000000013F991040 call @ILT+5(Asm) (13F99100Ah)
// get char, return success
_getch();
000000013F991045 call qword ptr [__imp__getch (13F99B540h)]
return EXIT_SUCCESS;
000000013F99104B xor eax,eax
}