1

I'm trying to write a kernel module to detect a fork bomb, and to do this, I want to add a field int descendantCount to task_struct. This is my code so far:

struct task_struct *pTask;
for_each_process(pTask)
{
    struct task_struct *p; 
    *p = *pTask; 

    //trace back to every ancestor 
    for(p = current; p != &init_task; p->parent)
    {
        //increment the descendant count of p's parent
        p->descendantCount = p->descendantCount +1  //want to do something like this

    }
} 

Basically, I'm trying to loop through every process, and for each process, go through all of it's ancestors and increment the ancestor's descendantCount, which is the field that I want to add to task_struct.

I found this, and this, but I'm just still really confused on how I would go about doing this, as I'm new to kernel programming... Should I be going to include/linux/sched.h and adding a field there? Something like this:

 struct task_struct { 
 ...... 

 pid_t pid; 

 .... 
 int descendantCount; 

 }

Any help would be greatly appreciated, thank you!!

Community
  • 1
  • 1
ocean800
  • 3,489
  • 13
  • 41
  • 73

1 Answers1

-1

It is unclear what the actual idea is - is this supposed to bo executed on fork? Regardless, the idea is wrong and the implementation is buggy regardless of how pseudocody pasted sample is.

First of all descendantCount is a name using camelCase, which makes it inconsistent with the rest of the code. A less bad name would be descendant_count.

Counter modification must use atomic operations to not lose writes or the entire thing needs to be using an exclusive lock.

The traversal uses ->parent which is subject to change with ptrace where it starts pointing to the tracer. The parent you want can be found in ->real_parent.

Except there is no RCU protection provided, thus processes can be freed as you traverse them making the loop a use-after-free.

With RCU or tasklist_lock the traversal will be safe, but nonsensical. Procesess can be reparented to init when their original parent dies, rendering your hierarchical approach broken.

Processes would have to be grouped in some manner, but parent<->child relation is unsuitable for this purpose. Somewhat working examples of such grouping are cgroups and simple stuff like uids/gids.

All in all, this does not work.

Given that it looks like you are new not only to kernel itself but also C, I can only recommend focusing on userspace for the time being.