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