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