驅動原理(應用程序訪問驅動程序)

以read爲例:linux

  read是一個系統調用,系統調用以前在應用程序當中(或者叫用戶空間當中),read的實現代碼在內核中,read是如何找到內核的實現代碼呢?vim

/*********************************************
*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_memspa

  反彙編:arm-linux-objdump –D –S read_mem >dumpcode

  找到主函數:vim dump -> /main
blog

  

  找到libc_read函數get

     

  關注兩行代碼:it

  mov r7,#3io

  svc 0x00000000class

  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;
}
相關文章
相關標籤/搜索