sanpatch

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: 17 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 sanpatch provides an in-process CUDA Compute Sanitizer device-patching oracle built on the Compute Sanitizer public API.

Wrapping a Go fuzz target with the external compute-sanitizer launcher leaves exec'd fuzz workers unsanitized because compute-sanitizer does not follow exec'd child processes. Package sanpatch instead loads libsanitizer-public.so in-process, compiles and verifies a device-side bounds-checking patch cubin, attaches it on module load, and inspects per-launch violation counters via sanitizer callback-safe memory APIs.

Non-poisoning detection and standing caveat

The embedded device patch checks every instrumented global memory access against up to MaxRanges registered device address ranges before the access executes. When an access falls outside all registered ranges, the patch records the first offending PC, address, size, and flags and returns SANITIZER_PATCH_ERROR, which exits the warp before the illegal access reaches memory so the CUDA context is not poisoned.

Standing caveats:

  • A clean verdict from a patched launch means "no violation before the first warp exit", not "no violation" anywhere in the kernel. Once a warp exits on a violation, downstream instructions in that warp do not run.
  • SANITIZER_PATCH_ERROR exits only the offending warp. In a kernel with intra-CTA barriers such as __syncthreads(), an early-exited warp can leave sibling warps waiting at the barrier and hang the launch unless paired with a launch timeout.
  • Oracle stages one Tracker per CUDA context. Launches on a given context must be serialized with Oracle.Snapshot (at most one in-flight launch per context).

Controls and liveness

Before any patch cubin is passed to the sanitizer library, VerifyPatchCubin parses its ELF symbol table in pure Go and requires exactly one defined STT_FUNC entry for the patch symbol (Control 0). Inside each fuzz worker, callers must run one warm-up launch and assert CheckLiveness so a wrong-arch or unpatched worker fails closed instead of silently reporting clean runs.

Scope limits

Package sanpatch provides a memory-access oracle, not device control-flow coverage. In Compute Sanitizer, SANITIZER_INSTRUCTION_BLOCK_ENTER fires per thread on CUDA thread-block (CTA) entry rather than per CFG basic block, so it is intentionally not used as a coverage signal here. Native GPU tests are env-gated on SANPATCH_NATIVE=1 under gpu-lock (inherited GPU_LOCK_HELD); host tests verify ELF symbol checks, tracker layout parity, bounds arithmetic, and fail-closed liveness without requiring a GPU.

This package is outside the compatibility promise of github.com/tmc/lib/nvidia. Its API may change or be removed in patch releases.

Index

Examples

Constants

View Source
const DefaultSymbol = "sanpatch_global_memaccess"

DefaultSymbol is the device patch callback exported by BoundsPatchSource.

View Source
const MaxRanges = 16

MaxRanges is the fixed capacity of registered device address intervals in Tracker, matching SANPATCH_MAX_RANGES in patch_bounds.cu.

Variables

View Source
var BoundsPatchSource string

BoundsPatchSource is the embedded CUDA C++ source for the non-poisoning global-memory bounds-checking device patch.

View Source
var ErrLivenessFailed = errors.New("sanpatch: liveness check failed")

ErrLivenessFailed is returned by CheckLiveness when instrumentation is absent or failed to install.

View Source
var ErrNoTracker = errors.New("sanpatch: no tracker allocated for context")

ErrNoTracker is returned by Oracle.Snapshot when no active device Tracker exists for the requested CUDA context (for example before any module load or after context destruction / Oracle.Close).

Functions

func CheckLiveness

func CheckLiveness(st Stats) error

CheckLiveness enforces fail-closed instrumentation liveness (Gate 6 Rule 5). A worker that ran a warm-up launch with zero patched modules, zero observed accesses, or any patch installation error must fail loudly rather than scoring inputs unsanitized.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/sanpatch"
)

func main() {
	okErr := sanpatch.CheckLiveness(sanpatch.Stats{ModulesPatched: 1, Accesses: 2})
	zeroErr := sanpatch.CheckLiveness(sanpatch.Stats{ModulesPatched: 1, Accesses: 0})
	fmt.Printf("live=%v zero_err=%v\n", okErr == nil, zeroErr != nil)
}
Output:
live=true zero_err=true

Types

type Config

type Config struct {
	// PatchCubin holds raw cubin ELF bytes compiled with
	// nvcc --cubin --compile-as-tools-patch. If empty, PatchCubinPath is read.
	PatchCubin []byte

	// PatchCubinPath locates a compiled patch cubin on disk when PatchCubin is empty.
	PatchCubinPath string

	// Symbol is the device callback function name to attach. Empty defaults to
	// [DefaultSymbol].
	Symbol string

	// Instruction is the sanitizer instruction class to patch. Zero defaults to
	// [sanitizer.InstructionGlobalMemoryAccess].
	Instruction sanitizer.InstructionId

	// ContextLog receives subscription results and process-local context
	// handles from module and launch callbacks. Its Write must not call
	// CUDA. A nil writer disables logging.
	ContextLog io.Writer
}

Config configures an in-process Compute Sanitizer Oracle.

type Oracle

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

Oracle owns the process's single Compute Sanitizer subscription, attaches a verified device patch cubin on every module load, stages per-launch legal buffer ranges into device memory, and reads back access and violation counts.

Create an Oracle before the process makes its first CUDA call so the sanitizer observes context creation and module loads. Launches on a given context must be serialized with Oracle.Snapshot (at most one in-flight launch per context).

func Install

func Install(cfg Config) (*Oracle, error)

Install loads libsanitizer-public.so from the CUDA toolkit, verifies the patch cubin via VerifyPatchCubin (Control 0), subscribes in-process, and enables resource and launch callbacks.

Install must be called before any CUDA context or module is created.

func (*Oracle) Close

func (o *Oracle) Close() error

Close unsubscribes from Compute Sanitizer and frees device trackers after waiting for any in-flight Oracle.Snapshot or launch staging to finish.

func (*Oracle) Info

func (o *Oracle) Info() PatchCubinInfo

Info returns the validated ELF metadata of the installed patch cubin.

func (*Oracle) SetRanges

func (o *Oracle) SetRanges(ranges ...Range) error

SetRanges configures the legal device address intervals checked by subsequent kernel launches. Pass zero ranges to run an unarmed warm-up launch that still increments access counters for CheckLiveness.

func (*Oracle) Snapshot

func (o *Oracle) Snapshot(ctx driver.Context, stream driver.Stream) (Tracker, error)

Snapshot synchronizes stream and reads back the device Tracker for ctx. Launches on ctx must be serialized with Snapshot. If no active tracker exists for ctx (before module load or after context destruction / Oracle.Close), Snapshot returns an error wrapping ErrNoTracker.

func (*Oracle) Stats

func (o *Oracle) Stats() Stats

Stats returns the current patching and instrumentation health snapshot.

type PatchCubinInfo

type PatchCubinInfo struct {
	Arch        int
	SymbolName  string
	SymbolCount int
}

PatchCubinInfo records the validated metadata of a compiled sanitizer patch cubin returned by VerifyPatchCubin.

func CompilePatchCubin

func CompilePatchCubin(ctx context.Context, nvcc, arch, dir string) ([]byte, PatchCubinInfo, error)

CompilePatchCubin compiles BoundsPatchSource with nvcc for arch (for example "sm_121a" or "sm_86") using --cubin --compile-as-tools-patch, runs VerifyPatchCubin (Control 0), and returns the verified cubin bytes.

Raw --cubin is used rather than --fatbin because arch-specific suffixes such as sm_121a are rejected inside fatbin wrappers by sanitizerAddPatches.

func VerifyPatchCubin

func VerifyPatchCubin(image []byte, symbol string) (PatchCubinInfo, error)

VerifyPatchCubin implements Control 0 in pure Go: it verifies that image is a little-endian CUDA ELF cubin (not a fatbin wrapper) carrying a nonzero SM target and exactly one defined STT_FUNC symbol named symbol.

Without this check, a patch compiled without --compile-as-tools-patch can dead-strip the device callback symbol and produce zero instrumentation, which is indistinguishable from a wrong-arch failure by instrumentation count alone.

func VerifyPatchCubinFile

func VerifyPatchCubinFile(path, symbol string) (PatchCubinInfo, error)

VerifyPatchCubinFile reads path and validates it with VerifyPatchCubin.

type Range

type Range struct {
	Lo uint64
	Hi uint64
}

Range describes a half-open legal device address interval [Lo, Hi).

func (Range) Contains

func (r Range) Contains(addr uint64, size uint32) bool

Contains reports whether the byte access [addr, addr+size) lies wholly within [r.Lo, r.Hi) without uint64 wraparound.

type Stats

type Stats struct {
	ModulesPatched int
	PatchErrors    int
	Accesses       uint64
	Violations     uint64
	LastPatchErr   error
}

Stats summarizes the patching and instrumentation health of an Oracle.

type Tracker

type Tracker struct {
	Accesses   uint64
	Violations uint64
	FirstPC    uint64
	FirstAddr  uint64
	FirstSize  uint32
	FirstFlags uint32
	RangeCount uint32
	Reserved   uint32
	Ranges     [MaxRanges]Range
}

Tracker mirrors struct SanPatchTracker in patch_bounds.cu byte-for-byte. The device patch updates Accesses, Violations, and First* atomically; the host stages Ranges and RangeCount before each launch and snapshots the result after stream synchronization.

func (*Tracker) CheckAccess

func (t *Tracker) CheckAccess(pc, addr uint64, size, flags uint32) bool

CheckAccess evaluates one global memory access against t using the exact rules of sanpatch_global_memaccess in patch_bounds.cu. It returns true when the access is permitted (or t is unarmed) and false when a violation is recorded.

Example
package main

import (
	"fmt"

	"github.com/tmc/lib/nvidia/x/obs/sanpatch"
)

func main() {
	var trk sanpatch.Tracker
	if err := trk.SetRanges(
		sanpatch.Range{Lo: 0x1000, Hi: 0x1400},
		sanpatch.Range{Lo: 0x2000, Hi: 0x2400},
	); err != nil {
		panic(err)
	}

	okIn := trk.CheckAccess(0x100, 0x1000, 4, 0)
	okOut := trk.CheckAccess(0x120, 0x1400, 4, 1)
	v, hasViolation := trk.Violation()
	fmt.Printf("in=%v out=%v accesses=%d violations=%d first_pc=%#x first_addr=%#x has=%v\n",
		okIn, okOut, trk.Accesses, trk.Violations, v.PC, v.Addr, hasViolation)
}
Output:
in=true out=false accesses=2 violations=1 first_pc=0x120 first_addr=0x1400 has=true

func (*Tracker) ResetCounters

func (t *Tracker) ResetCounters()

ResetCounters zeroes access and violation counters while preserving the registered legal ranges.

func (*Tracker) SetRanges

func (t *Tracker) SetRanges(ranges ...Range) error

SetRanges replaces the active legal device ranges on t. Passing zero ranges leaves t unarmed (counting accesses for liveness without checking bounds).

func (*Tracker) Violation

func (t *Tracker) Violation() (Violation, bool)

Violation returns the first violation recorded in t, if any.

type Violation

type Violation struct {
	PC    uint64
	Addr  uint64
	Size  uint32
	Flags uint32
}

Violation captures the first out-of-bounds memory access recorded by the device patch during a launch.

Jump to

Keyboard shortcuts

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