Master AN HA
Master AN HA

Reputation: 71

Kernel Module Programming

I'm trying to read and write to a proc file through kernel module
But when I run this command :

echo "hello" >> /proc/hello && cat /proc/hello

It doesn't print anything and when i open the file through text editor. I found mysterious symbols like this

 ^@^@^@^@^@^@^@^@^@^@ 

Any help will be appreciated thanks in advance

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/proc_fs.h>
#include<linux/sched.h>
#include <asm/uaccess.h>
#include <linux/slab.h>

int len,temp;
char *msg;

int read_proc(struct file *filp,char *buf,size_t count,loff_t *offp ){
    if(count>temp){count=temp;}
    temp=temp-count;
    copy_to_user(buf,msg, count);
    if(count==0)temp=len;
    return count;
}

int write_proc(struct file *filp,const char *buf,size_t count,loff_t *offp){
    copy_from_user(msg,buf,count);
    len=count;
    temp=len;
    return count;
}

struct file_operations proc_fops = {
    read: read_proc,
    write: write_proc
};

void create_new_proc_entry(void){
    proc_create("hello",0,NULL,&proc_fops);
    msg=kmalloc(GFP_KERNEL,10*sizeof(char));
}

int proc_init (void){
    create_new_proc_entry();
    return 0;
}

void proc_cleanup(void){
    remove_proc_entry("hello",NULL);
}

MODULE_LICENSE("GPL"); 
module_init(proc_init);
module_exit(proc_cleanup);

Upvotes: 7

Views: 397

Answers (2)

wack
wack

Reputation: 71

You can find kmalloc in slab.h:

static __always_inline void *kmalloc(size_t size, gfp_t flags)
{
    if (__builtin_constant_p(size)) {
        if (size > KMALLOC_MAX_CACHE_SIZE)
            return kmalloc_large(size, flags);
    #ifndef CONFIG_SLOB
        if (!(flags & GFP_DMA)) {
            int index = kmalloc_index(size);

            if (!index)
                return ZERO_SIZE_PTR;

            return kmem_cache_alloc_trace(kmalloc_caches[index],
                    flags, size);
        }
    #endif
    }
    return __kmalloc(size, flags);
}

Upvotes: 0

LPs
LPs

Reputation: 16213

Apart from other problems of your kernel module (like boundaries check)

This

msg=kmalloc(GFP_KERNEL,10*sizeof(char));

have to be

 msg=kmalloc(10*sizeof(char), GFP_KERNEL);

With your call to kmalloc you are trying, probably, to allocate too many or not enough bytes and it refuses your kmalloc request.

You should always check the kmalloc return value to be consistent: != NULL

Upvotes: 4

Related Questions