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