Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assembly- preserving register values?

I am having some trouble with, what I believe to be, using printf inside of a function that I have created in assembly. The function I made is:

printnstars:
    movl $0, %edi
    movl 4(%esp), %ebx

starloop:
    cmpl %ebx, %edi
    je exitloop
    incl %edi
    pushl $star
    call printf
    addl $4, %esp
    jmp starloop

exitloop:
    ret

The function takes in a number as a parameter, which I moved to %ebx, and prints that number of "*"s using:

star:
    .asciz "*"

The function does what it is supposed to do, but I run into problems when I try to do something like this:

    pushl (%ecx)
    call printnstars
    pushl (%ecx)
    call printnstars

Where (%ecx) is 2. If I only do one call, it behaves as expected and prints 2 stars, but when I call it again it prints infinite stars. It's quite obvious that %ecx must have gotten messed with inside of printf because I didn't use that register in anything I created. What do I do to make sure that (%ecx) will remain constant through multiple calls to printnstars?

Also it may be useful to note that this is used inside of a function that is printing a histogram with stars on each line referring to the number of time a number occurs. I have all of the frequency values based around %ecx, so that is why I am using (%ecx).

like image 662
zProgrammer Avatar asked Dec 17 '25 18:12

zProgrammer


1 Answers

What do I do to make sure that (%ecx) will remain constant through multiple calls to printnstars?

You save the register value in a local variable on the stack.

Also, remember that printf() takes a variable number of parameters and since it doesn't know beforehand how many of them there are and of what type, it doesn't remove the on-stack parameters and removing them from the stack (by adjusting esp) becomes the caller's responsibility.

like image 155
Alexey Frunze Avatar answered Dec 20 '25 14:12

Alexey Frunze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!