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