Structs, Arrays, Strings and Virtual Calls in Machine Code
Types vanish at compile time. A struct becomes a base address plus constant offsets, an array becomes a base plus an index times the element size, a string becomes an address in a read-only section, and a C++ virtual call becomes two loads and an indirect call. Recovering those types from the offsets is a large part of real reverse engineering: once you know that [rdi+0x10] is user->balance, every function touching it reads like source code. This lesson shows each pattern in compiler output and how analysts turn offsets back into types. The assembly course's Arrays & Indexing and Structures build the same layouts by hand.
Definitions
- Struct layout: fields in declaration order, each aligned to its size (on x86-64:
char1,short2,int4,longand pointers 8), with padding inserted before a field that would be misaligned and at the end so arrays of the struct stay aligned.sizeofincludes the padding. - Field access:
[base + offset]with a constant offset. Many different offsets from the same register = a struct. - Array access:
[base + index*scale]wherescaleis 1, 2, 4 or 8; for larger elements the compiler multiplies the index first (imul, orleaand shifts). - String literals live in
.rodata; code reaches them withlea reg, [rip+disp], which disassemblers annotate with the target address. - Virtual call (C++): an object with virtual functions starts with a pointer to its class's vtable, an array of function pointers in a read-only section (
.rodata, or.data.rel.roin PIE builds, because the pointers need load-time relocations).obj->f()loads the vtable pointer from[obj], then calls[vtable + slot*8].
Layout first, then code
Before reading the code, compute the layout. The C program prints the offsets and size of a small struct, which is exactly what a reverse engineer reconstructs from the other direction.
#include <stdio.h>
#include <stddef.h>
struct account {
char kind; /* 1 byte, then padding */
int id;
long balance;
char name[12];
short flags;
};
int main(void) {
printf("kind @ %zu\n", offsetof(struct account, kind));
printf("id @ %zu\n", offsetof(struct account, id));
printf("balance @ %zu\n", offsetof(struct account, balance));
printf("name @ %zu\n", offsetof(struct account, name));
printf("flags @ %zu\n", offsetof(struct account, flags));
printf("sizeof = %zu\n", sizeof(struct account));
return 0;
}kind @ 0
id @ 4
balance @ 8
name @ 16
flags @ 28
sizeof = 32
kind takes one byte and three bytes of padding follow so id is 4-aligned; balance needs 8-alignment and lands at 8; name at 16 runs to 28, flags at 28 takes two bytes, and the size is rounded up to 32, a multiple of the largest alignment. Reordering fields from largest to smallest would remove the padding; that kind of detail also tells an analyst whether two binaries were built from the same header.
The code
The session compiles functions that use the struct, an array of the structs, a string, and a C++ class with a virtual function.
cat > data.c <<'SRC'
struct account { char kind; int id; long balance; char name[12]; short flags; };
long get_balance(const struct account *a) { return a->balance; }
int get_flags(const struct account *a) { return a->flags; }
long nth_balance(const struct account *arr, long i) { return arr[i].balance; }
const char *banner(void) { return "toy bank v1"; }
SRC
cat > shape.cpp <<'SRC'
struct Shape { virtual ~Shape() {} virtual double area() const = 0; };
double area_of(const Shape *s) { return s->area(); }
SRC
asm() { grep -vE '^\s*\.(file|text|p2align|globl|type|size|ident|section|align|string|weak|cfi)|^\s*$|^\.LFB|^\.LFE|^\.LC.:' ; }
gcc -O2 -S -masm=intel -fno-asynchronous-unwind-tables -fcf-protection=none -o - data.c | asm
echo "== C++"
g++ -O2 -S -masm=intel -fno-asynchronous-unwind-tables -fcf-protection=none -o - shape.cpp \
| asm | c++filt | sed -n '/^area_of/,/^$/p' | head -5 .intel_syntax noprefix
get_balance:
mov rax, QWORD PTR 8[rdi]
ret
get_flags:
movsx eax, WORD PTR 28[rdi]
ret
nth_balance:
sal rsi, 5
mov rax, QWORD PTR 8[rsi+rdi]
ret
banner:
lea rax, .LC0[rip]
ret
== C++
area_of(Shape const*):
mov rax, QWORD PTR [rdi]
jmp [QWORD PTR 16[rax]]
GCC's own assembly output writes a displacement in front of the brackets (8[rdi]); objdump writes the same operand as [rdi+0x8]. Reading it with the layout in hand:
get_balance:mov rax, QWORD PTR 8[rdi], an 8-byte load at offset 8.get_flags:movsx eax, WORD PTR 28[rdi], a sign-extended 2-byte load at offset 28 (ashort). The operand size (QWORD,WORD) and the extension (movsxsigned,movzxunsigned) reveal the field's type.nth_balance: the element size is 32, so the index is shifted left by 5 (sal rsi, 5) before the load from8[rsi+rdi]: element base plus the field offset 8. Seeingshl/salby 5 next to an array access tells you the element is 32 bytes.banner:lea rax, .LC0[rip], the address of the literal in.rodata; in a linked binary, objdump shows it aslea rax, [rip+0x...] # 2004.area_of:mov rax, QWORD PTR [rdi]loads the vtable pointer, thenjmp [QWORD PTR 16[rax]]tail-calls the function pointer at offset 16, slot 2. Slot 2, not 0, because GCC puts two destructor entries (complete and deleting) first for the virtual destructor, andareacomes after them.
Recovering types: how analysts do it
- Collect the offsets used with one base register across functions: 8 (QWORD), 28 (WORD), 4 (DWORD)... and the largest offset gives a lower bound for the size.
- Look at allocation sites:
malloc(32)oroperator new(32)followed by stores to those offsets gives the size and the initial values. - Name the fields from their use: an offset passed to
printf("%s")is a string; one compared with constants is a kind or a state; one added to and stored back is a counter or balance. - Declare the struct in the decompiler (Ghidra's Data Type Manager, IDA's Local Types) and apply it to the pointer; every function using it becomes readable at once.
- For C++: find vtables in
.rodataor.data.rel.ro(arrays of function pointers, referenced from constructors), and RTTI (typeinfo for ...symbols, or.?AVnames in MSVC binaries) names the classes even in stripped builds.
How this matters for detection
- Memory-safety review: an index multiplied by an element size from input, without a bounds check, is an out-of-bounds read or write; a field read as
intin one function and written aslongin another hints at type confusion (Memory Safety). - Vtable integrity: exploits against C++ programs often corrupt the vtable pointer in an object, so a virtual call jumps wherever the attacker wants. Defences check vtables before calls: Clang's
-fsanitize=cfi-vcall, MSVC Control Flow Guard (__guard_dispatch_icall_fptrcalls before indirect calls) and, more coarsely, hardware indirect branch tracking (Intel IBT, ARM BTI), which only limits where an indirect call may land. - Malware configuration is often a struct in the data section; once its layout is known, every sample of the family can be parsed automatically.
How mistakes are prevented
- For authors:
static_assert(sizeof(struct account) == 32)andoffsetofchecks in headers shared between components or written to disk, so layout changes are caught at build time; fixed-width types (int32_t,int64_t) in file and network formats instead oflong. - Enable control-flow integrity where the toolchain supports it.
Pitfalls
longis 4 bytes on Windows (LLP64) and 8 on Linux (LP64), so the same struct has different layouts (Calling Conventions).- Packed structs (
#pragma pack,__attribute__((packed))) have no padding: common in file formats and network headers. - Compilers reorder nothing in C structs, but they can keep fields in registers so some never appear as memory accesses.
- The vtable slot number depends on the compiler's ABI: Itanium C++ ABI (GCC, Clang) puts two destructor entries where MSVC puts one.
Practice
1. You see movzx eax, BYTE PTR [rdi+0x14] and mov rdx, QWORD PTR [rdi+0x18] in one function. What can you say about the struct?
An unsigned 1-byte field at offset 0x14 (20) and an 8-byte field (a long, size_t or pointer) at offset 0x18 (24); the struct is at least 32 bytes.
2. An array access is imul rax, rsi, 24 followed by mov ecx, DWORD PTR [rdi+rax+4]. Element size and field?
24-byte elements; a 4-byte field at offset 4 of element rsi.
3. Reorder struct account to remove its internal padding. What is the new size?
long balance; int id; short flags; char kind; char name[12]; uses 8 + 4 + 2 + 1 + 12 = 27 bytes, rounded up to 32 for alignment. The end padding remains, but there is none between fields.
Test yourself
Why is balance at offset 8 and not 5 in struct account?
- The compiler sorts fields alphabetically
- An 8-byte long must be 8-aligned, so padding follows the earlier fields
- Offsets always start at 8
- Because of the vtable
movsx eax, WORD PTR 28[rdi] tells you the field at offset 28 is:
- An unsigned byte
- A signed 2-byte integer (short)
- A pointer
- A double
A C++ virtual call compiles to:
- A direct call to the function
- A load of the vtable pointer from the object, then an indirect call through a slot of the vtable
- A system call
- A jump table
In nth_balance, the index is shifted left by 5. What is the element size?
- 5 bytes
- 8 bytes
- 32 bytes
- 16 bytes