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