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    // OR embedded type (anonymous field): TypeName [comment]
233    let mut field_names: Vec<String> = Vec::new();
234    let mut ty_text: Option<String> = None;
235
236    for i in 0..node.child_count() {
237        if let Some(child) = node.child(i) {
238            match child.kind() {
239                "field_identifier" => field_names.push(source[child.byte_range()].to_string()),
240                "type_identifier" | "pointer_type" | "qualified_type" | "slice_type"
241                | "map_type" | "channel_type" | "array_type" | "interface_type" => {
242                    ty_text = Some(source[child.byte_range()].trim().to_string());
243                }
244                _ => {}
245            }
246        }
247    }
248
249    let guard =
250        trailing_comment_on_line(source, node).and_then(|c| extract_guard_from_go_comment(&c));
251
252    if !field_names.is_empty() {
253        if let Some(ty) = ty_text {
254            // Normal named fields
255            for name in field_names {
256                out.push((name, ty.clone(), guard.clone()));
257            }
258        }
259    } else if let Some(ty) = ty_text {
260        // Embedded (anonymous) field: `sync.Mutex` or `Base`.
261        // Go field name is the unqualified type name.
262        // The nested-struct resolution pass in lib.rs will later fill in
263        // the correct size/align from other parsed struct layouts.
264        let simple_name = ty.split('.').next_back().unwrap_or(&ty).to_string();
265        out.push((simple_name, ty, guard));
266    }
267}
268
269// ── public API ────────────────────────────────────────────────────────────────
270
271pub fn parse_go(source: &str, arch: &'static ArchConfig) -> anyhow::Result<Vec<StructLayout>> {
272    let mut parser = Parser::new();
273    parser.set_language(&tree_sitter_go::LANGUAGE.into())?;
274    let tree = parser
275        .parse(source, None)
276        .ok_or_else(|| anyhow::anyhow!("tree-sitter-go parse failed"))?;
277    Ok(extract_structs(source, tree.root_node(), arch))
278}
279
280// ── tests ─────────────────────────────────────────────────────────────────────
281
282#[cfg(test)]
283mod tests {
284    use super::*;
285    use padlock_core::arch::X86_64_SYSV;
286
287    #[test]
288    fn parse_simple_go_struct() {
289        let src = r#"
290package main
291type Point struct {
292    X int32
293    Y int32
294}
295"#;
296        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
297        assert_eq!(layouts.len(), 1);
298        assert_eq!(layouts[0].name, "Point");
299        assert_eq!(layouts[0].fields.len(), 2);
300    }
301
302    #[test]
303    fn go_layout_with_padding() {
304        let src = "package p\ntype T struct { A bool; B int64 }";
305        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
306        assert_eq!(layouts.len(), 1);
307        let l = &layouts[0];
308        assert_eq!(l.fields[0].offset, 0);
309        assert_eq!(l.fields[1].offset, 8); // bool (1) + 7 pad → 8
310    }
311
312    #[test]
313    fn go_string_is_two_words() {
314        let src = "package p\ntype S struct { Name string }";
315        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
316        assert_eq!(layouts[0].fields[0].size, 16); // ptr + len
317    }
318
319    // ── Go guard comment extraction ────────────────────────────────────────────
320
321    #[test]
322    fn extract_guard_padlock_form() {
323        assert_eq!(
324            extract_guard_from_go_comment("// padlock:guard=mu"),
325            Some("mu".to_string())
326        );
327    }
328
329    #[test]
330    fn extract_guard_guarded_by_form() {
331        assert_eq!(
332            extract_guard_from_go_comment("// guarded_by: counter_lock"),
333            Some("counter_lock".to_string())
334        );
335    }
336
337    #[test]
338    fn extract_guard_checklocksprotects_form() {
339        assert_eq!(
340            extract_guard_from_go_comment("// +checklocksprotects:mu"),
341            Some("mu".to_string())
342        );
343    }
344
345    #[test]
346    fn extract_guard_no_match_returns_none() {
347        assert!(extract_guard_from_go_comment("// just a comment").is_none());
348        assert!(extract_guard_from_go_comment("// TODO: fix this").is_none());
349    }
350
351    #[test]
352    fn go_struct_padlock_guard_annotation_sets_concurrent() {
353        let src = r#"package p
354type Cache struct {
355    Readers int64 // padlock:guard=mu
356    Writers int64 // padlock:guard=other_mu
357    Mu      sync.Mutex
358}
359"#;
360        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
361        let l = &layouts[0];
362        // Readers and Writers should be Concurrent with different guards
363        if let AccessPattern::Concurrent { guard, .. } = &l.fields[0].access {
364            assert_eq!(guard.as_deref(), Some("mu"));
365        } else {
366            panic!(
367                "expected Concurrent for Readers, got {:?}",
368                l.fields[0].access
369            );
370        }
371        if let AccessPattern::Concurrent { guard, .. } = &l.fields[1].access {
372            assert_eq!(guard.as_deref(), Some("other_mu"));
373        } else {
374            panic!(
375                "expected Concurrent for Writers, got {:?}",
376                l.fields[1].access
377            );
378        }
379    }
380
381    #[test]
382    fn go_struct_different_guards_same_cache_line_is_false_sharing() {
383        let src = r#"package p
384type HotPath struct {
385    Readers int64 // padlock:guard=lock_a
386    Writers int64 // padlock:guard=lock_b
387}
388"#;
389        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
390        assert!(padlock_core::analysis::false_sharing::has_false_sharing(
391            &layouts[0]
392        ));
393    }
394
395    #[test]
396    fn go_struct_same_guard_is_not_false_sharing() {
397        let src = r#"package p
398type Safe struct {
399    A int64 // padlock:guard=mu
400    B int64 // padlock:guard=mu
401}
402"#;
403        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
404        assert!(!padlock_core::analysis::false_sharing::has_false_sharing(
405            &layouts[0]
406        ));
407    }
408
409    // ── interface{} / any sizing ───────────────────────────────────────────────
410
411    #[test]
412    fn interface_field_is_two_words() {
413        // interface{} is a fat pointer: (type pointer, data pointer) = 2×pointer
414        let src = "package p\ntype S struct { V interface{} }";
415        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
416        assert_eq!(layouts[0].fields[0].size, 16); // 2 × 8B on x86-64
417        assert_eq!(layouts[0].fields[0].align, 8);
418    }
419
420    #[test]
421    fn any_field_is_two_words() {
422        // `any` is an alias for `interface{}` since Go 1.18
423        let src = "package p\ntype S struct { V any }";
424        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
425        assert_eq!(layouts[0].fields[0].size, 16); // 2 × 8B on x86-64
426        assert_eq!(layouts[0].fields[0].align, 8);
427    }
428
429    #[test]
430    fn interface_field_same_size_as_error() {
431        // `error` was already two-word; interface{} must match
432        let src_iface = "package p\ntype S struct { V interface{} }";
433        let src_err = "package p\ntype S struct { V error }";
434        let iface = parse_go(src_iface, &X86_64_SYSV).unwrap();
435        let err = parse_go(src_err, &X86_64_SYSV).unwrap();
436        assert_eq!(iface[0].fields[0].size, err[0].fields[0].size);
437    }
438
439    #[test]
440    fn struct_with_mixed_interface_and_ints_has_correct_layout() {
441        // interface{} at offset 0 (size 16, align 8) then int64 at offset 16
442        let src = "package p\ntype S struct { V interface{}; N int64 }";
443        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
444        let l = &layouts[0];
445        assert_eq!(l.fields[0].offset, 0);
446        assert_eq!(l.fields[0].size, 16);
447        assert_eq!(l.fields[1].offset, 16);
448        assert_eq!(l.total_size, 24);
449    }
450
451    // ── embedded struct support ───────────────────────────────────────────────
452
453    #[test]
454    fn embedded_struct_field_uses_type_name_as_field_name() {
455        // `Base` is an embedded field — Go uses the type name as the field name.
456        let src = r#"package p
457type Base struct { X int32 }
458type Derived struct {
459    Base
460    Y int32
461}
462"#;
463        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
464        let derived = layouts
465            .iter()
466            .find(|l| l.name == "Derived")
467            .expect("Derived");
468        // Must have a field named "Base"
469        assert!(
470            derived.fields.iter().any(|f| f.name == "Base"),
471            "embedded field should be named 'Base'"
472        );
473    }
474
475    #[test]
476    fn embedded_qualified_type_uses_unqualified_name() {
477        // `sync.Mutex` embedded — field name should be "Mutex"
478        let src = r#"package p
479type Safe struct {
480    sync.Mutex
481    Value int64
482}
483"#;
484        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
485        let l = layouts.iter().find(|l| l.name == "Safe").expect("Safe");
486        assert!(
487            l.fields.iter().any(|f| f.name == "Mutex"),
488            "embedded sync.Mutex should produce field named 'Mutex'"
489        );
490    }
491
492    #[test]
493    fn embedded_field_has_non_zero_size_from_resolution() {
494        // After lib.rs nested-struct resolution, Base's size should be filled in.
495        // We test via parse_source_str which triggers resolution.
496        let src = r#"package p
497type Inner struct { A int64; B int64 }
498type Outer struct {
499    Inner
500    C int32
501}
502"#;
503        use crate::{SourceLanguage, parse_source_str};
504        let layouts = parse_source_str(src, &SourceLanguage::Go, &X86_64_SYSV).unwrap();
505        let outer = layouts.iter().find(|l| l.name == "Outer").expect("Outer");
506        let inner_field = outer
507            .fields
508            .iter()
509            .find(|f| f.name == "Inner")
510            .expect("Inner field");
511        // Inner struct is 16 bytes (two int64s)
512        assert_eq!(
513            inner_field.size, 16,
514            "embedded Inner field should be resolved to 16 bytes"
515        );
516    }
517
518    #[test]
519    fn struct_with_no_embedded_fields_unaffected() {
520        let src = "package p\ntype S struct { A int32; B int64 }";
521        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
522        let l = &layouts[0];
523        assert_eq!(l.fields.len(), 2);
524        assert_eq!(l.fields[0].name, "A");
525        assert_eq!(l.fields[1].name, "B");
526    }
527
528    // ── bad weather: embedded fields ──────────────────────────────────────────
529
530    #[test]
531    fn embedded_unknown_type_falls_back_to_pointer_size() {
532        // If the embedded type is not defined in the file, size = pointer_size
533        let src = "package p\ntype S struct { external.Type\nX int32 }";
534        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
535        let l = layouts.iter().find(|l| l.name == "S").expect("S");
536        let emb = l
537            .fields
538            .iter()
539            .find(|f| f.name == "Type")
540            .expect("Type field");
541        // Falls back to pointer size (8 on x86_64) since type is unknown
542        assert_eq!(emb.size, 8);
543    }
544}