以read為例:
read是一個系統調用,系統調用之前在應用程序當中(或者叫用戶空間當中),read的實現代碼在內核中,read是如何找到內核的實現代碼呢?
/********************************************* *filename:read_mem.c ********************************************/ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int main() { int fd = 0; int dst = 0; fd = open("/dev/memdev0",O_RDWR); read(fd, &dst, sizeof(int)); printf("dst is %d\n",dst); close(fd); return 0; }
這個應用程序就是打開字符設備文件,然后使用系統調用,去讀取里頭的數據,
用 arm-linux-gcc static –g read_mem.c –o read_mem
反匯編:arm-linux-objdump –D –S read_mem >dump
找到主函數:vim dump -> /main
找到libc_read函數
關注兩行代碼:
mov r7,#3
svc 0x00000000
read的系統調用在應用程序當中主要做了兩項工作,3傳給了r7,然后使用svc指令。
svc系統調用指令,系統會從用戶空間進入到內核空間,而且入口是固定的,3就是代表read要實現的代碼,根據3查表,查出3代表的函數,然后調用這個函數。
打開entry_common.S;找到其中的ENTRY(vector_swi)
在這個函數中得到調用標號
根據標號找到一個調用表
然后找到進入表
打開calls.S文件,會得到一張系統調用列表(部分圖示)
3代表的就是read;
分析sys_read,原函數在read_write.c文件中(/linux/kernel code/linux-2.6.39/fs)
SYSCALL_DEFINE3(read, unsigned int, fd, char __user *, buf, size_t, count) { struct file *file; ssize_t ret = -EBADF; int fput_needed; file = fget_light(fd, &fput_needed); if (file) { loff_t pos = file_pos_read(file); ret = vfs_read(file, buf, count, &pos); file_pos_write(file, pos); fput_light(file, fput_needed); } return ret; }
函數fd進去后,利用fd找到文件所對應的struct file,利用struct file調用vfs_read();
ssize_t vfs_read(struct file *file, char __user *buf, size_t count, loff_t *pos) { ssize_t ret; if (!(file->f_mode & FMODE_READ)) return -EBADF; if (!file->f_op || (!file->f_op->read && !file->f_op->aio_read)) return -EINVAL; if (unlikely(!access_ok(VERIFY_WRITE, buf, count))) return -EFAULT; ret = rw_verify_area(READ, file, pos, count); if (ret >= 0) { count = ret; if (file->f_op->read) ret = file->f_op->read(file, buf, count, pos); else ret = do_sync_read(file, buf, count, pos); if (ret > 0) { fsnotify_access(file); add_rchar(current, ret); } inc_syscr(current); } return ret; }