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    let decl_start_byte = node.start_byte();
64    // type_declaration has a type_spec child
65    for i in 0..node.child_count() {
66        let child = node.child(i)?;
67        if child.kind() == "type_spec" {
68            return parse_type_spec(source, child, arch, source_line, decl_start_byte);
69        }
70    }
71    None
72}
73
74fn parse_type_spec(
75    source: &str,
76    node: Node<'_>,
77    arch: &'static ArchConfig,
78    source_line: u32,
79    decl_start_byte: usize,
80) -> Option<StructLayout> {
81    let mut name: Option<String> = None;
82    let mut struct_node: Option<Node> = None;
83
84    for i in 0..node.child_count() {
85        let child = node.child(i)?;
86        match child.kind() {
87            "type_identifier" => name = Some(source[child.byte_range()].to_string()),
88            "struct_type" => struct_node = Some(child),
89            _ => {}
90        }
91    }
92
93    let name = name?;
94    let struct_node = struct_node?;
95    parse_struct_type(
96        source,
97        struct_node,
98        name,
99        arch,
100        source_line,
101        decl_start_byte,
102    )
103}
104
105fn parse_struct_type(
106    source: &str,
107    node: Node<'_>,
108    name: String,
109    arch: &'static ArchConfig,
110    source_line: u32,
111    decl_start_byte: usize,
112) -> Option<StructLayout> {
113    let mut raw_fields: Vec<(String, String, Option<String>, u32)> = Vec::new();
114
115    for i in 0..node.child_count() {
116        let child = node.child(i)?;
117        if child.kind() == "field_declaration_list" {
118            for j in 0..child.child_count() {
119                let field_node = child.child(j)?;
120                if field_node.kind() == "field_declaration" {
121                    collect_field_declarations(source, field_node, &mut raw_fields);
122                }
123            }
124        }
125    }
126
127    if raw_fields.is_empty() {
128        return None;
129    }
130
131    // Simulate layout
132    let mut offset = 0usize;
133    let mut struct_align = 1usize;
134    let mut fields: Vec<Field> = Vec::new();
135
136    for (fname, ty_name, guard, field_line) in raw_fields {
137        let (size, align) = go_type_size_align(&ty_name, arch);
138        if align > 0 {
139            offset = offset.next_multiple_of(align);
140        }
141        struct_align = struct_align.max(align);
142        let access = if let Some(g) = guard {
143            AccessPattern::Concurrent {
144                guard: Some(g),
145                is_atomic: false,
146            }
147        } else {
148            AccessPattern::Unknown
149        };
150        fields.push(Field {
151            name: fname,
152            ty: TypeInfo::Primitive {
153                name: ty_name,
154                size,
155                align,
156            },
157            offset,
158            size,
159            align,
160            source_file: None,
161            source_line: Some(field_line),
162            access,
163        });
164        offset += size;
165    }
166    if struct_align > 0 {
167        offset = offset.next_multiple_of(struct_align);
168    }
169
170    Some(StructLayout {
171        name,
172        total_size: offset,
173        align: struct_align,
174        fields,
175        source_file: None,
176        source_line: Some(source_line),
177        arch,
178        is_packed: false,
179        is_union: false,
180        is_repr_rust: false,
181        suppressed_findings: super::suppress::suppressed_from_preceding_source(
182            source,
183            decl_start_byte,
184        ),
185    })
186}
187
188/// Extract a guard name from a Go field's trailing line comment.
189///
190/// Recognised forms (must appear after the field type on the same line):
191/// - `// padlock:guard=mu`
192/// - `// guarded_by: mu`
193/// - `// +checklocksprotects:mu` (gVisor-style)
194pub fn extract_guard_from_go_comment(comment: &str) -> Option<String> {
195    let c = comment.trim();
196    // Strip leading `//` and optional whitespace
197    let body = c.strip_prefix("//").map(str::trim)?;
198
199    // padlock:guard=mu
200    if let Some(rest) = body.strip_prefix("padlock:guard=") {
201        let guard = rest.trim();
202        if !guard.is_empty() {
203            return Some(guard.to_string());
204        }
205    }
206    // guarded_by: mu
207    if let Some(rest) = body
208        .strip_prefix("guarded_by:")
209        .or_else(|| body.strip_prefix("guarded_by ="))
210    {
211        let guard = rest.trim();
212        if !guard.is_empty() {
213            return Some(guard.to_string());
214        }
215    }
216    // +checklocksprotects:mu (gVisor)
217    if let Some(rest) = body.strip_prefix("+checklocksprotects:") {
218        let guard = rest.trim();
219        if !guard.is_empty() {
220            return Some(guard.to_string());
221        }
222    }
223    None
224}
225
226/// Find the trailing line comment on the same source line as `node`.
227fn trailing_comment_on_line(source: &str, node: Node<'_>) -> Option<String> {
228    // The node's end byte is just past the last token on the field line.
229    // Read the rest of that line from the source.
230    let end = node.end_byte();
231    if end >= source.len() {
232        return None;
233    }
234    let rest = &source[end..];
235    // Take only up to the next newline
236    let line = rest.lines().next().unwrap_or("");
237    // Look for `//` in that remainder
238    line.find("//").map(|pos| line[pos..].to_string())
239}
240
241fn collect_field_declarations(
242    source: &str,
243    node: Node<'_>,
244    out: &mut Vec<(String, String, Option<String>, u32)>,
245) {
246    // field_declaration: field_identifier+ type [comment]
247    // OR embedded type (anonymous field): TypeName [comment]
248    let mut field_names: Vec<String> = Vec::new();
249    let mut ty_text: Option<String> = None;
250    let field_line = node.start_position().row as u32 + 1;
251
252    for i in 0..node.child_count() {
253        if let Some(child) = node.child(i) {
254            match child.kind() {
255                "field_identifier" => field_names.push(source[child.byte_range()].to_string()),
256                "type_identifier" | "pointer_type" | "qualified_type" | "slice_type"
257                | "map_type" | "channel_type" | "array_type" | "interface_type" => {
258                    ty_text = Some(source[child.byte_range()].trim().to_string());
259                }
260                _ => {}
261            }
262        }
263    }
264
265    let guard =
266        trailing_comment_on_line(source, node).and_then(|c| extract_guard_from_go_comment(&c));
267
268    if !field_names.is_empty() {
269        if let Some(ty) = ty_text {
270            // Normal named fields
271            for name in field_names {
272                out.push((name, ty.clone(), guard.clone(), field_line));
273            }
274        }
275    } else if let Some(ty) = ty_text {
276        // Embedded (anonymous) field: `sync.Mutex` or `Base`.
277        // Go field name is the unqualified type name.
278        // The nested-struct resolution pass in lib.rs will later fill in
279        // the correct size/align from other parsed struct layouts.
280        let simple_name = ty.split('.').next_back().unwrap_or(&ty).to_string();
281        out.push((simple_name, ty, guard, field_line));
282    }
283}
284
285// ── public API ────────────────────────────────────────────────────────────────
286
287pub fn parse_go(source: &str, arch: &'static ArchConfig) -> anyhow::Result<Vec<StructLayout>> {
288    let mut parser = Parser::new();
289    parser.set_language(&tree_sitter_go::LANGUAGE.into())?;
290    let tree = parser
291        .parse(source, None)
292        .ok_or_else(|| anyhow::anyhow!("tree-sitter-go parse failed"))?;
293    Ok(extract_structs(source, tree.root_node(), arch))
294}
295
296// ── tests ─────────────────────────────────────────────────────────────────────
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301    use padlock_core::arch::X86_64_SYSV;
302
303    #[test]
304    fn parse_simple_go_struct() {
305        let src = r#"
306package main
307type Point struct {
308    X int32
309    Y int32
310}
311"#;
312        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
313        assert_eq!(layouts.len(), 1);
314        assert_eq!(layouts[0].name, "Point");
315        assert_eq!(layouts[0].fields.len(), 2);
316    }
317
318    #[test]
319    fn go_layout_with_padding() {
320        let src = "package p\ntype T struct { A bool; B int64 }";
321        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
322        assert_eq!(layouts.len(), 1);
323        let l = &layouts[0];
324        assert_eq!(l.fields[0].offset, 0);
325        assert_eq!(l.fields[1].offset, 8); // bool (1) + 7 pad → 8
326    }
327
328    #[test]
329    fn go_string_is_two_words() {
330        let src = "package p\ntype S struct { Name string }";
331        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
332        assert_eq!(layouts[0].fields[0].size, 16); // ptr + len
333    }
334
335    // ── Go guard comment extraction ────────────────────────────────────────────
336
337    #[test]
338    fn extract_guard_padlock_form() {
339        assert_eq!(
340            extract_guard_from_go_comment("// padlock:guard=mu"),
341            Some("mu".to_string())
342        );
343    }
344
345    #[test]
346    fn extract_guard_guarded_by_form() {
347        assert_eq!(
348            extract_guard_from_go_comment("// guarded_by: counter_lock"),
349            Some("counter_lock".to_string())
350        );
351    }
352
353    #[test]
354    fn extract_guard_checklocksprotects_form() {
355        assert_eq!(
356            extract_guard_from_go_comment("// +checklocksprotects:mu"),
357            Some("mu".to_string())
358        );
359    }
360
361    #[test]
362    fn extract_guard_no_match_returns_none() {
363        assert!(extract_guard_from_go_comment("// just a comment").is_none());
364        assert!(extract_guard_from_go_comment("// TODO: fix this").is_none());
365    }
366
367    #[test]
368    fn go_struct_padlock_guard_annotation_sets_concurrent() {
369        let src = r#"package p
370type Cache struct {
371    Readers int64 // padlock:guard=mu
372    Writers int64 // padlock:guard=other_mu
373    Mu      sync.Mutex
374}
375"#;
376        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
377        let l = &layouts[0];
378        // Readers and Writers should be Concurrent with different guards
379        if let AccessPattern::Concurrent { guard, .. } = &l.fields[0].access {
380            assert_eq!(guard.as_deref(), Some("mu"));
381        } else {
382            panic!(
383                "expected Concurrent for Readers, got {:?}",
384                l.fields[0].access
385            );
386        }
387        if let AccessPattern::Concurrent { guard, .. } = &l.fields[1].access {
388            assert_eq!(guard.as_deref(), Some("other_mu"));
389        } else {
390            panic!(
391                "expected Concurrent for Writers, got {:?}",
392                l.fields[1].access
393            );
394        }
395    }
396
397    #[test]
398    fn go_struct_different_guards_same_cache_line_is_false_sharing() {
399        let src = r#"package p
400type HotPath struct {
401    Readers int64 // padlock:guard=lock_a
402    Writers int64 // padlock:guard=lock_b
403}
404"#;
405        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
406        assert!(padlock_core::analysis::false_sharing::has_false_sharing(
407            &layouts[0]
408        ));
409    }
410
411    #[test]
412    fn go_struct_same_guard_is_not_false_sharing() {
413        let src = r#"package p
414type Safe struct {
415    A int64 // padlock:guard=mu
416    B int64 // padlock:guard=mu
417}
418"#;
419        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
420        assert!(!padlock_core::analysis::false_sharing::has_false_sharing(
421            &layouts[0]
422        ));
423    }
424
425    // ── interface{} / any sizing ───────────────────────────────────────────────
426
427    #[test]
428    fn interface_field_is_two_words() {
429        // interface{} is a fat pointer: (type pointer, data pointer) = 2×pointer
430        let src = "package p\ntype S struct { V interface{} }";
431        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
432        assert_eq!(layouts[0].fields[0].size, 16); // 2 × 8B on x86-64
433        assert_eq!(layouts[0].fields[0].align, 8);
434    }
435
436    #[test]
437    fn any_field_is_two_words() {
438        // `any` is an alias for `interface{}` since Go 1.18
439        let src = "package p\ntype S struct { V any }";
440        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
441        assert_eq!(layouts[0].fields[0].size, 16); // 2 × 8B on x86-64
442        assert_eq!(layouts[0].fields[0].align, 8);
443    }
444
445    #[test]
446    fn interface_field_same_size_as_error() {
447        // `error` was already two-word; interface{} must match
448        let src_iface = "package p\ntype S struct { V interface{} }";
449        let src_err = "package p\ntype S struct { V error }";
450        let iface = parse_go(src_iface, &X86_64_SYSV).unwrap();
451        let err = parse_go(src_err, &X86_64_SYSV).unwrap();
452        assert_eq!(iface[0].fields[0].size, err[0].fields[0].size);
453    }
454
455    #[test]
456    fn struct_with_mixed_interface_and_ints_has_correct_layout() {
457        // interface{} at offset 0 (size 16, align 8) then int64 at offset 16
458        let src = "package p\ntype S struct { V interface{}; N int64 }";
459        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
460        let l = &layouts[0];
461        assert_eq!(l.fields[0].offset, 0);
462        assert_eq!(l.fields[0].size, 16);
463        assert_eq!(l.fields[1].offset, 16);
464        assert_eq!(l.total_size, 24);
465    }
466
467    // ── embedded struct support ───────────────────────────────────────────────
468
469    #[test]
470    fn embedded_struct_field_uses_type_name_as_field_name() {
471        // `Base` is an embedded field — Go uses the type name as the field name.
472        let src = r#"package p
473type Base struct { X int32 }
474type Derived struct {
475    Base
476    Y int32
477}
478"#;
479        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
480        let derived = layouts
481            .iter()
482            .find(|l| l.name == "Derived")
483            .expect("Derived");
484        // Must have a field named "Base"
485        assert!(
486            derived.fields.iter().any(|f| f.name == "Base"),
487            "embedded field should be named 'Base'"
488        );
489    }
490
491    #[test]
492    fn embedded_qualified_type_uses_unqualified_name() {
493        // `sync.Mutex` embedded — field name should be "Mutex"
494        let src = r#"package p
495type Safe struct {
496    sync.Mutex
497    Value int64
498}
499"#;
500        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
501        let l = layouts.iter().find(|l| l.name == "Safe").expect("Safe");
502        assert!(
503            l.fields.iter().any(|f| f.name == "Mutex"),
504            "embedded sync.Mutex should produce field named 'Mutex'"
505        );
506    }
507
508    #[test]
509    fn embedded_field_has_non_zero_size_from_resolution() {
510        // After lib.rs nested-struct resolution, Base's size should be filled in.
511        // We test via parse_source_str which triggers resolution.
512        let src = r#"package p
513type Inner struct { A int64; B int64 }
514type Outer struct {
515    Inner
516    C int32
517}
518"#;
519        use crate::{SourceLanguage, parse_source_str};
520        let layouts = parse_source_str(src, &SourceLanguage::Go, &X86_64_SYSV).unwrap();
521        let outer = layouts.iter().find(|l| l.name == "Outer").expect("Outer");
522        let inner_field = outer
523            .fields
524            .iter()
525            .find(|f| f.name == "Inner")
526            .expect("Inner field");
527        // Inner struct is 16 bytes (two int64s)
528        assert_eq!(
529            inner_field.size, 16,
530            "embedded Inner field should be resolved to 16 bytes"
531        );
532    }
533
534    #[test]
535    fn struct_with_no_embedded_fields_unaffected() {
536        let src = "package p\ntype S struct { A int32; B int64 }";
537        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
538        let l = &layouts[0];
539        assert_eq!(l.fields.len(), 2);
540        assert_eq!(l.fields[0].name, "A");
541        assert_eq!(l.fields[1].name, "B");
542    }
543
544    // ── bad weather: embedded fields ──────────────────────────────────────────
545
546    #[test]
547    fn embedded_unknown_type_falls_back_to_pointer_size() {
548        // If the embedded type is not defined in the file, size = pointer_size
549        let src = "package p\ntype S struct { external.Type\nX int32 }";
550        let layouts = parse_go(src, &X86_64_SYSV).unwrap();
551        let l = layouts.iter().find(|l| l.name == "S").expect("S");
552        let emb = l
553            .fields
554            .iter()
555            .find(|f| f.name == "Type")
556            .expect("Type field");
557        // Falls back to pointer size (8 on x86_64) since type is unknown
558        assert_eq!(emb.size, 8);
559    }
560}