Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I see how a C++ class gets laid out in memory with gdb?

Tags:

c++

gdb

I've got a debug build of a program (the V8 JavaScript VM) and I want to understand how instances of certain classes are laid out in memory. I can pretty-print structures like this:

(gdb) print thread_local
$6 = {
  blocks_ = {
    data_ = 0x868ceb0,
    capacity_ = 7,
    length_ = 1
  },
  entered_contexts_ = {
    data_ = 0x868d828,
    capacity_ = 1,
    length_ = 1
  },
  saved_contexts_ = {
    data_ = 0x868d838,
    capacity_ = 1,
    length_ = 1
  },
  spare_ = 0x0,
  ignore_out_of_memory_ = false,
  call_depth_ = 1,
  handle_scope_data_ = {
    next = 0x0,
    limit = 0x0,
    level = 0
  }
}

but I want to know where those various members (blocks, entered_contexts, etc.) are physically, relative to the start of the object. On Solaris-based systems, mdb can do this for C structs like so:

> ::print -at port_event_t
0 port_event_t {
    0 int portev_events 
    4 ushort_t portev_source 
    6 ushort_t portev_pad 
    8 uintptr_t portev_object 
    10 void *portev_user 
}

In that example, each field is prefixed with its offset from the start of the structure. I want to do the same thing for C++ classes. gdb has to have this information in order to print out the struct members, but is there any way to view it?

Alternatively, is there some other way to do this for a running program?

like image 359
Dave Pacheco Avatar asked Oct 12 '11 20:10

Dave Pacheco


2 Answers

You can always print out the address of each member and this to figure it out yourself (you use & to get the member address, just like in the language itself).

like image 55
Mark B Avatar answered Oct 04 '22 02:10

Mark B


I wish I knew.

You can use ptype to list members. Then you can fabricate a poor man's offsetof like this:

(gdb) p/a &((my_struct_*)0)->my_member

(gdb) p/a &((struct sk_buff*)0)->iif
$7 = 0x74
like image 21
cdleonard Avatar answered Oct 04 '22 03:10

cdleonard