How does the compiler know that the function you are using is a system call?

For the next code snippet

int n;
char buf[100];
int fd = open ("/etc/passwd", O_RDONLY);
n = read ( fd, buf, 100);

How does the compiler know that reading is a system call, not some library function?

How does he get the system call number ( __NR_read)?

+5
source share
5 answers

open () is a library function located in libc.a / libc.so

+1
source

I very much doubt that the compiler knows that this is a system call. Most likely, something openis located in the library somewhere, and the code inside the library calls the corresponding kernel interface.

The assembly output from a simple program:

#include <stdio.h>
int main (void) {
    int fd = open("xyz");
    return 0;
}

(unnecessary bits are deleted):

main:
    pushl   %ebp            ; stack frame setup.
    movl    %esp, %ebp
    andl    $-16, %esp
    subl    $32, %esp

    movl    $.LC0, (%esp)   ; Store file name address.
    call    open            ; call the library function.
    movl    %eax, 28(%esp)  ; save returned file descriptor.

    movl    $0, %eax        ; return 0 error code.

    leave                   ; stack frame teardown.
    ret

.LC0:
    .string "xyz"           ; file name to open.

, , open. , . int 80 sysenter, , ( - YMMV).

libc - , .

:

, , , C (libc), glibc. .

, , . API .

" " "syscall" C, , . ( ) (.. CALL ISA). ( , ). , fork execve GLIBC, fork execve.

__open glibc 2.9 io/open.c weakref 'ed open. :

nm /usr/lib/libc.a | egrep 'W __open$|W open$'

:

00000000 W __open
00000000 W open
+13

read - . , libc .

+6

, .

gcc -S, - :

movl    $100, %edx
movq    %rcx, %rsi
movl    %eax, %edi
call    read

C (2).

EDIT: , GNU libc (, , Linux), glibc-2.12.1/sysdeps/syscalls.list. ( sysdeps/unix/syscall-template.S), libc.

+2

Android ( Android libc)

/* autogenerated by gensyscalls.py */
#include <sys/linux-syscalls.h>

    .text
    .type read, #function
    .globl read
    .align 4
    .fnstart

read:
    .save   {r4, r7}
    stmfd   sp!, {r4, r7}
    ldr     r7, =__NR_read
    swi     #0
    ldmfd   sp!, {r4, r7}
    movs    r0, r0
    bxpl    lr
    b       __set_syscall_errno
    .fnend

, __NR_read r7, SWI, SWI - , . , , libc .

+1

All Articles