Skip to content

Possible cgo pointer rule violation: FilteredSearch panics when the callback captures variables or Data holds a heap value #799

Closed

Description

@OvOhao

FilteredSearch passes the handler struct itself to C as the filter state:

golang/lib.go:243 (main, 1e8a192)

type FilteredSearchHandler struct {
	Callback func(key Key, handler *FilteredSearchHandler) int
	Data     any
}

golang/lib.go:771

	resultCount := uint(C.usearch_filtered_search(index.handle, unsafe.Pointer(&query[0]), C.usearch_scalar_f32_k, (C.size_t)(limit),
		(C.usearch_filtered_search_callback_t)(C.goFilteredSearchCallback), unsafe.Pointer(handler), //nolint:govet // handler is kept alive by the caller

The handler contains a func value and an any. When the callback is a
closure that captures variables, or Data holds anything allocated at run
time, the struct contains Go pointers, and the default cgocheck rejects the
call with panic: runtime error: argument of cgo function has Go pointer to unpinned Go pointer before the C function runs. The same call is in
FilteredSearchUnsafe (lib.go:859), FilteredSearchI8 (:1044) and
FilteredSearchU8 (:1137).

I ran a program with the same struct and call shape against a C stub that
invokes the callback (Go 1.27.0, darwin/arm64, default GODEBUG). These worked:
a top-level or non-capturing callback with Data: nil, and Data set to an
integer constant. These panicked at the call: a callback that captures a
variable, and Data set to a heap string, a pointer to a struct, or a map.
The README example uses a non-capturing callback with Data: nil, and the
tests (golang/lib_test.go:552-560 and siblings) use one with Data: int64(1);
both are the passing cases above, which is why they do not show the panic.
Filtering against a captured set of allowed keys, or using Data as the README
describes ("Optional user data") with a heap value, panics.

C does not keep the pointer after the call (it is used inside
usearch_filtered_search only), so the problem is the pointer content check,
not lifetime; the //nolint:govet comment addresses lifetime.

Suggested fix: pass a cgo.Handle instead of the struct, for example
h := cgo.NewHandle(handler); defer h.Delete() and pass
unsafe.Pointer(uintptr(h)) as the filter state, then recover it in
goFilteredSearchCallback with cgo.Handle(uintptr(state)).Value().

If you could credit me as a reporter for my contributions to security advisory I will be thankful.

Activity

  1. added a commit that references this issue on Oct 18, 2026
    ad77fe7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions