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)\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  // exportParamName returns the value of param as it should be
   926  // displayed in a c header file. If param contains any non-ASCII
   927  // characters, this function will return the character p followed by
   928  // the value of position; otherwise, this function will return the
   929  // value of param.
   930  func exportParamName(param string, position int) string {
   931  	if param == "" {
   932  		return fmt.Sprintf("p%d", position)
   933  	}
   934  
   935  	pname := param
   936  
   937  	for i := 0; i < len(param); i++ {
   938  		if param[i] > unicode.MaxASCII {
   939  			pname = fmt.Sprintf("p%d", position)
   940  			break
   941  		}
   942  	}
   943  
   944  	return pname
   945  }
   946  
   947  // Write out the various stubs we need to support functions exported
   948  // from Go so that they are callable from C.
   949  func (p *Package) writeExports(fgo2, fm, fgcc, fgcch io.Writer) {
   950  	p.writeExportHeader(fgcch)
   951  
   952  	fmt.Fprintf(fgcc, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
   953  	fmt.Fprintf(fgcc, "#include <stdlib.h>\n")
   954  	fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n\n")
   955  
   956  	// We use packed structs, but they are always aligned.
   957  	// The pragmas and address-of-packed-member are only recognized as
   958  	// warning groups in clang 4.0+, so ignore unknown pragmas first.
   959  	fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wunknown-pragmas\"\n")
   960  	fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wpragmas\"\n")
   961  	fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Waddress-of-packed-member\"\n")
   962  	fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wunknown-warning-option\"\n")
   963  	fmt.Fprintf(fgcc, "#pragma GCC diagnostic ignored \"-Wunaligned-access\"\n")
   964  
   965  	fmt.Fprintf(fgcc, "extern void crosscall2(void (*fn)(void *), void *, int, size_t);\n")
   966  	fmt.Fprintf(fgcc, "extern size_t _cgo_wait_runtime_init_done(void);\n")
   967  	fmt.Fprintf(fgcc, "extern void _cgo_release_context(size_t);\n\n")
   968  	fmt.Fprintf(fgcc, "extern char* _cgo_topofstack(void);")
   969  	fmt.Fprintf(fgcc, "%s\n", tsanProlog)
   970  	fmt.Fprintf(fgcc, "%s\n", msanProlog)
   971  
   972  	for _, exp := range p.ExpFunc {
   973  		fn := exp.Func
   974  
   975  		// Construct a struct that will be used to communicate
   976  		// arguments from C to Go. The C and Go definitions
   977  		// just have to agree. The gcc struct will be compiled
   978  		// with __attribute__((packed)) so all padding must be
   979  		// accounted for explicitly.
   980  		var ctype strings.Builder
   981  		const start = "struct {\n"
   982  		ctype.WriteString(start)
   983  		gotype := new(bytes.Buffer)
   984  		fmt.Fprintf(gotype, "struct {\n")
   985  		off := int64(0)
   986  		npad := 0
   987  		// the align is at least 1 (for char)
   988  		maxAlign := int64(1)
   989  		argField := func(typ ast.Expr, namePat string, args ...any) {
   990  			name := fmt.Sprintf(namePat, args...)
   991  			t := p.cgoType(typ)
   992  			if off%t.Align != 0 {
   993  				pad := t.Align - off%t.Align
   994  				fmt.Fprintf(&ctype, "\t\tchar __pad%d[%d];\n", npad, pad)
   995  				off += pad
   996  				npad++
   997  			}
   998  			fmt.Fprintf(&ctype, "\t\t%s %s;\n", t.C, name)
   999  			fmt.Fprintf(gotype, "\t\t%s ", name)
  1000  			noSourceConf.Fprint(gotype, fset, typ)
  1001  			fmt.Fprintf(gotype, "\n")
  1002  			off += t.Size
  1003  			// keep track of the maximum alignment among all fields
  1004  			// so that we can align the struct correctly
  1005  			if t.Align > maxAlign {
  1006  				maxAlign = t.Align
  1007  			}
  1008  		}
  1009  		if fn.Recv != nil {
  1010  			argField(fn.Recv.List[0].Type, "recv")
  1011  		}
  1012  		fntype := fn.Type
  1013  		forFieldList(fntype.Params,
  1014  			func(i int, aname string, atype ast.Expr) {
  1015  				argField(atype, "p%d", i)
  1016  			})
  1017  		forFieldList(fntype.Results,
  1018  			func(i int, aname string, atype ast.Expr) {
  1019  				argField(atype, "r%d", i)
  1020  			})
  1021  		if ctype.Len() == len(start) {
  1022  			ctype.WriteString("\t\tchar unused;\n") // avoid empty struct
  1023  		}
  1024  		ctype.WriteString("\t}")
  1025  		fmt.Fprintf(gotype, "\t}")
  1026  
  1027  		// Get the return type of the wrapper function
  1028  		// compiled by gcc.
  1029  		gccResult := ""
  1030  		if fntype.Results == nil || len(fntype.Results.List) == 0 {
  1031  			gccResult = "void"
  1032  		} else if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
  1033  			gccResult = p.cgoType(fntype.Results.List[0].Type).C.String()
  1034  		} else {
  1035  			fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
  1036  			fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName)
  1037  			forFieldList(fntype.Results,
  1038  				func(i int, aname string, atype ast.Expr) {
  1039  					fmt.Fprintf(fgcch, "\t%s r%d;", p.cgoType(atype).C, i)
  1040  					if len(aname) > 0 {
  1041  						fmt.Fprintf(fgcch, " /* %s */", aname)
  1042  					}
  1043  					fmt.Fprint(fgcch, "\n")
  1044  				})
  1045  			fmt.Fprintf(fgcch, "};\n")
  1046  			gccResult = "struct " + exp.ExpName + "_return"
  1047  		}
  1048  
  1049  		// Build the wrapper function compiled by gcc.
  1050  		var s strings.Builder
  1051  		fmt.Fprintf(&s, "%s %s(", gccResult, exp.ExpName)
  1052  		if fn.Recv != nil {
  1053  			s.WriteString(p.cgoType(fn.Recv.List[0].Type).C.String())
  1054  			s.WriteString(" recv")
  1055  		}
  1056  
  1057  		if len(fntype.Params.List) > 0 {
  1058  			forFieldList(fntype.Params,
  1059  				func(i int, aname string, atype ast.Expr) {
  1060  					if i > 0 || fn.Recv != nil {
  1061  						s.WriteString(", ")
  1062  					}
  1063  					fmt.Fprintf(&s, "%s %s", p.cgoType(atype).C, exportParamName(aname, i))
  1064  				})
  1065  		} else {
  1066  			s.WriteString("void")
  1067  		}
  1068  		s.WriteByte(')')
  1069  
  1070  		if len(exp.Doc) > 0 {
  1071  			fmt.Fprintf(fgcch, "\n%s", exp.Doc)
  1072  			if !strings.HasSuffix(exp.Doc, "\n") {
  1073  				fmt.Fprint(fgcch, "\n")
  1074  			}
  1075  		}
  1076  		fmt.Fprintf(fgcch, "extern %s;\n", s.String())
  1077  
  1078  		fmt.Fprintf(fgcc, "extern void _cgoexp%s_%s(void *);\n", cPrefix, exp.ExpName)
  1079  		fmt.Fprintf(fgcc, "\nCGO_NO_SANITIZE_THREAD")
  1080  		fmt.Fprintf(fgcc, "\n%s\n", s.String())
  1081  		fmt.Fprintf(fgcc, "{\n")
  1082  		fmt.Fprintf(fgcc, "\tsize_t _cgo_ctxt = _cgo_wait_runtime_init_done();\n")
  1083  		// The results part of the argument structure must be
  1084  		// initialized to 0 so the write barriers generated by
  1085  		// the assignments to these fields in Go are safe.
  1086  		//
  1087  		// We use a local static variable to get the zeroed
  1088  		// value of the argument type. This avoids including
  1089  		// string.h for memset, and is also robust to C++
  1090  		// types with constructors. Both GCC and LLVM optimize
  1091  		// this into just zeroing _cgo_a.
  1092  		//
  1093  		// The struct should be aligned to the maximum alignment
  1094  		// of any of its fields. This to avoid alignment
  1095  		// issues.
  1096  		fmt.Fprintf(fgcc, "\ttypedef %s %v __attribute__((aligned(%d))) _cgo_argtype;\n", ctype.String(), p.packedAttribute(), maxAlign)
  1097  		fmt.Fprintf(fgcc, "\tstatic _cgo_argtype _cgo_zero;\n")
  1098  		fmt.Fprintf(fgcc, "\t_cgo_argtype _cgo_a = _cgo_zero;\n")
  1099  		if gccResult != "void" && (len(fntype.Results.List) > 1 || len(fntype.Results.List[0].Names) > 1) {
  1100  			fmt.Fprintf(fgcc, "\t%s r;\n", gccResult)
  1101  		}
  1102  		if fn.Recv != nil {
  1103  			fmt.Fprintf(fgcc, "\t_cgo_a.recv = recv;\n")
  1104  		}
  1105  		forFieldList(fntype.Params,
  1106  			func(i int, aname string, atype ast.Expr) {
  1107  				fmt.Fprintf(fgcc, "\t_cgo_a.p%d = %s;\n", i, exportParamName(aname, i))
  1108  			})
  1109  		fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
  1110  		fmt.Fprintf(fgcc, "\tcrosscall2(_cgoexp%s_%s, &_cgo_a, %d, _cgo_ctxt);\n", cPrefix, exp.ExpName, off)
  1111  		fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
  1112  		fmt.Fprintf(fgcc, "\t_cgo_release_context(_cgo_ctxt);\n")
  1113  		if gccResult != "void" {
  1114  			if len(fntype.Results.List) == 1 && len(fntype.Results.List[0].Names) <= 1 {
  1115  				fmt.Fprintf(fgcc, "\treturn _cgo_a.r0;\n")
  1116  			} else {
  1117  				forFieldList(fntype.Results,
  1118  					func(i int, aname string, atype ast.Expr) {
  1119  						fmt.Fprintf(fgcc, "\tr.r%d = _cgo_a.r%d;\n", i, i)
  1120  					})
  1121  				fmt.Fprintf(fgcc, "\treturn r;\n")
  1122  			}
  1123  		}
  1124  		fmt.Fprintf(fgcc, "}\n")
  1125  
  1126  		// In internal linking mode, the Go linker sees both
  1127  		// the C wrapper written above and the Go wrapper it
  1128  		// references. Hence, export the C wrapper (e.g., for
  1129  		// if we're building a shared object). The Go linker
  1130  		// will resolve the C wrapper's reference to the Go
  1131  		// wrapper without a separate export.
  1132  		fmt.Fprintf(fgo2, "//go:cgo_export_dynamic %s\n", exp.ExpName)
  1133  		// cgo_export_static refers to a symbol by its linker
  1134  		// name, so set the linker name of the Go wrapper.
  1135  		fmt.Fprintf(fgo2, "//go:linkname _cgoexp%s_%s _cgoexp%s_%s\n", cPrefix, exp.ExpName, cPrefix, exp.ExpName)
  1136  		// In external linking mode, the Go linker sees the Go
  1137  		// wrapper, but not the C wrapper. For this case,
  1138  		// export the Go wrapper so the host linker can
  1139  		// resolve the reference from the C wrapper to the Go
  1140  		// wrapper.
  1141  		fmt.Fprintf(fgo2, "//go:cgo_export_static _cgoexp%s_%s\n", cPrefix, exp.ExpName)
  1142  
  1143  		// Build the wrapper function compiled by cmd/compile.
  1144  		// This unpacks the argument struct above and calls the Go function.
  1145  		fmt.Fprintf(fgo2, "func _cgoexp%s_%s(a *%s) {\n", cPrefix, exp.ExpName, gotype)
  1146  
  1147  		fmt.Fprintf(fm, "void _cgoexp%s_%s(void* p __attribute__((unused))){}\n", cPrefix, exp.ExpName)
  1148  
  1149  		fmt.Fprintf(fgo2, "\t")
  1150  
  1151  		if gccResult != "void" {
  1152  			// Write results back to frame.
  1153  			forFieldList(fntype.Results,
  1154  				func(i int, aname string, atype ast.Expr) {
  1155  					if i > 0 {
  1156  						fmt.Fprintf(fgo2, ", ")
  1157  					}
  1158  					fmt.Fprintf(fgo2, "a.r%d", i)
  1159  				})
  1160  			fmt.Fprintf(fgo2, " = ")
  1161  		}
  1162  		if fn.Recv != nil {
  1163  			fmt.Fprintf(fgo2, "a.recv.")
  1164  		}
  1165  		fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
  1166  		forFieldList(fntype.Params,
  1167  			func(i int, aname string, atype ast.Expr) {
  1168  				if i > 0 {
  1169  					fmt.Fprint(fgo2, ", ")
  1170  				}
  1171  				fmt.Fprintf(fgo2, "a.p%d", i)
  1172  			})
  1173  		fmt.Fprint(fgo2, ")\n")
  1174  		if gccResult != "void" {
  1175  			// Verify that any results don't contain any
  1176  			// Go pointers.
  1177  			forFieldList(fntype.Results,
  1178  				func(i int, aname string, atype ast.Expr) {
  1179  					if !p.hasPointer(nil, atype, false) {
  1180  						return
  1181  					}
  1182  
  1183  					// Use the export'ed file/line in error messages.
  1184  					pos := fset.Position(exp.Func.Pos())
  1185  					fmt.Fprintf(fgo2, "//line %s:%d\n", pos.Filename, pos.Line)
  1186  					fmt.Fprintf(fgo2, "\t_cgoCheckResult(a.r%d)\n", i)
  1187  				})
  1188  		}
  1189  		fmt.Fprint(fgo2, "}\n")
  1190  	}
  1191  
  1192  	fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
  1193  }
  1194  
  1195  // Write out the C header allowing C code to call exported gccgo functions.
  1196  func (p *Package) writeGccgoExports(fgo2, fm, fgcc, fgcch io.Writer) {
  1197  	gccgoSymbolPrefix := p.gccgoSymbolPrefix()
  1198  
  1199  	p.writeExportHeader(fgcch)
  1200  
  1201  	fmt.Fprintf(fgcc, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
  1202  	fmt.Fprintf(fgcc, "#include \"_cgo_export.h\"\n")
  1203  
  1204  	fmt.Fprintf(fgcc, "%s\n", gccgoExportFileProlog)
  1205  	fmt.Fprintf(fgcc, "%s\n", tsanProlog)
  1206  	fmt.Fprintf(fgcc, "%s\n", msanProlog)
  1207  
  1208  	for _, exp := range p.ExpFunc {
  1209  		fn := exp.Func
  1210  		fntype := fn.Type
  1211  
  1212  		cdeclBuf := new(strings.Builder)
  1213  		resultCount := 0
  1214  		forFieldList(fntype.Results,
  1215  			func(i int, aname string, atype ast.Expr) { resultCount++ })
  1216  		switch resultCount {
  1217  		case 0:
  1218  			fmt.Fprintf(cdeclBuf, "void")
  1219  		case 1:
  1220  			forFieldList(fntype.Results,
  1221  				func(i int, aname string, atype ast.Expr) {
  1222  					t := p.cgoType(atype)
  1223  					fmt.Fprintf(cdeclBuf, "%s", t.C)
  1224  				})
  1225  		default:
  1226  			// Declare a result struct.
  1227  			fmt.Fprintf(fgcch, "\n/* Return type for %s */\n", exp.ExpName)
  1228  			fmt.Fprintf(fgcch, "struct %s_return {\n", exp.ExpName)
  1229  			forFieldList(fntype.Results,
  1230  				func(i int, aname string, atype ast.Expr) {
  1231  					t := p.cgoType(atype)
  1232  					fmt.Fprintf(fgcch, "\t%s r%d;", t.C, i)
  1233  					if len(aname) > 0 {
  1234  						fmt.Fprintf(fgcch, " /* %s */", aname)
  1235  					}
  1236  					fmt.Fprint(fgcch, "\n")
  1237  				})
  1238  			fmt.Fprintf(fgcch, "};\n")
  1239  			fmt.Fprintf(cdeclBuf, "struct %s_return", exp.ExpName)
  1240  		}
  1241  
  1242  		cRet := cdeclBuf.String()
  1243  
  1244  		cdeclBuf = new(strings.Builder)
  1245  		fmt.Fprintf(cdeclBuf, "(")
  1246  		if fn.Recv != nil {
  1247  			fmt.Fprintf(cdeclBuf, "%s recv", p.cgoType(fn.Recv.List[0].Type).C.String())
  1248  		}
  1249  		// Function parameters.
  1250  		forFieldList(fntype.Params,
  1251  			func(i int, aname string, atype ast.Expr) {
  1252  				if i > 0 || fn.Recv != nil {
  1253  					fmt.Fprintf(cdeclBuf, ", ")
  1254  				}
  1255  				t := p.cgoType(atype)
  1256  				fmt.Fprintf(cdeclBuf, "%s p%d", t.C, i)
  1257  			})
  1258  		fmt.Fprintf(cdeclBuf, ")")
  1259  		cParams := cdeclBuf.String()
  1260  
  1261  		if len(exp.Doc) > 0 {
  1262  			fmt.Fprintf(fgcch, "\n%s", exp.Doc)
  1263  		}
  1264  
  1265  		fmt.Fprintf(fgcch, "extern %s %s%s;\n", cRet, exp.ExpName, cParams)
  1266  
  1267  		// We need to use a name that will be exported by the
  1268  		// Go code; otherwise gccgo will make it static and we
  1269  		// will not be able to link against it from the C
  1270  		// code.
  1271  		goName := "Cgoexp_" + exp.ExpName
  1272  		fmt.Fprintf(fgcc, `extern %s %s %s __asm__("%s.%s");`, cRet, goName, cParams, gccgoSymbolPrefix, gccgoToSymbol(goName))
  1273  		fmt.Fprint(fgcc, "\n")
  1274  
  1275  		fmt.Fprint(fgcc, "\nCGO_NO_SANITIZE_THREAD\n")
  1276  		fmt.Fprintf(fgcc, "%s %s %s {\n", cRet, exp.ExpName, cParams)
  1277  		if resultCount > 0 {
  1278  			fmt.Fprintf(fgcc, "\t%s r;\n", cRet)
  1279  		}
  1280  		fmt.Fprintf(fgcc, "\tif(_cgo_wait_runtime_init_done)\n")
  1281  		fmt.Fprintf(fgcc, "\t\t_cgo_wait_runtime_init_done();\n")
  1282  		fmt.Fprintf(fgcc, "\t_cgo_tsan_release();\n")
  1283  		fmt.Fprint(fgcc, "\t")
  1284  		if resultCount > 0 {
  1285  			fmt.Fprint(fgcc, "r = ")
  1286  		}
  1287  		fmt.Fprintf(fgcc, "%s(", goName)
  1288  		if fn.Recv != nil {
  1289  			fmt.Fprint(fgcc, "recv")
  1290  		}
  1291  		forFieldList(fntype.Params,
  1292  			func(i int, aname string, atype ast.Expr) {
  1293  				if i > 0 || fn.Recv != nil {
  1294  					fmt.Fprintf(fgcc, ", ")
  1295  				}
  1296  				fmt.Fprintf(fgcc, "p%d", i)
  1297  			})
  1298  		fmt.Fprint(fgcc, ");\n")
  1299  		fmt.Fprintf(fgcc, "\t_cgo_tsan_acquire();\n")
  1300  		if resultCount > 0 {
  1301  			fmt.Fprint(fgcc, "\treturn r;\n")
  1302  		}
  1303  		fmt.Fprint(fgcc, "}\n")
  1304  
  1305  		// Dummy declaration for _cgo_main.c
  1306  		fmt.Fprintf(fm, `char %s[1] __asm__("%s.%s");`, goName, gccgoSymbolPrefix, gccgoToSymbol(goName))
  1307  		fmt.Fprint(fm, "\n")
  1308  
  1309  		// For gccgo we use a wrapper function in Go, in order
  1310  		// to call CgocallBack and CgocallBackDone.
  1311  
  1312  		// This code uses printer.Fprint, not conf.Fprint,
  1313  		// because we don't want //line comments in the middle
  1314  		// of the function types.
  1315  		fmt.Fprint(fgo2, "\n")
  1316  		fmt.Fprintf(fgo2, "func %s(", goName)
  1317  		if fn.Recv != nil {
  1318  			fmt.Fprint(fgo2, "recv ")
  1319  			printer.Fprint(fgo2, fset, fn.Recv.List[0].Type)
  1320  		}
  1321  		forFieldList(fntype.Params,
  1322  			func(i int, aname string, atype ast.Expr) {
  1323  				if i > 0 || fn.Recv != nil {
  1324  					fmt.Fprintf(fgo2, ", ")
  1325  				}
  1326  				fmt.Fprintf(fgo2, "p%d ", i)
  1327  				printer.Fprint(fgo2, fset, atype)
  1328  			})
  1329  		fmt.Fprintf(fgo2, ")")
  1330  		if resultCount > 0 {
  1331  			fmt.Fprintf(fgo2, " (")
  1332  			forFieldList(fntype.Results,
  1333  				func(i int, aname string, atype ast.Expr) {
  1334  					if i > 0 {
  1335  						fmt.Fprint(fgo2, ", ")
  1336  					}
  1337  					printer.Fprint(fgo2, fset, atype)
  1338  				})
  1339  			fmt.Fprint(fgo2, ")")
  1340  		}
  1341  		fmt.Fprint(fgo2, " {\n")
  1342  		fmt.Fprint(fgo2, "\tsyscall.CgocallBack()\n")
  1343  		fmt.Fprint(fgo2, "\tdefer syscall.CgocallBackDone()\n")
  1344  		fmt.Fprint(fgo2, "\t")
  1345  		if resultCount > 0 {
  1346  			fmt.Fprint(fgo2, "return ")
  1347  		}
  1348  		if fn.Recv != nil {
  1349  			fmt.Fprint(fgo2, "recv.")
  1350  		}
  1351  		fmt.Fprintf(fgo2, "%s(", exp.Func.Name)
  1352  		forFieldList(fntype.Params,
  1353  			func(i int, aname string, atype ast.Expr) {
  1354  				if i > 0 {
  1355  					fmt.Fprint(fgo2, ", ")
  1356  				}
  1357  				fmt.Fprintf(fgo2, "p%d", i)
  1358  			})
  1359  		fmt.Fprint(fgo2, ")\n")
  1360  		fmt.Fprint(fgo2, "}\n")
  1361  	}
  1362  
  1363  	fmt.Fprintf(fgcch, "%s", gccExportHeaderEpilog)
  1364  }
  1365  
  1366  // writeExportHeader writes out the start of the _cgo_export.h file.
  1367  func (p *Package) writeExportHeader(fgcch io.Writer) {
  1368  	fmt.Fprintf(fgcch, "/* Code generated by cmd/cgo; DO NOT EDIT. */\n\n")
  1369  	pkg := *importPath
  1370  	if pkg == "" {
  1371  		pkg = p.PackagePath
  1372  	}
  1373  	fmt.Fprintf(fgcch, "/* package %s */\n\n", pkg)
  1374  	fmt.Fprintf(fgcch, "%s\n", builtinExportProlog)
  1375  
  1376  	// Remove absolute paths from #line comments in the preamble.
  1377  	// They aren't useful for people using the header file,
  1378  	// and they mean that the header files change based on the
  1379  	// exact location of GOPATH.
  1380  	re := regexp.MustCompile(`(?m)^(#line\s+\d+\s+")[^"]*[/\\]([^"]*")`)
  1381  	preamble := re.ReplaceAllString(p.Preamble, "$1$2")
  1382  
  1383  	fmt.Fprintf(fgcch, "/* Start of preamble from import \"C\" comments.  */\n\n")
  1384  	fmt.Fprintf(fgcch, "%s\n", preamble)
  1385  	fmt.Fprintf(fgcch, "\n/* End of preamble from import \"C\" comments.  */\n\n")
  1386  
  1387  	fmt.Fprintf(fgcch, "%s\n", p.gccExportHeaderProlog())
  1388  }
  1389  
  1390  // gccgoToSymbol converts a name to a mangled symbol for gccgo.
  1391  func gccgoToSymbol(ppath string) string {
  1392  	if gccgoMangler == nil {
  1393  		var err error
  1394  		cmd := os.Getenv("GCCGO")
  1395  		if cmd == "" {
  1396  			cmd, err = exec.LookPath("gccgo")
  1397  			if err != nil {
  1398  				fatalf("unable to locate gccgo: %v", err)
  1399  			}
  1400  		}
  1401  		gccgoMangler, err = pkgpath.ToSymbolFunc(cmd, outputDir())
  1402  		if err != nil {
  1403  			fatalf("%v", err)
  1404  		}
  1405  	}
  1406  	return gccgoMangler(ppath)
  1407  }
  1408  
  1409  // Return the package prefix when using gccgo.
  1410  func (p *Package) gccgoSymbolPrefix() string {
  1411  	if !*gccgo {
  1412  		return ""
  1413  	}
  1414  
  1415  	if *gccgopkgpath != "" {
  1416  		return gccgoToSymbol(*gccgopkgpath)
  1417  	}
  1418  	if *gccgoprefix == "" && p.PackageName == "main" {
  1419  		return "main"
  1420  	}
  1421  	prefix := gccgoToSymbol(*gccgoprefix)
  1422  	if prefix == "" {
  1423  		prefix = "go"
  1424  	}
  1425  	return prefix + "." + p.PackageName
  1426  }
  1427  
  1428  // Call a function for each entry in an ast.FieldList, passing the
  1429  // index into the list, the name if any, and the type.
  1430  func forFieldList(fl *ast.FieldList, fn func(int, string, ast.Expr)) {
  1431  	if fl == nil {
  1432  		return
  1433  	}
  1434  	i := 0
  1435  	for _, r := range fl.List {
  1436  		if r.Names == nil {
  1437  			fn(i, "", r.Type)
  1438  			i++
  1439  		} else {
  1440  			for _, n := range r.Names {
  1441  				fn(i, n.Name, r.Type)
  1442  				i++
  1443  			}
  1444  		}
  1445  	}
  1446  }
  1447  
  1448  func c(repr string, args ...any) *TypeRepr {
  1449  	return &TypeRepr{repr, args}
  1450  }
  1451  
  1452  // Map predeclared Go types to Type.
  1453  var goTypes = map[string]*Type{
  1454  	"bool":       {Size: 1, Align: 1, C: c("GoUint8")},
  1455  	"byte":       {Size: 1, Align: 1, C: c("GoUint8")},
  1456  	"int":        {Size: 0, Align: 0, C: c("GoInt")},
  1457  	"uint":       {Size: 0, Align: 0, C: c("GoUint")},
  1458  	"rune":       {Size: 4, Align: 4, C: c("GoInt32")},
  1459  	"int8":       {Size: 1, Align: 1, C: c("GoInt8")},
  1460  	"uint8":      {Size: 1, Align: 1, C: c("GoUint8")},
  1461  	"int16":      {Size: 2, Align: 2, C: c("GoInt16")},
  1462  	"uint16":     {Size: 2, Align: 2, C: c("GoUint16")},
  1463  	"int32":      {Size: 4, Align: 4, C: c("GoInt32")},
  1464  	"uint32":     {Size: 4, Align: 4, C: c("GoUint32")},
  1465  	"int64":      {Size: 8, Align: 8, C: c("GoInt64")},
  1466  	"uint64":     {Size: 8, Align: 8, C: c("GoUint64")},
  1467  	"float32":    {Size: 4, Align: 4, C: c("GoFloat32")},
  1468  	"float64":    {Size: 8, Align: 8, C: c("GoFloat64")},
  1469  	"complex64":  {Size: 8, Align: 4, C: c("GoComplex64")},
  1470  	"complex128": {Size: 16, Align: 8, C: c("GoComplex128")},
  1471  }
  1472  
  1473  // Map an ast type to a Type.
  1474  func (p *Package) cgoType(e ast.Expr) *Type {
  1475  	return p.doCgoType(e, make(map[ast.Expr]bool))
  1476  }
  1477  
  1478  // Map an ast type to a Type, avoiding cycles.
  1479  func (p *Package) doCgoType(e ast.Expr, m map[ast.Expr]bool) *Type {
  1480  	if m[e] {
  1481  		fatalf("%s: invalid recursive type", fset.Position(e.Pos()))
  1482  	}
  1483  	m[e] = true
  1484  	switch t := e.(type) {
  1485  	case *ast.StarExpr:
  1486  		x := p.doCgoType(t.X, m)
  1487  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("%s*", x.C)}
  1488  	case *ast.ArrayType:
  1489  		if t.Len == nil {
  1490  			// Slice: pointer, len, cap.
  1491  			return &Type{Size: p.PtrSize * 3, Align: p.PtrSize, C: c("GoSlice")}
  1492  		}
  1493  		// Non-slice array types are not supported.
  1494  	case *ast.StructType:
  1495  		// Not supported.
  1496  	case *ast.FuncType:
  1497  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
  1498  	case *ast.InterfaceType:
  1499  		return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
  1500  	case *ast.MapType:
  1501  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoMap")}
  1502  	case *ast.ChanType:
  1503  		return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoChan")}
  1504  	case *ast.Ident:
  1505  		goTypesFixup := func(r *Type) *Type {
  1506  			if r.Size == 0 { // int or uint
  1507  				rr := new(Type)
  1508  				*rr = *r
  1509  				rr.Size = p.IntSize
  1510  				rr.Align = p.IntSize
  1511  				r = rr
  1512  			}
  1513  			if r.Align > p.PtrSize {
  1514  				r.Align = p.PtrSize
  1515  			}
  1516  			return r
  1517  		}
  1518  		// Look up the type in the top level declarations.
  1519  		// TODO: Handle types defined within a function.
  1520  		for _, d := range p.Decl {
  1521  			gd, ok := d.(*ast.GenDecl)
  1522  			if !ok || gd.Tok != token.TYPE {
  1523  				continue
  1524  			}
  1525  			for _, spec := range gd.Specs {
  1526  				ts, ok := spec.(*ast.TypeSpec)
  1527  				if !ok {
  1528  					continue
  1529  				}
  1530  				if ts.Name.Name == t.Name {
  1531  					// Give a better error than the one
  1532  					// above if we detect a recursive type.
  1533  					if m[ts.Type] {
  1534  						fatalf("%s: invalid recursive type: %s refers to itself", fset.Position(e.Pos()), t.Name)
  1535  					}
  1536  					return p.doCgoType(ts.Type, m)
  1537  				}
  1538  			}
  1539  		}
  1540  		if def := typedef[t.Name]; def != nil {
  1541  			if defgo, ok := def.Go.(*ast.Ident); ok {
  1542  				switch defgo.Name {
  1543  				case "complex64", "complex128":
  1544  					// MSVC does not support the _Complex keyword
  1545  					// nor the complex macro.
  1546  					// Use GoComplex64 and GoComplex128 instead,
  1547  					// which are typedef-ed to a compatible type.
  1548  					// See go.dev/issues/36233.
  1549  					return goTypesFixup(goTypes[defgo.Name])
  1550  				}
  1551  			}
  1552  			return def
  1553  		}
  1554  		if t.Name == "uintptr" {
  1555  			return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("GoUintptr")}
  1556  		}
  1557  		if t.Name == "string" {
  1558  			// The string data is 1 pointer + 1 (pointer-sized) int.
  1559  			return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoString")}
  1560  		}
  1561  		if t.Name == "error" {
  1562  			return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
  1563  		}
  1564  		if t.Name == "any" {
  1565  			return &Type{Size: 2 * p.PtrSize, Align: p.PtrSize, C: c("GoInterface")}
  1566  		}
  1567  		if r, ok := goTypes[t.Name]; ok {
  1568  			return goTypesFixup(r)
  1569  		}
  1570  		error_(e.Pos(), "unrecognized Go type %s", t.Name)
  1571  		return &Type{Size: 4, Align: 4, C: c("int")}
  1572  	case *ast.SelectorExpr:
  1573  		id, ok := t.X.(*ast.Ident)
  1574  		if ok && id.Name == "unsafe" && t.Sel.Name == "Pointer" {
  1575  			return &Type{Size: p.PtrSize, Align: p.PtrSize, C: c("void*")}
  1576  		}
  1577  	}
  1578  	error_(e.Pos(), "Go type not supported in export: %s", gofmt(e))
  1579  	return &Type{Size: 4, Align: 4, C: c("int")}
  1580  }
  1581  
  1582  const gccProlog = `
  1583  #line 1 "cgo-gcc-prolog"
  1584  /*
  1585    If x and y are not equal, the type will be invalid
  1586    (have a negative array count) and an inscrutable error will come
  1587    out of the compiler and hopefully mention "name".
  1588  */
  1589  #define __cgo_compile_assert_eq(x, y, name) typedef char name[(x-y)*(x-y)*-2UL+1UL];
  1590  
  1591  /* Check at compile time that the sizes we use match our expectations. */
  1592  #define __cgo_size_assert(t, n) __cgo_compile_assert_eq(sizeof(t), (size_t)n, _cgo_sizeof_##t##_is_not_##n)
  1593  
  1594  __cgo_size_assert(char, 1)
  1595  __cgo_size_assert(short, 2)
  1596  __cgo_size_assert(int, 4)
  1597  typedef long long __cgo_long_long;
  1598  __cgo_size_assert(__cgo_long_long, 8)
  1599  __cgo_size_assert(float, 4)
  1600  __cgo_size_assert(double, 8)
  1601  
  1602  extern char* _cgo_topofstack(void);
  1603  
  1604  /*
  1605    We use packed structs, but they are always aligned.
  1606    The pragmas and address-of-packed-member are only recognized as warning
  1607    groups in clang 4.0+, so ignore unknown pragmas first.
  1608  */
  1609  #pragma GCC diagnostic ignored "-Wunknown-pragmas"
  1610  #pragma GCC diagnostic ignored "-Wpragmas"
  1611  #pragma GCC diagnostic ignored "-Waddress-of-packed-member"
  1612  #pragma GCC diagnostic ignored "-Wunknown-warning-option"
  1613  #pragma GCC diagnostic ignored "-Wunaligned-access"
  1614  
  1615  #include <errno.h>
  1616  #include <string.h>
  1617  `
  1618  
  1619  // Prologue defining TSAN functions in C.
  1620  const noTsanProlog = `
  1621  #define CGO_NO_SANITIZE_THREAD
  1622  #define _cgo_tsan_acquire()
  1623  #define _cgo_tsan_release()
  1624  `
  1625  
  1626  // This must match the TSAN code in runtime/cgo/libcgo.h.
  1627  // This is used when the code is built with the C/C++ Thread SANitizer,
  1628  // which is not the same as the Go race detector.
  1629  // __tsan_acquire tells TSAN that we are acquiring a lock on a variable,
  1630  // in this case _cgo_sync. __tsan_release releases the lock.
  1631  // (There is no actual lock, we are just telling TSAN that there is.)
  1632  //
  1633  // When we call from Go to C we call _cgo_tsan_acquire.
  1634  // When the C function returns we call _cgo_tsan_release.
  1635  // Similarly, when C calls back into Go we call _cgo_tsan_release
  1636  // and then call _cgo_tsan_acquire when we return to C.
  1637  // These calls tell TSAN that there is a serialization point at the C call.
  1638  //
  1639  // This is necessary because TSAN, which is a C/C++ tool, can not see
  1640  // the synchronization in the Go code. Without these calls, when
  1641  // multiple goroutines call into C code, TSAN does not understand
  1642  // that the calls are properly synchronized on the Go side.
  1643  //
  1644  // To be clear, if the calls are not properly synchronized on the Go side,
  1645  // we will be hiding races. But when using TSAN on mixed Go C/C++ code
  1646  // it is more important to avoid false positives, which reduce confidence
  1647  // in the tool, than to avoid false negatives.
  1648  const yesTsanProlog = `
  1649  #line 1 "cgo-tsan-prolog"
  1650  #define CGO_NO_SANITIZE_THREAD __attribute__ ((no_sanitize_thread))
  1651  
  1652  long long _cgo_sync __attribute__ ((common));
  1653  
  1654  extern void __tsan_acquire(void*);
  1655  extern void __tsan_release(void*);
  1656  
  1657  __attribute__ ((unused))
  1658  static void _cgo_tsan_acquire() {
  1659  	__tsan_acquire(&_cgo_sync);
  1660  }
  1661  
  1662  __attribute__ ((unused))
  1663  static void _cgo_tsan_release() {
  1664  	__tsan_release(&_cgo_sync);
  1665  }
  1666  `
  1667  
  1668  // Set to yesTsanProlog if we see -fsanitize=thread in the flags for gcc.
  1669  var tsanProlog = noTsanProlog
  1670  
  1671  // noMsanProlog is a prologue defining an MSAN function in C.
  1672  // This is used when not compiling with -fsanitize=memory.
  1673  const noMsanProlog = `
  1674  #define _cgo_msan_write(addr, sz)
  1675  `
  1676  
  1677  // yesMsanProlog is a prologue defining an MSAN function in C.
  1678  // This is used when compiling with -fsanitize=memory.
  1679  // See the comment above where _cgo_msan_write is called.
  1680  const yesMsanProlog = `
  1681  extern void __msan_unpoison(const volatile void *, size_t);
  1682  
  1683  #define _cgo_msan_write(addr, sz) __msan_unpoison((addr), (sz))
  1684  `
  1685  
  1686  // msanProlog is set to yesMsanProlog if we see -fsanitize=memory in the flags
  1687  // for the C compiler.
  1688  var msanProlog = noMsanProlog
  1689  
  1690  const builtinProlog = `
  1691  #line 1 "cgo-builtin-prolog"
  1692  #include <stddef.h>
  1693  
  1694  /* Define intgo when compiling with GCC.  */
  1695  typedef ptrdiff_t intgo;
  1696  
  1697  #define GO_CGO_GOSTRING_TYPEDEF
  1698  typedef struct { const char *p; intgo n; } _GoString_;
  1699  typedef struct { char *p; intgo n; intgo c; } _GoBytes_;
  1700  _GoString_ GoString(char *p);
  1701  _GoString_ GoStringN(char *p, int l);
  1702  _GoBytes_ GoBytes(void *p, int n);
  1703  char *CString(_GoString_);
  1704  void *CBytes(_GoBytes_);
  1705  void *_CMalloc(size_t);
  1706  
  1707  __attribute__ ((unused))
  1708  static size_t _GoStringLen(_GoString_ s) { return (size_t)s.n; }
  1709  
  1710  __attribute__ ((unused))
  1711  static const char *_GoStringPtr(_GoString_ s) { return s.p; }
  1712  `
  1713  
  1714  const goProlog = `
  1715  //go:linkname _cgo_runtime_cgocall runtime.cgocall
  1716  func _cgo_runtime_cgocall(unsafe.Pointer, uintptr) int32
  1717  
  1718  //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
  1719  //go:noescape
  1720  func _cgoCheckPointer(interface{}, interface{})
  1721  
  1722  //go:linkname _cgoCheckResult runtime.cgoCheckResult
  1723  //go:noescape
  1724  func _cgoCheckResult(interface{})
  1725  `
  1726  
  1727  const gccgoGoProlog = `
  1728  func _cgoCheckPointer(interface{}, interface{})
  1729  
  1730  func _cgoCheckResult(interface{})
  1731  `
  1732  
  1733  const goStringDef = `
  1734  //go:linkname _cgo_runtime_gostring runtime.gostring
  1735  func _cgo_runtime_gostring(*_Ctype_char) string
  1736  
  1737  // GoString converts the C string p into a Go string.
  1738  func _Cfunc_GoString(p *_Ctype_char) string {
  1739  	return _cgo_runtime_gostring(p)
  1740  }
  1741  `
  1742  
  1743  const goStringNDef = `
  1744  //go:linkname _cgo_runtime_gostringn runtime.gostringn
  1745  func _cgo_runtime_gostringn(*_Ctype_char, int) string
  1746  
  1747  // GoStringN converts the C data p with explicit length l to a Go string.
  1748  func _Cfunc_GoStringN(p *_Ctype_char, l _Ctype_int) string {
  1749  	return _cgo_runtime_gostringn(p, int(l))
  1750  }
  1751  `
  1752  
  1753  const goBytesDef = `
  1754  //go:linkname _cgo_runtime_gobytes runtime.gobytes
  1755  func _cgo_runtime_gobytes(unsafe.Pointer, int) []byte
  1756  
  1757  // GoBytes converts the C data p with explicit length l to a Go []byte.
  1758  func _Cfunc_GoBytes(p unsafe.Pointer, l _Ctype_int) []byte {
  1759  	return _cgo_runtime_gobytes(p, int(l))
  1760  }
  1761  `
  1762  
  1763  const cStringDef = `
  1764  // CString converts the Go string s to a C string.
  1765  //
  1766  // The C string is allocated in the C heap using malloc.
  1767  // It is the caller's responsibility to arrange for it to be
  1768  // freed, such as by calling C.free (be sure to include stdlib.h
  1769  // if C.free is needed).
  1770  func _Cfunc_CString(s string) *_Ctype_char {
  1771  	if len(s)+1 <= 0 {
  1772  		panic("string too large")
  1773  	}
  1774  	p := _cgo_cmalloc(uint64(len(s)+1))
  1775  	sliceHeader := struct {
  1776  		p   unsafe.Pointer
  1777  		len int
  1778  		cap int
  1779  	}{p, len(s)+1, len(s)+1}
  1780  	b := *(*[]byte)(unsafe.Pointer(&sliceHeader))
  1781  	copy(b, s)
  1782  	b[len(s)] = 0
  1783  	return (*_Ctype_char)(p)
  1784  }
  1785  `
  1786  
  1787  const cBytesDef = `
  1788  // CBytes converts the Go []byte slice b to a C array.
  1789  //
  1790  // The C array is allocated in the C heap using malloc.
  1791  // It is the caller's responsibility to arrange for it to be
  1792  // freed, such as by calling C.free (be sure to include stdlib.h
  1793  // if C.free is needed).
  1794  func _Cfunc_CBytes(b []byte) unsafe.Pointer {
  1795  	p := _cgo_cmalloc(uint64(len(b)))
  1796  	sliceHeader := struct {
  1797  		p   unsafe.Pointer
  1798  		len int
  1799  		cap int
  1800  	}{p, len(b), len(b)}
  1801  	s := *(*[]byte)(unsafe.Pointer(&sliceHeader))
  1802  	copy(s, b)
  1803  	return p
  1804  }
  1805  `
  1806  
  1807  const cMallocDef = `
  1808  func _Cfunc__CMalloc(n _Ctype_size_t) unsafe.Pointer {
  1809  	return _cgo_cmalloc(uint64(n))
  1810  }
  1811  `
  1812  
  1813  var builtinDefs = map[string]string{
  1814  	"GoString":  goStringDef,
  1815  	"GoStringN": goStringNDef,
  1816  	"GoBytes":   goBytesDef,
  1817  	"CString":   cStringDef,
  1818  	"CBytes":    cBytesDef,
  1819  	"_CMalloc":  cMallocDef,
  1820  }
  1821  
  1822  // Definitions for C.malloc in Go and in C. We define it ourselves
  1823  // since we call it from functions we define, such as C.CString.
  1824  // Also, we have historically ensured that C.malloc does not return
  1825  // nil even for an allocation of 0.
  1826  
  1827  const cMallocDefGo = `
  1828  //go:cgo_import_static _cgoPREFIX_Cfunc__Cmalloc
  1829  //go:linkname __cgofn__cgoPREFIX_Cfunc__Cmalloc _cgoPREFIX_Cfunc__Cmalloc
  1830  var __cgofn__cgoPREFIX_Cfunc__Cmalloc byte
  1831  var _cgoPREFIX_Cfunc__Cmalloc = unsafe.Pointer(&__cgofn__cgoPREFIX_Cfunc__Cmalloc)
  1832  
  1833  //go:linkname runtime_throw runtime.throw
  1834  func runtime_throw(string)
  1835  
  1836  //go:cgo_unsafe_args
  1837  func _cgo_cmalloc(p0 uint64) (r1 unsafe.Pointer) {
  1838  	_cgo_runtime_cgocall(_cgoPREFIX_Cfunc__Cmalloc, uintptr(unsafe.Pointer(&p0)))
  1839  	if r1 == nil {
  1840  		runtime_throw("runtime: C malloc failed")
  1841  	}
  1842  	return
  1843  }
  1844  `
  1845  
  1846  // cMallocDefC defines the C version of C.malloc for the gc compiler.
  1847  // It is defined here because C.CString and friends need a definition.
  1848  // We define it by hand, rather than simply inventing a reference to
  1849  // C.malloc, because <stdlib.h> may not have been included.
  1850  // This is approximately what writeOutputFunc would generate, but
  1851  // skips the cgo_topofstack code (which is only needed if the C code
  1852  // calls back into Go). This also avoids returning nil for an
  1853  // allocation of 0 bytes.
  1854  const cMallocDefC = `
  1855  CGO_NO_SANITIZE_THREAD
  1856  void _cgoPREFIX_Cfunc__Cmalloc(void *v) {
  1857  	struct {
  1858  		unsigned long long p0;
  1859  		void *r1;
  1860  	} PACKED *a = v;
  1861  	void *ret;
  1862  	_cgo_tsan_acquire();
  1863  	ret = malloc(a->p0);
  1864  	if (ret == NULL && a->p0 == 0) {
  1865  		ret = malloc(1);
  1866  	}
  1867  	a->r1 = ret;
  1868  	_cgo_tsan_release();
  1869  }
  1870  `
  1871  
  1872  func (p *Package) cPrologGccgo() string {
  1873  	r := strings.NewReplacer(
  1874  		"PREFIX", cPrefix,
  1875  		"GCCGOSYMBOLPREF", p.gccgoSymbolPrefix(),
  1876  		"_cgoCheckPointer", gccgoToSymbol("_cgoCheckPointer"),
  1877  		"_cgoCheckResult", gccgoToSymbol("_cgoCheckResult"))
  1878  	return r.Replace(cPrologGccgo)
  1879  }
  1880  
  1881  const cPrologGccgo = `
  1882  #line 1 "cgo-c-prolog-gccgo"
  1883  #include <stdint.h>
  1884  #include <stdlib.h>
  1885  #include <string.h>
  1886  
  1887  typedef unsigned char byte;
  1888  typedef intptr_t intgo;
  1889  
  1890  struct __go_string {
  1891  	const unsigned char *__data;
  1892  	intgo __length;
  1893  };
  1894  
  1895  typedef struct __go_open_array {
  1896  	void* __values;
  1897  	intgo __count;
  1898  	intgo __capacity;
  1899  } Slice;
  1900  
  1901  struct __go_string __go_byte_array_to_string(const void* p, intgo len);
  1902  struct __go_open_array __go_string_to_byte_array (struct __go_string str);
  1903  
  1904  extern void runtime_throw(const char *);
  1905  
  1906  const char *_cgoPREFIX_Cfunc_CString(struct __go_string s) {
  1907  	char *p = malloc(s.__length+1);
  1908  	if(p == NULL)
  1909  		runtime_throw("runtime: C malloc failed");
  1910  	memmove(p, s.__data, s.__length);
  1911  	p[s.__length] = 0;
  1912  	return p;
  1913  }
  1914  
  1915  void *_cgoPREFIX_Cfunc_CBytes(struct __go_open_array b) {
  1916  	char *p = malloc(b.__count);
  1917  	if(p == NULL)
  1918  		runtime_throw("runtime: C malloc failed");
  1919  	memmove(p, b.__values, b.__count);
  1920  	return p;
  1921  }
  1922  
  1923  struct __go_string _cgoPREFIX_Cfunc_GoString(char *p) {
  1924  	intgo len = (p != NULL) ? strlen(p) : 0;
  1925  	return __go_byte_array_to_string(p, len);
  1926  }
  1927  
  1928  struct __go_string _cgoPREFIX_Cfunc_GoStringN(char *p, int32_t n) {
  1929  	return __go_byte_array_to_string(p, n);
  1930  }
  1931  
  1932  Slice _cgoPREFIX_Cfunc_GoBytes(char *p, int32_t n) {
  1933  	struct __go_string s = { (const unsigned char *)p, n };
  1934  	return __go_string_to_byte_array(s);
  1935  }
  1936  
  1937  void *_cgoPREFIX_Cfunc__CMalloc(size_t n) {
  1938  	void *p = malloc(n);
  1939  	if(p == NULL && n == 0)
  1940  		p = malloc(1);
  1941  	if(p == NULL)
  1942  		runtime_throw("runtime: C malloc failed");
  1943  	return p;
  1944  }
  1945  
  1946  struct __go_type_descriptor;
  1947  typedef struct __go_empty_interface {
  1948  	const struct __go_type_descriptor *__type_descriptor;
  1949  	void *__object;
  1950  } Eface;
  1951  
  1952  extern void runtimeCgoCheckPointer(Eface, Eface)
  1953  	__asm__("runtime.cgoCheckPointer")
  1954  	__attribute__((weak));
  1955  
  1956  extern void localCgoCheckPointer(Eface, Eface)
  1957  	__asm__("GCCGOSYMBOLPREF._cgoCheckPointer");
  1958  
  1959  void localCgoCheckPointer(Eface ptr, Eface arg) {
  1960  	if(runtimeCgoCheckPointer) {
  1961  		runtimeCgoCheckPointer(ptr, arg);
  1962  	}
  1963  }
  1964  
  1965  extern void runtimeCgoCheckResult(Eface)
  1966  	__asm__("runtime.cgoCheckResult")
  1967  	__attribute__((weak));
  1968  
  1969  extern void localCgoCheckResult(Eface)
  1970  	__asm__("GCCGOSYMBOLPREF._cgoCheckResult");
  1971  
  1972  void localCgoCheckResult(Eface val) {
  1973  	if(runtimeCgoCheckResult) {
  1974  		runtimeCgoCheckResult(val);
  1975  	}
  1976  }
  1977  `
  1978  
  1979  // builtinExportProlog is a shorter version of builtinProlog,
  1980  // to be put into the _cgo_export.h file.
  1981  // For historical reasons we can't use builtinProlog in _cgo_export.h,
  1982  // because _cgo_export.h defines GoString as a struct while builtinProlog
  1983  // defines it as a function. We don't change this to avoid unnecessarily
  1984  // breaking existing code.
  1985  // The test of GO_CGO_GOSTRING_TYPEDEF avoids a duplicate definition
  1986  // error if a Go file with a cgo comment #include's the export header
  1987  // generated by a different package.
  1988  const builtinExportProlog = `
  1989  #line 1 "cgo-builtin-export-prolog"
  1990  
  1991  #include <stddef.h>
  1992  
  1993  #ifndef GO_CGO_EXPORT_PROLOGUE_H
  1994  #define GO_CGO_EXPORT_PROLOGUE_H
  1995  
  1996  #ifndef GO_CGO_GOSTRING_TYPEDEF
  1997  typedef struct { const char *p; ptrdiff_t n; } _GoString_;
  1998  extern size_t _GoStringLen(_GoString_ s);
  1999  extern const char *_GoStringPtr(_GoString_ s);
  2000  #endif
  2001  
  2002  #endif
  2003  `
  2004  
  2005  func (p *Package) gccExportHeaderProlog() string {
  2006  	return strings.ReplaceAll(gccExportHeaderProlog, "GOINTBITS", fmt.Sprint(8*p.IntSize))
  2007  }
  2008  
  2009  // gccExportHeaderProlog is written to the exported header, after the
  2010  // import "C" comment preamble but before the generated declarations
  2011  // of exported functions. This permits the generated declarations to
  2012  // use the type names that appear in goTypes, above.
  2013  //
  2014  // The test of GO_CGO_GOSTRING_TYPEDEF avoids a duplicate definition
  2015  // error if a Go file with a cgo comment #include's the export header
  2016  // generated by a different package. Unfortunately GoString means two
  2017  // different things: in this prolog it means a C name for the Go type,
  2018  // while in the prolog written into the start of the C code generated
  2019  // from a cgo-using Go file it means the C.GoString function. There is
  2020  // no way to resolve this conflict, but it also doesn't make much
  2021  // difference, as Go code never wants to refer to the latter meaning.
  2022  const gccExportHeaderProlog = `
  2023  /* Start of boilerplate cgo prologue.  */
  2024  #line 1 "cgo-gcc-export-header-prolog"
  2025  
  2026  #ifndef GO_CGO_PROLOGUE_H
  2027  #define GO_CGO_PROLOGUE_H
  2028  
  2029  typedef signed char GoInt8;
  2030  typedef unsigned char GoUint8;
  2031  typedef short GoInt16;
  2032  typedef unsigned short GoUint16;
  2033  typedef int GoInt32;
  2034  typedef unsigned int GoUint32;
  2035  typedef long long GoInt64;
  2036  typedef unsigned long long GoUint64;
  2037  typedef GoIntGOINTBITS GoInt;
  2038  typedef GoUintGOINTBITS GoUint;
  2039  typedef size_t GoUintptr;
  2040  typedef float GoFloat32;
  2041  typedef double GoFloat64;
  2042  #ifdef _MSC_VER
  2043  #if !defined(__cplusplus) || _MSVC_LANG <= 201402L
  2044  #include <complex.h>
  2045  typedef _Fcomplex GoComplex64;
  2046  typedef _Dcomplex GoComplex128;
  2047  #else
  2048  #include <complex>
  2049  typedef std::complex<float> GoComplex64;
  2050  typedef std::complex<double> GoComplex128;
  2051  #endif
  2052  #else
  2053  typedef float _Complex GoComplex64;
  2054  typedef double _Complex GoComplex128;
  2055  #endif
  2056  
  2057  /*
  2058    static assertion to make sure the file is being used on architecture
  2059    at least with matching size of GoInt.
  2060  */
  2061  typedef char _check_for_GOINTBITS_bit_pointer_matching_GoInt[sizeof(void*)==GOINTBITS/8 ? 1:-1];
  2062  
  2063  #ifndef GO_CGO_GOSTRING_TYPEDEF
  2064  typedef _GoString_ GoString;
  2065  #endif
  2066  typedef void *GoMap;
  2067  typedef void *GoChan;
  2068  typedef struct { void *t; void *v; } GoInterface;
  2069  typedef struct { void *data; GoInt len; GoInt cap; } GoSlice;
  2070  
  2071  #endif
  2072  
  2073  /* End of boilerplate cgo prologue.  */
  2074  
  2075  #ifdef __cplusplus
  2076  extern "C" {
  2077  #endif
  2078  `
  2079  
  2080  // gccExportHeaderEpilog goes at the end of the generated header file.
  2081  const gccExportHeaderEpilog = `
  2082  #ifdef __cplusplus
  2083  }
  2084  #endif
  2085  `
  2086  
  2087  // gccgoExportFileProlog is written to the _cgo_export.c file when
  2088  // using gccgo.
  2089  // We use weak declarations, and test the addresses, so that this code
  2090  // works with older versions of gccgo.
  2091  const gccgoExportFileProlog = `
  2092  #line 1 "cgo-gccgo-export-file-prolog"
  2093  extern _Bool runtime_iscgo __attribute__ ((weak));
  2094  
  2095  static void GoInit(void) __attribute__ ((constructor));
  2096  static void GoInit(void) {
  2097  	if(&runtime_iscgo)
  2098  		runtime_iscgo = 1;
  2099  }
  2100  
  2101  extern size_t _cgo_wait_runtime_init_done(void) __attribute__ ((weak));
  2102  `
  2103  

View as plain text