Skip to main content

padlock_source/frontends/
c_cpp.rs

1// padlock-source/src/frontends/c_cpp.rs
2//
3// Extracts struct layouts from C / C++ source using tree-sitter.
4// Sizes and alignments are computed from field type names + arch config;
5// there is no compiler involved so the results are approximate for complex types.
6
7use padlock_core::arch::ArchConfig;
8use padlock_core::ir::{AccessPattern, Field, StructLayout, TypeInfo};
9use tree_sitter::{Node, Parser};
10
11// ── type resolution ───────────────────────────────────────────────────────────
12
13/// Map a C/C++ type name to (size, align) using the target arch.
14fn c_type_size_align(ty: &str, arch: &'static ArchConfig) -> (usize, usize) {
15    let ty = ty.trim();
16    // Strip qualifiers
17    for qual in &["const ", "volatile ", "restrict ", "unsigned ", "signed "] {
18        if let Some(rest) = ty.strip_prefix(qual) {
19            return c_type_size_align(rest, arch);
20        }
21    }
22    // x86 SSE / AVX / AVX-512 SIMD types
23    match ty {
24        "__m64" => return (8, 8),
25        "__m128" | "__m128d" | "__m128i" => return (16, 16),
26        "__m256" | "__m256d" | "__m256i" => return (32, 32),
27        "__m512" | "__m512d" | "__m512i" => return (64, 64),
28        // ARM NEON — 64-bit (double-word) vectors
29        "float32x2_t" | "int32x2_t" | "uint32x2_t" | "int8x8_t" | "uint8x8_t" | "int16x4_t"
30        | "uint16x4_t" | "float64x1_t" | "int64x1_t" | "uint64x1_t" => return (8, 8),
31        // ARM NEON — 128-bit (quad-word) vectors
32        "float32x4_t" | "int32x4_t" | "uint32x4_t" | "float64x2_t" | "int64x2_t" | "uint64x2_t"
33        | "int8x16_t" | "uint8x16_t" | "int16x8_t" | "uint16x8_t" => return (16, 16),
34        _ => {}
35    }
36    // C++ standard library types (Linux/glibc + libstdc++ defaults).
37    // Sizes are platform-approximate; accuracy is "good enough" for cache-line
38    // bucketing and false-sharing detection.
39    match ty {
40        // ── Synchronisation ───────────────────────────────────────────────────
41        // pthread_mutex_t on Linux/glibc is 40 bytes.
42        "std::mutex"
43        | "std::recursive_mutex"
44        | "std::timed_mutex"
45        | "std::recursive_timed_mutex"
46        | "pthread_mutex_t" => return (40, 8),
47        "std::shared_mutex" | "std::shared_timed_mutex" => return (56, 8),
48        "std::condition_variable" | "pthread_cond_t" => return (48, 8),
49
50        // ── String / view ─────────────────────────────────────────────────────
51        // libstdc++ std::string: 32B (ptr + length + SSO buffer / capacity).
52        // libc++ (Clang): 24B. We use 32B (libstdc++ / GCC, dominant on Linux).
53        "std::string" | "std::wstring" | "std::u8string" | "std::u16string" | "std::u32string"
54        | "std::pmr::string" => return (32, 8),
55        // std::string_view / std::span<T>: pointer + length (2 words).
56        "std::string_view"
57        | "std::wstring_view"
58        | "std::u8string_view"
59        | "std::u16string_view"
60        | "std::u32string_view" => return (arch.pointer_size * 2, arch.pointer_size),
61
62        // ── Sequence containers ───────────────────────────────────────────────
63        // std::vector<T>: pointer + size + capacity = 3 words (24B on 64-bit).
64        // Size is independent of T.
65        ty if ty.starts_with("std::vector<") || ty == "std::vector" => {
66            return (arch.pointer_size * 3, arch.pointer_size);
67        }
68        // std::deque<T>: 80B on both libstdc++ and libc++ (64-bit Linux).
69        ty if ty.starts_with("std::deque<") || ty == "std::deque" => return (80, 8),
70        // std::list<T>: sentinel node pointer + size = 2 words + node pointers.
71        // libstdc++: 24B (size_t + two pointers). libc++: 24B.
72        ty if ty.starts_with("std::list<") || ty == "std::list" => {
73            return (arch.pointer_size * 3, arch.pointer_size);
74        }
75        // std::forward_list<T>: single pointer (head node).
76        ty if ty.starts_with("std::forward_list<") || ty == "std::forward_list" => {
77            return (arch.pointer_size, arch.pointer_size);
78        }
79        // std::array<T, N>: inline storage; size = N * sizeof(T).
80        // We cannot compute this without resolving T and N, so fall through.
81
82        // ── Associative / unordered containers ────────────────────────────────
83        // All map/set types: header node + size = ~48B (libstdc++) / ~40B (libc++).
84        // Use 48B as conservative approximation.
85        ty if ty.starts_with("std::map<")
86            || ty.starts_with("std::multimap<")
87            || ty.starts_with("std::set<")
88            || ty.starts_with("std::multiset<") =>
89        {
90            return (48, 8);
91        }
92        // std::unordered_map / unordered_set: bucket array pointer + size + load factor + etc.
93        // libstdc++: ~56B. libc++: ~72B. Use 56B.
94        ty if ty.starts_with("std::unordered_map<")
95            || ty.starts_with("std::unordered_multimap<")
96            || ty.starts_with("std::unordered_set<")
97            || ty.starts_with("std::unordered_multiset<") =>
98        {
99            return (56, 8);
100        }
101
102        // ── Smart pointers ────────────────────────────────────────────────────
103        // std::unique_ptr<T>: single pointer (deleter may be zero-sized via EBO).
104        ty if ty.starts_with("std::unique_ptr<") || ty == "std::unique_ptr" => {
105            return (arch.pointer_size, arch.pointer_size);
106        }
107        // std::shared_ptr<T> / std::weak_ptr<T>: object pointer + control block pointer.
108        ty if ty.starts_with("std::shared_ptr<")
109            || ty == "std::shared_ptr"
110            || ty.starts_with("std::weak_ptr<")
111            || ty == "std::weak_ptr" =>
112        {
113            return (arch.pointer_size * 2, arch.pointer_size);
114        }
115
116        // ── Type-erasure / utilities ──────────────────────────────────────────
117        // std::function<Sig>: 32B on libstdc++ and libc++ (64-bit Linux).
118        // Holds a functor pointer, a vtable pointer, and a small-functor buffer.
119        ty if ty.starts_with("std::function<") || ty == "std::function" => return (32, 8),
120        // std::any: 32B on libstdc++ (small-object buffer + vtable pointer).
121        "std::any" => return (32, 8),
122        // std::error_code / std::error_condition: pointer + int = 16B.
123        "std::error_code" | "std::error_condition" => return (16, 8),
124        // std::exception_ptr: single pointer.
125        "std::exception_ptr" => return (arch.pointer_size, arch.pointer_size),
126        // std::type_index: single pointer (wraps std::type_info*).
127        "std::type_index" => return (arch.pointer_size, arch.pointer_size),
128        // std::span<T>: pointer + length (2 words). Template arg irrelevant.
129        ty if ty.starts_with("std::span<") || ty == "std::span" => {
130            return (arch.pointer_size * 2, arch.pointer_size);
131        }
132        // std::optional<T>: sizeof(T) + 1B bool, padded to align(T).
133        // Recurse to resolve T then apply the formula.
134        ty if ty.starts_with("std::optional<") && ty.ends_with('>') => {
135            let inner = &ty["std::optional<".len()..ty.len() - 1];
136            let (t_size, t_align) = c_type_size_align(inner.trim(), arch);
137            let total = (t_size + 1).next_multiple_of(t_align.max(1));
138            return (total, t_align.max(1));
139        }
140
141        // ── Atomic ────────────────────────────────────────────────────────────
142        // std::atomic<T>: same size and alignment as T.
143        ty if ty.starts_with("std::atomic<") && ty.ends_with('>') => {
144            let inner = &ty[12..ty.len() - 1];
145            return c_type_size_align(inner.trim(), arch);
146        }
147        // std::atomic_flag: guaranteed 1B minimum, but often 4B in practice.
148        "std::atomic_flag" => return (4, 4),
149
150        _ => {} // fall through to primitive types below
151    }
152    // Primitive / stdint / pointer types
153    match ty {
154        "char" | "_Bool" | "bool" => (1, 1),
155        "short" | "short int" => (2, 2),
156        "int" => (4, 4),
157        "long" | "long int" => (arch.pointer_size, arch.pointer_size),
158        "long long" | "long long int" => (8, 8),
159        "float" => (4, 4),
160        "double" => (8, 8),
161        "long double" => (16, 16),
162
163        // C99 stdint exact-width types
164        "int8_t" | "uint8_t" => (1, 1),
165        "int16_t" | "uint16_t" => (2, 2),
166        "int32_t" | "uint32_t" => (4, 4),
167        "int64_t" | "uint64_t" => (8, 8),
168        "intmax_t" | "uintmax_t" => (8, 8),
169        "size_t" | "ssize_t" | "ptrdiff_t" | "intptr_t" | "uintptr_t" => {
170            (arch.pointer_size, arch.pointer_size)
171        }
172
173        // C99 fast types — uint_fast{8,16}_t are always 1/2B;
174        // uint_fast{32,64}_t are pointer-sized on 64-bit (8B), 4B on 32-bit.
175        "int_fast8_t" | "uint_fast8_t" => (1, 1),
176        "int_fast16_t" | "uint_fast16_t" => (2, 2),
177        "int_fast32_t" | "uint_fast32_t" | "int_fast64_t" | "uint_fast64_t" => {
178            (arch.pointer_size, arch.pointer_size)
179        }
180
181        // C99 least types — minimum guaranteed widths
182        "int_least8_t" | "uint_least8_t" => (1, 1),
183        "int_least16_t" | "uint_least16_t" => (2, 2),
184        "int_least32_t" | "uint_least32_t" => (4, 4),
185        "int_least64_t" | "uint_least64_t" => (8, 8),
186
187        // GCC/Clang 128-bit integer extension
188        "__int128" | "__uint128" | "__int128_t" | "__uint128_t" => (16, 16),
189
190        // Linux kernel short-form integer types (linux/types.h)
191        "u8" | "s8" => (1, 1),
192        "u16" | "s16" => (2, 2),
193        "u32" | "s32" => (4, 4),
194        "u64" | "s64" => (8, 8),
195
196        // Linux kernel double-underscore types (__u8, __s8, __be16, __le32, …)
197        "__u8" | "__s8" | "__u8__" | "__s8__" => (1, 1),
198        "__u16" | "__s16" | "__be16" | "__le16" => (2, 2),
199        "__u32" | "__s32" | "__be32" | "__le32" => (4, 4),
200        "__u64" | "__s64" | "__be64" | "__le64" => (8, 8),
201
202        // MSVC fixed-width intrinsics
203        "__int8" => (1, 1),
204        "__int16" => (2, 2),
205        "__int32" => (4, 4),
206        "__int64" => (8, 8),
207
208        // Windows SDK / WinAPI types
209        "BYTE" | "BOOLEAN" | "CHAR" | "INT8" | "UINT8" => (1, 1),
210        "WORD" | "WCHAR" | "SHORT" | "USHORT" | "INT16" | "UINT16" => (2, 2),
211        "DWORD" | "LONG" | "ULONG" | "INT" | "UINT" | "BOOL" | "FLOAT" | "INT32" | "UINT32" => {
212            (4, 4)
213        }
214        "QWORD" | "LONGLONG" | "ULONGLONG" | "INT64" | "UINT64" | "LARGE_INTEGER" => (8, 8),
215        "DWORD64" | "ULONG64" | "LONG64" => (8, 8),
216        "HANDLE" | "LPVOID" | "PVOID" | "LPCVOID" | "LPSTR" | "LPCSTR" | "LPWSTR" | "LPCWSTR"
217        | "SIZE_T" | "SSIZE_T" | "ULONG_PTR" | "LONG_PTR" | "DWORD_PTR" | "INT_PTR"
218        | "UINT_PTR" => (arch.pointer_size, arch.pointer_size),
219
220        // C/C++ character types
221        // wchar_t: 4B on Linux/macOS (GCC/Clang POSIX), 2B on Windows/MSVC.
222        // All current padlock arch configs are POSIX, so 4B is correct here.
223        "wchar_t" => (4, 4),
224        "char8_t" => (1, 1),
225        "char16_t" => (2, 2),
226        "char32_t" => (4, 4),
227
228        // Half-precision and bfloat16 (ARM, GCC, Clang, ML workloads)
229        "_Float16" | "__fp16" | "__bf16" => (2, 2),
230        // 128-bit float (GCC/Clang extension)
231        "_Float128" | "__float128" => (16, 16),
232
233        // Pointer types
234        ty if ty.ends_with('*') => (arch.pointer_size, arch.pointer_size),
235        // Unknown — use pointer size as a reasonable default
236        _ => (arch.pointer_size, arch.pointer_size),
237    }
238}
239
240// ── struct / union simulation ─────────────────────────────────────────────────
241
242/// Strip a bit-field width annotation (`:N`) from a type name for size lookup.
243/// `"int:3"` → `"int"`, `"std::atomic"` → unchanged (`:` not followed by digits only).
244fn strip_bitfield_suffix(ty: &str) -> &str {
245    if let Some(pos) = ty.rfind(':') {
246        let suffix = ty[pos + 1..].trim();
247        if !suffix.is_empty() && suffix.bytes().all(|b| b.is_ascii_digit()) {
248            return ty[..pos].trim_end();
249        }
250    }
251    ty
252}
253
254/// Return `true` when `ty` carries a bit-field width annotation (e.g. `"int:3"`).
255/// Bit-field packing is compiler-controlled and cannot be accurately modelled
256/// without a compiler, so structs containing bit-field members are skipped.
257fn is_bitfield_type(ty: &str) -> bool {
258    strip_bitfield_suffix(ty) != ty
259}
260
261/// Simulate C/C++ struct layout given ordered fields.
262///
263/// When `packed` is `true` the layout mirrors `__attribute__((packed))`:
264/// no inter-field alignment padding is inserted and the struct alignment
265/// is forced to 1. This matches GCC/Clang behaviour for packed structs.
266fn simulate_layout(
267    fields: &mut Vec<Field>,
268    struct_name: String,
269    arch: &'static ArchConfig,
270    source_line: Option<u32>,
271    packed: bool,
272) -> StructLayout {
273    let mut offset = 0usize;
274    let mut struct_align = 1usize;
275
276    for f in fields.iter_mut() {
277        if !packed && f.align > 0 {
278            offset = offset.next_multiple_of(f.align);
279        }
280        f.offset = offset;
281        offset += f.size;
282        if !packed {
283            struct_align = struct_align.max(f.align);
284        }
285    }
286    // Trailing padding (not present in packed structs)
287    if !packed && struct_align > 0 {
288        offset = offset.next_multiple_of(struct_align);
289    }
290
291    StructLayout {
292        name: struct_name,
293        total_size: offset,
294        align: struct_align,
295        fields: std::mem::take(fields),
296        source_file: None,
297        source_line,
298        arch,
299        is_packed: packed,
300        is_union: false,
301        is_repr_rust: false,
302        suppressed_findings: Vec::new(),
303    }
304}
305
306/// Simulate a C/C++ union layout: all fields start at offset 0;
307/// total size is the largest field, rounded to max alignment.
308fn simulate_union_layout(
309    fields: &mut Vec<Field>,
310    name: String,
311    arch: &'static ArchConfig,
312    source_line: Option<u32>,
313) -> StructLayout {
314    for f in fields.iter_mut() {
315        f.offset = 0;
316    }
317    let max_size = fields.iter().map(|f| f.size).max().unwrap_or(0);
318    let max_align = fields.iter().map(|f| f.align).max().unwrap_or(1);
319    let total_size = if max_align > 0 {
320        max_size.next_multiple_of(max_align)
321    } else {
322        max_size
323    };
324
325    StructLayout {
326        name,
327        total_size,
328        align: max_align,
329        fields: std::mem::take(fields),
330        source_file: None,
331        source_line,
332        arch,
333        is_packed: false,
334        is_union: true,
335        is_repr_rust: false,
336        suppressed_findings: Vec::new(),
337    }
338}
339
340// ── C++ class parsing (vtable + inheritance) ──────────────────────────────────
341
342/// Parse a `class_specifier` node, modelling:
343/// - A hidden vtable pointer (`__vptr`) when any method is `virtual`.
344/// - Base-class storage as a synthetic `__base_<Name>` field (size resolved
345///   later by the nested-struct resolution pass in `lib.rs`).
346fn parse_class_specifier(
347    source: &str,
348    node: Node<'_>,
349    arch: &'static ArchConfig,
350) -> Option<StructLayout> {
351    let mut class_name = "<anonymous>".to_string();
352    let mut base_names: Vec<String> = Vec::new();
353    let mut body_node: Option<Node> = None;
354    let mut is_packed = false;
355    let mut struct_alignas: Option<usize> = None;
356
357    for i in 0..node.child_count() {
358        let child = node.child(i)?;
359        match child.kind() {
360            "type_identifier" => class_name = source[child.byte_range()].to_string(),
361            "base_class_clause" => {
362                // tree-sitter-cpp structure: ':' [access_specifier] type_identifier
363                // type_identifier nodes are direct children of base_class_clause.
364                for j in 0..child.child_count() {
365                    if let Some(base) = child.child(j)
366                        && base.kind() == "type_identifier"
367                    {
368                        base_names.push(source[base.byte_range()].to_string());
369                    }
370                }
371            }
372            "field_declaration_list" => body_node = Some(child),
373            "attribute_specifier" => {
374                if source[child.byte_range()].contains("packed") {
375                    is_packed = true;
376                }
377            }
378            // C++11 class-level alignas: `class alignas(64) Name { ... };`
379            "alignas_qualifier" | "alignas_specifier" => {
380                if struct_alignas.is_none() {
381                    struct_alignas = parse_alignas_value(source, child);
382                }
383            }
384            _ => {}
385        }
386    }
387
388    let body = body_node?;
389
390    // Detect virtual methods: look for `virtual` keyword anywhere in body
391    let has_virtual = contains_virtual_keyword(source, body);
392
393    // Collect declared fields: (field_name, type_text, guard, alignas_override, source_line)
394    let mut raw_fields: Vec<RawField> = Vec::new();
395    for i in 0..body.child_count() {
396        let Some(child) = body.child(i) else {
397            continue;
398        };
399        if child.kind() == "field_declaration" {
400            if let Some(anon_fields) = parse_anonymous_nested(source, child, arch, false) {
401                raw_fields.extend(anon_fields);
402            } else if let Some((ty, fname, guard, al, ln)) = parse_field_declaration(source, child)
403            {
404                raw_fields.push((fname, ty, guard, al, ln));
405            }
406        }
407    }
408
409    // Build fields: vtable pointer, then base-class slots, then declared fields
410    let mut fields: Vec<Field> = Vec::new();
411
412    // Virtual dispatch pointer (hidden, at offset 0 for the first virtual class)
413    if has_virtual {
414        let ps = arch.pointer_size;
415        fields.push(Field {
416            name: "__vptr".to_string(),
417            ty: TypeInfo::Pointer {
418                size: ps,
419                align: ps,
420            },
421            offset: 0,
422            size: ps,
423            align: ps,
424            source_file: None,
425            source_line: None,
426            access: AccessPattern::Unknown,
427        });
428    }
429
430    // Base class storage (opaque until nested-struct resolver fills in sizes)
431    for base in &base_names {
432        let ps = arch.pointer_size;
433        fields.push(Field {
434            name: format!("__base_{base}"),
435            ty: TypeInfo::Opaque {
436                name: base.clone(),
437                size: ps,
438                align: ps,
439            },
440            offset: 0,
441            size: ps,
442            align: ps,
443            source_file: None,
444            source_line: None,
445            access: AccessPattern::Unknown,
446        });
447    }
448
449    // Skip classes with bit-field members (same reason as structs).
450    if raw_fields
451        .iter()
452        .any(|(_, ty, _, _, _)| is_bitfield_type(ty))
453    {
454        eprintln!(
455            "padlock: note: skipping '{class_name}' — contains bit-fields \
456             (bit-field layout is compiler-controlled; use binary analysis for accurate results)"
457        );
458        return None;
459    }
460
461    // Declared member fields
462    for (fname, ty_name, guard, alignas, field_line) in raw_fields {
463        let (size, natural_align) = c_type_size_align(&ty_name, arch);
464        let align = alignas.unwrap_or(natural_align);
465        let access = if let Some(g) = guard {
466            AccessPattern::Concurrent {
467                guard: Some(g),
468                is_atomic: false,
469            }
470        } else {
471            AccessPattern::Unknown
472        };
473        fields.push(Field {
474            name: fname,
475            ty: TypeInfo::Primitive {
476                name: ty_name,
477                size,
478                align,
479            },
480            offset: 0,
481            size,
482            align,
483            source_file: None,
484            source_line: Some(field_line),
485            access,
486        });
487    }
488
489    if fields.is_empty() {
490        return None;
491    }
492
493    let line = node.start_position().row as u32 + 1;
494    let mut layout = simulate_layout(&mut fields, class_name, arch, Some(line), is_packed);
495
496    if let Some(al) = struct_alignas
497        && al > layout.align
498    {
499        layout.align = al;
500        if !is_packed {
501            layout.total_size = layout.total_size.next_multiple_of(al);
502        }
503    }
504
505    layout.suppressed_findings =
506        super::suppress::suppressed_from_preceding_source(source, node.start_byte());
507
508    Some(layout)
509}
510
511/// Return true if a `field_declaration_list` node contains any `virtual` keyword
512/// (indicating that the class needs a vtable pointer).
513fn contains_virtual_keyword(source: &str, node: Node<'_>) -> bool {
514    let mut stack = vec![node];
515    while let Some(n) = stack.pop() {
516        if n.kind() == "virtual" {
517            return true;
518        }
519        // Also check raw text for cases where tree-sitter may not produce a
520        // dedicated `virtual` node (e.g. inside complex declarations).
521        if n.child_count() == 0 {
522            let text = &source[n.byte_range()];
523            if text == "virtual" {
524                return true;
525            }
526        }
527        for i in (0..n.child_count()).rev() {
528            if let Some(child) = n.child(i) {
529                stack.push(child);
530            }
531        }
532    }
533    false
534}
535
536// ── tree-sitter walker ────────────────────────────────────────────────────────
537
538fn extract_structs_from_tree(
539    source: &str,
540    root: Node<'_>,
541    arch: &'static ArchConfig,
542    layouts: &mut Vec<StructLayout>,
543) {
544    let cursor = root.walk();
545    let mut stack = vec![root];
546
547    while let Some(node) = stack.pop() {
548        // Push children in reverse so we process left-to-right
549        for i in (0..node.child_count()).rev() {
550            if let Some(child) = node.child(i) {
551                stack.push(child);
552            }
553        }
554
555        match node.kind() {
556            "struct_specifier" => {
557                if let Some(layout) = parse_struct_or_union_specifier(source, node, arch, false) {
558                    layouts.push(layout);
559                }
560            }
561            "union_specifier" => {
562                if let Some(layout) = parse_struct_or_union_specifier(source, node, arch, true) {
563                    layouts.push(layout);
564                }
565            }
566            "class_specifier" => {
567                if let Some(layout) = parse_class_specifier(source, node, arch) {
568                    layouts.push(layout);
569                }
570            }
571            _ => {}
572        }
573    }
574
575    // Also handle `typedef struct/union { ... } Name;`
576    let cursor2 = root.walk();
577    let mut stack2 = vec![root];
578    while let Some(node) = stack2.pop() {
579        for i in (0..node.child_count()).rev() {
580            if let Some(child) = node.child(i) {
581                stack2.push(child);
582            }
583        }
584        if node.kind() == "type_definition"
585            && let Some(layout) = parse_typedef_struct_or_union(source, node, arch)
586        {
587            let existing = layouts
588                .iter()
589                .position(|l| l.name == layout.name || l.name == "<anonymous>");
590            match existing {
591                Some(i) if layouts[i].name == "<anonymous>" => {
592                    layouts[i] = layout;
593                }
594                None => layouts.push(layout),
595                _ => {}
596            }
597        }
598    }
599    let _ = cursor;
600    let _ = cursor2; // silence unused warnings
601}
602
603/// Parse a `struct_specifier` or `union_specifier` node into a `StructLayout`.
604fn parse_struct_or_union_specifier(
605    source: &str,
606    node: Node<'_>,
607    arch: &'static ArchConfig,
608    is_union: bool,
609) -> Option<StructLayout> {
610    let mut name = "<anonymous>".to_string();
611    let mut body_node: Option<Node> = None;
612    let mut is_packed = false;
613    // Struct-level alignas: `struct alignas(64) CacheAligned { ... };`
614    let mut struct_alignas: Option<usize> = None;
615
616    for i in 0..node.child_count() {
617        let child = node.child(i)?;
618        match child.kind() {
619            "type_identifier" => name = source[child.byte_range()].to_string(),
620            "field_declaration_list" => body_node = Some(child),
621            "attribute_specifier" => {
622                let text = &source[child.byte_range()];
623                if text.contains("packed") {
624                    is_packed = true;
625                }
626            }
627            // C++11 struct-level alignas: `struct alignas(64) Name { ... };`
628            // tree-sitter-cpp: `alignas_qualifier` as direct child of struct_specifier
629            "alignas_qualifier" | "alignas_specifier" => {
630                if struct_alignas.is_none() {
631                    struct_alignas = parse_alignas_value(source, child);
632                }
633            }
634            _ => {}
635        }
636    }
637
638    let body = body_node?;
639    let mut raw_fields: Vec<RawField> = Vec::new();
640
641    for i in 0..body.child_count() {
642        let child = body.child(i)?;
643        if child.kind() == "field_declaration" {
644            // Check for anonymous nested struct/union: a field_declaration whose
645            // only non-field-identifier child is a struct_specifier/union_specifier
646            // with no type_identifier (i.e. `struct { int x; int y; };`).
647            if let Some(anon_fields) = parse_anonymous_nested(source, child, arch, is_union) {
648                raw_fields.extend(anon_fields);
649            } else if let Some((ty, fname, guard, al, ln)) = parse_field_declaration(source, child)
650            {
651                raw_fields.push((fname, ty, guard, al, ln));
652            }
653        }
654    }
655
656    if raw_fields.is_empty() {
657        return None;
658    }
659
660    // Bit-field packing is compiler-controlled and cannot be accurately modelled
661    // without a compiler. Skip the entire struct to avoid producing wrong layout
662    // data. Use `padlock analyze` on the compiled binary for accurate results.
663    if raw_fields
664        .iter()
665        .any(|(_, ty, _, _, _)| is_bitfield_type(ty))
666    {
667        eprintln!(
668            "padlock: note: skipping '{name}' — contains bit-fields \
669             (bit-field layout is compiler-controlled; use binary analysis for accurate results)"
670        );
671        return None;
672    }
673
674    let mut fields: Vec<Field> = raw_fields
675        .into_iter()
676        .map(|(fname, ty_name, guard, alignas, field_line)| {
677            let (size, natural_align) = c_type_size_align(&ty_name, arch);
678            // alignas(N) on a field overrides its alignment requirement.
679            let align = alignas.unwrap_or(natural_align);
680            let access = if let Some(g) = guard {
681                AccessPattern::Concurrent {
682                    guard: Some(g),
683                    is_atomic: false,
684                }
685            } else {
686                AccessPattern::Unknown
687            };
688            Field {
689                name: fname,
690                ty: TypeInfo::Primitive {
691                    name: ty_name,
692                    size,
693                    align,
694                },
695                offset: 0,
696                size,
697                align,
698                source_file: None,
699                source_line: Some(field_line),
700                access,
701            }
702        })
703        .collect();
704
705    let line = node.start_position().row as u32 + 1;
706    let mut layout = if is_union {
707        simulate_union_layout(&mut fields, name, arch, Some(line))
708    } else {
709        simulate_layout(&mut fields, name, arch, Some(line), is_packed)
710    };
711
712    // Apply struct-level alignas: the struct's alignment requirement is at
713    // least N; trailing padding may grow to satisfy the new alignment.
714    if let Some(al) = struct_alignas
715        && al > layout.align
716    {
717        layout.align = al;
718        if !is_packed {
719            layout.total_size = layout.total_size.next_multiple_of(al);
720        }
721    }
722
723    layout.suppressed_findings =
724        super::suppress::suppressed_from_preceding_source(source, node.start_byte());
725
726    Some(layout)
727}
728
729/// Parse a `typedef struct/union { ... } Name;` type_definition node.
730fn parse_typedef_struct_or_union(
731    source: &str,
732    node: Node<'_>,
733    arch: &'static ArchConfig,
734) -> Option<StructLayout> {
735    let mut specifier_node: Option<Node> = None;
736    let mut is_union = false;
737    let mut typedef_name: Option<String> = None;
738
739    for i in 0..node.child_count() {
740        let child = node.child(i)?;
741        match child.kind() {
742            "struct_specifier" => {
743                specifier_node = Some(child);
744                is_union = false;
745            }
746            "union_specifier" => {
747                specifier_node = Some(child);
748                is_union = true;
749            }
750            "type_identifier" => typedef_name = Some(source[child.byte_range()].to_string()),
751            _ => {}
752        }
753    }
754
755    let spec = specifier_node?;
756    let typedef_name = typedef_name?;
757
758    let mut layout = parse_struct_or_union_specifier(source, spec, arch, is_union)?;
759    if layout.name == "<anonymous>" {
760        layout.name = typedef_name;
761    }
762    Some(layout)
763}
764
765// Alias kept for the typedef pass in extract_structs_from_tree.
766#[allow(dead_code)]
767fn parse_typedef_struct(
768    source: &str,
769    node: Node<'_>,
770    arch: &'static ArchConfig,
771) -> Option<StructLayout> {
772    parse_typedef_struct_or_union(source, node, arch)
773}
774
775/// Extract a lock guard name from a C/C++ `__attribute__((guarded_by(X)))` or
776/// `__attribute__((pt_guarded_by(X)))` specifier node.
777///
778/// Also recognises the common macro forms `GUARDED_BY(X)` and `PT_GUARDED_BY(X)`
779/// which expand to the same attribute (Clang thread-safety analysis).
780/// The match is done on the raw source text of any `attribute_specifier` child,
781/// so it works regardless of how tree-sitter structures the inner tokens.
782fn extract_guard_from_c_field_text(field_source: &str) -> Option<String> {
783    // Patterns to search for (case-insensitive on the keyword, guard name is as-is)
784    for kw in &["guarded_by", "pt_guarded_by", "GUARDED_BY", "PT_GUARDED_BY"] {
785        if let Some(pos) = field_source.find(kw) {
786            let after = &field_source[pos + kw.len()..];
787            // Expect `(` optionally preceded by whitespace
788            let trimmed = after.trim_start();
789            if let Some(inner) = trimmed.strip_prefix('(') {
790                // Read until the matching ')'
791                if let Some(end) = inner.find(')') {
792                    let guard = inner[..end].trim().trim_matches('"');
793                    if !guard.is_empty() {
794                        return Some(guard.to_string());
795                    }
796                }
797            }
798        }
799    }
800    None
801}
802
803/// Parse a numeric value from an `alignas_qualifier` node: `alignas(N)`.
804/// tree-sitter-cpp uses the node kind `alignas_qualifier` for C++11 `alignas`.
805/// Returns `None` when the specifier contains a type expression rather than
806/// an integer literal (e.g. `alignas(double)` — handled elsewhere by the
807/// compiler; we skip those conservatively).
808fn parse_alignas_value(source: &str, node: Node<'_>) -> Option<usize> {
809    for i in 0..node.child_count() {
810        if let Some(child) = node.child(i) {
811            match child.kind() {
812                "number_literal" | "integer_literal" | "integer" => {
813                    let text = source[child.byte_range()].trim();
814                    if let Ok(n) = text.parse::<usize>() {
815                        return Some(n);
816                    }
817                    // Hex literal: 0x40
818                    if let Some(hex) = text.strip_prefix("0x").or_else(|| text.strip_prefix("0X")) {
819                        return usize::from_str_radix(hex, 16).ok();
820                    }
821                }
822                // Recurse for nested nodes (parenthesised expression, etc.)
823                "parenthesized_expression" | "argument_list" | "alignas_qualifier" => {
824                    if let r @ Some(_) = parse_alignas_value(source, child) {
825                        return r;
826                    }
827                }
828                _ => {}
829            }
830        }
831    }
832    None
833}
834
835/// Returns `(ty, field_name, guard, alignas_override)`.
836/// `alignas_override` is `Some(N)` when the field carries `alignas(N)`.
837/// Detect and parse an anonymous nested struct/union field declaration, e.g.:
838///
839/// ```c
840/// struct Packet {
841///     union {                    // ← anonymous nested union
842///         uint32_t raw;
843///         struct { uint8_t a; uint8_t b; uint8_t c; uint8_t d; };
844///     };
845///     uint64_t timestamp;
846/// };
847/// ```
848///
849/// A `field_declaration` is anonymous if it contains a `struct_specifier` or
850/// `union_specifier` child that has a `field_declaration_list` (i.e. a body)
851/// but no `type_identifier` (i.e. no name). The fields of the nested
852/// struct/union are flattened into the parent.
853///
854/// Returns `None` if the declaration is not an anonymous nested struct/union
855/// (the caller should fall through to `parse_field_declaration`).
856/// (field_name, type_text, guard, alignas_override, source_line_1based)
857type RawField = (String, String, Option<String>, Option<usize>, u32);
858
859#[allow(clippy::only_used_in_recursion)]
860fn parse_anonymous_nested(
861    source: &str,
862    node: Node<'_>,
863    arch: &'static ArchConfig,
864    parent_is_union: bool,
865) -> Option<Vec<RawField>> {
866    // Find a struct_specifier or union_specifier child.
867    for i in 0..node.child_count() {
868        let child = node.child(i)?;
869        if child.kind() != "struct_specifier" && child.kind() != "union_specifier" {
870            continue;
871        }
872        let nested_is_union = child.kind() == "union_specifier";
873
874        // Must have a body (field_declaration_list) but no type_identifier.
875        let mut has_name = false;
876        let mut body_node: Option<Node> = None;
877        for j in 0..child.child_count() {
878            let sub = child.child(j)?;
879            match sub.kind() {
880                "type_identifier" => has_name = true,
881                "field_declaration_list" => body_node = Some(sub),
882                _ => {}
883            }
884        }
885
886        if has_name || body_node.is_none() {
887            // Named struct/union used as a field type — handled by parse_field_declaration.
888            continue;
889        }
890
891        let body = body_node?;
892        let mut nested_raw: Vec<RawField> = Vec::new();
893
894        for j in 0..body.child_count() {
895            let inner = body.child(j)?;
896            if inner.kind() == "field_declaration" {
897                // Recurse to handle doubly-nested anonymous structs.
898                if let Some(deeper) = parse_anonymous_nested(source, inner, arch, nested_is_union) {
899                    nested_raw.extend(deeper);
900                } else if let Some((ty, fname, guard, al, ln)) =
901                    parse_field_declaration(source, inner)
902                {
903                    nested_raw.push((fname, ty, guard, al, ln));
904                }
905            }
906        }
907
908        // If nested is a union, the fields all share offset 0 (relative to the
909        // union's placement in the parent). We can't easily track this through
910        // raw field lists, so we emit them as a synthetic __anon_union_N field
911        // when the parent cares about offsets, or just flatten for unions.
912        //
913        // For simplicity: flatten all fields — the layout simulator will compute
914        // correct offsets if the parent is a struct, and union semantics are
915        // preserved when the parent is a union.
916        let _ = (nested_is_union, parent_is_union);
917
918        if !nested_raw.is_empty() {
919            return Some(nested_raw);
920        }
921    }
922    None
923}
924
925fn parse_field_declaration(source: &str, node: Node<'_>) -> Option<RawField> {
926    let mut ty_parts: Vec<String> = Vec::new();
927    let mut field_name: Option<String> = None;
928    // Bit-field width, e.g. `int flags : 3;` → Some("3")
929    let mut bit_width: Option<String> = None;
930    // Collect attribute text for guard extraction
931    let mut attr_text = String::new();
932    // Field-level alignas override
933    let mut alignas_override: Option<usize> = None;
934
935    for i in 0..node.child_count() {
936        let child = node.child(i)?;
937        match child.kind() {
938            "type_specifier" | "primitive_type" | "type_identifier" | "sized_type_specifier" => {
939                ty_parts.push(source[child.byte_range()].trim().to_string());
940            }
941            // C++ qualified types: std::mutex, ns::Type, etc.
942            // C++ template types:  std::atomic<uint64_t>, std::vector<int>, etc.
943            "qualified_identifier" | "template_type" => {
944                ty_parts.push(source[child.byte_range()].trim().to_string());
945            }
946            // Nested struct/union used as a field type: `struct Vec2 tl;`
947            // Extract just the type_identifier name (e.g. "Vec2") so the
948            // nested-struct resolution pass can match it by name.
949            "struct_specifier" | "union_specifier" => {
950                for j in 0..child.child_count() {
951                    if let Some(sub) = child.child(j)
952                        && sub.kind() == "type_identifier"
953                    {
954                        ty_parts.push(source[sub.byte_range()].trim().to_string());
955                        break;
956                    }
957                }
958            }
959            "field_identifier" => {
960                field_name = Some(source[child.byte_range()].trim().to_string());
961            }
962            "pointer_declarator" => {
963                field_name = extract_identifier(source, child);
964                ty_parts.push("*".to_string());
965            }
966            // Bit-field clause: `: N`  (tree-sitter-c/cpp node)
967            "bitfield_clause" => {
968                let text = source[child.byte_range()].trim();
969                // Strip leading ':' and whitespace to get just the width digits
970                bit_width = Some(text.trim_start_matches(':').trim().to_string());
971            }
972            // GNU attribute specifier: __attribute__((...))
973            "attribute_specifier" | "attribute" => {
974                attr_text.push_str(source[child.byte_range()].trim());
975                attr_text.push(' ');
976            }
977            // C++11 alignas: tree-sitter-cpp wraps it as type_qualifier → alignas_qualifier
978            // Also handle the direct form in case grammar versions differ.
979            "alignas_qualifier" | "alignas_specifier" => {
980                if alignas_override.is_none() {
981                    alignas_override = parse_alignas_value(source, child);
982                }
983            }
984            // type_qualifier wraps alignas_qualifier for field declarations:
985            // `alignas(8) char c;` → type_qualifier { alignas_qualifier { ... } }
986            "type_qualifier" => {
987                if alignas_override.is_none() {
988                    for j in 0..child.child_count() {
989                        if let Some(sub) = child.child(j)
990                            && (sub.kind() == "alignas_qualifier"
991                                || sub.kind() == "alignas_specifier")
992                        {
993                            alignas_override = parse_alignas_value(source, sub);
994                            break;
995                        }
996                    }
997                }
998            }
999            _ => {}
1000        }
1001    }
1002
1003    let base_ty = ty_parts.join(" ");
1004    let fname = field_name?;
1005    if base_ty.is_empty() {
1006        return None;
1007    }
1008    // Annotate bit-field types as "type:N" so callers can detect and report them;
1009    // `strip_bitfield_suffix` recovers the base type for size/align lookup.
1010    let ty = if let Some(w) = bit_width {
1011        format!("{base_ty}:{w}")
1012    } else {
1013        base_ty
1014    };
1015
1016    // Also check the full field source text (attribute_specifier may not always
1017    // be a direct child depending on tree-sitter grammar version).
1018    let field_src = source[node.byte_range()].to_string();
1019    let guard = extract_guard_from_c_field_text(&attr_text)
1020        .or_else(|| extract_guard_from_c_field_text(&field_src));
1021
1022    let line = node.start_position().row as u32 + 1;
1023    Some((ty, fname, guard, alignas_override, line))
1024}
1025
1026fn extract_identifier(source: &str, node: Node<'_>) -> Option<String> {
1027    if node.kind() == "field_identifier" || node.kind() == "identifier" {
1028        return Some(source[node.byte_range()].to_string());
1029    }
1030    for i in 0..node.child_count() {
1031        if let Some(child) = node.child(i)
1032            && let Some(name) = extract_identifier(source, child)
1033        {
1034            return Some(name);
1035        }
1036    }
1037    None
1038}
1039
1040// ── public API ────────────────────────────────────────────────────────────────
1041
1042pub fn parse_c(source: &str, arch: &'static ArchConfig) -> anyhow::Result<Vec<StructLayout>> {
1043    let mut parser = Parser::new();
1044    parser.set_language(&tree_sitter_c::LANGUAGE.into())?;
1045    let tree = parser
1046        .parse(source, None)
1047        .ok_or_else(|| anyhow::anyhow!("tree-sitter parse failed"))?;
1048    let mut layouts = Vec::new();
1049    extract_structs_from_tree(source, tree.root_node(), arch, &mut layouts);
1050    Ok(layouts)
1051}
1052
1053pub fn parse_cpp(source: &str, arch: &'static ArchConfig) -> anyhow::Result<Vec<StructLayout>> {
1054    let mut parser = Parser::new();
1055    parser.set_language(&tree_sitter_cpp::LANGUAGE.into())?;
1056    let tree = parser
1057        .parse(source, None)
1058        .ok_or_else(|| anyhow::anyhow!("tree-sitter parse failed"))?;
1059    let mut layouts = Vec::new();
1060    extract_structs_from_tree(source, tree.root_node(), arch, &mut layouts);
1061    Ok(layouts)
1062}
1063
1064// ── tests ─────────────────────────────────────────────────────────────────────
1065
1066#[cfg(test)]
1067mod tests {
1068    use super::*;
1069    use padlock_core::arch::X86_64_SYSV;
1070
1071    #[test]
1072    fn parse_simple_c_struct() {
1073        let src = r#"
1074struct Point {
1075    int x;
1076    int y;
1077};
1078"#;
1079        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1080        assert_eq!(layouts.len(), 1);
1081        assert_eq!(layouts[0].name, "Point");
1082        assert_eq!(layouts[0].fields.len(), 2);
1083        assert_eq!(layouts[0].fields[0].name, "x");
1084        assert_eq!(layouts[0].fields[1].name, "y");
1085    }
1086
1087    #[test]
1088    fn parse_typedef_struct() {
1089        let src = r#"
1090typedef struct {
1091    char  is_active;
1092    double timeout;
1093    int   port;
1094} Connection;
1095"#;
1096        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1097        assert_eq!(layouts.len(), 1);
1098        assert_eq!(layouts[0].name, "Connection");
1099        assert_eq!(layouts[0].fields.len(), 3);
1100    }
1101
1102    #[test]
1103    fn c_layout_computes_offsets() {
1104        let src = "struct T { char a; double b; };";
1105        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1106        assert_eq!(layouts.len(), 1);
1107        let layout = &layouts[0];
1108        // char at offset 0, double at offset 8 (7 bytes padding)
1109        assert_eq!(layout.fields[0].offset, 0);
1110        assert_eq!(layout.fields[1].offset, 8);
1111        assert_eq!(layout.total_size, 16);
1112    }
1113
1114    #[test]
1115    fn c_layout_detects_padding() {
1116        let src = "struct T { char a; int b; };";
1117        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1118        let gaps = padlock_core::ir::find_padding(&layouts[0]);
1119        assert!(!gaps.is_empty());
1120        assert_eq!(gaps[0].bytes, 3); // 3 bytes padding between char and int
1121    }
1122
1123    #[test]
1124    fn parse_cpp_struct() {
1125        let src = "struct Vec3 { float x; float y; float z; };";
1126        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1127        assert_eq!(layouts.len(), 1);
1128        assert_eq!(layouts[0].fields.len(), 3);
1129    }
1130
1131    // ── SIMD types ────────────────────────────────────────────────────────────
1132
1133    #[test]
1134    fn simd_sse_field_size_and_align() {
1135        let src = "struct Vecs { __m128 a; __m256 b; };";
1136        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1137        assert_eq!(layouts.len(), 1);
1138        let f = &layouts[0].fields;
1139        assert_eq!(f[0].size, 16); // __m128
1140        assert_eq!(f[0].align, 16);
1141        assert_eq!(f[1].size, 32); // __m256
1142        assert_eq!(f[1].align, 32);
1143    }
1144
1145    #[test]
1146    fn simd_avx512_size() {
1147        let src = "struct Wide { __m512 v; };";
1148        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1149        assert_eq!(layouts[0].fields[0].size, 64);
1150        assert_eq!(layouts[0].fields[0].align, 64);
1151    }
1152
1153    #[test]
1154    fn simd_padding_detected_when_small_field_before_avx() {
1155        // char(1) + [31 pad] + __m256(32) = 64 bytes, 31 wasted
1156        let src = "struct Mixed { char flag; __m256 data; };";
1157        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1158        let gaps = padlock_core::ir::find_padding(&layouts[0]);
1159        assert!(!gaps.is_empty());
1160        assert_eq!(gaps[0].bytes, 31);
1161    }
1162
1163    // ── union parsing ─────────────────────────────────────────────────────────
1164
1165    #[test]
1166    fn union_fields_all_at_offset_zero() {
1167        let src = "union Data { int i; float f; double d; };";
1168        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1169        assert_eq!(layouts.len(), 1);
1170        let u = &layouts[0];
1171        assert!(u.is_union);
1172        for field in &u.fields {
1173            assert_eq!(
1174                field.offset, 0,
1175                "union field '{}' should be at offset 0",
1176                field.name
1177            );
1178        }
1179    }
1180
1181    #[test]
1182    fn union_total_size_is_max_field() {
1183        // double is the largest (8 bytes); total should be 8
1184        let src = "union Data { int i; float f; double d; };";
1185        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1186        assert_eq!(layouts[0].total_size, 8);
1187    }
1188
1189    #[test]
1190    fn union_no_padding_finding() {
1191        let src = "union Data { int i; double d; };";
1192        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1193        let report = padlock_core::findings::Report::from_layouts(&layouts);
1194        let sr = &report.structs[0];
1195        assert!(
1196            !sr.findings
1197                .iter()
1198                .any(|f| matches!(f, padlock_core::findings::Finding::PaddingWaste { .. }))
1199        );
1200        assert!(
1201            !sr.findings
1202                .iter()
1203                .any(|f| matches!(f, padlock_core::findings::Finding::ReorderSuggestion { .. }))
1204        );
1205    }
1206
1207    #[test]
1208    fn typedef_union_parsed() {
1209        let src = "typedef union { int a; double b; } Value;";
1210        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1211        assert_eq!(layouts.len(), 1);
1212        assert_eq!(layouts[0].name, "Value");
1213        assert!(layouts[0].is_union);
1214    }
1215
1216    // ── attribute guard extraction ─────────────────────────────────────────────
1217
1218    #[test]
1219    fn extract_guard_from_c_guarded_by_macro() {
1220        let text = "int value GUARDED_BY(mu);";
1221        let guard = extract_guard_from_c_field_text(text);
1222        assert_eq!(guard.as_deref(), Some("mu"));
1223    }
1224
1225    #[test]
1226    fn extract_guard_from_c_attribute_specifier() {
1227        let text = "__attribute__((guarded_by(counter_lock))) uint64_t counter;";
1228        let guard = extract_guard_from_c_field_text(text);
1229        assert_eq!(guard.as_deref(), Some("counter_lock"));
1230    }
1231
1232    #[test]
1233    fn extract_guard_pt_guarded_by() {
1234        let text = "int *ptr PT_GUARDED_BY(ptr_lock);";
1235        let guard = extract_guard_from_c_field_text(text);
1236        assert_eq!(guard.as_deref(), Some("ptr_lock"));
1237    }
1238
1239    #[test]
1240    fn no_guard_returns_none() {
1241        let guard = extract_guard_from_c_field_text("int x;");
1242        assert!(guard.is_none());
1243    }
1244
1245    #[test]
1246    fn c_struct_guarded_by_sets_concurrent_access() {
1247        // Using GUARDED_BY macro style in comments/text — tree-sitter won't parse
1248        // macro expansions, so test the text-extraction path via parse_field_declaration
1249        // indirectly by checking extract_guard_from_c_field_text.
1250        let text = "uint64_t readers GUARDED_BY(lock_a);";
1251        assert_eq!(
1252            extract_guard_from_c_field_text(text).as_deref(),
1253            Some("lock_a")
1254        );
1255    }
1256
1257    #[test]
1258    fn c_struct_different_guards_detected_as_false_sharing() {
1259        use padlock_core::arch::X86_64_SYSV;
1260        use padlock_core::ir::{AccessPattern, Field, StructLayout, TypeInfo};
1261
1262        // Manually build a layout with two fields on the same cache line,
1263        // different guards — mirrors what the C frontend would produce for
1264        // __attribute__((guarded_by(...))) annotated fields.
1265        let mut layout = StructLayout {
1266            name: "S".into(),
1267            total_size: 128,
1268            align: 8,
1269            fields: vec![
1270                Field {
1271                    name: "readers".into(),
1272                    ty: TypeInfo::Primitive {
1273                        name: "uint64_t".into(),
1274                        size: 8,
1275                        align: 8,
1276                    },
1277                    offset: 0,
1278                    size: 8,
1279                    align: 8,
1280                    source_file: None,
1281                    source_line: None,
1282                    access: AccessPattern::Concurrent {
1283                        guard: Some("lock_a".into()),
1284                        is_atomic: false,
1285                    },
1286                },
1287                Field {
1288                    name: "writers".into(),
1289                    ty: TypeInfo::Primitive {
1290                        name: "uint64_t".into(),
1291                        size: 8,
1292                        align: 8,
1293                    },
1294                    offset: 8,
1295                    size: 8,
1296                    align: 8,
1297                    source_file: None,
1298                    source_line: None,
1299                    access: AccessPattern::Concurrent {
1300                        guard: Some("lock_b".into()),
1301                        is_atomic: false,
1302                    },
1303                },
1304            ],
1305            source_file: None,
1306            source_line: None,
1307            arch: &X86_64_SYSV,
1308            is_packed: false,
1309            is_union: false,
1310            is_repr_rust: false,
1311            suppressed_findings: Vec::new(),
1312        };
1313        assert!(padlock_core::analysis::false_sharing::has_false_sharing(
1314            &layout
1315        ));
1316        // Same guard → no false sharing
1317        layout.fields[1].access = AccessPattern::Concurrent {
1318            guard: Some("lock_a".into()),
1319            is_atomic: false,
1320        };
1321        assert!(!padlock_core::analysis::false_sharing::has_false_sharing(
1322            &layout
1323        ));
1324    }
1325
1326    // ── C++ class: vtable pointer ─────────────────────────────────────────────
1327
1328    #[test]
1329    fn cpp_class_with_virtual_method_has_vptr() {
1330        let src = r#"
1331class Widget {
1332    virtual void draw();
1333    int x;
1334    int y;
1335};
1336"#;
1337        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1338        assert_eq!(layouts.len(), 1);
1339        let l = &layouts[0];
1340        // First field must be __vptr
1341        assert_eq!(l.fields[0].name, "__vptr");
1342        assert_eq!(l.fields[0].size, 8); // pointer on x86_64
1343        // __vptr is at offset 0
1344        assert_eq!(l.fields[0].offset, 0);
1345        // int x should come after the pointer (at offset 8)
1346        let x = l.fields.iter().find(|f| f.name == "x").unwrap();
1347        assert_eq!(x.offset, 8);
1348    }
1349
1350    #[test]
1351    fn cpp_class_without_virtual_has_no_vptr() {
1352        let src = "class Plain { int a; int b; };";
1353        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1354        assert_eq!(layouts.len(), 1);
1355        assert!(!layouts[0].fields.iter().any(|f| f.name == "__vptr"));
1356    }
1357
1358    #[test]
1359    fn cpp_struct_keyword_with_virtual_has_vptr() {
1360        // `struct` in C++ can also have virtual methods
1361        let src = "struct IFoo { virtual ~IFoo(); virtual void bar(); };";
1362        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1363        // struct_specifier doesn't go through parse_class_specifier, so no __vptr
1364        // (vtable injection is only for `class` nodes)
1365        let _ = layouts; // just verify it parses without panic
1366    }
1367
1368    // ── C++ class: single inheritance ─────────────────────────────────────────
1369
1370    #[test]
1371    fn cpp_derived_class_has_base_slot() {
1372        let src = r#"
1373class Base {
1374    int x;
1375};
1376class Derived : public Base {
1377    int y;
1378};
1379"#;
1380        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1381        // Both Base and Derived should be parsed
1382        let derived = layouts.iter().find(|l| l.name == "Derived").unwrap();
1383        // Derived must have a __base_Base synthetic field
1384        assert!(
1385            derived.fields.iter().any(|f| f.name == "__base_Base"),
1386            "Derived should have a __base_Base field"
1387        );
1388        // The y field should come after __base_Base
1389        let base_field = derived
1390            .fields
1391            .iter()
1392            .find(|f| f.name == "__base_Base")
1393            .unwrap();
1394        let y_field = derived.fields.iter().find(|f| f.name == "y").unwrap();
1395        assert!(y_field.offset >= base_field.offset + base_field.size);
1396    }
1397
1398    #[test]
1399    fn cpp_class_multiple_inheritance_has_multiple_base_slots() {
1400        let src = r#"
1401class A { int a; };
1402class B { int b; };
1403class C : public A, public B { int c; };
1404"#;
1405        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1406        let c = layouts.iter().find(|l| l.name == "C").unwrap();
1407        assert!(c.fields.iter().any(|f| f.name == "__base_A"));
1408        assert!(c.fields.iter().any(|f| f.name == "__base_B"));
1409    }
1410
1411    #[test]
1412    fn cpp_virtual_base_class_total_size_accounts_for_vptr() {
1413        // class with virtual method: size = sizeof(__vptr) + member fields + padding
1414        let src = "class V { virtual void f(); int x; };";
1415        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1416        let l = &layouts[0];
1417        // __vptr(8) + int(4) + 4 pad = 16 bytes on x86_64
1418        assert_eq!(l.total_size, 16);
1419    }
1420
1421    // ── bitfield handling ─────────────────────────────────────────────────────
1422
1423    #[test]
1424    fn is_bitfield_type_detects_colon_n() {
1425        assert!(is_bitfield_type("int:3"));
1426        assert!(is_bitfield_type("unsigned int:16"));
1427        assert!(is_bitfield_type("uint32_t:1"));
1428        // Not bit-fields — contains ':' but not followed by pure digits
1429        assert!(!is_bitfield_type("std::atomic<int>"));
1430        assert!(!is_bitfield_type("ns::Type"));
1431        assert!(!is_bitfield_type("int"));
1432    }
1433
1434    #[test]
1435    fn struct_with_bitfields_is_skipped() {
1436        // Bit-field layout is compiler-controlled and cannot be accurately modelled
1437        // without a compiler. The struct must be skipped entirely.
1438        let src = r#"
1439struct Flags {
1440    unsigned int active : 1;
1441    unsigned int ready  : 1;
1442    unsigned int error  : 6;
1443    int value;
1444};
1445"#;
1446        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1447        // Flags must not appear — its layout cannot be accurately computed.
1448        assert!(
1449            layouts.iter().all(|l| l.name != "Flags"),
1450            "struct with bitfields should be skipped; got {:?}",
1451            layouts.iter().map(|l| &l.name).collect::<Vec<_>>()
1452        );
1453    }
1454
1455    #[test]
1456    fn struct_without_bitfields_is_still_parsed() {
1457        // Ensure the bitfield guard doesn't affect normal structs.
1458        let src = "struct Normal { int a; char b; double c; };";
1459        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1460        assert_eq!(layouts.len(), 1);
1461        assert_eq!(layouts[0].name, "Normal");
1462    }
1463
1464    #[test]
1465    fn c_struct_fields_have_source_lines() {
1466        let src = "struct Point {\n    int x;\n    int y;\n};";
1467        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1468        assert_eq!(layouts.len(), 1);
1469        let fields = &layouts[0].fields;
1470        // x is on line 2, y is on line 3
1471        assert_eq!(fields[0].source_line, Some(2), "x should be line 2");
1472        assert_eq!(fields[1].source_line, Some(3), "y should be line 3");
1473    }
1474
1475    #[test]
1476    fn cpp_class_with_bitfields_is_skipped() {
1477        let src = "class Packed { int x : 4; int y : 4; };";
1478        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1479        assert!(
1480            layouts.iter().all(|l| l.name != "Packed"),
1481            "C++ class with bitfields should be skipped"
1482        );
1483    }
1484
1485    #[test]
1486    fn all_bitfield_struct_is_skipped() {
1487        // Struct with ONLY bit-field members (no normal fields).
1488        // raw_fields is non-empty but all entries carry the `:N` annotation,
1489        // so the bit-field guard must still fire and skip the struct.
1490        let src = "struct BitPacked { int x:4; int y:4; };";
1491        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1492        assert!(
1493            layouts.iter().all(|l| l.name != "BitPacked"),
1494            "all-bitfield struct should be skipped; got {:?}",
1495            layouts.iter().map(|l| &l.name).collect::<Vec<_>>()
1496        );
1497    }
1498
1499    // ── __attribute__((packed)) detection ─────────────────────────────────────
1500
1501    #[test]
1502    fn packed_struct_has_no_alignment_padding() {
1503        // Without packed: char(1) + 3-byte pad + int(4) + char(1) + 3-byte pad = 12 bytes
1504        // With packed:    char(1) + int(4) + char(1) = 6 bytes, align=1
1505        let src = r#"
1506struct __attribute__((packed)) Tight {
1507    char a;
1508    int  b;
1509    char c;
1510};
1511"#;
1512        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1513        let l = layouts.iter().find(|l| l.name == "Tight").expect("Tight");
1514        assert!(l.is_packed, "should be marked is_packed");
1515        assert_eq!(l.total_size, 6, "packed: no padding inserted");
1516        assert_eq!(l.fields[0].offset, 0);
1517        assert_eq!(l.fields[1].offset, 1); // immediately after char
1518        assert_eq!(l.fields[2].offset, 5);
1519    }
1520
1521    #[test]
1522    fn non_packed_struct_has_normal_alignment_padding() {
1523        // Confirm baseline: same struct without __attribute__((packed)) gets padded
1524        let src = r#"
1525struct Normal {
1526    char a;
1527    int  b;
1528    char c;
1529};
1530"#;
1531        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1532        let l = layouts.iter().find(|l| l.name == "Normal").expect("Normal");
1533        assert!(!l.is_packed);
1534        assert_eq!(l.total_size, 12);
1535        assert_eq!(l.fields[1].offset, 4); // aligned to 4
1536    }
1537
1538    #[test]
1539    fn cpp_class_packed_attribute_detected() {
1540        let src = r#"
1541class __attribute__((packed)) Dense {
1542    char a;
1543    int  b;
1544};
1545"#;
1546        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1547        let l = layouts.iter().find(|l| l.name == "Dense").expect("Dense");
1548        assert!(
1549            l.is_packed,
1550            "C++ class with __attribute__((packed)) must be marked packed"
1551        );
1552        assert_eq!(l.total_size, 5); // char(1) + int(4), no padding
1553    }
1554
1555    // ── alignas detection ─────────────────────────────────────────────────────
1556
1557    #[test]
1558    fn field_alignas_overrides_natural_alignment() {
1559        // char is normally align=1 but alignas(8) forces it to align-8.
1560        // Layout: c(1B at offset 0, align=8) + x(4B at offset 4, align=4)
1561        // c must start on an 8-byte boundary (trivially satisfied at offset 0).
1562        // After c (1 byte), x aligns to 4: offset = 1.next_multiple_of(4) = 4.
1563        // Struct align = max(8, 4) = 8. Total = 8 bytes (4+4 → 8 → ok for align 8).
1564        let src = r#"
1565struct S {
1566    alignas(8) char c;
1567    int x;
1568};
1569"#;
1570        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1571        let l = layouts.iter().find(|l| l.name == "S").expect("S");
1572        // c should be forced to align 8
1573        let c_field = l.fields.iter().find(|f| f.name == "c").unwrap();
1574        assert_eq!(c_field.align, 8);
1575        // x comes after c (1 byte) with natural alignment 4 → offset 4
1576        let x_field = l.fields.iter().find(|f| f.name == "x").unwrap();
1577        assert_eq!(x_field.offset, 4);
1578        // Struct alignment is max(alignas(8), int align 4) = 8
1579        assert_eq!(l.align, 8);
1580        // Total = 8 bytes (x at 4, size 4; 4+4=8; 8 is multiple of align 8)
1581        assert_eq!(l.total_size, 8);
1582    }
1583
1584    #[test]
1585    fn struct_level_alignas_increases_struct_alignment() {
1586        // alignas(64) on the struct means its alignment requirement is 64.
1587        // Total size must be a multiple of 64.
1588        let src = r#"
1589struct alignas(64) CacheLine {
1590    int x;
1591    int y;
1592};
1593"#;
1594        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1595        let l = layouts
1596            .iter()
1597            .find(|l| l.name == "CacheLine")
1598            .expect("CacheLine");
1599        assert_eq!(l.align, 64);
1600        assert_eq!(l.total_size % 64, 0);
1601    }
1602
1603    #[test]
1604    fn alignas_on_field_smaller_than_natural_is_ignored() {
1605        // alignas(1) on an int field: does NOT reduce alignment below 4.
1606        // In C++, alignas cannot reduce alignment below the natural alignment.
1607        // Our implementation stores the alignas value; natural alignment wins
1608        // because we take max(alignas, natural) in the caller.
1609        // Note: we currently store alignas directly; this test documents behaviour.
1610        let src = "struct S { int x; int y; };";
1611        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1612        let l = &layouts[0];
1613        assert_eq!(l.fields[0].align, 4); // natural alignment, not reduced
1614    }
1615
1616    #[test]
1617    fn cpp_class_alignas_detected() {
1618        let src = r#"
1619class alignas(32) Aligned {
1620    double x;
1621    double y;
1622};
1623"#;
1624        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1625        let l = layouts
1626            .iter()
1627            .find(|l| l.name == "Aligned")
1628            .expect("Aligned");
1629        assert_eq!(l.align, 32);
1630        assert_eq!(l.total_size % 32, 0);
1631    }
1632
1633    // ── bad weather: alignas edge cases ───────────────────────────────────────
1634
1635    #[test]
1636    fn struct_without_alignas_unchanged() {
1637        // Ensure the alignas detection path doesn't affect structs without it
1638        let src = "struct Plain { int a; char b; };";
1639        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1640        let l = &layouts[0];
1641        assert_eq!(l.align, 4); // max field alignment = int = 4
1642        assert_eq!(l.total_size, 8); // int(4) + char(1) + 3 pad
1643    }
1644
1645    // ── anonymous nested structs/unions ───────────────────────────────────────
1646
1647    #[test]
1648    fn anonymous_nested_union_fields_flattened() {
1649        let src = r#"
1650struct Packet {
1651    union {
1652        uint32_t raw;
1653        uint8_t bytes[4];
1654    };
1655    uint64_t timestamp;
1656};
1657"#;
1658        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1659        let l = layouts.iter().find(|l| l.name == "Packet").expect("Packet");
1660        // raw, bytes (or similar) and timestamp must all be present
1661        assert!(
1662            l.fields.iter().any(|f| f.name == "raw"),
1663            "raw field must be flattened into Packet"
1664        );
1665        assert!(
1666            l.fields.iter().any(|f| f.name == "timestamp"),
1667            "timestamp must be present"
1668        );
1669    }
1670
1671    #[test]
1672    fn anonymous_nested_struct_fields_flattened() {
1673        let src = r#"
1674struct Outer {
1675    struct {
1676        int x;
1677        int y;
1678    };
1679    double z;
1680};
1681"#;
1682        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1683        let l = layouts.iter().find(|l| l.name == "Outer").expect("Outer");
1684        assert!(
1685            l.fields.iter().any(|f| f.name == "x"),
1686            "x must be flattened"
1687        );
1688        assert!(
1689            l.fields.iter().any(|f| f.name == "y"),
1690            "y must be flattened"
1691        );
1692        assert!(l.fields.iter().any(|f| f.name == "z"), "z present");
1693        // Total: x(4) + y(4) + z(8) = 16 bytes, no padding
1694        assert_eq!(l.total_size, 16);
1695    }
1696
1697    #[test]
1698    fn named_nested_struct_not_flattened() {
1699        // A named struct used as a field type must NOT be flattened
1700        let src = r#"
1701struct Vec2 { float x; float y; };
1702struct Rect { struct Vec2 tl; struct Vec2 br; };
1703"#;
1704        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1705        let rect = layouts.iter().find(|l| l.name == "Rect").expect("Rect");
1706        // Should have tl and br as opaque fields, not x/y flattened
1707        assert_eq!(rect.fields.len(), 2);
1708        assert!(rect.fields.iter().any(|f| f.name == "tl"));
1709        assert!(rect.fields.iter().any(|f| f.name == "br"));
1710    }
1711
1712    // ── type-table tests ──────────────────────────────────────────────────────
1713
1714    #[test]
1715    fn linux_kernel_types_correct_size() {
1716        // u8/u16/u32/u64 and s8/s16/s32/s64 (linux/types.h)
1717        assert_eq!(c_type_size_align("u8", &X86_64_SYSV), (1, 1));
1718        assert_eq!(c_type_size_align("u16", &X86_64_SYSV), (2, 2));
1719        assert_eq!(c_type_size_align("u32", &X86_64_SYSV), (4, 4));
1720        assert_eq!(c_type_size_align("u64", &X86_64_SYSV), (8, 8));
1721        assert_eq!(c_type_size_align("s8", &X86_64_SYSV), (1, 1));
1722        assert_eq!(c_type_size_align("s16", &X86_64_SYSV), (2, 2));
1723        assert_eq!(c_type_size_align("s32", &X86_64_SYSV), (4, 4));
1724        assert_eq!(c_type_size_align("s64", &X86_64_SYSV), (8, 8));
1725    }
1726
1727    #[test]
1728    fn linux_kernel_dunder_types_correct_size() {
1729        assert_eq!(c_type_size_align("__u8", &X86_64_SYSV), (1, 1));
1730        assert_eq!(c_type_size_align("__u16", &X86_64_SYSV), (2, 2));
1731        assert_eq!(c_type_size_align("__u32", &X86_64_SYSV), (4, 4));
1732        assert_eq!(c_type_size_align("__u64", &X86_64_SYSV), (8, 8));
1733        assert_eq!(c_type_size_align("__s8", &X86_64_SYSV), (1, 1));
1734        assert_eq!(c_type_size_align("__s64", &X86_64_SYSV), (8, 8));
1735        // Endian-annotated types are same width as their base
1736        assert_eq!(c_type_size_align("__be16", &X86_64_SYSV), (2, 2));
1737        assert_eq!(c_type_size_align("__le32", &X86_64_SYSV), (4, 4));
1738        assert_eq!(c_type_size_align("__be64", &X86_64_SYSV), (8, 8));
1739    }
1740
1741    #[test]
1742    fn c99_fast_types_correct_size() {
1743        // fast8/16 are their natural width
1744        assert_eq!(c_type_size_align("uint_fast8_t", &X86_64_SYSV), (1, 1));
1745        assert_eq!(c_type_size_align("uint_fast16_t", &X86_64_SYSV), (2, 2));
1746        // fast32/64 are pointer-sized on 64-bit
1747        assert_eq!(c_type_size_align("uint_fast32_t", &X86_64_SYSV), (8, 8));
1748        assert_eq!(c_type_size_align("uint_fast64_t", &X86_64_SYSV), (8, 8));
1749        // least types are their minimum guaranteed width
1750        assert_eq!(c_type_size_align("uint_least8_t", &X86_64_SYSV), (1, 1));
1751        assert_eq!(c_type_size_align("uint_least32_t", &X86_64_SYSV), (4, 4));
1752        assert_eq!(c_type_size_align("uint_least64_t", &X86_64_SYSV), (8, 8));
1753        assert_eq!(c_type_size_align("intmax_t", &X86_64_SYSV), (8, 8));
1754        assert_eq!(c_type_size_align("uintmax_t", &X86_64_SYSV), (8, 8));
1755    }
1756
1757    #[test]
1758    fn gcc_int128_correct_size() {
1759        assert_eq!(c_type_size_align("__int128", &X86_64_SYSV), (16, 16));
1760        assert_eq!(c_type_size_align("__uint128", &X86_64_SYSV), (16, 16));
1761        assert_eq!(c_type_size_align("__int128_t", &X86_64_SYSV), (16, 16));
1762        // unsigned __int128 — "unsigned " prefix is stripped, then __int128 matched
1763        assert_eq!(
1764            c_type_size_align("unsigned __int128", &X86_64_SYSV),
1765            (16, 16)
1766        );
1767    }
1768
1769    #[test]
1770    fn windows_types_correct_size() {
1771        assert_eq!(c_type_size_align("BYTE", &X86_64_SYSV), (1, 1));
1772        assert_eq!(c_type_size_align("WORD", &X86_64_SYSV), (2, 2));
1773        assert_eq!(c_type_size_align("DWORD", &X86_64_SYSV), (4, 4));
1774        assert_eq!(c_type_size_align("QWORD", &X86_64_SYSV), (8, 8));
1775        assert_eq!(c_type_size_align("BOOL", &X86_64_SYSV), (4, 4));
1776        assert_eq!(c_type_size_align("UINT8", &X86_64_SYSV), (1, 1));
1777        assert_eq!(c_type_size_align("INT32", &X86_64_SYSV), (4, 4));
1778        assert_eq!(c_type_size_align("UINT64", &X86_64_SYSV), (8, 8));
1779        assert_eq!(c_type_size_align("HANDLE", &X86_64_SYSV), (8, 8));
1780        assert_eq!(c_type_size_align("LPVOID", &X86_64_SYSV), (8, 8));
1781    }
1782
1783    #[test]
1784    fn char_types_correct_size() {
1785        assert_eq!(c_type_size_align("wchar_t", &X86_64_SYSV), (4, 4));
1786        assert_eq!(c_type_size_align("char8_t", &X86_64_SYSV), (1, 1));
1787        assert_eq!(c_type_size_align("char16_t", &X86_64_SYSV), (2, 2));
1788        assert_eq!(c_type_size_align("char32_t", &X86_64_SYSV), (4, 4));
1789    }
1790
1791    #[test]
1792    fn half_precision_types_correct_size() {
1793        assert_eq!(c_type_size_align("_Float16", &X86_64_SYSV), (2, 2));
1794        assert_eq!(c_type_size_align("__fp16", &X86_64_SYSV), (2, 2));
1795        assert_eq!(c_type_size_align("__bf16", &X86_64_SYSV), (2, 2));
1796        assert_eq!(c_type_size_align("_Float128", &X86_64_SYSV), (16, 16));
1797    }
1798
1799    #[test]
1800    fn unsigned_prefix_stripped_correctly() {
1801        // "unsigned short" → "short" → (2, 2)
1802        assert_eq!(c_type_size_align("unsigned short", &X86_64_SYSV), (2, 2));
1803        assert_eq!(c_type_size_align("unsigned int", &X86_64_SYSV), (4, 4));
1804        assert_eq!(
1805            c_type_size_align("unsigned long long", &X86_64_SYSV),
1806            (8, 8)
1807        );
1808        assert_eq!(
1809            c_type_size_align("long int", &X86_64_SYSV),
1810            (X86_64_SYSV.pointer_size, X86_64_SYSV.pointer_size)
1811        );
1812    }
1813
1814    #[test]
1815    fn linux_kernel_struct_with_new_types() {
1816        // Representative kernel-style struct using __u32, __be16, u8
1817        let src = r#"
1818struct NetHeader {
1819    __be32 src_ip;
1820    __be32 dst_ip;
1821    __be16 src_port;
1822    __be16 dst_port;
1823    u8     protocol;
1824    u8     ttl;
1825};
1826"#;
1827        let layouts = parse_c(src, &X86_64_SYSV).unwrap();
1828        assert_eq!(layouts.len(), 1);
1829        let l = &layouts[0];
1830        // 4+4+2+2+1+1 = 14B; max align is 4 (__be32) → padded to 16B
1831        assert_eq!(l.total_size, 16);
1832        assert_eq!(l.fields[0].size, 4); // __be32 src_ip
1833        assert_eq!(l.fields[2].size, 2); // __be16 src_port
1834        assert_eq!(l.fields[4].size, 1); // u8 protocol
1835    }
1836
1837    // ── C++ stdlib type tests ─────────────────────────────────────────────────
1838
1839    #[test]
1840    fn cpp_string_is_32_bytes() {
1841        assert_eq!(c_type_size_align("std::string", &X86_64_SYSV), (32, 8));
1842        assert_eq!(c_type_size_align("std::wstring", &X86_64_SYSV), (32, 8));
1843    }
1844
1845    #[test]
1846    fn cpp_string_view_is_two_words() {
1847        assert_eq!(c_type_size_align("std::string_view", &X86_64_SYSV), (16, 8));
1848    }
1849
1850    #[test]
1851    fn cpp_vector_is_24_bytes() {
1852        assert_eq!(c_type_size_align("std::vector<int>", &X86_64_SYSV), (24, 8));
1853        assert_eq!(
1854            c_type_size_align("std::vector<uint64_t>", &X86_64_SYSV),
1855            (24, 8)
1856        );
1857        // Size is independent of T
1858        assert_eq!(
1859            c_type_size_align("std::vector<std::string>", &X86_64_SYSV),
1860            (24, 8)
1861        );
1862    }
1863
1864    #[test]
1865    fn cpp_smart_pointers_correct_size() {
1866        // unique_ptr: single pointer
1867        assert_eq!(
1868            c_type_size_align("std::unique_ptr<int>", &X86_64_SYSV),
1869            (8, 8)
1870        );
1871        // shared_ptr / weak_ptr: two pointers
1872        assert_eq!(
1873            c_type_size_align("std::shared_ptr<int>", &X86_64_SYSV),
1874            (16, 8)
1875        );
1876        assert_eq!(
1877            c_type_size_align("std::weak_ptr<int>", &X86_64_SYSV),
1878            (16, 8)
1879        );
1880    }
1881
1882    #[test]
1883    fn cpp_optional_recursive_size() {
1884        // std::optional<bool>: 1B (bool) + 1B (has_value flag) → 2B
1885        assert_eq!(
1886            c_type_size_align("std::optional<bool>", &X86_64_SYSV),
1887            (2, 1)
1888        );
1889        // std::optional<int>: 4B + 1B → padded to 4B → 8B total? Let's check:
1890        // t_size=4, t_align=4; (4+1).next_multiple_of(4) = 8
1891        assert_eq!(
1892            c_type_size_align("std::optional<int>", &X86_64_SYSV),
1893            (8, 4)
1894        );
1895        // std::optional<double>: 8B + 1B → padded to 8B → 16B
1896        assert_eq!(
1897            c_type_size_align("std::optional<double>", &X86_64_SYSV),
1898            (16, 8)
1899        );
1900    }
1901
1902    #[test]
1903    fn cpp_function_is_32_bytes() {
1904        assert_eq!(
1905            c_type_size_align("std::function<void()>", &X86_64_SYSV),
1906            (32, 8)
1907        );
1908        assert_eq!(
1909            c_type_size_align("std::function<int(int)>", &X86_64_SYSV),
1910            (32, 8)
1911        );
1912    }
1913
1914    #[test]
1915    fn cpp_stdlib_struct_with_string_field() {
1916        // A struct with std::string fields — used to get pointer-size (8B), now 32B
1917        let src = r#"
1918struct Config {
1919    std::string name;
1920    int         version;
1921    bool        enabled;
1922};
1923"#;
1924        let layouts = parse_cpp(src, &X86_64_SYSV).unwrap();
1925        let l = &layouts[0];
1926        assert_eq!(l.fields[0].size, 32); // std::string, not 8
1927        // int at offset 32, bool at 36; total padded to 8-byte align = 40
1928        assert_eq!(l.fields[1].offset, 32);
1929        assert_eq!(l.fields[1].size, 4);
1930    }
1931}