0

I want to write a kernel module that inspects the scheduled instructions of a running process. I already had a look at Linux Kernel Process Management, which explains how to iterate over processes.

struct task_struct *task;
for_each_process(task) {
    /* this pointlessly prints the name and PID of each task */
    printk("%s[%d]\n", task->comm, task->pid);
}

But once I get hold of a task_struct, how can I get to the instructions? I am assuming that I need to find the program-counter first, to see which instructions are about to be executed next.

Which member of the task_struct do I need to inspect to end up at the instructions? And in what kind of struct type are they stored?

Thanks for your help. I'm not that experienced with kernel programming.

arne.z
  • 3,242
  • 3
  • 24
  • 46
  • Well, the user stack pointer should point at the stack location where the next instruction to be executed has been pushed, (or, at least next to it, depending on how the stack works). – ThingyWotsit May 12 '17 at 15:34
  • @ThingyWotsit, Okay, that sounds good. Is there a way to "walk" along the stack? Are the instructions something like a linked list that I can follow? – arne.z May 12 '17 at 15:56

1 Answers1

2

I'm guessing this is a follow on from your last question. You are correct that through a task_struct you can get access to a processes program counter (also called instruction pointer on x86). I will answer for x86 as you indicated that you are interested in finding instructions specific to that instruction set.

You should have a look in the file arch/x86/include/asm/processor.h. It contains quite a few helper macros and functions so you don't have to reinvent the wheel. One of the ones that is most likely to be of interest to you is task_pt_regs(task). This macro will give you all of the register values associated with a given task. These values are contained in a struct pt_regs. You can see the definition of this struct in arch/x86/include/asm/ptrace.h. The member that you are interested in is unsigned long ip.

You now have a memory address that points to the next instruction to be executed by the process. This will need to be converted to a physical address to be usable to you though. That is a topic for another question though.

One brief note, to answer the question in your comment. Instructions are not stored in some data structure like a linked list. They are simply in a sequence one after another with all of their operands. You should think about it more like a binary file that can be parsed by the processor.

rlf
  • 136
  • 2