I will be thankful for finding mistakes in my code. I was supposed to write a function that takes an address to a buffer, the letter l, the number n and the increase variable that can take only 2 values: 0 and 1. If the increase variable is 0, the function is supposed to repeat the same letter n times. If the increase variable is 1, the function should return a string of subsequent letters, for example "abcd...." (subsequent ascii characters). The letter l determines which letter we start with the string.
I tried using ddd, it tells me that the problem is with the line MOVL %ecx, (%edx) And I know that there is a wrong value in the register edx and ecx. Still, I cannot understand what is wrong and how to correct it. I will be very thankful for help.
#include <stdio.h>
#include <stdlib.h>
extern char * generate_str(char * s, int c, int n, int inc);
int main()
{
char s[100] = "something";
char c = 'a';
int n = 5;
int inc = 0;
printf("String %s\n", generate_str(s, (int)c, n, inc));
}
Assembly code:
.data
character: .int 0
# char -> 1
# int -> 4
# arguments: char * s, int c, int n, int inc
.equ bufor,8
.equ c,12
.equ n,16
.equ inc,20
#eax, ebx, ecx, edx
.text
.type generate_str, @function
.global generate_str
generate_str:
PUSHL %ebp #prolog of the function
MOVL %esp, %ebp
MOVL inc(%esp), %eax #copy variable inc into eax
MOVL n(%esp), %ebx #copy variable n into ebx
PUSHL %ecx #save contents of ecx
MOVL c(%esp), %ecx #copy variable c into ecx temporarily
MOVL %ecx, character #copy variable c into reserved memory called character
POPL %ecx #restore contents of c
MOVL bufor(%esp), %edx #copy addres of a buffer into edx
CMP $0, %eax # eax > 0 ? #is inc variable 0 or 1
JA one #if it is 1, go to line "one"
MOVL %ebx, %ecx %copy value of variable n into ecx, it tells how many letters should be placed in the buffer
p:
PUSHL %ecx #save contents of ecx
MOVL character, %ecx #copy character into ecx
MOVL %ecx, (%edx) #copy character into the place in the memory which address is given in edx
POPL %ecx #restore contents of ecx
ADDL $4, %edx #increase value of edx by 4, so we move forwards in the memory to save another letter there
loop p #loop until ecx is 0
jmp end #jump to the final part of the function
one: #if the value of inc is 1 then do another loop
PUSHL %ecx #save ecx and use this register to copy character into the place in memory which address is in the edx registry
MOVL character, %ecx
MOVL %ecx, (%edx)
POPL %ecx
ADDL $1, character #increase ascii character by 1
ADDL $4, %edx #move in memory by 4 bytes so we can save the next letter
loop one #continue loop until ecx is zero
jmp end
end:
MOVL %edx, %eax #copy address of the final string into eax
movl %ebp,%esp #restore registers
popl %ebp
RET