1

i want to call mmap syscall. In C code this was success, but from asm i have returned -9(bad file descritor) returned value after syscall instruction.

  1. Where is the mistake?
  2. Do I understand correctly that if after the system call instruction in the register eax the number is less than zero, then it can be converted to errno, and if more, then this is the returned address?

asm code:

   .text
   .globl _start

   .set PROT_READ,          0x1
   .set PROT_WRITE,     0x2
   .set MAP_PRIVATE,        0x2
   .set MAP_ANONYMOUS,     0x20

   _start:
    pushq   %rbp
    movq    %rsp, %rbp

    movl     $PROT_READ, %ecx        # PROT_READ
    orl      $PROT_WRITE, %ecx       # PROT_WRITE
    movl     $MAP_PRIVATE, %r9d      # MAP_PRIVATE
    orl      $MAP_ANONYMOUS, %r9d    # MAP_ANONYMOUS

    movl    $9, %eax
    movq    $0, %rdi
    movq    $24, %rsi
    movl    %ecx, %edx
    movl    %r9d, %ecx
    movl    $-1, %r8d
    movl    $0, %r9d
    syscall

    mov %rax, %rbx 
    movl $1, (%rbx) # store value

    popq    %rbp
    retq

C code:

 #define MAP_ANONYMOUS 0x20
 int a = PROT_READ | PROT_WRITE;         // result 3
 int b = MAP_PRIVATE | MAP_ANONYMOUS;    // result 34
 void *ptr = mmap (NULL, 7, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
fuz
  • 88,405
  • 25
  • 200
  • 352
xperious
  • 239
  • 3
  • 10
  • Your code does not link as is. Please check the syntax. You have `$ecx` instead of `%ecx` and `$r9d` instead of `%r9d`. – fuz Jan 03 '22 at 09:52
  • @fuz done, bad copy – xperious Jan 03 '22 at 09:58
  • 2
    You are placing the arguments into wrong registers. Refer to [this answer](https://stackoverflow.com/a/2538212/417501) for the correct registers. After fixing the arguments to go into the right registers, your system call succeeds. The code however crashes later when you attempt to return from `_start` when there is nothing to return to. – fuz Jan 03 '22 at 09:59
  • @fuz thanks about registers for syscall... i did't know it – xperious Jan 03 '22 at 10:03
  • @fuz why close question? Answer the question 2 pls – xperious Jan 03 '22 at 10:14
  • 1
    Question 2 is answered by the duplicate as well. “Returning from the syscall, register %rax contains the result of the system-call. A value in the range between -4095 and -1 indicates an error, it is -errno.” – fuz Jan 03 '22 at 10:16

0 Answers0