Skip to main content

padlock_source/frontends/
go.rs

1// padlock-source/src/frontends/go.rs
2//
3// Extracts struct layouts from Go source using tree-sitter-go.
4// Sizes use Go's platform-native alignment rules (same as C on the target arch).
5
6use padlock_core::arch::ArchConfig;
7use padlock_core::ir::{AccessPattern, Field, StructLayout, TypeInfo};
8use tree_sitter::{Node, Parser};
9
10// ── type resolution ───────────────────────────────────────────────────────────
11
12fn go_type_size_align(ty: &str, arch: &'static ArchConfig) -> (usize, usize) {
13    match ty.trim() {
14        "bool" => (1, 1),
15        "int8" | "uint8" | "byte" => (1, 1),
16        "int16" | "uint16" => (2, 2),
17        "int32" | "uint32" | "rune" | "float32" => (4, 4),
18        "int64" | "uint64" | "float64" | "complex64" => (8, 8),
19        "complex128" => (16, 16),
20        "int" | "uint" => (arch.pointer_size, arch.pointer_size),
21        "uintptr" => (arch.pointer_size, arch.pointer_size),
22        "string" => (arch.pointer_size * 2, arch.pointer_size), // ptr + len
23        ty if ty.starts_with("[]") => (arch.pointer_size * 3, arch.pointer_size), // ptr+len+cap
24        ty if ty.starts_with("map[") || ty.starts_with("chan ") => {
25            (arch.pointer_size, arch.pointer_size)
26        }
27        ty if ty.starts_with('*') => (arch.pointer_size, arch.pointer_size),
28        // Interface types: two-word fat pointer (type pointer + data pointer)
29        "error" | "interface{}" | "any" => (arch.pointer_size * 2, arch.pointer_size),
30        _ => (arch.pointer_size, arch.pointer_size),
31    }
32}
33
34// ── tree-sitter walker ────────────────────────────────────────────────────────
35
36fn extract_structs(source: &str, root: Node<'_>, arch: &'static ArchConfig) -> Vec<StructLayout> {
37    let mut layouts = Vec::new();
38    let mut stack = vec![root];
39
40    while let Some(node) = stack.pop() {
41        for i in (0..node.child_count()).rev() {
42            if let Some(c) = node.child(i) {
43                stack.push(c);
44            }
45        }
46
47        // type_declaration → type_spec → struct_type
48        if node.kind() == "type_declaration"
49            && let Some(layout) = parse_type_declaration(source, node, arch)
50        {
51            layouts.push(layout);
52        }
53    }
54    layouts
55}
56
57fn parse_type_declaration(
58    source: &str,
59    node: Node<'_>,
60    arch: &'static ArchConfig,
61) -> Option<StructLayout> {
62    let source_line = node.start_position().row as u32 + 1;
63    // type_declaration has a type_spec child
64    for i in 0..node.child_count() {
65        let child = node.child(i)?;
66        if child.kind() == "type_spec" {
67            return parse_type_spec(source, child, arch, source_line);
68        }
69    }
70    None
71}
72
73fn parse_type_spec(
74    source: &str,
75    node: Node<'_>,
76    arch: &'static ArchConfig,
77    source_line: u32,
78) -> Option<StructLayout> {
79    let mut name: Option<String> = None;
80    let mut struct_node: Option<Node> = None;
81
82    for i in 0..node.child_count() {
83        let child = node.child(i)?;
84        match child.kind() {
85            "type_identifier" => name = Some(source[child.byte_range()].to_string()),
86            "struct_type" => struct_node = Some(child),
87            _ => {}
88        }
89    }
90
91    let name = name?;
92    let struct_node = struct_node?;
93    parse_struct_type(source, struct_node, name, arch, source_line)
94}
95
96fn parse_struct_type(
97    source: &str,
98    node: Node<'_>,
99    name: String,
100    arch: &'static ArchConfig,
101    source_line: u32,
102) -> Option<StructLayout> {
103    let mut raw_fields: Vec<(String, String, Option<String>)> = Vec::new();
104
105    for i in 0..node.child_count() {
106        let child = node.child(i)?;
107        if child.kind() == "field_declaration_list" {
108            for j in 0..child.child_count() {
109                let field_node = child.child(j)?;
110                if field_node.kind() == "field_declaration" {
111                    collect_field_declarations(source, field_node, &mut raw_fields);
112                }
113            }
114        }
115    }
116
117    if raw_fields.is_empty() {
118        return None;
119    }
120
121    // Simulate layout
122    let mut offset = 0usize;
123    let mut struct_align = 1usize;
124    let mut fields: Vec<Field> = Vec::new();
125
126    for (fname, ty_name, guard) in raw_fields {
127        let (size, align) = go_type_size_align(&ty_name, arch);
128        if align > 0 {
129            offset = offset.next_multiple_of(align);
130        }
131        struct_align = struct_align.max(align);
132        let access = if let Some(g) = guard {
133            AccessPattern::Concurrent {
134                guard: Some(g),
135                is_atomic: false,
136            }
137        } else {
138            AccessPattern::Unknown
139        };
140        fields.push(Field {
141            name: fname,
142            ty: TypeInfo::Primitive {
143                name: ty_name,
144                size,
145                align,
146            },
147            offset,
148            size,
149            align,
150            source_file: None,
151            source_line: None,
152            access,
153        });
154        offset += size;
155    }
156    if struct_align > 0 {
157        offset = offset.next_multiple_of(struct_align);
158    }
159
160    Some(StructLayout {
161        name,
162        total_size: offset,
163        align: struct_align,
164        fields,
165        source_file: None,
166        source_line: Some(source_line),
167        arch,
168        is_packed: false,
169        is_union: false,
170    })
171}
172
173/// Extract a guard name from a Go field's trailing line comment.
174///
175/// Recognised forms (must appear after the field type on the same line):
176/// - `// padlock:guard=mu`
177/// - `// guarded_by: mu`
178/// - `// +checklocksprotects:mu` (gVisor-style)
179pub fn extract_guard_from_go_comment(comment: &str) -> Option<String> {
180    let c = comment.trim();
181    // Strip leading `//` and optional whitespace
182    let body = c.strip_prefix("//").map(str::trim)?;
183
184    // padlock:guard=mu
185    if let Some(rest) = body.strip_prefix("padlock:guard=") {
186        let guard = rest.trim();
187        if !guard.is_empty() {
188            return Some(guard.to_string());
189        }
190    }
191    // guarded_by: mu
192    if let Some(rest) = body
193        .strip_prefix("guarded_by:")
194        .or_else(|| body.strip_prefix("guarded_by ="))
195    {
196        let guard = rest.trim();
197        if !guard.is_empty() {
198            return Some(guard.to_string());
199        }
200    }
201    // +checklocksprotects:mu (gVisor)
202    if let Some(rest) = body.strip_prefix("+checklocksprotects:") {
203        let guard = rest.trim();
204        if !guard.is_empty() {
205            return Some(guard.to_string());
206        }
207    }
208    None
209}
210
211/// Find the trailing line comment on the same source line as `node`.
212fn trailing_comment_on_line(source: &str, node: Node<'_>) -> Option<String> {
213    // The node's end byte is just past the last token on the field line.
214    // Read the rest of that line from the source.
215    let end = node.end_byte();
216    if end >= source.len() {
217        return None;
218    }
219    let rest = &source[end..];
220    // Take only up to the next newline
221    let line = rest.lines().next().unwrap_or("");
222    // Look for `//` in that remainder
223    line.find("//").map(|pos| line[pos..].to_string())
224}
225
226fn collect_field_declarations(
227    source: &str,
228    node: Node<'_>,
229    out: &mut Vec<(String, String, Option<String>)>,
230) {
231    // field_declaration: field_identifier+ type [comment]
232    let mut field_names: Vec<String> = Vec::new();
233    let mut ty_text: Option<String> = None;
234
235    for i in 0..node.child_count() {
236        if let Some(child) = node.child(i) {
237            match child.kind() {
238                "field_identifier" => field_names.push(source[child.byte_range()].to_string()),
239                "type_identifier" | "pointer_type" | "qualified_type" | "slice_type"
240                | "map_type" | "channel_type" | "array_type" | "interface_type" => {
241                    ty_text = Some(source[child.byte_range()].trim().to_string());
242                }
243                _ => {}
244            }
245        }
246    }
247
248    if let Some(ty) = ty_text {
249        // Check for trailing guard comment on this field's line
250        let guard =
251            trailing_comment_on_line(source, node).and_then(|c| extract_guard_from_go_comment(&c));
252        for name in field_names {
253            out.push((name, ty.clone(), guard.clone()));
254        }
255    }
256}
257
258// ── public API ────────────────────────────────────────────────────────────────
259
260pub fn parse_go(source: &str, arch: &'static ArchConfig) -> anyhow::Result<Vec<StructLayout>> {
261    let mut parser = Parser::new();
262    parser.set_language(&tree_sitter_go::LANGUAGE.into())?;
263    let tree = parser
264        .parse(source, None)
265        .ok_or_else(|| anyhow::anyhow!("tree-sitter-go parse failed"))?;
266    Ok(extract_structs(source, tree.root_node(), arch))
267}
268
269// ── tests ─────────────────────────────────────────────────────────────────────
270
271#[cfg(test)]
272mod tests {
273    use super::*;
274    use padlock_core::arch::X86_64_SYSV;
275
276    #[test]
277    fn parse_simple_go_struct() {
278        let src = r#"
279package main
280type Point struct {
281    X int32
282    Y int32
283}
284"#;
285        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
286        assert_eq!(layouts.len(), 1);
287        assert_eq!(layouts[0].name, "Point");
288        assert_eq!(layouts[0].fields.len(), 2);
289    }
290
291    #[test]
292    fn go_layout_with_padding() {
293        let src = "package p\ntype T struct { A bool; B int64 }";
294        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
295        assert_eq!(layouts.len(), 1);
296        let l = &layouts[0];
297        assert_eq!(l.fields[0].offset, 0);
298        assert_eq!(l.fields[1].offset, 8); // bool (1) + 7 pad → 8
299    }
300
301    #[test]
302    fn go_string_is_two_words() {
303        let src = "package p\ntype S struct { Name string }";
304        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
305        assert_eq!(layouts[0].fields[0].size, 16); // ptr + len
306    }
307
308    // ── Go guard comment extraction ────────────────────────────────────────────
309
310    #[test]
311    fn extract_guard_padlock_form() {
312        assert_eq!(
313            extract_guard_from_go_comment("// padlock:guard=mu"),
314            Some("mu".to_string())
315        );
316    }
317
318    #[test]
319    fn extract_guard_guarded_by_form() {
320        assert_eq!(
321            extract_guard_from_go_comment("// guarded_by: counter_lock"),
322            Some("counter_lock".to_string())
323        );
324    }
325
326    #[test]
327    fn extract_guard_checklocksprotects_form() {
328        assert_eq!(
329            extract_guard_from_go_comment("// +checklocksprotects:mu"),
330            Some("mu".to_string())
331        );
332    }
333
334    #[test]
335    fn extract_guard_no_match_returns_none() {
336        assert!(extract_guard_from_go_comment("// just a comment").is_none());
337        assert!(extract_guard_from_go_comment("// TODO: fix this").is_none());
338    }
339
340    #[test]
341    fn go_struct_padlock_guard_annotation_sets_concurrent() {
342        let src = r#"package p
343type Cache struct {
344    Readers int64 // padlock:guard=mu
345    Writers int64 // padlock:guard=other_mu
346    Mu      sync.Mutex
347}
348"#;
349        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
350        let l = &layouts[0];
351        // Readers and Writers should be Concurrent with different guards
352        if let AccessPattern::Concurrent { guard, .. } = &l.fields[0].access {
353            assert_eq!(guard.as_deref(), Some("mu"));
354        } else {
355            panic!(
356                "expected Concurrent for Readers, got {:?}",
357                l.fields[0].access
358            );
359        }
360        if let AccessPattern::Concurrent { guard, .. } = &l.fields[1].access {
361            assert_eq!(guard.as_deref(), Some("other_mu"));
362        } else {
363            panic!(
364                "expected Concurrent for Writers, got {:?}",
365                l.fields[1].access
366            );
367        }
368    }
369
370    #[test]
371    fn go_struct_different_guards_same_cache_line_is_false_sharing() {
372        let src = r#"package p
373type HotPath struct {
374    Readers int64 // padlock:guard=lock_a
375    Writers int64 // padlock:guard=lock_b
376}
377"#;
378        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
379        assert!(padlock_core::analysis::false_sharing::has_false_sharing(
380            &layouts[0]
381        ));
382    }
383
384    #[test]
385    fn go_struct_same_guard_is_not_false_sharing() {
386        let src = r#"package p
387type Safe struct {
388    A int64 // padlock:guard=mu
389    B int64 // padlock:guard=mu
390}
391"#;
392        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
393        assert!(!padlock_core::analysis::false_sharing::has_false_sharing(
394            &layouts[0]
395        ));
396    }
397
398    // ── interface{} / any sizing ───────────────────────────────────────────────
399
400    #[test]
401    fn interface_field_is_two_words() {
402        // interface{} is a fat pointer: (type pointer, data pointer) = 2×pointer
403        let src = "package p\ntype S struct { V interface{} }";
404        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
405        assert_eq!(layouts[0].fields[0].size, 16); // 2 × 8B on x86-64
406        assert_eq!(layouts[0].fields[0].align, 8);
407    }
408
409    #[test]
410    fn any_field_is_two_words() {
411        // `any` is an alias for `interface{}` since Go 1.18
412        let src = "package p\ntype S struct { V any }";
413        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
414        assert_eq!(layouts[0].fields[0].size, 16); // 2 × 8B on x86-64
415        assert_eq!(layouts[0].fields[0].align, 8);
416    }
417
418    #[test]
419    fn interface_field_same_size_as_error() {
420        // `error` was already two-word; interface{} must match
421        let src_iface = "package p\ntype S struct { V interface{} }";
422        let src_err = "package p\ntype S struct { V error }";
423        let iface = parse_go(src_iface, &X86_64_SYSV).unwrap();
424        let err = parse_go(src_err, &X86_64_SYSV).unwrap();
425        assert_eq!(iface[0].fields[0].size, err[0].fields[0].size);
426    }
427
428    #[test]
429    fn struct_with_mixed_interface_and_ints_has_correct_layout() {
430        // interface{} at offset 0 (size 16, align 8) then int64 at offset 16
431        let src = "package p\ntype S struct { V interface{}; N int64 }";
432        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
433        let l = &layouts[0];
434        assert_eq!(l.fields[0].offset, 0);
435        assert_eq!(l.fields[0].size, 16);
436        assert_eq!(l.fields[1].offset, 16);
437        assert_eq!(l.total_size, 24);
438    }
439}