padlock-core 0.10.0

Core IR, analysis passes, and findings for the padlock struct layout analyzer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//padlock-core/src/ir.rs

pub use crate::arch::{ArchConfig, X86_64_SYSV};

/// Serde helpers for serializing/deserializing `&'static ArchConfig` by name.
mod arch_serde {
    use crate::arch::{ArchConfig, arch_by_name};
    use serde::{Deserialize, Deserializer, Serializer};

    pub fn serialize<S: Serializer>(arch: &&'static ArchConfig, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(arch.name)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<&'static ArchConfig, D::Error> {
        let name = String::deserialize(d)?;
        arch_by_name(&name).ok_or_else(|| {
            serde::de::Error::custom(format!(
                "unknown arch {name:?} in cache; \
                 clear it with `rm -rf .padlock-cache`"
            ))
        })
    }
}

/// The type of a single field. Recursive for nested structs.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum TypeInfo {
    Primitive {
        name: String,
        size: usize,
        align: usize,
    },
    Pointer {
        size: usize,
        align: usize,
    },
    Array {
        element: Box<TypeInfo>,
        count: usize,
        size: usize,
        align: usize,
    },
    Struct(Box<StructLayout>),
    Opaque {
        name: String,
        size: usize,
        align: usize,
    },
}

impl TypeInfo {
    pub fn size(&self) -> usize {
        match self {
            TypeInfo::Primitive { size, .. } => *size,
            TypeInfo::Pointer { size, .. } => *size,
            TypeInfo::Array { size, .. } => *size,
            TypeInfo::Struct(l) => l.total_size,
            TypeInfo::Opaque { size, .. } => *size,
        }
    }

    pub fn align(&self) -> usize {
        match self {
            TypeInfo::Primitive { align, .. } => *align,
            TypeInfo::Pointer { align, .. } => *align,
            TypeInfo::Array { align, .. } => *align,
            TypeInfo::Struct(l) => l.align,
            TypeInfo::Opaque { align, .. } => *align,
        }
    }
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum AccessPattern {
    Unknown,
    Concurrent {
        guard: Option<String>,
        is_atomic: bool,
        /// True when this pattern was set by an explicit source annotation
        /// (e.g. `GUARDED_BY`, `#[lock_protected_by]`, `// padlock:guard=`).
        /// False when inferred from the field's type name by the heuristic pass.
        #[serde(default)]
        is_annotated: bool,
    },
    ReadMostly,
    Padding,
}

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Field {
    pub name: String,
    pub ty: TypeInfo,
    pub offset: usize,
    pub size: usize,
    pub align: usize,
    pub source_file: Option<String>,
    pub source_line: Option<u32>,
    pub access: AccessPattern,
}

/// One complete struct as read from DWARF or source and enriched by analysis.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct StructLayout {
    pub name: String,
    pub total_size: usize,
    pub align: usize,
    pub fields: Vec<Field>,
    pub source_file: Option<String>,
    pub source_line: Option<u32>,
    #[serde(with = "arch_serde")]
    pub arch: &'static ArchConfig,
    pub is_packed: bool,
    /// True when this layout was parsed from a C/C++ `union` declaration.
    /// All fields share the same base offset (0); analysis suppresses reorder
    /// and padding findings that do not apply to unions.
    pub is_union: bool,
    /// True when this is a Rust struct with `repr(Rust)` (i.e. no `#[repr(C)]`,
    /// `#[repr(packed)]`, or `#[repr(transparent)]`). The compiler is free to
    /// reorder fields and eliminate padding — padlock's findings describe
    /// *declared-order* waste, which may not match the actual runtime layout.
    /// Always `false` for DWARF/binary layouts (which are always accurate).
    #[serde(default)]
    pub is_repr_rust: bool,
    /// Finding kinds that are suppressed for this struct via a source annotation.
    ///
    /// Populated by source frontends when they encounter a suppression directive:
    /// - Rust: `#[padlock_suppress = "ReorderSuggestion,FalseSharing"]`
    /// - C/C++/Go/Zig: `// padlock: ignore[ReorderSuggestion,FalseSharing]`
    ///
    /// Values match the variant names of [`padlock_core::findings::Finding`]:
    /// `"PaddingWaste"`, `"ReorderSuggestion"`, `"FalseSharing"`, `"LocalityIssue"`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub suppressed_findings: Vec<String>,

    /// Field names whose type size could not be accurately determined from source
    /// alone (e.g. a qualified name like `driver.Connector` whose package is not
    /// in the analyzed source set and may be an interface rather than a struct).
    ///
    /// When non-empty, padding and reorder findings on this struct may be
    /// inaccurate. For precise sizing use binary analysis or `--go-types`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub uncertain_fields: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct PaddingGap {
    pub after_field: String,
    pub bytes: usize,
    pub at_offset: usize,
}

#[derive(Debug, Clone, serde::Serialize)]
pub struct SharingConflict {
    pub fields: Vec<String>,
    pub cache_line: usize,
}

/// Find all padding gaps between consecutive fields.
///
/// Returns an empty vec for union layouts — all fields share offset 0 by
/// definition, so the concept of inter-field padding does not apply.
pub fn find_padding(layout: &StructLayout) -> Vec<PaddingGap> {
    if layout.is_union {
        return Vec::new();
    }
    let mut gaps = Vec::new();
    for window in layout.fields.windows(2) {
        let current = &window[0];
        let next = &window[1];
        let end = current.offset + current.size;
        if next.offset > end {
            gaps.push(PaddingGap {
                after_field: current.name.clone(),
                bytes: next.offset - end,
                at_offset: end,
            });
        }
    }
    // Trailing padding: struct total_size > last field end
    if let Some(last) = layout.fields.last() {
        let end = last.offset + last.size;
        if layout.total_size > end {
            gaps.push(PaddingGap {
                after_field: last.name.clone(),
                bytes: layout.total_size - end,
                at_offset: end,
            });
        }
    }
    gaps
}

/// Return fields sorted by descending alignment then descending size (optimal order).
///
/// This minimises struct padding (same goal as go/analysis/passes/fieldalignment).
///
/// **GC note (Go-specific)**: fieldalignment's `optimalOrder` adds a secondary
/// tie-breaking rule: when alignment is equal, pointer-bearing fields come before
/// pointer-free fields to minimise the GC scan range (`ptrdata`).  padlock's IR
/// stores all field types as language-agnostic `TypeInfo`, so pointer-vs-non-pointer
/// cannot be determined here without language-specific knowledge.  For Go structs the
/// resulting reorder order may differ from fieldalignment's suggestion by the GC-aware
/// tie-break, but the padding savings are identical.  A future Go-specific sort path
/// could incorporate this by carrying `has_gc_pointer: bool` on each `Field`.
pub fn optimal_order(layout: &StructLayout) -> Vec<&Field> {
    let mut sorted: Vec<&Field> = layout.fields.iter().collect();
    sorted.sort_by(|a, b| {
        b.align
            .cmp(&a.align)
            .then(b.size.cmp(&a.size))
            .then(a.name.cmp(&b.name))
    });
    sorted
}

// ── tests ─────────────────────────────────────────────────────────────────────

#[cfg(any(test, feature = "test-helpers"))]
pub mod test_fixtures {
    use super::*;
    use crate::arch::X86_64_SYSV;

    /// The canonical misaligned layout used across crate tests.
    ///   is_active: bool  offset 0,  size 1, align 1
    ///   [7 bytes padding]
    ///   timeout:   f64   offset 8,  size 8, align 8
    ///   is_tls:    bool  offset 16, size 1, align 1
    ///   [3 bytes padding]
    ///   port:      i32   offset 20, size 4, align 4
    ///   total_size 24
    pub fn connection_layout() -> StructLayout {
        StructLayout {
            name: "Connection".to_string(),
            total_size: 24,
            align: 8,
            fields: vec![
                Field {
                    name: "is_active".into(),
                    ty: TypeInfo::Primitive {
                        name: "bool".into(),
                        size: 1,
                        align: 1,
                    },
                    offset: 0,
                    size: 1,
                    align: 1,
                    source_file: None,
                    source_line: None,
                    access: AccessPattern::Unknown,
                },
                Field {
                    name: "timeout".into(),
                    ty: TypeInfo::Primitive {
                        name: "f64".into(),
                        size: 8,
                        align: 8,
                    },
                    offset: 8,
                    size: 8,
                    align: 8,
                    source_file: None,
                    source_line: None,
                    access: AccessPattern::Unknown,
                },
                Field {
                    name: "is_tls".into(),
                    ty: TypeInfo::Primitive {
                        name: "bool".into(),
                        size: 1,
                        align: 1,
                    },
                    offset: 16,
                    size: 1,
                    align: 1,
                    source_file: None,
                    source_line: None,
                    access: AccessPattern::Unknown,
                },
                Field {
                    name: "port".into(),
                    ty: TypeInfo::Primitive {
                        name: "i32".into(),
                        size: 4,
                        align: 4,
                    },
                    offset: 20,
                    size: 4,
                    align: 4,
                    source_file: None,
                    source_line: None,
                    access: AccessPattern::Unknown,
                },
            ],
            source_file: None,
            source_line: None,
            arch: &X86_64_SYSV,
            is_packed: false,
            is_union: false,
            is_repr_rust: false,
            suppressed_findings: Vec::new(),
            uncertain_fields: Vec::new(),
        }
    }

    /// A perfectly packed layout (no padding anywhere).
    pub fn packed_layout() -> StructLayout {
        StructLayout {
            name: "Packed".to_string(),
            total_size: 8,
            align: 4,
            fields: vec![
                Field {
                    name: "a".into(),
                    ty: TypeInfo::Primitive {
                        name: "i32".into(),
                        size: 4,
                        align: 4,
                    },
                    offset: 0,
                    size: 4,
                    align: 4,
                    source_file: None,
                    source_line: None,
                    access: AccessPattern::Unknown,
                },
                Field {
                    name: "b".into(),
                    ty: TypeInfo::Primitive {
                        name: "i16".into(),
                        size: 2,
                        align: 2,
                    },
                    offset: 4,
                    size: 2,
                    align: 2,
                    source_file: None,
                    source_line: None,
                    access: AccessPattern::Unknown,
                },
                Field {
                    name: "c".into(),
                    ty: TypeInfo::Primitive {
                        name: "i16".into(),
                        size: 2,
                        align: 2,
                    },
                    offset: 6,
                    size: 2,
                    align: 2,
                    source_file: None,
                    source_line: None,
                    access: AccessPattern::Unknown,
                },
            ],
            source_file: None,
            source_line: None,
            arch: &X86_64_SYSV,
            is_packed: false,
            is_union: false,
            is_repr_rust: false,
            suppressed_findings: Vec::new(),
            uncertain_fields: Vec::new(),
        }
    }

    #[test]
    fn test_find_padding_connection() {
        let layout = connection_layout();
        let gaps = find_padding(&layout);
        assert_eq!(
            gaps,
            vec![
                PaddingGap {
                    after_field: "is_active".into(),
                    bytes: 7,
                    at_offset: 1
                },
                PaddingGap {
                    after_field: "is_tls".into(),
                    bytes: 3,
                    at_offset: 17
                },
            ]
        );
    }

    #[test]
    fn test_find_padding_packed() {
        let layout = packed_layout();
        assert!(find_padding(&layout).is_empty());
    }

    #[test]
    fn test_optimal_order() {
        let layout = connection_layout();
        let order: Vec<&str> = optimal_order(&layout)
            .iter()
            .map(|f| f.name.as_str())
            .collect();
        // timeout (align 8) first, then port (align 4), then bools (align 1)
        assert_eq!(order[0], "timeout");
        assert_eq!(order[1], "port");
        assert!(order[2] == "is_active" || order[2] == "is_tls");
    }
}