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