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