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