String copy in Assembly

1.5k Views Asked by At

I've got a problems with copying string to empty array in Assembly.

Firstly, I get some junks instead string which i would like to copy.

Secondly, the program should work with string up to 100 chars but when I declare an array with 100 chars, I got "*** stack smashing detected ***" after compile using gcc.

#include<stdio.h>
void main() {
    char *s="aac";
    char t[4];
    asm volatile ( 
        ".intel_syntax noprefix;" 
        "mov eax, %0;"
        "push eax;" 
        "mov eax, %1;"
        "push eax;" 
        "call printing;"
        "jmp end;"
        "printing:"
        "push ebp;" 
        "mov ebp,esp;" 
        "push eax;"
        "push ebx;" 
        "push ecx;"
        "push edx;" 

        "mov ebx,[ebp+12];"
        "mov eax,[ebp+8];"

        "mov ecx,eax;"

        "copying:"
        "mov dl,[ebx];"
        "mov [eax],dl;"
        "inc ebx;"
        "inc eax;"
        "cmp dl,0;"
        "jnz copying;"

        "xor edx,edx;"

        "mov eax,4;"
        "mov ebx,1;"

        "mov edx,3;"
        "int 0x80;"
        "pop edx;"
        "pop ecx;"
        "pop ebx;"
        "pop eax;"
        "pop ebp;"
        "ret 4;"

        "end:"

        ".att_syntax prefix;"
    :
    :"r" (s), "r" (t)
    :"eax"
    );

printf("\n");

}

I'm newbie in Assembly so please help me.

Thank you in advance

1

There are 1 best solutions below

7
On BEST ANSWER

I see four problems with your code:

  • You are using the register al as buffer for transferring characters, while at the same time, you are using eax as source pointer. al is just a name for the lowest eight bits of eax so you are clobbering your source pointer. You might want to use edx instead. Clobbering the source pointer results in indeterminate copying lengths and can likely overflow your destination buffer on the stack, which will cause the stack smashing error.
  • The destination buffer on the stack is too small. You are trying to copy 3 characters and the NUL byte, which needs four bytes in the destination buffer.
  • You are passing the value of eax after the loop to the write syscall. This points past the copy destination, as you increased eax during the loop. If you copy eax to ecx before the copy loop, that problem is fixed.
  • finally, you copy three non-NUL characters, but print only two.