How does this adding of two numbers works in Assembly

后端 未结 1 1462
时光说笑
时光说笑 2021-01-26 05:55

I am new to assembly language and trying to understand a simple program which will add two nunbers and display the result.

section .data

message1 db \"value=%d%         


        
相关标签:
1条回答
  • 2021-01-26 06:09

    The printf librarymay be implemented in many ways, so it would be dangerous to assert that ALL printf routines will execute in the manner that THIS printf acts.

    The sequence

    push eax // push 100 on to stack push ebx // push 45 on to stack push message1 // push THE ADDRESS OF the message "value=%d" onto stack call printf // push the RETURN ADDRESS to the stack

    enters the printf routine with, reading the stack from the BOTTOM

    1. The return address
    2. A Pointer to the message
    3. Some parameter values

    So, PRINTF would most likely

    1. POP the return address and save it
    2. POP the pointer to the message
    3. MOVe the STACK POINTER to a register or save it

    Then it can go about its task - using the pointer to the message, write each character out until it encounters a keystring like %d which says 'print something as a decimal. So it POPs the next value from the stack (45, as pushed in ebx), formats that as a decimal and prints it, then continues with the printf string.

    Another %d - the 100 pushed from eax, then continue - until you find the 0 byte indicating end-of-string.

    All printf needs to do now to return is to restore the stack pointer from wherever it was stored, and return to the return address - wherever that's been stored.

    And when it returns, the stack is restored to exactly what it was when the printf was called - and at that time, EBX and EAX had been PUSHed. Each is 4 bytes, so the stack pointer needs to be adjusted by 8 bytes to remove the data stored by these two PUSH instructions.

    So - why do it that way - why not simply allw PRINTF to adjust the stack - which it could, since it knows it's removed 8 bytes for display (2*%d)?

    Well, in essence, it could - but suppose the message only contained one %d - or 3 - or something that consumed something OTHER than 8 bytes? On return, the stack-pointer would contain an unexpected value - which depends on how PRINTF interprets a string. Very difficult to pull assembler tricks like overwriting parts of messages withou being extraordinarily careful. As it's written, the printf function always acts in a predictable manner, returning having popped off the message address, regardless of any other consideration. Up to the programmer to properly deal with the stack contents.

    0 讨论(0)
提交回复
热议问题