问题
I'm trying to call sprintf
to format a string and store the result in a stack variable. However, my attempt is failing miserably and it crashes instantly.
sub esp, 0x100 ;Allocate 256 bytes on the stack.
push dword[RequestedFile] ;push string2
push dword[Host] ;push string1
push dword[GetHeader] ;push format "String1: %s, String2: %s"
push dword[ebp - 0x04] ;push buffer/stack variable
call [sprintf] ;store string in buffer
add esp, 0x10 ;restore stack
push dword[ebp - 0x04] ;push the stack variable.
push StringFormat ;push the format
call [printf] ;print the new string.
add esp, 0x08 ;restore the stack
add esp, 0x100 ;destroy the stack variable.
Any ideas what I'm doing wrong?
回答1:
You are using [ebp-4]
as if it were a pointer to your buffer, when in fact it is just random memory garbage in the last 4 bytes of your buffer (assuming nothing else has been allocated from the stack yet). If you want to keep using [ebp-4]
you will need to allocate that from the stack too and initialize it to the address. For example:
sub esp, 0x104 ;Allocate 256 bytes buffer and 4 bytes pointer
mov dword[ebp - 0x04], esp ;store address of buffer in local variable
push dword[RequestedFile] ;push string2
push dword[Host] ;push string1
push dword[GetHeader] ;push format "String1: %s, String2: %s"
push dword[ebp - 0x04] ;push buffer/stack variable
call [sprintf] ;store string in buffer
add esp, 0x10 ;restore stack
push dword[ebp - 0x04] ;push the stack variable.
push StringFormat ;push the format
call [printf] ;print the new string.
add esp, 0x08 ;restore the stack
add esp, 0x104 ;destroy the stack variables.
来源:https://stackoverflow.com/questions/23462749/call-to-sprintf-crashing-in-assembly