elks icon indicating copy to clipboard operation
elks copied to clipboard

Question on return code on create in socket.c

Open djohanse opened this issue 1 year ago • 2 comments

Hi Greg,

let me qualify my question by saying I have some knowledge and a lot of interest in networking code.

That being said, I've been working through the elks networking code trying to understand it from the bottom up. Something caught my attention that seems unusual.

In elks/elks/net/socket.c, lines 528-532:

if ((fd = sock->ops->create(sock, protocol)) < 0) { sock_release(sock); return fd; }

Why is the fd returned if the socket is released? Usually a return code of less than 0 indicates an error? I would have expected this to return an error code?

djohanse avatar Jan 19 '24 08:01 djohanse

I think I figured it out. I'm guessing its because you want the specific error return code from the call to create?

djohanse avatar Jan 19 '24 09:01 djohanse

I'm guessing its because you want the specific error return code from the call to create?

Yes. In the kernel, errors are returned as negative error numbers:

if (!suser())
    return -EPERM;

Then, in the C library, a negative number returned by the kernel is changed to a -1 C function return with the error number stored in errno in the libc/system/syscall code:

    .global _syscall
_syscall:
    int    $0x80
    test   %ax,%ax
    jns    _syscall_ok
    neg    %ax
    mov    %ax,errno
    mov    $-1,%ax
_syscall_ok:
    ret

I've been working through the elks networking code trying to understand it

Most of the interesting networking code is in the relatively well-written elkscmd/ktcp/ application, which implements TCP/IP as a usermode application. The kernel implementation is harder to follow, and its main purpose is redirecting and synchronizing socket I/O to and from the ktcp application.

ghaerr avatar Jan 19 '24 15:01 ghaerr