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