简体   繁体   English

C库如何调用内核系统调用

[英]How does a C library call kernel system calls

I know in Unix-like systems c librarys such as glibc acts as an intermediary between the kernel and the userland. 我知道在类似Unix的系统中,诸如glibc之类的c库充当内核和用户域之间的中介。 So for example when implementing malloc() how does glibc invoke system calls of the linux kernel does it use assembly? 因此,例如,在实现malloc() ,glibc如何调用Linux内核的系统调用,是否使用汇编语言?

In Linux x86 syscalls (system calls) are made by calling interrupt 0x80 . 在Linux x86中,系统调用(系统调用)是通过调用中断0x80 In assembly it is done with: 在组装中,它是通过以下方式完成的:

int $0x80

The choice of syscall is done by passing information to the CPU registers. syscall的选择是通过将信息传递到CPU寄存器来完成的。 malloc itself is not a syscall, but malloc algorithm usually uses sbrk or mmap syscalls ( brk syscall for sbrk ). malloc本身不是syscall,但是malloc算法通常使用sbrkmmap syscall( sbrk brk syscall)。

For more information on Linux x86 syscalls, you can read this document . 有关Linux x86系统调用的更多信息,您可以阅读本文档

EDIT: as mentioned by Jester in the comments, Intel x86 processors (after Pentium IV) now support systenter / sysexit instructions that don't have the int overhead and on these processors these instructions are used by Linux for syscalls. 编辑:正如Jester在评论中提到的那样,Intel x86处理器(在Pentium IV之后)现在支持没有int开销的systenter / sysexit指令,并且在这些处理器上,Linux将这些指令用于系统调用。

Example of calling exit(0) syscall on 0x86 architecture. 在0x86体系结构上调用exit(0)syscall的示例。

movl $1, %eax   #$1=number of exit syscall. 
movl $0, %ebx   #$0=First argument of exit syscall
int 0x80        #call the software interrupt

Every syscall has been given a number that can be found in /usr/include/asm/unistd.h. 每个系统调用都有一个编号,该编号可以在/usr/include/asm/unistd.h中找到。 In the above example exit syscall has number 1. Then you set the argument required for the syscall. 在以上示例中,出口syscall的编号为1。然后,设置syscall所需的参数。 After that you call software interrupt int 0x80. 之后,您调用软件中断int 0x80。

So for malloc, it will internally call brk or mmap and then it will set the required arguments and then will call int0x80. 因此,对于malloc,它将在内部调用brk或mmap,然后将设置所需的参数,然后将调用int0x80。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM