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

View as plain text