0

I have a problem with calling a function, which uses stack. The output of the program contains a lot of trash, it's like length of the string is wrong:

.code32

.equ kernel, 0x80
.equ stdout, 0x01
.equ write, 0x04
.equ exit, 0x01

.section .data
sum:
    .ascii "text"
.equ lensum, . - sum

.section .text

    .type writetxt, @function
writetxt:
    movl $write, %eax
    movl $stdout, %ebx
    popl %ecx
    pop %edx
    int kernel
    ret

.global _start

_start:
    pushl $lensum
    pushl $sum
    call writetxt

    movl $exit, %eax
    movl $0, %ebx
    int $kernel

I know that it is something with the function return address residing on stack, but i have no clue how to fix it

1 Answer 1

1

As you've noted yourself, the return address will be at the top of the stack (i.e. at (%esp)) as you enter writetxt. The last 32-bit value you pushed before the call will be at 4(%esp), and so on.

So instead of

popl %ecx
popl %edx

you should use something like

movl 4(%esp), %ecx
movl 8(%esp), %edx

Don't forget to adjust the stack pointer afterwards. For example, you could place an addl $8, %esp after the call writetext instruction.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.