Source file src/cmd/cgo/binding.go

     1  // Copyright 2026 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  	"cmp"
    10  	"fmt"
    11  	"go/ast"
    12  	"go/build/constraint"
    13  	"go/parser"
    14  	"go/token"
    15  	"go/types"
    16  	"internal/syslist"
    17  	"io"
    18  	"maps"
    19  	"os"
    20  	"path/filepath"
    21  	"runtime"
    22  	"slices"
    23  	"strconv"
    24  	"strings"
    25  	"sync"
    26  
    27  	"cmd/internal/edit"
    28  	"cmd/internal/hash"
    29  	"cmd/internal/objabi"
    30  	"cmd/internal/par"
    31  )
    32  
    33  // BindingVar describes a C global variable bound with //cgo:var.
    34  type BindingVar struct {
    35  	Name    string // Internal identifier (used in _Cvar_<Name>)
    36  	GoName  string // Go variable named by the pragma
    37  	CName   string // C symbol name
    38  	BindC   bool   // The pragma used the C.<CName> form, so C.<CName> is bound as well
    39  	Type    string // Go type expression
    40  	Library string // Shared library or DLL name; empty for libc and static
    41  	LibC    bool   // The symbol comes from the platform C runtime (libc)
    42  	Static  bool   // The symbol is resolved at link time from a .syso or .a (static)
    43  
    44  	// Methods of //cgo:dynload types:
    45  	RecvType string // The //cgo:dynload type, for a //cgo:var LibT.GoName pragma
    46  	SymIndex int    // Index of the symbol in RecvType's per-instance symbol table
    47  }
    48  
    49  // Bindings holds the parsed declarations and linker flags collected
    50  // from the //cgo: pragmas in a package.
    51  type Bindings struct {
    52  	mu              sync.Mutex
    53  	Package         string
    54  	LdFlags         []string
    55  	Vars            []BindingVar
    56  	Funcs           []BindingFunc
    57  	UsedBuiltins    map[string]bool   // cgo builtins (such as CString) referenced as C.name
    58  	TypeGoToC       map[string]string // Go type name -> C name, for //cgo:type GoName C.cName
    59  	TypeGoToAnyC    map[string]string // Go type name -> C name, for all //cgo:type pragmas
    60  	ConstCToGo      map[string]string // C name -> Go const name, for //cgo:const GoName C.cName
    61  	GoOnlyCNames    map[string]bool   // C names bound by pragmas without the C. prefix
    62  	DynloadTypes    []string          // //cgo:dynload types, in pragma order
    63  	DynloadCounts   map[string]int    // number of symbols bound for each //cgo:dynload type
    64  	DynloadVars     []BindingVar      // //cgo:var LibT.GoName methods
    65  	TypeMap         map[string]BindingType
    66  	UsedFuncPtrs    map[string]bool // bound C function names referenced in non-call context
    67  	UsedExportCalls map[string]bool // //export function names called via C.<name>(...)
    68  
    69  	typeSpecs             map[string]*ast.TypeSpec
    70  	resolveUsedTypeInFile func(expr ast.Expr, inPtr bool, imp fileImports)
    71  	tpkg                  *types.Package
    72  	typeInfo              *types.Info
    73  	constPkg              *types.Package
    74  	constFset             *token.FileSet
    75  	constFilePos          map[string]token.Pos
    76  	constSources          []bindingSource
    77  }
    78  
    79  // bindingSource holds the raw bytes and parsed AST of a source file inspected
    80  // for //cgo: pragmas.
    81  type bindingSource struct {
    82  	path     string // trimmed path for diagnostics
    83  	origPath string // untrimmed path for ${SRCDIR} expansion; defaults to path
    84  	data     []byte
    85  	file     *ast.File
    86  }
    87  
    88  func (bf *Bindings) needCMalloc() bool {
    89  	return bf.UsedBuiltins["CString"] || bf.UsedBuiltins["CBytes"] || bf.UsedBuiltins["_CMalloc"]
    90  }
    91  
    92  func targetPtrSize() int64 {
    93  	sz := ptrSizeMap[goarch]
    94  	if sz == 0 {
    95  		fatalf("unknown ptrSize for $GOARCH %q", goarch)
    96  	}
    97  	return sz
    98  }
    99  
   100  func targetCLongSize() int64 {
   101  	if goos == "windows" {
   102  		return 4
   103  	}
   104  	return targetPtrSize()
   105  }
   106  
   107  // forEachImportC calls fn for every `import "C"` spec in file, passing its
   108  // enclosing GenDecl, the ImportSpec, and its associated doc comment group.
   109  func forEachImportC(file *ast.File, fn func(gd *ast.GenDecl, spec *ast.ImportSpec, doc *ast.CommentGroup)) {
   110  	if file == nil {
   111  		return
   112  	}
   113  	for _, decl := range file.Decls {
   114  		gd, ok := decl.(*ast.GenDecl)
   115  		if !ok || gd.Tok != token.IMPORT {
   116  			continue
   117  		}
   118  		for _, spec := range gd.Specs {
   119  			imp, ok := spec.(*ast.ImportSpec)
   120  			if !ok || imp.Path.Value != `"C"` {
   121  				continue
   122  			}
   123  			doc := imp.Doc
   124  			if doc == nil && len(gd.Specs) == 1 {
   125  				doc = gd.Doc
   126  			}
   127  			fn(gd, imp, doc)
   128  		}
   129  	}
   130  }
   131  
   132  func primitiveCtypeToGo(name string) (string, bool) {
   133  	switch name {
   134  	case "_Ctype_char":
   135  		if targetCCharIsUnsigned(goos, goarch) {
   136  			return "uint8", true
   137  		}
   138  		return "int8", true
   139  	case "_Ctype_schar", "_Ctype_int8_t":
   140  		return "int8", true
   141  	case "_Ctype_uchar", "_Ctype_uint8_t":
   142  		return "uint8", true
   143  	case "_Ctype_short", "_Ctype_int16_t":
   144  		return "int16", true
   145  	case "_Ctype_ushort", "_Ctype_uint16_t":
   146  		return "uint16", true
   147  	case "_Ctype_int", "_Ctype_int32_t":
   148  		return "int32", true
   149  	case "_Ctype_uint", "_Ctype_uint32_t":
   150  		return "uint32", true
   151  	case "_Ctype_long":
   152  		if targetCLongSize() == 4 {
   153  			return "int32", true
   154  		}
   155  		return "int64", true
   156  	case "_Ctype_ulong":
   157  		if targetCLongSize() == 4 {
   158  			return "uint32", true
   159  		}
   160  		return "uint64", true
   161  	case "_Ctype_longlong", "_Ctype_int64_t":
   162  		return "int64", true
   163  	case "_Ctype_ulonglong", "_Ctype_uint64_t":
   164  		return "uint64", true
   165  	case "_Ctype_size_t", "_Ctype_uintptr_t":
   166  		if targetPtrSize() == 4 {
   167  			return "uint32", true
   168  		}
   169  		return "uint64", true
   170  	case "_Ctype_ssize_t", "_Ctype_ptrdiff_t", "_Ctype_intptr_t", "_Ctype_intgo":
   171  		if targetPtrSize() == 4 {
   172  			return "int32", true
   173  		}
   174  		return "int64", true
   175  	case "_Ctype_float":
   176  		return "float32", true
   177  	case "_Ctype_double":
   178  		return "float64", true
   179  	case "_Ctype__Bool", "_Ctype_bool":
   180  		return "bool", true
   181  	case "_Ctype_void":
   182  		return "[0]byte", true
   183  	case "_Ctype__GoString_":
   184  		return "string", true
   185  	case "_Ctype__GoBytes_":
   186  		return "[]byte", true
   187  	}
   188  	return "", false
   189  }
   190  
   191  // isStandardC reports whether lib names a standard C runtime or system library
   192  // that is implicitly linked by the platform runtime and should not be emitted
   193  // as an explicit shared-library dependency.
   194  func isStandardC(lib string) bool {
   195  	base := filepath.Base(lib)
   196  	lower := strings.ToLower(base)
   197  	switch lower {
   198  	case "c", "libc", "pthread", "libpthread", "dl", "libdl",
   199  		"libc.dylib", "libpthread.dylib",
   200  		"msvcrt", "msvcrt.dll", "ucrtbase", "ucrtbase.dll", "kernel32", "kernel32.dll":
   201  		return true
   202  	}
   203  	if goos == "darwin" || goos == "ios" {
   204  		if lower == "system" || lower == "libsystem" ||
   205  			strings.HasPrefix(lower, "libsystem.") || strings.HasPrefix(lower, "libsystem_") {
   206  			return true
   207  		}
   208  	}
   209  	return strings.HasPrefix(base, "libc.so") ||
   210  		strings.HasPrefix(base, "libpthread.so") ||
   211  		strings.HasPrefix(base, "libdl.so") ||
   212  		strings.HasPrefix(base, "ld-linux") ||
   213  		strings.HasPrefix(base, "ld-musl")
   214  }
   215  
   216  // dynLibName returns the name under which a dynamically linked library lib
   217  // is recorded as a dependency of the binary (for example, in an ELF DT_NEEDED
   218  // entry or a Mach-O LC_LOAD_DYLIB command). Elsewhere only the base name is
   219  // recorded and the library is found through the dynamic linker's search path,
   220  // but on Darwin an install name is a load path that dyld uses as written, so
   221  // absolute and @rpath, @loader_path, and @executable_path names are kept intact.
   222  func dynLibName(lib string) string {
   223  	lib = strings.TrimPrefix(lib, "./")
   224  	if (goos == "darwin" || goos == "ios") && (strings.HasPrefix(lib, "/") || strings.HasPrefix(lib, "@")) {
   225  		return lib
   226  	}
   227  	return filepath.Base(lib)
   228  }
   229  
   230  func windowsDLLName(lib string) string {
   231  	lib = strings.TrimSpace(strings.TrimPrefix(lib, "./"))
   232  	if lib == "" {
   233  		return "msvcrt.dll"
   234  	}
   235  	base := filepath.Base(lib)
   236  	switch strings.ToLower(base) {
   237  	case "c", "libc", "msvcrt", "msvcrt.dll":
   238  		return "msvcrt.dll"
   239  	case "ucrtbase", "ucrtbase.dll":
   240  		return "ucrtbase.dll"
   241  	case "kernel32", "kernel32.dll":
   242  		return "kernel32.dll"
   243  	}
   244  	if !strings.HasSuffix(strings.ToLower(base), ".dll") {
   245  		return base + ".dll"
   246  	}
   247  	return base
   248  }
   249  
   250  // cgoPragma is a parsed cgo binding pragma:
   251  //
   252  //	//cgo:func GoName [C.]cName {"lib" | static | libc}
   253  //	//cgo:var GoName [C.]cName {"lib" | static | libc}
   254  //	//cgo:type GoName [C.]cName
   255  //	//cgo:const GoName [C.]cName
   256  //	//cgo:dynload LibT
   257  //	//cgo:func LibT.GoName cName
   258  //	//cgo:var LibT.GoName cName
   259  //
   260  // Except for //cgo:dynload, a pragma names both a Go declaration, GoName, and
   261  // the C name, cName, that it binds it to. Writing the C name as C.cName also
   262  // lets Go code in the package refer to it as C.cName, as with traditional cgo;
   263  // without the C. prefix, it is reachable only through GoName.
   264  //
   265  // Pragmas are self-contained and may appear anywhere in a file that
   266  // imports "C".
   267  type cgoPragma struct {
   268  	Pos      token.Position
   269  	TokPos   token.Pos // position in the file set the pragma was parsed with
   270  	Text     string    // the pragma comment text
   271  	Kind     string    // pragma name: "func", "var", "type", "const", or "dynload"
   272  	RecvType string    // for func and var, the //cgo:dynload type LibT in the LibT.GoName form
   273  	GoName   string    // Go identifier being bound (the method name in the LibT.GoName form)
   274  	CName    string    // C symbol name
   275  	BindC    bool      // cName was written as C.cName, so Go code may also use C.cName
   276  
   277  	// Library specifier, for func and var.
   278  	Library string // shared library for the "lib" form
   279  	LibC    bool   // libc: the platform C runtime
   280  	Static  bool   // static: resolved at link time from a .syso or .a
   281  }
   282  
   283  // cgoPragmaSyntax maps each supported //cgo: pragma name to its syntax, for
   284  // error messages.
   285  var cgoPragmaSyntax = map[string]string{
   286  	"func":    `//cgo:func GoName [C.]cName {"lib" | static | libc}`,
   287  	"var":     `//cgo:var GoName [C.]cName {"lib" | static | libc}`,
   288  	"type":    `//cgo:type GoName [C.]cName`,
   289  	"const":   `//cgo:const GoName [C.]cName`,
   290  	"dynload": `//cgo:dynload LibT`,
   291  }
   292  
   293  // parseCgoDirective parses a "#cgo [cond] VERB: flags" line (where line starts
   294  // with "#cgo"). It returns the verb, raw flags string, whether any platform
   295  // condition matched the target goos/goarch, and whether the syntax is valid.
   296  func parseCgoDirective(line string) (verb, flags string, matched, ok bool) {
   297  	rest := strings.TrimSpace(line[4:])
   298  	before, after, hasColon := strings.Cut(rest, ":")
   299  	if !hasColon {
   300  		return "", "", false, false
   301  	}
   302  	head := strings.Fields(before)
   303  	if len(head) == 0 {
   304  		return "", "", false, false
   305  	}
   306  	verb = head[len(head)-1]
   307  	switch verb {
   308  	case "CFLAGS", "CPPFLAGS", "CXXFLAGS", "FFLAGS", "LDFLAGS", "pkg-config":
   309  	default:
   310  		return "", "", false, false
   311  	}
   312  	cond := strings.Join(head[:len(head)-1], " ")
   313  	if cond != "" && !matchCgoCond(cond) {
   314  		return verb, "", false, true
   315  	}
   316  	return verb, strings.TrimSpace(after), true, true
   317  }
   318  
   319  func matchCgoCond(cond string) bool {
   320  	expr, err := constraint.Parse("// +build " + cond)
   321  	if err != nil {
   322  		return false
   323  	}
   324  	return expr.Eval(func(tag string) bool {
   325  		switch tag {
   326  		case goos, goarch, "cgo", "gc":
   327  			return true
   328  		case "unix":
   329  			return syslist.UnixOS[goos]
   330  		case "linux":
   331  			return goos == "linux" || goos == "android"
   332  		case "darwin":
   333  			return goos == "darwin" || goos == "ios"
   334  		case "solaris":
   335  			return goos == "solaris" || goos == "illumos"
   336  		}
   337  		return false
   338  	})
   339  }
   340  
   341  // isCgoPragmaComment reports whether the comment text is a //cgo: binding
   342  // pragma (such as //cgo:func).
   343  func isCgoPragmaComment(text string) bool {
   344  	d, ok := ast.ParseDirective(0, text)
   345  	return ok && d.Tool == "cgo" && cgoPragmaSyntax[d.Name] != ""
   346  }
   347  
   348  // parseCgoPragma parses c as a //cgo: binding pragma. It reports false if c
   349  // is not such a pragma and exits with an error if c is malformed.
   350  func parseCgoPragma(fset *token.FileSet, c *ast.Comment) (cgoPragma, bool) {
   351  	d, ok := ast.ParseDirective(c.Pos(), c.Text)
   352  	if !ok || d.Tool != "cgo" || cgoPragmaSyntax[d.Name] == "" {
   353  		return cgoPragma{}, false
   354  	}
   355  	syntax := cgoPragmaSyntax[d.Name]
   356  	bad := func(why string) {
   357  		fatalf("%s: invalid //cgo:%s pragma: %s (want %s)", fset.Position(c.Pos()), d.Name, why, syntax)
   358  	}
   359  	args, err := d.ParseArgs()
   360  	if err != nil {
   361  		bad(err.Error())
   362  	}
   363  	// quoted reports whether arg was written as a quoted string.
   364  	quoted := func(arg ast.DirectiveArg) bool {
   365  		off := int(arg.Pos - d.ArgsPos)
   366  		return off >= 0 && off < len(d.Args) && (d.Args[off] == '"' || d.Args[off] == '`')
   367  	}
   368  	pr := cgoPragma{Pos: fset.Position(c.Pos()), TokPos: c.Pos(), Text: strings.TrimSpace(c.Text), Kind: d.Name}
   369  	if d.Name == "dynload" {
   370  		if len(args) != 1 {
   371  			bad("wrong number of arguments")
   372  		}
   373  		if quoted(args[0]) || !token.IsIdentifier(args[0].Arg) || args[0].Arg == "_" {
   374  			bad(fmt.Sprintf("invalid Go type name %q", args[0].Arg))
   375  		}
   376  		pr.GoName = args[0].Arg
   377  		return pr, true
   378  	}
   379  	if len(args) > 0 && !quoted(args[0]) && (d.Name == "func" || d.Name == "var") {
   380  		if recv, name, ok := strings.Cut(args[0].Arg, "."); ok {
   381  			syntax = "//cgo:" + d.Name + " LibT.GoName cName"
   382  			if len(args) != 2 {
   383  				bad("wrong number of arguments; a //cgo:dynload method takes no library specifier")
   384  			}
   385  			if !token.IsIdentifier(recv) || !token.IsIdentifier(name) || name == "_" {
   386  				bad(fmt.Sprintf("invalid Go name %q", args[0].Arg))
   387  			}
   388  			if quoted(args[1]) {
   389  				bad(fmt.Sprintf("invalid C name %q", args[1].Arg))
   390  			}
   391  			if strings.HasPrefix(args[1].Arg, "C.") {
   392  				bad("a //cgo:dynload method cannot bind a C. name")
   393  			}
   394  			if !token.IsIdentifier(args[1].Arg) {
   395  				bad(fmt.Sprintf("invalid C name %q", args[1].Arg))
   396  			}
   397  			pr.RecvType, pr.GoName, pr.CName = recv, name, args[1].Arg
   398  			return pr, true
   399  		}
   400  	}
   401  	hasLib := d.Name == "func" || d.Name == "var"
   402  	want := 2
   403  	if hasLib {
   404  		want = 3
   405  	}
   406  	if len(args) != want {
   407  		bad("wrong number of arguments")
   408  	}
   409  	if quoted(args[0]) || !token.IsIdentifier(args[0].Arg) || args[0].Arg == "_" {
   410  		bad(fmt.Sprintf("invalid Go name %q", args[0].Arg))
   411  	}
   412  	pr.GoName = args[0].Arg
   413  	pr.CName, pr.BindC = strings.CutPrefix(args[1].Arg, "C.")
   414  	if quoted(args[1]) || !token.IsIdentifier(pr.CName) {
   415  		bad(fmt.Sprintf("invalid C name %q", args[1].Arg))
   416  	}
   417  	if !hasLib {
   418  		return pr, true
   419  	}
   420  	lib := args[2]
   421  	switch {
   422  	case quoted(lib):
   423  		pr.Library = strings.TrimPrefix(lib.Arg, "./")
   424  		if pr.Library == "" {
   425  			bad("empty library name")
   426  		}
   427  	case lib.Arg == "static":
   428  		pr.Static = true
   429  	case lib.Arg == "libc":
   430  		pr.LibC = true
   431  	default:
   432  		bad(fmt.Sprintf("invalid library specifier %s", lib.Arg))
   433  	}
   434  	return pr, true
   435  }
   436  
   437  // parseCgoPragmas returns the //cgo: binding pragmas in file, in source order.
   438  // Pragmas are only allowed in files that import "C".
   439  func parseCgoPragmas(fset *token.FileSet, file *ast.File) []cgoPragma {
   440  	var pragmas []cgoPragma
   441  	importsC := hasImportCFile(file)
   442  	for _, cg := range file.Comments {
   443  		for _, c := range cg.List {
   444  			pr, ok := parseCgoPragma(fset, c)
   445  			if !ok {
   446  				continue
   447  			}
   448  			if !importsC {
   449  				fatalf("%s: //cgo:%s pragma is only allowed in a file that imports \"C\"", pr.Pos, pr.Kind)
   450  			}
   451  			pragmas = append(pragmas, pr)
   452  		}
   453  	}
   454  	return pragmas
   455  }
   456  
   457  // fileImports records the local import aliases used in a single Go source file
   458  // for the standard packages recognized by cgo bindings.
   459  type fileImports struct {
   460  	hasUnsafe  bool
   461  	unsafe     map[string]bool // local alias -> true ("." for dot import)
   462  	structs    map[string]bool
   463  	runtimeCgo map[string]bool
   464  }
   465  
   466  func collectFileImports(file *ast.File) fileImports {
   467  	imp := fileImports{
   468  		unsafe:     make(map[string]bool),
   469  		structs:    make(map[string]bool),
   470  		runtimeCgo: make(map[string]bool),
   471  	}
   472  	if file == nil {
   473  		return imp
   474  	}
   475  	for _, s := range file.Imports {
   476  		name := ""
   477  		if s.Name != nil {
   478  			name = s.Name.Name
   479  		}
   480  		switch s.Path.Value {
   481  		case `"unsafe"`:
   482  			imp.hasUnsafe = true
   483  			if name == "" {
   484  				imp.unsafe["unsafe"] = true
   485  			} else if name != "_" {
   486  				imp.unsafe[name] = true
   487  			}
   488  		case `"structs"`:
   489  			if name == "" {
   490  				imp.structs["structs"] = true
   491  			} else if name != "_" {
   492  				imp.structs[name] = true
   493  			}
   494  		case `"runtime/cgo"`:
   495  			if name == "" {
   496  				imp.runtimeCgo["cgo"] = true
   497  			} else if name != "_" {
   498  				imp.runtimeCgo[name] = true
   499  			}
   500  		}
   501  	}
   502  	return imp
   503  }
   504  
   505  func structHasHostLayoutOrIncomplete(st *ast.StructType, imp fileImports) bool {
   506  	if st.Fields == nil || len(st.Fields.List) == 0 {
   507  		return true
   508  	}
   509  	for _, field := range st.Fields.List {
   510  		switch ft := field.Type.(type) {
   511  		case *ast.SelectorExpr:
   512  			if id, ok := ft.X.(*ast.Ident); ok {
   513  				if (imp.structs[id.Name] && ft.Sel.Name == "HostLayout") ||
   514  					(imp.runtimeCgo[id.Name] && ft.Sel.Name == "Incomplete") {
   515  					return true
   516  				}
   517  			}
   518  		case *ast.Ident:
   519  			if (imp.structs["."] && ft.Name == "HostLayout") ||
   520  				(imp.runtimeCgo["."] && ft.Name == "Incomplete") {
   521  				return true
   522  			}
   523  		}
   524  	}
   525  	return false
   526  }
   527  
   528  // cVarExpr returns the Go expression for the bound C variable v.
   529  func cVarExpr(v BindingVar) string {
   530  	return "(*_Cvar_" + v.Name + ")"
   531  }
   532  
   533  // varImportSym returns the local symbol name for the dynamically imported
   534  // C variable v. On Windows, the symbol is the variable's import address
   535  // table slot rather than the variable itself; see writeGoTypes.
   536  func varImportSym(v BindingVar) string {
   537  	if goos == "windows" {
   538  		return fmt.Sprintf("_cgo%s_var_addr_%s", cPrefix, v.Name)
   539  	}
   540  	return fmt.Sprintf("_cgo%s_var_%s", cPrefix, v.Name)
   541  }
   542  
   543  func hasImportCFile(file *ast.File) bool {
   544  	return file != nil && slices.ContainsFunc(file.Imports, func(imp *ast.ImportSpec) bool {
   545  		return imp.Path.Value == `"C"`
   546  	})
   547  }
   548  
   549  func replaceCConstNodes(eb *edit.Buffer, tf *token.File, node ast.Node, constCToGo map[string]string) {
   550  	ast.Inspect(node, func(n ast.Node) bool {
   551  		sel, ok := n.(*ast.SelectorExpr)
   552  		if !ok {
   553  			return true
   554  		}
   555  		if id, ok := sel.X.(*ast.Ident); ok && id.Name == "C" {
   556  			if goName, ok := constCToGo[sel.Sel.Name]; ok {
   557  				eb.Replace(tf.Offset(sel.Pos()), tf.Offset(sel.End()), goName)
   558  				return false
   559  			}
   560  		}
   561  		return true
   562  	})
   563  }
   564  
   565  func (p *Package) buildConstPkg(entry *Bindings) {
   566  	constFset := token.NewFileSet()
   567  	entry.constFset = constFset
   568  	var files []*ast.File
   569  	filePos := make(map[string]token.Pos, len(entry.constSources))
   570  	for _, src := range entry.constSources {
   571  		if src.file == nil || src.data == nil {
   572  			continue
   573  		}
   574  		data := src.data
   575  		if hasImportCFile(src.file) {
   576  			if tf := p.fset.File(src.file.Package); tf != nil {
   577  				eb := edit.NewBuffer(data)
   578  				for _, decl := range src.file.Decls {
   579  					if gd, ok := decl.(*ast.GenDecl); ok && (gd.Tok == token.CONST || gd.Tok == token.TYPE) {
   580  						replaceCConstNodes(eb, tf, gd, entry.ConstCToGo)
   581  					}
   582  				}
   583  				data = eb.Bytes()
   584  			}
   585  		}
   586  		f, err := parser.ParseFile(constFset, src.path, data, 0)
   587  		if err != nil {
   588  			continue
   589  		}
   590  		files = append(files, f)
   591  		filePos[src.path] = f.Name.Pos()
   592  	}
   593  	if len(files) == 0 {
   594  		return
   595  	}
   596  	conf := types.Config{
   597  		Importer:                 bindingStubImporter{},
   598  		Sizes:                    types.SizesFor("gc", goarch),
   599  		Error:                    func(error) {},
   600  		DisableUnusedImportCheck: true,
   601  	}
   602  	entry.constPkg, _ = conf.Check(entry.Package, constFset, files, nil)
   603  	entry.constFilePos = filePos
   604  }
   605  
   606  // evalArrayLenIn evaluates exprStr as a Go array length in pkg at pos.
   607  // Evaluating "[" + exprStr + "]struct{}" lets go/types apply Go's array-length
   608  // rules and return the length via (*types.Array).Len without importing
   609  // go/constant (which cmd/dist rewrites to bootstrap/go/constant during
   610  // bootstrap while keeping go/types from the bootstrap toolchain).
   611  func evalArrayLenIn(fset *token.FileSet, pkg *types.Package, pos token.Pos, exprStr string) (int64, bool) {
   612  	tv, err := types.Eval(fset, pkg, pos, "["+exprStr+"]struct{}")
   613  	if err != nil {
   614  		return 0, false
   615  	}
   616  	if arr, ok := tv.Type.(*types.Array); ok && arr.Len() >= 0 {
   617  		return arr.Len(), true
   618  	}
   619  	return 0, false
   620  }
   621  
   622  func (p *Package) evalBindingArrayLen(expr ast.Expr, entry *Bindings) (int64, bool) {
   623  	var buf bytes.Buffer
   624  	noSourceConf.Fprint(&buf, p.fset, expr)
   625  	src := buf.Bytes()
   626  	if entry != nil && len(entry.ConstCToGo) > 0 {
   627  		tmpFset := token.NewFileSet()
   628  		if parsed, err := parser.ParseExprFrom(tmpFset, "", src, 0); err == nil {
   629  			if tf := tmpFset.File(parsed.Pos()); tf != nil {
   630  				eb := edit.NewBuffer(src)
   631  				replaceCConstNodes(eb, tf, parsed, entry.ConstCToGo)
   632  				src = eb.Bytes()
   633  			}
   634  		}
   635  	}
   636  	exprStr := string(src)
   637  	if entry != nil && entry.tpkg != nil {
   638  		if n, ok := evalArrayLenIn(p.fset, entry.tpkg, expr.Pos(), exprStr); ok {
   639  			return n, true
   640  		}
   641  		if len(entry.ConstCToGo) > 0 {
   642  			if entry.constFset == nil {
   643  				p.buildConstPkg(entry)
   644  			}
   645  			if entry.constPkg != nil {
   646  				pos := token.NoPos
   647  				if tf := p.fset.File(expr.Pos()); tf != nil {
   648  					pos = entry.constFilePos[tf.Name()]
   649  				}
   650  				if n, ok := evalArrayLenIn(entry.constFset, entry.constPkg, pos, exprStr); ok {
   651  					return n, true
   652  				}
   653  			}
   654  		}
   655  	} else {
   656  		if n, ok := evalArrayLenIn(token.NewFileSet(), nil, token.NoPos, exprStr); ok {
   657  			return n, true
   658  		}
   659  	}
   660  	return 0, false
   661  }
   662  
   663  func (p *Package) evalArrayLen(arr *ast.ArrayType, entry *Bindings) int64 {
   664  	if entry != nil && entry.typeInfo != nil {
   665  		if tv, ok := entry.typeInfo.Types[arr]; ok {
   666  			if t, ok := tv.Type.(*types.Array); ok && t.Len() >= 0 {
   667  				return t.Len()
   668  			}
   669  		}
   670  	}
   671  	if n, ok := p.evalBindingArrayLen(arr.Len, entry); ok {
   672  		return n
   673  	}
   674  	var lb bytes.Buffer
   675  	noSourceConf.Fprint(&lb, p.fset, arr.Len)
   676  	fatalf("%s: cannot evaluate array length %q as a non-negative integer constant", p.fset.Position(arr.Len.Pos()), lb.String())
   677  	return 0
   678  }
   679  
   680  func (p *Package) parseBinding(bindingPath string, data []byte) *Bindings {
   681  	return p.parseBindingFiles([]bindingSource{{path: bindingPath, data: data}})
   682  }
   683  
   684  // recvTypeName returns the name of the receiver base type of method d, or ""
   685  // if it is not a (possibly pointer to a) named type.
   686  func recvTypeName(d *ast.FuncDecl) string {
   687  	if d.Recv == nil || len(d.Recv.List) != 1 {
   688  		return ""
   689  	}
   690  	t := d.Recv.List[0].Type
   691  	if star, ok := t.(*ast.StarExpr); ok {
   692  		t = star.X
   693  	}
   694  	if id, ok := t.(*ast.Ident); ok {
   695  		return id.Name
   696  	}
   697  	return ""
   698  }
   699  
   700  // structEmbedsLibrary reports whether ts is a non-generic, non-alias struct
   701  // type that embeds runtime/cgo.Library.
   702  func structEmbedsLibrary(ts *ast.TypeSpec, imp fileImports) bool {
   703  	st, ok := ts.Type.(*ast.StructType)
   704  	if !ok || ts.TypeParams != nil || ts.Assign.IsValid() {
   705  		return false
   706  	}
   707  	for _, fld := range st.Fields.List {
   708  		if len(fld.Names) != 0 {
   709  			continue
   710  		}
   711  		switch ft := fld.Type.(type) {
   712  		case *ast.SelectorExpr:
   713  			if id, ok := ft.X.(*ast.Ident); ok && imp.runtimeCgo[id.Name] && ft.Sel.Name == "Library" {
   714  				return true
   715  			}
   716  		case *ast.Ident:
   717  			if imp.runtimeCgo["."] && ft.Name == "Library" {
   718  				return true
   719  			}
   720  		}
   721  	}
   722  	return false
   723  }
   724  
   725  func (p *Package) checkDynloadType(pr cgoPragma, ts *ast.TypeSpec, imp fileImports) {
   726  	if ts == nil {
   727  		fatalf("%s: //cgo:dynload %s: missing declaration of type %s", pr.Pos, pr.GoName, pr.GoName)
   728  	}
   729  	if !structEmbedsLibrary(ts, imp) {
   730  		fatalf("%s: //cgo:dynload type %s must be a struct type that embeds cgo.Library", p.fset.Position(ts.Pos()), pr.GoName)
   731  	}
   732  }
   733  
   734  func (p *Package) parseBindingFiles(sources []bindingSource) *Bindings {
   735  	if p.noCallbacks == nil {
   736  		p.noCallbacks = make(map[string]bool)
   737  	}
   738  	if p.noEscapes == nil {
   739  		p.noEscapes = make(map[string]bool)
   740  	}
   741  	entry := &Bindings{
   742  		LdFlags:         append([]string(nil), p.LdFlags...),
   743  		UsedBuiltins:    make(map[string]bool),
   744  		TypeGoToC:       make(map[string]string),
   745  		TypeGoToAnyC:    make(map[string]string),
   746  		ConstCToGo:      make(map[string]string),
   747  		GoOnlyCNames:    make(map[string]bool),
   748  		DynloadCounts:   make(map[string]int),
   749  		UsedFuncPtrs:    make(map[string]bool),
   750  		UsedExportCalls: make(map[string]bool),
   751  		constSources:    sources,
   752  	}
   753  
   754  	var pragmas []cgoPragma
   755  	for i := range sources {
   756  		src := &sources[i]
   757  		if src.file == nil {
   758  			fileAST, err := parser.ParseFile(p.fset, src.path, src.data, parser.ParseComments)
   759  			if err != nil {
   760  				fatalf("parsing %s: %s", src.path, err)
   761  			}
   762  			src.file = fileAST
   763  		}
   764  		if entry.Package == "" {
   765  			entry.Package = src.file.Name.Name
   766  		}
   767  		pragmas = append(pragmas, parseCgoPragmas(p.fset, src.file)...)
   768  
   769  		// Collect #cgo noescape and nocallback directives, and #cgo LDFLAGS
   770  		// directives (honoring their build constraints), from the import "C"
   771  		// preamble. When cmd/go passes -ldflags, it has already collected
   772  		// (and checked against CGO_LDFLAGS_ALLOW) the package's flags, so the
   773  		// preamble is not consulted for them.
   774  		if !hasImportCFile(src.file) {
   775  			continue
   776  		}
   777  		origPath := src.origPath
   778  		if origPath == "" {
   779  			origPath = src.path
   780  		}
   781  		srcDirVal := filepath.ToSlash(filepath.Dir(origPath))
   782  		forEachImportC(src.file, func(_ *ast.GenDecl, _ *ast.ImportSpec, doc *ast.CommentGroup) {
   783  			if doc == nil {
   784  				return
   785  			}
   786  			for line := range strings.SplitSeq(commentText(doc), "\n") {
   787  				cgoLine := strings.TrimSpace(line)
   788  				if !strings.HasPrefix(cgoLine, "#cgo") || len(cgoLine) < 5 || (cgoLine[4] != ' ' && cgoLine[4] != '\t') {
   789  					continue
   790  				}
   791  				if fields := strings.Fields(cgoLine); len(fields) == 3 {
   792  					switch fields[1] {
   793  					case "nocallback":
   794  						p.noCallbacks[fields[2]] = true
   795  						continue
   796  					case "noescape":
   797  						p.noEscapes[fields[2]] = true
   798  						continue
   799  					}
   800  				}
   801  				if ldflagsSet {
   802  					continue
   803  				}
   804  				verb, raw, matched, ok := parseCgoDirective(cgoLine)
   805  				if !ok || !matched || verb != "LDFLAGS" || raw == "" {
   806  					continue
   807  				}
   808  				fields, err := splitQuoted(raw)
   809  				if err != nil {
   810  					fatalf("%s: bad #cgo LDFLAGS: %q (%s)", src.path, raw, err)
   811  				}
   812  				for i, f := range fields {
   813  					fields[i] = strings.ReplaceAll(f, "${SRCDIR}", srcDirVal)
   814  				}
   815  				entry.LdFlags = append(entry.LdFlags, fields...)
   816  			}
   817  		})
   818  	}
   819  
   820  	// Index the package-level declarations that pragmas may name.
   821  	funcDecls := make(map[string]*ast.FuncDecl)
   822  	funcImports := make(map[string]fileImports)
   823  	methodDecls := make(map[string]*ast.FuncDecl) // keyed by "T.M"
   824  	methodImports := make(map[string]fileImports)
   825  	typeSpecs := make(map[string]*ast.TypeSpec)
   826  	typeImports := make(map[string]fileImports)
   827  	constSpecs := make(map[string]*ast.ValueSpec)
   828  	varSpecs := make(map[string]*ast.ValueSpec)
   829  	varImports := make(map[string]fileImports)
   830  	var typeOrder []string
   831  	for _, src := range sources {
   832  		imp := collectFileImports(src.file)
   833  		for _, decl := range src.file.Decls {
   834  			switch d := decl.(type) {
   835  			case *ast.FuncDecl:
   836  				if d.Recv == nil {
   837  					funcDecls[d.Name.Name] = d
   838  					funcImports[d.Name.Name] = imp
   839  				} else if recv := recvTypeName(d); recv != "" {
   840  					methodDecls[recv+"."+d.Name.Name] = d
   841  					methodImports[recv+"."+d.Name.Name] = imp
   842  				}
   843  			case *ast.GenDecl:
   844  				for _, spec := range d.Specs {
   845  					switch s := spec.(type) {
   846  					case *ast.TypeSpec:
   847  						if _, ok := typeSpecs[s.Name.Name]; !ok {
   848  							typeOrder = append(typeOrder, s.Name.Name)
   849  							typeSpecs[s.Name.Name] = s
   850  							typeImports[s.Name.Name] = imp
   851  						}
   852  					case *ast.ValueSpec:
   853  						m := varSpecs
   854  						if d.Tok == token.CONST {
   855  							m = constSpecs
   856  						}
   857  						for _, id := range s.Names {
   858  							m[id.Name] = s
   859  							if d.Tok == token.VAR {
   860  								varImports[id.Name] = imp
   861  							}
   862  						}
   863  					}
   864  				}
   865  			}
   866  		}
   867  	}
   868  	entry.typeSpecs = typeSpecs
   869  
   870  	// Check that each pragma names a declaration of the right kind, and
   871  	// that no Go or C. name is bound twice.
   872  	boundGo := make(map[string]bool)
   873  	boundC := make(map[string]bool)
   874  	for _, pr := range pragmas {
   875  		if pr.Kind == "dynload" {
   876  			p.checkDynloadType(pr, typeSpecs[pr.GoName], typeImports[pr.GoName])
   877  			if _, ok := entry.DynloadCounts[pr.GoName]; ok {
   878  				fatalf("%s: %s is declared by more than one //cgo:dynload pragma", pr.Pos, pr.GoName)
   879  			}
   880  			boundGo[pr.GoName] = true
   881  			entry.DynloadCounts[pr.GoName] = 0
   882  			entry.DynloadTypes = append(entry.DynloadTypes, pr.GoName)
   883  		}
   884  	}
   885  	for _, pr := range pragmas {
   886  		if pr.Kind == "dynload" {
   887  			continue
   888  		}
   889  		if pr.RecvType != "" {
   890  			key := pr.RecvType + "." + pr.GoName
   891  			if _, ok := entry.DynloadCounts[pr.RecvType]; !ok {
   892  				fatalf("%s: //cgo:%s %s: %s is not declared with //cgo:dynload", pr.Pos, pr.Kind, key, pr.RecvType)
   893  			}
   894  			if boundGo[key] {
   895  				fatalf("%s: %s is bound by more than one //cgo: pragma", pr.Pos, key)
   896  			}
   897  			boundGo[key] = true
   898  			d := methodDecls[key]
   899  			if d == nil {
   900  				fatalf("%s: //cgo:%s %s: missing declaration of method (*%s).%s", pr.Pos, pr.Kind, key, pr.RecvType, pr.GoName)
   901  			}
   902  			if _, ok := d.Recv.List[0].Type.(*ast.StarExpr); !ok {
   903  				fatalf("%s: //cgo:%s method %s must have a pointer receiver (*%s)", p.fset.Position(d.Pos()), pr.Kind, pr.GoName, pr.RecvType)
   904  			}
   905  			continue
   906  		}
   907  		if boundGo[pr.GoName] {
   908  			fatalf("%s: %s is bound by more than one //cgo: pragma", pr.Pos, pr.GoName)
   909  		}
   910  		boundGo[pr.GoName] = true
   911  		if pr.BindC {
   912  			if pr.CName == "malloc" || (pr.CName != "_CMalloc" && builtinDefs[pr.CName] != "") {
   913  				fatalf("%s: C.%s is a cgo builtin and cannot be bound by a //cgo: pragma", pr.Pos, pr.CName)
   914  			}
   915  			if boundC[pr.CName] {
   916  				fatalf("%s: C.%s is bound by more than one //cgo: pragma", pr.Pos, pr.CName)
   917  			}
   918  			boundC[pr.CName] = true
   919  		} else {
   920  			entry.GoOnlyCNames[pr.CName] = true
   921  		}
   922  		var found bool
   923  		switch pr.Kind {
   924  		case "func":
   925  			_, found = funcDecls[pr.GoName]
   926  		case "type":
   927  			_, found = typeSpecs[pr.GoName]
   928  		case "const":
   929  			_, found = constSpecs[pr.GoName]
   930  			if found && pr.BindC {
   931  				entry.ConstCToGo[pr.CName] = pr.GoName
   932  			}
   933  		case "var":
   934  			_, found = varSpecs[pr.GoName]
   935  		}
   936  		if !found {
   937  			fatalf("%s: //cgo:%s %s: missing declaration of %s %s", pr.Pos, pr.Kind, pr.GoName, pr.Kind, pr.GoName)
   938  		}
   939  	}
   940  
   941  	if len(sources) > 0 {
   942  		astFiles := make([]*ast.File, len(sources))
   943  		for i, src := range sources {
   944  			astFiles[i] = src.file
   945  		}
   946  		entry.typeInfo = &types.Info{
   947  			Types:  make(map[ast.Expr]types.TypeAndValue),
   948  			Uses:   make(map[*ast.Ident]types.Object),
   949  			Scopes: make(map[ast.Node]*types.Scope),
   950  		}
   951  		typeConf := types.Config{
   952  			Importer:                 bindingStubImporter{},
   953  			Sizes:                    types.SizesFor("gc", goarch),
   954  			Error:                    func(error) {},
   955  			DisableUnusedImportCheck: true,
   956  		}
   957  		entry.tpkg, _ = typeConf.Check(entry.Package, p.fset, astFiles, entry.typeInfo)
   958  	}
   959  
   960  	type rawTypeInfo struct {
   961  		ts    *ast.TypeSpec
   962  		imp   fileImports
   963  		cName string
   964  	}
   965  	rawTypes := make(map[string]rawTypeInfo)
   966  	cToGoType := make(map[string]string)
   967  	var pragmaTypes []string
   968  	for _, pr := range pragmas {
   969  		if pr.Kind != "type" {
   970  			continue
   971  		}
   972  		ts := typeSpecs[pr.GoName]
   973  		if ts.TypeParams != nil {
   974  			fatalf("%s: //cgo:type %s cannot have type parameters", p.fset.Position(ts.Pos()), pr.GoName)
   975  		}
   976  		if st, ok := ts.Type.(*ast.StructType); ok && !structHasHostLayoutOrIncomplete(st, typeImports[pr.GoName]) {
   977  			fatalf("%s: //cgo:type struct %s must embed structs.HostLayout", p.fset.Position(ts.Pos()), pr.GoName)
   978  		}
   979  		entry.TypeGoToAnyC[pr.GoName] = pr.CName
   980  		if pr.BindC {
   981  			entry.TypeGoToC[pr.GoName] = pr.CName
   982  			cToGoType[pr.CName] = pr.GoName
   983  		}
   984  		pragmaTypes = append(pragmaTypes, pr.GoName)
   985  	}
   986  	for _, goName := range typeOrder {
   987  		rawTypes[goName] = rawTypeInfo{ts: typeSpecs[goName], imp: typeImports[goName], cName: entry.TypeGoToC[goName]}
   988  	}
   989  
   990  	typeMap := make(map[string]BindingType)
   991  	entry.TypeMap = typeMap
   992  	resolving := make(map[string]bool)
   993  	resolved := make(map[string]bool)
   994  
   995  	var resolveType func(goName string)
   996  	var validateUsedTypeExpr func(expr ast.Expr, inPtr bool, imp fileImports)
   997  
   998  	validateUsedTypeExpr = func(expr ast.Expr, inPtr bool, imp fileImports) {
   999  		if expr == nil {
  1000  			return
  1001  		}
  1002  		switch e := expr.(type) {
  1003  		case *ast.ParenExpr:
  1004  			validateUsedTypeExpr(e.X, inPtr, imp)
  1005  		case *ast.StarExpr:
  1006  			validateUsedTypeExpr(e.X, true, imp)
  1007  		case *ast.ArrayType:
  1008  			if e.Len != nil {
  1009  				p.evalArrayLen(e, entry)
  1010  			}
  1011  			validateUsedTypeExpr(e.Elt, false, imp)
  1012  		case *ast.StructType:
  1013  			if e.Fields != nil {
  1014  				for _, fld := range e.Fields.List {
  1015  					validateUsedTypeExpr(fld.Type, false, imp)
  1016  				}
  1017  			}
  1018  		case *ast.SelectorExpr:
  1019  			id, ok := e.X.(*ast.Ident)
  1020  			if !ok {
  1021  				return
  1022  			}
  1023  			if (imp.unsafe[id.Name] && e.Sel.Name == "Pointer") ||
  1024  				(imp.structs[id.Name] && e.Sel.Name == "HostLayout") ||
  1025  				(imp.runtimeCgo[id.Name] && e.Sel.Name == "Incomplete") {
  1026  				return
  1027  			}
  1028  			if id.Name == "C" {
  1029  				if _, isPrim := primitiveCtypeToGo("_Ctype_" + e.Sel.Name); isPrim {
  1030  					return
  1031  				}
  1032  				if gName, ok := cToGoType[e.Sel.Name]; ok {
  1033  					resolveType(gName)
  1034  					return
  1035  				}
  1036  				if inPtr {
  1037  					return
  1038  				}
  1039  				fatalf("%s: cannot resolve C ABI layout of undefined type C.%s", p.fset.Position(e.Pos()), e.Sel.Name)
  1040  			}
  1041  			fatalf("%s: cannot resolve C ABI layout of external type %s.%s", p.fset.Position(e.Pos()), id.Name, e.Sel.Name)
  1042  		case *ast.Ident:
  1043  			switch e.Name {
  1044  			case "bool", "byte", "rune",
  1045  				"int", "int8", "int16", "int32", "int64",
  1046  				"uint", "uint8", "uint16", "uint32", "uint64", "uintptr",
  1047  				"float32", "float64", "complex64", "complex128",
  1048  				"string", "any", "error":
  1049  				return
  1050  			}
  1051  			if (imp.unsafe["."] && e.Name == "Pointer") ||
  1052  				(imp.structs["."] && e.Name == "HostLayout") ||
  1053  				(imp.runtimeCgo["."] && e.Name == "Incomplete") {
  1054  				return
  1055  			}
  1056  			if _, isPrim := primitiveCtypeToGo(e.Name); isPrim {
  1057  				return
  1058  			}
  1059  			if _, exists := rawTypes[e.Name]; exists {
  1060  				resolveType(e.Name)
  1061  				return
  1062  			}
  1063  			fatalf("%s: cannot resolve C ABI layout of undefined type %s", p.fset.Position(e.Pos()), e.Name)
  1064  		}
  1065  	}
  1066  
  1067  	abiInspector := &ABIConfig{OS: goos, Arch: goarch, PtrSize: targetPtrSize(), CLongSize: targetCLongSize()}
  1068  	resolveType = func(goName string) {
  1069  		if resolved[goName] || resolving[goName] {
  1070  			return
  1071  		}
  1072  		info, ok := rawTypes[goName]
  1073  		if !ok {
  1074  			return
  1075  		}
  1076  		resolving[goName] = true
  1077  		validateUsedTypeExpr(info.ts.Type, false, info.imp)
  1078  		resolving[goName] = false
  1079  		resolved[goName] = true
  1080  
  1081  		defStr := p.cgoASTToGoDefInFile(info.ts.Type, entry, info.imp)
  1082  		if targetBT, ok := typeMap[defStr]; ok && targetBT.Def != "" {
  1083  			defStr = targetBT.Def
  1084  		}
  1085  		bt := BindingType{Name: goName, Def: defStr}
  1086  		if info.cName != "" {
  1087  			bt.Name = "_Ctype_" + info.cName
  1088  		}
  1089  		// A type that cannot be shared with C has no C ABI layout. The
  1090  		// uses of the type report it (see cTypeError), so skip it here.
  1091  		if cDeclTypeError(defStr, typeMap) == "" {
  1092  			ti := abiInspector.inspectType(defStr, typeMap)
  1093  			bt.Size, bt.Align, bt.HasPointers = ti.size, ti.align, ti.hasPointers
  1094  		}
  1095  		if info.cName != "" {
  1096  			typeMap[bt.Name] = bt
  1097  		}
  1098  		typeMap[goName] = bt
  1099  	}
  1100  
  1101  	for _, goName := range pragmaTypes {
  1102  		resolveType(goName)
  1103  		if why := cDeclTypeError(goName, typeMap); why != "" {
  1104  			fatalf("%s: //cgo:type %s cannot be shared with C: %s", p.fset.Position(typeSpecs[goName].Pos()), goName, why)
  1105  		}
  1106  	}
  1107  	entry.resolveUsedTypeInFile = validateUsedTypeExpr
  1108  
  1109  	allocDynSym := func(recvType, goName string) (string, int) {
  1110  		dynName := fmt.Sprintf("_dyn%d_%s_%s", len(recvType), recvType, goName)
  1111  		for boundGo[dynName] {
  1112  			dynName = "_" + dynName
  1113  		}
  1114  		idx := entry.DynloadCounts[recvType]
  1115  		entry.DynloadCounts[recvType] = idx + 1
  1116  		return dynName, idx
  1117  	}
  1118  
  1119  	for _, pr := range pragmas {
  1120  		switch pr.Kind {
  1121  		case "var":
  1122  			if pr.RecvType != "" {
  1123  				key := pr.RecvType + "." + pr.GoName
  1124  				d := methodDecls[key]
  1125  				pos := p.fset.Position(d.Pos())
  1126  				if d.Body != nil {
  1127  					fatalf("%s: //cgo:var method %s cannot have a body", pos, pr.GoName)
  1128  				}
  1129  				var star *ast.StarExpr
  1130  				if d.Type.Params.NumFields() == 0 && d.Type.Results.NumFields() == 1 {
  1131  					star, _ = d.Type.Results.List[0].Type.(*ast.StarExpr)
  1132  				}
  1133  				if star == nil || d.Type.TypeParams != nil {
  1134  					fatalf("%s: //cgo:var method %s must have the form func (*%s) %s() *T", pos, pr.GoName, pr.RecvType, pr.GoName)
  1135  				}
  1136  				mImp := methodImports[key]
  1137  				validateUsedTypeExpr(star.X, true, mImp)
  1138  				vType := p.cgoASTToGoDefInFile(star.X, entry, mImp)
  1139  				if why := cDeclTypeError(vType, entry.TypeMap); why != "" {
  1140  					fatalf("%s: //cgo:var method %s: variable type %s cannot be shared with C: %s", p.fset.Position(star.X.Pos()), pr.GoName, vType, why)
  1141  				}
  1142  				dynName, symIdx := allocDynSym(pr.RecvType, pr.GoName)
  1143  				entry.DynloadVars = append(entry.DynloadVars, BindingVar{
  1144  					Name:     dynName,
  1145  					GoName:   pr.GoName,
  1146  					CName:    pr.CName,
  1147  					Type:     vType,
  1148  					RecvType: pr.RecvType,
  1149  					SymIndex: symIdx,
  1150  				})
  1151  				continue
  1152  			}
  1153  			if token.IsExported(pr.GoName) {
  1154  				fatalf("%s: //cgo:var %s: Go variable name must be unexported", pr.Pos, pr.GoName)
  1155  			}
  1156  			vs := varSpecs[pr.GoName]
  1157  			pos := p.fset.Position(vs.Pos())
  1158  			if len(vs.Names) != 1 {
  1159  				fatalf("%s: //cgo:var %s: the variable declaration must declare only %s", pos, pr.GoName, pr.GoName)
  1160  			}
  1161  			if vs.Type == nil {
  1162  				fatalf("%s: //cgo:var variable %s must specify an explicit type", pos, pr.GoName)
  1163  			}
  1164  			if len(vs.Values) > 0 {
  1165  				fatalf("%s: //cgo:var variable %s cannot have an initializer", pos, pr.GoName)
  1166  			}
  1167  			vImp := varImports[pr.GoName]
  1168  			validateUsedTypeExpr(vs.Type, false, vImp)
  1169  			vType := p.cgoASTToGoDefInFile(vs.Type, entry, vImp)
  1170  			if why := cDeclTypeError(vType, entry.TypeMap); why != "" {
  1171  				fatalf("%s: //cgo:var variable %s of type %s cannot be shared with C: %s", p.fset.Position(vs.Type.Pos()), pr.GoName, vType, why)
  1172  			}
  1173  			entry.Vars = append(entry.Vars, BindingVar{
  1174  				Name:    pr.GoName,
  1175  				GoName:  pr.GoName,
  1176  				CName:   pr.CName,
  1177  				BindC:   pr.BindC,
  1178  				Type:    vType,
  1179  				Library: pr.Library,
  1180  				LibC:    pr.LibC,
  1181  				Static:  pr.Static,
  1182  			})
  1183  		case "func":
  1184  			d := funcDecls[pr.GoName]
  1185  			if pr.RecvType != "" {
  1186  				d = methodDecls[pr.RecvType+"."+pr.GoName]
  1187  			}
  1188  			pos := p.fset.Position(d.Pos())
  1189  			if d.Body != nil {
  1190  				fatalf("%s: //cgo:func function %s cannot have a body", pos, pr.GoName)
  1191  			}
  1192  			fnName := pr.GoName
  1193  			if builtinDefs[fnName] != "" || fnName == "_cgo_malloc" {
  1194  				fnName = "_go_" + fnName
  1195  				for boundGo[fnName] {
  1196  					fnName = "_" + fnName
  1197  				}
  1198  			}
  1199  			fn := BindingFunc{
  1200  				Name:    fnName,
  1201  				GoName:  pr.GoName,
  1202  				CName:   pr.CName,
  1203  				BindC:   pr.BindC,
  1204  				Library: pr.Library,
  1205  				LibC:    pr.LibC,
  1206  				Static:  pr.Static,
  1207  			}
  1208  			fImp := funcImports[pr.GoName]
  1209  			if pr.RecvType != "" {
  1210  				fImp = methodImports[pr.RecvType+"."+pr.GoName]
  1211  				fn.Name, fn.SymIndex = allocDynSym(pr.RecvType, pr.GoName)
  1212  				fn.Indirect = true
  1213  				fn.RecvType = pr.RecvType
  1214  			}
  1215  			if d.Type.Params != nil {
  1216  				for _, field := range d.Type.Params.List {
  1217  					validateUsedTypeExpr(field.Type, false, fImp)
  1218  					pType := p.cgoASTToGoDefInFile(field.Type, entry, fImp)
  1219  					if why := cTypeError(pType, entry.TypeMap); why != "" {
  1220  						fatalf("%s: //cgo:func %s: parameter type %s cannot be passed to C: %s", p.fset.Position(field.Type.Pos()), pr.GoName, pType, why)
  1221  					}
  1222  					for range max(1, len(field.Names)) {
  1223  						fn.Params = append(fn.Params, pType)
  1224  					}
  1225  				}
  1226  			}
  1227  			if d.Type.Results != nil && len(d.Type.Results.List) > 0 {
  1228  				res := d.Type.Results.List[0].Type
  1229  				validateUsedTypeExpr(res, false, fImp)
  1230  				fn.Ret = p.cgoASTToGoDefInFile(res, entry, fImp)
  1231  				if why := cTypeError(fn.Ret, entry.TypeMap); why != "" {
  1232  					fatalf("%s: //cgo:func %s: result type %s cannot be returned from C: %s", p.fset.Position(res.Pos()), pr.GoName, fn.Ret, why)
  1233  				}
  1234  			}
  1235  			entry.Funcs = append(entry.Funcs, fn)
  1236  		}
  1237  	}
  1238  	return entry
  1239  }
  1240  
  1241  // processBinding consumes the //cgo: pragmas in all of the package's Go files,
  1242  // rewrites the Go source files, and generates Go wrappers and assembly trampolines
  1243  // without requiring a C compiler.
  1244  func (p *Package) processBinding(goFiles []string) {
  1245  	type parsedFile struct {
  1246  		srcfile    string
  1247  		data       []byte
  1248  		parsed     *ast.File
  1249  		hasImportC bool
  1250  	}
  1251  
  1252  	parsedFiles := make([]parsedFile, len(goFiles))
  1253  	sources := make([]bindingSource, len(goFiles))
  1254  	q := par.NewQueue(runtime.GOMAXPROCS(0))
  1255  	for i, srcfile := range goFiles {
  1256  		q.Add(func() {
  1257  			origPath := srcfile
  1258  			if *srcDir != "" && !filepath.IsAbs(srcfile) {
  1259  				origPath = filepath.Join(*srcDir, srcfile)
  1260  			}
  1261  			if aname, err := filepath.Abs(origPath); err == nil {
  1262  				origPath = aname
  1263  			}
  1264  			b, err := os.ReadFile(origPath)
  1265  			if err != nil {
  1266  				fatalf("%s", err)
  1267  			}
  1268  			trimmedPath, _ := objabi.ApplyRewrites(origPath, *trimpath)
  1269  			if strings.ContainsAny(trimmedPath, "\r\n") {
  1270  				fatalf("input path contains newline character: %q", trimmedPath)
  1271  			}
  1272  			parsed, err := parser.ParseFile(p.fset, trimmedPath, b, parser.ParseComments)
  1273  			if err != nil {
  1274  				fatalf("%s", err)
  1275  			}
  1276  			hasImportC := hasImportCFile(parsed)
  1277  			parsedFiles[i] = parsedFile{
  1278  				srcfile:    trimmedPath,
  1279  				data:       b,
  1280  				parsed:     parsed,
  1281  				hasImportC: hasImportC,
  1282  			}
  1283  			sources[i] = bindingSource{
  1284  				path:     trimmedPath,
  1285  				origPath: origPath,
  1286  				data:     b,
  1287  				file:     parsed,
  1288  			}
  1289  		})
  1290  	}
  1291  	<-q.Idle()
  1292  
  1293  	h := hash.New32()
  1294  	io.WriteString(h, *importPath)
  1295  	var rawExports []rawBindingExport
  1296  	expMap := make(map[string]bool)
  1297  	for _, pf := range parsedFiles {
  1298  		h.Write(pf.data)
  1299  		if pf.hasImportC {
  1300  			rawExports = append(rawExports, p.collectBindingExports(pf.parsed, expMap)...)
  1301  		}
  1302  	}
  1303  	if nerrors > 0 {
  1304  		os.Exit(2)
  1305  	}
  1306  
  1307  	entry := p.parseBindingFiles(sources)
  1308  	p.PackageName = entry.Package
  1309  	p.LdFlags = entry.LdFlags
  1310  	expFuncs := p.resolveBindingExports(entry, rawExports)
  1311  	if nerrors > 0 {
  1312  		os.Exit(2)
  1313  	}
  1314  
  1315  	// knownBoundNames are names that must not be referred to as C.name:
  1316  	// Go names bound by pragmas, and C names bound without the C. prefix.
  1317  	// References to them are rewritten to undefined identifiers.
  1318  	knownBoundNames := maps.Clone(entry.GoOnlyCNames)
  1319  	for _, goConst := range entry.ConstCToGo {
  1320  		knownBoundNames[goConst] = true
  1321  	}
  1322  	for goType := range entry.TypeGoToC {
  1323  		knownBoundNames[goType] = true
  1324  	}
  1325  
  1326  	// varMap and cFuncMap map C names bound with the C.cName form.
  1327  	varMap := make(map[string]BindingVar)
  1328  	boundGoVars := make(map[string]BindingVar)
  1329  	for _, v := range entry.Vars {
  1330  		if v.BindC {
  1331  			varMap[v.CName] = v
  1332  		}
  1333  		boundGoVars[v.GoName] = v
  1334  		knownBoundNames[v.GoName] = true
  1335  	}
  1336  
  1337  	cFuncMap := make(map[string]BindingFunc)
  1338  	goFuncMap := make(map[string]BindingFunc)
  1339  	boundGoFuncs := make(map[string]bool)
  1340  	boundMethods := make(map[string]bool) // "LibT.GoName" for //cgo:dynload methods
  1341  	boundCFuncs := make(map[string]bool)
  1342  	for _, v := range entry.DynloadVars {
  1343  		boundMethods[v.RecvType+"."+v.GoName] = true
  1344  	}
  1345  	for _, fn := range entry.Funcs {
  1346  		if fn.RecvType != "" {
  1347  			boundMethods[fn.RecvType+"."+fn.GoName] = true
  1348  			boundCFuncs[fn.CName] = true
  1349  			continue
  1350  		}
  1351  		if fn.BindC {
  1352  			cFuncMap[fn.CName] = fn
  1353  		}
  1354  		boundGoFuncs[fn.GoName] = true
  1355  		goFuncMap[fn.GoName] = fn
  1356  		boundCFuncs[fn.CName] = true
  1357  		knownBoundNames[fn.Name] = true
  1358  		knownBoundNames[fn.GoName] = true
  1359  	}
  1360  
  1361  	for _, cName := range slices.Sorted(maps.Keys(p.noEscapes)) {
  1362  		if !boundCFuncs[cName] {
  1363  			error_(token.NoPos, "#cgo noescape %s: no matched C function", cName)
  1364  		}
  1365  	}
  1366  	for _, cName := range slices.Sorted(maps.Keys(p.noCallbacks)) {
  1367  		if !boundCFuncs[cName] {
  1368  			error_(token.NoPos, "#cgo nocallback %s: no matched C function", cName)
  1369  		}
  1370  	}
  1371  	if nerrors > 0 {
  1372  		os.Exit(2)
  1373  	}
  1374  	for i := range entry.Funcs {
  1375  		fn := &entry.Funcs[i]
  1376  		fn.MayCallback = !p.noCallbacks[fn.CName]
  1377  	}
  1378  
  1379  	expFuncMap := make(map[string]BindingFunc, len(expFuncs))
  1380  	for _, ef := range expFuncs {
  1381  		expFuncMap[ef.Name] = exportBindingFunc(ef)
  1382  	}
  1383  
  1384  	rewriter := &bindingRewriter{
  1385  		p:               p,
  1386  		tpkg:            entry.tpkg,
  1387  		typeInfo:        entry.typeInfo,
  1388  		entry:           entry,
  1389  		varMap:          varMap,
  1390  		boundGoVars:     boundGoVars,
  1391  		cFuncMap:        cFuncMap,
  1392  		goFuncMap:       goFuncMap,
  1393  		knownBoundNames: knownBoundNames,
  1394  		expFuncMap:      expFuncMap,
  1395  	}
  1396  
  1397  	outGoFiles := make([]string, len(parsedFiles))
  1398  	rewriteQ := par.NewQueue(runtime.GOMAXPROCS(0))
  1399  	for i, pf := range parsedFiles {
  1400  		rewriteQ.Add(func() {
  1401  			trimmedSrc := pf.srcfile
  1402  			b := pf.data
  1403  			parsed := pf.parsed
  1404  			tf := p.fset.File(parsed.Package)
  1405  			editBuf := edit.NewBuffer(b)
  1406  
  1407  			// Strip //cgo: pragmas and bound func/var declarations;
  1408  			// _cgo_gotypes.go supplies their wrappers and C symbol imports.
  1409  			var stripped [][2]token.Pos
  1410  			stripNode := func(pos, end token.Pos) {
  1411  				editBuf.Replace(tf.Offset(pos), tf.Offset(end), "")
  1412  				stripped = append(stripped, [2]token.Pos{pos, end})
  1413  			}
  1414  			isBoundVar := func(spec ast.Spec) bool {
  1415  				vs, ok := spec.(*ast.ValueSpec)
  1416  				if !ok || len(vs.Names) != 1 {
  1417  					return false
  1418  				}
  1419  				_, ok = boundGoVars[vs.Names[0].Name]
  1420  				return ok
  1421  			}
  1422  			parsed.Decls = slices.DeleteFunc(parsed.Decls, func(decl ast.Decl) bool {
  1423  				switch d := decl.(type) {
  1424  				case *ast.FuncDecl:
  1425  					if d.Body == nil && (d.Recv == nil && boundGoFuncs[d.Name.Name] || d.Recv != nil && boundMethods[recvTypeName(d)+"."+d.Name.Name]) {
  1426  						stripNode(d.Pos(), d.End())
  1427  						return true
  1428  					}
  1429  				case *ast.GenDecl:
  1430  					if d.Tok == token.VAR {
  1431  						if len(d.Specs) > 0 && !slices.ContainsFunc(d.Specs, func(spec ast.Spec) bool { return !isBoundVar(spec) }) {
  1432  							stripNode(d.Pos(), d.End())
  1433  							return true
  1434  						}
  1435  						d.Specs = slices.DeleteFunc(d.Specs, func(spec ast.Spec) bool {
  1436  							if isBoundVar(spec) {
  1437  								stripNode(spec.Pos(), spec.End())
  1438  								return true
  1439  							}
  1440  							return false
  1441  						})
  1442  					}
  1443  				}
  1444  				return false
  1445  			})
  1446  
  1447  			for _, cg := range parsed.Comments {
  1448  				for _, c := range cg.List {
  1449  					if isCgoPragmaComment(c.Text) && !slices.ContainsFunc(stripped, func(r [2]token.Pos) bool {
  1450  						return c.Pos() < r[1] && c.End() > r[0]
  1451  					}) {
  1452  						editBuf.Replace(tf.Offset(c.Pos()), tf.Offset(c.End()), "")
  1453  					}
  1454  				}
  1455  			}
  1456  
  1457  			imp := collectFileImports(parsed)
  1458  			hasUnsafeImport := imp.hasUnsafe
  1459  
  1460  			if len(entry.DynloadTypes) > 0 {
  1461  				// Make registering the //cgo:dynload types the first
  1462  				// declaration in the file (see writeGoTypes). Put it right
  1463  				// after the imports (or the package clause), on the same
  1464  				// line, so that line numbers do not change and the first
  1465  				// declaration keeps its doc comment and directives.
  1466  				// Skip an import "C" declaration that is removed below.
  1467  				insertAt := tf.Offset(parsed.Name.End())
  1468  				for _, d := range parsed.Decls {
  1469  					gd, ok := d.(*ast.GenDecl)
  1470  					if !ok || gd.Tok != token.IMPORT {
  1471  						break
  1472  					}
  1473  					if hasUnsafeImport && len(gd.Specs) == 1 && gd.Specs[0].(*ast.ImportSpec).Path.Value == `"C"` {
  1474  						continue
  1475  					}
  1476  					insertAt = tf.Offset(gd.End())
  1477  				}
  1478  				editBuf.Insert(insertAt, "; "+dynloadRegisterDecl)
  1479  			}
  1480  
  1481  			if pf.hasImportC {
  1482  				forEachImportC(parsed, func(d *ast.GenDecl, s *ast.ImportSpec, _ *ast.CommentGroup) {
  1483  					if hasUnsafeImport {
  1484  						if len(d.Specs) == 1 {
  1485  							editBuf.Replace(tf.Offset(d.Pos()), tf.Offset(d.End()), "")
  1486  						} else {
  1487  							editBuf.Replace(tf.Offset(s.Pos()), tf.Offset(s.End()), "")
  1488  						}
  1489  					} else {
  1490  						editBuf.Replace(tf.Offset(s.Path.Pos()), tf.Offset(s.Path.End()), `_ "unsafe"`)
  1491  						hasUnsafeImport = true
  1492  					}
  1493  				})
  1494  			}
  1495  			if len(stripped) > 0 || pf.hasImportC {
  1496  				var keepImports strings.Builder
  1497  				for _, s := range parsed.Imports {
  1498  					alias := ""
  1499  					if s.Name != nil {
  1500  						alias = s.Name.Name
  1501  					}
  1502  					if alias == "_" || alias == "." {
  1503  						continue
  1504  					}
  1505  					switch s.Path.Value {
  1506  					case `"unsafe"`:
  1507  						fmt.Fprintf(&keepImports, "\nvar _ %s.Pointer\n", cmp.Or(alias, "unsafe"))
  1508  					case `"structs"`:
  1509  						fmt.Fprintf(&keepImports, "\nvar _ %s.HostLayout\n", cmp.Or(alias, "structs"))
  1510  					case `"runtime/cgo"`:
  1511  						fmt.Fprintf(&keepImports, "\ntype _ %s.Incomplete\n", cmp.Or(alias, "cgo"))
  1512  					}
  1513  				}
  1514  				if keepImports.Len() > 0 {
  1515  					editBuf.Insert(len(b), keepImports.String())
  1516  				}
  1517  			}
  1518  
  1519  			rewriter.rewriteFile(editBuf, tf, parsed, b, pf.hasImportC)
  1520  
  1521  			base := strings.TrimSuffix(filepath.Base(trimmedSrc), ".go")
  1522  			outName := base + ".cgobinding.go"
  1523  			fgo1 := creat(outName)
  1524  			fmt.Fprintf(fgo1, "// Code generated by cmd/cgo; DO NOT EDIT.\n\n")
  1525  			fmt.Fprintf(fgo1, "//line %s:1:1\n", filepath.ToSlash(trimmedSrc))
  1526  			fgo1.Write(editBuf.Bytes())
  1527  			fgo1.Close()
  1528  			outGoFiles[i] = outName
  1529  		})
  1530  	}
  1531  	<-rewriteQ.Idle()
  1532  	p.GoFiles = append(p.GoFiles, outGoFiles...)
  1533  
  1534  	origCPrefix := cPrefix
  1535  	cPrefix = fmt.Sprintf("_%x", h.Sum(nil)[0:6])
  1536  	p.writeGoTypes(entry, expFuncs)
  1537  	p.writeTrampolines(entry, expFuncs)
  1538  	cPrefix = origCPrefix
  1539  
  1540  	if *exportHeader != "" && len(expFuncs) > 0 {
  1541  		p.writeBindingExportHeader(*exportHeader, entry, expFuncs, sources)
  1542  	}
  1543  
  1544  	if len(p.LdFlags) > 0 {
  1545  		fflg := creat("_cgo_flags")
  1546  		for _, flag := range p.LdFlags {
  1547  			fmt.Fprintf(fflg, "_CGO_LDFLAGS_=%s\n", flag)
  1548  		}
  1549  		fflg.Close()
  1550  	}
  1551  }
  1552  
  1553  type bindingStubImporter struct{}
  1554  
  1555  func (bindingStubImporter) Import(path string) (*types.Package, error) {
  1556  	if path == "unsafe" {
  1557  		return types.Unsafe, nil
  1558  	}
  1559  	name := path
  1560  	if i := strings.LastIndex(path, "/"); i >= 0 {
  1561  		name = path[i+1:]
  1562  	}
  1563  	pkg := types.NewPackage(path, name)
  1564  	pkg.MarkComplete()
  1565  	return pkg, nil
  1566  }
  1567  
  1568  type bindingRewriter struct {
  1569  	p               *Package
  1570  	tpkg            *types.Package
  1571  	typeInfo        *types.Info
  1572  	entry           *Bindings
  1573  	varMap          map[string]BindingVar
  1574  	boundGoVars     map[string]BindingVar
  1575  	cFuncMap        map[string]BindingFunc
  1576  	goFuncMap       map[string]BindingFunc
  1577  	knownBoundNames map[string]bool
  1578  	expFuncMap      map[string]BindingFunc
  1579  }
  1580  
  1581  func (r *bindingRewriter) rewriteFile(editBuf *edit.Buffer, tf *token.File, file *ast.File, src []byte, hasImportC bool) {
  1582  	isImportC := func(id *ast.Ident) bool {
  1583  		obj := r.typeInfo.Uses[id]
  1584  		if obj == nil && r.tpkg != nil {
  1585  			if scope := r.tpkg.Scope().Innermost(id.Pos()); scope != nil {
  1586  				_, obj = scope.LookupParent(id.Name, id.Pos())
  1587  			}
  1588  		}
  1589  		pkgName, ok := obj.(*types.PkgName)
  1590  		return ok && pkgName.Imported().Path() == "C"
  1591  	}
  1592  	// isBoundGoFunc reports whether id refers to the package-level
  1593  	// declaration of a bound function, rather than a local name.
  1594  	isBoundGoFunc := func(id *ast.Ident) bool {
  1595  		obj := r.typeInfo.Uses[id]
  1596  		if obj == nil && r.tpkg != nil {
  1597  			if scope := r.tpkg.Scope().Innermost(id.Pos()); scope != nil {
  1598  				_, obj = scope.LookupParent(id.Name, id.Pos())
  1599  			}
  1600  		}
  1601  		fn, ok := obj.(*types.Func)
  1602  		return ok && r.tpkg != nil && fn.Parent() == r.tpkg.Scope()
  1603  	}
  1604  
  1605  	// Rewrite references to C names, and calls of bound functions that
  1606  	// pass pointers, which get the same cgocheck pointer checks as calls
  1607  	// in traditional cgo.
  1608  	edits := &bindingEdits{src: src}
  1609  	boundVarObjs := make(map[types.Object]BindingVar, len(r.boundGoVars))
  1610  	if r.tpkg != nil {
  1611  		for name, v := range r.boundGoVars {
  1612  			if obj := r.tpkg.Scope().Lookup(name); obj != nil {
  1613  				boundVarObjs[obj] = v
  1614  			}
  1615  		}
  1616  	}
  1617  	// Record selector expressions in call position (CallExpr.Fun, ignoring
  1618  	// enclosing parentheses) so C.<func> and C.<export> are rewritten as calls
  1619  	// there and as non-assignable C function pointers elsewhere.
  1620  	callFuns := make(map[*ast.SelectorExpr]bool)
  1621  	if hasImportC {
  1622  		ast.Inspect(file, func(node ast.Node) bool {
  1623  			if call, ok := node.(*ast.CallExpr); ok {
  1624  				if sel, ok := unparen(call.Fun).(*ast.SelectorExpr); ok {
  1625  					callFuns[sel] = true
  1626  				}
  1627  			}
  1628  			return true
  1629  		})
  1630  	}
  1631  	ast.Inspect(file, func(node ast.Node) bool {
  1632  		switch n := node.(type) {
  1633  		case *ast.SelectorExpr:
  1634  			if !hasImportC {
  1635  				return true
  1636  			}
  1637  			id, ok := n.X.(*ast.Ident)
  1638  			if !ok || id.Name != "C" || !isImportC(id) {
  1639  				return true
  1640  			}
  1641  			name := n.Sel.Name
  1642  			if name == "malloc" {
  1643  				name = "_CMalloc"
  1644  			}
  1645  			var repl string
  1646  			if goConst, isConst := r.entry.ConstCToGo[name]; isConst {
  1647  				repl = goConst
  1648  			} else if v, isVar := r.varMap[name]; isVar {
  1649  				repl = cVarExpr(v)
  1650  			} else if ef, isExp := r.expFuncMap[name]; isExp {
  1651  				if callFuns[n] {
  1652  					r.entry.mu.Lock()
  1653  					r.entry.UsedExportCalls[name] = true
  1654  					r.entry.mu.Unlock()
  1655  					repl = bindingFuncEntry(ef, r.entry.TypeMap)
  1656  				} else {
  1657  					repl = "_Cgo_ptr(_Cfpvar_fp_" + name + ")"
  1658  				}
  1659  			} else if builtinDefs[name] != "" {
  1660  				r.entry.mu.Lock()
  1661  				r.entry.UsedBuiltins[name] = true
  1662  				r.entry.mu.Unlock()
  1663  				repl = "_Cfunc_" + name
  1664  			} else if fn, isFunc := r.cFuncMap[name]; isFunc {
  1665  				if callFuns[n] {
  1666  					repl = bindingFuncEntry(fn, r.entry.TypeMap)
  1667  				} else {
  1668  					r.entry.mu.Lock()
  1669  					r.entry.UsedFuncPtrs[name] = true
  1670  					r.entry.mu.Unlock()
  1671  					repl = "_Cgo_ptr(_Cfpvar_fp_" + name + ")"
  1672  				}
  1673  			} else if _, isType := r.entry.TypeMap["_Ctype_"+name]; isType {
  1674  				repl = "_Ctype_" + name
  1675  			} else if goType, isPrim := primitiveCtypeToGo("_Ctype_" + name); isPrim {
  1676  				repl = goType
  1677  			} else if r.knownBoundNames[name] {
  1678  				repl = "_Cundef_" + name
  1679  			} else {
  1680  				repl = "_Cfunc_" + name
  1681  			}
  1682  			edits.replace(tf.Offset(n.Pos()), tf.Offset(n.End()), repl)
  1683  			return false
  1684  		case *ast.Ident:
  1685  			if v, ok := boundVarObjs[r.typeInfo.Uses[n]]; ok {
  1686  				edits.replace(tf.Offset(n.Pos()), tf.Offset(n.End()), cVarExpr(v))
  1687  			}
  1688  			return false
  1689  		}
  1690  		return true
  1691  	})
  1692  	type callSite struct {
  1693  		call *ast.CallExpr
  1694  		fn   BindingFunc
  1695  	}
  1696  	var calls []callSite
  1697  	deferred := make(map[*ast.CallExpr]bool)
  1698  	unused := make(map[*ast.CallExpr]bool)
  1699  	ast.Inspect(file, func(node ast.Node) bool {
  1700  		switch n := node.(type) {
  1701  		case *ast.DeferStmt:
  1702  			deferred[n.Call] = true
  1703  		case *ast.GoStmt:
  1704  			deferred[n.Call] = true
  1705  		case *ast.ExprStmt:
  1706  			if call, ok := n.X.(*ast.CallExpr); ok {
  1707  				unused[call] = true
  1708  			}
  1709  		case *ast.CallExpr:
  1710  			switch fun := unparen(n.Fun).(type) {
  1711  			case *ast.SelectorExpr:
  1712  				if id, ok := fun.X.(*ast.Ident); ok && hasImportC && id.Name == "C" && isImportC(id) {
  1713  					if fn, ok := r.cFuncMap[fun.Sel.Name]; ok {
  1714  						calls = append(calls, callSite{n, fn})
  1715  					} else if ef, ok := r.expFuncMap[fun.Sel.Name]; ok {
  1716  						calls = append(calls, callSite{n, ef})
  1717  					}
  1718  				}
  1719  			case *ast.Ident:
  1720  				if fn, ok := r.goFuncMap[fun.Name]; ok && isBoundGoFunc(fun) {
  1721  					calls = append(calls, callSite{n, fn})
  1722  				}
  1723  			}
  1724  		}
  1725  		return true
  1726  	})
  1727  	// Rewrite inner calls first so that outer calls include them.
  1728  	for _, c := range slices.Backward(calls) {
  1729  		if repl := r.p.rewriteBindingCall(edits, tf.Offset, c.call, c.fn, r.entry.TypeMap, deferred[c.call], unused[c.call]); repl != "" {
  1730  			edits.replace(tf.Offset(c.call.Pos()), tf.Offset(c.call.End()), repl)
  1731  		}
  1732  	}
  1733  	edits.apply(editBuf)
  1734  }
  1735  
  1736  func (p *Package) cgoASTToGoDefInFile(expr ast.Expr, entry *Bindings, imp fileImports) string {
  1737  	switch e := expr.(type) {
  1738  	case *ast.ParenExpr:
  1739  		return p.cgoASTToGoDefInFile(e.X, entry, imp)
  1740  	case *ast.Ident:
  1741  		if imp.structs["."] && e.Name == "HostLayout" {
  1742  			return "structs.HostLayout"
  1743  		}
  1744  		if imp.runtimeCgo["."] && e.Name == "Incomplete" {
  1745  			return "_cgopackage.Incomplete"
  1746  		}
  1747  		if imp.unsafe["."] && e.Name == "Pointer" {
  1748  			return "unsafe.Pointer"
  1749  		}
  1750  		return e.Name
  1751  	case *ast.SelectorExpr:
  1752  		if id, ok := e.X.(*ast.Ident); ok {
  1753  			if imp.structs[id.Name] && e.Sel.Name == "HostLayout" {
  1754  				return "structs.HostLayout"
  1755  			}
  1756  			if imp.unsafe[id.Name] && e.Sel.Name == "Pointer" {
  1757  				return "unsafe.Pointer"
  1758  			}
  1759  			if imp.runtimeCgo[id.Name] && e.Sel.Name == "Incomplete" {
  1760  				return "_cgopackage.Incomplete"
  1761  			}
  1762  			if id.Name == "C" {
  1763  				if goType, ok := primitiveCtypeToGo("_Ctype_" + e.Sel.Name); ok {
  1764  					return goType
  1765  				}
  1766  				return "_Ctype_" + e.Sel.Name
  1767  			}
  1768  		}
  1769  		return p.cgoASTToGoDefInFile(e.X, entry, imp) + "." + e.Sel.Name
  1770  	case *ast.StarExpr:
  1771  		return "*" + p.cgoASTToGoDefInFile(e.X, entry, imp)
  1772  	case *ast.ArrayType:
  1773  		lenStr := ""
  1774  		if e.Len != nil {
  1775  			lenStr = strconv.FormatInt(p.evalArrayLen(e, entry), 10)
  1776  		}
  1777  		return "[" + lenStr + "]" + p.cgoASTToGoDefInFile(e.Elt, entry, imp)
  1778  	case *ast.StructType:
  1779  		var buf bytes.Buffer
  1780  		buf.WriteString("struct {\n")
  1781  		for _, fld := range e.Fields.List {
  1782  			typeStr := p.cgoASTToGoDefInFile(fld.Type, entry, imp)
  1783  			var names []string
  1784  			for _, id := range fld.Names {
  1785  				names = append(names, id.Name)
  1786  			}
  1787  			nameStr := strings.Join(names, ", ")
  1788  			if nameStr == "" {
  1789  				fmt.Fprintf(&buf, "\t%s\n", typeStr)
  1790  			} else {
  1791  				fmt.Fprintf(&buf, "\t%s %s\n", nameStr, typeStr)
  1792  			}
  1793  		}
  1794  		buf.WriteString("}")
  1795  		return buf.String()
  1796  	default:
  1797  		var buf bytes.Buffer
  1798  		noSourceConf.Fprint(&buf, p.fset, expr)
  1799  		return buf.String()
  1800  	}
  1801  }
  1802  
  1803  // dynloadRegisterDecl is the declaration that registers the symbols of
  1804  // the //cgo:dynload types of a package during package initialization.
  1805  const dynloadRegisterDecl = "var _ = _cgo_register_libraries()"
  1806  
  1807  const bindingRuntimeProlog = `func _Cgo_ptr(ptr unsafe.Pointer) unsafe.Pointer { return ptr }
  1808  
  1809  //go:linkname _cgo_runtime_cgocall runtime.cgocall
  1810  func _cgo_runtime_cgocall(fn unsafe.Pointer, arg uintptr) int32
  1811  
  1812  //go:linkname _Cgo_always_false runtime.cgoAlwaysFalse
  1813  var _Cgo_always_false bool
  1814  
  1815  //go:linkname _Cgo_use runtime.cgoUse
  1816  func _Cgo_use(interface{})
  1817  
  1818  //go:linkname _Cgo_keepalive runtime.cgoKeepAlive
  1819  //go:noescape
  1820  func _Cgo_keepalive(interface{})
  1821  
  1822  //go:linkname _cgoCheckPointer runtime.cgoCheckPointer
  1823  //go:noescape
  1824  func _cgoCheckPointer(interface{}, interface{})
  1825  
  1826  //go:linkname _Cgo_no_callback runtime.cgoNoCallback
  1827  func _Cgo_no_callback(bool)
  1828  
  1829  `
  1830  
  1831  const bindingCMallocProlog = `//go:linkname _cgo_runtime_throw runtime.throw
  1832  func _cgo_runtime_throw(string)
  1833  
  1834  //go:linkname _cgo_trampoline__cgo_malloc _cgo%s_trampoline__cgo_malloc
  1835  var _cgo_trampoline__cgo_malloc byte
  1836  
  1837  type _cgo_arg__cgo_malloc struct {
  1838  	p0  _Ctype_size_t
  1839  	ret unsafe.Pointer
  1840  }
  1841  
  1842  func _cgo_cmalloc(n uint64) unsafe.Pointer {
  1843  	if n == 0 {
  1844  		n = 1
  1845  	}
  1846  	args := _cgo_arg__cgo_malloc{p0: _Ctype_size_t(n)}
  1847  	_cgo_runtime_cgocall(unsafe.Pointer(&_cgo_trampoline__cgo_malloc), uintptr(unsafe.Pointer(&args)))
  1848  	if _Cgo_always_false {
  1849  		_Cgo_keepalive(&args)
  1850  	}
  1851  	if args.ret == nil {
  1852  		_cgo_runtime_throw("runtime: C malloc failed")
  1853  	}
  1854  	return args.ret
  1855  }
  1856  
  1857  `
  1858  
  1859  // cTypeError reports why values of the Go type expression t cannot be passed
  1860  // to or returned from C, or "" if they can. Go strings, slices, maps,
  1861  // channels, functions, interfaces, and instantiated generic types have no C
  1862  // equivalent, so they (and pointers to, arrays of, and structs containing
  1863  // them) are rejected rather than passed in their Go runtime representation.
  1864  // Every struct type reachable from t, including through pointers, must
  1865  // embed structs.HostLayout so that its Go layout matches C's, unless it is
  1866  // an empty struct or an incomplete (opaque) C type embedding cgo.Incomplete.
  1867  // Incomplete types may only be used behind pointers. Named types are
  1868  // resolved through types, which maps a type name to its definition.
  1869  func cTypeError(t string, types map[string]BindingType) string {
  1870  	return cTypeErrorIn(t, types, make(map[string]bool), true)
  1871  }
  1872  
  1873  // cDeclTypeError is like cTypeError, but for the type of a declaration
  1874  // shared with C, such as a //cgo:type, rather than of a value passed by
  1875  // value, so the type itself may be incomplete.
  1876  func cDeclTypeError(t string, types map[string]BindingType) string {
  1877  	return cTypeErrorIn(t, types, make(map[string]bool), false)
  1878  }
  1879  
  1880  // cTypeErrorIn is like cTypeError. If byValue is false, t itself is not
  1881  // passed by value, so it may be an incomplete type.
  1882  func cTypeErrorIn(t string, types map[string]BindingType, seen map[string]bool, byValue bool) string {
  1883  	t = strings.TrimSpace(t)
  1884  	if strings.HasPrefix(t, "...") {
  1885  		return "Go variadic parameters are not supported"
  1886  	}
  1887  	expr, err := parser.ParseExpr(t)
  1888  	if err != nil {
  1889  		// Leave reporting malformed types to the ABI layout code.
  1890  		return ""
  1891  	}
  1892  	return cTypeExprError(expr, types, seen, byValue)
  1893  }
  1894  
  1895  func cTypeExprError(expr ast.Expr, types map[string]BindingType, seen map[string]bool, byValue bool) string {
  1896  	switch e := expr.(type) {
  1897  	case *ast.ParenExpr:
  1898  		return cTypeExprError(e.X, types, seen, byValue)
  1899  	case *ast.StarExpr:
  1900  		return cTypeExprError(e.X, types, seen, false)
  1901  	case *ast.ArrayType:
  1902  		if e.Len == nil {
  1903  			return "it contains a Go slice"
  1904  		}
  1905  		return cTypeExprError(e.Elt, types, seen, byValue)
  1906  	case *ast.Ellipsis:
  1907  		return "Go variadic parameters are not supported"
  1908  	case *ast.MapType:
  1909  		return "it contains a Go map"
  1910  	case *ast.ChanType:
  1911  		return "it contains a Go channel"
  1912  	case *ast.FuncType:
  1913  		return "it contains a Go func value"
  1914  	case *ast.InterfaceType:
  1915  		return "it contains a Go interface"
  1916  	case *ast.IndexExpr, *ast.IndexListExpr:
  1917  		return "it contains an instantiated generic type"
  1918  	case *ast.StructType:
  1919  		if structIsIncomplete(e) {
  1920  			if byValue {
  1921  				return "it contains an incomplete C type by value"
  1922  			}
  1923  			return ""
  1924  		}
  1925  		for _, field := range e.Fields.List {
  1926  			if why := cTypeExprError(field.Type, types, seen, true); why != "" {
  1927  				return why
  1928  			}
  1929  		}
  1930  		if len(e.Fields.List) > 0 && !slices.ContainsFunc(e.Fields.List, func(f *ast.Field) bool { return isHostLayoutExpr(f.Type) }) {
  1931  			return "it contains a struct type that does not embed structs.HostLayout"
  1932  		}
  1933  		return ""
  1934  	case *ast.Ident:
  1935  		switch e.Name {
  1936  		case "string":
  1937  			return "it contains a Go string"
  1938  		case "any", "error":
  1939  			return "it contains a Go interface"
  1940  		}
  1941  		return cTypeNameError(e.Name, types, seen, byValue)
  1942  	case *ast.SelectorExpr:
  1943  		if x, ok := e.X.(*ast.Ident); ok {
  1944  			return cTypeNameError(x.Name+"."+e.Sel.Name, types, seen, byValue)
  1945  		}
  1946  	}
  1947  	return ""
  1948  }
  1949  
  1950  func cTypeNameError(name string, types map[string]BindingType, seen map[string]bool, byValue bool) string {
  1951  	key := name
  1952  	if byValue {
  1953  		key += " (by value)"
  1954  	}
  1955  	if seen[key] {
  1956  		return ""
  1957  	}
  1958  	seen[key] = true
  1959  	if bt, ok := types[name]; ok && bt.Def != "" {
  1960  		return cTypeErrorIn(bt.Def, types, seen, byValue)
  1961  	}
  1962  	return ""
  1963  }
  1964  
  1965  // structIsIncomplete reports whether st is an incomplete C type, which
  1966  // embeds cgo.Incomplete (spelled _cgopackage.Incomplete in Go type
  1967  // definitions generated for bindings).
  1968  func structIsIncomplete(st *ast.StructType) bool {
  1969  	return slices.ContainsFunc(st.Fields.List, func(f *ast.Field) bool {
  1970  		sel, ok := f.Type.(*ast.SelectorExpr)
  1971  		if !ok {
  1972  			return false
  1973  		}
  1974  		id, ok := sel.X.(*ast.Ident)
  1975  		return ok && (id.Name == "_cgopackage" || id.Name == "cgo") && sel.Sel.Name == "Incomplete"
  1976  	})
  1977  }
  1978  
  1979  // bindingEdits is a set of non-overlapping replacements in a source file.
  1980  // A replacement that covers others absorbs them, so a rewritten call may
  1981  // include the rewritten text of its arguments.
  1982  type bindingEdits struct {
  1983  	src   []byte
  1984  	edits []bindingEdit
  1985  }
  1986  
  1987  type bindingEdit struct {
  1988  	start, end int
  1989  	text       string
  1990  }
  1991  
  1992  // replace replaces src[start:end] with text, which must already include
  1993  // the effect of any earlier replacements within src[start:end].
  1994  func (e *bindingEdits) replace(start, end int, text string) {
  1995  	e.edits = slices.DeleteFunc(e.edits, func(x bindingEdit) bool {
  1996  		return start <= x.start && x.end <= end
  1997  	})
  1998  	e.edits = append(e.edits, bindingEdit{start, end, text})
  1999  }
  2000  
  2001  // text returns src[start:end] with the replacements within it applied.
  2002  func (e *bindingEdits) text(start, end int) string {
  2003  	var inside []bindingEdit
  2004  	for _, x := range e.edits {
  2005  		if start <= x.start && x.end <= end {
  2006  			inside = append(inside, x)
  2007  		}
  2008  	}
  2009  	slices.SortFunc(inside, func(a, b bindingEdit) int { return cmp.Compare(a.start, b.start) })
  2010  	var sb strings.Builder
  2011  	pos := start
  2012  	for _, x := range inside {
  2013  		sb.Write(e.src[pos:x.start])
  2014  		sb.WriteString(x.text)
  2015  		pos = x.end
  2016  	}
  2017  	sb.Write(e.src[pos:end])
  2018  	return sb.String()
  2019  }
  2020  
  2021  func (e *bindingEdits) apply(buf *edit.Buffer) {
  2022  	for _, x := range e.edits {
  2023  		buf.Replace(x.start, x.end, x.text)
  2024  	}
  2025  }
  2026  
  2027  // bindingPointerChecks reports, for each parameter of fn, whether an
  2028  // argument passed for it needs a cgocheck pointer check.
  2029  func bindingPointerChecks(fn BindingFunc, types map[string]BindingType) (checks []bool, any bool) {
  2030  	checks = make([]bool, len(fn.Params))
  2031  	for i, pt := range fn.Params {
  2032  		checks[i] = bindingHasPointer(pt, types, true)
  2033  		any = any || checks[i]
  2034  	}
  2035  	return checks, any
  2036  }
  2037  
  2038  // bindingFuncEntry returns the name of the Go function to call for fn
  2039  // when its arguments have not been checked by the caller: the checking
  2040  // wrapper _Cgocheck_<name> if any argument might need a pointer check, or
  2041  // the unchecked _Cfunc_<name> otherwise.
  2042  func bindingFuncEntry(fn BindingFunc, types map[string]BindingType) string {
  2043  	if _, any := bindingPointerChecks(fn, types); any {
  2044  		return "_Cgocheck_" + fn.Name
  2045  	}
  2046  	return "_Cfunc_" + fn.Name
  2047  }
  2048  
  2049  // bindingHasPointer is like hasPointer, for a Go type expression t in the
  2050  // signature of a bound function. If top is true, it reports whether t is or
  2051  // contains a pointer that might point to a Go pointer, so that values of
  2052  // type t passed to C need a cgocheck pointer check; if top is false, it
  2053  // reports whether t is or contains a pointer. Named types are resolved
  2054  // through types; types that cannot be resolved are assumed to contain
  2055  // pointers.
  2056  func bindingHasPointer(t string, types map[string]BindingType, top bool) bool {
  2057  	expr, err := parser.ParseExpr(t)
  2058  	if err != nil {
  2059  		return true
  2060  	}
  2061  	return bindingHasPointerExpr(expr, types, top, make(map[string]bool))
  2062  }
  2063  
  2064  func bindingHasPointerExpr(expr ast.Expr, types map[string]BindingType, top bool, seen map[string]bool) bool {
  2065  	switch t := expr.(type) {
  2066  	case *ast.ParenExpr:
  2067  		return bindingHasPointerExpr(t.X, types, top, seen)
  2068  	case *ast.ArrayType:
  2069  		if t.Len == nil {
  2070  			return true
  2071  		}
  2072  		return bindingHasPointerExpr(t.Elt, types, top, seen)
  2073  	case *ast.StructType:
  2074  		return slices.ContainsFunc(t.Fields.List, func(f *ast.Field) bool {
  2075  			return bindingHasPointerExpr(f.Type, types, top, seen)
  2076  		})
  2077  	case *ast.StarExpr:
  2078  		if !top {
  2079  			return true
  2080  		}
  2081  		return bindingHasPointerExpr(t.X, types, false, seen)
  2082  	case *ast.Ident:
  2083  		switch t.Name {
  2084  		case "bool", "byte", "rune", "uintptr",
  2085  			"int", "int8", "int16", "int32", "int64",
  2086  			"uint", "uint8", "uint16", "uint32", "uint64",
  2087  			"float32", "float64", "complex64", "complex128":
  2088  			return false
  2089  		}
  2090  		return bindingHasPointerName(t.Name, types, top, seen)
  2091  	case *ast.SelectorExpr:
  2092  		if x, ok := t.X.(*ast.Ident); ok {
  2093  			switch {
  2094  			case x.Name == "unsafe" && t.Sel.Name == "Pointer":
  2095  				return true
  2096  			case x.Name == "structs" && t.Sel.Name == "HostLayout":
  2097  				return false
  2098  			}
  2099  			return bindingHasPointerName(x.Name+"."+t.Sel.Name, types, top, seen)
  2100  		}
  2101  	}
  2102  	return true
  2103  }
  2104  
  2105  func bindingHasPointerName(name string, types map[string]BindingType, top bool, seen map[string]bool) bool {
  2106  	bt, ok := types[name]
  2107  	if !ok || bt.Def == "" {
  2108  		return true
  2109  	}
  2110  	key := fmt.Sprintf("%s/%v", name, top)
  2111  	if seen[key] {
  2112  		return false
  2113  	}
  2114  	seen[key] = true
  2115  	expr, err := parser.ParseExpr(bt.Def)
  2116  	if err != nil {
  2117  		return true
  2118  	}
  2119  	return bindingHasPointerExpr(expr, types, top, seen)
  2120  }
  2121  
  2122  // rewriteBindingCall returns the replacement text for call, a call of the
  2123  // bound function fn, that performs the cgocheck pointer checks of
  2124  // traditional cgo (see rewriteCall, checkIndex, checkAddr, and checkSlice)
  2125  // and then calls the unchecked _Cfunc_ entry for fn. It returns "" if no
  2126  // argument needs a check, in which case the call is left to fn's checking
  2127  // Go wrapper. The arguments are evaluated once, in order, into a
  2128  // _cgo_arg_<name> value, which also converts untyped constant arguments
  2129  // to the parameter types. For example, with p and q pointers, the call
  2130  // F(&x.f, p) becomes
  2131  //
  2132  //	func() (_cgoa _cgo_arg_F) {
  2133  //		_cgoBase0 := &x.f; _cgoa.p0 = _cgoBase0; _cgoa.p1 = p
  2134  //		_cgoCheckPointer(_cgoBase0, 0 == 0); _cgoCheckPointer(_cgoa.p1, nil)
  2135  //		_cgoa.ret = _Cfunc_F(_cgoa.p0, _cgoa.p1); return
  2136  //	}().ret
  2137  //
  2138  // on a single line. A call whose result is unused discards it. A deferred
  2139  // call or go statement evaluates the arguments immediately and checks and
  2140  // calls when the returned function literal runs.
  2141  func (p *Package) rewriteBindingCall(e *bindingEdits, off func(token.Pos) int, call *ast.CallExpr, fn BindingFunc, types map[string]BindingType, deferred, unused bool) string {
  2142  	if call.Ellipsis.IsValid() || len(call.Args) != len(fn.Params) {
  2143  		return ""
  2144  	}
  2145  	isNil := func(x ast.Expr) bool {
  2146  		id, ok := x.(*ast.Ident)
  2147  		return ok && id.Name == "nil"
  2148  	}
  2149  	needs, _ := bindingPointerChecks(fn, types)
  2150  	anyCheck := false
  2151  	for i, arg := range call.Args {
  2152  		anyCheck = anyCheck || needs[i] && !isNil(arg)
  2153  	}
  2154  	if !anyCheck {
  2155  		return ""
  2156  	}
  2157  	// isType reports whether x is a type in a conversion.
  2158  	var isType func(x ast.Expr) bool
  2159  	isType = func(x ast.Expr) bool {
  2160  		switch t := x.(type) {
  2161  		case *ast.ParenExpr:
  2162  			return isType(t.X)
  2163  		case *ast.StarExpr:
  2164  			return isType(t.X)
  2165  		case *ast.SelectorExpr:
  2166  			if id, ok := t.X.(*ast.Ident); ok && id.Name == "C" {
  2167  				if _, ok := types["_Ctype_"+t.Sel.Name]; ok {
  2168  					return true
  2169  				}
  2170  				_, isPrim := primitiveCtypeToGo("_Ctype_" + t.Sel.Name)
  2171  				return isPrim
  2172  			}
  2173  		}
  2174  		return p.isType(x)
  2175  	}
  2176  	text := func(start, end token.Pos) string { return e.text(off(start), off(end)) }
  2177  
  2178  	var stmts, checks strings.Builder
  2179  	for i, arg := range call.Args {
  2180  		field := fmt.Sprintf("_cgoa.p%d", i)
  2181  		if !needs[i] || isNil(arg) || p.checkUnsafeStringData(arg) {
  2182  			fmt.Fprintf(&stmts, "%s = %s; ", field, text(arg.Pos(), arg.End()))
  2183  			continue
  2184  		}
  2185  		// Strip type conversions.
  2186  		core := arg
  2187  		for {
  2188  			c, ok := core.(*ast.CallExpr)
  2189  			if !ok || len(c.Args) != 1 || c.Ellipsis.IsValid() || !(isType(c.Fun) || p.isUnsafeData(c.Fun, false)) {
  2190  				break
  2191  			}
  2192  			core = c.Args[0]
  2193  		}
  2194  		// withCore returns arg with core replaced by repl.
  2195  		withCore := func(repl string) string {
  2196  			return text(arg.Pos(), core.Pos()) + repl + text(core.End(), arg.End())
  2197  		}
  2198  		if u, ok := core.(*ast.UnaryExpr); ok && u.Op == token.AND {
  2199  			if index, ok := u.X.(*ast.IndexExpr); ok {
  2200  				// &a[i]: check the complete contents of the slice or array a.
  2201  				idx := fmt.Sprintf("_cgoIndex%d", i)
  2202  				addr, deref, ref := "", "", idx
  2203  				if p.isVariable(index.X) {
  2204  					addr, deref, ref = "&", "*", "(*"+idx+")"
  2205  				}
  2206  				fmt.Fprintf(&stmts, "%s := %s%s; ", idx, addr, text(index.X.Pos(), index.X.End()))
  2207  				fmt.Fprintf(&stmts, "%s = %s; ", field, withCore("&"+ref+text(index.Lbrack, index.End())))
  2208  				fmt.Fprintf(&checks, "_cgoCheckPointer(%s, %s%s); ", field, deref, idx)
  2209  				continue
  2210  			}
  2211  			// &x: check just the memory that x occupies.
  2212  			base := fmt.Sprintf("_cgoBase%d", i)
  2213  			fmt.Fprintf(&stmts, "%s := %s; ", base, text(core.Pos(), core.End()))
  2214  			fmt.Fprintf(&stmts, "%s = %s; ", field, withCore(base))
  2215  			fmt.Fprintf(&checks, "_cgoCheckPointer(%s, 0 == 0); ", base)
  2216  			continue
  2217  		}
  2218  		if _, ok := core.(*ast.SliceExpr); ok {
  2219  			// a[i:j]: check just the contents of the slice.
  2220  			sl := fmt.Sprintf("_cgoSlice%d", i)
  2221  			fmt.Fprintf(&stmts, "%s := %s; ", sl, text(core.Pos(), core.End()))
  2222  			fmt.Fprintf(&stmts, "%s = %s; ", field, withCore(sl))
  2223  			fmt.Fprintf(&checks, "_cgoCheckPointer(%s, 0 == 0); ", sl)
  2224  			continue
  2225  		}
  2226  		fmt.Fprintf(&stmts, "%s = %s; ", field, text(arg.Pos(), arg.End()))
  2227  		fmt.Fprintf(&checks, "_cgoCheckPointer(%s, nil); ", field)
  2228  	}
  2229  
  2230  	var args []string
  2231  	for i := range call.Args {
  2232  		args = append(args, fmt.Sprintf("_cgoa.p%d", i))
  2233  	}
  2234  	callText := fmt.Sprintf("_Cfunc_%s(%s)", fn.Name, strings.Join(args, ", "))
  2235  
  2236  	var repl string
  2237  	switch {
  2238  	case deferred:
  2239  		repl = fmt.Sprintf("func() func() { var _cgoa _cgo_arg_%s; %sreturn func() { %s%s } }()()",
  2240  			fn.Name, &stmts, &checks, callText)
  2241  	case fn.Ret != "" && !unused:
  2242  		repl = fmt.Sprintf("func() (_cgoa _cgo_arg_%s) { %s%s_cgoa.ret = %s; return }().ret",
  2243  			fn.Name, &stmts, &checks, callText)
  2244  	default:
  2245  		repl = fmt.Sprintf("func() { var _cgoa _cgo_arg_%s; %s%s%s }()",
  2246  			fn.Name, &stmts, &checks, callText)
  2247  	}
  2248  	// Keep the line count, so that positions after the call do not move:
  2249  	// add the newlines of any dropped comments before the closing brace.
  2250  	if n := strings.Count(text(call.Pos(), call.End()), "\n") - strings.Count(repl, "\n"); n > 0 {
  2251  		i := strings.LastIndex(repl, "}")
  2252  		repl = repl[:i] + strings.Repeat("\n", n) + repl[i:]
  2253  	}
  2254  	return repl
  2255  }
  2256  
  2257  func (p *Package) writeGoTypes(bf *Bindings, expFuncs []ExportFunc) {
  2258  	f := creat("_cgo_gotypes.go")
  2259  	defer f.Close()
  2260  
  2261  	needsStructs := false
  2262  	for _, v := range bf.Vars {
  2263  		if strings.Contains(v.Type, "structs.HostLayout") {
  2264  			needsStructs = true
  2265  			break
  2266  		}
  2267  	}
  2268  	if !needsStructs {
  2269  		for _, fn := range bf.Funcs {
  2270  			if strings.Contains(fn.Ret, "structs.HostLayout") ||
  2271  				slices.ContainsFunc(fn.Params, func(pt string) bool { return strings.Contains(pt, "structs.HostLayout") }) {
  2272  				needsStructs = true
  2273  				break
  2274  			}
  2275  		}
  2276  	}
  2277  
  2278  	if !needsStructs {
  2279  		for _, v := range bf.DynloadVars {
  2280  			if strings.Contains(v.Type, "structs.HostLayout") {
  2281  				needsStructs = true
  2282  				break
  2283  			}
  2284  		}
  2285  	}
  2286  	if !needsStructs {
  2287  		for _, ef := range expFuncs {
  2288  			if strings.Contains(ef.Ret, "structs.HostLayout") ||
  2289  				slices.ContainsFunc(ef.Params, func(pt string) bool { return strings.Contains(pt, "structs.HostLayout") }) {
  2290  				needsStructs = true
  2291  				break
  2292  			}
  2293  		}
  2294  	}
  2295  
  2296  	fmt.Fprintf(f, "// Code generated by cmd/cgo; DO NOT EDIT.\n\n")
  2297  	fmt.Fprintf(f, "package %s\n\n", bf.Package)
  2298  	fmt.Fprintf(f, "import \"unsafe\"\n\n")
  2299  	if needsStructs {
  2300  		fmt.Fprintf(f, "import \"structs\"\n\n")
  2301  	}
  2302  	if *importRuntimeCgo || len(bf.DynloadTypes) > 0 {
  2303  		fmt.Fprintf(f, "import _cgopackage \"runtime/cgo\"\n\n")
  2304  		fmt.Fprintf(f, "type _ _cgopackage.Incomplete\n\n")
  2305  	}
  2306  	fmt.Fprintf(f, "var _ unsafe.Pointer\n\n")
  2307  
  2308  	if len(bf.DynloadTypes) > 0 {
  2309  		fmt.Fprintf(f, "//go:linkname _cgo_register_library runtime/cgo.registerLibrary\n")
  2310  		fmt.Fprintf(f, "func _cgo_register_library(typ any, syms []string)\n\n")
  2311  		fmt.Fprintf(f, "//go:linkname _cgo_library_symbol runtime/cgo.librarySymbol\n")
  2312  		fmt.Fprintf(f, "func _cgo_library_symbol(lib *_cgopackage.Library, index int) unsafe.Pointer\n\n")
  2313  
  2314  		// Register the symbols bound to each //cgo:dynload type, in symbol
  2315  		// index order, so that cgo.Open can resolve all of them when it
  2316  		// loads the library. Package initialization may call cgo.Open, so
  2317  		// the registration must happen first: every file of the package
  2318  		// starts with a variable declaration that calls
  2319  		// _cgo_register_libraries (see dynloadRegisterDecl), and since
  2320  		// that call depends on no package-level variables, the variable in
  2321  		// the first file is initialized before any other variable, and
  2322  		// before any init function runs. Registering again is harmless.
  2323  		fmt.Fprintf(f, "func _cgo_register_libraries() bool {\n")
  2324  		for _, t := range bf.DynloadTypes {
  2325  			syms := make([]string, bf.DynloadCounts[t])
  2326  			for _, fn := range bf.Funcs {
  2327  				if fn.Indirect && fn.RecvType == t {
  2328  					syms[fn.SymIndex] = strconv.Quote(fn.CName)
  2329  				}
  2330  			}
  2331  			for _, v := range bf.DynloadVars {
  2332  				if v.RecvType == t {
  2333  					syms[v.SymIndex] = strconv.Quote(v.CName)
  2334  				}
  2335  			}
  2336  			fmt.Fprintf(f, "\t_cgo_register_library((*%s)(nil), []string{%s})\n", t, strings.Join(syms, ", "))
  2337  		}
  2338  		fmt.Fprintf(f, "\treturn true\n}\n\n")
  2339  		fmt.Fprintf(f, "%s\n\n", dynloadRegisterDecl)
  2340  	}
  2341  	resolveDynSym := func(index int) string {
  2342  		return fmt.Sprintf("_cgo_library_symbol(&_cgo_recv.Library, %d)", index)
  2343  	}
  2344  	for _, v := range bf.DynloadVars {
  2345  		fmt.Fprintf(f, "func (_cgo_recv *%s) %s() *%s {\n\treturn (*%s)(%s)\n}\n\n", v.RecvType, v.GoName, v.Type, v.Type, resolveDynSym(v.SymIndex))
  2346  	}
  2347  
  2348  	impLocal := func(sym string) string {
  2349  		if goos == "aix" {
  2350  			return "__cgo_imp_" + sym
  2351  		}
  2352  		return sym
  2353  	}
  2354  	if len(bf.Funcs) > 0 || len(bf.Vars) > 0 || len(bf.LdFlags) > 0 || bf.needCMalloc() {
  2355  		importedLibs := make(map[string]bool)
  2356  		for _, fn := range bf.Funcs {
  2357  			if fn.Library != "" && !isStandardC(fn.Library) {
  2358  				importedLibs[dynLibName(fn.Library)] = true
  2359  			}
  2360  		}
  2361  		for _, v := range bf.Vars {
  2362  			if v.Library != "" && !isStandardC(v.Library) {
  2363  				importedLibs[dynLibName(v.Library)] = true
  2364  			}
  2365  		}
  2366  		for _, flag := range bf.LdFlags {
  2367  			fields, _ := splitQuoted(flag)
  2368  			for _, field := range fields {
  2369  				if !strings.HasPrefix(field, "-") && (strings.HasSuffix(field, ".so") || strings.Contains(field, ".so.") || strings.HasSuffix(field, ".dylib") || strings.HasSuffix(field, ".dll")) {
  2370  					if !isStandardC(field) {
  2371  						importedLibs[dynLibName(field)] = true
  2372  					}
  2373  				}
  2374  			}
  2375  		}
  2376  		sortedLibs := slices.Sorted(maps.Keys(importedLibs))
  2377  		if goos != "windows" && goos != "aix" {
  2378  			for _, lib := range sortedLibs {
  2379  				fmt.Fprintf(f, "//go:cgo_import_dynamic _ _ %q\n", lib)
  2380  			}
  2381  			if len(sortedLibs) > 0 {
  2382  				fmt.Fprintf(f, "\n")
  2383  			}
  2384  		}
  2385  
  2386  		dynImpLib := func(rawLib string) string {
  2387  			switch goos {
  2388  			case "windows":
  2389  				return windowsDLLName(rawLib)
  2390  			case "aix":
  2391  				if rawLib != "" && !isStandardC(rawLib) {
  2392  					lib := strings.TrimPrefix(rawLib, "./")
  2393  					if n := strings.Split(lib, "/"); len(n) == 2 && strings.HasSuffix(n[0], ".a") && (strings.HasSuffix(n[1], ".o") || strings.Contains(n[1], ".so.")) {
  2394  						return lib
  2395  					}
  2396  					return ""
  2397  				}
  2398  				return "libc.a/shr_64.o"
  2399  			default:
  2400  				return ""
  2401  			}
  2402  		}
  2403  		emittedImp := make(map[string]bool)
  2404  		for _, fn := range bf.Funcs {
  2405  			cSym := fn.CName
  2406  			if fn.Static || fn.Indirect {
  2407  				// Resolved at link time (.syso/.a) or at run time (cgo.Open).
  2408  				continue
  2409  			}
  2410  			if !emittedImp[cSym] {
  2411  				emittedImp[cSym] = true
  2412  				if lib := dynImpLib(fn.Library); lib != "" {
  2413  					fmt.Fprintf(f, "//go:cgo_import_dynamic %s %s %q\n", impLocal(cSym), cSym, lib)
  2414  				} else {
  2415  					fmt.Fprintf(f, "//go:cgo_import_dynamic %s %s\n", impLocal(cSym), cSym)
  2416  				}
  2417  			}
  2418  		}
  2419  		if bf.needCMalloc() {
  2420  			// C.CString, C.CBytes, and C.malloc allocate with libc malloc.
  2421  			// Use a package-scoped import symbol if the package binds a
  2422  			// static or non-libc malloc.
  2423  			cMallocSym := cMallocImportSym(bf)
  2424  			if !emittedImp[cMallocSym] {
  2425  				emittedImp[cMallocSym] = true
  2426  				if lib := dynImpLib(""); lib != "" {
  2427  					fmt.Fprintf(f, "//go:cgo_import_dynamic %s malloc %q\n", impLocal(cMallocSym), lib)
  2428  				} else {
  2429  					fmt.Fprintf(f, "//go:cgo_import_dynamic %s malloc\n", impLocal(cMallocSym))
  2430  				}
  2431  			}
  2432  		}
  2433  		if len(emittedImp) > 0 {
  2434  			fmt.Fprintf(f, "\n")
  2435  		}
  2436  
  2437  		emittedStatic := make(map[string]bool)
  2438  		emittedVarImp := false
  2439  		for _, fn := range bf.Funcs {
  2440  			if fn.Static && fn.BindC && bf.UsedFuncPtrs[fn.CName] && !emittedStatic[fn.CName] {
  2441  				emittedStatic[fn.CName] = true
  2442  				emittedVarImp = true
  2443  				fmt.Fprintf(f, "//go:cgo_import_static %s\n", fn.CName)
  2444  			}
  2445  		}
  2446  		for _, v := range bf.Vars {
  2447  			if v.Static {
  2448  				if !emittedStatic[v.CName] {
  2449  					emittedStatic[v.CName] = true
  2450  					emittedVarImp = true
  2451  					// Resolved at link time from a .syso or .a file.
  2452  					fmt.Fprintf(f, "//go:cgo_import_static %s\n", v.CName)
  2453  				}
  2454  			} else {
  2455  				emittedVarImp = true
  2456  				localSym := varImportSym(v)
  2457  				if lib := dynImpLib(v.Library); lib != "" {
  2458  					fmt.Fprintf(f, "//go:cgo_import_dynamic %s %s %q\n", localSym, v.CName, lib)
  2459  				} else {
  2460  					fmt.Fprintf(f, "//go:cgo_import_dynamic %s %s\n", localSym, v.CName)
  2461  				}
  2462  			}
  2463  		}
  2464  		if emittedVarImp {
  2465  			fmt.Fprintf(f, "\n")
  2466  		}
  2467  	}
  2468  
  2469  	for _, flag := range bf.LdFlags {
  2470  		fmt.Fprintf(f, "//go:cgo_ldflag %q\n", flag)
  2471  	}
  2472  	if len(bf.LdFlags) > 0 {
  2473  		fmt.Fprintf(f, "\n")
  2474  	}
  2475  
  2476  	// _Cvar_<Name> points to the C variable. Usually it is initialized
  2477  	// with the address of __cgo_var_<Name>, which is the variable itself.
  2478  	// A dynamically imported symbol on Windows is instead a slot in the PE
  2479  	// import address table, which the Windows loader fills in with the
  2480  	// address of the variable in the DLL: PE has no copy relocations, so
  2481  	// code outside a DLL can only reach the DLL's data through such a slot.
  2482  	// There, _Cvar_<Name> is the slot itself.
  2483  	for _, v := range bf.Vars {
  2484  		if goos == "windows" && !v.Static {
  2485  			fmt.Fprintf(f, "//go:linkname _Cvar_%s %s\n", v.Name, varImportSym(v))
  2486  			fmt.Fprintf(f, "var _Cvar_%s *%s\n\n", v.Name, v.Type)
  2487  			continue
  2488  		}
  2489  		goSym := "__cgo_var_" + v.Name
  2490  		target := v.CName
  2491  		if !v.Static {
  2492  			target = varImportSym(v)
  2493  		}
  2494  		fmt.Fprintf(f, "//go:linkname %s %s\n", goSym, target)
  2495  		fmt.Fprintf(f, "var %s byte\n", goSym)
  2496  		fmt.Fprintf(f, "var _Cvar_%s *%s = (*%s)(unsafe.Pointer(&%s))\n\n", v.Name, v.Type, v.Type, goSym)
  2497  	}
  2498  
  2499  	// _Cfpvar_fp_<CName> holds the C function pointer for a bound C function
  2500  	// referenced in a non-call expression. On Windows, a dynamically imported
  2501  	// symbol is a PE IAT slot holding the function's address; on AIX, it is an
  2502  	// XCOFF TOC slot holding the pointer to the function descriptor.
  2503  	for _, fn := range bf.Funcs {
  2504  		if !fn.BindC || fn.Indirect || !bf.UsedFuncPtrs[fn.CName] {
  2505  			continue
  2506  		}
  2507  		if !fn.Static && (goos == "windows" || goos == "aix") {
  2508  			fmt.Fprintf(f, "//go:linkname _Cfpvar_fp_%s %s\n", fn.CName, impLocal(fn.CName))
  2509  			fmt.Fprintf(f, "var _Cfpvar_fp_%s unsafe.Pointer\n\n", fn.CName)
  2510  			continue
  2511  		}
  2512  		target := fn.CName
  2513  		if !fn.Static {
  2514  			target = impLocal(fn.CName)
  2515  		}
  2516  		fmt.Fprintf(f, "//go:linkname __cgo_fp_%s %s\n", fn.CName, target)
  2517  		fmt.Fprintf(f, "var __cgo_fp_%s byte\n", fn.CName)
  2518  		fmt.Fprintf(f, "var _Cfpvar_fp_%s unsafe.Pointer = unsafe.Pointer(&__cgo_fp_%s)\n\n", fn.CName, fn.CName)
  2519  	}
  2520  
  2521  	abiCfg := &ABIConfig{OS: goos, Arch: goarch, PtrSize: targetPtrSize(), CLongSize: targetCLongSize()}
  2522  
  2523  	fmt.Fprint(f, bindingRuntimeProlog)
  2524  	if len(expFuncs) > 0 {
  2525  		fmt.Fprintf(f, "//go:linkname _cgoCheckResult runtime.cgoCheckResult\n//go:noescape\nfunc _cgoCheckResult(interface{})\n\n")
  2526  		p.writeBindingExports(f, expFuncs, bf.TypeMap, abiCfg)
  2527  	}
  2528  
  2529  	emittedAlias := make(map[string]bool)
  2530  	if len(bf.TypeGoToC) > 0 {
  2531  		for _, goName := range slices.Sorted(maps.Keys(bf.TypeGoToC)) {
  2532  			cName := bf.TypeGoToC[goName]
  2533  			aliasName := "_Ctype_" + cName
  2534  			if !emittedAlias[aliasName] && aliasName != goName {
  2535  				emittedAlias[aliasName] = true
  2536  				fmt.Fprintf(f, "type %s = %s\n", aliasName, goName)
  2537  			}
  2538  		}
  2539  		fmt.Fprintf(f, "\n")
  2540  	}
  2541  
  2542  	definedCfuncs := make(map[string]bool)
  2543  	if len(bf.UsedBuiltins) > 0 {
  2544  		charGoType, _ := primitiveCtypeToGo("_Ctype_char")
  2545  		sizeGoType, _ := primitiveCtypeToGo("_Ctype_size_t")
  2546  		for _, bType := range []struct{ c, goType string }{
  2547  			{"_Ctype_char", charGoType},
  2548  			{"_Ctype_int", "int32"},
  2549  			{"_Ctype_size_t", sizeGoType},
  2550  		} {
  2551  			if !emittedAlias[bType.c] {
  2552  				emittedAlias[bType.c] = true
  2553  				fmt.Fprintf(f, "type %s = %s\n", bType.c, bType.goType)
  2554  			}
  2555  		}
  2556  		fmt.Fprintf(f, "\n")
  2557  		if bf.needCMalloc() {
  2558  			fmt.Fprintf(f, bindingCMallocProlog, cPrefix)
  2559  		}
  2560  		for _, name := range slices.Sorted(maps.Keys(bf.UsedBuiltins)) {
  2561  			definedCfuncs[name] = true
  2562  			fmt.Fprintf(f, "%s\n\n", strings.TrimSpace(builtinDefs[name]))
  2563  		}
  2564  	}
  2565  
  2566  	for _, fn := range bf.Funcs {
  2567  		definedCfuncs[fn.Name] = true
  2568  	}
  2569  	for _, ef := range expFuncs {
  2570  		if bf.UsedExportCalls[ef.Name] {
  2571  			definedCfuncs[ef.Name] = true
  2572  		}
  2573  	}
  2574  	emitFuncWrapper := func(fn BindingFunc, emitArgStruct bool) {
  2575  		fmt.Fprintf(f, "//go:linkname _cgo_trampoline_%s _cgo%s_trampoline_%s\n", fn.Name, cPrefix, fn.Name)
  2576  		fmt.Fprintf(f, "var _cgo_trampoline_%s byte\n\n", fn.Name)
  2577  
  2578  		if emitArgStruct && (fn.Indirect || len(fn.Params) > 0 || fn.Ret != "") {
  2579  			fmt.Fprintf(f, "type _cgo_arg_%s struct {\n", fn.Name)
  2580  			if fn.Indirect {
  2581  				fmt.Fprintf(f, "\tfn uintptr\n")
  2582  			}
  2583  			for i, pt := range fn.Params {
  2584  				fmt.Fprintf(f, "\tp%d %s\n", i, pt)
  2585  			}
  2586  			if fn.Ret != "" {
  2587  				fmt.Fprintf(f, "\tret %s\n", fn.Ret)
  2588  			}
  2589  			fmt.Fprintf(f, "}\n\n")
  2590  		}
  2591  
  2592  		var paramDecls []string
  2593  		var paramPass []string
  2594  		var paramNames []string
  2595  		if fn.Indirect {
  2596  			paramDecls = append(paramDecls, "fn uintptr")
  2597  			paramPass = append(paramPass, "fn: fn")
  2598  		}
  2599  		for i, pt := range fn.Params {
  2600  			paramDecls = append(paramDecls, fmt.Sprintf("p%d %s", i, pt))
  2601  			paramPass = append(paramPass, fmt.Sprintf("p%d: p%d", i, i))
  2602  			paramNames = append(paramNames, fmt.Sprintf("p%d", i))
  2603  		}
  2604  		retSig := ""
  2605  		if fn.Ret != "" {
  2606  			retSig = " " + fn.Ret
  2607  		}
  2608  		noCallback := p.noCallbacks[fn.CName]
  2609  		noEscape := p.noEscapes[fn.CName]
  2610  		hasArgs := fn.Indirect || len(fn.Params) > 0 || fn.Ret != ""
  2611  		// When a C call with a return value may invoke Go callbacks, the
  2612  		// trampoline relocates &args by the _cgo_topofstack delta if the
  2613  		// goroutine stack grows. Pass args as a value parameter to a
  2614  		// //go:cgo_unsafe_args helper so the compiler always places it on
  2615  		// the goroutine stack (never heap-allocating even if > MaxStackVarSize).
  2616  		pinArgsOnStack := hasArgs && !noCallback && fn.Ret != ""
  2617  
  2618  		if pinArgsOnStack {
  2619  			fmt.Fprintf(f, "//go:cgo_unsafe_args\n")
  2620  			fmt.Fprintf(f, "func _cgo_call_%s(args _cgo_arg_%s)%s {\n", fn.Name, fn.Name, retSig)
  2621  			fmt.Fprintf(f, "\t_cgo_runtime_cgocall(unsafe.Pointer(&_cgo_trampoline_%s), uintptr(unsafe.Pointer(&args)))\n", fn.Name)
  2622  			fmt.Fprintf(f, "\tif _Cgo_always_false {\n")
  2623  			fmt.Fprintf(f, "\t\t_Cgo_keepalive(&args)\n")
  2624  			fmt.Fprintf(f, "\t}\n")
  2625  			fmt.Fprintf(f, "\treturn args.ret\n")
  2626  			fmt.Fprintf(f, "}\n\n")
  2627  		}
  2628  		fmt.Fprintf(f, "func _Cfunc_%s(%s)%s {\n", fn.Name, strings.Join(paramDecls, ", "), retSig)
  2629  		if pinArgsOnStack {
  2630  			fmt.Fprintf(f, "\tr := _cgo_call_%s(_cgo_arg_%s{%s})\n", fn.Name, fn.Name, strings.Join(paramPass, ", "))
  2631  		} else {
  2632  			if noCallback {
  2633  				fmt.Fprintf(f, "\t_Cgo_no_callback(true)\n")
  2634  			}
  2635  			if !hasArgs {
  2636  				fmt.Fprintf(f, "\t_cgo_runtime_cgocall(unsafe.Pointer(&_cgo_trampoline_%s), 0)\n", fn.Name)
  2637  			} else {
  2638  				fmt.Fprintf(f, "\targs := _cgo_arg_%s{%s}\n", fn.Name, strings.Join(paramPass, ", "))
  2639  				fmt.Fprintf(f, "\t_cgo_runtime_cgocall(unsafe.Pointer(&_cgo_trampoline_%s), uintptr(unsafe.Pointer(&args)))\n", fn.Name)
  2640  			}
  2641  			if noCallback {
  2642  				fmt.Fprintf(f, "\t_Cgo_no_callback(false)\n")
  2643  			}
  2644  		}
  2645  		touchFunc := "_Cgo_use"
  2646  		if noEscape && noCallback {
  2647  			touchFunc = "_Cgo_keepalive"
  2648  		}
  2649  		var touchParams []string
  2650  		for i, name := range paramNames {
  2651  			if abiCfg.inspectType(fn.Params[i], bf.TypeMap).hasPointers {
  2652  				touchParams = append(touchParams, name)
  2653  			}
  2654  		}
  2655  		keepArgsHere := hasArgs && !pinArgsOnStack
  2656  		if len(touchParams) > 0 || keepArgsHere {
  2657  			fmt.Fprintf(f, "\tif _Cgo_always_false {\n")
  2658  			for _, name := range touchParams {
  2659  				fmt.Fprintf(f, "\t\t%s(%s)\n", touchFunc, name)
  2660  			}
  2661  			if keepArgsHere {
  2662  				fmt.Fprintf(f, "\t\t_Cgo_keepalive(&args)\n")
  2663  			}
  2664  			fmt.Fprintf(f, "\t}\n")
  2665  		}
  2666  		if fn.Ret != "" {
  2667  			if pinArgsOnStack {
  2668  				fmt.Fprintf(f, "\treturn r\n")
  2669  			} else {
  2670  				fmt.Fprintf(f, "\treturn args.ret\n")
  2671  			}
  2672  		}
  2673  		fmt.Fprintf(f, "}\n\n")
  2674  
  2675  		var fnArg string
  2676  		if fn.Indirect {
  2677  			fnArg = "uintptr(" + resolveDynSym(fn.SymIndex) + ")"
  2678  		}
  2679  		emitGoFuncWrapper(f, fn, fnArg, definedCfuncs, bf.TypeMap)
  2680  	}
  2681  	for _, fn := range bf.Funcs {
  2682  		emitFuncWrapper(fn, true)
  2683  	}
  2684  	for _, ef := range expFuncs {
  2685  		if bf.UsedExportCalls[ef.Name] {
  2686  			emitFuncWrapper(exportBindingFunc(ef), false)
  2687  		}
  2688  	}
  2689  }
  2690  
  2691  // emitGoFuncWrapper writes the Go function or //cgo:dynload method wrapper calling _Cfunc_<fn.Name>.
  2692  func emitGoFuncWrapper(f *os.File, fn BindingFunc, fnArg string, definedCfuncs map[string]bool, types map[string]BindingType) {
  2693  	if fn.GoName == "" && !fn.BindC {
  2694  		return
  2695  	}
  2696  	var paramDecls []string
  2697  	var passArgs []string
  2698  	recv := ""
  2699  	if fn.Indirect {
  2700  		recv = "(_cgo_recv *" + fn.RecvType + ") "
  2701  		passArgs = append(passArgs, fnArg)
  2702  	}
  2703  	for i, pt := range fn.Params {
  2704  		pName := fmt.Sprintf("p%d", i)
  2705  		paramDecls = append(paramDecls, fmt.Sprintf("%s %s", pName, pt))
  2706  		passArgs = append(passArgs, pName)
  2707  	}
  2708  	retSig := ""
  2709  	retPrefix := ""
  2710  	if fn.Ret != "" {
  2711  		retSig = " " + fn.Ret
  2712  		retPrefix = "return "
  2713  	}
  2714  	cSym := fn.CName
  2715  	targetFunc := fn.Name
  2716  	callExpr := fmt.Sprintf("_Cfunc_%s(%s)", targetFunc, strings.Join(passArgs, ", "))
  2717  
  2718  	// Calls that are not rewritten to check their own arguments (calls
  2719  	// from other packages and from files without import "C", method and
  2720  	// indirect calls, and calls whose arguments cannot be analyzed) go
  2721  	// through the wrapper, which checks every argument that might contain
  2722  	// a Go pointer. Without knowing how an argument was formed, it checks
  2723  	// the complete memory allocation that the argument points to.
  2724  	var checks strings.Builder
  2725  	needs, _ := bindingPointerChecks(fn, types)
  2726  	for i, need := range needs {
  2727  		if need {
  2728  			fmt.Fprintf(&checks, "\t_cgoCheckPointer(p%d, nil)\n", i)
  2729  		}
  2730  	}
  2731  	if checks.Len() > 0 && !fn.Indirect {
  2732  		// Calls to C.cName that rewriteBindingCall leaves as direct calls
  2733  		// (such as multi-value argument forwarding) use _Cgocheck_<name>;
  2734  		// see bindingFuncEntry.
  2735  		entry := bindingFuncEntry(fn, types)
  2736  		fmt.Fprintf(f, "func %s(%s)%s {\n%s\t%s%s\n}\n\n",
  2737  			entry, strings.Join(paramDecls, ", "), retSig, &checks, retPrefix, callExpr)
  2738  		checks.Reset()
  2739  		callExpr = fmt.Sprintf("%s(%s)", entry, strings.Join(passArgs, ", "))
  2740  	}
  2741  	if fn.GoName == "" {
  2742  		return
  2743  	}
  2744  	fmt.Fprintf(f, "func %s%s(%s)%s {\n%s\t%s%s\n}\n\n",
  2745  		recv, fn.GoName, strings.Join(paramDecls, ", "), retSig, &checks, retPrefix, callExpr)
  2746  	if fn.BindC && cSym != targetFunc && !definedCfuncs[cSym] {
  2747  		definedCfuncs[cSym] = true
  2748  		fmt.Fprintf(f, "var _Cfunc_%s = _Cfunc_%s\n\n", cSym, targetFunc)
  2749  	}
  2750  }
  2751  
  2752  func cMallocImportSym(bf *Bindings) string {
  2753  	for _, fn := range bf.Funcs {
  2754  		if fn.CName == "malloc" && (fn.Static || !fn.LibC) {
  2755  			return fmt.Sprintf("_cgo%s_libc_malloc", cPrefix)
  2756  		}
  2757  	}
  2758  	return "malloc"
  2759  }
  2760  
  2761  func (p *Package) writeTrampolines(bf *Bindings, expFuncs []ExportFunc) {
  2762  	f := creat("_cgo_trampolines.s")
  2763  	defer f.Close()
  2764  
  2765  	fmt.Fprintf(f, "// Code generated by cmd/cgo; DO NOT EDIT.\n\n")
  2766  	fmt.Fprintf(f, "#include \"textflag.h\"\n\n")
  2767  
  2768  	if len(bf.Funcs) == 0 && !bf.needCMalloc() && len(expFuncs) == 0 {
  2769  		return
  2770  	}
  2771  
  2772  	abi := getABI(goos, goarch)
  2773  	for _, fn := range bf.Funcs {
  2774  		abi.writeTrampoline(f, fn, bf.TypeMap)
  2775  	}
  2776  	if bf.needCMalloc() {
  2777  		sizeGoType, _ := primitiveCtypeToGo("_Ctype_size_t")
  2778  		abi.writeTrampoline(f, BindingFunc{
  2779  			Name:   "_cgo_malloc",
  2780  			CName:  cMallocImportSym(bf),
  2781  			Params: []string{sizeGoType},
  2782  			Ret:    "unsafe.Pointer",
  2783  			LibC:   true,
  2784  		}, bf.TypeMap)
  2785  	}
  2786  	for _, ef := range expFuncs {
  2787  		abi.writeCallbackTrampoline(f, BindingFunc{
  2788  			Name:   ef.Name,
  2789  			Params: ef.Params,
  2790  			Ret:    ef.Ret,
  2791  		}, bf.TypeMap)
  2792  		if bf.UsedExportCalls[ef.Name] {
  2793  			abi.writeTrampoline(f, exportBindingFunc(ef), bf.TypeMap)
  2794  		}
  2795  	}
  2796  }
  2797  

View as plain text