...
Run Format

Source file src/cmd/cgo/out.go

Documentation: cmd/cgo

     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  	"path/filepath"
    19  	"regexp"
    20  	"sort"
    21  	"strings"
    22  )
    23  
    24  var (
    25  	conf         = printer.Config{Mode: printer.SourcePos, Tabwidth: 8}
    26  	noSourceConf = printer.Config{Tabwidth: 8}
    27  )
    28  
    29  // writeDefs creates output files to be compiled by gc and gcc.
    30  func (p *Package) writeDefs() {
    31  	var fgo2, fc io.Writer
    32  	f := creat(*objDir + "_cgo_gotypes.go")
    33  	defer f.Close()
    34  	fgo2 = f
    35  	if *gccgo {
    36  		f := creat(*objDir + "_cgo_defun.c")
    37  		defer f.Close()
    38  		fc = f
    39  	}
    40  	fm := creat(*objDir + "_cgo_main.c")
    41  
    42  	var gccgoInit bytes.Buffer
    43  
    44  	fflg := creat(*objDir + "_cgo_flags")
    45  	for k, v := range p.CgoFlags {
    46  		fmt.Fprintf(fflg, "_CGO_%s=%s\n", k, strings.Join(v, " "))
    47  		if k == "LDFLAGS" && !*gccgo {
    48  			for _, arg := range v {
    49  				fmt.Fprintf(fgo2, "//go:cgo_ldflag %q\n", arg)
    50  			}
    51  		}
    52  	}
    53  	fflg.Close()
    54  
    55  	// Write C main file for using gcc to resolve imports.
    56  	fmt.Fprintf(fm, "int main() { return 0; }\n")
    57  	if *importRuntimeCgo {
    58  		fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*, int, __SIZE_TYPE__), void *a, int c, __SIZE_TYPE__ ctxt) { }\n")
    59  		fmt.Fprintf(fm, "__SIZE_TYPE__ _cgo_wait_runtime_init_done() { return 0; }\n")
    60  		fmt.Fprintf(fm, "void _cgo_release_context(__SIZE_TYPE__ ctxt) { }\n")
    61  		fmt.Fprintf(fm, "char* _cgo_topofstack(void) { return (char*)0; }\n")
    62  	} else {
    63  		// If we're not importing runtime/cgo, we *are* runtime/cgo,
    64  		// which provides these functions. We just need a prototype.
    65  		fmt.Fprintf(fm, "void crosscall2(void(*fn)(void*, int, __SIZE_TYPE__), void *a, int c, __SIZE_TYPE__ ctxt);\n")
    66  		fmt.Fprintf(fm, "__SIZE_TYPE__ _cgo_wait_runtime_init_done();\n")
    67  		fmt.Fprintf(fm, "void _cgo_release_context(__SIZE_TYPE__);\n")
    68  	}
    69  	fmt.Fprintf(fm, "void _cgo_allocate(void *a, int c) { }\n")
    70  	fmt.Fprintf(fm, "void _cgo_panic(void *a, int c) { }\n")
    71  	fmt.Fprintf(fm, "void _cgo_reginit(void) { }\n")
    72  
    73  	// Write second Go output: definitions of _C_xxx.
    74  	// In a separate file so that the import of "unsafe" does not
    75  	// pollute the original file.
    76  	fmt.Fprintf(fgo2, "// Code generated by cmd/cgo; DO NOT EDIT.\n\n")
    77  	fmt.Fprintf(fgo2, "package %s\n\n", p.PackageName)
    78  	fmt.Fprintf(fgo2, "import \"unsafe\"\n\n")
    79  	if !*gccgo && *importRuntimeCgo {
    80  		fmt.Fprintf(fgo2, "import _ \"runtime/cgo\"\n\n")
    81  	}
    82  	if *importSyscall {
    83  		fmt.Fprintf(fgo2, "import \"syscall\"\n\n")
    84  		fmt.Fprintf(fgo2, "var _ syscall.Errno\n")
    85  	}
    86  	fmt.Fprintf(fgo2, "func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }\n\n")
    87  
    88  	if !*gccgo {
    89  		fmt.Fprintf(fgo2, "//go:linkname _Cgo_always_false runtime.cgoAlwaysFalse\n")
    90  		fmt.Fprintf(fgo2, "var _Cgo_always_false bool\n")
    91  		fmt.Fprintf(fgo2, "//go:linkname _Cgo_use runtime.cgoUse\n")
    92  		fmt.Fprintf(fgo2, "func _Cgo_use(interface{})\n")
    93  	}
    94  
    95  	typedefNames := make([]string, 0, len(typedef))
    96  	for name := range typedef {
    97  		typedefNames = append(typedefNames, name)
    98  	}
    99  	sort.Strings(typedefNames)
   100  	for _, name := range typedefNames {
   101  		def := typedef[name]
   102  		fmt.Fprintf(fgo2, "type %s ", name)
   103  		// We don't have source info for these types, so write them out without source info.
   104  		// Otherwise types would look like:
   105  		//
   106  		// type _Ctype_struct_cb struct {
   107  		// //line :1
   108  		//        on_test *[0]byte
   109  		// //line :1
   110  		// }
   111  		//
   112  		// Which is not useful. Moreover we never override source info,
   113  		// so subsequent source code uses the same source info.
   114  		// Moreover, empty file name makes compile emit no source debug info at all.
   115  		var buf bytes.Buffer
   116  		noSourceConf.Fprint(&buf, fset, def.Go)
   117  		if bytes.HasPrefix(buf.Bytes(), []byte("_Ctype_")) {
   118  			// This typedef is of the form `typedef a b` and should be an alias.
   119  			fmt.Fprintf(fgo2, "= ")
   120  		}
   121  		fmt.Fprintf(fgo2, "%s", buf.Bytes())
   122  		fmt.Fprintf(fgo2, "\n\n")
   123  	}
   124  	if *gccgo {
   125  		fmt.Fprintf(fgo2, "type _Ctype_void byte\n")
   126  	} else {
   127  		fmt.Fprintf(fgo2, "type _Ctype_void [0]byte\n")
   128  	}
   129  
   130  	if *gccgo {
   131  		fmt.Fprint(fgo2, gccgoGoProlog)
   132  		fmt.Fprint(fc, p.cPrologGccgo())
   133  	} else {
   134  		fmt.Fprint(fgo2, goProlog)
   135  	}
   136  
   137  	if fc != nil {
   138  		fmt.Fprintf(fc, "#line 1 \"cgo-generated-wrappers\"\n")
   139  	}
   140  	if fm != nil {
   141  		fmt.Fprintf(fm, "#line 1 \"cgo-generated-wrappers\"\n")
   142  	}
   143  
   144  	gccgoSymbolPrefix := p.gccgoSymbolPrefix()
   145  
   146  	cVars := make(map[string]bool)
   147  	for _, key := range nameKeys(p.Name) {
   148  		n := p.Name[key]
   149  		if !n.IsVar() {
   150  			continue
   151  		}
   152  
   153  		if !cVars[n.C] {
   154  			if *gccgo {
   155  				fmt.Fprintf(fc, "extern byte *%s;\n", n.C)
   156  			} else {
   157  				fmt.Fprintf(fm, "extern char %s[];\n", n.C)
   158  				fmt.Fprintf(fm, "void *_cgohack_%s = %s;\n\n", n.C, n.C)
   159  				fmt.Fprintf(fgo2, "//go:linkname __cgo_%s %s\n", n.C, n.C)
   160  				fmt.Fprintf(fgo2, "//go:cgo_import_static %s\n", n.C)
   161  				fmt.Fprintf(fgo2, "var __cgo_%s byte\n", n.C)
   162  			}
   163  			cVars[n.C] = true
   164  		}
   165  
   166  		var node ast.Node
   167  		if n.Kind == "var" {
   168  			node = &ast.StarExpr{X: n.Type.Go}
   169  		} else if n.Kind == "fpvar" {
   170  			node = n.Type.Go
   171  		} else {
   172  			panic(fmt.Errorf("invalid var kind %q", n.Kind))
   173  		}
   174  		if *gccgo {
   175  			fmt.Fprintf(fc, `extern void *%s __asm__("%s.%s");`, n.Mangle, gccgoSymbolPrefix, n.Mangle)
   176  			fmt.Fprintf(&gccgoInit, "\t%s = &%s;\n", n.Mangle, n.C)
   177  			fmt.Fprintf(fc, "\n")
   178  		}
   179  
   180  		fmt.Fprintf(fgo2, "var %s ", n.Mangle)
   181  		conf.Fprint(fgo2, fset, node)
   182  		if !*gccgo {
   183  			fmt.Fprintf(fgo2, " = (")
   184  			conf.Fprint(fgo2, fset, node)
   185  			fmt.Fprintf(fgo2, ")(unsafe.Pointer(&__cgo_%s))", n.C)
   186  		}
   187  		fmt.Fprintf(fgo2, "\n")
   188  	}
   189  	if *gccgo {
   190  		fmt.Fprintf(fc, "\n")
   191  	}
   192  
   193  	for _, key := range nameKeys(p.Name) {
   194  		n := p.Name[key]
   195  		if n.Const != "" {
   196  			fmt.Fprintf(fgo2, "const %s = %s\n", n.Mangle, n.Const)
   197  		}
   198  	}
   199  	fmt.Fprintf(fgo2, "\n")
   200  
   201  	callsMalloc := false
   202  	for _, key := range nameKeys(p.Name) {
   203  		n := p.Name[key]
   204  		if n.FuncType != nil {
   205  			p.writeDefsFunc(fgo2, n, &callsMalloc)
   206  		}
   207  	}
   208  
   209  	fgcc := creat(*objDir + "_cgo_export.c")
   210  	fgcch := creat(*objDir + "_cgo_export.h")
   211  	if *gccgo {
   212  		p.writeGccgoExports(fgo2, fm, fgcc, fgcch)
   213  	} else {
   214  		p.writeExports(fgo2, fm, fgcc, fgcch)
   215  	}
   216  
   217  	if callsMalloc && !*gccgo {
   218  		fmt.Fprint(fgo2, strings.Replace(cMallocDefGo, "PREFIX", cPrefix, -1))
   219  		fmt.Fprint(fgcc, strings.Replace(strings.Replace(cMallocDefC, "PREFIX", cPrefix, -1), "PACKED", p.packedAttribute(), -1))
   220  	}
   221  
   222  	if err := fgcc.Close(); err != nil {
   223  		fatalf("%s", err)
   224  	}
   225  	if err := fgcch.Close(); err != nil {
   226  		fatalf("%s", err)
   227  	}
   228  
   229  	if *exportHeader != "" && len(p.ExpFunc) > 0 {
   230  		fexp := creat(*exportHeader)
   231  		fgcch, err := os.Open(*objDir + "_cgo_export.h")
   232  		if err != nil {
   233  			fatalf("%s", err)
   234  		}
   235  		_, err = io.Copy(fexp, fgcch)
   236  		if err != nil {
   237  			fatalf("%s", err)
   238  		}
   239  		if err = fexp.Close(); err != nil {
   240  			fatalf("%s", err)
   241  		}
   242  	}
   243  
   244  	init := gccgoInit.String()
   245  	if init != "" {
   246  		fmt.Fprintln(fc, "static void init(void) __attribute__ ((constructor));")
   247  		fmt.Fprintln(fc, "static void init(void) {")
   248  		fmt.Fprint(fc, init)
   249  		fmt.Fprintln(fc, "}")
   250  	}
   251  }
   252  
   253  func dynimport(obj string) {
   254  	stdout := os.Stdout
   255  	if *dynout != "" {
   256  		f, err := os.Create(*dynout)
   257  		if err != nil {
   258  			fatalf("%s", err)
   259  		}
   260  		stdout = f
   261  	}
   262  
   263  	fmt.Fprintf(stdout, "package %s\n", *dynpackage)
   264  
   265  	if f, err := elf.Open(obj); err == nil {
   266  		if *dynlinker {
   267  			// Emit the cgo_dynamic_linker line.
   268  			if sec := f.Section(".interp"); sec != nil {
   269  				if data, err := sec.Data(); err == nil && len(data) > 1 {
   270  					// skip trailing \0 in data
   271  					fmt.Fprintf(stdout, "//go:cgo_dynamic_linker %q\n", string(data[:len(data)-1]))
   272  				}
   273  			}
   274  		}
   275  		sym, _ := f.ImportedSymbols()
   276  		for _, s := range sym {
   277  			targ := s.Name
   278  			if s.Version != "" {
   279  				targ += "#" + s.Version
   280  			}
   281  			fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", s.Name, targ, s.Library)
   282  		}
   283  		lib, _ := f.ImportedLibraries()
   284  		for _, l := range lib {
   285  			fmt.Fprintf(stdout, "//go:cgo_import_dynamic _ _ %q\n", l)
   286  		}
   287  		return
   288  	}
   289  
   290  	if f, err := macho.Open(obj); err == nil {
   291  		sym, _ := f.ImportedSymbols()
   292  		for _, s := range sym {
   293  			if len(s) > 0 && s[0] == '_' {
   294  				s = s[1:]
   295  			}
   296  			fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", s, s, "")
   297  		}
   298  		lib, _ := f.ImportedLibraries()
   299  		for _, l := range lib {
   300  			fmt.Fprintf(stdout, "//go:cgo_import_dynamic _ _ %q\n", l)
   301  		}
   302  		return
   303  	}
   304  
   305  	if f, err := pe.Open(obj); err == nil {
   306  		sym, _ := f.ImportedSymbols()
   307  		for _, s := range sym {
   308  			ss := strings.Split(s, ":")
   309  			name := strings.Split(ss[0], "@")[0]
   310  			fmt.Fprintf(stdout, "//go:cgo_import_dynamic %s %s %q\n", name, ss[0], strings.ToLower(ss[1]))
   311  		}
   312  		return
   313  	}
   314  
   315  	fatalf("cannot parse %s as ELF, Mach-O or PE", obj)
   316  }
   317  
   318  // Construct a gcc struct matching the gc argument frame.
   319  // Assumes that in gcc, char is 1 byte, short 2 bytes, int 4 bytes, long long 8 bytes.
   320  // These assumptions are checked by the gccProlog.
   321  // Also assumes that gc convention is to word-align the
   322  // input and output parameters.
   323  func (p *Package) structType(n *Name) (string, int64) {
   324  	var buf bytes.Buffer
   325  	fmt.Fprint(&buf, "struct {\n")
   326  	off := int64(0)
   327  	for i, t := range n.FuncType.Params {
   328  		if off%t.Align != 0 {
   329  			pad := t.Align - off%t.Align
   330  			fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
   331  			off += pad
   332  		}
   333  		c := t.Typedef
   334  		if c == "" {
   335  			c = t.C.String()
   336  		}
   337  		fmt.Fprintf(&buf, "\t\t%s p%d;\n", c, i)
   338  		off += t.Size
   339  	}
   340  	if off%p.PtrSize != 0 {
   341  		pad := p.PtrSize - off%p.PtrSize
   342  		fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
   343  		off += pad
   344  	}
   345  	if t := n.FuncType.Result; t != nil {
   346  		if off%t.Align != 0 {
   347  			pad := t.Align - off%t.Align
   348  			fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
   349  			off += pad
   350  		}
   351  		fmt.Fprintf(&buf, "\t\t%s r;\n", t.C)
   352  		off += t.Size
   353  	}
   354  	if off%p.PtrSize != 0 {
   355  		pad := p.PtrSize - off%p.PtrSize
   356  		fmt.Fprintf(&buf, "\t\tchar __pad%d[%d];\n", off, pad)
   357  		off += pad
   358  	}
   359  	if off == 0 {
   360  		fmt.Fprintf(&buf, "\t\tchar unused;\n") // avoid empty struct
   361  	}
   362  	fmt.Fprintf(&buf, "\t}")
   363  	return buf.String(), off
   364  }
   365  
   366  func (p *Package) writeDefsFunc(fgo2 io.Writer, n *Name, callsMalloc *bool) {
   367  	name := n.Go
   368  	gtype := n.FuncType.Go
   369  	void := gtype.Results == nil || len(gtype.Results.List) == 0
   370  	if n.AddError {
   371  		// Add "error" to return type list.
   372  		// Type list is known to be 0 or 1 element - it's a C function.
   373  		err := &ast.Field{Type: ast.NewIdent("error")}
   374  		l := gtype.Results.List
   375  		if len(l) == 0 {
   376  			l = []*ast.Field{err}
   377  		} else {
   378  			l = []*ast.Field{l[0], err}
   379  		}
   380  		t := new(ast.FuncType)
   381  		*t = *gtype
   382  		t.Results = &ast.FieldList{List: l}
   383  		gtype = t
   384  	}
   385  
   386  	// Go func declaration.
   387  	d := &ast.FuncDecl{
   388  		Name: ast.NewIdent(n.Mangle),
   389  		Type: gtype,
   390  	}
   391  
   392  	// Builtins defined in the C prolog.
   393  	inProlog := builtinDefs[name] != ""
   394  	cname := fmt.Sprintf("_cgo%s%s", cPrefix, n.Mangle)
   395  	paramnames := []string(nil)
   396  	if d.Type.Params != nil {
   397  		for i, param := range d.Type.Params.List {
   398  			paramName := fmt.Sprintf("p%d", i)
   399  			param.Names = []*ast.Ident{ast.NewIdent(paramName)}
   400  			paramnames = append(paramnames, paramName)
   401  		}
   402  	}
   403  
   404  	if *gccgo {
   405  		// Gccgo style hooks.
   406  		fmt.Fprint(fgo2, "\n")
   407  		conf.Fprint(fgo2, fset, d)
   408  		fmt.Fprint(fgo2, " {\n")
   409  		if !inProlog {
   410  			fmt.Fprint(fgo2, "\tdefer syscall.CgocallDone()\n")
   411  			fmt.Fprint(fgo2, "\tsyscall.Cgocall()\n")
   412  		}
   413  		if n.AddError {
   414  			fmt.Fprint(fgo2, "\tsyscall.SetErrno(0)\n")
   415  		}
   416  		fmt.Fprint(fgo2, "\t")
   417  		if !void {
   418  			fmt.Fprint(fgo2, "r := ")
   419  		}
   420  		fmt.Fprintf(fgo2, "%s(%s)\n", cname, strings.Join(paramnames, ", "))
   421  
   422  		if n.AddError {
   423  			fmt.Fprint(fgo2, "\te := syscall.GetErrno()\n")
   424  			fmt.Fprint(fgo2, "\tif e != 0 {\n")
   425  			fmt.Fprint(fgo2, "\t\treturn ")
   426  			if !void {
   427  				fmt.Fprint(fgo2, "r, ")
   428  			}
   429  			fmt.Fprint(fgo2, "e\n")
   430  			fmt.Fprint(fgo2, "\t}\n")
   431  			fmt.Fprint(fgo2, "\treturn ")
   432  			if !void {
   433  				fmt.Fprint(fgo2, "r, ")
   434  			}
   435  			fmt.Fprint(fgo2, "nil\n")
   436  		} else if !void {
   437  			fmt.Fprint(fgo2, "\treturn r\n")
   438  		}
   439  
   440  		fmt.Fprint(fgo2, "}\n")
   441  
   442  		// declare the C function.
   443  		fmt.Fprintf(fgo2, "//extern %s\n", cname)
   444  		d.Name = ast.NewIdent(cname)
   445  		if n.AddError {
   446  			l := d.Type.Results.List
   447  			d.Type.Results.List = l[:len(l)-1]
   448  		}
   449  		conf.Fprint(fgo2, fset, d)
   450  		fmt.Fprint(fgo2, "\n")
   451  
   452  		return
   453  	}
   454  
   455  	if inProlog {
   456  		fmt.Fprint(fgo2, builtinDefs[name])
   457  		if strings.Contains(builtinDefs[name], "_cgo_cmalloc") {
   458  			*callsMalloc = true
   459  		}
   460  		return
   461  	}
   462  
   463  	// Wrapper calls into gcc, passing a pointer to the argument frame.
   464  	fmt.Fprintf(fgo2, "//go:cgo_import_static %s\n", cname)
   465  	fmt.Fprintf(fgo2, "//go:linkname __cgofn_%s %s\n", cname, cname)
   466  	fmt.Fprintf(fgo2, "var __cgofn_%s byte\n", cname)
   467  	fmt.Fprintf(fgo2, "var %s = unsafe.Pointer(&__cgofn_%s)\n", cname, cname)
   468  
   469  	nret := 0
   470  	if !void {
   471  		d.Type.Results.List[0].Names = []*ast.Ident{ast.NewIdent("r1")}
   472  		nret = 1
   473  	}
   474  	if n.AddError {
   475  		d.Type.Results.List[nret].Names = []*ast.Ident{ast.NewIdent("r2")}
   476  	}
   477  
   478  	fmt.Fprint(fgo2, "\n")
   479  	fmt.Fprint(fgo2, "//go:cgo_unsafe_args\n")
   480  	conf.Fprint(fgo2, fset, d)
   481  	fmt.Fprint(fgo2, " {\n")
   482  
   483  	// NOTE: Using uintptr to hide from escape analysis.
   484  	arg := "0"
   485  	if len(paramnames) > 0 {
   486  		arg = "uintptr(unsafe.Pointer(&p0))"
   487  	} else if !void {
   488  		arg = "uintptr(unsafe.Pointer(&r1))"
   489  	}
   490  
   491  	prefix := ""
   492  	if n.AddError {
   493  		prefix = "errno := "
   494  	}
   495  	fmt.Fprintf(fgo2, "\t%s_cgo_runtime_cgocall(%s, %s)\n", prefix, cname, arg)
   496  	if n.AddError {
   497  		fmt.Fprintf(fgo2, "\tif errno != 0 { r2 = syscall.Errno(errno) }\n")
   498  	}
   499  	fmt.Fprintf(fgo2, "\tif _Cgo_always_false {\n")
   500  	if d.Type.Params != nil {
   501  		for i := range d.Type.Params.List {
   502  			fmt.Fprintf(fgo2, "\t\t_Cgo_use(p%d)\n", i)
   503  		}
   504  	}
   505  	fmt.Fprintf(fgo2, "\t}\n")
   506  	fmt.Fprintf(fgo2, "\treturn\n")
   507  	fmt.Fprintf(fgo2, "}\n")
   508  }
   509  
   510  // writeOutput creates stubs for a specific source file to be compiled by gc
   511  func (p *Package) writeOutput(f *File, srcfile string) {
   512  	base := srcfile
   513  	if strings.HasSuffix(base, ".go") {
   514  		base = base[0 : len(base)-3]
   515  	}
   516  	base = filepath.Base(base)
   517  	fgo1 := creat(*objDir + base + ".cgo1.go")
   518  	fgcc := creat(*objDir + base + ".cgo2.c")
   519  
   520  	p.GoFiles = append(p.GoFiles, base+".cgo1.go")
   521  	p.GccFiles = append(p.GccFiles, base+".cgo2.c")
   522  
   523  	// Write Go output: Go input with rewrites of C.xxx to _C_xxx.
   524  	fmt.Fprintf(fgo1, "// Code generated by cmd/cgo; DO NOT EDIT.\n\n")
   525  	fmt.Fprintf(fgo1, "//line %s:1:1\n", srcfile)
   526  	fgo1.Write(f.Edit.Bytes())
   527  
   528  	// While we process the vars and funcs, also write gcc output.
   529  	// Gcc output starts with the preamble.
   530  	fmt.Fprintf(fgcc, "%s\n", builtinProlog)
   531  	fmt.Fprintf(fgcc, "%s\n", f.Preamble)
   532  	fmt.Fprintf(fgcc, "%s\n", gccProlog)
   533  	fmt.Fprintf(fgcc, "%s\n", tsanProlog)
   534  	fmt.Fprintf(fgcc, "%s\n", msanProlog)
   535  
   536  	for _, key := range nameKeys(f.Name) {
   537  		n := f.Name[key]
   538  		if n.FuncType != nil {
   539  			p.writeOutputFunc(fgcc, n)
   540  		}
   541  	}
   542  
   543  	fgo1.Close()
   544  	fgcc.Close()
   545  }
   546  
   547  // fixGo converts the internal Name.Go field into the name we should show
   548  // to users in error messages. There's only one for now: on input we rewrite
   549  // C.malloc into C._CMalloc, so change it back here.
   550  func fixGo(name string) string {
   551  	if name == "_CMalloc" {
   552  		return "malloc"
   553  	}
   554  	return name
   555  }
   556  
   557  var isBuiltin = map[string]bool{
   558  	"_Cfunc_CString":   true,
   559  	"_Cfunc_CBytes":    true,
   560  	"_Cfunc_GoString":  true,
   561  	"_Cfunc_GoStringN": true,
   562  	"_Cfunc_GoBytes":   true,
   563  	"_Cfunc__CMalloc":  true,
   564  }
   565  
   566  func (p *Package) writeOutputFunc(fgcc *os.File, n *Name) {
   567  	name := n.Mangle
   568  	if isBuiltin[name] || p.Written[name] {
   569  		// The builtins are already defined in the C prolog, and we don't
   570  		// want to duplicate function definitions we've already done.
   571  		return
   572  	}
   573  	p.Written[name] = true
   574  
   575  	if *gccgo {
   576  		p.writeGccgoOutputFunc(fgcc, n)
   577  		return
   578  	}
   579  
   580  	ctype, _ := p.structType(n)
   581  
   582  	// Gcc wrapper unpacks the C argument struct
   583  	// and calls the actual C function.
   584  	fmt.Fprintf(fgcc, "CGO_NO_SANITIZE_THREAD\n")
   585  	if n.AddError {
   586  		fmt.Fprintf(fgcc, "int\n")
   587  	} else {
   588  		fmt.Fprintf(fgcc, "void\n")
   589  	}
   590  	fmt.Fprintf(fgcc, "_cgo%s%s(void *v)\n", cPrefix, n.Mangle)
   591  	fmt.Fprintf(fgcc, "{\n")
   592  	if n.AddError {
   593  		fmt.Fprintf(fgcc, "\tint _cgo_errno;\n")
   594  	}
   595  	// We're trying to write a gcc struct that matches gc's layout.
   596  	// Use packed attribute to force no padding in this struct in case
   597  	// gcc has different packing requirements.
   598  	fmt.Fprintf(fgcc, "\t%s %v *_cgo_a = v;\n", ctype, p.packedAttribute())
   599  	if n.FuncType.Result != nil {
   600  		// Save the stack top for use below.
   601  		fmt.Fprintf(fgcc, "\tchar *_cgo_stktop = _cgo_topofstack();\n")
   602  	}
   603  	tr := n.FuncType.Result
   604  	if tr != nil {
   605  		fmt.Fprintf(fgcc, "\t__typeof__(_cgo_a->r) _cgo_r;\n")
   606  	}
   607  	fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
   608  	if n.AddError {
   609  		fmt.Fprintf(fgcc, "\terrno = 0;\n")
   610  	}
   611  	fmt.Fprintf(fgcc, "\t")
   612  	if tr != nil {
   613  		fmt.Fprintf(fgcc, "_cgo_r = ")
   614  		if c := tr.C.String(); c[len(c)-1] == '*' {
   615  			fmt.Fprint(fgcc, "(__typeof__(_cgo_a->r)) ")
   616  		}
   617  	}
   618  	if n.Kind == "macro" {
   619  		fmt.Fprintf(fgcc, "%s;\n", n.C)
   620  	} else {
   621  		fmt.Fprintf(fgcc, "%s(", n.C)
   622  		for i := range n.FuncType.Params {
   623  			if i > 0 {
   624  				fmt.Fprintf(fgcc, ", ")
   625  			}
   626  			fmt.Fprintf(fgcc, "_cgo_a->p%d", i)
   627  		}
   628  		fmt.Fprintf(fgcc, ");\n")
   629  	}
   630  	if n.AddError {
   631  		fmt.Fprintf(fgcc, "\t_cgo_errno = errno;\n")
   632  	}
   633  	fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
   634  	if n.FuncType.Result != nil {
   635  		// The cgo call may have caused a stack copy (via a callback).
   636  		// Adjust the return value pointer appropriately.
   637  		fmt.Fprintf(fgcc, "\t_cgo_a = (void*)((char*)_cgo_a + (_cgo_topofstack() - _cgo_stktop));\n")
   638  		// Save the return value.
   639  		fmt.Fprintf(fgcc, "\t_cgo_a->r = _cgo_r;\n")
   640  		// The return value is on the Go stack. If we are using msan,
   641  		// and if the C value is partially or completely uninitialized,
   642  		// the assignment will mark the Go stack as uninitialized.
   643  		// The Go compiler does not update msan for changes to the
   644  		// stack. It is possible that the stack will remain
   645  		// uninitialized, and then later be used in a way that is
   646  		// visible to msan, possibly leading to a false positive.
   647  		// Mark the stack space as written, to avoid this problem.
   648  		// See issue 26209.
   649  		fmt.Fprintf(fgcc, "\t_cgo_msan_write(&_cgo_a->r, sizeof(_cgo_a->r));\n")
   650  	}
   651  	if n.AddError {
   652  		fmt.Fprintf(fgcc, "\treturn _cgo_errno;\n")
   653  	}
   654  	fmt.Fprintf(fgcc, "}\n")
   655  	fmt.Fprintf(fgcc, "\n")
   656  }
   657  
   658  // Write out a wrapper for a function when using gccgo. This is a
   659  // simple wrapper that just calls the real function. We only need a
   660  // wrapper to support static functions in the prologue--without a
   661  // wrapper, we can't refer to the function, since the reference is in
   662  // a different file.
   663  func (p *Package) writeGccgoOutputFunc(fgcc *os.File, n *Name) {
   664  	fmt.Fprintf(fgcc, "CGO_NO_SANITIZE_THREAD\n")
   665  	if t := n.FuncType.Result; t != nil {
   666  		fmt.Fprintf(fgcc, "%s\n", t.C.String())
   667  	} else {
   668  		fmt.Fprintf(fgcc, "void\n")
   669  	}
   670  	fmt.Fprintf(fgcc, "_cgo%s%s(", cPrefix, n.Mangle)
   671  	for i, t := range n.FuncType.Params {
   672  		if i > 0 {
   673  			fmt.Fprintf(fgcc, ", ")
   674  		}
   675  		c := t.Typedef
   676  		if c == "" {
   677  			c = t.C.String()
   678  		}
   679  		fmt.Fprintf(fgcc, "%s p%d", c, i)
   680  	}
   681  	fmt.Fprintf(fgcc, ")\n")
   682  	fmt.Fprintf(fgcc, "{\n")
   683  	if t := n.FuncType.Result; t != nil {
   684  		fmt.Fprintf(fgcc, "\t%s _cgo_r;\n", t.C.String())
   685  	}
   686  	fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
   687  	fmt.Fprintf(fgcc, "\t")
   688  	if t := n.FuncType.Result; t != nil {
   689  		fmt.Fprintf(fgcc, "_cgo_r = ")
   690  		// Cast to void* to avoid warnings due to omitted qualifiers.
   691  		if c := t.C.String(); c[len(c)-1] == '*' {
   692  			fmt.Fprintf(fgcc, "(void*)")
   693  		}
   694  	}
   695  	if n.Kind == "macro" {
   696  		fmt.Fprintf(fgcc, "%s;\n", n.C)
   697  	} else {
   698  		fmt.Fprintf(fgcc, "%s(", n.C)
   699  		for i := range n.FuncType.Params {
   700  			if i > 0 {
   701  				fmt.Fprintf(fgcc, ", ")
   702  			}
   703  			fmt.Fprintf(fgcc, "p%d", i)
   704  		}
   705  		fmt.Fprintf(fgcc, ");\n")
   706  	}
   707  	fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
   708  	if t := n.FuncType.Result; t != nil {
   709  		fmt.Fprintf(fgcc, "\treturn ")
   710  		// Cast to void* to avoid warnings due to omitted qualifiers
   711  		// and explicit incompatible struct types.
   712  		if c := t.C.String(); c[len(c)-1] == '*' {
   713  			fmt.Fprintf(fgcc, "(void*)")
   714  		}
   715  		fmt.Fprintf(fgcc, "_cgo_r;\n")
   716  	}
   717  	fmt.Fprintf(fgcc, "}\n")
   718  	fmt.Fprintf(fgcc, "\n")
   719  }
   720  
   721  // packedAttribute returns host compiler struct attribute that will be
   722  // used to match gc's struct layout. For example, on 386 Windows,
   723  // gcc wants to 8-align int64s, but gc does not.
   724  // Use __gcc_struct__ to work around https://gcc.gnu.org/PR52991 on x86,
   725  // and https://golang.org/issue/5603.
   726  func (p *Package) packedAttribute() string {
   727  	s := "__attribute__((__packed__"
   728  	if !p.GccIsClang && (goarch == "amd64" || goarch == "386") {
   729  		s += ", __gcc_struct__"
   730  	}
   731  	return s + "))"
   732  }
   733  
   734  // Write out the various stubs we need to support functions exported
   735  // from Go so that they are callable from C.
   736  func (p *Package) writeExports(fgo2, fm, fgcc, fgcch io.Writer) {
   737  	p.writeExportHeader(fgcch)
   738  
   739  	fmt.Fprintf(fgcc, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
   740  	fmt.Fprintf(fgcc, "#include <stdlib.h>\n")
   741  	fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n\n")
   742  
   743  	fmt.Fprintf(fgcc, "extern void crosscall2(void (*fn)(void *, int, __SIZE_TYPE__), void *, int, __SIZE_TYPE__);\n")
   744  	fmt.Fprintf(fgcc, "extern __SIZE_TYPE__ _cgo_wait_runtime_init_done();\n")
   745  	fmt.Fprintf(fgcc, "extern void _cgo_release_context(__SIZE_TYPE__);\n\n")
   746  	fmt.Fprintf(fgcc, "extern char* _cgo_topofstack(void);")
   747  	fmt.Fprintf(fgcc, "%s\n", tsanProlog)
   748  	fmt.Fprintf(fgcc, "%s\n", msanProlog)
   749  
   750  	for _, exp := range p.ExpFunc {
   751  		fn := exp.Func
   752  
   753  		// Construct a gcc struct matching the gc argument and
   754  		// result frame. The gcc struct will be compiled with
   755  		// __attribute__((packed)) so all padding must be accounted
   756  		// for explicitly.
   757  		ctype := "struct {\n"
   758  		off := int64(0)
   759  		npad := 0
   760  		if fn.Recv != nil {
   761  			t := p.cgoType(fn.Recv.List[0].Type)
   762  			ctype += fmt.Sprintf("\t\t%s recv;\n", t.C)
   763  			off += t.Size
   764  		}
   765  		fntype := fn.Type
   766  		forFieldList(fntype.Params,
   767  			func(i int, aname string, atype ast.Expr) {
   768  				t := p.cgoType(atype)
   769  				if off%t.Align != 0 {
   770  					pad := t.Align - off%t.Align
   771  					ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad)
   772  					off += pad
   773  					npad++
   774  				}
   775  				ctype += fmt.Sprintf("\t\t%s p%d;\n", t.C, i)
   776  				off += t.Size
   777  			})
   778  		if off%p.PtrSize != 0 {
   779  			pad := p.PtrSize - off%p.PtrSize
   780  			ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad)
   781  			off += pad
   782  			npad++
   783  		}
   784  		forFieldList(fntype.Results,
   785  			func(i int, aname string, atype ast.Expr) {
   786  				t := p.cgoType(atype)
   787  				if off%t.Align != 0 {
   788  					pad := t.Align - off%t.Align
   789  					ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad)
   790  					off += pad
   791  					npad++
   792  				}
   793  				ctype += fmt.Sprintf("\t\t%s r%d;\n", t.C, i)
   794  				off += t.Size
   795  			})
   796  		if off%p.PtrSize != 0 {
   797  			pad := p.PtrSize - off%p.PtrSize
   798  			ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad)
   799  			off += pad
   800  			npad++
   801  		}
   802  		if ctype == "struct {\n" {
   803  			ctype += "\t\tchar unused;\n" // avoid empty struct
   804  		}
   805  		ctype += "\t}"
   806  
   807  		// Get the return type of the wrapper function
   808  		// compiled by gcc.
   809  		gccResult := ""
   810  		if fntype.Results == nil || len(fntype.Results.List) == 0 {
   811  			gccResult = "void"
   812  		} else if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
   813  			gccResult = p.cgoType(fntype.Results.List[0].Type).C.String()
   814  		} else {
   815  			fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
   816  			fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName)
   817  			forFieldList(fntype.Results,
   818  				func(i int, aname string, atype ast.Expr) {
   819  					fmt.Fprintf(fgcch, "\t%s r%d;", p.cgoType(atype).C, i)
   820  					if len(aname) > 0 {
   821  						fmt.Fprintf(fgcch, " /* %s */", aname)
   822  					}
   823  					fmt.Fprint(fgcch, "\n")
   824  				})
   825  			fmt.Fprintf(fgcch, "};\n")
   826  			gccResult = "struct " + exp.ExpName + "_return"
   827  		}
   828  
   829  		// Build the wrapper function compiled by gcc.
   830  		s := fmt.Sprintf("%s %s(", gccResult, exp.ExpName)
   831  		if fn.Recv != nil {
   832  			s += p.cgoType(fn.Recv.List[0].Type).C.String()
   833  			s += " recv"
   834  		}
   835  		forFieldList(fntype.Params,
   836  			func(i int, aname string, atype ast.Expr) {
   837  				if i > 0 || fn.Recv != nil {
   838  					s += ", "
   839  				}
   840  				s += fmt.Sprintf("%s p%d", p.cgoType(atype).C, i)
   841  			})
   842  		s += ")"
   843  
   844  		if len(exp.Doc) > 0 {
   845  			fmt.Fprintf(fgcch, "\n%s", exp.Doc)
   846  		}
   847  		fmt.Fprintf(fgcch, "\nextern %s;\n", s)
   848  
   849  		fmt.Fprintf(fgcc, "extern void _cgoexp%s_%s(void *, int, __SIZE_TYPE__);\n", cPrefix, exp.ExpName)
   850  		fmt.Fprintf(fgcc, "\nCGO_NO_SANITIZE_THREAD")
   851  		fmt.Fprintf(fgcc, "\n%s\n", s)
   852  		fmt.Fprintf(fgcc, "{\n")
   853  		fmt.Fprintf(fgcc, "\t__SIZE_TYPE__ _cgo_ctxt = _cgo_wait_runtime_init_done();\n")
   854  		fmt.Fprintf(fgcc, "\t%s %v a;\n", ctype, p.packedAttribute())
   855  		if gccResult != "void" && (len(fntype.Results.List) > 1 || len(fntype.Results.List[0].Names) > 1) {
   856  			fmt.Fprintf(fgcc, "\t%s r;\n", gccResult)
   857  		}
   858  		if fn.Recv != nil {
   859  			fmt.Fprintf(fgcc, "\ta.recv = recv;\n")
   860  		}
   861  		forFieldList(fntype.Params,
   862  			func(i int, aname string, atype ast.Expr) {
   863  				fmt.Fprintf(fgcc, "\ta.p%d = p%d;\n", i, i)
   864  			})
   865  		fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
   866  		fmt.Fprintf(fgcc, "\tcrosscall2(_cgoexp%s_%s, &a, %d, _cgo_ctxt);\n", cPrefix, exp.ExpName, off)
   867  		fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
   868  		fmt.Fprintf(fgcc, "\t_cgo_release_context(_cgo_ctxt);\n")
   869  		if gccResult != "void" {
   870  			if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
   871  				fmt.Fprintf(fgcc, "\treturn a.r0;\n")
   872  			} else {
   873  				forFieldList(fntype.Results,
   874  					func(i int, aname string, atype ast.Expr) {
   875  						fmt.Fprintf(fgcc, "\tr.r%d = a.r%d;\n", i, i)
   876  					})
   877  				fmt.Fprintf(fgcc, "\treturn r;\n")
   878  			}
   879  		}
   880  		fmt.Fprintf(fgcc, "}\n")
   881  
   882  		// Build the wrapper function compiled by cmd/compile.
   883  		goname := "_cgoexpwrap" + cPrefix + "_"
   884  		if fn.Recv != nil {
   885  			goname += fn.Recv.List[0].Names[0].Name + "_"
   886  		}
   887  		goname += exp.Func.Name.Name
   888  		fmt.Fprintf(fgo2, "//go:cgo_export_dynamic %s\n", exp.ExpName)
   889  		fmt.Fprintf(fgo2, "//go:linkname _cgoexp%s_%s _cgoexp%s_%s\n", cPrefix, exp.ExpName, cPrefix, exp.ExpName)
   890  		fmt.Fprintf(fgo2, "//go:cgo_export_static _cgoexp%s_%s\n", cPrefix, exp.ExpName)
   891  		fmt.Fprintf(fgo2, "//go:nosplit\n") // no split stack, so no use of m or g
   892  		fmt.Fprintf(fgo2, "//go:norace\n")  // must not have race detector calls inserted
   893  		fmt.Fprintf(fgo2, "func _cgoexp%s_%s(a unsafe.Pointer, n int32, ctxt uintptr) {\n", cPrefix, exp.ExpName)
   894  		fmt.Fprintf(fgo2, "\tfn := %s\n", goname)
   895  		// The indirect here is converting from a Go function pointer to a C function pointer.
   896  		fmt.Fprintf(fgo2, "\t_cgo_runtime_cgocallback(**(**unsafe.Pointer)(unsafe.Pointer(&fn)), a, uintptr(n), ctxt);\n")
   897  		fmt.Fprintf(fgo2, "}\n")
   898  
   899  		fmt.Fprintf(fm, "int _cgoexp%s_%s;\n", cPrefix, exp.ExpName)
   900  
   901  		// This code uses printer.Fprint, not conf.Fprint,
   902  		// because we don't want //line comments in the middle
   903  		// of the function types.
   904  		fmt.Fprintf(fgo2, "\n")
   905  		fmt.Fprintf(fgo2, "func %s(", goname)
   906  		comma := false
   907  		if fn.Recv != nil {
   908  			fmt.Fprintf(fgo2, "recv ")
   909  			printer.Fprint(fgo2, fset, fn.Recv.List[0].Type)
   910  			comma = true
   911  		}
   912  		forFieldList(fntype.Params,
   913  			func(i int, aname string, atype ast.Expr) {
   914  				if comma {
   915  					fmt.Fprintf(fgo2, ", ")
   916  				}
   917  				fmt.Fprintf(fgo2, "p%d ", i)
   918  				printer.Fprint(fgo2, fset, atype)
   919  				comma = true
   920  			})
   921  		fmt.Fprintf(fgo2, ")")
   922  		if gccResult != "void" {
   923  			fmt.Fprint(fgo2, " (")
   924  			forFieldList(fntype.Results,
   925  				func(i int, aname string, atype ast.Expr) {
   926  					if i > 0 {
   927  						fmt.Fprint(fgo2, ", ")
   928  					}
   929  					fmt.Fprintf(fgo2, "r%d ", i)
   930  					printer.Fprint(fgo2, fset, atype)
   931  				})
   932  			fmt.Fprint(fgo2, ")")
   933  		}
   934  		fmt.Fprint(fgo2, " {\n")
   935  		if gccResult == "void" {
   936  			fmt.Fprint(fgo2, "\t")
   937  		} else {
   938  			// Verify that any results don't contain any
   939  			// Go pointers.
   940  			addedDefer := false
   941  			forFieldList(fntype.Results,
   942  				func(i int, aname string, atype ast.Expr) {
   943  					if !p.hasPointer(nil, atype, false) {
   944  						return
   945  					}
   946  					if !addedDefer {
   947  						fmt.Fprint(fgo2, "\tdefer func() {\n")
   948  						addedDefer = true
   949  					}
   950  					fmt.Fprintf(fgo2, "\t\t_cgoCheckResult(r%d)\n", i)
   951  				})
   952  			if addedDefer {
   953  				fmt.Fprint(fgo2, "\t}()\n")
   954  			}
   955  			fmt.Fprint(fgo2, "\treturn ")
   956  		}
   957  		if fn.Recv != nil {
   958  			fmt.Fprintf(fgo2, "recv.")
   959  		}
   960  		fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
   961  		forFieldList(fntype.Params,
   962  			func(i int, aname string, atype ast.Expr) {
   963  				if i > 0 {
   964  					fmt.Fprint(fgo2, ", ")
   965  				}
   966  				fmt.Fprintf(fgo2, "p%d", i)
   967  			})
   968  		fmt.Fprint(fgo2, ")\n")
   969  		fmt.Fprint(fgo2, "}\n")
   970  	}
   971  
   972  	fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
   973  }
   974  
   975  // Write out the C header allowing C code to call exported gccgo functions.
   976  func (p *Package) writeGccgoExports(fgo2, fm, fgcc, fgcch io.Writer) {
   977  	gccgoSymbolPrefix := p.gccgoSymbolPrefix()
   978  
   979  	p.writeExportHeader(fgcch)
   980  
   981  	fmt.Fprintf(fgcc, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
   982  	fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n")
   983  
   984  	fmt.Fprintf(fgcc, "%s\n", gccgoExportFileProlog)
   985  	fmt.Fprintf(fgcc, "%s\n", tsanProlog)
   986  	fmt.Fprintf(fgcc, "%s\n", msanProlog)
   987  
   988  	for _, exp := range p.ExpFunc {
   989  		fn := exp.Func
   990  		fntype := fn.Type
   991  
   992  		cdeclBuf := new(bytes.Buffer)
   993  		resultCount := 0
   994  		forFieldList(fntype.Results,
   995  			func(i int, aname string, atype ast.Expr) { resultCount++ })
   996  		switch resultCount {
   997  		case 0:
   998  			fmt.Fprintf(cdeclBuf, "void")
   999  		case 1:
  1000  			forFieldList(fntype.Results,
  1001  				func(i int, aname string, atype ast.Expr) {
  1002  					t := p.cgoType(atype)
  1003  					fmt.Fprintf(cdeclBuf, "%s", t.C)
  1004  				})
  1005  		default:
  1006  			// Declare a result struct.
  1007  			fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
  1008  			fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName)
  1009  			forFieldList(fntype.Results,
  1010  				func(i int, aname string, atype ast.Expr) {
  1011  					t := p.cgoType(atype)
  1012  					fmt.Fprintf(fgcch, "\t%s r%d;", t.C, i)
  1013  					if len(aname) > 0 {
  1014  						fmt.Fprintf(fgcch, " /* %s */", aname)
  1015  					}
  1016  					fmt.Fprint(fgcch, "\n")
  1017  				})
  1018  			fmt.Fprintf(fgcch, "};\n")
  1019  			fmt.Fprintf(cdeclBuf, "struct %s_return", exp.ExpName)
  1020  		}
  1021  
  1022  		cRet := cdeclBuf.String()
  1023  
  1024  		cdeclBuf = new(bytes.Buffer)
  1025  		fmt.Fprintf(cdeclBuf, "(")
  1026  		if fn.Recv != nil {
  1027  			fmt.Fprintf(cdeclBuf, "%s recv", p.cgoType(fn.Recv.List[0].Type).C.String())
  1028  		}
  1029  		// Function parameters.
  1030  		forFieldList(fntype.Params,
  1031  			func(i int, aname string, atype ast.Expr) {
  1032  				if i > 0 || fn.Recv != nil {
  1033  					fmt.Fprintf(cdeclBuf, ", ")
  1034  				}
  1035  				t := p.cgoType(atype)
  1036  				fmt.Fprintf(cdeclBuf, "%s p%d", t.C, i)
  1037  			})
  1038  		fmt.Fprintf(cdeclBuf, ")")
  1039  		cParams := cdeclBuf.String()
  1040  
  1041  		if len(exp.Doc) > 0 {
  1042  			fmt.Fprintf(fgcch, "\n%s", exp.Doc)
  1043  		}
  1044  
  1045  		fmt.Fprintf(fgcch, "extern %s %s%s;\n", cRet, exp.ExpName, cParams)
  1046  
  1047  		// We need to use a name that will be exported by the
  1048  		// Go code; otherwise gccgo will make it static and we
  1049  		// will not be able to link against it from the C
  1050  		// code.
  1051  		goName := "Cgoexp_" + exp.ExpName
  1052  		fmt.Fprintf(fgcc, `extern %s %s %s __asm__("%s.%s");`, cRet, goName, cParams, gccgoSymbolPrefix, goName)
  1053  		fmt.Fprint(fgcc, "\n")
  1054  
  1055  		fmt.Fprint(fgcc, "\nCGO_NO_SANITIZE_THREAD\n")
  1056  		fmt.Fprintf(fgcc, "%s %s %s {\n", cRet, exp.ExpName, cParams)
  1057  		if resultCount > 0 {
  1058  			fmt.Fprintf(fgcc, "\t%s r;\n", cRet)
  1059  		}
  1060  		fmt.Fprintf(fgcc, "\tif(_cgo_wait_runtime_init_done)\n")
  1061  		fmt.Fprintf(fgcc, "\t\t_cgo_wait_runtime_init_done();\n")
  1062  		fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
  1063  		fmt.Fprint(fgcc, "\t")
  1064  		if resultCount > 0 {
  1065  			fmt.Fprint(fgcc, "r = ")
  1066  		}
  1067  		fmt.Fprintf(fgcc, "%s(", goName)
  1068  		if fn.Recv != nil {
  1069  			fmt.Fprint(fgcc, "recv")
  1070  		}
  1071  		forFieldList(fntype.Params,
  1072  			func(i int, aname string, atype ast.Expr) {
  1073  				if i > 0 || fn.Recv != nil {
  1074  					fmt.Fprintf(fgcc, ", ")
  1075  				}
  1076  				fmt.Fprintf(fgcc, "p%d", i)
  1077  			})
  1078  		fmt.Fprint(fgcc, ");\n")
  1079  		fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
  1080  		if resultCount > 0 {
  1081  			fmt.Fprint(fgcc, "\treturn r;\n")
  1082  		}
  1083  		fmt.Fprint(fgcc, "}\n")
  1084  
  1085  		// Dummy declaration for _cgo_main.c
  1086  		fmt.Fprintf(fm, `char %s[1] __asm__("%s.%s");`, goName, gccgoSymbolPrefix, goName)
  1087  		fmt.Fprint(fm, "\n")
  1088  
  1089  		// For gccgo we use a wrapper function in Go, in order
  1090  		// to call CgocallBack and CgocallBackDone.
  1091  
  1092  		// This code uses printer.Fprint, not conf.Fprint,
  1093  		// because we don't want //line comments in the middle
  1094  		// of the function types.
  1095  		fmt.Fprint(fgo2, "\n")
  1096  		fmt.Fprintf(fgo2, "func %s(", goName)
  1097  		if fn.Recv != nil {
  1098  			fmt.Fprint(fgo2, "recv ")
  1099  			printer.Fprint(fgo2, fset, fn.Recv.List[0].Type)
  1100  		}
  1101  		forFieldList(fntype.Params,
  1102  			func(i int, aname string, atype ast.Expr) {
  1103  				if i > 0 || fn.Recv != nil {
  1104  					fmt.Fprintf(fgo2, ", ")
  1105  				}
  1106  				fmt.Fprintf(fgo2, "p%d ", i)
  1107  				printer.Fprint(fgo2, fset, atype)
  1108  			})
  1109  		fmt.Fprintf(fgo2, ")")
  1110  		if resultCount > 0 {
  1111  			fmt.Fprintf(fgo2, " (")
  1112  			forFieldList(fntype.Results,
  1113  				func(i int, aname string, atype ast.Expr) {
  1114  					if i > 0 {
  1115  						fmt.Fprint(fgo2, ", ")
  1116  					}
  1117  					printer.Fprint(fgo2, fset, atype)
  1118  				})
  1119  			fmt.Fprint(fgo2, ")")
  1120  		}
  1121  		fmt.Fprint(fgo2, " {\n")
  1122  		fmt.Fprint(fgo2, "\tsyscall.CgocallBack()\n")
  1123  		fmt.Fprint(fgo2, "\tdefer syscall.CgocallBackDone()\n")
  1124  		fmt.Fprint(fgo2, "\t")
  1125  		if resultCount > 0 {
  1126  			fmt.Fprint(fgo2, "return ")
  1127  		}
  1128  		if fn.Recv != nil {
  1129  			fmt.Fprint(fgo2, "recv.")
  1130  		}
  1131  		fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
  1132  		forFieldList(fntype.Params,
  1133  			func(i int, aname string, atype ast.Expr) {
  1134  				if i > 0 {
  1135  					fmt.Fprint(fgo2, ", ")
  1136  				}
  1137  				fmt.Fprintf(fgo2, "p%d", i)
  1138  			})
  1139  		fmt.Fprint(fgo2, ")\n")
  1140  		fmt.Fprint(fgo2, "}\n")
  1141  	}
  1142  
  1143  	fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
  1144  }
  1145  
  1146  // writeExportHeader writes out the start of the _cgo_export.h file.
  1147  func (p *Package) writeExportHeader(fgcch io.Writer) {
  1148  	fmt.Fprintf(fgcch, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
  1149  	pkg := *importPath
  1150  	if pkg == "" {
  1151  		pkg = p.PackagePath
  1152  	}
  1153  	fmt.Fprintf(fgcch, "/* package %s */\n\n", pkg)
  1154  	fmt.Fprintf(fgcch, "%s\n", builtinExportProlog)
  1155  
  1156  	// Remove absolute paths from #line comments in the preamble.
  1157  	// They aren't useful for people using the header file,
  1158  	// and they mean that the header files change based on the
  1159  	// exact location of GOPATH.
  1160  	re := regexp.MustCompile(`(?m)^(#line\s+[0-9]+\s+")[^"]*[/\\]([^"]*")`)
  1161  	preamble := re.ReplaceAllString(p.Preamble, "$1$2")
  1162  
  1163  	fmt.Fprintf(fgcch, "/* Start of preamble from import \"C\" comments.  */\n\n")
  1164  	fmt.Fprintf(fgcch, "%s\n", preamble)
  1165  	fmt.Fprintf(fgcch, "\n/* End of preamble from import \"C\" comments.  */\n\n")
  1166  
  1167  	fmt.Fprintf(fgcch, "%s\n", p.gccExportHeaderProlog())
  1168  }
  1169  
  1170  // Return the package prefix when using gccgo.
  1171  func (p *Package) gccgoSymbolPrefix() string {
  1172  	if !*gccgo {
  1173  		return ""
  1174  	}
  1175  
  1176  	clean := func(r rune) rune {
  1177  		switch {
  1178  		case 'A' <= r && r <= 'Z', 'a' <= r && r <= 'z',
  1179  			'0' <= r && r <= '9':
  1180  			return r
  1181  		}
  1182  		return '_'
  1183  	}
  1184  
  1185  	if *gccgopkgpath != "" {
  1186  		return strings.Map(clean, *gccgopkgpath)
  1187  	}
  1188  	if *gccgoprefix == "" && p.PackageName == "main" {
  1189  		return "main"
  1190  	}
  1191  	prefix := strings.Map(clean, *gccgoprefix)
  1192  	if prefix == "" {
  1193  		prefix = "go"
  1194  	}
  1195  	return prefix + "." + p.PackageName
  1196  }
  1197  
  1198  // Call a function for each entry in an ast.FieldList, passing the
  1199  // index into the list, the name if any, and the type.
  1200  func forFieldList(fl *ast.FieldList, fn func(int, string, ast.Expr)) {
  1201  	if fl == nil {
  1202  		return
  1203  	}
  1204  	i := 0
  1205  	for _, r := range fl.List {
  1206  		if r.Names == nil {
  1207  			fn(i, "", r.Type)
  1208  			i++
  1209  		} else {
  1210  			for _, n := range r.Names {
  1211  				fn(i, n.Name, r.Type)
  1212  				i++
  1213  			}
  1214  		}
  1215  	}
  1216  }
  1217  
  1218  func c(repr string, args ...interface{}) *TypeRepr {
  1219  	return &TypeRepr{repr, args}
  1220  }
  1221  
  1222  // Map predeclared Go types to Type.
  1223  var goTypes = map[string]*Type{
  1224  	"bool":       {Size: 1, Align: 1, C: c("GoUint8")},
  1225  	"byte":       {Size: 1, Align: 1, C: c("GoUint8")},
  1226  	"int":        {Size: 0, Align: 0, C: c("GoInt")},
  1227  	"uint":       {Size: 0, Align: 0, C: c("GoUint")},
  1228  	"rune":       {Size: 4, Align: 4, C: c("GoInt32")},
  1229  	"int8":       {Size: 1, Align: 1, C: c("GoInt8")},
  1230  	"uint8":      {Size: 1, Align: 1, C: c("GoUint8")},
  1231  	"int16":      {Size: 2, Align: 2, C: c("GoInt16")},
  1232  	"uint16":     {Size: 2, Align: 2, C: c("GoUint16")},
  1233  	"int32":      {Size: 4, Align: 4, C: c("GoInt32")},
  1234  	"uint32":     {Size: 4, Align: 4, C: c("GoUint32")},
  1235  	"int64":      {Size: 8, Align: 8, C: c("GoInt64")},
  1236  	"uint64":     {Size: 8, Align: 8, C: c("GoUint64")},
  1237  	"float32":    {Size: 4, Align: 4, C: c("GoFloat32")},
  1238  	"float64":    {Size: 8, Align: 8, C: c("GoFloat64")},
  1239  	"complex64":  {Size: 8, Align: 4, C: c("GoComplex64")},
  1240  	"complex128": {Size: 16, Align: 8, C: c("GoComplex128")},
  1241  }
  1242  
  1243  // Map an ast type to a Type.
  1244  func (p *Package) cgoType(e ast.Expr) *Type {
  1245  	switch t := e.(type) {
  1246  	case *ast.StarExpr:
  1247  		x := p.cgoType(t.X)
  1248  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("%s*", x.C)}
  1249  	case *ast.ArrayType:
  1250  		if t.Len == nil {
  1251  			// Slice: pointer, len, cap.
  1252  			return &Type{Size: p.PtrSize * 3, Align: p.PtrSize, C: c("GoSlice")}
  1253  		}
  1254  		// Non-slice array types are not supported.
  1255  	case *ast.StructType:
  1256  		// Not supported.
  1257  	case *ast.FuncType:
  1258  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
  1259  	case *ast.InterfaceType:
  1260  		return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
  1261  	case *ast.MapType:
  1262  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoMap")}
  1263  	case *ast.ChanType:
  1264  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoChan")}
  1265  	case *ast.Ident:
  1266  		// Look up the type in the top level declarations.
  1267  		// TODO: Handle types defined within a function.
  1268  		for _, d := range p.Decl {
  1269  			gd, ok := d.(*ast.GenDecl)
  1270  			if !ok || gd.Tok != token.TYPE {
  1271  				continue
  1272  			}
  1273  			for _, spec := range gd.Specs {
  1274  				ts, ok := spec.(*ast.TypeSpec)
  1275  				if !ok {
  1276  					continue
  1277  				}
  1278  				if ts.Name.Name == t.Name {
  1279  					return p.cgoType(ts.Type)
  1280  				}
  1281  			}
  1282  		}
  1283  		if def := typedef[t.Name]; def != nil {
  1284  			return def
  1285  		}
  1286  		if t.Name == "uintptr" {
  1287  			return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoUintptr")}
  1288  		}
  1289  		if t.Name == "string" {
  1290  			// The string data is 1 pointer + 1 (pointer-sized) int.
  1291  			return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoString")}
  1292  		}
  1293  		if t.Name == "error" {
  1294  			return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
  1295  		}
  1296  		if r, ok := goTypes[t.Name]; ok {
  1297  			if r.Size == 0 { // int or uint
  1298  				rr := new(Type)
  1299  				*rr = *r
  1300  				rr.Size = p.IntSize
  1301  				rr.Align = p.IntSize
  1302  				r = rr
  1303  			}
  1304  			if r.Align > p.PtrSize {
  1305  				r.Align = p.PtrSize
  1306  			}
  1307  			return r
  1308  		}
  1309  		error_(e.Pos(), "unrecognized Go type %s", t.Name)
  1310  		return &Type{Size: 4, Align: 4, C: c("int")}
  1311  	case *ast.SelectorExpr:
  1312  		id, ok := t.X.(*ast.Ident)
  1313  		if ok && id.Name == "unsafe" && t.Sel.Name == "Pointer" {
  1314  			return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
  1315  		}
  1316  	}
  1317  	error_(e.Pos(), "Go type not supported in export: %s", gofmt(e))
  1318  	return &Type{Size: 4, Align: 4, C: c("int")}
  1319  }
  1320  
  1321  const gccProlog = `
  1322  #line 1 "cgo-gcc-prolog"
  1323  /*
  1324    If x and y are not equal, the type will be invalid
  1325    (have a negative array count) and an inscrutable error will come
  1326    out of the compiler and hopefully mention "name".
  1327  */
  1328  #define __cgo_compile_assert_eq(x, y, name) typedef char name[(x-y)*(x-y)*-2+1];
  1329  
  1330  /* Check at compile time that the sizes we use match our expectations. */
  1331  #define __cgo_size_assert(t, n) __cgo_compile_assert_eq(sizeof(t), n, _cgo_sizeof_##t##_is_not_##n)
  1332  
  1333  __cgo_size_assert(char, 1)
  1334  __cgo_size_assert(short, 2)
  1335  __cgo_size_assert(int, 4)
  1336  typedef long long __cgo_long_long;
  1337  __cgo_size_assert(__cgo_long_long, 8)
  1338  __cgo_size_assert(float, 4)
  1339  __cgo_size_assert(double, 8)
  1340  
  1341  extern char* _cgo_topofstack(void);
  1342  
  1343  #include <errno.h>
  1344  #include <string.h>
  1345  `
  1346  
  1347  // Prologue defining TSAN functions in C.
  1348  const noTsanProlog = `
  1349  #define CGO_NO_SANITIZE_THREAD
  1350  #define _cgo_tsan_acquire()
  1351  #define _cgo_tsan_release()
  1352  `
  1353  
  1354  // This must match the TSAN code in runtime/cgo/libcgo.h.
  1355  // This is used when the code is built with the C/C++ Thread SANitizer,
  1356  // which is not the same as the Go race detector.
  1357  // __tsan_acquire tells TSAN that we are acquiring a lock on a variable,
  1358  // in this case _cgo_sync. __tsan_release releases the lock.
  1359  // (There is no actual lock, we are just telling TSAN that there is.)
  1360  //
  1361  // When we call from Go to C we call _cgo_tsan_acquire.
  1362  // When the C function returns we call _cgo_tsan_release.
  1363  // Similarly, when C calls back into Go we call _cgo_tsan_release
  1364  // and then call _cgo_tsan_acquire when we return to C.
  1365  // These calls tell TSAN that there is a serialization point at the C call.
  1366  //
  1367  // This is necessary because TSAN, which is a C/C++ tool, can not see
  1368  // the synchronization in the Go code. Without these calls, when
  1369  // multiple goroutines call into C code, TSAN does not understand
  1370  // that the calls are properly synchronized on the Go side.
  1371  //
  1372  // To be clear, if the calls are not properly synchronized on the Go side,
  1373  // we will be hiding races. But when using TSAN on mixed Go C/C++ code
  1374  // it is more important to avoid false positives, which reduce confidence
  1375  // in the tool, than to avoid false negatives.
  1376  const yesTsanProlog = `
  1377  #line 1 "cgo-tsan-prolog"
  1378  #define CGO_NO_SANITIZE_THREAD __attribute__ ((no_sanitize_thread))
  1379  
  1380  long long _cgo_sync __attribute__ ((common));
  1381  
  1382  extern void __tsan_acquire(void*);
  1383  extern void __tsan_release(void*);
  1384  
  1385  __attribute__ ((unused))
  1386  static void _cgo_tsan_acquire() {
  1387  	__tsan_acquire(&_cgo_sync);
  1388  }
  1389  
  1390  __attribute__ ((unused))
  1391  static void _cgo_tsan_release() {
  1392  	__tsan_release(&_cgo_sync);
  1393  }
  1394  `
  1395  
  1396  // Set to yesTsanProlog if we see -fsanitize=thread in the flags for gcc.
  1397  var tsanProlog = noTsanProlog
  1398  
  1399  // noMsanProlog is a prologue defining an MSAN function in C.
  1400  // This is used when not compiling with -fsanitize=memory.
  1401  const noMsanProlog = `
  1402  #define _cgo_msan_write(addr, sz)
  1403  `
  1404  
  1405  // yesMsanProlog is a prologue defining an MSAN function in C.
  1406  // This is used when compiling with -fsanitize=memory.
  1407  // See the comment above where _cgo_msan_write is called.
  1408  const yesMsanProlog = `
  1409  extern void __msan_unpoison(const volatile void *, size_t);
  1410  
  1411  #define _cgo_msan_write(addr, sz) __msan_unpoison((addr), (sz))
  1412  `
  1413  
  1414  // msanProlog is set to yesMsanProlog if we see -fsanitize=memory in the flags
  1415  // for the C compiler.
  1416  var msanProlog = noMsanProlog
  1417  
  1418  const builtinProlog = `
  1419  #line 1 "cgo-builtin-prolog"
  1420  #include <stddef.h> /* for ptrdiff_t and size_t below */
  1421  
  1422  /* Define intgo when compiling with GCC.  */
  1423  typedef ptrdiff_t intgo;
  1424  
  1425  typedef struct { const char *p; intgo n; } _GoString_;
  1426  typedef struct { char *p; intgo n; intgo c; } _GoBytes_;
  1427  _GoString_ GoString(char *p);
  1428  _GoString_ GoStringN(char *p, int l);
  1429  _GoBytes_ GoBytes(void *p, int n);
  1430  char *CString(_GoString_);
  1431  void *CBytes(_GoBytes_);
  1432  void *_CMalloc(size_t);
  1433  
  1434  __attribute__ ((unused))
  1435  static size_t _GoStringLen(_GoString_ s) { return s.n; }
  1436  
  1437  __attribute__ ((unused))
  1438  static const char *_GoStringPtr(_GoString_ s) { return s.p; }
  1439  `
  1440  
  1441  const goProlog = `
  1442  //go:linkname _cgo_runtime_cgocall runtime.cgocall
  1443  func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
  1444  
  1445  //go:linkname _cgo_runtime_cgocallback runtime.cgocallback
  1446  func _cgo_runtime_cgocallback(unsafe.Pointer, unsafe.Pointer, uintptr, uintptr)
  1447  
  1448  //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
  1449  func _cgoCheckPointer(interface{}, ...interface{})
  1450  
  1451  //go:linkname _cgoCheckResult runtime.cgoCheckResult
  1452  func _cgoCheckResult(interface{})
  1453  `
  1454  
  1455  const gccgoGoProlog = `
  1456  func _cgoCheckPointer(interface{}, ...interface{})
  1457  
  1458  func _cgoCheckResult(interface{})
  1459  `
  1460  
  1461  const goStringDef = `
  1462  //go:linkname _cgo_runtime_gostring runtime.gostring
  1463  func _cgo_runtime_gostring(*_Ctype_char) string
  1464  
  1465  func _Cfunc_GoString(p *_Ctype_char) string {
  1466  	return _cgo_runtime_gostring(p)
  1467  }
  1468  `
  1469  
  1470  const goStringNDef = `
  1471  //go:linkname _cgo_runtime_gostringn runtime.gostringn
  1472  func _cgo_runtime_gostringn(*_Ctype_char, int) string
  1473  
  1474  func _Cfunc_GoStringN(p *_Ctype_char, l _Ctype_int) string {
  1475  	return _cgo_runtime_gostringn(p, int(l))
  1476  }
  1477  `
  1478  
  1479  const goBytesDef = `
  1480  //go:linkname _cgo_runtime_gobytes runtime.gobytes
  1481  func _cgo_runtime_gobytes(unsafe.Pointer, int) []byte
  1482  
  1483  func _Cfunc_GoBytes(p unsafe.Pointer, l _Ctype_int) []byte {
  1484  	return _cgo_runtime_gobytes(p, int(l))
  1485  }
  1486  `
  1487  
  1488  const cStringDef = `
  1489  func _Cfunc_CString(s string) *_Ctype_char {
  1490  	p := _cgo_cmalloc(uint64(len(s)+1))
  1491  	pp := (*[1<<30]byte)(p)
  1492  	copy(pp[:], s)
  1493  	pp[len(s)] = 0
  1494  	return (*_Ctype_char)(p)
  1495  }
  1496  `
  1497  
  1498  const cBytesDef = `
  1499  func _Cfunc_CBytes(b []byte) unsafe.Pointer {
  1500  	p := _cgo_cmalloc(uint64(len(b)))
  1501  	pp := (*[1<<30]byte)(p)
  1502  	copy(pp[:], b)
  1503  	return p
  1504  }
  1505  `
  1506  
  1507  const cMallocDef = `
  1508  func _Cfunc__CMalloc(n _Ctype_size_t) unsafe.Pointer {
  1509  	return _cgo_cmalloc(uint64(n))
  1510  }
  1511  `
  1512  
  1513  var builtinDefs = map[string]string{
  1514  	"GoString":  goStringDef,
  1515  	"GoStringN": goStringNDef,
  1516  	"GoBytes":   goBytesDef,
  1517  	"CString":   cStringDef,
  1518  	"CBytes":    cBytesDef,
  1519  	"_CMalloc":  cMallocDef,
  1520  }
  1521  
  1522  // Definitions for C.malloc in Go and in C. We define it ourselves
  1523  // since we call it from functions we define, such as C.CString.
  1524  // Also, we have historically ensured that C.malloc does not return
  1525  // nil even for an allocation of 0.
  1526  
  1527  const cMallocDefGo = `
  1528  //go:cgo_import_static _cgoPREFIX_Cfunc__Cmalloc
  1529  //go:linkname __cgofn__cgoPREFIX_Cfunc__Cmalloc _cgoPREFIX_Cfunc__Cmalloc
  1530  var __cgofn__cgoPREFIX_Cfunc__Cmalloc byte
  1531  var _cgoPREFIX_Cfunc__Cmalloc = unsafe.Pointer(&__cgofn__cgoPREFIX_Cfunc__Cmalloc)
  1532  
  1533  //go:linkname runtime_throw runtime.throw
  1534  func runtime_throw(string)
  1535  
  1536  //go:cgo_unsafe_args
  1537  func _cgo_cmalloc(p0 uint64) (r1 unsafe.Pointer) {
  1538  	_cgo_runtime_cgocall(_cgoPREFIX_Cfunc__Cmalloc, uintptr(unsafe.Pointer(&p0)))
  1539  	if r1 == nil {
  1540  		runtime_throw("runtime: C malloc failed")
  1541  	}
  1542  	return
  1543  }
  1544  `
  1545  
  1546  // cMallocDefC defines the C version of C.malloc for the gc compiler.
  1547  // It is defined here because C.CString and friends need a definition.
  1548  // We define it by hand, rather than simply inventing a reference to
  1549  // C.malloc, because <stdlib.h> may not have been included.
  1550  // This is approximately what writeOutputFunc would generate, but
  1551  // skips the cgo_topofstack code (which is only needed if the C code
  1552  // calls back into Go). This also avoids returning nil for an
  1553  // allocation of 0 bytes.
  1554  const cMallocDefC = `
  1555  CGO_NO_SANITIZE_THREAD
  1556  void _cgoPREFIX_Cfunc__Cmalloc(void *v) {
  1557  	struct {
  1558  		unsigned long long p0;
  1559  		void *r1;
  1560  	} PACKED *a = v;
  1561  	void *ret;
  1562  	_cgo_tsan_acquire();
  1563  	ret = malloc(a->p0);
  1564  	if (ret == 0 && a->p0 == 0) {
  1565  		ret = malloc(1);
  1566  	}
  1567  	a->r1 = ret;
  1568  	_cgo_tsan_release();
  1569  }
  1570  `
  1571  
  1572  func (p *Package) cPrologGccgo() string {
  1573  	return strings.Replace(strings.Replace(cPrologGccgo, "PREFIX", cPrefix, -1),
  1574  		"GCCGOSYMBOLPREF", p.gccgoSymbolPrefix(), -1)
  1575  }
  1576  
  1577  const cPrologGccgo = `
  1578  #line 1 "cgo-c-prolog-gccgo"
  1579  #include <stdint.h>
  1580  #include <stdlib.h>
  1581  #include <string.h>
  1582  
  1583  typedef unsigned char byte;
  1584  typedef intptr_t intgo;
  1585  
  1586  struct __go_string {
  1587  	const unsigned char *__data;
  1588  	intgo __length;
  1589  };
  1590  
  1591  typedef struct __go_open_array {
  1592  	void* __values;
  1593  	intgo __count;
  1594  	intgo __capacity;
  1595  } Slice;
  1596  
  1597  struct __go_string __go_byte_array_to_string(const void* p, intgo len);
  1598  struct __go_open_array __go_string_to_byte_array (struct __go_string str);
  1599  
  1600  const char *_cgoPREFIX_Cfunc_CString(struct __go_string s) {
  1601  	char *p = malloc(s.__length+1);
  1602  	memmove(p, s.__data, s.__length);
  1603  	p[s.__length] = 0;
  1604  	return p;
  1605  }
  1606  
  1607  void *_cgoPREFIX_Cfunc_CBytes(struct __go_open_array b) {
  1608  	char *p = malloc(b.__count);
  1609  	memmove(p, b.__values, b.__count);
  1610  	return p;
  1611  }
  1612  
  1613  struct __go_string _cgoPREFIX_Cfunc_GoString(char *p) {
  1614  	intgo len = (p != NULL) ? strlen(p) : 0;
  1615  	return __go_byte_array_to_string(p, len);
  1616  }
  1617  
  1618  struct __go_string _cgoPREFIX_Cfunc_GoStringN(char *p, int32_t n) {
  1619  	return __go_byte_array_to_string(p, n);
  1620  }
  1621  
  1622  Slice _cgoPREFIX_Cfunc_GoBytes(char *p, int32_t n) {
  1623  	struct __go_string s = { (const unsigned char *)p, n };
  1624  	return __go_string_to_byte_array(s);
  1625  }
  1626  
  1627  extern void runtime_throw(const char *);
  1628  void *_cgoPREFIX_Cfunc__CMalloc(size_t n) {
  1629          void *p = malloc(n);
  1630          if(p == NULL && n == 0)
  1631                  p = malloc(1);
  1632          if(p == NULL)
  1633                  runtime_throw("runtime: C malloc failed");
  1634          return p;
  1635  }
  1636  
  1637  struct __go_type_descriptor;
  1638  typedef struct __go_empty_interface {
  1639  	const struct __go_type_descriptor *__type_descriptor;
  1640  	void *__object;
  1641  } Eface;
  1642  
  1643  extern void runtimeCgoCheckPointer(Eface, Slice)
  1644  	__asm__("runtime.cgoCheckPointer")
  1645  	__attribute__((weak));
  1646  
  1647  extern void localCgoCheckPointer(Eface, Slice)
  1648  	__asm__("GCCGOSYMBOLPREF._cgoCheckPointer");
  1649  
  1650  void localCgoCheckPointer(Eface ptr, Slice args) {
  1651  	if(runtimeCgoCheckPointer) {
  1652  		runtimeCgoCheckPointer(ptr, args);
  1653  	}
  1654  }
  1655  
  1656  extern void runtimeCgoCheckResult(Eface)
  1657  	__asm__("runtime.cgoCheckResult")
  1658  	__attribute__((weak));
  1659  
  1660  extern void localCgoCheckResult(Eface)
  1661  	__asm__("GCCGOSYMBOLPREF._cgoCheckResult");
  1662  
  1663  void localCgoCheckResult(Eface val) {
  1664  	if(runtimeCgoCheckResult) {
  1665  		runtimeCgoCheckResult(val);
  1666  	}
  1667  }
  1668  `
  1669  
  1670  // builtinExportProlog is a shorter version of builtinProlog,
  1671  // to be put into the _cgo_export.h file.
  1672  // For historical reasons we can't use builtinProlog in _cgo_export.h,
  1673  // because _cgo_export.h defines GoString as a struct while builtinProlog
  1674  // defines it as a function. We don't change this to avoid unnecessarily
  1675  // breaking existing code.
  1676  const builtinExportProlog = `
  1677  #line 1 "cgo-builtin-prolog"
  1678  
  1679  #include <stddef.h> /* for ptrdiff_t below */
  1680  
  1681  #ifndef GO_CGO_EXPORT_PROLOGUE_H
  1682  #define GO_CGO_EXPORT_PROLOGUE_H
  1683  
  1684  typedef struct { const char *p; ptrdiff_t n; } _GoString_;
  1685  
  1686  #endif
  1687  `
  1688  
  1689  func (p *Package) gccExportHeaderProlog() string {
  1690  	return strings.Replace(gccExportHeaderProlog, "GOINTBITS", fmt.Sprint(8*p.IntSize), -1)
  1691  }
  1692  
  1693  const gccExportHeaderProlog = `
  1694  /* Start of boilerplate cgo prologue.  */
  1695  #line 1 "cgo-gcc-export-header-prolog"
  1696  
  1697  #ifndef GO_CGO_PROLOGUE_H
  1698  #define GO_CGO_PROLOGUE_H
  1699  
  1700  typedef signed char GoInt8;
  1701  typedef unsigned char GoUint8;
  1702  typedef short GoInt16;
  1703  typedef unsigned short GoUint16;
  1704  typedef int GoInt32;
  1705  typedef unsigned int GoUint32;
  1706  typedef long long GoInt64;
  1707  typedef unsigned long long GoUint64;
  1708  typedef GoIntGOINTBITS GoInt;
  1709  typedef GoUintGOINTBITS GoUint;
  1710  typedef __SIZE_TYPE__ GoUintptr;
  1711  typedef float GoFloat32;
  1712  typedef double GoFloat64;
  1713  typedef float _Complex GoComplex64;
  1714  typedef double _Complex GoComplex128;
  1715  
  1716  /*
  1717    static assertion to make sure the file is being used on architecture
  1718    at least with matching size of GoInt.
  1719  */
  1720  typedef char _check_for_GOINTBITS_bit_pointer_matching_GoInt[sizeof(void*)==GOINTBITS/8 ? 1:-1];
  1721  
  1722  typedef _GoString_ GoString;
  1723  typedef void *GoMap;
  1724  typedef void *GoChan;
  1725  typedef struct { void *t; void *v; } GoInterface;
  1726  typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
  1727  
  1728  #endif
  1729  
  1730  /* End of boilerplate cgo prologue.  */
  1731  
  1732  #ifdef __cplusplus
  1733  extern "C" {
  1734  #endif
  1735  `
  1736  
  1737  // gccExportHeaderEpilog goes at the end of the generated header file.
  1738  const gccExportHeaderEpilog = `
  1739  #ifdef __cplusplus
  1740  }
  1741  #endif
  1742  `
  1743  
  1744  // gccgoExportFileProlog is written to the _cgo_export.c file when
  1745  // using gccgo.
  1746  // We use weak declarations, and test the addresses, so that this code
  1747  // works with older versions of gccgo.
  1748  const gccgoExportFileProlog = `
  1749  #line 1 "cgo-gccgo-export-file-prolog"
  1750  extern _Bool runtime_iscgo __attribute__ ((weak));
  1751  
  1752  static void GoInit(void) __attribute__ ((constructor));
  1753  static void GoInit(void) {
  1754  	if(&runtime_iscgo)
  1755  		runtime_iscgo = 1;
  1756  }
  1757  
  1758  extern __SIZE_TYPE__ _cgo_wait_runtime_init_done() __attribute__ ((weak));
  1759  `
  1760  

View as plain text