0

I'm trying to copy data from one array to another using inline assembly in C by using the rep movsd, my code currently looks like this:

#include<stdio.h>

int main(){
  int v1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  int v2[10];

  asm ("mov %edi, v2\n"
    "mov %esi, v1\n"
    "mov %ecx, 40\n"
    "rep movsd"
  );

  for(int i=0;i<10;i++){
    printf("%d ", v2[i]);
  }

  printf("\n");
  return 0;
}

But I keep getting an error saying that I can't use v2 and v1 in the following way:

Undefined symbol "v2" can't be used to  make a PIE object

I couldn't find the correct syntax to add C pointers to the inline assembly.

I'm using the following version of gcc:

gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Bruno Mello
  • 4,448
  • 1
  • 9
  • 39
  • Is it allowed to use [Extended Asm](https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html)? – MikeCAT Mar 23 '21 at 14:37
  • 1
    You want extended inline asm. But you should really answer first, why you want assembly. – Jester Mar 23 '21 at 14:37
  • Yes, it is allowed @MikeCAT – Bruno Mello Mar 23 '21 at 14:38
  • 2
    @Jester, I don't really want to use it. I have a professor that said that C had this feature and we should try running an inline assembly to copy data from one array to another. I personally think it is useless but I'm trying to figure it out how to do it – Bruno Mello Mar 23 '21 at 14:40
  • 1
    There's a lot of general info at https://stackoverflow.com/tags/inline-assembly/info. Be warned that doing this correctly involves quite a bit more than just dumping instructions inside `asm("...")`. You have to really cooperate with the compiler to get the data you need from it, and inform it what registers and machine state you are changing. – Nate Eldredge Mar 23 '21 at 14:43
  • `rep movsD` with ECX=40 would copy 40 dwords (40 ints). Looks like you want 40 bytes. The linked duplicates are using `rep movsb` (which is just as fast on modern CPUs), but takes its count in bytes, i.e. `sizeof(v2)`. You can adapt that if you want, `sizeof(v2)/4`. (Normally you'd do `sizeof(v2)/sizeof(v2[0])`, but you *do* specifically want size/4, regardless of sizeof(int), if you're using `movsd`) – Peter Cordes Mar 23 '21 at 14:47
  • @BrunoMello Then you want *extended asm* as MikeCAT mentioned. Read the manual very carefully. It is quite hard to get inline assembly right and if you make mistakes, you may not find out until your program gets complex and the compiler attempts to make use of one of the assumptions your code violates. – fuz Mar 23 '21 at 16:07

0 Answers0