github.com/hlts2/go@v0.0.0-20170904000733-812b34efaed8/src/cmd/cgo/out.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 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 "io" 17 "os" 18 "sort" 19 "strings" 20 ) 21 22 var ( 23 conf = printer.Config{Mode: printer.SourcePos, Tabwidth: 8} 24 noSourceConf = printer.Config{Tabwidth: 8} 25 ) 26 27 // writeDefs creates output files to be compiled by gc and gcc. 28 func (p *Package) writeDefs() { 29 var fgo2, fc io.Writer 30 f := creat(*objDir + "_cgo_gotypes.go") 31 defer f.Close() 32 fgo2 = f 33 if *gccgo { 34 f := creat(*objDir + "_cgo_defun.c") 35 defer f.Close() 36 fc = f 37 } 38 fm := creat(*objDir + "_cgo_main.c") 39 40 var gccgoInit bytes.Buffer 41 42 fflg := creat(*objDir + "_cgo_flags") 43 for k, v := range p.CgoFlags { 44 fmt.Fprintf(fflg, "_CGO_%s=%s\n", k, strings.Join(v, " ")) 45 if k == "LDFLAGS" && !*gccgo { 46 for _, arg := range v { 47 fmt.Fprintf(fgo2, "//go:cgo_ldflag %q\n", arg) 48 } 49 } 50 } 51 fflg.Close() 52 53 // Write C main file for using gcc to resolve imports. 54 fmt.Fprintf(fm, "int main() { return 0; }\n") 55 if *importRuntimeCgo { 56 fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*, int, __SIZE_TYPE__), void *a, int c, __SIZE_TYPE__ ctxt) { }\n") 57 fmt.Fprintf(fm, "__SIZE_TYPE__ _cgo_wait_runtime_init_done() { return 0; }\n") 58 fmt.Fprintf(fm, "void _cgo_release_context(__SIZE_TYPE__ ctxt) { }\n") 59 fmt.Fprintf(fm, "char* _cgo_topofstack(void) { return (char*)0; }\n") 60 } else { 61 // If we're not importing runtime/cgo, we *are* runtime/cgo, 62 // which provides these functions. We just need a prototype. 63 fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*, int, __SIZE_TYPE__), void *a, int c, __SIZE_TYPE__ ctxt);\n") 64 fmt.Fprintf(fm, "__SIZE_TYPE__ _cgo_wait_runtime_init_done();\n") 65 fmt.Fprintf(fm, "void _cgo_release_context(__SIZE_TYPE__);\n") 66 } 67 fmt.Fprintf(fm, "void _cgo_allocate(void *a, int c) { }\n") 68 fmt.Fprintf(fm, "void _cgo_panic(void *a, int c) { }\n") 69 fmt.Fprintf(fm, "void _cgo_reginit(void) { }\n") 70 71 // Write second Go output: definitions of _C_xxx. 72 // In a separate file so that the import of "unsafe" does not 73 // pollute the original file. 74 fmt.Fprintf(fgo2, "// Created by cgo - DO NOT EDIT\n\n") 75 fmt.Fprintf(fgo2, "package %s\n\n", p.PackageName) 76 fmt.Fprintf(fgo2, "import \"unsafe\"\n\n") 77 if !*gccgo && *importRuntimeCgo { 78 fmt.Fprintf(fgo2, "import _ \"runtime/cgo\"\n\n") 79 } 80 if *importSyscall { 81 fmt.Fprintf(fgo2, "import \"syscall\"\n\n") 82 fmt.Fprintf(fgo2, "var _ syscall.Errno\n") 83 } 84 fmt.Fprintf(fgo2, "func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }\n\n") 85 86 if !*gccgo { 87 fmt.Fprintf(fgo2, "//go:linkname _Cgo_always_false runtime.cgoAlwaysFalse\n") 88 fmt.Fprintf(fgo2, "var _Cgo_always_false bool\n") 89 fmt.Fprintf(fgo2, "//go:linkname _Cgo_use runtime.cgoUse\n") 90 fmt.Fprintf(fgo2, "func _Cgo_use(interface{})\n") 91 } 92 93 typedefNames := make([]string, 0, len(typedef)) 94 for name := range typedef { 95 typedefNames = append(typedefNames, name) 96 } 97 sort.Strings(typedefNames) 98 for _, name := range typedefNames { 99 def := typedef[name] 100 fmt.Fprintf(fgo2, "type %s ", name) 101 // We don't have source info for these types, so write them out without source info. 102 // Otherwise types would look like: 103 // 104 // type _Ctype_struct_cb struct { 105 // //line :1 106 // on_test *[0]byte 107 // //line :1 108 // } 109 // 110 // Which is not useful. Moreover we never override source info, 111 // so subsequent source code uses the same source info. 112 // Moreover, empty file name makes compile emit no source debug info at all. 113 noSourceConf.Fprint(fgo2, fset, def.Go) 114 fmt.Fprintf(fgo2, "\n\n") 115 } 116 if *gccgo { 117 fmt.Fprintf(fgo2, "type _Ctype_void byte\n") 118 } else { 119 fmt.Fprintf(fgo2, "type _Ctype_void [0]byte\n") 120 } 121 122 if *gccgo { 123 fmt.Fprint(fgo2, gccgoGoProlog) 124 fmt.Fprint(fc, p.cPrologGccgo()) 125 } else { 126 fmt.Fprint(fgo2, goProlog) 127 } 128 129 if fc != nil { 130 fmt.Fprintf(fc, "#line 1 \"cgo-generated-wrappers\"\n") 131 } 132 if fm != nil { 133 fmt.Fprintf(fm, "#line 1 \"cgo-generated-wrappers\"\n") 134 } 135 136 gccgoSymbolPrefix := p.gccgoSymbolPrefix() 137 138 cVars := make(map[string]bool) 139 for _, key := range nameKeys(p.Name) { 140 n := p.Name[key] 141 if !n.IsVar() { 142 continue 143 } 144 145 if !cVars[n.C] { 146 if *gccgo { 147 fmt.Fprintf(fc, "extern byte *%s;\n", n.C) 148 } else { 149 fmt.Fprintf(fm, "extern char %s[];\n", n.C) 150 fmt.Fprintf(fm, "void *_cgohack_%s = %s;\n\n", n.C, n.C) 151 fmt.Fprintf(fgo2, "//go:linkname __cgo_%s %s\n", n.C, n.C) 152 fmt.Fprintf(fgo2, "//go:cgo_import_static %s\n", n.C) 153 fmt.Fprintf(fgo2, "var __cgo_%s byte\n", n.C) 154 } 155 cVars[n.C] = true 156 } 157 158 var node ast.Node 159 if n.Kind == "var" { 160 node = &ast.StarExpr{X: n.Type.Go} 161 } else if n.Kind == "fpvar" { 162 node = n.Type.Go 163 } else { 164 panic(fmt.Errorf("invalid var kind %q", n.Kind)) 165 } 166 if *gccgo { 167 fmt.Fprintf(fc, `extern void *%s __asm__("%s.%s");`, n.Mangle, gccgoSymbolPrefix, n.Mangle) 168 fmt.Fprintf(&gccgoInit, "\t%s = &%s;\n", n.Mangle, n.C) 169 fmt.Fprintf(fc, "\n") 170 } 171 172 fmt.Fprintf(fgo2, "var %s ", n.Mangle) 173 conf.Fprint(fgo2, fset, node) 174 if !*gccgo { 175 fmt.Fprintf(fgo2, " = (") 176 conf.Fprint(fgo2, fset, node) 177 fmt.Fprintf(fgo2, ")(unsafe.Pointer(&__cgo_%s))", n.C) 178 } 179 fmt.Fprintf(fgo2, "\n") 180 } 181 if *gccgo { 182 fmt.Fprintf(fc, "\n") 183 } 184 185 for _, key := range nameKeys(p.Name) { 186 n := p.Name[key] 187 if n.Const != "" { 188 fmt.Fprintf(fgo2, "const %s = %s\n", n.Mangle, n.Const) 189 } 190 } 191 fmt.Fprintf(fgo2, "\n") 192 193 callsMalloc := false 194 for _, key := range nameKeys(p.Name) { 195 n := p.Name[key] 196 if n.FuncType != nil { 197 p.writeDefsFunc(fgo2, n, &callsMalloc) 198 } 199 } 200 201 fgcc := creat(*objDir + "_cgo_export.c") 202 fgcch := creat(*objDir + "_cgo_export.h") 203 if *gccgo { 204 p.writeGccgoExports(fgo2, fm, fgcc, fgcch) 205 } else { 206 p.writeExports(fgo2, fm, fgcc, fgcch) 207 } 208 209 if callsMalloc && !*gccgo { 210 fmt.Fprint(fgo2, strings.Replace(cMallocDefGo, "PREFIX", cPrefix, -1)) 211 fmt.Fprint(fgcc, strings.Replace(strings.Replace(cMallocDefC, "PREFIX", cPrefix, -1), "PACKED", p.packedAttribute(), -1)) 212 } 213 214 if err := fgcc.Close(); err != nil { 215 fatalf("%s", err) 216 } 217 if err := fgcch.Close(); err != nil { 218 fatalf("%s", err) 219 } 220 221 if *exportHeader != "" && len(p.ExpFunc) > 0 { 222 fexp := creat(*exportHeader) 223 fgcch, err := os.Open(*objDir + "_cgo_export.h") 224 if err != nil { 225 fatalf("%s", err) 226 } 227 _, err = io.Copy(fexp, fgcch) 228 if err != nil { 229 fatalf("%s", err) 230 } 231 if err = fexp.Close(); err != nil { 232 fatalf("%s", err) 233 } 234 } 235 236 init := gccgoInit.String() 237 if init != "" { 238 fmt.Fprintln(fc, "static void init(void) __attribute__ ((constructor));") 239 fmt.Fprintln(fc, "static void init(void) {") 240 fmt.Fprint(fc, init) 241 fmt.Fprintln(fc, "}") 242 } 243 } 244 245 func dynimport(obj string) { 246 stdout := os.Stdout 247 if *dynout != "" { 248 f, err := os.Create(*dynout) 249 if err != nil { 250 fatalf("%s", err) 251 } 252 stdout = f 253 } 254 255 fmt.Fprintf(stdout, "package %s\n", *dynpackage) 256 257 if f, err := elf.Open(obj); err == nil { 258 if *dynlinker { 259 // Emit the cgo_dynamic_linker line. 260 if sec := f.Section(".interp"); sec != nil { 261 if data, err := sec.Data(); err == nil && len(data) > 1 { 262 // skip trailing \0 in data 263 fmt.Fprintf(stdout, "//go:cgo_dynamic_linker %q\n", string(data[:len(data)-1])) 264 } 265 } 266 } 267 sym, err := f.ImportedSymbols() 268 if err != nil { 269 fatalf("cannot load imported symbols from ELF file %s: %v", obj, err) 270 } 271 for _, s := range sym { 272 targ := s.Name 273 if s.Version != "" { 274 targ += "#" + s.Version 275 } 276 fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", s.Name, targ, s.Library) 277 } 278 lib, err := f.ImportedLibraries() 279 if err != nil { 280 fatalf("cannot load imported libraries from ELF file %s: %v", obj, err) 281 } 282 for _, l := range lib { 283 fmt.Fprintf(stdout, "//go:cgo_import_dynamic _ _ %q\n", l) 284 } 285 return 286 } 287 288 if f, err := macho.Open(obj); err == nil { 289 sym, err := f.ImportedSymbols() 290 if err != nil { 291 fatalf("cannot load imported symbols from Mach-O file %s: %v", obj, err) 292 } 293 for _, s := range sym { 294 if len(s) > 0 && s[0] == '_' { 295 s = s[1:] 296 } 297 fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", s, s, "") 298 } 299 lib, err := f.ImportedLibraries() 300 if err != nil { 301 fatalf("cannot load imported libraries from Mach-O file %s: %v", obj, err) 302 } 303 for _, l := range lib { 304 fmt.Fprintf(stdout, "//go:cgo_import_dynamic _ _ %q\n", l) 305 } 306 return 307 } 308 309 if f, err := pe.Open(obj); err == nil { 310 sym, err := f.ImportedSymbols() 311 if err != nil { 312 fatalf("cannot load imported symbols from PE file %s: %v", obj, err) 313 } 314 for _, s := range sym { 315 ss := strings.Split(s, ":") 316 name := strings.Split(ss[0], "@")[0] 317 fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", name, ss[0], strings.ToLower(ss[1])) 318 } 319 return 320 } 321 322 fatalf("cannot parse %s as ELF, Mach-O or PE", obj) 323 } 324 325 // Construct a gcc struct matching the gc argument frame. 326 // Assumes that in gcc, char is 1 byte, short 2 bytes, int 4 bytes, long long 8 bytes. 327 // These assumptions are checked by the gccProlog. 328 // Also assumes that gc convention is to word-align the 329 // input and output parameters. 330 func (p *Package) structType(n *Name) (string, int64) { 331 var buf bytes.Buffer 332 fmt.Fprint(&buf, "struct {\n") 333 off := int64(0) 334 for i, t := range n.FuncType.Params { 335 if off%t.Align != 0 { 336 pad := t.Align - off%t.Align 337 fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad) 338 off += pad 339 } 340 c := t.Typedef 341 if c == "" { 342 c = t.C.String() 343 } 344 fmt.Fprintf(&buf, "\t\t%s p%d;\n", c, i) 345 off += t.Size 346 } 347 if off%p.PtrSize != 0 { 348 pad := p.PtrSize - off%p.PtrSize 349 fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad) 350 off += pad 351 } 352 if t := n.FuncType.Result; t != nil { 353 if off%t.Align != 0 { 354 pad := t.Align - off%t.Align 355 fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad) 356 off += pad 357 } 358 fmt.Fprintf(&buf, "\t\t%s r;\n", t.C) 359 off += t.Size 360 } 361 if off%p.PtrSize != 0 { 362 pad := p.PtrSize - off%p.PtrSize 363 fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad) 364 off += pad 365 } 366 if off == 0 { 367 fmt.Fprintf(&buf, "\t\tchar unused;\n") // avoid empty struct 368 } 369 fmt.Fprintf(&buf, "\t}") 370 return buf.String(), off 371 } 372 373 func (p *Package) writeDefsFunc(fgo2 io.Writer, n *Name, callsMalloc *bool) { 374 name := n.Go 375 gtype := n.FuncType.Go 376 void := gtype.Results == nil || len(gtype.Results.List) == 0 377 if n.AddError { 378 // Add "error" to return type list. 379 // Type list is known to be 0 or 1 element - it's a C function. 380 err := &ast.Field{Type: ast.NewIdent("error")} 381 l := gtype.Results.List 382 if len(l) == 0 { 383 l = []*ast.Field{err} 384 } else { 385 l = []*ast.Field{l[0], err} 386 } 387 t := new(ast.FuncType) 388 *t = *gtype 389 t.Results = &ast.FieldList{List: l} 390 gtype = t 391 } 392 393 // Go func declaration. 394 d := &ast.FuncDecl{ 395 Name: ast.NewIdent(n.Mangle), 396 Type: gtype, 397 } 398 399 // Builtins defined in the C prolog. 400 inProlog := builtinDefs[name] != "" 401 cname := fmt.Sprintf("_cgo%s%s", cPrefix, n.Mangle) 402 paramnames := []string(nil) 403 if d.Type.Params != nil { 404 for i, param := range d.Type.Params.List { 405 paramName := fmt.Sprintf("p%d", i) 406 param.Names = []*ast.Ident{ast.NewIdent(paramName)} 407 paramnames = append(paramnames, paramName) 408 } 409 } 410 411 if *gccgo { 412 // Gccgo style hooks. 413 fmt.Fprint(fgo2, "\n") 414 conf.Fprint(fgo2, fset, d) 415 fmt.Fprint(fgo2, " {\n") 416 if !inProlog { 417 fmt.Fprint(fgo2, "\tdefer syscall.CgocallDone()\n") 418 fmt.Fprint(fgo2, "\tsyscall.Cgocall()\n") 419 } 420 if n.AddError { 421 fmt.Fprint(fgo2, "\tsyscall.SetErrno(0)\n") 422 } 423 fmt.Fprint(fgo2, "\t") 424 if !void { 425 fmt.Fprint(fgo2, "r := ") 426 } 427 fmt.Fprintf(fgo2, "%s(%s)\n", cname, strings.Join(paramnames, ", ")) 428 429 if n.AddError { 430 fmt.Fprint(fgo2, "\te := syscall.GetErrno()\n") 431 fmt.Fprint(fgo2, "\tif e != 0 {\n") 432 fmt.Fprint(fgo2, "\t\treturn ") 433 if !void { 434 fmt.Fprint(fgo2, "r, ") 435 } 436 fmt.Fprint(fgo2, "e\n") 437 fmt.Fprint(fgo2, "\t}\n") 438 fmt.Fprint(fgo2, "\treturn ") 439 if !void { 440 fmt.Fprint(fgo2, "r, ") 441 } 442 fmt.Fprint(fgo2, "nil\n") 443 } else if !void { 444 fmt.Fprint(fgo2, "\treturn r\n") 445 } 446 447 fmt.Fprint(fgo2, "}\n") 448 449 // declare the C function. 450 fmt.Fprintf(fgo2, "//extern %s\n", cname) 451 d.Name = ast.NewIdent(cname) 452 if n.AddError { 453 l := d.Type.Results.List 454 d.Type.Results.List = l[:len(l)-1] 455 } 456 conf.Fprint(fgo2, fset, d) 457 fmt.Fprint(fgo2, "\n") 458 459 return 460 } 461 462 if inProlog { 463 fmt.Fprint(fgo2, builtinDefs[name]) 464 if strings.Contains(builtinDefs[name], "_cgo_cmalloc") { 465 *callsMalloc = true 466 } 467 return 468 } 469 470 // Wrapper calls into gcc, passing a pointer to the argument frame. 471 fmt.Fprintf(fgo2, "//go:cgo_import_static %s\n", cname) 472 fmt.Fprintf(fgo2, "//go:linkname __cgofn_%s %s\n", cname, cname) 473 fmt.Fprintf(fgo2, "var __cgofn_%s byte\n", cname) 474 fmt.Fprintf(fgo2, "var %s = unsafe.Pointer(&__cgofn_%s)\n", cname, cname) 475 476 nret := 0 477 if !void { 478 d.Type.Results.List[0].Names = []*ast.Ident{ast.NewIdent("r1")} 479 nret = 1 480 } 481 if n.AddError { 482 d.Type.Results.List[nret].Names = []*ast.Ident{ast.NewIdent("r2")} 483 } 484 485 fmt.Fprint(fgo2, "\n") 486 fmt.Fprint(fgo2, "//go:cgo_unsafe_args\n") 487 conf.Fprint(fgo2, fset, d) 488 fmt.Fprint(fgo2, " {\n") 489 490 // NOTE: Using uintptr to hide from escape analysis. 491 arg := "0" 492 if len(paramnames) > 0 { 493 arg = "uintptr(unsafe.Pointer(&p0))" 494 } else if !void { 495 arg = "uintptr(unsafe.Pointer(&r1))" 496 } 497 498 prefix := "" 499 if n.AddError { 500 prefix = "errno := " 501 } 502 fmt.Fprintf(fgo2, "\t%s_cgo_runtime_cgocall(%s, %s)\n", prefix, cname, arg) 503 if n.AddError { 504 fmt.Fprintf(fgo2, "\tif errno != 0 { r2 = syscall.Errno(errno) }\n") 505 } 506 fmt.Fprintf(fgo2, "\tif _Cgo_always_false {\n") 507 if d.Type.Params != nil { 508 for i := range d.Type.Params.List { 509 fmt.Fprintf(fgo2, "\t\t_Cgo_use(p%d)\n", i) 510 } 511 } 512 fmt.Fprintf(fgo2, "\t}\n") 513 fmt.Fprintf(fgo2, "\treturn\n") 514 fmt.Fprintf(fgo2, "}\n") 515 } 516 517 // writeOutput creates stubs for a specific source file to be compiled by gc 518 func (p *Package) writeOutput(f *File, srcfile string) { 519 base := srcfile 520 if strings.HasSuffix(base, ".go") { 521 base = base[0 : len(base)-3] 522 } 523 base = strings.Map(slashToUnderscore, base) 524 fgo1 := creat(*objDir + base + ".cgo1.go") 525 fgcc := creat(*objDir + base + ".cgo2.c") 526 527 p.GoFiles = append(p.GoFiles, base+".cgo1.go") 528 p.GccFiles = append(p.GccFiles, base+".cgo2.c") 529 530 // Write Go output: Go input with rewrites of C.xxx to _C_xxx. 531 fmt.Fprintf(fgo1, "// Created by cgo - DO NOT EDIT\n\n") 532 conf.Fprint(fgo1, fset, f.AST) 533 534 // While we process the vars and funcs, also write gcc output. 535 // Gcc output starts with the preamble. 536 fmt.Fprintf(fgcc, "%s\n", f.Preamble) 537 fmt.Fprintf(fgcc, "%s\n", gccProlog) 538 fmt.Fprintf(fgcc, "%s\n", tsanProlog) 539 540 for _, key := range nameKeys(f.Name) { 541 n := f.Name[key] 542 if n.FuncType != nil { 543 p.writeOutputFunc(fgcc, n) 544 } 545 } 546 547 fgo1.Close() 548 fgcc.Close() 549 } 550 551 // fixGo converts the internal Name.Go field into the name we should show 552 // to users in error messages. There's only one for now: on input we rewrite 553 // C.malloc into C._CMalloc, so change it back here. 554 func fixGo(name string) string { 555 if name == "_CMalloc" { 556 return "malloc" 557 } 558 return name 559 } 560 561 var isBuiltin = map[string]bool{ 562 "_Cfunc_CString": true, 563 "_Cfunc_CBytes": true, 564 "_Cfunc_GoString": true, 565 "_Cfunc_GoStringN": true, 566 "_Cfunc_GoBytes": true, 567 "_Cfunc__CMalloc": true, 568 } 569 570 func (p *Package) writeOutputFunc(fgcc *os.File, n *Name) { 571 name := n.Mangle 572 if isBuiltin[name] || p.Written[name] { 573 // The builtins are already defined in the C prolog, and we don't 574 // want to duplicate function definitions we've already done. 575 return 576 } 577 p.Written[name] = true 578 579 if *gccgo { 580 p.writeGccgoOutputFunc(fgcc, n) 581 return 582 } 583 584 ctype, _ := p.structType(n) 585 586 // Gcc wrapper unpacks the C argument struct 587 // and calls the actual C function. 588 fmt.Fprintf(fgcc, "CGO_NO_SANITIZE_THREAD\n") 589 if n.AddError { 590 fmt.Fprintf(fgcc, "int\n") 591 } else { 592 fmt.Fprintf(fgcc, "void\n") 593 } 594 fmt.Fprintf(fgcc, "_cgo%s%s(void *v)\n", cPrefix, n.Mangle) 595 fmt.Fprintf(fgcc, "{\n") 596 if n.AddError { 597 fmt.Fprintf(fgcc, "\tint _cgo_errno;\n") 598 } 599 // We're trying to write a gcc struct that matches gc's layout. 600 // Use packed attribute to force no padding in this struct in case 601 // gcc has different packing requirements. 602 fmt.Fprintf(fgcc, "\t%s %v *a = v;\n", ctype, p.packedAttribute()) 603 if n.FuncType.Result != nil { 604 // Save the stack top for use below. 605 fmt.Fprintf(fgcc, "\tchar *stktop = _cgo_topofstack();\n") 606 } 607 tr := n.FuncType.Result 608 if tr != nil { 609 fmt.Fprintf(fgcc, "\t__typeof__(a->r) r;\n") 610 } 611 fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n") 612 if n.AddError { 613 fmt.Fprintf(fgcc, "\terrno = 0;\n") 614 } 615 fmt.Fprintf(fgcc, "\t") 616 if tr != nil { 617 fmt.Fprintf(fgcc, "r = ") 618 if c := tr.C.String(); c[len(c)-1] == '*' { 619 fmt.Fprint(fgcc, "(__typeof__(a->r)) ") 620 } 621 } 622 if n.Kind == "macro" { 623 fmt.Fprintf(fgcc, "%s;\n", n.C) 624 } else { 625 fmt.Fprintf(fgcc, "%s(", n.C) 626 for i := range n.FuncType.Params { 627 if i > 0 { 628 fmt.Fprintf(fgcc, ", ") 629 } 630 fmt.Fprintf(fgcc, "a->p%d", i) 631 } 632 fmt.Fprintf(fgcc, ");\n") 633 } 634 if n.AddError { 635 fmt.Fprintf(fgcc, "\t_cgo_errno = errno;\n") 636 } 637 fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n") 638 if n.FuncType.Result != nil { 639 // The cgo call may have caused a stack copy (via a callback). 640 // Adjust the return value pointer appropriately. 641 fmt.Fprintf(fgcc, "\ta = (void*)((char*)a + (_cgo_topofstack() - stktop));\n") 642 // Save the return value. 643 fmt.Fprintf(fgcc, "\ta->r = r;\n") 644 } 645 if n.AddError { 646 fmt.Fprintf(fgcc, "\treturn _cgo_errno;\n") 647 } 648 fmt.Fprintf(fgcc, "}\n") 649 fmt.Fprintf(fgcc, "\n") 650 } 651 652 // Write out a wrapper for a function when using gccgo. This is a 653 // simple wrapper that just calls the real function. We only need a 654 // wrapper to support static functions in the prologue--without a 655 // wrapper, we can't refer to the function, since the reference is in 656 // a different file. 657 func (p *Package) writeGccgoOutputFunc(fgcc *os.File, n *Name) { 658 fmt.Fprintf(fgcc, "CGO_NO_SANITIZE_THREAD\n") 659 if t := n.FuncType.Result; t != nil { 660 fmt.Fprintf(fgcc, "%s\n", t.C.String()) 661 } else { 662 fmt.Fprintf(fgcc, "void\n") 663 } 664 fmt.Fprintf(fgcc, "_cgo%s%s(", cPrefix, n.Mangle) 665 for i, t := range n.FuncType.Params { 666 if i > 0 { 667 fmt.Fprintf(fgcc, ", ") 668 } 669 c := t.Typedef 670 if c == "" { 671 c = t.C.String() 672 } 673 fmt.Fprintf(fgcc, "%s p%d", c, i) 674 } 675 fmt.Fprintf(fgcc, ")\n") 676 fmt.Fprintf(fgcc, "{\n") 677 if t := n.FuncType.Result; t != nil { 678 fmt.Fprintf(fgcc, "\t%s r;\n", t.C.String()) 679 } 680 fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n") 681 fmt.Fprintf(fgcc, "\t") 682 if t := n.FuncType.Result; t != nil { 683 fmt.Fprintf(fgcc, "r = ") 684 // Cast to void* to avoid warnings due to omitted qualifiers. 685 if c := t.C.String(); c[len(c)-1] == '*' { 686 fmt.Fprintf(fgcc, "(void*)") 687 } 688 } 689 fmt.Fprintf(fgcc, "%s(", n.C) 690 for i := range n.FuncType.Params { 691 if i > 0 { 692 fmt.Fprintf(fgcc, ", ") 693 } 694 fmt.Fprintf(fgcc, "p%d", i) 695 } 696 fmt.Fprintf(fgcc, ");\n") 697 fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n") 698 if t := n.FuncType.Result; t != nil { 699 fmt.Fprintf(fgcc, "\treturn ") 700 // Cast to void* to avoid warnings due to omitted qualifiers 701 // and explicit incompatible struct types. 702 if c := t.C.String(); c[len(c)-1] == '*' { 703 fmt.Fprintf(fgcc, "(void*)") 704 } 705 fmt.Fprintf(fgcc, "r;\n") 706 } 707 fmt.Fprintf(fgcc, "}\n") 708 fmt.Fprintf(fgcc, "\n") 709 } 710 711 // packedAttribute returns host compiler struct attribute that will be 712 // used to match gc's struct layout. For example, on 386 Windows, 713 // gcc wants to 8-align int64s, but gc does not. 714 // Use __gcc_struct__ to work around http://gcc.gnu.org/PR52991 on x86, 715 // and https://golang.org/issue/5603. 716 func (p *Package) packedAttribute() string { 717 s := "__attribute__((__packed__" 718 if !p.GccIsClang && (goarch == "amd64" || goarch == "386") { 719 s += ", __gcc_struct__" 720 } 721 return s + "))" 722 } 723 724 // Write out the various stubs we need to support functions exported 725 // from Go so that they are callable from C. 726 func (p *Package) writeExports(fgo2, fm, fgcc, fgcch io.Writer) { 727 p.writeExportHeader(fgcch) 728 729 fmt.Fprintf(fgcc, "/* Created by cgo - DO NOT EDIT. */\n") 730 fmt.Fprintf(fgcc, "#include <stdlib.h>\n") 731 fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n\n") 732 733 fmt.Fprintf(fgcc, "extern void crosscall2(void (*fn)(void *, int, __SIZE_TYPE__), void *, int, __SIZE_TYPE__);\n") 734 fmt.Fprintf(fgcc, "extern __SIZE_TYPE__ _cgo_wait_runtime_init_done();\n") 735 fmt.Fprintf(fgcc, "extern void _cgo_release_context(__SIZE_TYPE__);\n\n") 736 fmt.Fprintf(fgcc, "extern char* _cgo_topofstack(void);") 737 fmt.Fprintf(fgcc, "%s\n", tsanProlog) 738 739 for _, exp := range p.ExpFunc { 740 fn := exp.Func 741 742 // Construct a gcc struct matching the gc argument and 743 // result frame. The gcc struct will be compiled with 744 // __attribute__((packed)) so all padding must be accounted 745 // for explicitly. 746 ctype := "struct {\n" 747 off := int64(0) 748 npad := 0 749 if fn.Recv != nil { 750 t := p.cgoType(fn.Recv.List[0].Type) 751 ctype += fmt.Sprintf("\t\t%s recv;\n", t.C) 752 off += t.Size 753 } 754 fntype := fn.Type 755 forFieldList(fntype.Params, 756 func(i int, aname string, atype ast.Expr) { 757 t := p.cgoType(atype) 758 if off%t.Align != 0 { 759 pad := t.Align - off%t.Align 760 ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad) 761 off += pad 762 npad++ 763 } 764 ctype += fmt.Sprintf("\t\t%s p%d;\n", t.C, i) 765 off += t.Size 766 }) 767 if off%p.PtrSize != 0 { 768 pad := p.PtrSize - off%p.PtrSize 769 ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad) 770 off += pad 771 npad++ 772 } 773 forFieldList(fntype.Results, 774 func(i int, aname string, atype ast.Expr) { 775 t := p.cgoType(atype) 776 if off%t.Align != 0 { 777 pad := t.Align - off%t.Align 778 ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad) 779 off += pad 780 npad++ 781 } 782 ctype += fmt.Sprintf("\t\t%s r%d;\n", t.C, i) 783 off += t.Size 784 }) 785 if off%p.PtrSize != 0 { 786 pad := p.PtrSize - off%p.PtrSize 787 ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad) 788 off += pad 789 npad++ 790 } 791 if ctype == "struct {\n" { 792 ctype += "\t\tchar unused;\n" // avoid empty struct 793 } 794 ctype += "\t}" 795 796 // Get the return type of the wrapper function 797 // compiled by gcc. 798 gccResult := "" 799 if fntype.Results == nil || len(fntype.Results.List) == 0 { 800 gccResult = "void" 801 } else if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 { 802 gccResult = p.cgoType(fntype.Results.List[0].Type).C.String() 803 } else { 804 fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName) 805 fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName) 806 forFieldList(fntype.Results, 807 func(i int, aname string, atype ast.Expr) { 808 fmt.Fprintf(fgcch, "\t%s r%d;", p.cgoType(atype).C, i) 809 if len(aname) > 0 { 810 fmt.Fprintf(fgcch, " /* %s */", aname) 811 } 812 fmt.Fprint(fgcch, "\n") 813 }) 814 fmt.Fprintf(fgcch, "};\n") 815 gccResult = "struct " + exp.ExpName + "_return" 816 } 817 818 // Build the wrapper function compiled by gcc. 819 s := fmt.Sprintf("%s %s(", gccResult, exp.ExpName) 820 if fn.Recv != nil { 821 s += p.cgoType(fn.Recv.List[0].Type).C.String() 822 s += " recv" 823 } 824 forFieldList(fntype.Params, 825 func(i int, aname string, atype ast.Expr) { 826 if i > 0 || fn.Recv != nil { 827 s += ", " 828 } 829 s += fmt.Sprintf("%s p%d", p.cgoType(atype).C, i) 830 }) 831 s += ")" 832 833 if len(exp.Doc) > 0 { 834 fmt.Fprintf(fgcch, "\n%s", exp.Doc) 835 } 836 fmt.Fprintf(fgcch, "\nextern %s;\n", s) 837 838 fmt.Fprintf(fgcc, "extern void _cgoexp%s_%s(void *, int, __SIZE_TYPE__);\n", cPrefix, exp.ExpName) 839 fmt.Fprintf(fgcc, "\nCGO_NO_SANITIZE_THREAD") 840 fmt.Fprintf(fgcc, "\n%s\n", s) 841 fmt.Fprintf(fgcc, "{\n") 842 fmt.Fprintf(fgcc, "\t__SIZE_TYPE__ _cgo_ctxt = _cgo_wait_runtime_init_done();\n") 843 fmt.Fprintf(fgcc, "\t%s %v a;\n", ctype, p.packedAttribute()) 844 if gccResult != "void" && (len(fntype.Results.List) > 1 || len(fntype.Results.List[0].Names) > 1) { 845 fmt.Fprintf(fgcc, "\t%s r;\n", gccResult) 846 } 847 if fn.Recv != nil { 848 fmt.Fprintf(fgcc, "\ta.recv = recv;\n") 849 } 850 forFieldList(fntype.Params, 851 func(i int, aname string, atype ast.Expr) { 852 fmt.Fprintf(fgcc, "\ta.p%d = p%d;\n", i, i) 853 }) 854 fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n") 855 fmt.Fprintf(fgcc, "\tcrosscall2(_cgoexp%s_%s, &a, %d, _cgo_ctxt);\n", cPrefix, exp.ExpName, off) 856 fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n") 857 fmt.Fprintf(fgcc, "\t_cgo_release_context(_cgo_ctxt);\n") 858 if gccResult != "void" { 859 if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 { 860 fmt.Fprintf(fgcc, "\treturn a.r0;\n") 861 } else { 862 forFieldList(fntype.Results, 863 func(i int, aname string, atype ast.Expr) { 864 fmt.Fprintf(fgcc, "\tr.r%d = a.r%d;\n", i, i) 865 }) 866 fmt.Fprintf(fgcc, "\treturn r;\n") 867 } 868 } 869 fmt.Fprintf(fgcc, "}\n") 870 871 // Build the wrapper function compiled by cmd/compile. 872 goname := "_cgoexpwrap" + cPrefix + "_" 873 if fn.Recv != nil { 874 goname += fn.Recv.List[0].Names[0].Name + "_" 875 } 876 goname += exp.Func.Name.Name 877 fmt.Fprintf(fgo2, "//go:cgo_export_dynamic %s\n", exp.ExpName) 878 fmt.Fprintf(fgo2, "//go:linkname _cgoexp%s_%s _cgoexp%s_%s\n", cPrefix, exp.ExpName, cPrefix, exp.ExpName) 879 fmt.Fprintf(fgo2, "//go:cgo_export_static _cgoexp%s_%s\n", cPrefix, exp.ExpName) 880 fmt.Fprintf(fgo2, "//go:nosplit\n") // no split stack, so no use of m or g 881 fmt.Fprintf(fgo2, "//go:norace\n") // must not have race detector calls inserted 882 fmt.Fprintf(fgo2, "func _cgoexp%s_%s(a unsafe.Pointer, n int32, ctxt uintptr) {\n", cPrefix, exp.ExpName) 883 fmt.Fprintf(fgo2, "\tfn := %s\n", goname) 884 // The indirect here is converting from a Go function pointer to a C function pointer. 885 fmt.Fprintf(fgo2, "\t_cgo_runtime_cgocallback(**(**unsafe.Pointer)(unsafe.Pointer(&fn)), a, uintptr(n), ctxt);\n") 886 fmt.Fprintf(fgo2, "}\n") 887 888 fmt.Fprintf(fm, "int _cgoexp%s_%s;\n", cPrefix, exp.ExpName) 889 890 // This code uses printer.Fprint, not conf.Fprint, 891 // because we don't want //line comments in the middle 892 // of the function types. 893 fmt.Fprintf(fgo2, "\n") 894 fmt.Fprintf(fgo2, "func %s(", goname) 895 comma := false 896 if fn.Recv != nil { 897 fmt.Fprintf(fgo2, "recv ") 898 printer.Fprint(fgo2, fset, fn.Recv.List[0].Type) 899 comma = true 900 } 901 forFieldList(fntype.Params, 902 func(i int, aname string, atype ast.Expr) { 903 if comma { 904 fmt.Fprintf(fgo2, ", ") 905 } 906 fmt.Fprintf(fgo2, "p%d ", i) 907 printer.Fprint(fgo2, fset, atype) 908 comma = true 909 }) 910 fmt.Fprintf(fgo2, ")") 911 if gccResult != "void" { 912 fmt.Fprint(fgo2, " (") 913 forFieldList(fntype.Results, 914 func(i int, aname string, atype ast.Expr) { 915 if i > 0 { 916 fmt.Fprint(fgo2, ", ") 917 } 918 fmt.Fprintf(fgo2, "r%d ", i) 919 printer.Fprint(fgo2, fset, atype) 920 }) 921 fmt.Fprint(fgo2, ")") 922 } 923 fmt.Fprint(fgo2, " {\n") 924 if gccResult == "void" { 925 fmt.Fprint(fgo2, "\t") 926 } else { 927 // Verify that any results don't contain any 928 // Go pointers. 929 addedDefer := false 930 forFieldList(fntype.Results, 931 func(i int, aname string, atype ast.Expr) { 932 if !p.hasPointer(nil, atype, false) { 933 return 934 } 935 if !addedDefer { 936 fmt.Fprint(fgo2, "\tdefer func() {\n") 937 addedDefer = true 938 } 939 fmt.Fprintf(fgo2, "\t\t_cgoCheckResult(r%d)\n", i) 940 }) 941 if addedDefer { 942 fmt.Fprint(fgo2, "\t}()\n") 943 } 944 fmt.Fprint(fgo2, "\treturn ") 945 } 946 if fn.Recv != nil { 947 fmt.Fprintf(fgo2, "recv.") 948 } 949 fmt.Fprintf(fgo2, "%s(", exp.Func.Name) 950 forFieldList(fntype.Params, 951 func(i int, aname string, atype ast.Expr) { 952 if i > 0 { 953 fmt.Fprint(fgo2, ", ") 954 } 955 fmt.Fprintf(fgo2, "p%d", i) 956 }) 957 fmt.Fprint(fgo2, ")\n") 958 fmt.Fprint(fgo2, "}\n") 959 } 960 961 fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog) 962 } 963 964 // Write out the C header allowing C code to call exported gccgo functions. 965 func (p *Package) writeGccgoExports(fgo2, fm, fgcc, fgcch io.Writer) { 966 gccgoSymbolPrefix := p.gccgoSymbolPrefix() 967 968 p.writeExportHeader(fgcch) 969 970 fmt.Fprintf(fgcc, "/* Created by cgo - DO NOT EDIT. */\n") 971 fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n") 972 973 fmt.Fprintf(fgcc, "%s\n", gccgoExportFileProlog) 974 fmt.Fprintf(fgcc, "%s\n", tsanProlog) 975 976 for _, exp := range p.ExpFunc { 977 fn := exp.Func 978 fntype := fn.Type 979 980 cdeclBuf := new(bytes.Buffer) 981 resultCount := 0 982 forFieldList(fntype.Results, 983 func(i int, aname string, atype ast.Expr) { resultCount++ }) 984 switch resultCount { 985 case 0: 986 fmt.Fprintf(cdeclBuf, "void") 987 case 1: 988 forFieldList(fntype.Results, 989 func(i int, aname string, atype ast.Expr) { 990 t := p.cgoType(atype) 991 fmt.Fprintf(cdeclBuf, "%s", t.C) 992 }) 993 default: 994 // Declare a result struct. 995 fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName) 996 fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName) 997 forFieldList(fntype.Results, 998 func(i int, aname string, atype ast.Expr) { 999 t := p.cgoType(atype) 1000 fmt.Fprintf(fgcch, "\t%s r%d;", t.C, i) 1001 if len(aname) > 0 { 1002 fmt.Fprintf(fgcch, " /* %s */", aname) 1003 } 1004 fmt.Fprint(fgcch, "\n") 1005 }) 1006 fmt.Fprintf(fgcch, "};\n") 1007 fmt.Fprintf(cdeclBuf, "struct %s_return", exp.ExpName) 1008 } 1009 1010 cRet := cdeclBuf.String() 1011 1012 cdeclBuf = new(bytes.Buffer) 1013 fmt.Fprintf(cdeclBuf, "(") 1014 if fn.Recv != nil { 1015 fmt.Fprintf(cdeclBuf, "%s recv", p.cgoType(fn.Recv.List[0].Type).C.String()) 1016 } 1017 // Function parameters. 1018 forFieldList(fntype.Params, 1019 func(i int, aname string, atype ast.Expr) { 1020 if i > 0 || fn.Recv != nil { 1021 fmt.Fprintf(cdeclBuf, ", ") 1022 } 1023 t := p.cgoType(atype) 1024 fmt.Fprintf(cdeclBuf, "%s p%d", t.C, i) 1025 }) 1026 fmt.Fprintf(cdeclBuf, ")") 1027 cParams := cdeclBuf.String() 1028 1029 if len(exp.Doc) > 0 { 1030 fmt.Fprintf(fgcch, "\n%s", exp.Doc) 1031 } 1032 1033 fmt.Fprintf(fgcch, "extern %s %s%s;\n", cRet, exp.ExpName, cParams) 1034 1035 // We need to use a name that will be exported by the 1036 // Go code; otherwise gccgo will make it static and we 1037 // will not be able to link against it from the C 1038 // code. 1039 goName := "Cgoexp_" + exp.ExpName 1040 fmt.Fprintf(fgcc, `extern %s %s %s __asm__("%s.%s");`, cRet, goName, cParams, gccgoSymbolPrefix, goName) 1041 fmt.Fprint(fgcc, "\n") 1042 1043 fmt.Fprint(fgcc, "\nCGO_NO_SANITIZE_THREAD\n") 1044 fmt.Fprintf(fgcc, "%s %s %s {\n", cRet, exp.ExpName, cParams) 1045 if resultCount > 0 { 1046 fmt.Fprintf(fgcc, "\t%s r;\n", cRet) 1047 } 1048 fmt.Fprintf(fgcc, "\tif(_cgo_wait_runtime_init_done)\n") 1049 fmt.Fprintf(fgcc, "\t\t_cgo_wait_runtime_init_done();\n") 1050 fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n") 1051 fmt.Fprint(fgcc, "\t") 1052 if resultCount > 0 { 1053 fmt.Fprint(fgcc, "r = ") 1054 } 1055 fmt.Fprintf(fgcc, "%s(", goName) 1056 if fn.Recv != nil { 1057 fmt.Fprint(fgcc, "recv") 1058 } 1059 forFieldList(fntype.Params, 1060 func(i int, aname string, atype ast.Expr) { 1061 if i > 0 || fn.Recv != nil { 1062 fmt.Fprintf(fgcc, ", ") 1063 } 1064 fmt.Fprintf(fgcc, "p%d", i) 1065 }) 1066 fmt.Fprint(fgcc, ");\n") 1067 fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n") 1068 if resultCount > 0 { 1069 fmt.Fprint(fgcc, "\treturn r;\n") 1070 } 1071 fmt.Fprint(fgcc, "}\n") 1072 1073 // Dummy declaration for _cgo_main.c 1074 fmt.Fprintf(fm, `char %s[1] __asm__("%s.%s");`, goName, gccgoSymbolPrefix, goName) 1075 fmt.Fprint(fm, "\n") 1076 1077 // For gccgo we use a wrapper function in Go, in order 1078 // to call CgocallBack and CgocallBackDone. 1079 1080 // This code uses printer.Fprint, not conf.Fprint, 1081 // because we don't want //line comments in the middle 1082 // of the function types. 1083 fmt.Fprint(fgo2, "\n") 1084 fmt.Fprintf(fgo2, "func %s(", goName) 1085 if fn.Recv != nil { 1086 fmt.Fprint(fgo2, "recv ") 1087 printer.Fprint(fgo2, fset, fn.Recv.List[0].Type) 1088 } 1089 forFieldList(fntype.Params, 1090 func(i int, aname string, atype ast.Expr) { 1091 if i > 0 || fn.Recv != nil { 1092 fmt.Fprintf(fgo2, ", ") 1093 } 1094 fmt.Fprintf(fgo2, "p%d ", i) 1095 printer.Fprint(fgo2, fset, atype) 1096 }) 1097 fmt.Fprintf(fgo2, ")") 1098 if resultCount > 0 { 1099 fmt.Fprintf(fgo2, " (") 1100 forFieldList(fntype.Results, 1101 func(i int, aname string, atype ast.Expr) { 1102 if i > 0 { 1103 fmt.Fprint(fgo2, ", ") 1104 } 1105 printer.Fprint(fgo2, fset, atype) 1106 }) 1107 fmt.Fprint(fgo2, ")") 1108 } 1109 fmt.Fprint(fgo2, " {\n") 1110 fmt.Fprint(fgo2, "\tsyscall.CgocallBack()\n") 1111 fmt.Fprint(fgo2, "\tdefer syscall.CgocallBackDone()\n") 1112 fmt.Fprint(fgo2, "\t") 1113 if resultCount > 0 { 1114 fmt.Fprint(fgo2, "return ") 1115 } 1116 if fn.Recv != nil { 1117 fmt.Fprint(fgo2, "recv.") 1118 } 1119 fmt.Fprintf(fgo2, "%s(", exp.Func.Name) 1120 forFieldList(fntype.Params, 1121 func(i int, aname string, atype ast.Expr) { 1122 if i > 0 { 1123 fmt.Fprint(fgo2, ", ") 1124 } 1125 fmt.Fprintf(fgo2, "p%d", i) 1126 }) 1127 fmt.Fprint(fgo2, ")\n") 1128 fmt.Fprint(fgo2, "}\n") 1129 } 1130 1131 fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog) 1132 } 1133 1134 // writeExportHeader writes out the start of the _cgo_export.h file. 1135 func (p *Package) writeExportHeader(fgcch io.Writer) { 1136 fmt.Fprintf(fgcch, "/* Created by \"go tool cgo\" - DO NOT EDIT. */\n\n") 1137 pkg := *importPath 1138 if pkg == "" { 1139 pkg = p.PackagePath 1140 } 1141 fmt.Fprintf(fgcch, "/* package %s */\n\n", pkg) 1142 1143 fmt.Fprintf(fgcch, "/* Start of preamble from import \"C\" comments. */\n\n") 1144 fmt.Fprintf(fgcch, "%s\n", p.Preamble) 1145 fmt.Fprintf(fgcch, "\n/* End of preamble from import \"C\" comments. */\n\n") 1146 1147 fmt.Fprintf(fgcch, "%s\n", p.gccExportHeaderProlog()) 1148 } 1149 1150 // Return the package prefix when using gccgo. 1151 func (p *Package) gccgoSymbolPrefix() string { 1152 if !*gccgo { 1153 return "" 1154 } 1155 1156 clean := func(r rune) rune { 1157 switch { 1158 case 'A' <= r && r <= 'Z', 'a' <= r && r <= 'z', 1159 '0' <= r && r <= '9': 1160 return r 1161 } 1162 return '_' 1163 } 1164 1165 if *gccgopkgpath != "" { 1166 return strings.Map(clean, *gccgopkgpath) 1167 } 1168 if *gccgoprefix == "" && p.PackageName == "main" { 1169 return "main" 1170 } 1171 prefix := strings.Map(clean, *gccgoprefix) 1172 if prefix == "" { 1173 prefix = "go" 1174 } 1175 return prefix + "." + p.PackageName 1176 } 1177 1178 // Call a function for each entry in an ast.FieldList, passing the 1179 // index into the list, the name if any, and the type. 1180 func forFieldList(fl *ast.FieldList, fn func(int, string, ast.Expr)) { 1181 if fl == nil { 1182 return 1183 } 1184 i := 0 1185 for _, r := range fl.List { 1186 if r.Names == nil { 1187 fn(i, "", r.Type) 1188 i++ 1189 } else { 1190 for _, n := range r.Names { 1191 fn(i, n.Name, r.Type) 1192 i++ 1193 } 1194 } 1195 } 1196 } 1197 1198 func c(repr string, args ...interface{}) *TypeRepr { 1199 return &TypeRepr{repr, args} 1200 } 1201 1202 // Map predeclared Go types to Type. 1203 var goTypes = map[string]*Type{ 1204 "bool": {Size: 1, Align: 1, C: c("GoUint8")}, 1205 "byte": {Size: 1, Align: 1, C: c("GoUint8")}, 1206 "int": {Size: 0, Align: 0, C: c("GoInt")}, 1207 "uint": {Size: 0, Align: 0, C: c("GoUint")}, 1208 "rune": {Size: 4, Align: 4, C: c("GoInt32")}, 1209 "int8": {Size: 1, Align: 1, C: c("GoInt8")}, 1210 "uint8": {Size: 1, Align: 1, C: c("GoUint8")}, 1211 "int16": {Size: 2, Align: 2, C: c("GoInt16")}, 1212 "uint16": {Size: 2, Align: 2, C: c("GoUint16")}, 1213 "int32": {Size: 4, Align: 4, C: c("GoInt32")}, 1214 "uint32": {Size: 4, Align: 4, C: c("GoUint32")}, 1215 "int64": {Size: 8, Align: 8, C: c("GoInt64")}, 1216 "uint64": {Size: 8, Align: 8, C: c("GoUint64")}, 1217 "float32": {Size: 4, Align: 4, C: c("GoFloat32")}, 1218 "float64": {Size: 8, Align: 8, C: c("GoFloat64")}, 1219 "complex64": {Size: 8, Align: 4, C: c("GoComplex64")}, 1220 "complex128": {Size: 16, Align: 8, C: c("GoComplex128")}, 1221 } 1222 1223 // Map an ast type to a Type. 1224 func (p *Package) cgoType(e ast.Expr) *Type { 1225 switch t := e.(type) { 1226 case *ast.StarExpr: 1227 x := p.cgoType(t.X) 1228 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("%s*", x.C)} 1229 case *ast.ArrayType: 1230 if t.Len == nil { 1231 // Slice: pointer, len, cap. 1232 return &Type{Size: p.PtrSize * 3, Align: p.PtrSize, C: c("GoSlice")} 1233 } 1234 // Non-slice array types are not supported. 1235 case *ast.StructType: 1236 // Not supported. 1237 case *ast.FuncType: 1238 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")} 1239 case *ast.InterfaceType: 1240 return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")} 1241 case *ast.MapType: 1242 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoMap")} 1243 case *ast.ChanType: 1244 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoChan")} 1245 case *ast.Ident: 1246 // Look up the type in the top level declarations. 1247 // TODO: Handle types defined within a function. 1248 for _, d := range p.Decl { 1249 gd, ok := d.(*ast.GenDecl) 1250 if !ok || gd.Tok != token.TYPE { 1251 continue 1252 } 1253 for _, spec := range gd.Specs { 1254 ts, ok := spec.(*ast.TypeSpec) 1255 if !ok { 1256 continue 1257 } 1258 if ts.Name.Name == t.Name { 1259 return p.cgoType(ts.Type) 1260 } 1261 } 1262 } 1263 if def := typedef[t.Name]; def != nil { 1264 return def 1265 } 1266 if t.Name == "uintptr" { 1267 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoUintptr")} 1268 } 1269 if t.Name == "string" { 1270 // The string data is 1 pointer + 1 (pointer-sized) int. 1271 return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoString")} 1272 } 1273 if t.Name == "error" { 1274 return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")} 1275 } 1276 if r, ok := goTypes[t.Name]; ok { 1277 if r.Size == 0 { // int or uint 1278 rr := new(Type) 1279 *rr = *r 1280 rr.Size = p.IntSize 1281 rr.Align = p.IntSize 1282 r = rr 1283 } 1284 if r.Align > p.PtrSize { 1285 r.Align = p.PtrSize 1286 } 1287 return r 1288 } 1289 error_(e.Pos(), "unrecognized Go type %s", t.Name) 1290 return &Type{Size: 4, Align: 4, C: c("int")} 1291 case *ast.SelectorExpr: 1292 id, ok := t.X.(*ast.Ident) 1293 if ok && id.Name == "unsafe" && t.Sel.Name == "Pointer" { 1294 return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")} 1295 } 1296 } 1297 error_(e.Pos(), "Go type not supported in export: %s", gofmt(e)) 1298 return &Type{Size: 4, Align: 4, C: c("int")} 1299 } 1300 1301 const gccProlog = ` 1302 #line 1 "cgo-gcc-prolog" 1303 /* 1304 If x and y are not equal, the type will be invalid 1305 (have a negative array count) and an inscrutable error will come 1306 out of the compiler and hopefully mention "name". 1307 */ 1308 #define __cgo_compile_assert_eq(x, y, name) typedef char name[(x-y)*(x-y)*-2+1]; 1309 1310 /* Check at compile time that the sizes we use match our expectations. */ 1311 #define __cgo_size_assert(t, n) __cgo_compile_assert_eq(sizeof(t), n, _cgo_sizeof_##t##_is_not_##n) 1312 1313 __cgo_size_assert(char, 1) 1314 __cgo_size_assert(short, 2) 1315 __cgo_size_assert(int, 4) 1316 typedef long long __cgo_long_long; 1317 __cgo_size_assert(__cgo_long_long, 8) 1318 __cgo_size_assert(float, 4) 1319 __cgo_size_assert(double, 8) 1320 1321 extern char* _cgo_topofstack(void); 1322 1323 #include <errno.h> 1324 #include <string.h> 1325 ` 1326 1327 // Prologue defining TSAN functions in C. 1328 const noTsanProlog = ` 1329 #define CGO_NO_SANITIZE_THREAD 1330 #define _cgo_tsan_acquire() 1331 #define _cgo_tsan_release() 1332 ` 1333 1334 // This must match the TSAN code in runtime/cgo/libcgo.h. 1335 // This is used when the code is built with the C/C++ Thread SANitizer, 1336 // which is not the same as the Go race detector. 1337 // __tsan_acquire tells TSAN that we are acquiring a lock on a variable, 1338 // in this case _cgo_sync. __tsan_release releases the lock. 1339 // (There is no actual lock, we are just telling TSAN that there is.) 1340 // 1341 // When we call from Go to C we call _cgo_tsan_acquire. 1342 // When the C function returns we call _cgo_tsan_release. 1343 // Similarly, when C calls back into Go we call _cgo_tsan_release 1344 // and then call _cgo_tsan_acquire when we return to C. 1345 // These calls tell TSAN that there is a serialization point at the C call. 1346 // 1347 // This is necessary because TSAN, which is a C/C++ tool, can not see 1348 // the synchronization in the Go code. Without these calls, when 1349 // multiple goroutines call into C code, TSAN does not understand 1350 // that the calls are properly synchronized on the Go side. 1351 // 1352 // To be clear, if the calls are not properly synchronized on the Go side, 1353 // we will be hiding races. But when using TSAN on mixed Go C/C++ code 1354 // it is more important to avoid false positives, which reduce confidence 1355 // in the tool, than to avoid false negatives. 1356 const yesTsanProlog = ` 1357 #line 1 "cgo-tsan-prolog" 1358 #define CGO_NO_SANITIZE_THREAD __attribute__ ((no_sanitize_thread)) 1359 1360 long long _cgo_sync __attribute__ ((common)); 1361 1362 extern void __tsan_acquire(void*); 1363 extern void __tsan_release(void*); 1364 1365 __attribute__ ((unused)) 1366 static void _cgo_tsan_acquire() { 1367 __tsan_acquire(&_cgo_sync); 1368 } 1369 1370 __attribute__ ((unused)) 1371 static void _cgo_tsan_release() { 1372 __tsan_release(&_cgo_sync); 1373 } 1374 ` 1375 1376 // Set to yesTsanProlog if we see -fsanitize=thread in the flags for gcc. 1377 var tsanProlog = noTsanProlog 1378 1379 const builtinProlog = ` 1380 #line 1 "cgo-builtin-prolog" 1381 #include <stddef.h> /* for ptrdiff_t and size_t below */ 1382 1383 /* Define intgo when compiling with GCC. */ 1384 typedef ptrdiff_t intgo; 1385 1386 typedef struct { char *p; intgo n; } _GoString_; 1387 typedef struct { char *p; intgo n; intgo c; } _GoBytes_; 1388 _GoString_ GoString(char *p); 1389 _GoString_ GoStringN(char *p, int l); 1390 _GoBytes_ GoBytes(void *p, int n); 1391 char *CString(_GoString_); 1392 void *CBytes(_GoBytes_); 1393 void *_CMalloc(size_t); 1394 ` 1395 1396 const goProlog = ` 1397 //go:linkname _cgo_runtime_cgocall runtime.cgocall 1398 func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32 1399 1400 //go:linkname _cgo_runtime_cgocallback runtime.cgocallback 1401 func _cgo_runtime_cgocallback(unsafe.Pointer, unsafe.Pointer, uintptr, uintptr) 1402 1403 //go:linkname _cgoCheckPointer runtime.cgoCheckPointer 1404 func _cgoCheckPointer(interface{}, ...interface{}) 1405 1406 //go:linkname _cgoCheckResult runtime.cgoCheckResult 1407 func _cgoCheckResult(interface{}) 1408 ` 1409 1410 const gccgoGoProlog = ` 1411 func _cgoCheckPointer(interface{}, ...interface{}) 1412 1413 func _cgoCheckResult(interface{}) 1414 ` 1415 1416 const goStringDef = ` 1417 //go:linkname _cgo_runtime_gostring runtime.gostring 1418 func _cgo_runtime_gostring(*_Ctype_char) string 1419 1420 func _Cfunc_GoString(p *_Ctype_char) string { 1421 return _cgo_runtime_gostring(p) 1422 } 1423 ` 1424 1425 const goStringNDef = ` 1426 //go:linkname _cgo_runtime_gostringn runtime.gostringn 1427 func _cgo_runtime_gostringn(*_Ctype_char, int) string 1428 1429 func _Cfunc_GoStringN(p *_Ctype_char, l _Ctype_int) string { 1430 return _cgo_runtime_gostringn(p, int(l)) 1431 } 1432 ` 1433 1434 const goBytesDef = ` 1435 //go:linkname _cgo_runtime_gobytes runtime.gobytes 1436 func _cgo_runtime_gobytes(unsafe.Pointer, int) []byte 1437 1438 func _Cfunc_GoBytes(p unsafe.Pointer, l _Ctype_int) []byte { 1439 return _cgo_runtime_gobytes(p, int(l)) 1440 } 1441 ` 1442 1443 const cStringDef = ` 1444 func _Cfunc_CString(s string) *_Ctype_char { 1445 p := _cgo_cmalloc(uint64(len(s)+1)) 1446 pp := (*[1<<30]byte)(p) 1447 copy(pp[:], s) 1448 pp[len(s)] = 0 1449 return (*_Ctype_char)(p) 1450 } 1451 ` 1452 1453 const cBytesDef = ` 1454 func _Cfunc_CBytes(b []byte) unsafe.Pointer { 1455 p := _cgo_cmalloc(uint64(len(b))) 1456 pp := (*[1<<30]byte)(p) 1457 copy(pp[:], b) 1458 return p 1459 } 1460 ` 1461 1462 const cMallocDef = ` 1463 func _Cfunc__CMalloc(n _Ctype_size_t) unsafe.Pointer { 1464 return _cgo_cmalloc(uint64(n)) 1465 } 1466 ` 1467 1468 var builtinDefs = map[string]string{ 1469 "GoString": goStringDef, 1470 "GoStringN": goStringNDef, 1471 "GoBytes": goBytesDef, 1472 "CString": cStringDef, 1473 "CBytes": cBytesDef, 1474 "_CMalloc": cMallocDef, 1475 } 1476 1477 // Definitions for C.malloc in Go and in C. We define it ourselves 1478 // since we call it from functions we define, such as C.CString. 1479 // Also, we have historically ensured that C.malloc does not return 1480 // nil even for an allocation of 0. 1481 1482 const cMallocDefGo = ` 1483 //go:cgo_import_static _cgoPREFIX_Cfunc__Cmalloc 1484 //go:linkname __cgofn__cgoPREFIX_Cfunc__Cmalloc _cgoPREFIX_Cfunc__Cmalloc 1485 var __cgofn__cgoPREFIX_Cfunc__Cmalloc byte 1486 var _cgoPREFIX_Cfunc__Cmalloc = unsafe.Pointer(&__cgofn__cgoPREFIX_Cfunc__Cmalloc) 1487 1488 //go:linkname runtime_throw runtime.throw 1489 func runtime_throw(string) 1490 1491 //go:cgo_unsafe_args 1492 func _cgo_cmalloc(p0 uint64) (r1 unsafe.Pointer) { 1493 _cgo_runtime_cgocall(_cgoPREFIX_Cfunc__Cmalloc, uintptr(unsafe.Pointer(&p0))) 1494 if r1 == nil { 1495 runtime_throw("runtime: C malloc failed") 1496 } 1497 return 1498 } 1499 ` 1500 1501 // cMallocDefC defines the C version of C.malloc for the gc compiler. 1502 // It is defined here because C.CString and friends need a definition. 1503 // We define it by hand, rather than simply inventing a reference to 1504 // C.malloc, because <stdlib.h> may not have been included. 1505 // This is approximately what writeOutputFunc would generate, but 1506 // skips the cgo_topofstack code (which is only needed if the C code 1507 // calls back into Go). This also avoids returning nil for an 1508 // allocation of 0 bytes. 1509 const cMallocDefC = ` 1510 CGO_NO_SANITIZE_THREAD 1511 void _cgoPREFIX_Cfunc__Cmalloc(void *v) { 1512 struct { 1513 unsigned long long p0; 1514 void *r1; 1515 } PACKED *a = v; 1516 void *ret; 1517 _cgo_tsan_acquire(); 1518 ret = malloc(a->p0); 1519 if (ret == 0 && a->p0 == 0) { 1520 ret = malloc(1); 1521 } 1522 a->r1 = ret; 1523 _cgo_tsan_release(); 1524 } 1525 ` 1526 1527 func (p *Package) cPrologGccgo() string { 1528 return strings.Replace(strings.Replace(cPrologGccgo, "PREFIX", cPrefix, -1), 1529 "GCCGOSYMBOLPREF", p.gccgoSymbolPrefix(), -1) 1530 } 1531 1532 const cPrologGccgo = ` 1533 #line 1 "cgo-c-prolog-gccgo" 1534 #include <stdint.h> 1535 #include <stdlib.h> 1536 #include <string.h> 1537 1538 typedef unsigned char byte; 1539 typedef intptr_t intgo; 1540 1541 struct __go_string { 1542 const unsigned char *__data; 1543 intgo __length; 1544 }; 1545 1546 typedef struct __go_open_array { 1547 void* __values; 1548 intgo __count; 1549 intgo __capacity; 1550 } Slice; 1551 1552 struct __go_string __go_byte_array_to_string(const void* p, intgo len); 1553 struct __go_open_array __go_string_to_byte_array (struct __go_string str); 1554 1555 const char *_cgoPREFIX_Cfunc_CString(struct __go_string s) { 1556 char *p = malloc(s.__length+1); 1557 memmove(p, s.__data, s.__length); 1558 p[s.__length] = 0; 1559 return p; 1560 } 1561 1562 void *_cgoPREFIX_Cfunc_CBytes(struct __go_open_array b) { 1563 char *p = malloc(b.__count); 1564 memmove(p, b.__values, b.__count); 1565 return p; 1566 } 1567 1568 struct __go_string _cgoPREFIX_Cfunc_GoString(char *p) { 1569 intgo len = (p != NULL) ? strlen(p) : 0; 1570 return __go_byte_array_to_string(p, len); 1571 } 1572 1573 struct __go_string _cgoPREFIX_Cfunc_GoStringN(char *p, int32_t n) { 1574 return __go_byte_array_to_string(p, n); 1575 } 1576 1577 Slice _cgoPREFIX_Cfunc_GoBytes(char *p, int32_t n) { 1578 struct __go_string s = { (const unsigned char *)p, n }; 1579 return __go_string_to_byte_array(s); 1580 } 1581 1582 extern void runtime_throw(const char *); 1583 void *_cgoPREFIX_Cfunc__CMalloc(size_t n) { 1584 void *p = malloc(n); 1585 if(p == NULL && n == 0) 1586 p = malloc(1); 1587 if(p == NULL) 1588 runtime_throw("runtime: C malloc failed"); 1589 return p; 1590 } 1591 1592 struct __go_type_descriptor; 1593 typedef struct __go_empty_interface { 1594 const struct __go_type_descriptor *__type_descriptor; 1595 void *__object; 1596 } Eface; 1597 1598 extern void runtimeCgoCheckPointer(Eface, Slice) 1599 __asm__("runtime.cgoCheckPointer") 1600 __attribute__((weak)); 1601 1602 extern void localCgoCheckPointer(Eface, Slice) 1603 __asm__("GCCGOSYMBOLPREF._cgoCheckPointer"); 1604 1605 void localCgoCheckPointer(Eface ptr, Slice args) { 1606 if(runtimeCgoCheckPointer) { 1607 runtimeCgoCheckPointer(ptr, args); 1608 } 1609 } 1610 1611 extern void runtimeCgoCheckResult(Eface) 1612 __asm__("runtime.cgoCheckResult") 1613 __attribute__((weak)); 1614 1615 extern void localCgoCheckResult(Eface) 1616 __asm__("GCCGOSYMBOLPREF._cgoCheckResult"); 1617 1618 void localCgoCheckResult(Eface val) { 1619 if(runtimeCgoCheckResult) { 1620 runtimeCgoCheckResult(val); 1621 } 1622 } 1623 ` 1624 1625 func (p *Package) gccExportHeaderProlog() string { 1626 return strings.Replace(gccExportHeaderProlog, "GOINTBITS", fmt.Sprint(8*p.IntSize), -1) 1627 } 1628 1629 const gccExportHeaderProlog = ` 1630 /* Start of boilerplate cgo prologue. */ 1631 #line 1 "cgo-gcc-export-header-prolog" 1632 1633 #ifndef GO_CGO_PROLOGUE_H 1634 #define GO_CGO_PROLOGUE_H 1635 1636 typedef signed char GoInt8; 1637 typedef unsigned char GoUint8; 1638 typedef short GoInt16; 1639 typedef unsigned short GoUint16; 1640 typedef int GoInt32; 1641 typedef unsigned int GoUint32; 1642 typedef long long GoInt64; 1643 typedef unsigned long long GoUint64; 1644 typedef GoIntGOINTBITS GoInt; 1645 typedef GoUintGOINTBITS GoUint; 1646 typedef __SIZE_TYPE__ GoUintptr; 1647 typedef float GoFloat32; 1648 typedef double GoFloat64; 1649 typedef float _Complex GoComplex64; 1650 typedef double _Complex GoComplex128; 1651 1652 /* 1653 static assertion to make sure the file is being used on architecture 1654 at least with matching size of GoInt. 1655 */ 1656 typedef char _check_for_GOINTBITS_bit_pointer_matching_GoInt[sizeof(void*)==GOINTBITS/8 ? 1:-1]; 1657 1658 typedef struct { const char *p; GoInt n; } GoString; 1659 typedef void *GoMap; 1660 typedef void *GoChan; 1661 typedef struct { void *t; void *v; } GoInterface; 1662 typedef struct { void *data; GoInt len; GoInt cap; } GoSlice; 1663 1664 #endif 1665 1666 /* End of boilerplate cgo prologue. */ 1667 1668 #ifdef __cplusplus 1669 extern "C" { 1670 #endif 1671 ` 1672 1673 // gccExportHeaderEpilog goes at the end of the generated header file. 1674 const gccExportHeaderEpilog = ` 1675 #ifdef __cplusplus 1676 } 1677 #endif 1678 ` 1679 1680 // gccgoExportFileProlog is written to the _cgo_export.c file when 1681 // using gccgo. 1682 // We use weak declarations, and test the addresses, so that this code 1683 // works with older versions of gccgo. 1684 const gccgoExportFileProlog = ` 1685 #line 1 "cgo-gccgo-export-file-prolog" 1686 extern _Bool runtime_iscgo __attribute__ ((weak)); 1687 1688 static void GoInit(void) __attribute__ ((constructor)); 1689 static void GoInit(void) { 1690 if(&runtime_iscgo) 1691 runtime_iscgo = 1; 1692 } 1693 1694 extern __SIZE_TYPE__ _cgo_wait_runtime_init_done() __attribute__ ((weak)); 1695 `