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

View as plain text