Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/cgo/out.go

Documentation: cmd/cgo

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

View as plain text