http://blog.chinaunix.net/uid-22359610-id-461249.html
一、socket()库函数到系统调用,再到内核
1、Linux运行的C库是glibc;
2、socket()调用如下:
1) socket()->__socket():glibc-2.3.6/sysdept/generic/socket.c (weak_alias(name1, name2))
2) __socket():glibc-2.3.6/sysdept/unix/sysv/linux/i386/socket.S
3) ENTER_KERNEL:
-
movl $SYS_ify(socketcall), %eax /* System call number in %eax. */
-
-
/* Use ## so `socket' is a separate token that might be #define'd. */
-
movl $P(SOCKOP_,socket), %ebx /* Subcode is first arg to syscall. */
-
lea 4(%esp), %ecx /* Address of args is 2nd arg. */
-
-
/* Do the system call trap. */
-
ENTER_KERNEL
这里,
SYS_ify宏定义为:glibc-2.3.6/sysdept/unix/sysv/linux/i386/Sysdept.h
-
#define SYS_ify(syscall_name) __NR_##syscall_name;
P宏定义为:glibc-2.3.6/sysdept/unix/sysv/linux/i386/socket.S
-
#define P(a, b) P2(a, b)
-
#define P2(a, b) a##b
其中,##为连接符号;
-
#define __NR_socketcall 102
-
SOCKOP_socket:glibc-2.3.6/sysdept/unix/sysv/linux/Socketcall.h
-
-
#define SOCKOP_socket 1
因此,中断号是102,子中断号是1;
4) int 0x80进入内核:glibc-2.3.6/sysdept/unix/sysv/linux/i386/Sysdept.h:
-
# define ENTER_KERNEL int $0x80
5) system_call中断入口:kernel/arch/x86/kernel/entry_32.S:
-
syscall_call:
-
call *sys_call_table(,%eax,4)
6) 进入中断向量表:kernel/arch/x86/kernel/syscall_table_32.S中的102号中断:
7) 进入sys_socketcall()函数,根据子中断号以决定走哪个分支:kernel/net/Socket.c:
-
switch (call) {
-
case SYS_SOCKET:
-
break;
-
case SYS_BIND:
-
…...
二、socket其他库函数(bind, accept...)
1、对于其他库函数,都是引用上面提到的glibc-2.3.6/sysdept/unix/sysv/linux/i386/socket.S来实现的,如
a) bind.S:
-
#define socket bind
-
#define NARGS 3
-
#define NO_WEAK_ALIAS 1
-
#include <socket.S>
-
weak_alias (bind, __bind)
b) accept.S:
-
#define socket accept
-
#define __socket __libc_accept
-
#define NARGS 3
-
#define NEED_CANCELLATION
-
#include <socket.S>
-
libc_hidden_def (accept)
在各个库函数调用中,设置不同的参数,如socket(用于设置子中断号), NARGS(系统调用的参数个数)等,最终由
-
movl $P(SOCKOP_,socket), %ebx /* Subcode is first arg to syscall. */
来生成最终的子中断号,然后放到ebx寄存器中;
2、所有socket系统调用的子中断号参见glibc-2.3.6/sysdept/unix/sysv/linux/Socketcall.h:
-
#define SOCKOP_socket 1
-
#define SOCKOP_bind 2
-
#define SOCKOP_connect 3
-
#define SOCKOP_listen 4
-
#define SOCKOP_accept 5
-
#define SOCKOP_getsockname 6
-
#define SOCKOP_getpeername 7
-
#define SOCKOP_socketpair 8
-
#define SOCKOP_send 9
-
#define SOCKOP_recv 10
-
#define SOCKOP_sendto 11
-
#define SOCKOP_recvfrom 12
-
#define SOCKOP_shutdown 13
-
#define SOCKOP_setsockopt 14
-
#define SOCKOP_getsockopt 15
-
#define SOCKOP_sendmsg 16
-
#define SOCKOP_recvmsg 17
阅读(2028) | 评论(0) | 转发(1) |