2

I writing a compiler as my university project. I am on the stage of code generating. And I'm wondering why this isn't working (prints always 0):

.extern printf
.section .data
hello:
    .string "Hello %f!\n"
.section .text
.globl main
main:
    pushl %ebp
    movl %esp, %ebp

    pushl $3214514586 // or pushl $0xbf99999a
    pushl $hello
    call printf

    leave
    ret

but this works correctly:

.extern printf
.section .data
hello:
    .string "Hello %f!\n"
.section .text
.globl main
main:
    pushl %ebp
    movl %esp, %ebp

    pushl $3214514586 // or pushl $0xbf99999a

    flds (%esp)
    fstpl (%esp)

    pushl $hello
    call printf
    leave
    ret

1 Answers1

3

In C float argments to a varargs function (such as printf) are promoted to double. Your second code converts the 4-byte float to an 8-byte double so that it passes the correct value to printf, however it overwrites the saved value of ebp so may crash.

Timothy Baldwin
  • 3,551
  • 1
  • 14
  • 23
  • The first half of your answer is spot on, but I don't get the second - where is he corrupting the saved ebp? – Matteo Italia Dec 23 '17 at 09:26
  • Nah ok now I see it, but I'd point out that it's common to both snippets. – Matteo Italia Dec 23 '17 at 09:28
  • 1
    @Matteo, No, the first example doesn't *overwrite* anything on the stack; it just does pushes. The second example pushes 4 bytes and then overwrites it with 8 bytes, clobbering whatever was above it on the stack, which was the saved value of ebp. – prl Dec 23 '17 at 09:38
  • The first example may also overwrite the saved `ebp` value as functions are allowed to modify their arguments. – Timothy Baldwin Dec 23 '17 at 13:17
  • Does it promote to double even in using gcc -m32? – Дмитрий Терехов Dec 23 '17 at 13:47
  • @Дмитрий Терехов: yes, C's promotion rules for variadic functions have nothing to do with 64-bit integers or the target machine, just that passing a `float` to a variadic function always promotes it to `double` before you even look at the ABI to decide what that means for the binary representation. – Peter Cordes Dec 23 '17 at 16:21