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

View as plain text