Source file src/cmd/cgo/bindingexport.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  	"fmt"
    10  	"go/ast"
    11  	"os"
    12  	"path/filepath"
    13  	"strings"
    14  )
    15  
    16  // ExportFunc describes an //export Go function callable from C in a cgo
    17  // binding package.
    18  type ExportFunc struct {
    19  	Name   string
    20  	Params []string
    21  	Ret    string
    22  	Func   *ast.FuncDecl
    23  	Imp    fileImports
    24  }
    25  
    26  // rawBindingExport records an //export function declaration along with the
    27  // import aliases of the source file it was declared in.
    28  type rawBindingExport struct {
    29  	fn  *ast.FuncDecl
    30  	imp fileImports
    31  }
    32  
    33  // collectBindingExports returns the //export functions declared in file,
    34  // reporting errors for exports that cannot be supported without a C
    35  // compiler. expMap records the export names seen so far.
    36  func (p *Package) collectBindingExports(file *ast.File, expMap map[string]bool) []rawBindingExport {
    37  	var rawExports []rawBindingExport
    38  	imp := collectFileImports(file)
    39  	for _, decl := range file.Decls {
    40  		d, ok := decl.(*ast.FuncDecl)
    41  		if !ok || d.Doc == nil {
    42  			continue
    43  		}
    44  		for _, c := range d.Doc.List {
    45  			trimmed := strings.TrimSpace(c.Text)
    46  			after, hasExport := strings.CutPrefix(trimmed, "//export")
    47  			if !hasExport || (after != "" && after[0] != ' ' && after[0] != '\t') {
    48  				continue
    49  			}
    50  			expName := strings.TrimSpace(after)
    51  			if expName == "" || strings.ContainsAny(expName, " \t") {
    52  				error_(c.Pos(), "malformed //export directive: %s", trimmed)
    53  				continue
    54  			}
    55  			if expName != d.Name.Name {
    56  				error_(c.Pos(), "export comment has wrong name %q, want %q", expName, d.Name.Name)
    57  				continue
    58  			}
    59  			if d.Recv != nil {
    60  				error_(d.Pos(), "cannot export method %s: //export functions cannot have a receiver", d.Name.Name)
    61  				continue
    62  			}
    63  			if d.Type.TypeParams != nil && len(d.Type.TypeParams.List) > 0 {
    64  				error_(d.Pos(), "cannot export generic function %s", d.Name.Name)
    65  				continue
    66  			}
    67  			if d.Body == nil {
    68  				error_(d.Pos(), "cannot export bodyless function declaration %s", d.Name.Name)
    69  				continue
    70  			}
    71  			if d.Type.Results != nil && d.Type.Results.NumFields() > 1 {
    72  				error_(d.Pos(), "cannot export function %s with multiple return values", d.Name.Name)
    73  				continue
    74  			}
    75  			if expMap[expName] {
    76  				error_(d.Pos(), "duplicate //export name %s", expName)
    77  				continue
    78  			}
    79  			rawExports = append(rawExports, rawBindingExport{fn: d, imp: imp})
    80  			expMap[expName] = true
    81  			break
    82  		}
    83  	}
    84  	return rawExports
    85  }
    86  
    87  // exportBindingFunc returns the static BindingFunc used to invoke the C-ABI
    88  // wrapper of an //export Go function from Go code (via C.<name>(...)).
    89  func exportBindingFunc(ef ExportFunc) BindingFunc {
    90  	return BindingFunc{
    91  		Name:        ef.Name,
    92  		CName:       ef.Name,
    93  		BindC:       true,
    94  		Static:      true,
    95  		Params:      ef.Params,
    96  		Ret:         ef.Ret,
    97  		MayCallback: true,
    98  	}
    99  }
   100  
   101  // resolveBindingExports validates and computes the Go argument layouts of the
   102  // exported functions rawExports.
   103  func (p *Package) resolveBindingExports(entry *Bindings, rawExports []rawBindingExport) []ExportFunc {
   104  	boundConflict := make(map[string]bool)
   105  	for _, fn := range entry.Funcs {
   106  		boundConflict[fn.Name] = true
   107  		if !fn.Indirect {
   108  			boundConflict[fn.GoName] = true
   109  			boundConflict[fn.CName] = true
   110  		}
   111  	}
   112  	for _, v := range entry.Vars {
   113  		boundConflict[v.GoName] = true
   114  		boundConflict[v.CName] = true
   115  	}
   116  	for goName, cName := range entry.TypeGoToC {
   117  		boundConflict[goName] = true
   118  		boundConflict[cName] = true
   119  	}
   120  	for cName, goName := range entry.ConstCToGo {
   121  		boundConflict[goName] = true
   122  		boundConflict[cName] = true
   123  	}
   124  	for _, t := range entry.DynloadTypes {
   125  		boundConflict[t] = true
   126  	}
   127  
   128  	var expFuncs []ExportFunc
   129  	for _, re := range rawExports {
   130  		fn := re.fn
   131  		if fn.Name.Name == "malloc" || fn.Name.Name == "_cgo_malloc" || builtinDefs[fn.Name.Name] != "" {
   132  			error_(fn.Pos(), "//export %s conflicts with cgo builtin", fn.Name.Name)
   133  			continue
   134  		}
   135  		if boundConflict[fn.Name.Name] {
   136  			error_(fn.Pos(), "//export %s conflicts with //cgo: binding", fn.Name.Name)
   137  			continue
   138  		}
   139  		var params []string
   140  		if fn.Type.Params != nil {
   141  			for _, field := range fn.Type.Params.List {
   142  				if isUnsupportedExportType(field.Type, entry.typeSpecs, make(map[string]bool)) {
   143  					var tb bytes.Buffer
   144  					noSourceConf.Fprint(&tb, p.fset, field.Type)
   145  					error_(field.Type.Pos(), "Go type not supported in //export without a C compiler: %s", tb.String())
   146  					continue
   147  				}
   148  				if entry.resolveUsedTypeInFile != nil {
   149  					entry.resolveUsedTypeInFile(field.Type, false, re.imp)
   150  				}
   151  				pType := p.cgoASTToGoDefInFile(field.Type, entry, re.imp)
   152  				if why := cTypeError(pType, entry.TypeMap); why != "" {
   153  					error_(field.Type.Pos(), "//export %s: parameter type %s cannot be passed from C: %s", fn.Name.Name, pType, why)
   154  					continue
   155  				}
   156  				for range max(1, len(field.Names)) {
   157  					params = append(params, pType)
   158  				}
   159  			}
   160  		}
   161  		ret := ""
   162  		if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 {
   163  			retExpr := fn.Type.Results.List[0].Type
   164  			if isUnsupportedExportType(retExpr, entry.typeSpecs, make(map[string]bool)) {
   165  				var tb bytes.Buffer
   166  				noSourceConf.Fprint(&tb, p.fset, retExpr)
   167  				error_(retExpr.Pos(), "Go type not supported in //export without a C compiler: %s", tb.String())
   168  			} else {
   169  				if entry.resolveUsedTypeInFile != nil {
   170  					entry.resolveUsedTypeInFile(retExpr, false, re.imp)
   171  				}
   172  				ret = p.cgoASTToGoDefInFile(retExpr, entry, re.imp)
   173  				if why := cTypeError(ret, entry.TypeMap); why != "" {
   174  					error_(retExpr.Pos(), "//export %s: result type %s cannot be returned to C: %s", fn.Name.Name, ret, why)
   175  					ret = ""
   176  				}
   177  			}
   178  		}
   179  		expFuncs = append(expFuncs, ExportFunc{
   180  			Name:   fn.Name.Name,
   181  			Params: params,
   182  			Ret:    ret,
   183  			Func:   fn,
   184  			Imp:    re.imp,
   185  		})
   186  	}
   187  	return expFuncs
   188  }
   189  
   190  // writeBindingExports emits the Go export directives, _Cfpvar_fp_
   191  // function-pointer variables, and _cgoexp_ crosscall2 wrappers for expFuncs.
   192  func (p *Package) writeBindingExports(f *os.File, expFuncs []ExportFunc, typeMap map[string]BindingType, abiCfg *ABIConfig) {
   193  	for _, ef := range expFuncs {
   194  		fmt.Fprintf(f, "//go:cgo_export_dynamic %s\n", ef.Name)
   195  		fmt.Fprintf(f, "//go:cgo_export_static %s\n\n", ef.Name)
   196  	}
   197  	for _, ef := range expFuncs {
   198  		fmt.Fprintf(f, "//go:linkname __cgofn_%s %s\n", ef.Name, ef.Name)
   199  		fmt.Fprintf(f, "var __cgofn_%s byte\n", ef.Name)
   200  		fmt.Fprintf(f, "var _Cfpvar_fp_%s unsafe.Pointer = unsafe.Pointer(&__cgofn_%s)\n\n", ef.Name, ef.Name)
   201  
   202  		if len(ef.Params) > 0 || ef.Ret != "" {
   203  			fmt.Fprintf(f, "type _cgo_arg_%s struct {\n", ef.Name)
   204  			for i, pt := range ef.Params {
   205  				fmt.Fprintf(f, "\tp%d %s\n", i, pt)
   206  			}
   207  			if ef.Ret != "" {
   208  				fmt.Fprintf(f, "\tret %s\n", ef.Ret)
   209  			}
   210  			fmt.Fprintf(f, "}\n\n")
   211  		}
   212  
   213  		var callArgs []string
   214  		for i := range ef.Params {
   215  			callArgs = append(callArgs, fmt.Sprintf("args.p%d", i))
   216  		}
   217  		callStr := fmt.Sprintf("%s(%s)", ef.Name, strings.Join(callArgs, ", "))
   218  
   219  		fmt.Fprintf(f, "//go:linkname _cgoexp%s_%s _cgoexp%s_%s\n", cPrefix, ef.Name, cPrefix, ef.Name)
   220  		fmt.Fprintf(f, "func _cgoexp%s_%s(a unsafe.Pointer) {\n", cPrefix, ef.Name)
   221  		if len(ef.Params) == 0 && ef.Ret == "" {
   222  			fmt.Fprintf(f, "\t%s()\n", ef.Name)
   223  		} else {
   224  			fmt.Fprintf(f, "\targs := (*_cgo_arg_%s)(a)\n", ef.Name)
   225  			if ef.Ret != "" {
   226  				fmt.Fprintf(f, "\targs.ret = %s\n", callStr)
   227  				if abiCfg.inspectType(ef.Ret, typeMap).hasPointers {
   228  					if ef.Func != nil && p.fset != nil {
   229  						pos := p.fset.Position(ef.Func.Pos())
   230  						fmt.Fprintf(f, "//line %s:%d\n", filepath.ToSlash(pos.Filename), pos.Line)
   231  					}
   232  					fmt.Fprintf(f, "\t_cgoCheckResult(args.ret)\n")
   233  					if ef.Func != nil && p.fset != nil {
   234  						fmt.Fprintf(f, "//line :1\n")
   235  					}
   236  				}
   237  			} else {
   238  				fmt.Fprintf(f, "\t%s\n", callStr)
   239  			}
   240  		}
   241  		fmt.Fprintf(f, "}\n\n")
   242  
   243  		fmt.Fprintf(f, "var _cgo_fn_%s = _cgoexp%s_%s\n\n", ef.Name, cPrefix, ef.Name)
   244  	}
   245  }
   246  
   247  func isUnsupportedExportType(expr ast.Expr, typeSpecs map[string]*ast.TypeSpec, seen map[string]bool) bool {
   248  	switch t := expr.(type) {
   249  	case *ast.ParenExpr:
   250  		return isUnsupportedExportType(t.X, typeSpecs, seen)
   251  	case *ast.Ellipsis, *ast.MapType, *ast.ChanType, *ast.InterfaceType, *ast.FuncType:
   252  		return true
   253  	case *ast.ArrayType:
   254  		if t.Len == nil {
   255  			return true
   256  		}
   257  		return isUnsupportedExportType(t.Elt, typeSpecs, seen)
   258  	case *ast.StructType:
   259  		if t.Fields != nil {
   260  			for _, fld := range t.Fields.List {
   261  				if isUnsupportedExportType(fld.Type, typeSpecs, seen) {
   262  					return true
   263  				}
   264  			}
   265  		}
   266  		return false
   267  	case *ast.StarExpr:
   268  		if at, ok := t.X.(*ast.ArrayType); ok && at.Len != nil {
   269  			if bl, ok := at.Len.(*ast.BasicLit); ok && bl.Value == "0" {
   270  				return false
   271  			}
   272  		}
   273  		return isUnsupportedExportType(t.X, typeSpecs, seen)
   274  	case *ast.Ident:
   275  		switch t.Name {
   276  		case "string", "complex64", "complex128", "any", "error":
   277  			return true
   278  		}
   279  		if ts, ok := typeSpecs[t.Name]; ok && !seen[t.Name] {
   280  			seen[t.Name] = true
   281  			res := isUnsupportedExportType(ts.Type, typeSpecs, seen)
   282  			delete(seen, t.Name)
   283  			return res
   284  		}
   285  	case *ast.SelectorExpr:
   286  		if id, ok := t.X.(*ast.Ident); ok && id.Name == "C" {
   287  			switch t.Sel.Name {
   288  			case "_GoString_", "_GoBytes_", "complexfloat", "complexdouble":
   289  				return true
   290  			}
   291  		}
   292  	}
   293  	return false
   294  }
   295  
   296  func bindingExportCType(expr ast.Expr, entry *Bindings, imp fileImports, seen map[string]bool) (string, bool) {
   297  	switch t := expr.(type) {
   298  	case *ast.ParenExpr:
   299  		return bindingExportCType(t.X, entry, imp, seen)
   300  	case *ast.StarExpr:
   301  		if at, ok := t.X.(*ast.ArrayType); ok && at.Len != nil {
   302  			if bl, ok := at.Len.(*ast.BasicLit); ok && bl.Value == "0" {
   303  				return "void*", true
   304  			}
   305  		}
   306  		if sel, ok := t.X.(*ast.SelectorExpr); ok {
   307  			if id, ok := sel.X.(*ast.Ident); ok && id.Name == "C" && sel.Sel.Name == "void" {
   308  				return "void*", true
   309  			}
   310  		}
   311  		elem, ok := bindingExportCType(t.X, entry, imp, seen)
   312  		if !ok {
   313  			return "", false
   314  		}
   315  		return elem + "*", true
   316  	case *ast.SelectorExpr:
   317  		if id, ok := t.X.(*ast.Ident); ok {
   318  			if imp.unsafe[id.Name] && t.Sel.Name == "Pointer" {
   319  				return "void*", true
   320  			}
   321  			if id.Name == "C" {
   322  				switch t.Sel.Name {
   323  				case "int8_t":
   324  					return "GoInt8", true
   325  				case "uint8_t":
   326  					return "GoUint8", true
   327  				case "int16_t":
   328  					return "GoInt16", true
   329  				case "uint16_t":
   330  					return "GoUint16", true
   331  				case "int32_t":
   332  					return "GoInt32", true
   333  				case "uint32_t":
   334  					return "GoUint32", true
   335  				case "int64_t":
   336  					return "GoInt64", true
   337  				case "uint64_t":
   338  					return "GoUint64", true
   339  				case "uintptr_t":
   340  					return "GoUintptr", true
   341  				case "intptr_t", "ssize_t":
   342  					return "ptrdiff_t", true
   343  				case "bool":
   344  					return "_Bool", true
   345  				default:
   346  					return cname(t.Sel.Name), true
   347  				}
   348  			}
   349  		}
   350  	case *ast.Ident:
   351  		if imp.unsafe["."] && t.Name == "Pointer" {
   352  			return "void*", true
   353  		}
   354  		if cName, ok := entry.TypeGoToAnyC[t.Name]; ok && cName != "" {
   355  			return cname(cName), true
   356  		}
   357  		if t.Name == "uintptr" {
   358  			return "GoUintptr", true
   359  		}
   360  		if gt, ok := goTypes[t.Name]; ok {
   361  			return gt.C.String(), true
   362  		}
   363  		if ts, ok := entry.typeSpecs[t.Name]; ok && !seen[t.Name] {
   364  			seen[t.Name] = true
   365  			res, ok := bindingExportCType(ts.Type, entry, imp, seen)
   366  			delete(seen, t.Name)
   367  			return res, ok
   368  		}
   369  	}
   370  	return "", false
   371  }
   372  
   373  func (p *Package) writeBindingExportHeader(headerPath string, entry *Bindings, expFuncs []ExportFunc, sources []bindingSource) {
   374  	var preamble strings.Builder
   375  	for _, bs := range sources {
   376  		if bs.file == nil {
   377  			continue
   378  		}
   379  		forEachImportC(bs.file, func(_ *ast.GenDecl, _ *ast.ImportSpec, doc *ast.CommentGroup) {
   380  			if doc == nil {
   381  				return
   382  			}
   383  			for line := range strings.SplitSeq(commentText(doc), "\n") {
   384  				l := strings.TrimSpace(line)
   385  				if (len(l) >= 5 && l[:4] == "#cgo" && (l[4] == ' ' || l[4] == '\t')) || isCgoPragmaComment("//"+l) {
   386  					preamble.WriteByte('\n')
   387  					continue
   388  				}
   389  				preamble.WriteString(line)
   390  				preamble.WriteByte('\n')
   391  			}
   392  		})
   393  	}
   394  	origPreamble := p.Preamble
   395  	if p.Preamble == "" {
   396  		p.Preamble = preamble.String()
   397  	}
   398  	defer func() { p.Preamble = origPreamble }()
   399  
   400  	formatCType := func(expr ast.Expr, imp fileImports) string {
   401  		ct, ok := bindingExportCType(expr, entry, imp, make(map[string]bool))
   402  		if !ok {
   403  			var tb bytes.Buffer
   404  			noSourceConf.Fprint(&tb, p.fset, expr)
   405  			fatalf("%s: cannot represent Go type %s in _cgo_export.h (bind it with //cgo:type)", p.fset.Position(expr.Pos()), tb.String())
   406  		}
   407  		return ct
   408  	}
   409  
   410  	var hdr bytes.Buffer
   411  	p.writeExportHeader(&hdr)
   412  	for _, ef := range expFuncs {
   413  		if ef.Func == nil {
   414  			continue
   415  		}
   416  		fntype := ef.Func.Type
   417  		cRet := "void"
   418  		if fntype.Results != nil && len(fntype.Results.List) > 0 {
   419  			cRet = formatCType(fntype.Results.List[0].Type, ef.Imp)
   420  		}
   421  		var s strings.Builder
   422  		fmt.Fprintf(&s, "%s %s(", cRet, ef.Name)
   423  		if fntype.Params != nil && len(fntype.Params.List) > 0 {
   424  			forFieldList(fntype.Params, func(i int, aname string, atype ast.Expr) {
   425  				if i > 0 {
   426  					s.WriteString(", ")
   427  				}
   428  				cParamType := formatCType(atype, ef.Imp)
   429  				fmt.Fprintf(&s, "%s %s", cParamType, exportParamName(aname, i))
   430  			})
   431  		} else {
   432  			s.WriteString("void")
   433  		}
   434  		s.WriteByte(')')
   435  		fmt.Fprintf(&hdr, "extern %s;\n", s.String())
   436  	}
   437  	fmt.Fprintf(&hdr, "%s", gccExportHeaderEpilog)
   438  
   439  	if err := os.WriteFile(headerPath, hdr.Bytes(), 0666); err != nil {
   440  		fatalf("%s", err)
   441  	}
   442  }
   443  

View as plain text