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