library

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 20 Imported by: ? 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

Overview

Package library loads a C shared library (.so, .dylib, .dll) into a Go program without cgo, through purego, and binds its exported functions to Go function variables. It works the same in a cgo and a cgo-free build, on Linux, macOS and Windows for amd64 and arm64; Supported reports whether this build can load at all.

A library is loaded once per canonical path and never unloaded: unloading native code that a Go program has called into, or that started threads, is not safe. Use immutable, revision-specific paths.

Only functions the Go side calls are bound. purego's callbacks (C calling back into Go) are limited in number and platform, so a C API meant for this package takes no function pointers it would call on a Go program's behalf.

Index

Constants

View Source
const CitationSchema = "ext.library.citation/v1"

CitationSchema names the citation format.

Variables

View Source
var ErrNoAsset = errors.New("the citation publishes no build for this target")

ErrNoAsset is a target the citation publishes nothing for.

View Source
var ErrNotDescribed = errors.New("library: not in the library's description")

ErrNotDescribed is an object kind, operation or event its library does not describe.

View Source
var ErrNotProvided = errors.New("no copy of this library is provided")

ErrNotProvided is a library no package of this program provides a copy of.

View Source
var ErrUnsupported = errors.New("loading a C shared library is unsupported in this build")

ErrUnsupported is returned where this build cannot load a C library.

Functions

func Call

func Call[Out any](o *Object, op string, in any) (Out, error)

Call is Object.Call with the answer as an Out.

func LocalPath

func LocalPath(p string) bool

LocalPath reports whether p is a relative, slash-separated path that stays inside its root.

func Materialize

func Materialize(c Copy, library, dir string) (string, error)

Materialize writes c under dir/<library>/<sha256>/<file> and returns the path, reusing a file that is already there with the same contents.

func Provide

func Provide(library string, c Copy)

Provide records the copy of library (its C prefix, such as ext_plugin) this program carries. The package ext bundle fetch writes calls it from init; a second, different copy of the same library is a build mistake and panics.

func Supported

func Supported() bool

Types

type Asset

type Asset struct {
	// Targets are the GOOS/GOARCH pairs the archive serves, such as "darwin/arm64".
	Targets []string `json:"targets"`
	URL     string   `json:"url"`
	SHA256  string   `json:"sha256"`
	// Root is the directory inside the archive that holds its files, if it has one.
	Root    string  `json:"root,omitempty"`
	Drivers Drivers `json:"drivers"`
}

An Asset is one published archive (a .tar.gz) and what each driver takes from it.

type C2GoFiles

type C2GoFiles struct {
	Go string `json:"go"`
}

C2GoFiles is a directory of Go source: the library translated by ccgo, with its binding.

type CGoFiles

type CGoFiles struct {
	Include string   `json:"include"`           // a directory of headers
	Static  string   `json:"static"`            // the static library
	CFlags  []string `json:"cflags,omitempty"`  // such as -DEXT_PLUGIN_HOST_STATIC
	LDFlags []string `json:"ldflags,omitempty"` // system libraries, such as -lpthread
}

CGoFiles are the headers and the static library a cgo build links.

type Caller

type Caller interface {
	Call(handle uint64, op string, input []byte) ([]byte, error)
}

A Caller runs one operation of a library's interface. *Interface is one.

type Citation

type Citation struct {
	Schema  string  `json:"schema"`
	Library string  `json:"library"` // the library's C prefix, such as ext_plugin or ext_ledger
	Version string  `json:"version"`
	Assets  []Asset `json:"assets"`
}

A Citation pins one release of a C library: where each platform's build is published and the SHA-256 it must have. It is plain data, published by the library's own releases and read by ext bundle fetch; this package knows no library by name.

func ParseCitation

func ParseCitation(data []byte) (Citation, error)

ParseCitation decodes and validates a citation, refusing unknown fields.

func ReadCitation

func ReadCitation(file string) (Citation, error)

ReadCitation reads and validates a citation file.

func (Citation) Asset

func (c Citation) Asset(target, driver string) (Asset, error)

Asset returns the asset that serves driver (cgo, purego or c2go) for target ("goos/goarch"). A target's drivers may come from different assets: the translation ccgo makes for a target is published apart from its built library.

func (Citation) Validate

func (c Citation) Validate() error

Validate checks the citation's names, digests, URLs and file paths.

type CodeError

type CodeError struct {
	Library string
	Op      string
	Code    int32
	Name    string
}

A CodeError is a non-zero code a library returned, with its name when the library exports one.

func (*CodeError) CodeName

func (e *CodeError) CodeName() string

CodeName is the library's name for the code, empty when it exports none.

func (*CodeError) Error

func (e *CodeError) Error() string

type Copy

type Copy struct {
	File   string
	Data   []byte
	SHA256 string
}

A Copy is a built C shared library a program carries in its binary, as the package ext bundle fetch writes for the purego driver embeds it: its file name, its bytes and their SHA-256.

func Provided

func Provided(library string) (Copy, bool)

Provided returns the copy of library this program carries.

type Described

type Described struct {
	*Interface
	Description Description
}

Described is a bound library with its description.

func Describe

func Describe(i *Interface) (*Described, error)

Describe reads the description of the library behind i and checks it is the library i binds.

func (*Described) Library

func (d *Described) Library() *Object

Library is handle 0, the library itself.

func (*Described) Open

func (d *Described) Open(kind string, config any, handlers Handlers) (*Object, error)

Open opens an object of kind from config (any value that marshals to a JSON object; its "object" field is set to kind). handlers serve the object's events by kind; an event without a handler is denied (or, when it asks nothing, dropped).

type Description

type Description struct {
	Library    string                       `json:"library"`
	ABIVersion uint32                       `json:"abi_version"`
	About      string                       `json:"about,omitempty"`
	Codes      []string                     `json:"codes"`
	Objects    map[string]ObjectDescription `json:"objects"`
}

A Description is a library's description of its interface.

type Driver

type Driver interface {
	Prefix() string
	ABIVersion() uint32
	Open([]byte) (uint64, error)
	Call(uint64, string, []byte) ([]byte, error)
	Close(uint64) error
}

Driver transports the same described ABI through linked or translated code. Implementations own their allocation boundary and return canonical CodeErrors.

type Drivers

type Drivers struct {
	CGo    *CGoFiles    `json:"cgo,omitempty"`
	PureGo *PureGoFiles `json:"purego,omitempty"`
	C2Go   *C2GoFiles   `json:"c2go,omitempty"`
}

Drivers says, per driver, which files of an asset it needs. A driver that is absent is not published for the asset's targets.

type Event

type Event struct {
	// Seq counts the object's queued events from 1; an event the library made up itself (such as
	// a count of events it dropped) has 0.
	Seq uint64 `json:"seq"`
	// Ticket is not 0 for an event that waits for an answer.
	Ticket uint64 `json:"ticket"`
	Kind   string `json:"kind"`
	// Tag names the call the event belongs to, for an event its description marks as the call's.
	Tag  string          `json:"tag,omitempty"`
	Data json.RawMessage `json:"data"`
}

An Event is one entry of an object's event queue.

func (Event) Asks

func (e Event) Asks() bool

Asks reports whether the event waits for an answer.

type EventDescription

type EventDescription struct {
	About        string          `json:"about,omitempty"`
	Answer       string          `json:"answer"`
	Call         bool            `json:"call,omitempty"`
	Data         json.RawMessage `json:"data,omitempty"`
	DefaultError json.RawMessage `json:"default_error,omitempty"`
}

An EventDescription is one kind of event and how it is answered: "allow" (a policy: allowed or not), "result" (a payload or a public error) or "none" (it asks nothing). An event with Call belongs to the call whose tag it carries.

type Events

type Events struct {
	// contains filtered or unexported fields
}

Events is the loop ServeEvents started.

func ServeEvents

func ServeEvents(c Caller, handle uint64, answer func(Event) map[string]any, notify func(Event)) *Events

ServeEvents takes handle's events until the object is closed. An event that asks goes to answer on a goroutine of its own, and the fields answer returns (such as {"allow": true} or {"payload": ...}) are sent back with its ticket; an answer that panics, or returns nil, sends {"allow": false}. An event that asks nothing goes to notify on the serving goroutine, in the order queued. Either may be nil.

func (*Events) Done

func (e *Events) Done() <-chan struct{}

Done is closed once the object is closed and the loop has ended.

func (*Events) Fence

func (e *Events) Fence()

Fence returns once every event queued before it was called has been handled (an event that asks has been handed to answer; one that asks nothing has returned from notify), or the loop has ended.

type Handler

type Handler func(data json.RawMessage) (any, error)

A Handler serves one kind of event. For an event answered "allow", a nil error allows. For one answered "result", the value is the payload; an error is passed on as the public error when it marshals to an object with a code (such as {"code":..., "message":...}), and is the description's default error otherwise. For one that asks nothing, the result is ignored.

type Handlers

type Handlers map[string]Handler

Handlers serve events by kind.

type Interface

type Interface struct {
	// contains filtered or unexported fields
}

An Interface is a library's four-function interface, the one every library of lib/ exports beside its typed C API: <prefix>_abi_version, <prefix>_open (a JSON config in, a handle out), <prefix>_call (a handle, an operation name and a JSON object in, a JSON value out) and <prefix>_close, with <prefix>_free for what call returns and, when exported, <prefix>_code_name for its error codes. It knows nothing else about the library: ext_ledger's objects and operations are the ledger's, ext_plugin's the plugin engine's.

func BindInterface

func BindInterface(lib *Library, prefix string, want uint32) (*Interface, error)

BindInterface binds prefix's interface in lib and checks its ABI version is want.

func FromDriver

func FromDriver(driver Driver, prefix string, want uint32) (*Interface, error)

FromDriver validates an explicit driver; it never substitutes another engine.

func (*Interface) Call

func (i *Interface) Call(handle uint64, op string, input []byte) ([]byte, error)

Call runs op on handle (0 for the library itself) with a JSON object and returns the JSON value it answers.

func (*Interface) Close

func (i *Interface) Close(handle uint64) error

Close frees the object behind handle.

func (*Interface) Open

func (i *Interface) Open(config []byte) (uint64, error)

Open opens an object from a JSON config and returns its handle.

func (*Interface) Prefix

func (i *Interface) Prefix() string

Prefix is the library's C prefix.

type Library

type Library struct {
	// contains filtered or unexported fields
}

Library is a loaded C shared library.

func Open

func Open(path string) (*Library, error)

Open loads the library at path, resolving symbolic links first, or returns the library already loaded from that canonical path. A failed load is remembered too: loading may have run native initialisers.

func OpenProvided

func OpenProvided(library, dir string) (*Library, error)

OpenProvided opens the copy of library this program carries. The copy is written once under dir (the user cache's ext-go/library when dir is empty), in a directory named for its digest, after its bytes are checked against that digest; an existing file there is used only if it matches.

func (*Library) Bind

func (l *Library) Bind(fn any, name string) error

Bind sets fn, a pointer to a variable of function type, to call the exported function name with the C calling convention.

func (*Library) BindAll

func (l *Library) BindAll(functions map[string]any) error

BindAll binds each function variable to the export of the same key.

func (*Library) Path

func (l *Library) Path() string

Path is the canonical path the library was loaded from.

func (*Library) Symbol

func (l *Library) Symbol(name string) (uintptr, error)

Symbol is the address of an exported symbol, or an error when it is absent.

type Object

type Object struct {
	// contains filtered or unexported fields
}

Object is an object of a described library: handle 0 (Library) or one Open made.

func (*Object) Call

func (o *Object) Call(op string, in, out any) error

Call runs op with in (any value that marshals to JSON; nil is {}) and unmarshals what it answers into out, unless out is nil.

func (*Object) CallWith

func (o *Object) CallWith(op string, in, out any, handlers Handlers) error

CallWith is Call with handlers for the events op raises for this call (its "raises", such as progress): the call is tagged, and those events reach these handlers, before CallWith returns.

func (*Object) Close

func (o *Object) Close() error

Close closes the object and, for one with events, waits for its loop to end and for the answers already being sent, so the library has freed the object (and removed what it owns, such as a command scope's snapshot) when Close returns. A handler still running is not waited for; its answer is not sent. Handle 0 is never closed.

func (*Object) Handle

func (o *Object) Handle() uint64

Handle is the object's handle, as another object's config names it (a ledger watch names its store). Handle 0 is the library.

func (*Object) Kind

func (o *Object) Kind() string

Kind is the object's kind in the description.

type ObjectDescription

type ObjectDescription struct {
	About      string                          `json:"about,omitempty"`
	Config     json.RawMessage                 `json:"config,omitempty"`
	Operations map[string]OperationDescription `json:"operations"`
	Events     map[string]EventDescription     `json:"events,omitempty"`
}

An ObjectDescription is one kind of object. The object called "library" is handle 0, which is never opened or closed.

type OperationDescription

type OperationDescription struct {
	About  string          `json:"about,omitempty"`
	Input  json.RawMessage `json:"input,omitempty"`
	Output json.RawMessage `json:"output,omitempty"`
	Raises []string        `json:"raises,omitempty"`
}

An OperationDescription is one operation: the JSON Schemas of its input and output, and the events it raises for the call itself (such as progress).

type PureGoFiles

type PureGoFiles struct {
	Shared string `json:"shared"`
}

PureGoFiles is the shared library purego loads.

Jump to

Keyboard shortcuts

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