get_ds, set_fs, get_fs函數的使用

來源:互聯網
上載者:User

在linux核心編程時,進行系統調用(如檔案操作)時如果要訪問使用者空間的參數,可以用set_fs,get_ds等函數實現訪問。get_ds獲得kernel的記憶體訪問位址範圍(IA32是4GB),set_fs是設定當前的地址訪問限制值,get_fs是取得當前的地址訪問限制值。進程由使用者態進入核態,linux進程的task_struct結構中的成員addr_limit也應該由0xBFFFFFFF變為0xFFFFFFFF(addr_limit規定了進程有使用者態核核心態情況下的虛擬位址空間存取範圍,在使用者態,addr_limit成員值是0xBFFFFFFF也就是有3GB的虛擬記憶體空間,在核心態,是0xFFFFFFFF,範圍擴充了1GB)。使用這三個函數是為了安全性。為了保證使用者態的地址所指向空間有效,函數會做一些檢查工作。

如果set_fs(KERNEL_DS),函數將跳過這些檢查。
下面是典型用法:

//#define __NO_VERSION__
//#define __KERNEL__
//#define MODULE
#define __KERNEL_SYSCALLS__
#include <linux/unistd.h>;
#include <linux/init.h>;
#include <linux/module.h>;
#include <linux/kernel.h>;
#include <linux/file.h>;
#include <linux/fs.h>;
#include <linux/sched.h>;
#include <asm/uaccess.h>;
#include <asm/processor.h>;

int init_module(void)
{
         struct file *fp = NULL;
         char buf[100];
         int i;

         for(i=0;i<100;i++)
                 buf[i] = 0;
         printk(KERN_ALERT "Hello ,ftyjl.\n");
         fp = filp_open("/tmp/8899", 3, 0);   //核心的open函數,返回struct file *
         if (fp == NULL)
                 printk(KERN_ALERT "filp_open error ,ftyjl.\n");
         mm_segment_t old_fs=get_fs(); //下面兩步,設定當前執行環境為kernel_ds,否則會出錯
         set_fs(get_ds());
         fp->f_op->read(fp, buf, 2, &fp->f_pos);   //調用真正的read
         set_fs(old_fs);   //恢複環境
         printk(KERN_ALERT "ftyjl:read[%s]\n", buf);

         printk(KERN_ALERT "end of Hello ,ftyjl.\n");
         return 0;
}
void cleanup_module(void)
{
         printk(KERN_ALERT "Good bye, ftyjl\n");
}

MODULE_LICENSE("Proprietary");

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.