Im trying to concatenate two given strings using inline assembly in C using the gcc compiler and intel syntax. I have been successfull to print the first string but not the second and I can't figure out why. Here is my code:
#include <stdio.h>
void my_strcat(char *str1, const char *str2) {
__asm__ volatile (
"mov %[str1], %%rax\n\t" // Move str1 pointer to rax register
"mov %[str2], %%rbx\n\t" // Move str2 pointer to rbx register
"1:\n\t" // Loop label
"cmpb $0, (%%rax)\n\t" // Compare the value at rax with 0
"jne 2f\n\t" // Jump to 2 if not equal (i.e., not end of str1)
"lodsb\n\t" // Load a byte from str2 to al and increment str2 pointer
"stosb\n\t" // Store a byte from al to str1 and increment str1 pointer
"testb %%al, %%al\n\t" // Test if al is 0
"jne 1b\n\t" // Jump to 1 if not equal (i.e., not end of str2)
"2:\n\t" // Loop label
"dec %%rax\n\t" // Decrement rax to undo the null terminator
"movb $0, (%%rax)\n\t" // Null terminate the concatenated string
: [str1] "+r" (str1), [str2] "+r" (str2) // Input/output operands
: // No input-only operands
: "rax", "rbx", "memory" // Clobbered registers and memory
);
}
int main() {
char str1[20] = "Hello";
char str2[20] = " world!";
my_strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
Any help would be appreciated !