Source file src/cmd/cgo/out.go

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

View as plain text