Search

Module to display the current working directory


The following module, on insertion into the kernel, displays the current working directory in the kernel space . The code is same as what is used in the system call getcwd.

The current working directory is saved as the member, name, of the structure qstr, which in turn is a member, d_name, of the structure dentry. Both the structures are found in dacache.h.

The pointer to the dentry is stored as a member, dentry, of the structure path which is defined in the file path.h
The file fs_struct.h defines a structure by the name fs_struct which has members,path and root, of type struct path.

The current pointer is of the type struct task_struct, this structure is defined in sched.h and the structure has a member fs of the type fs_struct.

Hence to access the value of the current working directory we need to trace the path

fs->path->dentry->d_name->name


*************************current_pwd.c**********************************
#include <linux/init.h>
#include <linux/module.h>
#include<linux/sched.h>
#include <linux/rcupdate.h>
#include <linux/fdtable.h>
#include <linux/fs.h>
#include <linux/fs_struct.h>
#include <linux/dcache.h>


MODULE_LICENSE("Dual BSD/GPL");

static int current_init(void)
{

char *cwd;
        struct path pwd, root;
pwd = current->fs->pwd;
path_get(&pwd);
root= current->fs->root;
path_get(&root);
char *buf = (char *)kmalloc(GFP_KERNEL,100*sizeof(char));
cwd = d_path(&pwd,buf,100*sizeof(char));
printk(KERN_ALERT "Hello,the current working directory is \n %s",cwd);

return 0;
}

static void current_exit(void)
{

printk(KERN_ALERT "Goodbye cruel world");
}

module_init(current_init);
module_exit(current_exit);

***********************************************************************************


****************************Makefile*****************************
obj-m += current_pwd.o
all:
make -C /lib/modules/$(shell uname -r)/build  M=$(PWD) modules
clean:
make -C  /lib/modules/$(shell uname -r)/build  M=$(PWD) clean
**************************************************************

Run the followig commands to compile and load.

$ sudo make

If there are no errors after compiling in the above step, we can insert the module using

$ sudo insmod current_pwd.ko

To see the output

$ dmesg

At the end of the messages you should see your current working directory being printed .



No comments:

Post a Comment