Black Lives Matter. Support the Equal Justice Initiative.

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

View as plain text