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