call to sprintf crashing in assembly

梦想的初衷 提交于 2020-01-05 05:27:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!