github.com/guyezi/gofrontend@v0.0.0-20200228202240-7a62a49e62c0/libgo/go/cmd/cgo/out.go (about)

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