【发布时间】:2012-01-12 15:18:59
【问题描述】:
我正在使用 ASM 编写基本上相当于 memset() 的内容。我编写的代码有效,除了当我尝试恢复堆栈时,它会因访问冲突而崩溃。我已使用内联汇编将代码放入 MSVC,因此我可以对其进行调试。
函数返回时出现问题。但是,当我取出 add esp, 4 行时,代码可以正确执行,但在 main() 函数返回后,MSVC 说变量周围的堆栈已损坏。
如果没有add esp, 4,我不愿意继续,因为我知道这会在以后引起问题。
我将如何解决这个问题?
int main(int argc, char **argv)
{
char szText[3];
/*__asm
{
push 3
mov edx, 65
lea ecx, szText
call memset
}*/
memset((void*)&szText, 'A', 3);
return 42;
}
void __declspec(naked) __fastcall memset(void *pDest, int iValue, int iSize)
{
__asm
{
; Assume the pointer to the memory is stored in ECX
; Assume the value is stored in EDX
; Assume the size of the block is stored on the stack
mov eax, esi ; Put ESI somewhere it won't be touched (I think)
mov esi, ecx ; Move the address of the memory into ESI
xor ecx, ecx ; Zero ECX
mov ecx, [esp+4] ; Get the size of the block into ECX. ECX is our loop counter
memset_count:
cmp ecx, 0 ; If we are at the end of the block,
jz memset_return ; Jump to return
mov [esi], edx ; Move our value into the memory
inc esi ; Otherwise, increment out position in the memory
dec ecx ; Decrement out counter
jmp memset_count ; Start again
memset_return:
mov esi, eax ; Restore ESI
add esp, 4 ; Clean up the stack
ret
}
}
【问题讨论】:
标签: assembly x86 stack inline-assembly calling-convention