How can I copy the data of buf in kernel space to the uio structhre in user space.

Jun Furukawa furukawa at
Mon Feb 1 08:12:11 UTC 2010

For my research, I am now hooking the function vn_write().

This is the part of the source code.

#include <sys/param.h>                /* module           */
#include <sys/module.h>               /* module           */
#include <sys/kernel.h>               /* module           */
#include <sys/types.h>                /* size_t, copystr  */
#include <sys/systm.h>                /* copystr */
#include <sys/proc.h>                 /* struct thread    */
#include <sys/file.h>                 /* vnops            */
#include <fs/msdosfs/msdosfs_vnops.c> /* msdosfs_vnodeops */

fo_write_hook(struct file *fp,
                struct uio *uio,
                struct ucred *active_cred,
                int flags,
                struct thread *td);

typedef int (*fow_t)(struct file*,
                struct uio*,
                struct ucred*,
                int flags,
                struct thread*);

fow_t old_fo_write;
static char mybuf[256+1];
static size_t len;

/* vn_write hook */
vn_write_hook(struct file *fp,
                struct uio *uio,
                struct ucred *active_cred,
                int flags,
                struct thread *td)
                int error;

                memset(&mybuf, '\0', 257);

                error = copyinstr(uio->uio_iov->iov_base, mybuf, 256, &len);

                if (error != 0) {
                        uprintf("Cannot write data to kernel space\n");

                /* encrypt the data by ceaser algorithm */
                for (int i = 0; i < len ; i++)
                        mybuf[i] += 3;

                error = copystr(&mybuf, uio->uio_iov->iov_base, 257, &len);

                if (error != 0) {
                        uprintf("Cannot write data to user space\n");

        return (old_vn_write(fp, uio, active_cred, flags, td));

This software is implemented as a kernel module.

After I installed this software and execute cp command, vn_write_hook 
function is executed.

However, when copystr(&mybuf, uio->uio_iov->iov_base, 257, &len) is 

kernel goes to panic.

I referenced /usr/share/examples/kld/cdev/module/cdev.c for writing the 
part of program

that copies buffer in kernel space to a buf in user space program. 
However, as we have seen,

this doesn't work appropriately.

How can I solve this problem?

Please give me your help.

--Jun Furukawa

More information about the freebsd-questions mailing list