1

I would like to know if anybody has a solution to my problem. I'm doing a project for school. This project is about creating a function (only in NASM) that uses a syscall (I have to create ft_read which reproduces the behaviour of the real read system call).

Here is the situation :

When everything is okay (FD, buff, count), my function works properly.

BUT I don't know how to check if the syscall was successful or if it failed.

For example : When I use a fake fd (-1 for example), the syscall read returns 9 in rax. I understood that 9 is the error code for the variable Errno.

The problem is that I don't know how to differentiate the error code for errno from the return value of read (red of 9 char from the file).

If anybody has an idea on how to do I would be glad to know !

Here is my code at the moment :

extern  ___error
SYS_READ_MAC equ 0x2000003
SYS_READ_LINUX equ 3
section .text
    global _ft_read
_ft_read:
    cmp rdi, 0
    jl _error
    cmp rsi, 0
    je _error
    cmp rdx, 0
    jl _error
    mov rax, SYS_READ_MAC
    syscall
    cmp rax, 0
    jl _error
    ret
_error:
    mov r10, rax
    call ___error
    mov qword [rax], r10
    mov rax, -1
    ret

Sorry if my english isn't perfect, i'm not a native english speaker.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • It doesn't even assemble: file.asm:15: error: parser: instruction expected (I changed `cmpq` to `cmp`) – JCWasmx86 Jul 15 '20 at 15:00
  • Yes, sorry. I didn't realized I shared my modificated file (I tested some stuff because I saw on the internet that cmpq could be a solution, but I don't success to make it work) – Alexandre de Temmerman Jul 16 '20 at 07:36

1 Answers1

0

I found my answer :

I didn't realized it, and I don't know exactly why, but I was set on unsigned mode. So I can't see if rax contains a negative value.

In unsigned mode, the carry flag (CF) is set at 1 if the last operation (or the last syscall ?) failed.

So the solution was to do : JC _error (jump to error if carry flag is set on 1).

My code now :

extern  ___error
SYS_READ_MAC equ 0x2000003
SYS_READ_LINUX equ 3
section .text
    global _ft_read
_ft_read:
    mov rax, SYS_READ_MAC
    syscall
    jc _error
    ret
_error:
    mov r10, rax
    call ___error
    mov qword [rax], r10
    mov rax, -1
    ret
  • I don't know why am I in unsigned mode. I compile with the command : nasm -f macho64 -o If anyone has an answer I'd be glad to know. I'll clode the subject in two days since I've found the answer to my primary question. – Alexandre de Temmerman Jul 16 '20 at 09:50
  • 2
    **Only MacOS sets CF as an error indication**. Linux returns errors in-band, by returning RAX = -4095 .. -1. i.e. as an unsigned compare, `cmp rax, -4095` / `jae` as used by glibc: [What are the return values of system calls in Assembly?](https://stackoverflow.com/q/38751614) – Peter Cordes Jul 18 '20 at 20:48