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