github.com/llvm-mirror/llgo@v0.0.0-20190322182713-bf6f0a60fce1/third_party/gofrontend/libgo/go/cmd/cgo/out.go (about)

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