github.com/fjballest/golang@v0.0.0-20151209143359-e4c5fe594ca8/src/cmd/cgo/out.go (about)

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