ffi

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 8 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Examples

Constants

View Source
const (
	Width8 = 0 // 8-byte word: int64, uint64, pointer, double
	Width1 = 1 // 1 byte: int8, uint8, bool, char
	Width2 = 2 // 2 bytes: int16, uint16
	Width4 = 3 // 4 bytes: int32, uint32, float
)

Argument width codes for the widths mask of CallWidths and CallFloatWidths. Position i's code occupies bits 2i and 2i+1, so position i has width w when widths has w<<(2*i). The zero code is a full 8-byte word, which makes a zero mask mean the same thing as Call.

View Source
const MaxArgs = 32

MaxArgs is the maximum number of positional arguments Call accepts.

Variables

View Source
var ErrCgoDisabled = errors.New("ffi: inline ffi-eject mode requires CGO_ENABLED=1 (or purego fakecgo) for foreign calls")

ErrCgoDisabled is returned by inline-mode entry points (Open, Sym, Close, RegisterFunc) when built under CGO_ENABLED=0 without a fakecgo bootstrap.

Functions

func Call

func Call(fn uintptr, n int, args *[MaxArgs]uintptr, floatMask uint32) (r1, r2, r3 uintptr)

Call calls the C function fn with n positional argument words taken from args[:n]. Bit i of floatMask marks position i as a floating-point bit pattern (a float64 in the full word, a float32 in its low 32 bits — see math.Float32bits); the other positions are integer or pointer words. It returns the first two integer result registers and the errno slot, and performs no heap allocation.

For a C function that returns a floating-point value, use CallFloat.

r3 is the errno the call left behind, where the trampoline captures it:

  • darwin: errno, narrowed to 32 bits (see below).
  • linux/amd64, linux/arm64: 0. A copy ejected with ffi-eject -with-errno adds CallErrno, which returns errno there for the calls that ask for it.
  • freebsd, netbsd: 0.
  • windows/arm64: meaningless; neither errno nor GetLastError is captured.

Like errno itself, r3 means something only when the result says the call failed; a successful call may leave a stale nonzero value behind.

On darwin r3 is narrowed to 32 bits here. The trampoline reads errno with an 8-byte load through the int* that __error() returns, so the upper half of the slot is whatever adjacent thread-local memory holds and varies from call to call; a caller testing r3 != 0 would see a nonzero value after a successful call. errno is a C int, so the low 32 bits are the whole value.

The garbage collector does not treat a uintptr as a reference, and a laundered uintptr goes stale if the object it names moves. If an argument is a Go pointer laundered through uintptr(unsafe.Pointer(x)), pin x with a runtime.Pinner bracketing the call (Pin also forces x to the heap), or call through a //go:uintptrescapes wrapper such as the calls/ package generates. runtime.KeepAlive after the call is NOT sufficient by itself: it prevents reclamation but not movement, and a stack-resident x moves whenever the goroutine stack grows or the GC relocates it, leaving the C function writing through the stale address (ffitest/noescape_probe_test.go demonstrates this). Pointers into C memory need no such care.

The ffivet analyzer (cmd/ffivet) flags a launder with no guard, but only when the conversion and the call are in the same function: it is intraprocedural, so a pointer laundered in one frame and passed through a slice or a helper into a call in another is invisible to it. Run ffivet -opaque-args to list the call sites it cannot reach rather than reading a clean report as full coverage.

A wrapper whose parameters are typed unsafe.Pointer rather than uintptr — what purego's RegisterLibFunc generates — has no laundering in Go source at all, because the conversion happens inside purego's own closure. The GC does trace an unsafe.Pointer, so the object stays live while the value is in a Go frame, but nothing pins it across the call and nothing accounts for a callee that keeps the address afterwards. A callback-driven API that retains the pointer until the handler fires needs the object reachable that whole time; no post-call guard expresses that, and ffivet does not check it.

fn must be non-zero, args non-nil, n in [0, MaxArgs], floatMask must not mark a position beyond n, and floatMask must not mark more than 8 positions (the width of the floating-point register file on these ABIs); Call panics otherwise.

func CallErrno

func CallErrno(fn uintptr, n int, args *[MaxArgs]uintptr, floatMask uint32) (r1, r2 uintptr, errno int32)

CallErrno is like Call but returns the errno the C function left behind, for functions that report failure through it. errno is read right after fn returns, on the same thread, before any other C call can change it. Like errno itself, it means something only when r1 says the call failed.

Only calls made through CallErrno pay to read errno: on linux it costs one extra libc call, and Call does not read errno there at all. On darwin every call already reads it, and CallErrno returns what Call returns as r3.

func CallFloat

func CallFloat(fn uintptr, n int, args *[MaxArgs]uintptr, floatMask uint32) (r1, rf1 uintptr)

CallFloat is like Call but also returns the first floating-point result register's bits, for C functions that return a float32 or float64. Decode a float64 result with math.Float64frombits(rf1); a float32 result with math.Float32frombits(uint32(rf1)). r1 is still returned for functions that set both. The same pointer-liveness contract as Call applies.

func CallFloatWidths

func CallFloatWidths(fn uintptr, n int, args *[MaxArgs]uintptr, floatMask uint32, widths uint64) (r1, rf1 uintptr)

CallFloatWidths is like CallFloat but takes argument widths as CallWidths does.

func CallWidths

func CallWidths(fn uintptr, n int, args *[MaxArgs]uintptr, floatMask uint32, widths uint64) (r1, r2, r3 uintptr)

CallWidths is like Call but also takes the size of each argument, which darwin/arm64 needs to lay out stack arguments: Apple's arm64 ABI packs arguments past the eighth integer register at their natural size and alignment rather than in 8-byte slots, so an int32 there moves every later stack argument. Position i's width code is (widths>>(2*i))&3, one of Width8, Width1, Width2, Width4; a zero widths is Call. Mark every position narrower than 8 bytes, not only the ones known to reach the stack, since which positions spill depends on how many integer arguments precede them.

widths affects stack arguments on darwin/arm64 only. Register arguments, and every argument on the other platforms, are passed as full words whatever their width, so there the mask is validated and otherwise ignored. The callee reads only the low bytes of a narrow argument; the caller need not extend it. The arguments of a variadic function past its fixed parameters are 8-byte stack slots on darwin/arm64, so leave their positions at Width8.

widths must not mark a position beyond n; CallWidths panics otherwise, and under every other condition Call panics.

func Close

func Close(handle uintptr) error

func Open

func Open(path string) (uintptr, error)

func RegisterFunc

func RegisterFunc(fptr any, fn uintptr) error

RegisterFunc binds fptr to fn using a local marshaler for the platform's C calling convention. It returns an error without changing fptr if the signature is unsupported. Unlike Register, it does not use purego's reflective marshaler.

Supported platforms are darwin/arm64, linux/arm64, and the System V amd64 platforms (darwin, freebsd, linux, netbsd). Arguments may be integer, bool, float, pointer, or plain-data struct values, and there may be one result of the same kinds. Pointer fields in structs, strings, slices, function values, and variadic signatures are rejected everywhere.

On arm64, struct arguments and results are at most 16 bytes and not homogeneous floating-point aggregates, and all arguments must fit in the eight integer and eight floating-point registers.

On amd64, structs are classified by eightbyte as the System V ABI specifies. Arguments that do not fit in the six integer and eight SSE registers, and structs larger than 16 bytes, are passed on the stack; a struct result larger than 16 bytes is returned through a hidden pointer. A struct result with two SSE eightbytes (returned in XMM0 and XMM1) is rejected, as are signatures needing more than MaxArgs argument words.

The Go signature and struct layout must match C, including padding. Pointers are pinned for the duration of the call; C must not retain them after return. A uintptr containing a Go address must already be pinned by the caller.

Example
package main

import (
	"fmt"

	ffi "github.com/tmc/lib/nvidia/internal/ffi"
)

type team12 struct{ A, B, C int32 }

func main() {
	var call func(team12) int32
	err := ffi.RegisterFunc(&call, 0)
	fmt.Println(err)
}
Output:
ffi: function address is zero

func Sym

func Sym(handle uintptr, name string) (uintptr, error)

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL