Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/cgo/out.go

Documentation: cmd/cgo

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

View as plain text