unstrip 1.1.0

Recover symbols, types, and method signatures from stripped Go binaries. Ghidra/IDA/Binary Ninja exporters included.
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
use std::io::{self, Write};

use crate::pclntab::Function;
use crate::types::{KindData, KindName, StructField, Type};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Target {
    Ida,
    Ghidra,
    BinaryNinja,
}

/// Emit a script that, run inside the target reverse engineering tool,
/// applies every recovered function name (with file:line as a function
/// comment) and every recovered struct type (as a C declaration the tool
/// can parse).
///
/// Pass `types` as an empty slice to emit functions only. Pass
/// `signatures = None` to emit bare function names without the recovered
/// Go-syntax signature in the per-function comment.
pub fn write_script<W: Write>(
    w: &mut W,
    target: Target,
    funcs: &[Function],
    types: &[Type],
    signatures: Option<&std::collections::HashMap<u64, String>>,
    generator: &str,
) -> io::Result<()> {
    match target {
        Target::Ida => write_ida(w, funcs, types, signatures, generator),
        Target::Ghidra => write_ghidra(w, funcs, types, signatures, generator),
        Target::BinaryNinja => write_binja(w, funcs, types, signatures, generator),
    }
}

fn sig_for(
    f: &Function,
    signatures: Option<&std::collections::HashMap<u64, String>>,
) -> Option<String> {
    signatures.and_then(|m| m.get(&f.address)).cloned()
}

fn write_ida<W: Write>(
    w: &mut W,
    funcs: &[Function],
    types: &[Type],
    signatures: Option<&std::collections::HashMap<u64, String>>,
    generator: &str,
) -> io::Result<()> {
    writeln!(
        w,
        "# Generated by {generator}. Run inside IDA: File -> Script File... (Python3)"
    )?;
    writeln!(w, "import ida_funcs, ida_name, ida_bytes, ida_typeinf, idc")?;
    writeln!(w)?;
    emit_stats_preamble(w)?;
    writeln!(w, "def _func(addr, name, comment):")?;
    writeln!(w, "    try:")?;
    writeln!(w, "        ok = ida_funcs.add_func(addr)")?;
    writeln!(
        w,
        "        ok = ida_name.set_name(addr, name, ida_name.SN_FORCE | ida_name.SN_NOCHECK) and ok"
    )?;
    writeln!(w, "        if comment:")?;
    writeln!(w, "            idc.set_func_cmt(addr, comment, 0)")?;
    writeln!(w, "        if ok:")?;
    writeln!(w, "            _stats['func_ok'] += 1")?;
    writeln!(w, "        else:")?;
    writeln!(w, "            _stats['func_fail'] += 1")?;
    writeln!(
        w,
        "            _stats['failures'].append(('func', '0x{{:x}} {{}}'.format(addr, name), 'IDA refused add_func or set_name'))"
    )?;
    writeln!(w, "    except Exception as e:")?;
    writeln!(w, "        _stats['func_fail'] += 1")?;
    writeln!(
        w,
        "        _stats['failures'].append(('func', '0x{{:x}} {{}}'.format(addr, name), repr(e)))"
    )?;
    writeln!(w)?;
    writeln!(w, "def _struct(decl):")?;
    writeln!(w, "    try:")?;
    writeln!(w, "        til = ida_typeinf.get_idati()")?;
    writeln!(
        w,
        "        rc = ida_typeinf.parse_decls(til, decl, None, ida_typeinf.PT_TYP)"
    )?;
    // ida_typeinf.parse_decls returns the number of errors, so 0 means
    // success. Any positive value indicates the parser rejected at least
    // one struct in the supplied decl block.
    writeln!(w, "        if rc == 0:")?;
    writeln!(w, "            _stats['struct_ok'] += 1")?;
    writeln!(w, "        else:")?;
    writeln!(w, "            _stats['struct_fail'] += 1")?;
    writeln!(
        w,
        "            _stats['failures'].append(('struct', decl.split('{{')[0].strip()[:80], 'IDA parse_decls returned {{}} errors'.format(rc)))"
    )?;
    writeln!(w, "    except Exception as e:")?;
    writeln!(w, "        _stats['struct_fail'] += 1")?;
    writeln!(
        w,
        "        _stats['failures'].append(('struct', decl.split('{{')[0].strip()[:80], repr(e)))"
    )?;
    writeln!(w)?;

    for f in funcs {
        let name = sanitize_label(&f.name);
        let sig = sig_for(f, signatures);
        let comment = function_comment(f, sig.as_deref());
        writeln!(
            w,
            "_func(0x{:x}, {}, {})",
            f.address,
            escape_py(&name),
            escape_py(&comment),
        )?;
    }

    if !types.is_empty() {
        writeln!(w)?;
        writeln!(
            w,
            "# Recovered struct types ({} total)",
            count_struct_types(types)
        )?;
        for decl in struct_c_decls(types) {
            writeln!(w, "_struct({})", escape_py(&decl))?;
        }
    }

    emit_stats_postamble(w, generator)?;
    Ok(())
}

fn write_ghidra<W: Write>(
    w: &mut W,
    funcs: &[Function],
    types: &[Type],
    signatures: Option<&std::collections::HashMap<u64, String>>,
    generator: &str,
) -> io::Result<()> {
    writeln!(
        w,
        "# Generated by {generator}. Run inside Ghidra: Window -> Script Manager (Python)."
    )?;
    writeln!(w, "# @author Riven Labs")?;
    writeln!(w, "# @category {generator}")?;
    writeln!(w, "# @keybinding")?;
    writeln!(w, "# @menupath Tools.{generator}.Apply recovered symbols")?;
    writeln!(w, "# @toolbar")?;
    writeln!(w, "# @runtime PyGhidra")?;
    writeln!(
        w,
        "# @description Apply {generator}-recovered Go function names, file:line comments, and struct types to the current program."
    )?;
    writeln!(w)?;
    writeln!(
        w,
        "from ghidra.program.model.symbol.SourceType import USER_DEFINED"
    )?;
    writeln!(w, "from ghidra.app.util.cparser.C import CParser")?;
    writeln!(
        w,
        "from ghidra.program.model.data import DataTypeConflictHandler"
    )?;
    writeln!(w)?;
    writeln!(w, "fm = currentProgram.getFunctionManager()")?;
    writeln!(w, "af = currentProgram.getAddressFactory()")?;
    writeln!(w, "dtm = currentProgram.getDataTypeManager()")?;
    writeln!(w, "listing = currentProgram.getListing()")?;
    writeln!(w)?;
    emit_stats_preamble(w)?;
    writeln!(w, "def _func(addr, name, comment):")?;
    writeln!(w, "    label = '0x{{:x}} {{}}'.format(addr, name)")?;
    writeln!(w, "    try:")?;
    writeln!(
        w,
        "        a = af.getDefaultAddressSpace().getAddress(addr)"
    )?;
    writeln!(w, "        f = fm.getFunctionAt(a)")?;
    writeln!(w, "        if f is None:")?;
    writeln!(
        w,
        "            f = fm.createFunction(name, a, None, USER_DEFINED)"
    )?;
    writeln!(w, "        else:")?;
    writeln!(w, "            f.setName(name, USER_DEFINED)")?;
    writeln!(w, "        if comment:")?;
    writeln!(w, "            f.setComment(comment)")?;
    writeln!(w, "        _stats['func_ok'] += 1")?;
    writeln!(w, "    except Exception as e:")?;
    writeln!(w, "        _stats['func_fail'] += 1")?;
    writeln!(
        w,
        "        _stats['failures'].append(('func', label, repr(e)))"
    )?;
    writeln!(w)?;
    writeln!(w, "def _struct(decl):")?;
    writeln!(w, "    label = decl.split('{{')[0].strip()[:80]")?;
    writeln!(w, "    try:")?;
    writeln!(w, "        parser = CParser(dtm)")?;
    writeln!(w, "        parsed = parser.parse(decl)")?;
    writeln!(w, "        if parsed is None:")?;
    writeln!(w, "            _stats['struct_fail'] += 1")?;
    writeln!(
        w,
        "            _stats['failures'].append(('struct', label, 'CParser returned None'))"
    )?;
    writeln!(w, "            return")?;
    writeln!(
        w,
        "        dtm.addDataType(parsed, DataTypeConflictHandler.REPLACE_HANDLER)"
    )?;
    writeln!(w, "        _stats['struct_ok'] += 1")?;
    writeln!(w, "    except Exception as e:")?;
    writeln!(w, "        _stats['struct_fail'] += 1")?;
    writeln!(
        w,
        "        _stats['failures'].append(('struct', label, repr(e)))"
    )?;
    writeln!(w)?;

    for f in funcs {
        let name = sanitize_label(&f.name);
        let sig = sig_for(f, signatures);
        let comment = function_comment(f, sig.as_deref());
        writeln!(
            w,
            "_func(0x{:x}, {}, {})",
            f.address,
            escape_py(&name),
            escape_py(&comment),
        )?;
    }

    if !types.is_empty() {
        writeln!(w)?;
        writeln!(
            w,
            "# Recovered struct types ({} total)",
            count_struct_types(types)
        )?;
        for decl in struct_c_decls(types) {
            writeln!(w, "_struct({})", escape_py(&decl))?;
        }
    }

    emit_stats_postamble(w, generator)?;
    Ok(())
}

fn write_binja<W: Write>(
    w: &mut W,
    funcs: &[Function],
    types: &[Type],
    signatures: Option<&std::collections::HashMap<u64, String>>,
    generator: &str,
) -> io::Result<()> {
    writeln!(w, "# Generated by {generator}. Run inside Binary Ninja:")?;
    writeln!(
        w,
        "#   bv = binaryninja.load('binary'); exec(open('this.py').read())"
    )?;
    writeln!(
        w,
        "from binaryninja import Symbol, SymbolType, Type as BNType"
    )?;
    writeln!(w)?;
    emit_stats_preamble(w)?;
    writeln!(w, "def _func(addr, name, comment):")?;
    writeln!(w, "    label = '0x{{:x}} {{}}'.format(addr, name)")?;
    writeln!(w, "    try:")?;
    writeln!(w, "        bv.add_function(addr)")?;
    writeln!(
        w,
        "        bv.define_user_symbol(Symbol(SymbolType.FunctionSymbol, addr, name))"
    )?;
    writeln!(w, "        if comment:")?;
    writeln!(w, "            f = bv.get_function_at(addr)")?;
    writeln!(w, "            if f is not None:")?;
    writeln!(w, "                f.comment = comment")?;
    writeln!(w, "        _stats['func_ok'] += 1")?;
    writeln!(w, "    except Exception as e:")?;
    writeln!(w, "        _stats['func_fail'] += 1")?;
    writeln!(
        w,
        "        _stats['failures'].append(('func', label, repr(e)))"
    )?;
    writeln!(w)?;
    writeln!(w, "def _struct(decl):")?;
    writeln!(w, "    label = decl.split('{{')[0].strip()[:80]")?;
    writeln!(w, "    try:")?;
    writeln!(w, "        types = bv.parse_types_from_string(decl)")?;
    writeln!(w, "        for name, typ in types.types.items():")?;
    writeln!(w, "            bv.define_user_type(name, typ)")?;
    writeln!(w, "        _stats['struct_ok'] += 1")?;
    writeln!(w, "    except Exception as e:")?;
    writeln!(w, "        _stats['struct_fail'] += 1")?;
    writeln!(
        w,
        "        _stats['failures'].append(('struct', label, repr(e)))"
    )?;
    writeln!(w)?;

    for f in funcs {
        let name = sanitize_label(&f.name);
        let sig = sig_for(f, signatures);
        let comment = function_comment(f, sig.as_deref());
        writeln!(
            w,
            "_func(0x{:x}, {}, {})",
            f.address,
            escape_py(&name),
            escape_py(&comment),
        )?;
    }

    if !types.is_empty() {
        writeln!(w)?;
        writeln!(
            w,
            "# Recovered struct types ({} total)",
            count_struct_types(types)
        )?;
        for decl in struct_c_decls(types) {
            writeln!(w, "_struct({})", escape_py(&decl))?;
        }
    }

    emit_stats_postamble(w, generator)?;
    Ok(())
}

/// Emit the shared Python preamble that initializes the per-script
/// success/failure counters. Every writer calls this once before the
/// per-symbol _func() and _struct() calls so the helpers have a place
/// to record what landed and what did not.
fn emit_stats_preamble<W: Write>(w: &mut W) -> io::Result<()> {
    writeln!(w, "_stats = {{")?;
    writeln!(w, "    'func_ok': 0,")?;
    writeln!(w, "    'func_fail': 0,")?;
    writeln!(w, "    'struct_ok': 0,")?;
    writeln!(w, "    'struct_fail': 0,")?;
    writeln!(w, "    'failures': [],")?;
    writeln!(w, "}}")?;
    writeln!(w)?;
    Ok(())
}

/// Emit the shared Python postamble that prints honest counts and a
/// per-failure breakdown. Called once at the bottom of every writer
/// after the last _func() / _struct() call.
fn emit_stats_postamble<W: Write>(w: &mut W, generator: &str) -> io::Result<()> {
    writeln!(w)?;
    writeln!(w, "_func_total = _stats['func_ok'] + _stats['func_fail']")?;
    writeln!(
        w,
        "_struct_total = _stats['struct_ok'] + _stats['struct_fail']"
    )?;
    writeln!(
        w,
        "print('{generator}: applied {{}}/{{}} symbols ({{}} failed)'.format(_stats['func_ok'], _func_total, _stats['func_fail']))"
    )?;
    writeln!(
        w,
        "print('{generator}: applied {{}}/{{}} struct types ({{}} failed)'.format(_stats['struct_ok'], _struct_total, _stats['struct_fail']))"
    )?;
    // Limit the per-failure dump to keep the Script Manager output
    // readable; surface enough to start debugging without dumping
    // thousands of lines on a bad export.
    writeln!(w, "if _stats['failures']:")?;
    writeln!(
        w,
        "    print('{generator}: first {{}} failures:'.format(min(20, len(_stats['failures']))))"
    )?;
    writeln!(w, "    for kind, key, reason in _stats['failures'][:20]:")?;
    writeln!(
        w,
        "        print('  {{}}  {{}}  {{}}'.format(kind, key, reason))"
    )?;
    writeln!(w, "    if len(_stats['failures']) > 20:")?;
    writeln!(
        w,
        "        print('  ... and {{}} more (see _stats[\"failures\"] for the full list)'.format(len(_stats['failures']) - 20))"
    )?;
    Ok(())
}

/// Sanitize a Go symbol name into a label the disassembler will accept.
/// Go names contain `.`, `(`, `)`, `*`, `[`, `]`, `/`, `,`, `<-`, etc.
/// IDA accepts most of these; Ghidra is stricter. We map the universally
/// rejected characters to `_` and keep `.` since both tools tolerate it.
fn sanitize_label(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    for ch in name.chars() {
        match ch {
            'a'..='z' | 'A'..='Z' | '0'..='9' | '_' | '.' | '$' => out.push(ch),
            // Replace structural chars with underscore. The original full name
            // ends up in the function comment so nothing is lost.
            '(' | ')' | '[' | ']' | '*' | '/' | ',' | ' ' | '-' | '<' | '>' | '{' | '}' | ':'
            | ';' | '"' | '\'' | '?' | '!' | '#' | '@' | '\\' | '+' | '=' | '&' | '|' | '^'
            | '~' | '%' => out.push('_'),
            _ => out.push('_'),
        }
    }
    // Disassemblers reject labels starting with a digit.
    if out
        .chars()
        .next()
        .map(|c| c.is_ascii_digit())
        .unwrap_or(false)
    {
        out.insert(0, '_');
    }
    if out.is_empty() {
        out.push('_');
    }
    out
}

/// Per-function comment: "go: <full name>\n<file>:<line>".
fn function_comment(f: &Function, signature: Option<&str>) -> String {
    let mut s = format!("go: {}", f.name);
    if let Some(sig) = signature {
        s.push_str(sig);
    }
    if let Some(file) = &f.file {
        s.push('\n');
        s.push_str(file);
        if let Some(line) = f.start_line {
            s.push(':');
            s.push_str(&line.to_string());
        }
    }
    s
}

fn count_struct_types(types: &[Type]) -> usize {
    types
        .iter()
        .filter(|t| matches!(t.kind_data, KindData::Struct { .. }))
        .count()
}

/// Produce C struct declarations for every recovered Go struct type.
/// Fields whose types we can't easily express in C (other structs, slices,
/// interfaces) become opaque byte arrays of the right size so the layout
/// stays correct in the disassembler's struct view.
/// C keywords and Ghidra-CParser reserved words that would collide with a
/// Go field name. Any field whose sanitized name lands in this set gets a
/// trailing underscore so the C parser doesn't reject the whole struct.
///
/// The collision is real: `runtime.boundsError` has a Go field named
/// `signed bool`, which renders as `unsigned char signed;` and breaks the
/// parse silently. Same story for any Go type with a field named after a
/// C type-specifier or storage-class keyword.
fn is_c_reserved(name: &str) -> bool {
    matches!(
        name,
        "auto"
            | "break"
            | "case"
            | "char"
            | "const"
            | "continue"
            | "default"
            | "do"
            | "double"
            | "else"
            | "enum"
            | "extern"
            | "float"
            | "for"
            | "goto"
            | "if"
            | "inline"
            | "int"
            | "long"
            | "register"
            | "restrict"
            | "return"
            | "short"
            | "signed"
            | "sizeof"
            | "static"
            | "struct"
            | "switch"
            | "typedef"
            | "union"
            | "unsigned"
            | "void"
            | "volatile"
            | "while"
            | "_Alignas"
            | "_Alignof"
            | "_Atomic"
            | "_Bool"
            | "_Complex"
            | "_Generic"
            | "_Imaginary"
            | "_Noreturn"
            | "_Static_assert"
            | "_Thread_local"
    )
}

/// Escape a field name that would otherwise collide with a C reserved
/// keyword. Suffix with `_`. The original Go field name is preserved in
/// the recovered function comment elsewhere; this is only the C-decl
/// identifier used by the disassembler's parser.
fn escape_c_field_name(name: &str) -> String {
    if is_c_reserved(name) {
        format!("{name}_")
    } else {
        name.to_string()
    }
}

fn struct_c_decls(types: &[Type]) -> Vec<String> {
    let by_addr: std::collections::HashMap<u64, &Type> =
        types.iter().map(|t| (t.addr, t)).collect();
    let mut decls = Vec::new();
    let mut emitted_names: std::collections::HashSet<String> = std::collections::HashSet::new();

    for t in types {
        let KindData::Struct { fields } = &t.kind_data else {
            continue;
        };
        let c_name = sanitize_label(&t.name);
        if c_name.is_empty() || !emitted_names.insert(c_name.clone()) {
            continue;
        }
        let mut decl = format!("struct {} {{\n", c_name);
        let mut next_offset = 0u64;
        let mut emitted = 0usize;
        for (idx, field) in fields.iter().enumerate() {
            let fsize = field_size(field, &by_addr);
            // Zero-size fields (Go marker types like sys.NotInHeap, struct{})
            // would render as `unsigned char foo[0];` which some C parsers
            // (including Ghidra's CParser on some versions) reject. Skip them.
            if fsize == 0 {
                continue;
            }
            // Pad to the field's offset if Go inserted alignment padding.
            if field.offset > next_offset {
                let pad = field.offset - next_offset;
                decl.push_str(&format!("    unsigned char _pad_{idx}[{pad}];\n"));
                next_offset = field.offset;
            }
            let (prefix, suffix) = c_type_for_field(field, &by_addr);
            let fname = sanitize_label(&field.name);
            let fname = if fname.is_empty() || fname == "_" {
                format!("_anon_{idx}")
            } else {
                escape_c_field_name(&fname)
            };
            decl.push_str(&format!("    {prefix} {fname}{suffix};\n"));
            next_offset += fsize;
            emitted += 1;
        }
        if next_offset < t.size {
            let tail = t.size - next_offset;
            decl.push_str(&format!("    unsigned char _tail[{tail}];\n"));
        }
        // Empty structs would emit `struct foo {};` which Ghidra rejects.
        if emitted == 0 && t.size == 0 {
            // Zero-size struct (Go's `struct{}` family). Skip; nothing to model.
            continue;
        }
        decl.push_str("};\n");
        decls.push(decl);
    }
    decls
}

fn field_size(field: &StructField, by_addr: &std::collections::HashMap<u64, &Type>) -> u64 {
    by_addr.get(&field.typ).map(|t| t.size).unwrap_or(8)
}

/// Map a Go field to a C type that has the right byte size. We don't try to
/// preserve semantic types (the field's "real" type is in the unstrip JSON);
/// we only need correct sizing so the disassembler's struct view shows
/// field-aligned offsets.
/// Returns `(type_prefix, suffix)` so callers can emit `<prefix> <name><suffix>`.
/// C array fields look like `unsigned char field[16];` (suffix is `[16]`);
/// most other types have empty suffix.
fn c_type_for_field(
    field: &StructField,
    by_addr: &std::collections::HashMap<u64, &Type>,
) -> (String, String) {
    let Some(t) = by_addr.get(&field.typ) else {
        return ("void *".into(), String::new());
    };
    match t.kind {
        KindName::Bool | KindName::Uint8 | KindName::Int8 => {
            ("unsigned char".into(), String::new())
        }
        KindName::Int16 | KindName::Uint16 => ("unsigned short".into(), String::new()),
        KindName::Int32 | KindName::Uint32 | KindName::Float32 => {
            ("unsigned int".into(), String::new())
        }
        KindName::Int64
        | KindName::Uint64
        | KindName::Float64
        | KindName::Int
        | KindName::Uint
        | KindName::Uintptr => ("unsigned long long".into(), String::new()),
        KindName::Pointer
        | KindName::UnsafePointer
        | KindName::Chan
        | KindName::Map
        | KindName::Func => ("void *".into(), String::new()),
        // Sized aggregates become opaque byte arrays. Disassembler still
        // sees the right struct layout, and the field name preserves intent.
        _ => ("unsigned char".into(), format!("[{}]", t.size)),
    }
}

/// Python single-quoted string literal with `\` and `'` escaped. Go symbol
/// names can contain `()`, `[]`, `*`, and other punctuation but no quotes;
/// escaping `'`, `\`, and newlines (for multi-line comments) is sufficient.
fn escape_py(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('\'');
    for c in s.chars() {
        match c {
            '\\' => out.push_str("\\\\"),
            '\'' => out.push_str("\\'"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\x{:02x}", c as u32)),
            c => out.push(c),
        }
    }
    out.push('\'');
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn escapes_quotes_and_backslashes() {
        assert_eq!(escape_py("a'b"), "'a\\'b'");
        assert_eq!(escape_py("a\\b"), "'a\\\\b'");
    }

    #[test]
    fn passes_normal_go_names() {
        assert_eq!(escape_py("main.main"), "'main.main'");
        assert_eq!(escape_py("(*os.File).Read"), "'(*os.File).Read'");
    }

    #[test]
    fn sanitize_label_handles_go_punctuation() {
        assert_eq!(sanitize_label("main.main"), "main.main");
        assert_eq!(sanitize_label("(*os.File).Read"), "__os.File_.Read");
        assert_eq!(
            sanitize_label("main.Set[go.shape.string]"),
            "main.Set_go.shape.string_"
        );
        assert_eq!(sanitize_label("123main"), "_123main");
    }

    #[test]
    fn escapes_newlines_in_comments() {
        assert_eq!(escape_py("a\nb"), "'a\\nb'");
    }
}