0

I'm trying to copy array A to array B. Here's my cpp file.

#include <stdio.h>

using namespace std;

void copy(int * to, int * from, unsigned int n); //_Z6copyPiS_j

int main(){
  int * a = new int [4];
  int * b = new int [4];
  for (int i=0;i<4;++i)
  {
    a[i] = i+1;
  }
  kopiuj(b,a,4);
  for (int i=0;i<4;++i)
  {
    printf("%d - ", b[i]);
  }
  delete(a);
  delete(b);
  return 0;
}

and here is my asm file with copy function implementation

BITS 64
section .text

global _Z6kopiujPiS_j

_Z6kopiujPiS_j:                  

push rbp
mov rbp, rsp
cld
mov edi,  dword [rbp+8] ; destination
mov esi,  dword [rbp+12] ; source
mov ecx,  dword [rbp+16] ; size

rep movsd; repeat ecx times


mov rsp, rbp
pop rbp
ret                    

here is how I compile it. Unfortunately it has to be 64 bit.(exercise requirement)

// nasm -felf64 82.asm -o 82.o
// g++ -m64 -o 82m.o -c 82m.cpp
// g++ -m64 82m.o 82.o -o 82

and at rep movsd I get segmentation fault. What I'm doing wrong ?

Aleksander Monk
  • 2,787
  • 2
  • 18
  • 31
  • 64bit == pointers are 8 bytes: Why ebp+8/12/16..those are 4 apart? And what calling convention passes the first 3 args via the stack? – ABuckau May 14 '16 at 17:15

1 Answers1

3

You seem to be assuming the parameters are passed on the stack. The common calling conventions for x64 use registers for the first few parameters. See Why does Windows64 use a different calling convention from all other OSes on x86-64?. (Or look at the generated assembly for the call to see how the parameters are passed.)

Community
  • 1
  • 1
Alan Stokes
  • 18,815
  • 3
  • 45
  • 64
  • Thank you, that was my fault. First I wrote program for 32 bits and then tried to convert it to 64 and completely forgot about convention. – Aleksander Monk May 14 '16 at 17:27