title: mmap system call returning -14(-EFAULT??)
body: <p>I am implementing mmap function using system call.(I am implementing mmap manually because of some reasons.)</p>
  
  <p>But I am getting return value -14 (-EFAULT, I checked with GDB) whith this message:</p>
  
  <pre><code>WARN  Nar::Mmap: Memory allocation failed.
  </code></pre>
  
  <p>Here is function:</p>
  
  <pre><code>void *Mmap(void *Address, size_t Length, int Prot, int Flags, int Fd, off_t Offset) {
      MmapArgument ma;
      ma.Address = (unsigned long)Address;
      ma.Length = (unsigned long)Length;
      ma.Prot = (unsigned long)Prot;
      ma.Flags = (unsigned long)Flags;
      ma.Fd = (unsigned long)Fd;
      ma.Offset = (unsigned long)Offset;
      void *ptr = (void *)CallSystem(SysMmap, (uint64_t)&amp;ma, Unused, Unused, Unused, Unused);
      int errCode = (int)ptr;
      if(errCode &lt; 0) {
          Print("WARN  Nar::Mmap: Memory allocation failed.\n");
          return NULL;
      }
      return ptr;
  }
  </code></pre>
  
  <p>I wrote a macro(To use like malloc() function):</p>
  
  <pre><code>#define Malloc(x) Mmap(0, x, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
  </code></pre>
  
  <p>and I used like this:</p>
  
  <pre><code>Malloc(45);
  </code></pre>
  
  <p>I looked at man page. I couldn't find about EFAULT on mmap man page, but I found something about EFAULT on mmap2 man page.</p>
  
  <blockquote>
    <p>EFAULT Problem with getting the data from user space.</p>
  </blockquote>
  
  <p>I think this means something is wrong with passing struct to system call.
  But I believe nothing is wrong with my struct:</p>
  
  <pre><code>struct MmapArgument {
      unsigned long Address;
      unsigned long Length;
      unsigned long Prot;
      unsigned long Flags;
      unsigned long Fd;
      unsigned long Offset;
  };
  </code></pre>
  
  <p>Maybe something is wrong with handing result value?
  Openning a file (which doesn't exist) with CallSystem gave me -2(-ENOENT), which is correct.</p>
  
  <p>EDIT: Full source of CallSystem. open, write, close works, but mmap(or old_mmap) not works.
  All of the arguments were passed well.</p>
  
  <pre><code>section     .text
  
  global CallSystem
  CallSystem:
      mov rax, rdi        ;RAX
      mov rbx, rsi        ;RBX
  
      mov r10, rdx
      mov r11, rcx
      mov rcx, r10        ;RCX
      mov rdx, r11        ;RDX
  
      mov rsi, r8     ;RSI
      mov rdi, r9     ;RDI
  
      int 0x80
      mov rdx, 0  ;Upper 64bit
      ret                 ;Return
  </code></pre>