1 Replies - 1013 Views - Last Post: 31 January 2013 - 03:34 PM

#1 c3phalex1n  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 25-January 13

a question about how to work with c functions in asm

Posted 31 January 2013 - 12:39 PM

Hi Guys...!
Look the following source...! please!

.section .data
          data1:
          .int 200000
          data2:
          .int 201010
          result:
          .quad 0
          output:
          .asciz "The result is %qd\n"
.section .text
.globl main
main:
          nop
          movl data, %eax
          mull data2
          movl %eax, result
          movl %edx, result+4
          pushl %edx
          pushl %eax
          call printf
          add $12, %esp
          pushl $0
          call exit
          


Guys i dont know why using add $12, %esp in this snippet code!
Who can tell me what does it instruction in this code?!

sorry for bad english speaking!

Is This A Good Question/Topic? 0
  • +

Replies To: a question about how to work with c functions in asm

#2 GunnerInc  Icon User is online

  • "Hurry up and wait"
  • member icon




Reputation: 858
  • View blog
  • Posts: 2,276
  • Joined: 28-March 11

Re: a question about how to work with c functions in asm

Posted 31 January 2013 - 03:34 PM

The code is wrong, it should be add $8, %esp because 2 parameters were passed to printf.

printf is a variable argument function, meaning it could take any amount of arguments. The callee (printf) has no way of knowing how many arguments were passed, so in order to adjust the stack correctly, the caller (you) have to adjust the stack with add esp, 4 * NumberOfArgs <- convert that to your AT&T syntax. The above is 32 bit code, and all parameters are DWORD sized (4 bytes a piece)

    pushl %edx
    pushl %eax

you are passing 2 parameters on the stack, each one is 4 bytes (2 DWORDS) so after printf, you adjust the stack with add esp, 4 * NumberOfArgs, if you don't, or use the wrong number, your code might not throw a hissy fit right away, but it WILL crash eventually.

Most C functions use the CDECL calling convention where you the programmer must adjust the stack after each call.

There is a pinned topic called Assembler - Getting Started it contains a wealth of information to help you on your Assembly journey. There is even a link to a Wiki article explaining calling conventions.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1