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