github.com/alash3al/go@v0.0.0-20150827002835-d497eeb00540/src/cmd/cgo/out.go (about)

     1  // Copyright 2009 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  import (
     8  	"bytes"
     9  	"debug/elf"
    10  	"debug/macho"
    11  	"debug/pe"
    12  	"fmt"
    13  	"go/ast"
    14  	"go/printer"
    15  	"go/token"
    16  	"io"
    17  	"os"
    18  	"sort"
    19  	"strings"
    20  )
    21  
    22  var conf = printer.Config{Mode: printer.SourcePos, Tabwidth: 8}
    23  
    24  // writeDefs creates output files to be compiled by gc and gcc.
    25  func (p *Package) writeDefs() {
    26  	var fgo2, fc io.Writer
    27  	f := creat(*objDir + "_cgo_gotypes.go")
    28  	defer f.Close()
    29  	fgo2 = f
    30  	if *gccgo {
    31  		f := creat(*objDir + "_cgo_defun.c")
    32  		defer f.Close()
    33  		fc = f
    34  	}
    35  	fm := creat(*objDir + "_cgo_main.c")
    36  
    37  	var gccgoInit bytes.Buffer
    38  
    39  	fflg := creat(*objDir + "_cgo_flags")
    40  	for k, v := range p.CgoFlags {
    41  		fmt.Fprintf(fflg, "_CGO_%s=%s\n", k, strings.Join(v, " "))
    42  		if k == "LDFLAGS" && !*gccgo {
    43  			for _, arg := range v {
    44  				fmt.Fprintf(fgo2, "//go:cgo_ldflag %q\n", arg)
    45  			}
    46  		}
    47  	}
    48  	fflg.Close()
    49  
    50  	// Write C main file for using gcc to resolve imports.
    51  	fmt.Fprintf(fm, "int main() { return 0; }\n")
    52  	if *importRuntimeCgo {
    53  		fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*, int), void *a, int c) { }\n")
    54  		fmt.Fprintf(fm, "void _cgo_wait_runtime_init_done() { }\n")
    55  		fmt.Fprintf(fm, "char* _cgo_topofstack(void) { return (char*)0; }\n")
    56  	} else {
    57  		// If we're not importing runtime/cgo, we *are* runtime/cgo,
    58  		// which provides these functions.  We just need a prototype.
    59  		fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*, int), void *a, int c);\n")
    60  		fmt.Fprintf(fm, "void _cgo_wait_runtime_init_done();\n")
    61  	}
    62  	fmt.Fprintf(fm, "void _cgo_allocate(void *a, int c) { }\n")
    63  	fmt.Fprintf(fm, "void _cgo_panic(void *a, int c) { }\n")
    64  	fmt.Fprintf(fm, "void _cgo_reginit(void) { }\n")
    65  
    66  	// Write second Go output: definitions of _C_xxx.
    67  	// In a separate file so that the import of "unsafe" does not
    68  	// pollute the original file.
    69  	fmt.Fprintf(fgo2, "// Created by cgo - DO NOT EDIT\n\n")
    70  	fmt.Fprintf(fgo2, "package %s\n\n", p.PackageName)
    71  	fmt.Fprintf(fgo2, "import \"unsafe\"\n\n")
    72  	if !*gccgo && *importRuntimeCgo {
    73  		fmt.Fprintf(fgo2, "import _ \"runtime/cgo\"\n\n")
    74  	}
    75  	if *importSyscall {
    76  		fmt.Fprintf(fgo2, "import \"syscall\"\n\n")
    77  		fmt.Fprintf(fgo2, "var _ syscall.Errno\n")
    78  	}
    79  	fmt.Fprintf(fgo2, "func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }\n\n")
    80  
    81  	if !*gccgo {
    82  		fmt.Fprintf(fgo2, "//go:linkname _Cgo_always_false runtime.cgoAlwaysFalse\n")
    83  		fmt.Fprintf(fgo2, "var _Cgo_always_false bool\n")
    84  		fmt.Fprintf(fgo2, "//go:linkname _Cgo_use runtime.cgoUse\n")
    85  		fmt.Fprintf(fgo2, "func _Cgo_use(interface{})\n")
    86  	}
    87  
    88  	typedefNames := make([]string, 0, len(typedef))
    89  	for name := range typedef {
    90  		typedefNames = append(typedefNames, name)
    91  	}
    92  	sort.Strings(typedefNames)
    93  	for _, name := range typedefNames {
    94  		def := typedef[name]
    95  		fmt.Fprintf(fgo2, "type %s ", name)
    96  		conf.Fprint(fgo2, fset, def.Go)
    97  		fmt.Fprintf(fgo2, "\n\n")
    98  	}
    99  	if *gccgo {
   100  		fmt.Fprintf(fgo2, "type _Ctype_void byte\n")
   101  	} else {
   102  		fmt.Fprintf(fgo2, "type _Ctype_void [0]byte\n")
   103  	}
   104  
   105  	if *gccgo {
   106  		fmt.Fprint(fc, p.cPrologGccgo())
   107  	} else {
   108  		fmt.Fprint(fgo2, goProlog)
   109  	}
   110  
   111  	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, aname string, 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, aname string, 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, aname string, atype ast.Expr) {
   748  					fmt.Fprintf(fgcch, "\t%s r%d;", p.cgoType(atype).C, i)
   749  					if len(aname) > 0 {
   750  						fmt.Fprintf(fgcch, " /* %s */", aname)
   751  					}
   752  					fmt.Fprint(fgcch, "\n")
   753  				})
   754  			fmt.Fprintf(fgcch, "};\n")
   755  			gccResult = "struct " + exp.ExpName + "_return"
   756  		}
   757  
   758  		// Build the wrapper function compiled by gcc.
   759  		s := fmt.Sprintf("%s %s(", gccResult, exp.ExpName)
   760  		if fn.Recv != nil {
   761  			s += p.cgoType(fn.Recv.List[0].Type).C.String()
   762  			s += " recv"
   763  		}
   764  		forFieldList(fntype.Params,
   765  			func(i int, aname string, atype ast.Expr) {
   766  				if i > 0 || fn.Recv != nil {
   767  					s += ", "
   768  				}
   769  				s += fmt.Sprintf("%s p%d", p.cgoType(atype).C, i)
   770  			})
   771  		s += ")"
   772  
   773  		if len(exp.Doc) > 0 {
   774  			fmt.Fprintf(fgcch, "\n%s", exp.Doc)
   775  		}
   776  		fmt.Fprintf(fgcch, "\nextern %s;\n", s)
   777  
   778  		fmt.Fprintf(fgcc, "extern void _cgoexp%s_%s(void *, int);\n", cPrefix, exp.ExpName)
   779  		fmt.Fprintf(fgcc, "\n%s\n", s)
   780  		fmt.Fprintf(fgcc, "{\n")
   781  		fmt.Fprintf(fgcc, "\t_cgo_wait_runtime_init_done();\n")
   782  		fmt.Fprintf(fgcc, "\t%s %v a;\n", ctype, p.packedAttribute())
   783  		if gccResult != "void" && (len(fntype.Results.List) > 1 || len(fntype.Results.List[0].Names) > 1) {
   784  			fmt.Fprintf(fgcc, "\t%s r;\n", gccResult)
   785  		}
   786  		if fn.Recv != nil {
   787  			fmt.Fprintf(fgcc, "\ta.recv = recv;\n")
   788  		}
   789  		forFieldList(fntype.Params,
   790  			func(i int, aname string, atype ast.Expr) {
   791  				fmt.Fprintf(fgcc, "\ta.p%d = p%d;\n", i, i)
   792  			})
   793  		fmt.Fprintf(fgcc, "\tcrosscall2(_cgoexp%s_%s, &a, %d);\n", cPrefix, exp.ExpName, off)
   794  		if gccResult != "void" {
   795  			if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
   796  				fmt.Fprintf(fgcc, "\treturn a.r0;\n")
   797  			} else {
   798  				forFieldList(fntype.Results,
   799  					func(i int, aname string, atype ast.Expr) {
   800  						fmt.Fprintf(fgcc, "\tr.r%d = a.r%d;\n", i, i)
   801  					})
   802  				fmt.Fprintf(fgcc, "\treturn r;\n")
   803  			}
   804  		}
   805  		fmt.Fprintf(fgcc, "}\n")
   806  
   807  		// Build the wrapper function compiled by gc.
   808  		goname := exp.Func.Name.Name
   809  		if fn.Recv != nil {
   810  			goname = "_cgoexpwrap" + cPrefix + "_" + fn.Recv.List[0].Names[0].Name + "_" + goname
   811  		}
   812  		fmt.Fprintf(fgo2, "//go:cgo_export_dynamic %s\n", goname)
   813  		fmt.Fprintf(fgo2, "//go:linkname _cgoexp%s_%s _cgoexp%s_%s\n", cPrefix, exp.ExpName, cPrefix, exp.ExpName)
   814  		fmt.Fprintf(fgo2, "//go:cgo_export_static _cgoexp%s_%s\n", cPrefix, exp.ExpName)
   815  		fmt.Fprintf(fgo2, "//go:nosplit\n") // no split stack, so no use of m or g
   816  		fmt.Fprintf(fgo2, "//go:norace\n")  // must not have race detector calls inserted
   817  		fmt.Fprintf(fgo2, "func _cgoexp%s_%s(a unsafe.Pointer, n int32) {", cPrefix, exp.ExpName)
   818  		fmt.Fprintf(fgo2, "\tfn := %s\n", goname)
   819  		// The indirect here is converting from a Go function pointer to a C function pointer.
   820  		fmt.Fprintf(fgo2, "\t_cgo_runtime_cgocallback(**(**unsafe.Pointer)(unsafe.Pointer(&fn)), a, uintptr(n));\n")
   821  		fmt.Fprintf(fgo2, "}\n")
   822  
   823  		fmt.Fprintf(fm, "int _cgoexp%s_%s;\n", cPrefix, exp.ExpName)
   824  
   825  		// Calling a function with a receiver from C requires
   826  		// a Go wrapper function.
   827  		if fn.Recv != nil {
   828  			fmt.Fprintf(fgo2, "func %s(recv ", goname)
   829  			conf.Fprint(fgo2, fset, fn.Recv.List[0].Type)
   830  			forFieldList(fntype.Params,
   831  				func(i int, aname string, atype ast.Expr) {
   832  					fmt.Fprintf(fgo2, ", p%d ", i)
   833  					conf.Fprint(fgo2, fset, atype)
   834  				})
   835  			fmt.Fprintf(fgo2, ")")
   836  			if gccResult != "void" {
   837  				fmt.Fprint(fgo2, " (")
   838  				forFieldList(fntype.Results,
   839  					func(i int, aname string, atype ast.Expr) {
   840  						if i > 0 {
   841  							fmt.Fprint(fgo2, ", ")
   842  						}
   843  						conf.Fprint(fgo2, fset, atype)
   844  					})
   845  				fmt.Fprint(fgo2, ")")
   846  			}
   847  			fmt.Fprint(fgo2, " {\n")
   848  			fmt.Fprint(fgo2, "\t")
   849  			if gccResult != "void" {
   850  				fmt.Fprint(fgo2, "return ")
   851  			}
   852  			fmt.Fprintf(fgo2, "recv.%s(", exp.Func.Name)
   853  			forFieldList(fntype.Params,
   854  				func(i int, aname string, atype ast.Expr) {
   855  					if i > 0 {
   856  						fmt.Fprint(fgo2, ", ")
   857  					}
   858  					fmt.Fprintf(fgo2, "p%d", i)
   859  				})
   860  			fmt.Fprint(fgo2, ")\n")
   861  			fmt.Fprint(fgo2, "}\n")
   862  		}
   863  	}
   864  
   865  	fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
   866  }
   867  
   868  // Write out the C header allowing C code to call exported gccgo functions.
   869  func (p *Package) writeGccgoExports(fgo2, fm, fgcc, fgcch io.Writer) {
   870  	gccgoSymbolPrefix := p.gccgoSymbolPrefix()
   871  
   872  	p.writeExportHeader(fgcch)
   873  
   874  	fmt.Fprintf(fgcc, "/* Created by cgo - DO NOT EDIT. */\n")
   875  	fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n")
   876  
   877  	fmt.Fprintf(fgcc, "%s\n", gccgoExportFileProlog)
   878  
   879  	for _, exp := range p.ExpFunc {
   880  		fn := exp.Func
   881  		fntype := fn.Type
   882  
   883  		cdeclBuf := new(bytes.Buffer)
   884  		resultCount := 0
   885  		forFieldList(fntype.Results,
   886  			func(i int, aname string, atype ast.Expr) { resultCount++ })
   887  		switch resultCount {
   888  		case 0:
   889  			fmt.Fprintf(cdeclBuf, "void")
   890  		case 1:
   891  			forFieldList(fntype.Results,
   892  				func(i int, aname string, atype ast.Expr) {
   893  					t := p.cgoType(atype)
   894  					fmt.Fprintf(cdeclBuf, "%s", t.C)
   895  				})
   896  		default:
   897  			// Declare a result struct.
   898  			fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
   899  			fmt.Fprintf(fgcch, "struct %s_result {\n", exp.ExpName)
   900  			forFieldList(fntype.Results,
   901  				func(i int, aname string, atype ast.Expr) {
   902  					t := p.cgoType(atype)
   903  					fmt.Fprintf(fgcch, "\t%s r%d;", t.C, i)
   904  					if len(aname) > 0 {
   905  						fmt.Fprintf(fgcch, " /* %s */", aname)
   906  					}
   907  					fmt.Fprint(fgcch, "\n")
   908  				})
   909  			fmt.Fprintf(fgcch, "};\n")
   910  			fmt.Fprintf(cdeclBuf, "struct %s_result", exp.ExpName)
   911  		}
   912  
   913  		cRet := cdeclBuf.String()
   914  
   915  		cdeclBuf = new(bytes.Buffer)
   916  		fmt.Fprintf(cdeclBuf, "(")
   917  		if fn.Recv != nil {
   918  			fmt.Fprintf(cdeclBuf, "%s recv", p.cgoType(fn.Recv.List[0].Type).C.String())
   919  		}
   920  		// Function parameters.
   921  		forFieldList(fntype.Params,
   922  			func(i int, aname string, atype ast.Expr) {
   923  				if i > 0 || fn.Recv != nil {
   924  					fmt.Fprintf(cdeclBuf, ", ")
   925  				}
   926  				t := p.cgoType(atype)
   927  				fmt.Fprintf(cdeclBuf, "%s p%d", t.C, i)
   928  			})
   929  		fmt.Fprintf(cdeclBuf, ")")
   930  		cParams := cdeclBuf.String()
   931  
   932  		if len(exp.Doc) > 0 {
   933  			fmt.Fprintf(fgcch, "\n%s", exp.Doc)
   934  		}
   935  
   936  		// We need to use a name that will be exported by the
   937  		// Go code; otherwise gccgo will make it static and we
   938  		// will not be able to link against it from the C
   939  		// code.
   940  		goName := "Cgoexp_" + exp.ExpName
   941  		fmt.Fprintf(fgcch, `extern %s %s %s __asm__("%s.%s");`, cRet, goName, cParams, gccgoSymbolPrefix, goName)
   942  		fmt.Fprint(fgcch, "\n")
   943  
   944  		// Use a #define so that the C code that includes
   945  		// cgo_export.h will be able to refer to the Go
   946  		// function using the expected name.
   947  		fmt.Fprintf(fgcch, "#define %s %s\n", exp.ExpName, goName)
   948  
   949  		// Use a #undef in _cgo_export.c so that we ignore the
   950  		// #define from cgo_export.h, since here we are
   951  		// defining the real function.
   952  		fmt.Fprintf(fgcc, "#undef %s\n", exp.ExpName)
   953  
   954  		fmt.Fprint(fgcc, "\n")
   955  		fmt.Fprintf(fgcc, "%s %s %s {\n", cRet, exp.ExpName, cParams)
   956  		fmt.Fprintf(fgcc, "\tif(_cgo_wait_runtime_init_done)\n")
   957  		fmt.Fprintf(fgcc, "\t\t_cgo_wait_runtime_init_done();\n")
   958  		fmt.Fprint(fgcc, "\t")
   959  		if resultCount > 0 {
   960  			fmt.Fprint(fgcc, "return ")
   961  		}
   962  		fmt.Fprintf(fgcc, "%s(", goName)
   963  		if fn.Recv != nil {
   964  			fmt.Fprint(fgcc, "recv")
   965  		}
   966  		forFieldList(fntype.Params,
   967  			func(i int, aname string, atype ast.Expr) {
   968  				if i > 0 || fn.Recv != nil {
   969  					fmt.Fprintf(fgcc, ", ")
   970  				}
   971  				fmt.Fprintf(fgcc, "p%d", i)
   972  			})
   973  		fmt.Fprint(fgcc, ");\n")
   974  		fmt.Fprint(fgcc, "}\n")
   975  
   976  		// Dummy declaration for _cgo_main.c
   977  		fmt.Fprintf(fm, `char %s[1] __asm__("%s.%s");`, goName, gccgoSymbolPrefix, goName)
   978  		fmt.Fprint(fm, "\n")
   979  
   980  		// For gccgo we use a wrapper function in Go, in order
   981  		// to call CgocallBack and CgocallBackDone.
   982  
   983  		// This code uses printer.Fprint, not conf.Fprint,
   984  		// because we don't want //line comments in the middle
   985  		// of the function types.
   986  		fmt.Fprint(fgo2, "\n")
   987  		fmt.Fprintf(fgo2, "func %s(", goName)
   988  		if fn.Recv != nil {
   989  			fmt.Fprint(fgo2, "recv ")
   990  			printer.Fprint(fgo2, fset, fn.Recv.List[0].Type)
   991  		}
   992  		forFieldList(fntype.Params,
   993  			func(i int, aname string, atype ast.Expr) {
   994  				if i > 0 || fn.Recv != nil {
   995  					fmt.Fprintf(fgo2, ", ")
   996  				}
   997  				fmt.Fprintf(fgo2, "p%d ", i)
   998  				printer.Fprint(fgo2, fset, atype)
   999  			})
  1000  		fmt.Fprintf(fgo2, ")")
  1001  		if resultCount > 0 {
  1002  			fmt.Fprintf(fgo2, " (")
  1003  			forFieldList(fntype.Results,
  1004  				func(i int, aname string, atype ast.Expr) {
  1005  					if i > 0 {
  1006  						fmt.Fprint(fgo2, ", ")
  1007  					}
  1008  					printer.Fprint(fgo2, fset, atype)
  1009  				})
  1010  			fmt.Fprint(fgo2, ")")
  1011  		}
  1012  		fmt.Fprint(fgo2, " {\n")
  1013  		fmt.Fprint(fgo2, "\tsyscall.CgocallBack()\n")
  1014  		fmt.Fprint(fgo2, "\tdefer syscall.CgocallBackDone()\n")
  1015  		fmt.Fprint(fgo2, "\t")
  1016  		if resultCount > 0 {
  1017  			fmt.Fprint(fgo2, "return ")
  1018  		}
  1019  		if fn.Recv != nil {
  1020  			fmt.Fprint(fgo2, "recv.")
  1021  		}
  1022  		fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
  1023  		forFieldList(fntype.Params,
  1024  			func(i int, aname string, atype ast.Expr) {
  1025  				if i > 0 {
  1026  					fmt.Fprint(fgo2, ", ")
  1027  				}
  1028  				fmt.Fprintf(fgo2, "p%d", i)
  1029  			})
  1030  		fmt.Fprint(fgo2, ")\n")
  1031  		fmt.Fprint(fgo2, "}\n")
  1032  	}
  1033  
  1034  	fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
  1035  }
  1036  
  1037  // writeExportHeader writes out the start of the _cgo_export.h file.
  1038  func (p *Package) writeExportHeader(fgcch io.Writer) {
  1039  	fmt.Fprintf(fgcch, "/* Created by \"go tool cgo\" - DO NOT EDIT. */\n\n")
  1040  	pkg := *importPath
  1041  	if pkg == "" {
  1042  		pkg = p.PackagePath
  1043  	}
  1044  	fmt.Fprintf(fgcch, "/* package %s */\n\n", pkg)
  1045  
  1046  	fmt.Fprintf(fgcch, "/* Start of preamble from import \"C\" comments.  */\n\n")
  1047  	fmt.Fprintf(fgcch, "%s\n", p.Preamble)
  1048  	fmt.Fprintf(fgcch, "\n/* End of preamble from import \"C\" comments.  */\n\n")
  1049  
  1050  	fmt.Fprintf(fgcch, "%s\n", p.gccExportHeaderProlog())
  1051  }
  1052  
  1053  // Return the package prefix when using gccgo.
  1054  func (p *Package) gccgoSymbolPrefix() string {
  1055  	if !*gccgo {
  1056  		return ""
  1057  	}
  1058  
  1059  	clean := func(r rune) rune {
  1060  		switch {
  1061  		case 'A' <= r && r <= 'Z', 'a' <= r && r <= 'z',
  1062  			'0' <= r && r <= '9':
  1063  			return r
  1064  		}
  1065  		return '_'
  1066  	}
  1067  
  1068  	if *gccgopkgpath != "" {
  1069  		return strings.Map(clean, *gccgopkgpath)
  1070  	}
  1071  	if *gccgoprefix == "" && p.PackageName == "main" {
  1072  		return "main"
  1073  	}
  1074  	prefix := strings.Map(clean, *gccgoprefix)
  1075  	if prefix == "" {
  1076  		prefix = "go"
  1077  	}
  1078  	return prefix + "." + p.PackageName
  1079  }
  1080  
  1081  // Call a function for each entry in an ast.FieldList, passing the
  1082  // index into the list, the name if any, and the type.
  1083  func forFieldList(fl *ast.FieldList, fn func(int, string, ast.Expr)) {
  1084  	if fl == nil {
  1085  		return
  1086  	}
  1087  	i := 0
  1088  	for _, r := range fl.List {
  1089  		if r.Names == nil {
  1090  			fn(i, "", r.Type)
  1091  			i++
  1092  		} else {
  1093  			for _, n := range r.Names {
  1094  				fn(i, n.Name, r.Type)
  1095  				i++
  1096  			}
  1097  		}
  1098  	}
  1099  }
  1100  
  1101  func c(repr string, args ...interface{}) *TypeRepr {
  1102  	return &TypeRepr{repr, args}
  1103  }
  1104  
  1105  // Map predeclared Go types to Type.
  1106  var goTypes = map[string]*Type{
  1107  	"bool":       {Size: 1, Align: 1, C: c("GoUint8")},
  1108  	"byte":       {Size: 1, Align: 1, C: c("GoUint8")},
  1109  	"int":        {Size: 0, Align: 0, C: c("GoInt")},
  1110  	"uint":       {Size: 0, Align: 0, C: c("GoUint")},
  1111  	"rune":       {Size: 4, Align: 4, C: c("GoInt32")},
  1112  	"int8":       {Size: 1, Align: 1, C: c("GoInt8")},
  1113  	"uint8":      {Size: 1, Align: 1, C: c("GoUint8")},
  1114  	"int16":      {Size: 2, Align: 2, C: c("GoInt16")},
  1115  	"uint16":     {Size: 2, Align: 2, C: c("GoUint16")},
  1116  	"int32":      {Size: 4, Align: 4, C: c("GoInt32")},
  1117  	"uint32":     {Size: 4, Align: 4, C: c("GoUint32")},
  1118  	"int64":      {Size: 8, Align: 8, C: c("GoInt64")},
  1119  	"uint64":     {Size: 8, Align: 8, C: c("GoUint64")},
  1120  	"float32":    {Size: 4, Align: 4, C: c("GoFloat32")},
  1121  	"float64":    {Size: 8, Align: 8, C: c("GoFloat64")},
  1122  	"complex64":  {Size: 8, Align: 8, C: c("GoComplex64")},
  1123  	"complex128": {Size: 16, Align: 16, C: c("GoComplex128")},
  1124  }
  1125  
  1126  // Map an ast type to a Type.
  1127  func (p *Package) cgoType(e ast.Expr) *Type {
  1128  	switch t := e.(type) {
  1129  	case *ast.StarExpr:
  1130  		x := p.cgoType(t.X)
  1131  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("%s*", x.C)}
  1132  	case *ast.ArrayType:
  1133  		if t.Len == nil {
  1134  			// Slice: pointer, len, cap.
  1135  			return &Type{Size: p.PtrSize * 3, Align: p.PtrSize, C: c("GoSlice")}
  1136  		}
  1137  	case *ast.StructType:
  1138  		// TODO
  1139  	case *ast.FuncType:
  1140  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
  1141  	case *ast.InterfaceType:
  1142  		return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
  1143  	case *ast.MapType:
  1144  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoMap")}
  1145  	case *ast.ChanType:
  1146  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoChan")}
  1147  	case *ast.Ident:
  1148  		// Look up the type in the top level declarations.
  1149  		// TODO: Handle types defined within a function.
  1150  		for _, d := range p.Decl {
  1151  			gd, ok := d.(*ast.GenDecl)
  1152  			if !ok || gd.Tok != token.TYPE {
  1153  				continue
  1154  			}
  1155  			for _, spec := range gd.Specs {
  1156  				ts, ok := spec.(*ast.TypeSpec)
  1157  				if !ok {
  1158  					continue
  1159  				}
  1160  				if ts.Name.Name == t.Name {
  1161  					return p.cgoType(ts.Type)
  1162  				}
  1163  			}
  1164  		}
  1165  		if def := typedef[t.Name]; def != nil {
  1166  			return def
  1167  		}
  1168  		if t.Name == "uintptr" {
  1169  			return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoUintptr")}
  1170  		}
  1171  		if t.Name == "string" {
  1172  			// The string data is 1 pointer + 1 (pointer-sized) int.
  1173  			return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoString")}
  1174  		}
  1175  		if t.Name == "error" {
  1176  			return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
  1177  		}
  1178  		if r, ok := goTypes[t.Name]; ok {
  1179  			if r.Size == 0 { // int or uint
  1180  				rr := new(Type)
  1181  				*rr = *r
  1182  				rr.Size = p.IntSize
  1183  				rr.Align = p.IntSize
  1184  				r = rr
  1185  			}
  1186  			if r.Align > p.PtrSize {
  1187  				r.Align = p.PtrSize
  1188  			}
  1189  			return r
  1190  		}
  1191  		error_(e.Pos(), "unrecognized Go type %s", t.Name)
  1192  		return &Type{Size: 4, Align: 4, C: c("int")}
  1193  	case *ast.SelectorExpr:
  1194  		id, ok := t.X.(*ast.Ident)
  1195  		if ok && id.Name == "unsafe" && t.Sel.Name == "Pointer" {
  1196  			return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
  1197  		}
  1198  	}
  1199  	error_(e.Pos(), "Go type not supported in export: %s", gofmt(e))
  1200  	return &Type{Size: 4, Align: 4, C: c("int")}
  1201  }
  1202  
  1203  const gccProlog = `
  1204  /*
  1205    If x and y are not equal, the type will be invalid
  1206    (have a negative array count) and an inscrutable error will come
  1207    out of the compiler and hopefully mention "name".
  1208  */
  1209  #define __cgo_compile_assert_eq(x, y, name) typedef char name[(x-y)*(x-y)*-2+1];
  1210  
  1211  // Check at compile time that the sizes we use match our expectations.
  1212  #define __cgo_size_assert(t, n) __cgo_compile_assert_eq(sizeof(t), n, _cgo_sizeof_##t##_is_not_##n)
  1213  
  1214  __cgo_size_assert(char, 1)
  1215  __cgo_size_assert(short, 2)
  1216  __cgo_size_assert(int, 4)
  1217  typedef long long __cgo_long_long;
  1218  __cgo_size_assert(__cgo_long_long, 8)
  1219  __cgo_size_assert(float, 4)
  1220  __cgo_size_assert(double, 8)
  1221  
  1222  extern char* _cgo_topofstack(void);
  1223  
  1224  #include <errno.h>
  1225  #include <string.h>
  1226  `
  1227  
  1228  const builtinProlog = `
  1229  #include <stddef.h> /* for ptrdiff_t and size_t below */
  1230  
  1231  /* Define intgo when compiling with GCC.  */
  1232  typedef ptrdiff_t intgo;
  1233  
  1234  typedef struct { char *p; intgo n; } _GoString_;
  1235  typedef struct { char *p; intgo n; intgo c; } _GoBytes_;
  1236  _GoString_ GoString(char *p);
  1237  _GoString_ GoStringN(char *p, int l);
  1238  _GoBytes_ GoBytes(void *p, int n);
  1239  char *CString(_GoString_);
  1240  void *_CMalloc(size_t);
  1241  `
  1242  
  1243  const goProlog = `
  1244  //go:linkname _cgo_runtime_cgocall runtime.cgocall
  1245  func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
  1246  
  1247  //go:linkname _cgo_runtime_cmalloc runtime.cmalloc
  1248  func _cgo_runtime_cmalloc(uintptr) unsafe.Pointer
  1249  
  1250  //go:linkname _cgo_runtime_cgocallback runtime.cgocallback
  1251  func _cgo_runtime_cgocallback(unsafe.Pointer, unsafe.Pointer, uintptr)
  1252  `
  1253  
  1254  const goStringDef = `
  1255  //go:linkname _cgo_runtime_gostring runtime.gostring
  1256  func _cgo_runtime_gostring(*_Ctype_char) string
  1257  
  1258  func _Cfunc_GoString(p *_Ctype_char) string {
  1259  	return _cgo_runtime_gostring(p)
  1260  }
  1261  `
  1262  
  1263  const goStringNDef = `
  1264  //go:linkname _cgo_runtime_gostringn runtime.gostringn
  1265  func _cgo_runtime_gostringn(*_Ctype_char, int) string
  1266  
  1267  func _Cfunc_GoStringN(p *_Ctype_char, l _Ctype_int) string {
  1268  	return _cgo_runtime_gostringn(p, int(l))
  1269  }
  1270  `
  1271  
  1272  const goBytesDef = `
  1273  //go:linkname _cgo_runtime_gobytes runtime.gobytes
  1274  func _cgo_runtime_gobytes(unsafe.Pointer, int) []byte
  1275  
  1276  func _Cfunc_GoBytes(p unsafe.Pointer, l _Ctype_int) []byte {
  1277  	return _cgo_runtime_gobytes(p, int(l))
  1278  }
  1279  `
  1280  
  1281  const cStringDef = `
  1282  func _Cfunc_CString(s string) *_Ctype_char {
  1283  	p := _cgo_runtime_cmalloc(uintptr(len(s)+1))
  1284  	pp := (*[1<<30]byte)(p)
  1285  	copy(pp[:], s)
  1286  	pp[len(s)] = 0
  1287  	return (*_Ctype_char)(p)
  1288  }
  1289  `
  1290  
  1291  const cMallocDef = `
  1292  func _Cfunc__CMalloc(n _Ctype_size_t) unsafe.Pointer {
  1293  	return _cgo_runtime_cmalloc(uintptr(n))
  1294  }
  1295  `
  1296  
  1297  var builtinDefs = map[string]string{
  1298  	"GoString":  goStringDef,
  1299  	"GoStringN": goStringNDef,
  1300  	"GoBytes":   goBytesDef,
  1301  	"CString":   cStringDef,
  1302  	"_CMalloc":  cMallocDef,
  1303  }
  1304  
  1305  func (p *Package) cPrologGccgo() string {
  1306  	return strings.Replace(cPrologGccgo, "PREFIX", cPrefix, -1)
  1307  }
  1308  
  1309  const cPrologGccgo = `
  1310  #include <stdint.h>
  1311  #include <stdlib.h>
  1312  #include <string.h>
  1313  
  1314  typedef unsigned char byte;
  1315  typedef intptr_t intgo;
  1316  
  1317  struct __go_string {
  1318  	const unsigned char *__data;
  1319  	intgo __length;
  1320  };
  1321  
  1322  typedef struct __go_open_array {
  1323  	void* __values;
  1324  	intgo __count;
  1325  	intgo __capacity;
  1326  } Slice;
  1327  
  1328  struct __go_string __go_byte_array_to_string(const void* p, intgo len);
  1329  struct __go_open_array __go_string_to_byte_array (struct __go_string str);
  1330  
  1331  const char *_cgoPREFIX_Cfunc_CString(struct __go_string s) {
  1332  	char *p = malloc(s.__length+1);
  1333  	memmove(p, s.__data, s.__length);
  1334  	p[s.__length] = 0;
  1335  	return p;
  1336  }
  1337  
  1338  struct __go_string _cgoPREFIX_Cfunc_GoString(char *p) {
  1339  	intgo len = (p != NULL) ? strlen(p) : 0;
  1340  	return __go_byte_array_to_string(p, len);
  1341  }
  1342  
  1343  struct __go_string _cgoPREFIX_Cfunc_GoStringN(char *p, int32_t n) {
  1344  	return __go_byte_array_to_string(p, n);
  1345  }
  1346  
  1347  Slice _cgoPREFIX_Cfunc_GoBytes(char *p, int32_t n) {
  1348  	struct __go_string s = { (const unsigned char *)p, n };
  1349  	return __go_string_to_byte_array(s);
  1350  }
  1351  
  1352  extern void runtime_throw(const char *);
  1353  void *_cgoPREFIX_Cfunc__CMalloc(size_t n) {
  1354          void *p = malloc(n);
  1355          if(p == NULL && n == 0)
  1356                  p = malloc(1);
  1357          if(p == NULL)
  1358                  runtime_throw("runtime: C malloc failed");
  1359          return p;
  1360  }
  1361  `
  1362  
  1363  func (p *Package) gccExportHeaderProlog() string {
  1364  	return strings.Replace(gccExportHeaderProlog, "GOINTBITS", fmt.Sprint(8*p.IntSize), -1)
  1365  }
  1366  
  1367  const gccExportHeaderProlog = `
  1368  /* Start of boilerplate cgo prologue.  */
  1369  
  1370  #ifndef GO_CGO_PROLOGUE_H
  1371  #define GO_CGO_PROLOGUE_H
  1372  
  1373  typedef signed char GoInt8;
  1374  typedef unsigned char GoUint8;
  1375  typedef short GoInt16;
  1376  typedef unsigned short GoUint16;
  1377  typedef int GoInt32;
  1378  typedef unsigned int GoUint32;
  1379  typedef long long GoInt64;
  1380  typedef unsigned long long GoUint64;
  1381  typedef GoIntGOINTBITS GoInt;
  1382  typedef GoUintGOINTBITS GoUint;
  1383  typedef __SIZE_TYPE__ GoUintptr;
  1384  typedef float GoFloat32;
  1385  typedef double GoFloat64;
  1386  typedef __complex float GoComplex64;
  1387  typedef __complex double GoComplex128;
  1388  
  1389  /*
  1390    static assertion to make sure the file is being used on architecture
  1391    at least with matching size of GoInt.
  1392  */
  1393  typedef char _check_for_GOINTBITS_bit_pointer_matching_GoInt[sizeof(void*)==GOINTBITS/8 ? 1:-1];
  1394  
  1395  typedef struct { char *p; GoInt n; } GoString;
  1396  typedef void *GoMap;
  1397  typedef void *GoChan;
  1398  typedef struct { void *t; void *v; } GoInterface;
  1399  typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
  1400  
  1401  #endif
  1402  
  1403  /* End of boilerplate cgo prologue.  */
  1404  
  1405  #ifdef __cplusplus
  1406  extern "C" {
  1407  #endif
  1408  `
  1409  
  1410  // gccExportHeaderEpilog goes at the end of the generated header file.
  1411  const gccExportHeaderEpilog = `
  1412  #ifdef __cplusplus
  1413  }
  1414  #endif
  1415  `
  1416  
  1417  // gccgoExportFileProlog is written to the _cgo_export.c file when
  1418  // using gccgo.
  1419  // We use weak declarations, and test the addresses, so that this code
  1420  // works with older versions of gccgo.
  1421  const gccgoExportFileProlog = `
  1422  extern _Bool runtime_iscgo __attribute__ ((weak));
  1423  
  1424  static void GoInit(void) __attribute__ ((constructor));
  1425  static void GoInit(void) {
  1426  	if(&runtime_iscgo)
  1427  		runtime_iscgo = 1;
  1428  }
  1429  
  1430  extern void _cgo_wait_runtime_init_done() __attribute__ ((weak));
  1431  `