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