汇编程序在调用printf后崩溃

问题描述 投票:0回答:1

我正在编写一个简单的函数来从堆栈中打印浮点值。生成此函数,因此未进行优化。程序在printf调用时崩溃。

;input: float32 as dword ptr ebp+8
printfloat32:
 push   ebp
  mov   ebp,    esp
  sub   esp,    16
;local ptr variable k at dword ptr ebp-4
  mov   dword ptr ebp-4,    lpcstr4 ;which is "%f"

movss       xmm0,           dword ptr ebp+8
cvtss2sd    xmm0,           xmm0
  sub       esp,            8
movsd       qword ptr esp,  xmm0
 push       dword ptr ebp-4
 call       printstr
  add       esp,            12

  mov   esp,    ebp
  pop   ebp
  ret

printstr是printf。这是完整生成的代码:https://pastebin.com/g0Wff0JY

c assembly x86 fasm
1个回答
1
投票

看图像,我看到可能存在什么问题,但我不知道法术语法:

        call    [printstr]     ;syntax used for the first call
        ...
        call    printstr       ;syntax used for the second call that fails

如果printstr是一个基于内存的函数指针,那么第二个调用语法可能试图调用存储指针的位置,而不是通过使用内存中的值作为函数指针来调用实际函数。

对于最新版本的Visual Studio,默认的printf和scanf有效地内联到C / C ++代码中,语法相当复杂。而不是处理这个,有可用的可调用遗留版本需要这个includelib语句:

        includelib      legacy_stdio_definitions.lib    ;for scanf, printf, ...

我将代码从问题转换为masm语法,将printstr更改为printf,并在Windows 7 Pro 64位上使用Visual Studio 2015测试了32位构建(构建为32位,因此以32位模式运行)。我对这段代码没有任何问题。我使用调试器逐步完成代码,并没有看到存储在堆栈中的内容有任何问题。我怀疑问题是没有括号的第二次调用printstr,我在转换为masm语法时进行了更正。

        .data
varf    real4   123.75
lpcstr4 db      "%f",00ah,0             ;added new line
        .code
        extern  printf:near             ;instead of printstr

printfloat32 proc
        push    ebp
        mov     ebp,esp
        sub     esp,16
        mov     dword ptr [ebp-4], offset lpcstr4
        movss   xmm0,dword ptr [ebp+8]
        cvtss2sd xmm0,xmm0
        sub     esp,8
        movsd   qword ptr [esp],xmm0
        push    dword ptr [ebp-4]
        call    printf                  ;was printstr
        add     esp,12
        mov     esp,ebp
        pop     ebp
        ret
printfloat32 endp

main    proc
        push    varf            ;test printfloat32 function
        call    printfloat32
        add     esp,4
        xor     eax,eax
        ret
main    endp
        end

使用printstr作为printf的指针。 Masm不需要括号,因为它知道printstr是一个dd(指向printf的指针)。

        .code
        extern  printf:near
printstr dd     printf          ;masm doesn't need brackets

printfloat32 proc
;       ...
        call    printstr        ;masm doesn't need brackets
;       ...
printfloat32 endp

如果printstr是在此源文件的外部,则masm语法将是

        extrn   printstr:ptr    ; or extern   printstr:dword
© www.soinside.com 2019 - 2024. All rights reserved.