...
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  	// We use packed structs, but they are always aligned.
   744  	// The pragmas and address-of-packed-member are not recognized as warning groups in clang 3.4.1, so ignore unknown pragmas first.
   745  	fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wunknown-pragmas\"\n")
   746  	fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wpragmas\"\n")
   747  	fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Waddress-of-packed-member\"\n")
   748  
   749  	fmt.Fprintf(fgcc, "extern void crosscall2(void (*fn)(void *, int, __SIZE_TYPE__), void *, int, __SIZE_TYPE__);\n")
   750  	fmt.Fprintf(fgcc, "extern __SIZE_TYPE__ _cgo_wait_runtime_init_done();\n")
   751  	fmt.Fprintf(fgcc, "extern void _cgo_release_context(__SIZE_TYPE__);\n\n")
   752  	fmt.Fprintf(fgcc, "extern char* _cgo_topofstack(void);")
   753  	fmt.Fprintf(fgcc, "%s\n", tsanProlog)
   754  	fmt.Fprintf(fgcc, "%s\n", msanProlog)
   755  
   756  	for _, exp := range p.ExpFunc {
   757  		fn := exp.Func
   758  
   759  		// Construct a gcc struct matching the gc argument and
   760  		// result frame. The gcc struct will be compiled with
   761  		// __attribute__((packed)) so all padding must be accounted
   762  		// for explicitly.
   763  		ctype := "struct {\n"
   764  		off := int64(0)
   765  		npad := 0
   766  		if fn.Recv != nil {
   767  			t := p.cgoType(fn.Recv.List[0].Type)
   768  			ctype += fmt.Sprintf("\t\t%s recv;\n", t.C)
   769  			off += t.Size
   770  		}
   771  		fntype := fn.Type
   772  		forFieldList(fntype.Params,
   773  			func(i int, aname string, atype ast.Expr) {
   774  				t := p.cgoType(atype)
   775  				if off%t.Align != 0 {
   776  					pad := t.Align - off%t.Align
   777  					ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad)
   778  					off += pad
   779  					npad++
   780  				}
   781  				ctype += fmt.Sprintf("\t\t%s p%d;\n", t.C, i)
   782  				off += t.Size
   783  			})
   784  		if off%p.PtrSize != 0 {
   785  			pad := p.PtrSize - off%p.PtrSize
   786  			ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad)
   787  			off += pad
   788  			npad++
   789  		}
   790  		forFieldList(fntype.Results,
   791  			func(i int, aname string, atype ast.Expr) {
   792  				t := p.cgoType(atype)
   793  				if off%t.Align != 0 {
   794  					pad := t.Align - off%t.Align
   795  					ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad)
   796  					off += pad
   797  					npad++
   798  				}
   799  				ctype += fmt.Sprintf("\t\t%s r%d;\n", t.C, i)
   800  				off += t.Size
   801  			})
   802  		if off%p.PtrSize != 0 {
   803  			pad := p.PtrSize - off%p.PtrSize
   804  			ctype += fmt.Sprintf("\t\tchar __pad%d[%d];\n", npad, pad)
   805  			off += pad
   806  			npad++
   807  		}
   808  		if ctype == "struct {\n" {
   809  			ctype += "\t\tchar unused;\n" // avoid empty struct
   810  		}
   811  		ctype += "\t}"
   812  
   813  		// Get the return type of the wrapper function
   814  		// compiled by gcc.
   815  		gccResult := ""
   816  		if fntype.Results == nil || len(fntype.Results.List) == 0 {
   817  			gccResult = "void"
   818  		} else if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
   819  			gccResult = p.cgoType(fntype.Results.List[0].Type).C.String()
   820  		} else {
   821  			fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
   822  			fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName)
   823  			forFieldList(fntype.Results,
   824  				func(i int, aname string, atype ast.Expr) {
   825  					fmt.Fprintf(fgcch, "\t%s r%d;", p.cgoType(atype).C, i)
   826  					if len(aname) > 0 {
   827  						fmt.Fprintf(fgcch, " /* %s */", aname)
   828  					}
   829  					fmt.Fprint(fgcch, "\n")
   830  				})
   831  			fmt.Fprintf(fgcch, "};\n")
   832  			gccResult = "struct " + exp.ExpName + "_return"
   833  		}
   834  
   835  		// Build the wrapper function compiled by gcc.
   836  		s := fmt.Sprintf("%s %s(", gccResult, exp.ExpName)
   837  		if fn.Recv != nil {
   838  			s += p.cgoType(fn.Recv.List[0].Type).C.String()
   839  			s += " recv"
   840  		}
   841  		forFieldList(fntype.Params,
   842  			func(i int, aname string, atype ast.Expr) {
   843  				if i > 0 || fn.Recv != nil {
   844  					s += ", "
   845  				}
   846  				s += fmt.Sprintf("%s p%d", p.cgoType(atype).C, i)
   847  			})
   848  		s += ")"
   849  
   850  		if len(exp.Doc) > 0 {
   851  			fmt.Fprintf(fgcch, "\n%s", exp.Doc)
   852  		}
   853  		fmt.Fprintf(fgcch, "\nextern %s;\n", s)
   854  
   855  		fmt.Fprintf(fgcc, "extern void _cgoexp%s_%s(void *, int, __SIZE_TYPE__);\n", cPrefix, exp.ExpName)
   856  		fmt.Fprintf(fgcc, "\nCGO_NO_SANITIZE_THREAD")
   857  		fmt.Fprintf(fgcc, "\n%s\n", s)
   858  		fmt.Fprintf(fgcc, "{\n")
   859  		fmt.Fprintf(fgcc, "\t__SIZE_TYPE__ _cgo_ctxt = _cgo_wait_runtime_init_done();\n")
   860  		fmt.Fprintf(fgcc, "\t%s %v a;\n", ctype, p.packedAttribute())
   861  		if gccResult != "void" && (len(fntype.Results.List) > 1 || len(fntype.Results.List[0].Names) > 1) {
   862  			fmt.Fprintf(fgcc, "\t%s r;\n", gccResult)
   863  		}
   864  		if fn.Recv != nil {
   865  			fmt.Fprintf(fgcc, "\ta.recv = recv;\n")
   866  		}
   867  		forFieldList(fntype.Params,
   868  			func(i int, aname string, atype ast.Expr) {
   869  				fmt.Fprintf(fgcc, "\ta.p%d = p%d;\n", i, i)
   870  			})
   871  		fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
   872  		fmt.Fprintf(fgcc, "\tcrosscall2(_cgoexp%s_%s, &a, %d, _cgo_ctxt);\n", cPrefix, exp.ExpName, off)
   873  		fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
   874  		fmt.Fprintf(fgcc, "\t_cgo_release_context(_cgo_ctxt);\n")
   875  		if gccResult != "void" {
   876  			if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
   877  				fmt.Fprintf(fgcc, "\treturn a.r0;\n")
   878  			} else {
   879  				forFieldList(fntype.Results,
   880  					func(i int, aname string, atype ast.Expr) {
   881  						fmt.Fprintf(fgcc, "\tr.r%d = a.r%d;\n", i, i)
   882  					})
   883  				fmt.Fprintf(fgcc, "\treturn r;\n")
   884  			}
   885  		}
   886  		fmt.Fprintf(fgcc, "}\n")
   887  
   888  		// Build the wrapper function compiled by cmd/compile.
   889  		goname := "_cgoexpwrap" + cPrefix + "_"
   890  		if fn.Recv != nil {
   891  			goname += fn.Recv.List[0].Names[0].Name + "_"
   892  		}
   893  		goname += exp.Func.Name.Name
   894  		fmt.Fprintf(fgo2, "//go:cgo_export_dynamic %s\n", exp.ExpName)
   895  		fmt.Fprintf(fgo2, "//go:linkname _cgoexp%s_%s _cgoexp%s_%s\n", cPrefix, exp.ExpName, cPrefix, exp.ExpName)
   896  		fmt.Fprintf(fgo2, "//go:cgo_export_static _cgoexp%s_%s\n", cPrefix, exp.ExpName)
   897  		fmt.Fprintf(fgo2, "//go:nosplit\n") // no split stack, so no use of m or g
   898  		fmt.Fprintf(fgo2, "//go:norace\n")  // must not have race detector calls inserted
   899  		fmt.Fprintf(fgo2, "func _cgoexp%s_%s(a unsafe.Pointer, n int32, ctxt uintptr) {\n", cPrefix, exp.ExpName)
   900  		fmt.Fprintf(fgo2, "\tfn := %s\n", goname)
   901  		// The indirect here is converting from a Go function pointer to a C function pointer.
   902  		fmt.Fprintf(fgo2, "\t_cgo_runtime_cgocallback(**(**unsafe.Pointer)(unsafe.Pointer(&fn)), a, uintptr(n), ctxt);\n")
   903  		fmt.Fprintf(fgo2, "}\n")
   904  
   905  		fmt.Fprintf(fm, "int _cgoexp%s_%s;\n", cPrefix, exp.ExpName)
   906  
   907  		// This code uses printer.Fprint, not conf.Fprint,
   908  		// because we don't want //line comments in the middle
   909  		// of the function types.
   910  		fmt.Fprintf(fgo2, "\n")
   911  		fmt.Fprintf(fgo2, "func %s(", goname)
   912  		comma := false
   913  		if fn.Recv != nil {
   914  			fmt.Fprintf(fgo2, "recv ")
   915  			printer.Fprint(fgo2, fset, fn.Recv.List[0].Type)
   916  			comma = true
   917  		}
   918  		forFieldList(fntype.Params,
   919  			func(i int, aname string, atype ast.Expr) {
   920  				if comma {
   921  					fmt.Fprintf(fgo2, ", ")
   922  				}
   923  				fmt.Fprintf(fgo2, "p%d ", i)
   924  				printer.Fprint(fgo2, fset, atype)
   925  				comma = true
   926  			})
   927  		fmt.Fprintf(fgo2, ")")
   928  		if gccResult != "void" {
   929  			fmt.Fprint(fgo2, " (")
   930  			forFieldList(fntype.Results,
   931  				func(i int, aname string, atype ast.Expr) {
   932  					if i > 0 {
   933  						fmt.Fprint(fgo2, ", ")
   934  					}
   935  					fmt.Fprintf(fgo2, "r%d ", i)
   936  					printer.Fprint(fgo2, fset, atype)
   937  				})
   938  			fmt.Fprint(fgo2, ")")
   939  		}
   940  		fmt.Fprint(fgo2, " {\n")
   941  		if gccResult == "void" {
   942  			fmt.Fprint(fgo2, "\t")
   943  		} else {
   944  			// Verify that any results don't contain any
   945  			// Go pointers.
   946  			addedDefer := false
   947  			forFieldList(fntype.Results,
   948  				func(i int, aname string, atype ast.Expr) {
   949  					if !p.hasPointer(nil, atype, false) {
   950  						return
   951  					}
   952  					if !addedDefer {
   953  						fmt.Fprint(fgo2, "\tdefer func() {\n")
   954  						addedDefer = true
   955  					}
   956  					fmt.Fprintf(fgo2, "\t\t_cgoCheckResult(r%d)\n", i)
   957  				})
   958  			if addedDefer {
   959  				fmt.Fprint(fgo2, "\t}()\n")
   960  			}
   961  			fmt.Fprint(fgo2, "\treturn ")
   962  		}
   963  		if fn.Recv != nil {
   964  			fmt.Fprintf(fgo2, "recv.")
   965  		}
   966  		fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
   967  		forFieldList(fntype.Params,
   968  			func(i int, aname string, atype ast.Expr) {
   969  				if i > 0 {
   970  					fmt.Fprint(fgo2, ", ")
   971  				}
   972  				fmt.Fprintf(fgo2, "p%d", i)
   973  			})
   974  		fmt.Fprint(fgo2, ")\n")
   975  		fmt.Fprint(fgo2, "}\n")
   976  	}
   977  
   978  	fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
   979  }
   980  
   981  // Write out the C header allowing C code to call exported gccgo functions.
   982  func (p *Package) writeGccgoExports(fgo2, fm, fgcc, fgcch io.Writer) {
   983  	gccgoSymbolPrefix := p.gccgoSymbolPrefix()
   984  
   985  	p.writeExportHeader(fgcch)
   986  
   987  	fmt.Fprintf(fgcc, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
   988  	fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n")
   989  
   990  	fmt.Fprintf(fgcc, "%s\n", gccgoExportFileProlog)
   991  	fmt.Fprintf(fgcc, "%s\n", tsanProlog)
   992  	fmt.Fprintf(fgcc, "%s\n", msanProlog)
   993  
   994  	for _, exp := range p.ExpFunc {
   995  		fn := exp.Func
   996  		fntype := fn.Type
   997  
   998  		cdeclBuf := new(bytes.Buffer)
   999  		resultCount := 0
  1000  		forFieldList(fntype.Results,
  1001  			func(i int, aname string, atype ast.Expr) { resultCount++ })
  1002  		switch resultCount {
  1003  		case 0:
  1004  			fmt.Fprintf(cdeclBuf, "void")
  1005  		case 1:
  1006  			forFieldList(fntype.Results,
  1007  				func(i int, aname string, atype ast.Expr) {
  1008  					t := p.cgoType(atype)
  1009  					fmt.Fprintf(cdeclBuf, "%s", t.C)
  1010  				})
  1011  		default:
  1012  			// Declare a result struct.
  1013  			fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
  1014  			fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName)
  1015  			forFieldList(fntype.Results,
  1016  				func(i int, aname string, atype ast.Expr) {
  1017  					t := p.cgoType(atype)
  1018  					fmt.Fprintf(fgcch, "\t%s r%d;", t.C, i)
  1019  					if len(aname) > 0 {
  1020  						fmt.Fprintf(fgcch, " /* %s */", aname)
  1021  					}
  1022  					fmt.Fprint(fgcch, "\n")
  1023  				})
  1024  			fmt.Fprintf(fgcch, "};\n")
  1025  			fmt.Fprintf(cdeclBuf, "struct %s_return", exp.ExpName)
  1026  		}
  1027  
  1028  		cRet := cdeclBuf.String()
  1029  
  1030  		cdeclBuf = new(bytes.Buffer)
  1031  		fmt.Fprintf(cdeclBuf, "(")
  1032  		if fn.Recv != nil {
  1033  			fmt.Fprintf(cdeclBuf, "%s recv", p.cgoType(fn.Recv.List[0].Type).C.String())
  1034  		}
  1035  		// Function parameters.
  1036  		forFieldList(fntype.Params,
  1037  			func(i int, aname string, atype ast.Expr) {
  1038  				if i > 0 || fn.Recv != nil {
  1039  					fmt.Fprintf(cdeclBuf, ", ")
  1040  				}
  1041  				t := p.cgoType(atype)
  1042  				fmt.Fprintf(cdeclBuf, "%s p%d", t.C, i)
  1043  			})
  1044  		fmt.Fprintf(cdeclBuf, ")")
  1045  		cParams := cdeclBuf.String()
  1046  
  1047  		if len(exp.Doc) > 0 {
  1048  			fmt.Fprintf(fgcch, "\n%s", exp.Doc)
  1049  		}
  1050  
  1051  		fmt.Fprintf(fgcch, "extern %s %s%s;\n", cRet, exp.ExpName, cParams)
  1052  
  1053  		// We need to use a name that will be exported by the
  1054  		// Go code; otherwise gccgo will make it static and we
  1055  		// will not be able to link against it from the C
  1056  		// code.
  1057  		goName := "Cgoexp_" + exp.ExpName
  1058  		fmt.Fprintf(fgcc, `extern %s %s %s __asm__("%s.%s");`, cRet, goName, cParams, gccgoSymbolPrefix, goName)
  1059  		fmt.Fprint(fgcc, "\n")
  1060  
  1061  		fmt.Fprint(fgcc, "\nCGO_NO_SANITIZE_THREAD\n")
  1062  		fmt.Fprintf(fgcc, "%s %s %s {\n", cRet, exp.ExpName, cParams)
  1063  		if resultCount > 0 {
  1064  			fmt.Fprintf(fgcc, "\t%s r;\n", cRet)
  1065  		}
  1066  		fmt.Fprintf(fgcc, "\tif(_cgo_wait_runtime_init_done)\n")
  1067  		fmt.Fprintf(fgcc, "\t\t_cgo_wait_runtime_init_done();\n")
  1068  		fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
  1069  		fmt.Fprint(fgcc, "\t")
  1070  		if resultCount > 0 {
  1071  			fmt.Fprint(fgcc, "r = ")
  1072  		}
  1073  		fmt.Fprintf(fgcc, "%s(", goName)
  1074  		if fn.Recv != nil {
  1075  			fmt.Fprint(fgcc, "recv")
  1076  		}
  1077  		forFieldList(fntype.Params,
  1078  			func(i int, aname string, atype ast.Expr) {
  1079  				if i > 0 || fn.Recv != nil {
  1080  					fmt.Fprintf(fgcc, ", ")
  1081  				}
  1082  				fmt.Fprintf(fgcc, "p%d", i)
  1083  			})
  1084  		fmt.Fprint(fgcc, ");\n")
  1085  		fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
  1086  		if resultCount > 0 {
  1087  			fmt.Fprint(fgcc, "\treturn r;\n")
  1088  		}
  1089  		fmt.Fprint(fgcc, "}\n")
  1090  
  1091  		// Dummy declaration for _cgo_main.c
  1092  		fmt.Fprintf(fm, `char %s[1] __asm__("%s.%s");`, goName, gccgoSymbolPrefix, goName)
  1093  		fmt.Fprint(fm, "\n")
  1094  
  1095  		// For gccgo we use a wrapper function in Go, in order
  1096  		// to call CgocallBack and CgocallBackDone.
  1097  
  1098  		// This code uses printer.Fprint, not conf.Fprint,
  1099  		// because we don't want //line comments in the middle
  1100  		// of the function types.
  1101  		fmt.Fprint(fgo2, "\n")
  1102  		fmt.Fprintf(fgo2, "func %s(", goName)
  1103  		if fn.Recv != nil {
  1104  			fmt.Fprint(fgo2, "recv ")
  1105  			printer.Fprint(fgo2, fset, fn.Recv.List[0].Type)
  1106  		}
  1107  		forFieldList(fntype.Params,
  1108  			func(i int, aname string, atype ast.Expr) {
  1109  				if i > 0 || fn.Recv != nil {
  1110  					fmt.Fprintf(fgo2, ", ")
  1111  				}
  1112  				fmt.Fprintf(fgo2, "p%d ", i)
  1113  				printer.Fprint(fgo2, fset, atype)
  1114  			})
  1115  		fmt.Fprintf(fgo2, ")")
  1116  		if resultCount > 0 {
  1117  			fmt.Fprintf(fgo2, " (")
  1118  			forFieldList(fntype.Results,
  1119  				func(i int, aname string, atype ast.Expr) {
  1120  					if i > 0 {
  1121  						fmt.Fprint(fgo2, ", ")
  1122  					}
  1123  					printer.Fprint(fgo2, fset, atype)
  1124  				})
  1125  			fmt.Fprint(fgo2, ")")
  1126  		}
  1127  		fmt.Fprint(fgo2, " {\n")
  1128  		fmt.Fprint(fgo2, "\tsyscall.CgocallBack()\n")
  1129  		fmt.Fprint(fgo2, "\tdefer syscall.CgocallBackDone()\n")
  1130  		fmt.Fprint(fgo2, "\t")
  1131  		if resultCount > 0 {
  1132  			fmt.Fprint(fgo2, "return ")
  1133  		}
  1134  		if fn.Recv != nil {
  1135  			fmt.Fprint(fgo2, "recv.")
  1136  		}
  1137  		fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
  1138  		forFieldList(fntype.Params,
  1139  			func(i int, aname string, atype ast.Expr) {
  1140  				if i > 0 {
  1141  					fmt.Fprint(fgo2, ", ")
  1142  				}
  1143  				fmt.Fprintf(fgo2, "p%d", i)
  1144  			})
  1145  		fmt.Fprint(fgo2, ")\n")
  1146  		fmt.Fprint(fgo2, "}\n")
  1147  	}
  1148  
  1149  	fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
  1150  }
  1151  
  1152  // writeExportHeader writes out the start of the _cgo_export.h file.
  1153  func (p *Package) writeExportHeader(fgcch io.Writer) {
  1154  	fmt.Fprintf(fgcch, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
  1155  	pkg := *importPath
  1156  	if pkg == "" {
  1157  		pkg = p.PackagePath
  1158  	}
  1159  	fmt.Fprintf(fgcch, "/* package %s */\n\n", pkg)
  1160  	fmt.Fprintf(fgcch, "%s\n", builtinExportProlog)
  1161  
  1162  	// Remove absolute paths from #line comments in the preamble.
  1163  	// They aren't useful for people using the header file,
  1164  	// and they mean that the header files change based on the
  1165  	// exact location of GOPATH.
  1166  	re := regexp.MustCompile(`(?m)^(#line\s+[0-9]+\s+")[^"]*[/\\]([^"]*")`)
  1167  	preamble := re.ReplaceAllString(p.Preamble, "$1$2")
  1168  
  1169  	fmt.Fprintf(fgcch, "/* Start of preamble from import \"C\" comments.  */\n\n")
  1170  	fmt.Fprintf(fgcch, "%s\n", preamble)
  1171  	fmt.Fprintf(fgcch, "\n/* End of preamble from import \"C\" comments.  */\n\n")
  1172  
  1173  	fmt.Fprintf(fgcch, "%s\n", p.gccExportHeaderProlog())
  1174  }
  1175  
  1176  // Return the package prefix when using gccgo.
  1177  func (p *Package) gccgoSymbolPrefix() string {
  1178  	if !*gccgo {
  1179  		return ""
  1180  	}
  1181  
  1182  	clean := func(r rune) rune {
  1183  		switch {
  1184  		case 'A' <= r && r <= 'Z', 'a' <= r && r <= 'z',
  1185  			'0' <= r && r <= '9':
  1186  			return r
  1187  		}
  1188  		return '_'
  1189  	}
  1190  
  1191  	if *gccgopkgpath != "" {
  1192  		return strings.Map(clean, *gccgopkgpath)
  1193  	}
  1194  	if *gccgoprefix == "" && p.PackageName == "main" {
  1195  		return "main"
  1196  	}
  1197  	prefix := strings.Map(clean, *gccgoprefix)
  1198  	if prefix == "" {
  1199  		prefix = "go"
  1200  	}
  1201  	return prefix + "." + p.PackageName
  1202  }
  1203  
  1204  // Call a function for each entry in an ast.FieldList, passing the
  1205  // index into the list, the name if any, and the type.
  1206  func forFieldList(fl *ast.FieldList, fn func(int, string, ast.Expr)) {
  1207  	if fl == nil {
  1208  		return
  1209  	}
  1210  	i := 0
  1211  	for _, r := range fl.List {
  1212  		if r.Names == nil {
  1213  			fn(i, "", r.Type)
  1214  			i++
  1215  		} else {
  1216  			for _, n := range r.Names {
  1217  				fn(i, n.Name, r.Type)
  1218  				i++
  1219  			}
  1220  		}
  1221  	}
  1222  }
  1223  
  1224  func c(repr string, args ...interface{}) *TypeRepr {
  1225  	return &TypeRepr{repr, args}
  1226  }
  1227  
  1228  // Map predeclared Go types to Type.
  1229  var goTypes = map[string]*Type{
  1230  	"bool":       {Size: 1, Align: 1, C: c("GoUint8")},
  1231  	"byte":       {Size: 1, Align: 1, C: c("GoUint8")},
  1232  	"int":        {Size: 0, Align: 0, C: c("GoInt")},
  1233  	"uint":       {Size: 0, Align: 0, C: c("GoUint")},
  1234  	"rune":       {Size: 4, Align: 4, C: c("GoInt32")},
  1235  	"int8":       {Size: 1, Align: 1, C: c("GoInt8")},
  1236  	"uint8":      {Size: 1, Align: 1, C: c("GoUint8")},
  1237  	"int16":      {Size: 2, Align: 2, C: c("GoInt16")},
  1238  	"uint16":     {Size: 2, Align: 2, C: c("GoUint16")},
  1239  	"int32":      {Size: 4, Align: 4, C: c("GoInt32")},
  1240  	"uint32":     {Size: 4, Align: 4, C: c("GoUint32")},
  1241  	"int64":      {Size: 8, Align: 8, C: c("GoInt64")},
  1242  	"uint64":     {Size: 8, Align: 8, C: c("GoUint64")},
  1243  	"float32":    {Size: 4, Align: 4, C: c("GoFloat32")},
  1244  	"float64":    {Size: 8, Align: 8, C: c("GoFloat64")},
  1245  	"complex64":  {Size: 8, Align: 4, C: c("GoComplex64")},
  1246  	"complex128": {Size: 16, Align: 8, C: c("GoComplex128")},
  1247  }
  1248  
  1249  // Map an ast type to a Type.
  1250  func (p *Package) cgoType(e ast.Expr) *Type {
  1251  	switch t := e.(type) {
  1252  	case *ast.StarExpr:
  1253  		x := p.cgoType(t.X)
  1254  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("%s*", x.C)}
  1255  	case *ast.ArrayType:
  1256  		if t.Len == nil {
  1257  			// Slice: pointer, len, cap.
  1258  			return &Type{Size: p.PtrSize * 3, Align: p.PtrSize, C: c("GoSlice")}
  1259  		}
  1260  		// Non-slice array types are not supported.
  1261  	case *ast.StructType:
  1262  		// Not supported.
  1263  	case *ast.FuncType:
  1264  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
  1265  	case *ast.InterfaceType:
  1266  		return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
  1267  	case *ast.MapType:
  1268  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoMap")}
  1269  	case *ast.ChanType:
  1270  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoChan")}
  1271  	case *ast.Ident:
  1272  		// Look up the type in the top level declarations.
  1273  		// TODO: Handle types defined within a function.
  1274  		for _, d := range p.Decl {
  1275  			gd, ok := d.(*ast.GenDecl)
  1276  			if !ok || gd.Tok != token.TYPE {
  1277  				continue
  1278  			}
  1279  			for _, spec := range gd.Specs {
  1280  				ts, ok := spec.(*ast.TypeSpec)
  1281  				if !ok {
  1282  					continue
  1283  				}
  1284  				if ts.Name.Name == t.Name {
  1285  					return p.cgoType(ts.Type)
  1286  				}
  1287  			}
  1288  		}
  1289  		if def := typedef[t.Name]; def != nil {
  1290  			return def
  1291  		}
  1292  		if t.Name == "uintptr" {
  1293  			return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoUintptr")}
  1294  		}
  1295  		if t.Name == "string" {
  1296  			// The string data is 1 pointer + 1 (pointer-sized) int.
  1297  			return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoString")}
  1298  		}
  1299  		if t.Name == "error" {
  1300  			return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
  1301  		}
  1302  		if r, ok := goTypes[t.Name]; ok {
  1303  			if r.Size == 0 { // int or uint
  1304  				rr := new(Type)
  1305  				*rr = *r
  1306  				rr.Size = p.IntSize
  1307  				rr.Align = p.IntSize
  1308  				r = rr
  1309  			}
  1310  			if r.Align > p.PtrSize {
  1311  				r.Align = p.PtrSize
  1312  			}
  1313  			return r
  1314  		}
  1315  		error_(e.Pos(), "unrecognized Go type %s", t.Name)
  1316  		return &Type{Size: 4, Align: 4, C: c("int")}
  1317  	case *ast.SelectorExpr:
  1318  		id, ok := t.X.(*ast.Ident)
  1319  		if ok && id.Name == "unsafe" && t.Sel.Name == "Pointer" {
  1320  			return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
  1321  		}
  1322  	}
  1323  	error_(e.Pos(), "Go type not supported in export: %s", gofmt(e))
  1324  	return &Type{Size: 4, Align: 4, C: c("int")}
  1325  }
  1326  
  1327  const gccProlog = `
  1328  #line 1 "cgo-gcc-prolog"
  1329  /*
  1330    If x and y are not equal, the type will be invalid
  1331    (have a negative array count) and an inscrutable error will come
  1332    out of the compiler and hopefully mention "name".
  1333  */
  1334  #define __cgo_compile_assert_eq(x, y, name) typedef char name[(x-y)*(x-y)*-2+1];
  1335  
  1336  /* Check at compile time that the sizes we use match our expectations. */
  1337  #define __cgo_size_assert(t, n) __cgo_compile_assert_eq(sizeof(t), n, _cgo_sizeof_##t##_is_not_##n)
  1338  
  1339  __cgo_size_assert(char, 1)
  1340  __cgo_size_assert(short, 2)
  1341  __cgo_size_assert(int, 4)
  1342  typedef long long __cgo_long_long;
  1343  __cgo_size_assert(__cgo_long_long, 8)
  1344  __cgo_size_assert(float, 4)
  1345  __cgo_size_assert(double, 8)
  1346  
  1347  extern char* _cgo_topofstack(void);
  1348  
  1349  /* We use packed structs, but they are always aligned.  */
  1350  /* The pragmas and address-of-packed-member are not recognized as warning groups in clang 3.4.1, so ignore unknown pragmas first. */
  1351  
  1352  #pragma GCC diagnostic ignored "-Wunknown-pragmas"
  1353  #pragma GCC diagnostic ignored "-Wpragmas"
  1354  #pragma GCC diagnostic ignored "-Waddress-of-packed-member"
  1355  
  1356  #include <errno.h>
  1357  #include <string.h>
  1358  `
  1359  
  1360  // Prologue defining TSAN functions in C.
  1361  const noTsanProlog = `
  1362  #define CGO_NO_SANITIZE_THREAD
  1363  #define _cgo_tsan_acquire()
  1364  #define _cgo_tsan_release()
  1365  `
  1366  
  1367  // This must match the TSAN code in runtime/cgo/libcgo.h.
  1368  // This is used when the code is built with the C/C++ Thread SANitizer,
  1369  // which is not the same as the Go race detector.
  1370  // __tsan_acquire tells TSAN that we are acquiring a lock on a variable,
  1371  // in this case _cgo_sync. __tsan_release releases the lock.
  1372  // (There is no actual lock, we are just telling TSAN that there is.)
  1373  //
  1374  // When we call from Go to C we call _cgo_tsan_acquire.
  1375  // When the C function returns we call _cgo_tsan_release.
  1376  // Similarly, when C calls back into Go we call _cgo_tsan_release
  1377  // and then call _cgo_tsan_acquire when we return to C.
  1378  // These calls tell TSAN that there is a serialization point at the C call.
  1379  //
  1380  // This is necessary because TSAN, which is a C/C++ tool, can not see
  1381  // the synchronization in the Go code. Without these calls, when
  1382  // multiple goroutines call into C code, TSAN does not understand
  1383  // that the calls are properly synchronized on the Go side.
  1384  //
  1385  // To be clear, if the calls are not properly synchronized on the Go side,
  1386  // we will be hiding races. But when using TSAN on mixed Go C/C++ code
  1387  // it is more important to avoid false positives, which reduce confidence
  1388  // in the tool, than to avoid false negatives.
  1389  const yesTsanProlog = `
  1390  #line 1 "cgo-tsan-prolog"
  1391  #define CGO_NO_SANITIZE_THREAD __attribute__ ((no_sanitize_thread))
  1392  
  1393  long long _cgo_sync __attribute__ ((common));
  1394  
  1395  extern void __tsan_acquire(void*);
  1396  extern void __tsan_release(void*);
  1397  
  1398  __attribute__ ((unused))
  1399  static void _cgo_tsan_acquire() {
  1400  	__tsan_acquire(&_cgo_sync);
  1401  }
  1402  
  1403  __attribute__ ((unused))
  1404  static void _cgo_tsan_release() {
  1405  	__tsan_release(&_cgo_sync);
  1406  }
  1407  `
  1408  
  1409  // Set to yesTsanProlog if we see -fsanitize=thread in the flags for gcc.
  1410  var tsanProlog = noTsanProlog
  1411  
  1412  // noMsanProlog is a prologue defining an MSAN function in C.
  1413  // This is used when not compiling with -fsanitize=memory.
  1414  const noMsanProlog = `
  1415  #define _cgo_msan_write(addr, sz)
  1416  `
  1417  
  1418  // yesMsanProlog is a prologue defining an MSAN function in C.
  1419  // This is used when compiling with -fsanitize=memory.
  1420  // See the comment above where _cgo_msan_write is called.
  1421  const yesMsanProlog = `
  1422  extern void __msan_unpoison(const volatile void *, size_t);
  1423  
  1424  #define _cgo_msan_write(addr, sz) __msan_unpoison((addr), (sz))
  1425  `
  1426  
  1427  // msanProlog is set to yesMsanProlog if we see -fsanitize=memory in the flags
  1428  // for the C compiler.
  1429  var msanProlog = noMsanProlog
  1430  
  1431  const builtinProlog = `
  1432  #line 1 "cgo-builtin-prolog"
  1433  #include <stddef.h> /* for ptrdiff_t and size_t below */
  1434  
  1435  /* Define intgo when compiling with GCC.  */
  1436  typedef ptrdiff_t intgo;
  1437  
  1438  typedef struct { const char *p; intgo n; } _GoString_;
  1439  typedef struct { char *p; intgo n; intgo c; } _GoBytes_;
  1440  _GoString_ GoString(char *p);
  1441  _GoString_ GoStringN(char *p, int l);
  1442  _GoBytes_ GoBytes(void *p, int n);
  1443  char *CString(_GoString_);
  1444  void *CBytes(_GoBytes_);
  1445  void *_CMalloc(size_t);
  1446  
  1447  __attribute__ ((unused))
  1448  static size_t _GoStringLen(_GoString_ s) { return s.n; }
  1449  
  1450  __attribute__ ((unused))
  1451  static const char *_GoStringPtr(_GoString_ s) { return s.p; }
  1452  `
  1453  
  1454  const goProlog = `
  1455  //go:linkname _cgo_runtime_cgocall runtime.cgocall
  1456  func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
  1457  
  1458  //go:linkname _cgo_runtime_cgocallback runtime.cgocallback
  1459  func _cgo_runtime_cgocallback(unsafe.Pointer, unsafe.Pointer, uintptr, uintptr)
  1460  
  1461  //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
  1462  func _cgoCheckPointer(interface{}, ...interface{})
  1463  
  1464  //go:linkname _cgoCheckResult runtime.cgoCheckResult
  1465  func _cgoCheckResult(interface{})
  1466  `
  1467  
  1468  const gccgoGoProlog = `
  1469  func _cgoCheckPointer(interface{}, ...interface{})
  1470  
  1471  func _cgoCheckResult(interface{})
  1472  `
  1473  
  1474  const goStringDef = `
  1475  //go:linkname _cgo_runtime_gostring runtime.gostring
  1476  func _cgo_runtime_gostring(*_Ctype_char) string
  1477  
  1478  func _Cfunc_GoString(p *_Ctype_char) string {
  1479  	return _cgo_runtime_gostring(p)
  1480  }
  1481  `
  1482  
  1483  const goStringNDef = `
  1484  //go:linkname _cgo_runtime_gostringn runtime.gostringn
  1485  func _cgo_runtime_gostringn(*_Ctype_char, int) string
  1486  
  1487  func _Cfunc_GoStringN(p *_Ctype_char, l _Ctype_int) string {
  1488  	return _cgo_runtime_gostringn(p, int(l))
  1489  }
  1490  `
  1491  
  1492  const goBytesDef = `
  1493  //go:linkname _cgo_runtime_gobytes runtime.gobytes
  1494  func _cgo_runtime_gobytes(unsafe.Pointer, int) []byte
  1495  
  1496  func _Cfunc_GoBytes(p unsafe.Pointer, l _Ctype_int) []byte {
  1497  	return _cgo_runtime_gobytes(p, int(l))
  1498  }
  1499  `
  1500  
  1501  const cStringDef = `
  1502  func _Cfunc_CString(s string) *_Ctype_char {
  1503  	p := _cgo_cmalloc(uint64(len(s)+1))
  1504  	pp := (*[1<<30]byte)(p)
  1505  	copy(pp[:], s)
  1506  	pp[len(s)] = 0
  1507  	return (*_Ctype_char)(p)
  1508  }
  1509  `
  1510  
  1511  const cBytesDef = `
  1512  func _Cfunc_CBytes(b []byte) unsafe.Pointer {
  1513  	p := _cgo_cmalloc(uint64(len(b)))
  1514  	pp := (*[1<<30]byte)(p)
  1515  	copy(pp[:], b)
  1516  	return p
  1517  }
  1518  `
  1519  
  1520  const cMallocDef = `
  1521  func _Cfunc__CMalloc(n _Ctype_size_t) unsafe.Pointer {
  1522  	return _cgo_cmalloc(uint64(n))
  1523  }
  1524  `
  1525  
  1526  var builtinDefs = map[string]string{
  1527  	"GoString":  goStringDef,
  1528  	"GoStringN": goStringNDef,
  1529  	"GoBytes":   goBytesDef,
  1530  	"CString":   cStringDef,
  1531  	"CBytes":    cBytesDef,
  1532  	"_CMalloc":  cMallocDef,
  1533  }
  1534  
  1535  // Definitions for C.malloc in Go and in C. We define it ourselves
  1536  // since we call it from functions we define, such as C.CString.
  1537  // Also, we have historically ensured that C.malloc does not return
  1538  // nil even for an allocation of 0.
  1539  
  1540  const cMallocDefGo = `
  1541  //go:cgo_import_static _cgoPREFIX_Cfunc__Cmalloc
  1542  //go:linkname __cgofn__cgoPREFIX_Cfunc__Cmalloc _cgoPREFIX_Cfunc__Cmalloc
  1543  var __cgofn__cgoPREFIX_Cfunc__Cmalloc byte
  1544  var _cgoPREFIX_Cfunc__Cmalloc = unsafe.Pointer(&__cgofn__cgoPREFIX_Cfunc__Cmalloc)
  1545  
  1546  //go:linkname runtime_throw runtime.throw
  1547  func runtime_throw(string)
  1548  
  1549  //go:cgo_unsafe_args
  1550  func _cgo_cmalloc(p0 uint64) (r1 unsafe.Pointer) {
  1551  	_cgo_runtime_cgocall(_cgoPREFIX_Cfunc__Cmalloc, uintptr(unsafe.Pointer(&p0)))
  1552  	if r1 == nil {
  1553  		runtime_throw("runtime: C malloc failed")
  1554  	}
  1555  	return
  1556  }
  1557  `
  1558  
  1559  // cMallocDefC defines the C version of C.malloc for the gc compiler.
  1560  // It is defined here because C.CString and friends need a definition.
  1561  // We define it by hand, rather than simply inventing a reference to
  1562  // C.malloc, because <stdlib.h> may not have been included.
  1563  // This is approximately what writeOutputFunc would generate, but
  1564  // skips the cgo_topofstack code (which is only needed if the C code
  1565  // calls back into Go). This also avoids returning nil for an
  1566  // allocation of 0 bytes.
  1567  const cMallocDefC = `
  1568  CGO_NO_SANITIZE_THREAD
  1569  void _cgoPREFIX_Cfunc__Cmalloc(void *v) {
  1570  	struct {
  1571  		unsigned long long p0;
  1572  		void *r1;
  1573  	} PACKED *a = v;
  1574  	void *ret;
  1575  	_cgo_tsan_acquire();
  1576  	ret = malloc(a->p0);
  1577  	if (ret == 0 && a->p0 == 0) {
  1578  		ret = malloc(1);
  1579  	}
  1580  	a->r1 = ret;
  1581  	_cgo_tsan_release();
  1582  }
  1583  `
  1584  
  1585  func (p *Package) cPrologGccgo() string {
  1586  	return strings.Replace(strings.Replace(cPrologGccgo, "PREFIX", cPrefix, -1),
  1587  		"GCCGOSYMBOLPREF", p.gccgoSymbolPrefix(), -1)
  1588  }
  1589  
  1590  const cPrologGccgo = `
  1591  #line 1 "cgo-c-prolog-gccgo"
  1592  #include <stdint.h>
  1593  #include <stdlib.h>
  1594  #include <string.h>
  1595  
  1596  typedef unsigned char byte;
  1597  typedef intptr_t intgo;
  1598  
  1599  struct __go_string {
  1600  	const unsigned char *__data;
  1601  	intgo __length;
  1602  };
  1603  
  1604  typedef struct __go_open_array {
  1605  	void* __values;
  1606  	intgo __count;
  1607  	intgo __capacity;
  1608  } Slice;
  1609  
  1610  struct __go_string __go_byte_array_to_string(const void* p, intgo len);
  1611  struct __go_open_array __go_string_to_byte_array (struct __go_string str);
  1612  
  1613  const char *_cgoPREFIX_Cfunc_CString(struct __go_string s) {
  1614  	char *p = malloc(s.__length+1);
  1615  	memmove(p, s.__data, s.__length);
  1616  	p[s.__length] = 0;
  1617  	return p;
  1618  }
  1619  
  1620  void *_cgoPREFIX_Cfunc_CBytes(struct __go_open_array b) {
  1621  	char *p = malloc(b.__count);
  1622  	memmove(p, b.__values, b.__count);
  1623  	return p;
  1624  }
  1625  
  1626  struct __go_string _cgoPREFIX_Cfunc_GoString(char *p) {
  1627  	intgo len = (p != NULL) ? strlen(p) : 0;
  1628  	return __go_byte_array_to_string(p, len);
  1629  }
  1630  
  1631  struct __go_string _cgoPREFIX_Cfunc_GoStringN(char *p, int32_t n) {
  1632  	return __go_byte_array_to_string(p, n);
  1633  }
  1634  
  1635  Slice _cgoPREFIX_Cfunc_GoBytes(char *p, int32_t n) {
  1636  	struct __go_string s = { (const unsigned char *)p, n };
  1637  	return __go_string_to_byte_array(s);
  1638  }
  1639  
  1640  extern void runtime_throw(const char *);
  1641  void *_cgoPREFIX_Cfunc__CMalloc(size_t n) {
  1642          void *p = malloc(n);
  1643          if(p == NULL && n == 0)
  1644                  p = malloc(1);
  1645          if(p == NULL)
  1646                  runtime_throw("runtime: C malloc failed");
  1647          return p;
  1648  }
  1649  
  1650  struct __go_type_descriptor;
  1651  typedef struct __go_empty_interface {
  1652  	const struct __go_type_descriptor *__type_descriptor;
  1653  	void *__object;
  1654  } Eface;
  1655  
  1656  extern void runtimeCgoCheckPointer(Eface, Slice)
  1657  	__asm__("runtime.cgoCheckPointer")
  1658  	__attribute__((weak));
  1659  
  1660  extern void localCgoCheckPointer(Eface, Slice)
  1661  	__asm__("GCCGOSYMBOLPREF._cgoCheckPointer");
  1662  
  1663  void localCgoCheckPointer(Eface ptr, Slice args) {
  1664  	if(runtimeCgoCheckPointer) {
  1665  		runtimeCgoCheckPointer(ptr, args);
  1666  	}
  1667  }
  1668  
  1669  extern void runtimeCgoCheckResult(Eface)
  1670  	__asm__("runtime.cgoCheckResult")
  1671  	__attribute__((weak));
  1672  
  1673  extern void localCgoCheckResult(Eface)
  1674  	__asm__("GCCGOSYMBOLPREF._cgoCheckResult");
  1675  
  1676  void localCgoCheckResult(Eface val) {
  1677  	if(runtimeCgoCheckResult) {
  1678  		runtimeCgoCheckResult(val);
  1679  	}
  1680  }
  1681  `
  1682  
  1683  // builtinExportProlog is a shorter version of builtinProlog,
  1684  // to be put into the _cgo_export.h file.
  1685  // For historical reasons we can't use builtinProlog in _cgo_export.h,
  1686  // because _cgo_export.h defines GoString as a struct while builtinProlog
  1687  // defines it as a function. We don't change this to avoid unnecessarily
  1688  // breaking existing code.
  1689  const builtinExportProlog = `
  1690  #line 1 "cgo-builtin-prolog"
  1691  
  1692  #include <stddef.h> /* for ptrdiff_t below */
  1693  
  1694  #ifndef GO_CGO_EXPORT_PROLOGUE_H
  1695  #define GO_CGO_EXPORT_PROLOGUE_H
  1696  
  1697  typedef struct { const char *p; ptrdiff_t n; } _GoString_;
  1698  
  1699  #endif
  1700  `
  1701  
  1702  func (p *Package) gccExportHeaderProlog() string {
  1703  	return strings.Replace(gccExportHeaderProlog, "GOINTBITS", fmt.Sprint(8*p.IntSize), -1)
  1704  }
  1705  
  1706  const gccExportHeaderProlog = `
  1707  /* Start of boilerplate cgo prologue.  */
  1708  #line 1 "cgo-gcc-export-header-prolog"
  1709  
  1710  #ifndef GO_CGO_PROLOGUE_H
  1711  #define GO_CGO_PROLOGUE_H
  1712  
  1713  typedef signed char GoInt8;
  1714  typedef unsigned char GoUint8;
  1715  typedef short GoInt16;
  1716  typedef unsigned short GoUint16;
  1717  typedef int GoInt32;
  1718  typedef unsigned int GoUint32;
  1719  typedef long long GoInt64;
  1720  typedef unsigned long long GoUint64;
  1721  typedef GoIntGOINTBITS GoInt;
  1722  typedef GoUintGOINTBITS GoUint;
  1723  typedef __SIZE_TYPE__ GoUintptr;
  1724  typedef float GoFloat32;
  1725  typedef double GoFloat64;
  1726  typedef float _Complex GoComplex64;
  1727  typedef double _Complex GoComplex128;
  1728  
  1729  /*
  1730    static assertion to make sure the file is being used on architecture
  1731    at least with matching size of GoInt.
  1732  */
  1733  typedef char _check_for_GOINTBITS_bit_pointer_matching_GoInt[sizeof(void*)==GOINTBITS/8 ? 1:-1];
  1734  
  1735  typedef _GoString_ GoString;
  1736  typedef void *GoMap;
  1737  typedef void *GoChan;
  1738  typedef struct { void *t; void *v; } GoInterface;
  1739  typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
  1740  
  1741  #endif
  1742  
  1743  /* End of boilerplate cgo prologue.  */
  1744  
  1745  #ifdef __cplusplus
  1746  extern "C" {
  1747  #endif
  1748  `
  1749  
  1750  // gccExportHeaderEpilog goes at the end of the generated header file.
  1751  const gccExportHeaderEpilog = `
  1752  #ifdef __cplusplus
  1753  }
  1754  #endif
  1755  `
  1756  
  1757  // gccgoExportFileProlog is written to the _cgo_export.c file when
  1758  // using gccgo.
  1759  // We use weak declarations, and test the addresses, so that this code
  1760  // works with older versions of gccgo.
  1761  const gccgoExportFileProlog = `
  1762  #line 1 "cgo-gccgo-export-file-prolog"
  1763  extern _Bool runtime_iscgo __attribute__ ((weak));
  1764  
  1765  static void GoInit(void) __attribute__ ((constructor));
  1766  static void GoInit(void) {
  1767  	if(&runtime_iscgo)
  1768  		runtime_iscgo = 1;
  1769  }
  1770  
  1771  extern __SIZE_TYPE__ _cgo_wait_runtime_init_done() __attribute__ ((weak));
  1772  `
  1773  

View as plain text