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