Source file src/cmd/cgo/out.go

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

View as plain text