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 ¶
const DefaultSymbol = "sanpatch_global_memaccess"
DefaultSymbol is the device patch callback exported by BoundsPatchSource.
const MaxRanges = 16
MaxRanges is the fixed capacity of registered device address intervals in Tracker, matching SANPATCH_MAX_RANGES in patch_bounds.cu.
Variables ¶
var BoundsPatchSource string
BoundsPatchSource is the embedded CUDA C++ source for the non-poisoning global-memory bounds-checking device patch.
var ErrLivenessFailed = errors.New("sanpatch: liveness check failed")
ErrLivenessFailed is returned by CheckLiveness when instrumentation is absent or failed to install.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
type PatchCubinInfo ¶
PatchCubinInfo records the validated metadata of a compiled sanitizer patch cubin returned by VerifyPatchCubin.
func CompilePatchCubin ¶
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 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 ¶
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.