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