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