[RFC]Something wrong with my module

Jonathan Neuschäfer j.neuschaefer at gmx.net
Thu Apr 12 10:33:55 EDT 2012


On Thu, Apr 12, 2012 at 09:52:02PM +0800, harryxiyou wrote:
> On Thu, Apr 12, 2012 at 9:03 PM, Jonathan Neuschäfer
> <j.neuschaefer at gmx.net> wrote:
> 
> Hi Jonathan,
> 
> > On Thu, Apr 12, 2012 at 06:16:56PM +0800, harryxiyou wrote:
> >> Hi greg,
> >>
> ...
> >>
> >> hw2.c
> >>
> >> #include <linux/module.h>
> >> #include <linux/kernel.h>
> >> #include <linux/init.h>
> >> #include <linux/sched.h>
> >> #include <linux/list.h>
> >> #include <linux/slab.h>
> >>
> >> struct pcb {
> >>       int pid;
> >>       int state;
> >>       int flag;
> >>       char *comm;
> >>       struct list_head tasks;
> >> };
[...]

(from print_pid:)
> >>       struct task_struct *p = NULL;
[...]
> >>               printk("pid: %d, state: %ld, comm: %s\n", p->pid, p->state, p->comm);

> 
> Hmmm.., i just want to give a simplest task_struct, which is my pcb structure.
> Of course, it is bogus but it is now wrong for inserting. It can not
> print my fields
> correctly. (I run this module after i take away the rm_task function)
> 
> Some wrong logs like this:
> 
[...]
> [ 1515.055481] pid: 0, state: 1, comm:
> [ 1515.055483] the number of process is 145
> 
> I give the pid 8, state 8, and comm "jiawei" in my module. But it can
> not print correctly. Maybe kernel can tell my bogus one,right?

This has to do with the way accessing struct fields works in C:
For each struct each field name is translated by the compiler into an
offset which is used to compute the address of a field given the struct's
address. When you access the pid field of a struct task_struct the offset
will be at least around 20 * sizeof(int), which is an invalid offset to
your struct pcb, where the offsets are (most of the time):
	pid: 0
	state: sizeof(int)
	flag: 2 * sizeof(int)
	comm: 3 * sizeof(int)
	tasks: 3 * sizeof(int) + sizeof(char *)
(You get (an approximation of) the offset of a field by adding the size
 of the previous field (the compiler also adds some padding - see
 Documentation/unaligned-memory-access.txt in the kernel tree and
 http://en.wikipedia.org/wiki/Data_padding#Data_structure_padding))

Thanks,
	Jonathan Neuschäfer



More information about the Kernelnewbies mailing list