Source file
src/cmd/cgo/out.go
1
2
3
4
5 package main
6
7 import (
8 "bytes"
9 "cmd/internal/pkgpath"
10 "debug/elf"
11 "debug/macho"
12 "debug/pe"
13 "fmt"
14 "go/ast"
15 "go/printer"
16 "go/token"
17 "internal/buildcfg"
18 "internal/xcoff"
19 "io"
20 "os"
21 "os/exec"
22 "path/filepath"
23 "regexp"
24 "sort"
25 "strings"
26 "unicode"
27 )
28
29 var (
30 conf = printer.Config{Mode: printer.SourcePos, Tabwidth: 8}
31 noSourceConf = printer.Config{Tabwidth: 8}
32 )
33
34
35 func (p *Package) writeDefs() {
36 var fgo2, fc io.Writer
37 f := creat("_cgo_gotypes.go")
38 defer f.Close()
39 fgo2 = f
40 if *gccgo {
41 f := creat("_cgo_defun.c")
42 defer f.Close()
43 fc = f
44 }
45 fm := creat("_cgo_main.c")
46
47 var gccgoInit strings.Builder
48
49 if !*gccgo {
50 for _, arg := range p.LdFlags {
51 fmt.Fprintf(fgo2, "//go:cgo_ldflag %q\n", arg)
52 }
53 } else {
54 fflg := creat("_cgo_flags")
55 for _, arg := range p.LdFlags {
56 fmt.Fprintf(fflg, "_CGO_LDFLAGS=%s\n", arg)
57 }
58 fflg.Close()
59 }
60
61
62 fmt.Fprintf(fm, "#include <stddef.h>\n")
63 fmt.Fprintf(fm, "int main(int argc __attribute__((unused)), char **argv __attribute__((unused))) { return 0; }\n")
64 if *importRuntimeCgo {
65 fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*) __attribute__((unused)), void *a __attribute__((unused)), int c __attribute__((unused)), size_t ctxt __attribute__((unused))) { }\n")
66 fmt.Fprintf(fm, "size_t _cgo_wait_runtime_init_done(void) { return 0; }\n")
67 fmt.Fprintf(fm, "void _cgo_release_context(size_t ctxt __attribute__((unused))) { }\n")
68 fmt.Fprintf(fm, "char* _cgo_topofstack(void) { return (char*)0; }\n")
69 if buildcfg.Experiment.RuntimeCgoPurego {
70 fmt.Fprintf(fm, "void (*_cgo_tsan_acquire_fn)(void*);\n")
71 fmt.Fprintf(fm, "void (*_cgo_tsan_release_fn)(void*);\n")
72 fmt.Fprintf(fm, "void (*_cgo_yield)(void);\n")
73 }
74 } else {
75
76
77 fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*), void *a, int c, size_t ctxt);\n")
78 fmt.Fprintf(fm, "size_t _cgo_wait_runtime_init_done(void);\n")
79 fmt.Fprintf(fm, "void _cgo_release_context(size_t);\n")
80 }
81 fmt.Fprintf(fm, "void _cgo_allocate(void *a __attribute__((unused)), int c __attribute__((unused))) { }\n")
82 fmt.Fprintf(fm, "void _cgo_panic(void *a __attribute__((unused)), int c __attribute__((unused))) { }\n")
83 fmt.Fprintf(fm, "void _cgo_reginit(void) { }\n")
84
85
86
87
88 fmt.Fprintf(fgo2, "// Code generated by cmd/cgo; DO NOT EDIT.\n\n")
89 fmt.Fprintf(fgo2, "package %s\n\n", p.PackageName)
90 fmt.Fprintf(fgo2, "import \"unsafe\"\n\n")
91 if *importSyscall {
92 fmt.Fprintf(fgo2, "import \"syscall\"\n\n")
93 }
94 if *importRuntimeCgo {
95 if !*gccgoDefineCgoIncomplete {
96 fmt.Fprintf(fgo2, "import _cgopackage \"runtime/cgo\"\n\n")
97 fmt.Fprintf(fgo2, "type _ _cgopackage.Incomplete\n")
98 } else {
99 fmt.Fprintf(fgo2, "//go:notinheap\n")
100 fmt.Fprintf(fgo2, "type _cgopackage_Incomplete struct{ _ struct{ _ struct{} } }\n")
101 }
102 }
103 if *importSyscall {
104 fmt.Fprintf(fgo2, "var _ syscall.Errno\n")
105 }
106 fmt.Fprintf(fgo2, "func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }\n\n")
107
108 if !*gccgo {
109 fmt.Fprintf(fgo2, "//go:linkname _Cgo_always_false runtime.cgoAlwaysFalse\n")
110 fmt.Fprintf(fgo2, "var _Cgo_always_false bool\n")
111 fmt.Fprintf(fgo2, "//go:linkname _Cgo_use runtime.cgoUse\n")
112 fmt.Fprintf(fgo2, "func _Cgo_use(interface{})\n")
113 fmt.Fprintf(fgo2, "//go:linkname _Cgo_keepalive runtime.cgoKeepAlive\n")
114 fmt.Fprintf(fgo2, "//go:noescape\n")
115 fmt.Fprintf(fgo2, "func _Cgo_keepalive(interface{})\n")
116 }
117 fmt.Fprintf(fgo2, "//go:linkname _Cgo_no_callback runtime.cgoNoCallback\n")
118 fmt.Fprintf(fgo2, "func _Cgo_no_callback(bool)\n")
119
120 typedefNames := make([]string, 0, len(typedef))
121 for name := range typedef {
122 if name == "_Ctype_void" {
123
124
125 continue
126 }
127 typedefNames = append(typedefNames, name)
128 }
129 sort.Strings(typedefNames)
130 for _, name := range typedefNames {
131 def := typedef[name]
132 fmt.Fprintf(fgo2, "type %s ", name)
133
134
135
136
137
138
139
140
141
142
143
144
145 var buf bytes.Buffer
146 noSourceConf.Fprint(&buf, fset, def.Go)
147 if bytes.HasPrefix(buf.Bytes(), []byte("_Ctype_")) ||
148 strings.HasPrefix(name, "_Ctype_enum_") ||
149 strings.HasPrefix(name, "_Ctype_union_") {
150
151 fmt.Fprintf(fgo2, "= ")
152 }
153 fmt.Fprintf(fgo2, "%s", buf.Bytes())
154 fmt.Fprintf(fgo2, "\n\n")
155 }
156 if *gccgo {
157 fmt.Fprintf(fgo2, "type _Ctype_void byte\n")
158 } else {
159 fmt.Fprintf(fgo2, "type _Ctype_void [0]byte\n")
160 }
161
162 if *gccgo {
163 fmt.Fprint(fgo2, gccgoGoProlog)
164 fmt.Fprint(fc, p.cPrologGccgo())
165 } else {
166 fmt.Fprint(fgo2, goProlog)
167 }
168
169 if fc != nil {
170 fmt.Fprintf(fc, "#line 1 \"cgo-generated-wrappers\"\n")
171 }
172 if fm != nil {
173 fmt.Fprintf(fm, "#line 1 \"cgo-generated-wrappers\"\n")
174 }
175
176 gccgoSymbolPrefix := p.gccgoSymbolPrefix()
177
178 cVars := make(map[string]bool)
179 for _, key := range nameKeys(p.Name) {
180 n := p.Name[key]
181 if !n.IsVar() {
182 continue
183 }
184
185 if !cVars[n.C] {
186 if *gccgo {
187 fmt.Fprintf(fc, "extern byte *%s;\n", n.C)
188 } else {
189
190
191
192
193
194
195 if n.Kind == "fpvar" {
196 fmt.Fprintf(fm, "extern void %s();\n", n.C)
197 } else {
198 fmt.Fprintf(fm, "extern char %s[];\n", n.C)
199 fmt.Fprintf(fm, "void *_cgohack_%s = %s;\n\n", n.C, n.C)
200 }
201 fmt.Fprintf(fgo2, "//go:linkname __cgo_%s %s\n", n.C, n.C)
202 fmt.Fprintf(fgo2, "//go:cgo_import_static %s\n", n.C)
203 fmt.Fprintf(fgo2, "var __cgo_%s byte\n", n.C)
204 }
205 cVars[n.C] = true
206 }
207
208 var node ast.Node
209 if n.Kind == "var" {
210 node = &ast.StarExpr{X: n.Type.Go}
211 } else if n.Kind == "fpvar" {
212 node = n.Type.Go
213 } else {
214 panic(fmt.Errorf("invalid var kind %q", n.Kind))
215 }
216 if *gccgo {
217 fmt.Fprintf(fc, `extern void *%s __asm__("%s.%s");`, n.Mangle, gccgoSymbolPrefix, gccgoToSymbol(n.Mangle))
218 fmt.Fprintf(&gccgoInit, "\t%s = &%s;\n", n.Mangle, n.C)
219 fmt.Fprintf(fc, "\n")
220 }
221
222 fmt.Fprintf(fgo2, "var %s ", n.Mangle)
223 conf.Fprint(fgo2, fset, node)
224 if !*gccgo {
225 fmt.Fprintf(fgo2, " = (")
226 conf.Fprint(fgo2, fset, node)
227 fmt.Fprintf(fgo2, ")(unsafe.Pointer(&__cgo_%s))", n.C)
228 }
229 fmt.Fprintf(fgo2, "\n")
230 }
231 if *gccgo {
232 fmt.Fprintf(fc, "\n")
233 }
234
235 for _, key := range nameKeys(p.Name) {
236 n := p.Name[key]
237 if n.Const != "" {
238 fmt.Fprintf(fgo2, "const %s = %s\n", n.Mangle, n.Const)
239 }
240 }
241 fmt.Fprintf(fgo2, "\n")
242
243 callsMalloc := false
244 for _, key := range nameKeys(p.Name) {
245 n := p.Name[key]
246 if n.FuncType != nil {
247 p.writeDefsFunc(fgo2, n, &callsMalloc)
248 }
249 }
250
251 fgcc := creat("_cgo_export.c")
252 fgcch := creat("_cgo_export.h")
253 if *gccgo {
254 p.writeGccgoExports(fgo2, fm, fgcc, fgcch)
255 } else {
256 p.writeExports(fgo2, fm, fgcc, fgcch)
257 }
258
259 if callsMalloc && !*gccgo {
260 fmt.Fprint(fgo2, strings.ReplaceAll(cMallocDefGo, "PREFIX", cPrefix))
261 fmt.Fprint(fgcc, strings.ReplaceAll(strings.Replace(cMallocDefC, "PREFIX", cPrefix, -1), "PACKED", p.packedAttribute()))
262 }
263
264 if err := fgcc.Close(); err != nil {
265 fatalf("%s", err)
266 }
267 if err := fgcch.Close(); err != nil {
268 fatalf("%s", err)
269 }
270
271 if *exportHeader != "" && len(p.ExpFunc) > 0 {
272 fexp, err := os.Create(*exportHeader)
273 if err != nil {
274 fatalf("%s", err)
275 }
276 fgcch, err := os.Open(filepath.Join(outputDir(), "_cgo_export.h"))
277 if err != nil {
278 fatalf("%s", err)
279 }
280 defer fgcch.Close()
281 _, err = io.Copy(fexp, fgcch)
282 if err != nil {
283 fatalf("%s", err)
284 }
285 if err = fexp.Close(); err != nil {
286 fatalf("%s", err)
287 }
288 }
289
290 init := gccgoInit.String()
291 if init != "" {
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307 fmt.Fprintln(fc, "static void init(void) __attribute__ ((constructor, no_split_stack));")
308 fmt.Fprintln(fc, "static void init(void) {")
309 fmt.Fprint(fc, init)
310 fmt.Fprintln(fc, "}")
311 }
312 }
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328 func elfImportedSymbols(f *elf.File) []elf.ImportedSymbol {
329 syms, _ := f.DynamicSymbols()
330 var imports []elf.ImportedSymbol
331 for _, s := range syms {
332 if (elf.ST_BIND(s.Info) == elf.STB_GLOBAL || elf.ST_BIND(s.Info) == elf.STB_WEAK) && s.Section == elf.SHN_UNDEF {
333 imports = append(imports, elf.ImportedSymbol{
334 Name: s.Name,
335 Library: s.Library,
336 Version: s.Version,
337 })
338 }
339 }
340 return imports
341 }
342
343 func dynimport(obj string) {
344 stdout := os.Stdout
345 if *dynout != "" {
346 f, err := os.Create(*dynout)
347 if err != nil {
348 fatalf("%s", err)
349 }
350 defer func() {
351 if err = f.Close(); err != nil {
352 fatalf("error closing %s: %v", *dynout, err)
353 }
354 }()
355
356 stdout = f
357 }
358
359 fmt.Fprintf(stdout, "package %s\n", *dynpackage)
360
361 if f, err := elf.Open(obj); err == nil {
362 defer f.Close()
363 if *dynlinker {
364
365 if sec := f.Section(".interp"); sec != nil {
366 if data, err := sec.Data(); err == nil && len(data) > 1 {
367
368 fmt.Fprintf(stdout, "//go:cgo_dynamic_linker %q\n", string(data[:len(data)-1]))
369 }
370 }
371 }
372 sym := elfImportedSymbols(f)
373 for _, s := range sym {
374 targ := s.Name
375 if s.Version != "" {
376 targ += "#" + s.Version
377 }
378 checkImportSymName(s.Name)
379 checkImportSymName(targ)
380 fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", s.Name, targ, s.Library)
381 }
382 lib, _ := f.ImportedLibraries()
383 for _, l := range lib {
384 fmt.Fprintf(stdout, "//go:cgo_import_dynamic _ _ %q\n", l)
385 }
386 return
387 }
388
389 if f, err := macho.Open(obj); err == nil {
390 defer f.Close()
391 sym, _ := f.ImportedSymbols()
392 for _, s := range sym {
393 s = strings.TrimPrefix(s, "_")
394 checkImportSymName(s)
395 fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", s, s, "")
396 }
397 lib, _ := f.ImportedLibraries()
398 for _, l := range lib {
399 fmt.Fprintf(stdout, "//go:cgo_import_dynamic _ _ %q\n", l)
400 }
401 return
402 }
403
404 if f, err := pe.Open(obj); err == nil {
405 defer f.Close()
406 sym, _ := f.ImportedSymbols()
407 for _, s := range sym {
408 ss := strings.Split(s, ":")
409 name := strings.Split(ss[0], "@")[0]
410 checkImportSymName(name)
411 checkImportSymName(ss[0])
412 dll := strings.ToLower(ss[1])
413 checkImportSymName(dll)
414 if strings.Contains(dll, "/") || strings.Contains(dll, `\`) || strings.Contains(dll, "..") || strings.Contains(dll, ":") {
415 fatalf("dynamic library %q contains unsupported path characters", ss[1])
416 }
417 fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", name, ss[0], dll)
418 }
419 return
420 }
421
422 if f, err := xcoff.Open(obj); err == nil {
423 defer f.Close()
424 sym, err := f.ImportedSymbols()
425 if err != nil {
426 fatalf("cannot load imported symbols from XCOFF file %s: %v", obj, err)
427 }
428 for _, s := range sym {
429 if s.Name == "runtime_rt0_go" || s.Name == "_rt0_ppc64_aix_lib" {
430
431
432
433 continue
434 }
435 checkImportSymName(s.Name)
436 fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", s.Name, s.Name, s.Library)
437 }
438 lib, err := f.ImportedLibraries()
439 if err != nil {
440 fatalf("cannot load imported libraries from XCOFF file %s: %v", obj, err)
441 }
442 for _, l := range lib {
443 fmt.Fprintf(stdout, "//go:cgo_import_dynamic _ _ %q\n", l)
444 }
445 return
446 }
447
448 fatalf("cannot parse %s as ELF, Mach-O, PE or XCOFF", obj)
449 }
450
451
452
453
454
455
456
457 func checkImportSymName(s string) {
458 for _, c := range s {
459 if !unicode.IsGraphic(c) || unicode.IsSpace(c) {
460 fatalf("dynamic symbol %q contains unsupported character", s)
461 }
462 }
463 if strings.Contains(s, "//") || strings.Contains(s, "/*") {
464 fatalf("dynamic symbol %q contains Go comment", s)
465 }
466 }
467
468
469
470
471
472
473 func (p *Package) structType(n *Name) (string, int64) {
474
475
476
477
478
479 stripConst := func(s string) string {
480 i := strings.LastIndex(s, "const")
481 if i == -1 {
482 return s
483 }
484
485
486 if r, ok := strings.CutSuffix(s, "const"); ok {
487 return strings.TrimSpace(r)
488 }
489
490 var nonConst []string
491 for _, f := range strings.Fields(s[i:]) {
492 switch f {
493 case "const":
494 case "restrict", "volatile":
495 nonConst = append(nonConst, f)
496 default:
497 return s
498 }
499 }
500
501 return strings.TrimSpace(s[:i]) + " " + strings.Join(nonConst, " ")
502 }
503
504 var buf strings.Builder
505 fmt.Fprint(&buf, "struct {\n")
506 off := int64(0)
507 for i, t := range n.FuncType.Params {
508 if off%t.Align != 0 {
509 pad := t.Align - off%t.Align
510 fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
511 off += pad
512 }
513 c := t.Typedef
514 if c == "" {
515 c = stripConst(t.C.String())
516 }
517 fmt.Fprintf(&buf, "\t\t%s p%d;\n", c, i)
518 off += t.Size
519 }
520 if off%p.PtrSize != 0 {
521 pad := p.PtrSize - off%p.PtrSize
522 fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
523 off += pad
524 }
525 if t := n.FuncType.Result; t != nil {
526 if off%t.Align != 0 {
527 pad := t.Align - off%t.Align
528 fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
529 off += pad
530 }
531 fmt.Fprintf(&buf, "\t\t%s r;\n", stripConst(t.C.String()))
532 off += t.Size
533 }
534 if off%p.PtrSize != 0 {
535 pad := p.PtrSize - off%p.PtrSize
536 fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
537 off += pad
538 }
539 if off == 0 {
540 fmt.Fprintf(&buf, "\t\tchar unused;\n")
541 }
542 fmt.Fprintf(&buf, "\t}")
543 return buf.String(), off
544 }
545
546 func (p *Package) writeDefsFunc(fgo2 io.Writer, n *Name, callsMalloc *bool) {
547 name := n.Go
548 gtype := n.FuncType.Go
549 void := gtype.Results == nil || len(gtype.Results.List) == 0
550 if n.AddError {
551
552
553 err := &ast.Field{Type: ast.NewIdent("error")}
554 l := gtype.Results.List
555 if len(l) == 0 {
556 l = []*ast.Field{err}
557 } else {
558 l = []*ast.Field{l[0], err}
559 }
560 t := new(ast.FuncType)
561 *t = *gtype
562 t.Results = &ast.FieldList{List: l}
563 gtype = t
564 }
565
566
567 d := &ast.FuncDecl{
568 Name: ast.NewIdent(n.Mangle),
569 Type: gtype,
570 }
571
572
573 inProlog := builtinDefs[name] != ""
574 cname := fmt.Sprintf("_cgo%s%s", cPrefix, n.Mangle)
575 paramnames := []string(nil)
576 if d.Type.Params != nil {
577 for i, param := range d.Type.Params.List {
578 paramName := fmt.Sprintf("p%d", i)
579 param.Names = []*ast.Ident{ast.NewIdent(paramName)}
580 paramnames = append(paramnames, paramName)
581 }
582 }
583
584 if *gccgo {
585
586 fmt.Fprint(fgo2, "\n")
587 conf.Fprint(fgo2, fset, d)
588 fmt.Fprint(fgo2, " {\n")
589 if !inProlog {
590 fmt.Fprint(fgo2, "\tdefer syscall.CgocallDone()\n")
591 fmt.Fprint(fgo2, "\tsyscall.Cgocall()\n")
592 }
593 if n.AddError {
594 fmt.Fprint(fgo2, "\tsyscall.SetErrno(0)\n")
595 }
596 fmt.Fprint(fgo2, "\t")
597 if !void {
598 fmt.Fprint(fgo2, "r := ")
599 }
600 fmt.Fprintf(fgo2, "%s(%s)\n", cname, strings.Join(paramnames, ", "))
601
602 if n.AddError {
603 fmt.Fprint(fgo2, "\te := syscall.GetErrno()\n")
604 fmt.Fprint(fgo2, "\tif e != 0 {\n")
605 fmt.Fprint(fgo2, "\t\treturn ")
606 if !void {
607 fmt.Fprint(fgo2, "r, ")
608 }
609 fmt.Fprint(fgo2, "e\n")
610 fmt.Fprint(fgo2, "\t}\n")
611 fmt.Fprint(fgo2, "\treturn ")
612 if !void {
613 fmt.Fprint(fgo2, "r, ")
614 }
615 fmt.Fprint(fgo2, "nil\n")
616 } else if !void {
617 fmt.Fprint(fgo2, "\treturn r\n")
618 }
619
620 fmt.Fprint(fgo2, "}\n")
621
622
623 fmt.Fprintf(fgo2, "//extern %s\n", cname)
624 d.Name = ast.NewIdent(cname)
625 if n.AddError {
626 l := d.Type.Results.List
627 d.Type.Results.List = l[:len(l)-1]
628 }
629 conf.Fprint(fgo2, fset, d)
630 fmt.Fprint(fgo2, "\n")
631
632 return
633 }
634
635 if inProlog {
636 fmt.Fprint(fgo2, builtinDefs[name])
637 if strings.Contains(builtinDefs[name], "_cgo_cmalloc") {
638 *callsMalloc = true
639 }
640 return
641 }
642
643
644 fmt.Fprintf(fgo2, "//go:cgo_import_static %s\n", cname)
645 fmt.Fprintf(fgo2, "//go:linkname __cgofn_%s %s\n", cname, cname)
646 fmt.Fprintf(fgo2, "var __cgofn_%s byte\n", cname)
647 fmt.Fprintf(fgo2, "var %s = unsafe.Pointer(&__cgofn_%s)\n", cname, cname)
648
649 nret := 0
650 if !void {
651 d.Type.Results.List[0].Names = []*ast.Ident{ast.NewIdent("r1")}
652 nret = 1
653 }
654 if n.AddError {
655 d.Type.Results.List[nret].Names = []*ast.Ident{ast.NewIdent("r2")}
656 }
657
658 fmt.Fprint(fgo2, "\n")
659 fmt.Fprint(fgo2, "//go:cgo_unsafe_args\n")
660 conf.Fprint(fgo2, fset, d)
661 fmt.Fprint(fgo2, " {\n")
662
663
664 arg := "0"
665 if len(paramnames) > 0 {
666 arg = "uintptr(unsafe.Pointer(&p0))"
667 } else if !void {
668 arg = "uintptr(unsafe.Pointer(&r1))"
669 }
670
671 noCallback := p.noCallbacks[n.C]
672 if noCallback {
673
674 fmt.Fprintf(fgo2, "\t_Cgo_no_callback(true)\n")
675 }
676
677 prefix := ""
678 if n.AddError {
679 prefix = "errno := "
680 }
681 fmt.Fprintf(fgo2, "\t%s_cgo_runtime_cgocall(%s, %s)\n", prefix, cname, arg)
682 if n.AddError {
683 fmt.Fprintf(fgo2, "\tif errno != 0 { r2 = syscall.Errno(errno) }\n")
684 }
685 if noCallback {
686 fmt.Fprintf(fgo2, "\t_Cgo_no_callback(false)\n")
687 }
688
689
690
691
692 touchFunc := "_Cgo_use"
693 if p.noEscapes[n.C] && p.noCallbacks[n.C] {
694 touchFunc = "_Cgo_keepalive"
695 }
696
697 if len(paramnames) > 0 {
698 fmt.Fprintf(fgo2, "\tif _Cgo_always_false {\n")
699 for _, name := range paramnames {
700 fmt.Fprintf(fgo2, "\t\t%s(%s)\n", touchFunc, name)
701 }
702 fmt.Fprintf(fgo2, "\t}\n")
703 }
704
705 fmt.Fprintf(fgo2, "\treturn\n")
706 fmt.Fprintf(fgo2, "}\n")
707 }
708
709
710 func (p *Package) writeOutput(f *File, srcfile string) {
711 base := srcfile
712 base = strings.TrimSuffix(base, ".go")
713 base = filepath.Base(base)
714 fgo1 := creat(base + ".cgo1.go")
715 fgcc := creat(base + ".cgo2.c")
716
717 p.GoFiles = append(p.GoFiles, base+".cgo1.go")
718 p.GccFiles = append(p.GccFiles, base+".cgo2.c")
719
720
721 fmt.Fprintf(fgo1, "// Code generated by cmd/cgo; DO NOT EDIT.\n\n")
722 if strings.ContainsAny(srcfile, "\r\n") {
723
724
725 fatalf("internal error: writeOutput: srcfile contains unexpected newline character: %q", srcfile)
726 }
727 fmt.Fprintf(fgo1, "//line %s:1:1\n", srcfile)
728 fgo1.Write(f.Edit.Bytes())
729
730
731
732 fmt.Fprintf(fgcc, "%s\n", builtinProlog)
733 fmt.Fprintf(fgcc, "%s\n", f.Preamble)
734 fmt.Fprintf(fgcc, "%s\n", gccProlog)
735 fmt.Fprintf(fgcc, "%s\n", tsanProlog)
736 fmt.Fprintf(fgcc, "%s\n", msanProlog)
737
738 for _, key := range nameKeys(f.Name) {
739 n := f.Name[key]
740 if n.FuncType != nil {
741 p.writeOutputFunc(fgcc, n)
742 }
743 }
744
745 fgo1.Close()
746 fgcc.Close()
747 }
748
749
750
751
752 func fixGo(name string) string {
753 if name == "_CMalloc" {
754 return "malloc"
755 }
756 return name
757 }
758
759 var isBuiltin = map[string]bool{
760 "_Cfunc_CString": true,
761 "_Cfunc_CBytes": true,
762 "_Cfunc_GoString": true,
763 "_Cfunc_GoStringN": true,
764 "_Cfunc_GoBytes": true,
765 "_Cfunc__CMalloc": true,
766 }
767
768 func (p *Package) writeOutputFunc(fgcc *os.File, n *Name) {
769 name := n.Mangle
770 if isBuiltin[name] || p.Written[name] {
771
772
773 return
774 }
775 p.Written[name] = true
776
777 if *gccgo {
778 p.writeGccgoOutputFunc(fgcc, n)
779 return
780 }
781
782 ctype, _ := p.structType(n)
783
784
785
786 fmt.Fprintf(fgcc, "CGO_NO_SANITIZE_THREAD\n")
787 if n.AddError {
788 fmt.Fprintf(fgcc, "int\n")
789 } else {
790 fmt.Fprintf(fgcc, "void\n")
791 }
792 fmt.Fprintf(fgcc, "_cgo%s%s(void *v __attribute__((unused)))\n", cPrefix, n.Mangle)
793 fmt.Fprintf(fgcc, "{\n")
794 if n.AddError {
795 fmt.Fprintf(fgcc, "\tint _cgo_errno;\n")
796 }
797
798
799
800 tr := n.FuncType.Result
801 if (n.Kind != "macro" && len(n.FuncType.Params) > 0) || tr != nil {
802 fmt.Fprintf(fgcc, "\t%s %v *_cgo_a = v;\n", ctype, p.packedAttribute())
803 }
804 if tr != nil {
805
806 fmt.Fprintf(fgcc, "\tchar *_cgo_stktop = _cgo_topofstack();\n")
807 fmt.Fprintf(fgcc, "\t__typeof__(_cgo_a->r) _cgo_r;\n")
808 }
809 fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
810 if n.AddError {
811 fmt.Fprintf(fgcc, "\terrno = 0;\n")
812 }
813 fmt.Fprintf(fgcc, "\t")
814 if tr != nil {
815 fmt.Fprintf(fgcc, "_cgo_r = ")
816 if c := tr.C.String(); c[len(c)-1] == '*' {
817 fmt.Fprint(fgcc, "(__typeof__(_cgo_a->r)) ")
818 }
819 }
820 if n.Kind == "macro" {
821 fmt.Fprintf(fgcc, "%s;\n", n.C)
822 } else {
823 fmt.Fprintf(fgcc, "%s(", n.C)
824 for i := range n.FuncType.Params {
825 if i > 0 {
826 fmt.Fprintf(fgcc, ", ")
827 }
828 fmt.Fprintf(fgcc, "_cgo_a->p%d", i)
829 }
830 fmt.Fprintf(fgcc, ");\n")
831 }
832 if n.AddError {
833 fmt.Fprintf(fgcc, "\t_cgo_errno = errno;\n")
834 }
835 fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
836 if tr != nil {
837
838
839 fmt.Fprintf(fgcc, "\t_cgo_a = (void*)((char*)_cgo_a + (_cgo_topofstack() - _cgo_stktop));\n")
840
841 fmt.Fprintf(fgcc, "\t_cgo_a->r = _cgo_r;\n")
842
843
844
845
846
847
848
849
850
851 fmt.Fprintf(fgcc, "\t_cgo_msan_write(&_cgo_a->r, sizeof(_cgo_a->r));\n")
852 }
853 if n.AddError {
854 fmt.Fprintf(fgcc, "\treturn _cgo_errno;\n")
855 }
856 fmt.Fprintf(fgcc, "}\n")
857 fmt.Fprintf(fgcc, "\n")
858 }
859
860
861
862
863
864
865 func (p *Package) writeGccgoOutputFunc(fgcc *os.File, n *Name) {
866 fmt.Fprintf(fgcc, "CGO_NO_SANITIZE_THREAD\n")
867 if t := n.FuncType.Result; t != nil {
868 fmt.Fprintf(fgcc, "%s\n", t.C.String())
869 } else {
870 fmt.Fprintf(fgcc, "void\n")
871 }
872 fmt.Fprintf(fgcc, "_cgo%s%s(", cPrefix, n.Mangle)
873 for i, t := range n.FuncType.Params {
874 if i > 0 {
875 fmt.Fprintf(fgcc, ", ")
876 }
877 c := t.Typedef
878 if c == "" {
879 c = t.C.String()
880 }
881 fmt.Fprintf(fgcc, "%s p%d", c, i)
882 }
883 fmt.Fprintf(fgcc, ")\n")
884 fmt.Fprintf(fgcc, "{\n")
885 if t := n.FuncType.Result; t != nil {
886 fmt.Fprintf(fgcc, "\t%s _cgo_r;\n", t.C.String())
887 }
888 fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
889 fmt.Fprintf(fgcc, "\t")
890 if t := n.FuncType.Result; t != nil {
891 fmt.Fprintf(fgcc, "_cgo_r = ")
892
893 if c := t.C.String(); c[len(c)-1] == '*' {
894 fmt.Fprintf(fgcc, "(void*)")
895 }
896 }
897 if n.Kind == "macro" {
898 fmt.Fprintf(fgcc, "%s;\n", n.C)
899 } else {
900 fmt.Fprintf(fgcc, "%s(", n.C)
901 for i := range n.FuncType.Params {
902 if i > 0 {
903 fmt.Fprintf(fgcc, ", ")
904 }
905 fmt.Fprintf(fgcc, "p%d", i)
906 }
907 fmt.Fprintf(fgcc, ");\n")
908 }
909 fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
910 if t := n.FuncType.Result; t != nil {
911 fmt.Fprintf(fgcc, "\treturn ")
912
913
914 if c := t.C.String(); c[len(c)-1] == '*' {
915 fmt.Fprintf(fgcc, "(void*)")
916 }
917 fmt.Fprintf(fgcc, "_cgo_r;\n")
918 }
919 fmt.Fprintf(fgcc, "}\n")
920 fmt.Fprintf(fgcc, "\n")
921 }
922
923
924
925
926
927
928 func (p *Package) packedAttribute() string {
929 s := "__attribute__((__packed__"
930 if !p.GccIsClang && (goarch == "amd64" || goarch == "386") {
931 s += ", __gcc_struct__"
932 }
933 return s + "))"
934 }
935
936
937
938 func genParamName(param string, position int) string {
939 return fmt.Sprintf("p%d", position)
940 }
941
942
943
944
945
946
947 func exportParamName(param string, position int) string {
948 if param == "" {
949 return fmt.Sprintf("p%d", position)
950 }
951
952 pname := param
953
954 for i := 0; i < len(param); i++ {
955 if param[i] > unicode.MaxASCII {
956 pname = fmt.Sprintf("p%d", position)
957 break
958 }
959 }
960
961 return pname
962 }
963
964
965
966 func (p *Package) writeExports(fgo2, fm, fgcc, fgcch io.Writer) {
967 p.writeExportHeader(fgcch)
968
969 fmt.Fprintf(fgcc, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
970 fmt.Fprintf(fgcc, "#include <stdlib.h>\n")
971 fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n\n")
972
973
974
975
976 fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wunknown-pragmas\"\n")
977 fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wpragmas\"\n")
978 fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Waddress-of-packed-member\"\n")
979 fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wunknown-warning-option\"\n")
980 fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wunaligned-access\"\n")
981
982 fmt.Fprintf(fgcc, "extern void crosscall2(void (*fn)(void *), void *, int, size_t);\n")
983 fmt.Fprintf(fgcc, "extern size_t _cgo_wait_runtime_init_done(void);\n")
984 fmt.Fprintf(fgcc, "extern void _cgo_release_context(size_t);\n\n")
985 fmt.Fprintf(fgcc, "extern char* _cgo_topofstack(void);")
986 fmt.Fprintf(fgcc, "%s\n", tsanProlog)
987 fmt.Fprintf(fgcc, "%s\n", msanProlog)
988 if buildcfg.Experiment.RuntimeCgoPurego && *importRuntimeCgo && !*gccgo {
989 fmt.Fprintf(fgcc, "%s\n", sanitizerInitProlog)
990 }
991
992 for _, exp := range p.ExpFunc {
993 fn := exp.Func
994
995
996
997
998
999
1000 var ctype strings.Builder
1001 const start = "struct {\n"
1002 ctype.WriteString(start)
1003 gotype := new(bytes.Buffer)
1004 fmt.Fprintf(gotype, "struct {\n")
1005 off := int64(0)
1006 npad := 0
1007
1008 maxAlign := int64(1)
1009 argField := func(typ ast.Expr, namePat string, args ...any) {
1010 name := fmt.Sprintf(namePat, args...)
1011 t := p.cgoType(typ)
1012 if off%t.Align != 0 {
1013 pad := t.Align - off%t.Align
1014 fmt.Fprintf(&ctype, "\t\tchar __pad%d[%d];\n", npad, pad)
1015 off += pad
1016 npad++
1017 }
1018 fmt.Fprintf(&ctype, "\t\t%s %s;\n", t.C, name)
1019 fmt.Fprintf(gotype, "\t\t%s ", name)
1020 noSourceConf.Fprint(gotype, fset, typ)
1021 fmt.Fprintf(gotype, "\n")
1022 off += t.Size
1023
1024
1025 if t.Align > maxAlign {
1026 maxAlign = t.Align
1027 }
1028 }
1029 if fn.Recv != nil {
1030 argField(fn.Recv.List[0].Type, "recv")
1031 }
1032 fntype := fn.Type
1033 forFieldList(fntype.Params,
1034 func(i int, aname string, atype ast.Expr) {
1035 argField(atype, "p%d", i)
1036 })
1037 forFieldList(fntype.Results,
1038 func(i int, aname string, atype ast.Expr) {
1039 argField(atype, "r%d", i)
1040 })
1041 if ctype.Len() == len(start) {
1042 ctype.WriteString("\t\tchar unused;\n")
1043 }
1044 ctype.WriteString("\t}")
1045 fmt.Fprintf(gotype, "\t}")
1046
1047
1048
1049 gccResult := ""
1050 if fntype.Results == nil || len(fntype.Results.List) == 0 {
1051 gccResult = "void"
1052 } else if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
1053 gccResult = p.cgoType(fntype.Results.List[0].Type).C.String()
1054 } else {
1055 fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
1056 fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName)
1057 forFieldList(fntype.Results,
1058 func(i int, aname string, atype ast.Expr) {
1059 fmt.Fprintf(fgcch, "\t%s r%d;", p.cgoType(atype).C, i)
1060 if len(aname) > 0 {
1061 fmt.Fprintf(fgcch, " /* %s */", aname)
1062 }
1063 fmt.Fprint(fgcch, "\n")
1064 })
1065 fmt.Fprintf(fgcch, "};\n")
1066 gccResult = "struct " + exp.ExpName + "_return"
1067 }
1068
1069
1070
1071
1072
1073
1074 cdecl := func(paramName func(aname string, i int) string) string {
1075 var s strings.Builder
1076 fmt.Fprintf(&s, "%s %s(", gccResult, exp.ExpName)
1077 if fn.Recv != nil {
1078 s.WriteString(p.cgoType(fn.Recv.List[0].Type).C.String())
1079 s.WriteString(" recv")
1080 }
1081
1082 if len(fntype.Params.List) > 0 {
1083 forFieldList(fntype.Params,
1084 func(i int, aname string, atype ast.Expr) {
1085 if i > 0 || fn.Recv != nil {
1086 s.WriteString(", ")
1087 }
1088 fmt.Fprintf(&s, "%s %s", p.cgoType(atype).C, paramName(aname, i))
1089 })
1090 } else {
1091 s.WriteString("void")
1092 }
1093 s.WriteByte(')')
1094 return s.String()
1095 }
1096
1097 if len(exp.Doc) > 0 {
1098 fmt.Fprintf(fgcch, "\n%s", exp.Doc)
1099 if !strings.HasSuffix(exp.Doc, "\n") {
1100 fmt.Fprint(fgcch, "\n")
1101 }
1102 }
1103 fmt.Fprintf(fgcch, "extern %s;\n", cdecl(exportParamName))
1104
1105 fmt.Fprintf(fgcc, "extern void _cgoexp%s_%s(void *);\n", cPrefix, exp.ExpName)
1106 fmt.Fprintf(fgcc, "\nCGO_NO_SANITIZE_THREAD")
1107 fmt.Fprintf(fgcc, "\n%s\n", cdecl(genParamName))
1108 fmt.Fprintf(fgcc, "{\n")
1109 fmt.Fprintf(fgcc, "\tsize_t _cgo_ctxt = _cgo_wait_runtime_init_done();\n")
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123 fmt.Fprintf(fgcc, "\ttypedef %s %v __attribute__((aligned(%d))) _cgo_argtype;\n", ctype.String(), p.packedAttribute(), maxAlign)
1124 fmt.Fprintf(fgcc, "\tstatic _cgo_argtype _cgo_zero;\n")
1125 fmt.Fprintf(fgcc, "\t_cgo_argtype _cgo_a = _cgo_zero;\n")
1126 if gccResult != "void" && (len(fntype.Results.List) > 1 || len(fntype.Results.List[0].Names) > 1) {
1127 fmt.Fprintf(fgcc, "\t%s r;\n", gccResult)
1128 }
1129 if fn.Recv != nil {
1130 fmt.Fprintf(fgcc, "\t_cgo_a.recv = recv;\n")
1131 }
1132 forFieldList(fntype.Params,
1133 func(i int, aname string, atype ast.Expr) {
1134 fmt.Fprintf(fgcc, "\t_cgo_a.p%d = %s;\n", i, genParamName(aname, i))
1135 })
1136 fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
1137 fmt.Fprintf(fgcc, "\tcrosscall2(_cgoexp%s_%s, &_cgo_a, %d, _cgo_ctxt);\n", cPrefix, exp.ExpName, off)
1138 fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
1139 fmt.Fprintf(fgcc, "\t_cgo_release_context(_cgo_ctxt);\n")
1140 if gccResult != "void" {
1141 if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
1142 fmt.Fprintf(fgcc, "\treturn _cgo_a.r0;\n")
1143 } else {
1144 forFieldList(fntype.Results,
1145 func(i int, aname string, atype ast.Expr) {
1146 fmt.Fprintf(fgcc, "\tr.r%d = _cgo_a.r%d;\n", i, i)
1147 })
1148 fmt.Fprintf(fgcc, "\treturn r;\n")
1149 }
1150 }
1151 fmt.Fprintf(fgcc, "}\n")
1152
1153
1154
1155
1156
1157
1158
1159 fmt.Fprintf(fgo2, "//go:cgo_export_dynamic %s\n", exp.ExpName)
1160
1161
1162 fmt.Fprintf(fgo2, "//go:linkname _cgoexp%s_%s _cgoexp%s_%s\n", cPrefix, exp.ExpName, cPrefix, exp.ExpName)
1163
1164
1165
1166
1167
1168 fmt.Fprintf(fgo2, "//go:cgo_export_static _cgoexp%s_%s\n", cPrefix, exp.ExpName)
1169
1170
1171
1172 fmt.Fprintf(fgo2, "func _cgoexp%s_%s(a *%s) {\n", cPrefix, exp.ExpName, gotype)
1173
1174 fmt.Fprintf(fm, "void _cgoexp%s_%s(void* p __attribute__((unused))){}\n", cPrefix, exp.ExpName)
1175
1176 fmt.Fprintf(fgo2, "\t")
1177
1178 if gccResult != "void" {
1179
1180 forFieldList(fntype.Results,
1181 func(i int, aname string, atype ast.Expr) {
1182 if i > 0 {
1183 fmt.Fprintf(fgo2, ", ")
1184 }
1185 fmt.Fprintf(fgo2, "a.r%d", i)
1186 })
1187 fmt.Fprintf(fgo2, " = ")
1188 }
1189 if fn.Recv != nil {
1190 fmt.Fprintf(fgo2, "a.recv.")
1191 }
1192 fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
1193 forFieldList(fntype.Params,
1194 func(i int, aname string, atype ast.Expr) {
1195 if i > 0 {
1196 fmt.Fprint(fgo2, ", ")
1197 }
1198 fmt.Fprintf(fgo2, "a.p%d", i)
1199 })
1200 fmt.Fprint(fgo2, ")\n")
1201 if gccResult != "void" {
1202
1203
1204 forFieldList(fntype.Results,
1205 func(i int, aname string, atype ast.Expr) {
1206 if !p.hasPointer(nil, atype, false) {
1207 return
1208 }
1209
1210
1211 pos := fset.Position(exp.Func.Pos())
1212 fmt.Fprintf(fgo2, "//line %s:%d\n", pos.Filename, pos.Line)
1213 fmt.Fprintf(fgo2, "\t_cgoCheckResult(a.r%d)\n", i)
1214 })
1215 }
1216 fmt.Fprint(fgo2, "}\n")
1217 }
1218
1219 fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
1220 }
1221
1222
1223 func (p *Package) writeGccgoExports(fgo2, fm, fgcc, fgcch io.Writer) {
1224 gccgoSymbolPrefix := p.gccgoSymbolPrefix()
1225
1226 p.writeExportHeader(fgcch)
1227
1228 fmt.Fprintf(fgcc, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
1229 fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n")
1230
1231 fmt.Fprintf(fgcc, "%s\n", gccgoExportFileProlog)
1232 fmt.Fprintf(fgcc, "%s\n", tsanProlog)
1233 fmt.Fprintf(fgcc, "%s\n", msanProlog)
1234
1235 for _, exp := range p.ExpFunc {
1236 fn := exp.Func
1237 fntype := fn.Type
1238
1239 cdeclBuf := new(strings.Builder)
1240 resultCount := 0
1241 forFieldList(fntype.Results,
1242 func(i int, aname string, atype ast.Expr) { resultCount++ })
1243 switch resultCount {
1244 case 0:
1245 fmt.Fprintf(cdeclBuf, "void")
1246 case 1:
1247 forFieldList(fntype.Results,
1248 func(i int, aname string, atype ast.Expr) {
1249 t := p.cgoType(atype)
1250 fmt.Fprintf(cdeclBuf, "%s", t.C)
1251 })
1252 default:
1253
1254 fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
1255 fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName)
1256 forFieldList(fntype.Results,
1257 func(i int, aname string, atype ast.Expr) {
1258 t := p.cgoType(atype)
1259 fmt.Fprintf(fgcch, "\t%s r%d;", t.C, i)
1260 if len(aname) > 0 {
1261 fmt.Fprintf(fgcch, " /* %s */", aname)
1262 }
1263 fmt.Fprint(fgcch, "\n")
1264 })
1265 fmt.Fprintf(fgcch, "};\n")
1266 fmt.Fprintf(cdeclBuf, "struct %s_return", exp.ExpName)
1267 }
1268
1269 cRet := cdeclBuf.String()
1270
1271 cdeclBuf = new(strings.Builder)
1272 fmt.Fprintf(cdeclBuf, "(")
1273 if fn.Recv != nil {
1274 fmt.Fprintf(cdeclBuf, "%s recv", p.cgoType(fn.Recv.List[0].Type).C.String())
1275 }
1276
1277 forFieldList(fntype.Params,
1278 func(i int, aname string, atype ast.Expr) {
1279 if i > 0 || fn.Recv != nil {
1280 fmt.Fprintf(cdeclBuf, ", ")
1281 }
1282 t := p.cgoType(atype)
1283 fmt.Fprintf(cdeclBuf, "%s p%d", t.C, i)
1284 })
1285 fmt.Fprintf(cdeclBuf, ")")
1286 cParams := cdeclBuf.String()
1287
1288 if len(exp.Doc) > 0 {
1289 fmt.Fprintf(fgcch, "\n%s", exp.Doc)
1290 }
1291
1292 fmt.Fprintf(fgcch, "extern %s %s%s;\n", cRet, exp.ExpName, cParams)
1293
1294
1295
1296
1297
1298 goName := "Cgoexp_" + exp.ExpName
1299 fmt.Fprintf(fgcc, `extern %s %s %s __asm__("%s.%s");`, cRet, goName, cParams, gccgoSymbolPrefix, gccgoToSymbol(goName))
1300 fmt.Fprint(fgcc, "\n")
1301
1302 fmt.Fprint(fgcc, "\nCGO_NO_SANITIZE_THREAD\n")
1303 fmt.Fprintf(fgcc, "%s %s %s {\n", cRet, exp.ExpName, cParams)
1304 if resultCount > 0 {
1305 fmt.Fprintf(fgcc, "\t%s r;\n", cRet)
1306 }
1307 fmt.Fprintf(fgcc, "\tif(_cgo_wait_runtime_init_done)\n")
1308 fmt.Fprintf(fgcc, "\t\t_cgo_wait_runtime_init_done();\n")
1309 fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
1310 fmt.Fprint(fgcc, "\t")
1311 if resultCount > 0 {
1312 fmt.Fprint(fgcc, "r = ")
1313 }
1314 fmt.Fprintf(fgcc, "%s(", goName)
1315 if fn.Recv != nil {
1316 fmt.Fprint(fgcc, "recv")
1317 }
1318 forFieldList(fntype.Params,
1319 func(i int, aname string, atype ast.Expr) {
1320 if i > 0 || fn.Recv != nil {
1321 fmt.Fprintf(fgcc, ", ")
1322 }
1323 fmt.Fprintf(fgcc, "p%d", i)
1324 })
1325 fmt.Fprint(fgcc, ");\n")
1326 fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
1327 if resultCount > 0 {
1328 fmt.Fprint(fgcc, "\treturn r;\n")
1329 }
1330 fmt.Fprint(fgcc, "}\n")
1331
1332
1333 fmt.Fprintf(fm, `char %s[1] __asm__("%s.%s");`, goName, gccgoSymbolPrefix, gccgoToSymbol(goName))
1334 fmt.Fprint(fm, "\n")
1335
1336
1337
1338
1339
1340
1341
1342 fmt.Fprint(fgo2, "\n")
1343 fmt.Fprintf(fgo2, "func %s(", goName)
1344 if fn.Recv != nil {
1345 fmt.Fprint(fgo2, "recv ")
1346 printer.Fprint(fgo2, fset, fn.Recv.List[0].Type)
1347 }
1348 forFieldList(fntype.Params,
1349 func(i int, aname string, atype ast.Expr) {
1350 if i > 0 || fn.Recv != nil {
1351 fmt.Fprintf(fgo2, ", ")
1352 }
1353 fmt.Fprintf(fgo2, "p%d ", i)
1354 printer.Fprint(fgo2, fset, atype)
1355 })
1356 fmt.Fprintf(fgo2, ")")
1357 if resultCount > 0 {
1358 fmt.Fprintf(fgo2, " (")
1359 forFieldList(fntype.Results,
1360 func(i int, aname string, atype ast.Expr) {
1361 if i > 0 {
1362 fmt.Fprint(fgo2, ", ")
1363 }
1364 printer.Fprint(fgo2, fset, atype)
1365 })
1366 fmt.Fprint(fgo2, ")")
1367 }
1368 fmt.Fprint(fgo2, " {\n")
1369 fmt.Fprint(fgo2, "\tsyscall.CgocallBack()\n")
1370 fmt.Fprint(fgo2, "\tdefer syscall.CgocallBackDone()\n")
1371 fmt.Fprint(fgo2, "\t")
1372 if resultCount > 0 {
1373 fmt.Fprint(fgo2, "return ")
1374 }
1375 if fn.Recv != nil {
1376 fmt.Fprint(fgo2, "recv.")
1377 }
1378 fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
1379 forFieldList(fntype.Params,
1380 func(i int, aname string, atype ast.Expr) {
1381 if i > 0 {
1382 fmt.Fprint(fgo2, ", ")
1383 }
1384 fmt.Fprintf(fgo2, "p%d", i)
1385 })
1386 fmt.Fprint(fgo2, ")\n")
1387 fmt.Fprint(fgo2, "}\n")
1388 }
1389
1390 fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
1391 }
1392
1393
1394 func (p *Package) writeExportHeader(fgcch io.Writer) {
1395 fmt.Fprintf(fgcch, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
1396 pkg := *importPath
1397 if pkg == "" {
1398 pkg = p.PackagePath
1399 }
1400 fmt.Fprintf(fgcch, "/* package %s */\n\n", pkg)
1401 fmt.Fprintf(fgcch, "%s\n", builtinExportProlog)
1402
1403
1404
1405
1406
1407 re := regexp.MustCompile(`(?m)^(#line\s+\d+\s+")[^"]*[/\\]([^"]*")`)
1408 preamble := re.ReplaceAllString(p.Preamble, "$1$2")
1409
1410 fmt.Fprintf(fgcch, "/* Start of preamble from import \"C\" comments. */\n\n")
1411 fmt.Fprintf(fgcch, "%s\n", preamble)
1412 fmt.Fprintf(fgcch, "\n/* End of preamble from import \"C\" comments. */\n\n")
1413
1414 fmt.Fprintf(fgcch, "%s\n", p.gccExportHeaderProlog())
1415 }
1416
1417
1418 func gccgoToSymbol(ppath string) string {
1419 if gccgoMangler == nil {
1420 var err error
1421 cmd := os.Getenv("GCCGO")
1422 if cmd == "" {
1423 cmd, err = exec.LookPath("gccgo")
1424 if err != nil {
1425 fatalf("unable to locate gccgo: %v", err)
1426 }
1427 }
1428 gccgoMangler, err = pkgpath.ToSymbolFunc(cmd, outputDir())
1429 if err != nil {
1430 fatalf("%v", err)
1431 }
1432 }
1433 return gccgoMangler(ppath)
1434 }
1435
1436
1437 func (p *Package) gccgoSymbolPrefix() string {
1438 if !*gccgo {
1439 return ""
1440 }
1441
1442 if *gccgopkgpath != "" {
1443 return gccgoToSymbol(*gccgopkgpath)
1444 }
1445 if *gccgoprefix == "" && p.PackageName == "main" {
1446 return "main"
1447 }
1448 prefix := gccgoToSymbol(*gccgoprefix)
1449 if prefix == "" {
1450 prefix = "go"
1451 }
1452 return prefix + "." + p.PackageName
1453 }
1454
1455
1456
1457 func forFieldList(fl *ast.FieldList, fn func(int, string, ast.Expr)) {
1458 if fl == nil {
1459 return
1460 }
1461 i := 0
1462 for _, r := range fl.List {
1463 if r.Names == nil {
1464 fn(i, "", r.Type)
1465 i++
1466 } else {
1467 for _, n := range r.Names {
1468 fn(i, n.Name, r.Type)
1469 i++
1470 }
1471 }
1472 }
1473 }
1474
1475 func c(repr string, args ...any) *TypeRepr {
1476 return &TypeRepr{repr, args}
1477 }
1478
1479
1480 var goTypes = map[string]*Type{
1481 "bool": {Size: 1, Align: 1, C: c("GoUint8")},
1482 "byte": {Size: 1, Align: 1, C: c("GoUint8")},
1483 "int": {Size: 0, Align: 0, C: c("GoInt")},
1484 "uint": {Size: 0, Align: 0, C: c("GoUint")},
1485 "rune": {Size: 4, Align: 4, C: c("GoInt32")},
1486 "int8": {Size: 1, Align: 1, C: c("GoInt8")},
1487 "uint8": {Size: 1, Align: 1, C: c("GoUint8")},
1488 "int16": {Size: 2, Align: 2, C: c("GoInt16")},
1489 "uint16": {Size: 2, Align: 2, C: c("GoUint16")},
1490 "int32": {Size: 4, Align: 4, C: c("GoInt32")},
1491 "uint32": {Size: 4, Align: 4, C: c("GoUint32")},
1492 "int64": {Size: 8, Align: 8, C: c("GoInt64")},
1493 "uint64": {Size: 8, Align: 8, C: c("GoUint64")},
1494 "float32": {Size: 4, Align: 4, C: c("GoFloat32")},
1495 "float64": {Size: 8, Align: 8, C: c("GoFloat64")},
1496 "complex64": {Size: 8, Align: 4, C: c("GoComplex64")},
1497 "complex128": {Size: 16, Align: 8, C: c("GoComplex128")},
1498 }
1499
1500
1501 func (p *Package) cgoType(e ast.Expr) *Type {
1502 return p.doCgoType(e, make(map[ast.Expr]bool))
1503 }
1504
1505
1506 func (p *Package) doCgoType(e ast.Expr, m map[ast.Expr]bool) *Type {
1507 if m[e] {
1508 fatalf("%s: invalid recursive type", fset.Position(e.Pos()))
1509 }
1510 m[e] = true
1511 switch t := e.(type) {
1512 case *ast.StarExpr:
1513 x := p.doCgoType(t.X, m)
1514 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("%s*", x.C)}
1515 case *ast.ArrayType:
1516 if t.Len == nil {
1517
1518 return &Type{Size: p.PtrSize * 3, Align: p.PtrSize, C: c("GoSlice")}
1519 }
1520
1521 case *ast.StructType:
1522
1523 case *ast.FuncType:
1524 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
1525 case *ast.InterfaceType:
1526 return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
1527 case *ast.MapType:
1528 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoMap")}
1529 case *ast.ChanType:
1530 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoChan")}
1531 case *ast.Ident:
1532 goTypesFixup := func(r *Type) *Type {
1533 if r.Size == 0 {
1534 rr := new(Type)
1535 *rr = *r
1536 rr.Size = p.IntSize
1537 rr.Align = p.IntSize
1538 r = rr
1539 }
1540 if r.Align > p.PtrSize {
1541 r.Align = p.PtrSize
1542 }
1543 return r
1544 }
1545
1546
1547 for _, d := range p.Decl {
1548 gd, ok := d.(*ast.GenDecl)
1549 if !ok || gd.Tok != token.TYPE {
1550 continue
1551 }
1552 for _, spec := range gd.Specs {
1553 ts, ok := spec.(*ast.TypeSpec)
1554 if !ok {
1555 continue
1556 }
1557 if ts.Name.Name == t.Name {
1558
1559
1560 if m[ts.Type] {
1561 fatalf("%s: invalid recursive type: %s refers to itself", fset.Position(e.Pos()), t.Name)
1562 }
1563 return p.doCgoType(ts.Type, m)
1564 }
1565 }
1566 }
1567 if def := typedef[t.Name]; def != nil {
1568 if defgo, ok := def.Go.(*ast.Ident); ok {
1569 switch defgo.Name {
1570 case "complex64", "complex128":
1571
1572
1573
1574
1575
1576 return goTypesFixup(goTypes[defgo.Name])
1577 }
1578 }
1579 return def
1580 }
1581 if t.Name == "uintptr" {
1582 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoUintptr")}
1583 }
1584 if t.Name == "string" {
1585
1586 return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoString")}
1587 }
1588 if t.Name == "error" {
1589 return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
1590 }
1591 if t.Name == "any" {
1592 return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
1593 }
1594 if r, ok := goTypes[t.Name]; ok {
1595 return goTypesFixup(r)
1596 }
1597 error_(e.Pos(), "unrecognized Go type %s", t.Name)
1598 return &Type{Size: 4, Align: 4, C: c("int")}
1599 case *ast.SelectorExpr:
1600 id, ok := t.X.(*ast.Ident)
1601 if ok && id.Name == "unsafe" && t.Sel.Name == "Pointer" {
1602 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
1603 }
1604 }
1605 error_(e.Pos(), "Go type not supported in export: %s", gofmt(e))
1606 return &Type{Size: 4, Align: 4, C: c("int")}
1607 }
1608
1609 const gccProlog = `
1610 #line 1 "cgo-gcc-prolog"
1611 /*
1612 If x and y are not equal, the type will be invalid
1613 (have a negative array count) and an inscrutable error will come
1614 out of the compiler and hopefully mention "name".
1615 */
1616 #define __cgo_compile_assert_eq(x, y, name) typedef char name[(x-y)*(x-y)*-2UL+1UL];
1617
1618 /* Check at compile time that the sizes we use match our expectations. */
1619 #define __cgo_size_assert(t, n) __cgo_compile_assert_eq(sizeof(t), (size_t)n, _cgo_sizeof_##t##_is_not_##n)
1620
1621 __cgo_size_assert(char, 1)
1622 __cgo_size_assert(short, 2)
1623 __cgo_size_assert(int, 4)
1624 typedef long long __cgo_long_long;
1625 __cgo_size_assert(__cgo_long_long, 8)
1626 __cgo_size_assert(float, 4)
1627 __cgo_size_assert(double, 8)
1628
1629 extern char* _cgo_topofstack(void);
1630
1631 /*
1632 We use packed structs, but they are always aligned.
1633 The pragmas and address-of-packed-member are only recognized as warning
1634 groups in clang 4.0+, so ignore unknown pragmas first.
1635 */
1636 #pragma GCC diagnostic ignored "-Wunknown-pragmas"
1637 #pragma GCC diagnostic ignored "-Wpragmas"
1638 #pragma GCC diagnostic ignored "-Waddress-of-packed-member"
1639 #pragma GCC diagnostic ignored "-Wunknown-warning-option"
1640 #pragma GCC diagnostic ignored "-Wunaligned-access"
1641
1642 #include <errno.h>
1643 #include <string.h>
1644 `
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669 const tsanProlog = `
1670 #undef _CGO_TSAN
1671 #if defined(__SANITIZE_THREAD__)
1672 #define _CGO_TSAN 1
1673 #elif defined(__has_feature)
1674 #if __has_feature(thread_sanitizer)
1675 #define _CGO_TSAN 1
1676 #endif
1677 #endif
1678 #ifdef _CGO_TSAN
1679 #line 1 "cgo-tsan-prolog"
1680 #define CGO_NO_SANITIZE_THREAD __attribute__ ((no_sanitize_thread))
1681
1682 long long _cgo_sync __attribute__ ((common));
1683
1684 extern void __tsan_acquire(void*);
1685 extern void __tsan_release(void*);
1686
1687 __attribute__ ((unused))
1688 static void _cgo_tsan_acquire(void) {
1689 __tsan_acquire(&_cgo_sync);
1690 }
1691
1692 __attribute__ ((unused))
1693 static void _cgo_tsan_release(void) {
1694 __tsan_release(&_cgo_sync);
1695 }
1696 #line 1 "cgo-generated-wrappers"
1697 #else
1698 #define CGO_NO_SANITIZE_THREAD
1699 #define _cgo_tsan_acquire()
1700 #define _cgo_tsan_release()
1701 #endif
1702 `
1703
1704
1705
1706
1707 const sanitizerInitProlog = `
1708 #if defined(_CGO_TSAN) && !defined(_WIN32)
1709 #line 1 "cgo-sanitizer-init-prolog"
1710 #include <string.h>
1711 static char _cgo_yield_strncpy_src = 0;
1712 static char _cgo_yield_strncpy_dst = 0;
1713 static volatile size_t _cgo_yield_strncpy_n = 0;
1714 static void _cgo_tsan_yield(void) {
1715 strncpy(&_cgo_yield_strncpy_dst, &_cgo_yield_strncpy_src, _cgo_yield_strncpy_n);
1716 }
1717 extern void (*_cgo_tsan_acquire_fn)(void*);
1718 extern void (*_cgo_tsan_release_fn)(void*);
1719 extern void (*_cgo_yield)(void);
1720 #ifdef __ELF__
1721 __attribute__((constructor(101)))
1722 #else
1723 __attribute__((constructor))
1724 #endif
1725 CGO_NO_SANITIZE_THREAD
1726 static void _cgo_sanitizer_init(void) {
1727 void (*expected)(void) = 0;
1728 /* Store release first so a concurrent caller never acquires without releasing. */
1729 __atomic_store_n(&_cgo_tsan_release_fn, __tsan_release, __ATOMIC_RELEASE);
1730 __atomic_store_n(&_cgo_tsan_acquire_fn, __tsan_acquire, __ATOMIC_RELEASE);
1731 /* Only set _cgo_yield once so multiple cgo packages or Darwin libInit do not overwrite it concurrently. */
1732 __atomic_compare_exchange_n(&_cgo_yield, &expected, _cgo_tsan_yield, 0, __ATOMIC_RELEASE, __ATOMIC_RELAXED);
1733 }
1734 #line 1 "cgo-generated-wrappers"
1735 #endif
1736 `
1737
1738
1739
1740 const msanProlog = `
1741 #undef _CGO_MSAN
1742 #if defined(__has_feature)
1743 #if __has_feature(memory_sanitizer)
1744 #define _CGO_MSAN 1
1745 #endif
1746 #endif
1747 #ifdef _CGO_MSAN
1748 #line 1 "cgo-msan-prolog"
1749 extern void __msan_unpoison(const volatile void *, size_t);
1750
1751 #define _cgo_msan_write(addr, sz) __msan_unpoison((addr), (sz))
1752 #line 1 "cgo-generated-wrappers"
1753 #else
1754 #define _cgo_msan_write(addr, sz)
1755 #endif
1756 `
1757
1758 const builtinProlog = `
1759 #line 1 "cgo-builtin-prolog"
1760 #include <stddef.h>
1761
1762 /* Define intgo when compiling with GCC. */
1763 typedef ptrdiff_t intgo;
1764
1765 #define GO_CGO_GOSTRING_TYPEDEF
1766 typedef struct { const char *p; intgo n; } _GoString_;
1767 typedef struct { char *p; intgo n; intgo c; } _GoBytes_;
1768 _GoString_ GoString(char *p);
1769 _GoString_ GoStringN(char *p, int l);
1770 _GoBytes_ GoBytes(void *p, int n);
1771 char *CString(_GoString_);
1772 void *CBytes(_GoBytes_);
1773 void *_CMalloc(size_t);
1774
1775 __attribute__ ((unused))
1776 static size_t _GoStringLen(_GoString_ s) { return (size_t)s.n; }
1777
1778 __attribute__ ((unused))
1779 static const char *_GoStringPtr(_GoString_ s) { return s.p; }
1780 `
1781
1782 const goProlog = `
1783 //go:linkname _cgo_runtime_cgocall runtime.cgocall
1784 func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
1785
1786 //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
1787 //go:noescape
1788 func _cgoCheckPointer(interface{}, interface{})
1789
1790 //go:linkname _cgoCheckResult runtime.cgoCheckResult
1791 //go:noescape
1792 func _cgoCheckResult(interface{})
1793 `
1794
1795 const gccgoGoProlog = `
1796 func _cgoCheckPointer(interface{}, interface{})
1797
1798 func _cgoCheckResult(interface{})
1799 `
1800
1801 const goStringDef = `
1802 //go:linkname _cgo_runtime_gostring runtime.gostring
1803 func _cgo_runtime_gostring(*_Ctype_char) string
1804
1805 // GoString converts the C string p into a Go string.
1806 func _Cfunc_GoString(p *_Ctype_char) string {
1807 return _cgo_runtime_gostring(p)
1808 }
1809 `
1810
1811 const goStringNDef = `
1812 //go:linkname _cgo_runtime_gostringn runtime.gostringn
1813 func _cgo_runtime_gostringn(*_Ctype_char, int) string
1814
1815 // GoStringN converts the C data p with explicit length l to a Go string.
1816 func _Cfunc_GoStringN(p *_Ctype_char, l _Ctype_int) string {
1817 return _cgo_runtime_gostringn(p, int(l))
1818 }
1819 `
1820
1821 const goBytesDef = `
1822 //go:linkname _cgo_runtime_gobytes runtime.gobytes
1823 func _cgo_runtime_gobytes(unsafe.Pointer, int) []byte
1824
1825 // GoBytes converts the C data p with explicit length l to a Go []byte.
1826 func _Cfunc_GoBytes(p unsafe.Pointer, l _Ctype_int) []byte {
1827 return _cgo_runtime_gobytes(p, int(l))
1828 }
1829 `
1830
1831 const cStringDef = `
1832 // CString converts the Go string s to a C string.
1833 //
1834 // The C string is allocated in the C heap using malloc.
1835 // It is the caller's responsibility to arrange for it to be
1836 // freed, such as by calling C.free (be sure to include stdlib.h
1837 // if C.free is needed).
1838 func _Cfunc_CString(s string) *_Ctype_char {
1839 if len(s)+1 <= 0 {
1840 panic("string too large")
1841 }
1842 p := _cgo_cmalloc(uint64(len(s)+1))
1843 sliceHeader := struct {
1844 p unsafe.Pointer
1845 len int
1846 cap int
1847 }{p, len(s)+1, len(s)+1}
1848 b := *(*[]byte)(unsafe.Pointer(&sliceHeader))
1849 copy(b, s)
1850 b[len(s)] = 0
1851 return (*_Ctype_char)(p)
1852 }
1853 `
1854
1855 const cBytesDef = `
1856 // CBytes converts the Go []byte slice b to a C array.
1857 //
1858 // The C array is allocated in the C heap using malloc.
1859 // It is the caller's responsibility to arrange for it to be
1860 // freed, such as by calling C.free (be sure to include stdlib.h
1861 // if C.free is needed).
1862 func _Cfunc_CBytes(b []byte) unsafe.Pointer {
1863 p := _cgo_cmalloc(uint64(len(b)))
1864 sliceHeader := struct {
1865 p unsafe.Pointer
1866 len int
1867 cap int
1868 }{p, len(b), len(b)}
1869 s := *(*[]byte)(unsafe.Pointer(&sliceHeader))
1870 copy(s, b)
1871 return p
1872 }
1873 `
1874
1875 const cMallocDef = `
1876 func _Cfunc__CMalloc(n _Ctype_size_t) unsafe.Pointer {
1877 return _cgo_cmalloc(uint64(n))
1878 }
1879 `
1880
1881 var builtinDefs = map[string]string{
1882 "GoString": goStringDef,
1883 "GoStringN": goStringNDef,
1884 "GoBytes": goBytesDef,
1885 "CString": cStringDef,
1886 "CBytes": cBytesDef,
1887 "_CMalloc": cMallocDef,
1888 }
1889
1890
1891
1892
1893
1894
1895 const cMallocDefGo = `
1896 //go:cgo_import_static _cgoPREFIX_Cfunc__Cmalloc
1897 //go:linkname __cgofn__cgoPREFIX_Cfunc__Cmalloc _cgoPREFIX_Cfunc__Cmalloc
1898 var __cgofn__cgoPREFIX_Cfunc__Cmalloc byte
1899 var _cgoPREFIX_Cfunc__Cmalloc = unsafe.Pointer(&__cgofn__cgoPREFIX_Cfunc__Cmalloc)
1900
1901 //go:linkname runtime_throw runtime.throw
1902 func runtime_throw(string)
1903
1904 //go:cgo_unsafe_args
1905 func _cgo_cmalloc(p0 uint64) (r1 unsafe.Pointer) {
1906 _cgo_runtime_cgocall(_cgoPREFIX_Cfunc__Cmalloc, uintptr(unsafe.Pointer(&p0)))
1907 if r1 == nil {
1908 runtime_throw("runtime: C malloc failed")
1909 }
1910 return
1911 }
1912 `
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922 const cMallocDefC = `
1923 CGO_NO_SANITIZE_THREAD
1924 void _cgoPREFIX_Cfunc__Cmalloc(void *v) {
1925 struct {
1926 unsigned long long p0;
1927 void *r1;
1928 } PACKED *a = v;
1929 void *ret;
1930 _cgo_tsan_acquire();
1931 ret = malloc(a->p0);
1932 if (ret == NULL && a->p0 == 0) {
1933 ret = malloc(1);
1934 }
1935 a->r1 = ret;
1936 _cgo_tsan_release();
1937 }
1938 `
1939
1940 func (p *Package) cPrologGccgo() string {
1941 r := strings.NewReplacer(
1942 "PREFIX", cPrefix,
1943 "GCCGOSYMBOLPREF", p.gccgoSymbolPrefix(),
1944 "_cgoCheckPointer", gccgoToSymbol("_cgoCheckPointer"),
1945 "_cgoCheckResult", gccgoToSymbol("_cgoCheckResult"))
1946 return r.Replace(cPrologGccgo)
1947 }
1948
1949 const cPrologGccgo = `
1950 #line 1 "cgo-c-prolog-gccgo"
1951 #include <stdint.h>
1952 #include <stdlib.h>
1953 #include <string.h>
1954
1955 typedef unsigned char byte;
1956 typedef intptr_t intgo;
1957
1958 struct __go_string {
1959 const unsigned char *__data;
1960 intgo __length;
1961 };
1962
1963 typedef struct __go_open_array {
1964 void* __values;
1965 intgo __count;
1966 intgo __capacity;
1967 } Slice;
1968
1969 struct __go_string __go_byte_array_to_string(const void* p, intgo len);
1970 struct __go_open_array __go_string_to_byte_array (struct __go_string str);
1971
1972 extern void runtime_throw(const char *);
1973
1974 const char *_cgoPREFIX_Cfunc_CString(struct __go_string s) {
1975 char *p = malloc(s.__length+1);
1976 if(p == NULL)
1977 runtime_throw("runtime: C malloc failed");
1978 memmove(p, s.__data, s.__length);
1979 p[s.__length] = 0;
1980 return p;
1981 }
1982
1983 void *_cgoPREFIX_Cfunc_CBytes(struct __go_open_array b) {
1984 char *p = malloc(b.__count);
1985 if(p == NULL)
1986 runtime_throw("runtime: C malloc failed");
1987 memmove(p, b.__values, b.__count);
1988 return p;
1989 }
1990
1991 struct __go_string _cgoPREFIX_Cfunc_GoString(char *p) {
1992 intgo len = (p != NULL) ? strlen(p) : 0;
1993 return __go_byte_array_to_string(p, len);
1994 }
1995
1996 struct __go_string _cgoPREFIX_Cfunc_GoStringN(char *p, int32_t n) {
1997 return __go_byte_array_to_string(p, n);
1998 }
1999
2000 Slice _cgoPREFIX_Cfunc_GoBytes(char *p, int32_t n) {
2001 struct __go_string s = { (const unsigned char *)p, n };
2002 return __go_string_to_byte_array(s);
2003 }
2004
2005 void *_cgoPREFIX_Cfunc__CMalloc(size_t n) {
2006 void *p = malloc(n);
2007 if(p == NULL && n == 0)
2008 p = malloc(1);
2009 if(p == NULL)
2010 runtime_throw("runtime: C malloc failed");
2011 return p;
2012 }
2013
2014 struct __go_type_descriptor;
2015 typedef struct __go_empty_interface {
2016 const struct __go_type_descriptor *__type_descriptor;
2017 void *__object;
2018 } Eface;
2019
2020 extern void runtimeCgoCheckPointer(Eface, Eface)
2021 __asm__("runtime.cgoCheckPointer")
2022 __attribute__((weak));
2023
2024 extern void localCgoCheckPointer(Eface, Eface)
2025 __asm__("GCCGOSYMBOLPREF._cgoCheckPointer");
2026
2027 void localCgoCheckPointer(Eface ptr, Eface arg) {
2028 if(runtimeCgoCheckPointer) {
2029 runtimeCgoCheckPointer(ptr, arg);
2030 }
2031 }
2032
2033 extern void runtimeCgoCheckResult(Eface)
2034 __asm__("runtime.cgoCheckResult")
2035 __attribute__((weak));
2036
2037 extern void localCgoCheckResult(Eface)
2038 __asm__("GCCGOSYMBOLPREF._cgoCheckResult");
2039
2040 void localCgoCheckResult(Eface val) {
2041 if(runtimeCgoCheckResult) {
2042 runtimeCgoCheckResult(val);
2043 }
2044 }
2045 `
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056 const builtinExportProlog = `
2057 #line 1 "cgo-builtin-export-prolog"
2058
2059 #include <stddef.h>
2060
2061 #ifndef GO_CGO_EXPORT_PROLOGUE_H
2062 #define GO_CGO_EXPORT_PROLOGUE_H
2063
2064 #ifndef GO_CGO_GOSTRING_TYPEDEF
2065 typedef struct { const char *p; ptrdiff_t n; } _GoString_;
2066 extern size_t _GoStringLen(_GoString_ s);
2067 extern const char *_GoStringPtr(_GoString_ s);
2068 #endif
2069
2070 #endif
2071 `
2072
2073 func (p *Package) gccExportHeaderProlog() string {
2074 return strings.ReplaceAll(gccExportHeaderProlog, "GOINTBITS", fmt.Sprint(8*p.IntSize))
2075 }
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090 const gccExportHeaderProlog = `
2091 /* Start of boilerplate cgo prologue. */
2092 #line 1 "cgo-gcc-export-header-prolog"
2093
2094 #ifndef GO_CGO_PROLOGUE_H
2095 #define GO_CGO_PROLOGUE_H
2096
2097 typedef signed char GoInt8;
2098 typedef unsigned char GoUint8;
2099 typedef short GoInt16;
2100 typedef unsigned short GoUint16;
2101 typedef int GoInt32;
2102 typedef unsigned int GoUint32;
2103 typedef long long GoInt64;
2104 typedef unsigned long long GoUint64;
2105 typedef GoIntGOINTBITS GoInt;
2106 typedef GoUintGOINTBITS GoUint;
2107 typedef size_t GoUintptr;
2108 typedef float GoFloat32;
2109 typedef double GoFloat64;
2110 #ifdef _MSC_VER
2111 #if !defined(__cplusplus) || _MSVC_LANG <= 201402L
2112 #include <complex.h>
2113 typedef _Fcomplex GoComplex64;
2114 typedef _Dcomplex GoComplex128;
2115 #else
2116 #include <complex>
2117 typedef std::complex<float> GoComplex64;
2118 typedef std::complex<double> GoComplex128;
2119 #endif
2120 #else
2121 typedef float _Complex GoComplex64;
2122 typedef double _Complex GoComplex128;
2123 #endif
2124
2125 /*
2126 static assertion to make sure the file is being used on architecture
2127 at least with matching size of GoInt.
2128 */
2129 typedef char _check_for_GOINTBITS_bit_pointer_matching_GoInt[sizeof(void*)==GOINTBITS/8 ? 1:-1];
2130
2131 #ifndef GO_CGO_GOSTRING_TYPEDEF
2132 typedef _GoString_ GoString;
2133 #endif
2134 typedef void *GoMap;
2135 typedef void *GoChan;
2136 typedef struct { void *t; void *v; } GoInterface;
2137 typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
2138
2139 #endif
2140
2141 /* End of boilerplate cgo prologue. */
2142
2143 #ifdef __cplusplus
2144 extern "C" {
2145 #endif
2146 `
2147
2148
2149 const gccExportHeaderEpilog = `
2150 #ifdef __cplusplus
2151 }
2152 #endif
2153 `
2154
2155
2156
2157
2158
2159 const gccgoExportFileProlog = `
2160 #line 1 "cgo-gccgo-export-file-prolog"
2161 extern _Bool runtime_iscgo __attribute__ ((weak));
2162
2163 static void GoInit(void) __attribute__ ((constructor));
2164 static void GoInit(void) {
2165 if(&runtime_iscgo)
2166 runtime_iscgo = 1;
2167 }
2168
2169 extern size_t _cgo_wait_runtime_init_done(void) __attribute__ ((weak));
2170 `
2171
View as plain text