2008年3月31日 星期一

核心進行開檔,讀檔與寫檔的程式作為範例

透過

oldfs=get_fs();

set_fs(KERNEL_DS);

把目前執行程式current可存取的記憶體範圍設定為4GB,這樣當Kernel-Mode的程式碼呼叫函式時,就可以存取目前在3-4GB記憶體範圍內核心程式碼所包含的參數. 在開檔動作之後,就可以透過filp->f_pos移動檔案指標,寫入檔案,與讀取檔案的動作,而且這些動作所帶入的參數都是位於核心所屬的記憶體範圍內(3GB-4GB).

REF:http://loda.zhupiter.com/LinuxProtectModeArch.htm

gcc -D__KERNEL__ -DMODULE -Wall -O2 -I/usr/include/linux -I/usr/src/linux/include -c kernel.c -o kernel.o
#include <linux/kernel.h>

#include <linux/module.h>

#include <linux/errno.h>

//

#include <asm/atomic.h>

#include <asm/processor.h>

#include <asm/uaccess.h>

#include <linux/file.h>

//

char buf[]="This is a kernel-mode file operation testing program";

char b_buf[128];

//

int init_module(void)

{

char filename[]="/linux.tmp";

struct file *filp;

int r;

mm_segment_t oldfs;

//

printk("\ninit_module\n\n");

//

oldfs=get_fs();

set_fs(KERNEL_DS);

filp=filp_open(filename,O_CREAT|O_RDWR,0777);

if(IS_ERR(filp))

{

printk("\nFile Open Error:%s\n",filename);

return 0;

}

if(!filp->f_op)

{

printk("\nFile Operation Method Error!!\n");

return 0;

}

//

printk("\nFile Offset Position:%xh\n",(unsigned)filp->f_pos);

r=filp->f_op->write(filp,buf,sizeof(buf),&filp->f_pos);

printk("\nWrite :%xh bytes Offset=%xh\n",r,(unsigned)filp->f_pos);

//

filp->f_pos=0x00;

r=filp->f_op->read(filp,b_buf,sizeof(b_buf),&filp->f_pos);

printk("\nRead %xh bytes %s\n",r,b_buf);

filp_close(filp,NULL);

set_fs(oldfs);

return 0;

}

//

void cleanup_module(void)

{

printk("\nclean_module\n\n");

}

沒有留言: