Identifying whether a user-process or kernel-thread execution takes place by looking at CPU registers

Dave Hylands dhylands at gmail.com
Sat May 14 15:12:21 EDT 2011


Hi John,

On Sat, May 14, 2011 at 10:55 AM, limp <johnkyr83 at hotmail.com> wrote:
> Thank you all for your replies.
>
>> If you want details about how to determine the task_struct from SP, I
>> can get into that, although it's subject to change. Using "current" it
>> the normal technique.
>
> Yes, I want to determine the "task_struct" from the SP. According to what I
> read, on x86 "current" is calculated by masking out the 13 least significant
> bits of the stack pointer to obtain the "thread_info" structure and
> consequently
> the "task_struct". Is that what you had in mind?

Well, what you get from the SP is something called thread_info (I'm
familiar with ARM)
http://lxr.linux.no/linux+v2.6.38/arch/arm/include/asm/thread_info.h#L50

The function current_thread_info gets the pointer to the thread_info
struct by looking at the stack pointer:
<http://lxr.linux.no/linux+v2.6.38/arch/arm/include/asm/thread_info.h#L94>

The thread_info struct contains a pointer to the task_struct.

So when the stack is allocated, it comes from an 8K chunk of memory (I
think it may be 4K on x86) which is aligned on an 8K boundary, which
is why the masking works. The stack starts at the high end of this and
grow down. The thread_info is stored at the low end, so when you
overflow your stack you corrupt your own thread_info.

It looks like all of the architectures use a similar design.

The thread_info is allocated here:
http://lxr.linux.no/linux+v2.6.38/kernel/fork.c#L118

which is called from here:
http://lxr.linux.no/linux+v2.6.38/kernel/fork.c#L260

> Another question is if the "task_struct" is allocated in contiguous memory
> space as I don't see a "packed" attribute in the structure definition.

Those are mutually independant concepts.

All allocated memory in the kernel is virtually contiguous. Packed
data is when the packing between members in a structure is removed.
<http://en.wikipedia.org/wiki/Data_structure_alignment>

> If yes, do you know of an easy way of finding the offset of the "mm" field
> of the structure so that I can obtain its value? I guess a way is by finding
> it manually from the structure definition but it seems quite complex.

In C there is an offsetof macro:
<http://linux.die.net/man/3/offsetof>
<http://www.netrino.com/Embedded-Systems/How-To/C-Offsetof-Macro>

-- 
Dave Hylands
Shuswap, BC, Canada
http://www.davehylands.com



More information about the Kernelnewbies mailing list