1

For a pretty-printer that I'm writing, I would like to know the alignment or the type which is used in a container. Unfortunately using alignof() or any similar "standard" operator doesn't work (https://sourceware.org/bugzilla/show_bug.cgi?id=17095). Using "typical" macro tricks that work directly in source code also doesn't work:

p ((char *)(&((struct { char c; double _h; } *)0)->_h) - (char *)0)
A syntax error in expression, near `{ char c; double _h; } *)0)->_h) - (char *)0)'.

Is that possible at all, or maybe the only way is to have that supported by GDB internally?

Freddie Chopin
  • 8,440
  • 2
  • 28
  • 58

1 Answers1

2

There's no way to get this information, because currently gdb does not have it.

Before DWARF version 5, there was no standard way to express alignment in the debug info. DWARF 5 added DW_AT_alignment, but gdb still simply ignores this attribute; to expose it via the Python API would require reading it and storing it in gdb's internal struct type. I don't know offhand whether compilers emit this attribute yet.

If you were very desperate you could do this either using the gdb compile feature or by running the compiler yourself, and having it emit the alignment in a way that can be extracted.

However, normally alignment is not too difficult to compute from the relevant type sizes, and if your target architectures are relatively limited then it's probably simpler to just roll your own alignment computer.

Tom Tromey
  • 21,507
  • 2
  • 45
  • 63
  • By "alignment is not too difficult to compute from the relevant type sizes" you mean to just take the size and calculate the next power-of-two which is not greater than architecture's max alignment? This would only work for types which were not aligned manually and would fail for arrays and structs... So I'm guessing you are thinking about something more complex than that. – Freddie Chopin Apr 02 '17 at 06:37
  • If you're worried about types that have their alignment set explicitly, then there's really nothing you can do except either run the compiler somehow, or fix gdb. For more ordinary cases you can just implement the usual type layout rules for your platform. – Tom Tromey Apr 02 '17 at 16:13
  • @TomTromey it looks like since this answer, you added it to gdb? : ) It is in 8.2 – Lack Oct 31 '18 at 01:54
  • 1
    Yeah, I added it. Now there is an `align` attribute on each `gdb.Type`, and `alignof` works in expressions. – Tom Tromey Oct 31 '18 at 13:26