github.com/bir3/gocompiler@v0.3.205/src/cmd/cgo/out.go (about)

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