Maxime Crespo
Maxime Crespo

Reputation: 229

How to change errno value in asm x64

I write assembly for a school project and I'm stuck on a point, i need re rewrite Read in asm, so i got it, but i need to set the errno variable, then my read can return -1 in case of an error and set value of errno to 9 for example. And i don't found how to change this famous errno :( this is my actual code :

global my_write

section .text
my_write:
    mov rax, 1  ; sys_write
    syscall     ; call write
    cmp rax, 0
    jl error
    ret
error:
    mov rax, -1
    ret

ps : i found somewhere i need to use __error but i don't find any docs on this :(

thanks a lot :D

edit :

Thanks for you help guys ! __errno_location work i make this :

extern __ernno_location
global my_write

section .text
my_write:
    mov rax, 1  ; sys_write
    syscall     ; call write
    cmp rax, 0
    jl error
    ret
error:
    neg rax    ; get absolute value of syscall return
    mov rdi, rax
    call __ernno_location
    mov [rax], rdi  ; set the value of errno
    mov rax, -1
    ret

Upvotes: 3

Views: 2446

Answers (1)

Jester
Jester

Reputation: 58782

That's tricky business. You need to look up the definition of errno in your system. It may be going through a helper function like

/* Function to get address of global `errno' variable.  */
extern int *__errno_location (void) __THROW __attribute__ ((__const__));
/* When using threads, errno is a per-thread value.  */
#   define errno (*__errno_location ())

So you can call that function from your assembly and then set the value through the returned pointer. More portable way would be to write a helper function in C, say:

#include <errno.h>
void set_errno(int value)
{
    errno = value;
}

which would take care of the platform dependent stuff.

Upvotes: 7

Related Questions