tags:

views:

142

answers:

3

In the Linux kernel, I need to find the offsets of member variables of a struct that is used. For example, for the init_task which is of type task_struct, I would like the offsets of its pid and tasks.

I only have the vmlinux present for this. I can refer to the open source kernel code, but it may differ from the build I have.

Is it possible to get the offsets without the source ?

EDIT: The vmlinux is for ARM, and I may not always be able to run C code on the target device.

+1  A: 

6.47 Offsetof

GCC implements for both C and C++ a syntactic extension to implement the offsetof macro.

 primary:
         "__builtin_offsetof" "(" typename "," offsetof_member_designator ")"

 offsetof_member_designator:
           identifier
         | offsetof_member_designator "." identifier
         | offsetof_member_designator "[" expr "]"

This extension is sufficient such that

 #define offsetof(type, member)  __builtin_offsetof (type, member)

is a suitable definition of the offsetof macro. In C++, type may be dependent. In either case, member may consist of a single identifier, or a sequence of member accesses and array references.

DigitalRoss
Thanks - this is very useful, but I have another problem. The target vmlinux is for ARM and I may not always be able to run C code on the target. Is it possible to run this on the host ?
Naseer
Strictly speaking, no. In practice, the offsets will generally be the same.
DigitalRoss
Actually, use the cross-compiler, with "int x[] = { offsetof(..), ... };" and then just look at the generated assembly. Then you will know for sure.
DigitalRoss
Thanks. This is a solution that works when I have access to the header file. Do you know of a way to get this info without it ?
Naseer
A: 

Found another solution with arm-eabi-gdb - I can do print &init_task and print &init_task.pid and the difference is the offset.

Naseer
+1  A: 

The size and layout of structures is present in the debugging information of the compiled object files (if you compile with -g and don't strip).

pahole (aka "poke-a-hole", packaged as dev-util/dwarves in Gentoo) reads an object's DWARF debugging information to output information about "holes" in structures -- that may be a good starting point for you.

ephemient
Awesome ! pahole is the best tool for this job.
Naseer