Help us shape the future of Go! Take the 2026 Go Developer Survey

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

View as plain text