elf

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: 10 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.

README

ELF metadata reader

Read(io.ReaderAt) returns typed ELF headers, sections (with indices), program headers, and ordinary/dynamic symbol tables. Each symbol retains its source table, raw binding/type/info/other, section index, value and size; ordinary defined symbols link to their section metadata. Missing tables are explicitly TablesAbsent, distinct from a present table containing only its null entry.

The reader supplies metadata needed by an operation-specific PT_LOAD/storage observer. It does not choose symbols, enforce a cache inventory, translate addresses, load a DSO, or prove readable runtime storage. Callers retain source/config identity, actual mappings, segment containment/permissions, cache policy, ELF-address observer and qualification gates.

Existing readers were considered first: cudaoccupancy reads CUDA kernel resources; cudasass.CubinImage.Symbols filters an ordinary table by symbol name and is scoped to cubin images. Neither exports dual-table source identity plus section and PT_LOAD metadata for host ELF observers. They remain unchanged. Future integrations can consume this small reader after separate review; existing frozen 6/64/72 policies are unchanged.

Tests construct ELF bytes in memory; no compiler, CUDA, loaded library or binary fixture is required. Controls cover ELF64 little-endian and ELF32 big-endian, GNU-unique/TLS/UNDEF/ABS/COMMON, dual-table identity, defined sections, writable PT_LOAD, absent versus null-only tables, malformed/overflowing ranges, invalid names/links/sections, unsupported compressed/extended tables and duplicate table kinds.

GOWORK=off go test ./x/elfinspect
GOWORK=off go vet ./x/elfinspect

Run from the nvidia module. No dependencies were added. This is file metadata/source evidence only; native qualification and performance are not claimed.

Documentation

Overview

Package elfinspect reads ELF headers, sections, segments, and symbol tables. It preserves file metadata without loading code or interpreting symbol names as an admission policy. In particular, GNU-unique bindings remain raw value 10, and TLS, undefined, absolute, and common symbols remain distinct.

Read reports absent symbol tables explicitly. Neither a present table nor any section or PT_LOAD mapping proves runtime storage or loaded addresses. ReadFunction copies the file bytes of one uniquely named STT_FUNC symbol without applying relocations.

For CUDA images, OpenCubin opens a cubin whose legacy header carries the toolkit version in e_version (CUDA 12.9 writes 129), which debug/elf.NewFile rejects, and Arch reads the SM its header records. NVInfoRecords splits a .nv.info section into its EIATTR records, and Kernels decodes each entry point's required and maximum CTA shape, register ceiling and count, stack frame, static shared memory and parameter layout. Tests check both against cuobjdump -elf for cubins in testdata/cuobjdump.

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 (
	// CapmercPrefix is the ELF section name prefix for CUDA capmerc sections.
	CapmercPrefix = ".nv.capmerc."

	// CapmercTextPrefix is the ELF section name prefix for per-kernel capmerc
	// text mirror sections.
	CapmercTextPrefix = ".nv.capmerc.text."

	// MinDriverCapmercCompatBug is the minimum CUDA driver version (13.5 = 13050)
	// whose Mercury/CapMerc finalizer rejects pre-13.5 cubins with nulled
	// .nv.capmerc.* sections ("Finalization failed 'unsupported elf type'") and
	// poisons the immediately following module load with CUDA_ERROR_UNKNOWN.
	MinDriverCapmercCompatBug = 13050
)
View Source
const (
	FormatNVal = 0x01
	FormatBVal = 0x02
	FormatHVal = 0x03
	FormatSVal = 0x04
)

EIATTR record formats. Only FormatSVal records carry a 16-bit size and a payload of that many bytes. FormatNVal, FormatBVal and FormatHVal records are four bytes in all: the format, the attribute and a 16-bit value.

View Source
const (
	AttrMaxThreads     = 0x05 // EIATTR_MAX_THREADS: maximum CTA shape, three uint32
	AttrParamCBank     = 0x0a // EIATTR_PARAM_CBANK: where the parameters sit in constant bank 0
	AttrReqNTID        = 0x10 // EIATTR_REQNTID: required CTA shape, three uint32
	AttrFrameSize      = 0x11 // EIATTR_FRAME_SIZE: per-thread stack frame bytes, in .nv.info
	AttrKParamInfo     = 0x17 // EIATTR_KPARAM_INFO: one kernel parameter
	AttrCBankParamSize = 0x19 // EIATTR_CBANK_PARAM_SIZE: parameter bytes
	AttrMaxRegCount    = 0x1b // EIATTR_MAXREG_COUNT: register ceiling
	AttrRegCount       = 0x2f // EIATTR_REGCOUNT: registers per thread, in .nv.info
)

EIATTR attributes that Kernels decodes.

View Source
const (
	// FatbinMagic is the 32-bit little-endian magic number at the start of an
	// NVIDIA fatbinary container.
	FatbinMagic uint32 = 0xBA55ED50
)

Variables

View Source
var (
	// ErrNotFatbin is wrapped by [*FatbinError] when input lacks [FatbinMagic].
	ErrNotFatbin = errors.New("elfinspect: not a fatbin container")

	// ErrCompressedFatbinEntry is wrapped by [*FatbinError] when a cubin entry
	// is compressed (LZ4 or Zstd) and cannot be unwrapped without decompression.
	ErrCompressedFatbinEntry = errors.New("elfinspect: compressed fatbin entry")
)
View Source
var ErrCapmercStripUnsupported = errors.New("elfinspect: cannot strip .nv.capmerc from pre-13.5 cubin on CUDA >= 13.5 driver")

ErrCapmercStripUnsupported is returned when refusing to strip .nv.capmerc.* sections from a pre-13.5 cubin targeting a CUDA >= 13.5 driver (version >= 13050).

View Source
var ErrNVInfo = errors.New("malformed .nv.info")

ErrNVInfo reports a malformed .nv.info section.

View Source
var ErrStaleCapmerc = errors.New("elfinspect: stale .nv.capmerc section")

ErrStaleCapmerc is wrapped by *CapmercError when a cubin contains .nv.capmerc.* sections that would become stale after patching .text.<kernel>.

Functions

func ActiveDriverVersion

func ActiveDriverVersion() int

ActiveDriverVersion returns the active CUDA driver version reported by the registered callback, or 0 if no driver is loaded.

func Arch

func Arch(r io.ReaderAt) (int, error)

Arch returns the SM number the CUDA ELF header in r records, such as 90 for sm_90a or 121 for sm_121a. From ELF ABI version 8 (CUDA 13) the number is bits 8-15 of e_flags, and before it bits 0-7. The feature suffix is not decoded. Arch returns an error for an image that is not a little-endian CUDA ELF or records no SM.

func CheckStripCapmercToolkit

func CheckStripCapmercToolkit(major, minor int, hasToolkit bool, driverVersion int) error

CheckStripCapmercToolkit reports an error wrapping ErrCapmercStripUnsupported when driverVersion >= 13050 and a cubin built with a pre-13.5 toolkit has active .nv.capmerc.* sections to strip.

func CubinToolkitVersion

func CubinToolkitVersion(r io.ReaderAt) (major, minor int, ok bool)

CubinToolkitVersion returns the CUDA toolkit (major, minor) recorded in cubin r, checking .note.nv.tkinfo, .note.nv.cuinfo, and legacy ABI v7 e_version.

func IsFatbin

func IsFatbin(data []byte) bool

IsFatbin reports whether data begins with FatbinMagic.

func OpenCubin

func OpenCubin(r io.ReaderAt) (*elf.File, error)

OpenCubin opens the CUDA ELF image in r, as elf.NewFile does.

Legacy NVIDIA ELF (OS ABI 0x33, ABI version 7) stores the toolkit version in the header's e_version: nvcc 12.6 writes 126 and 12.9 writes 129. elf.NewFile accepts only EV_CURRENT there and rejects every such image with "mismatched ELF version". OpenCubin reads that field as EV_CURRENT while parsing; it never writes to r, so a checksum of the image (such as cuptiGetCubinCrc) still sees the original bytes. Any other image, including a non-CUDA one, is opened unchanged.

func ParseCuinfoVersion

func ParseCuinfoVersion(data []byte) (major, minor int, ok bool)

ParseCuinfoVersion extracts the CUDA toolkit major.minor from a .note.nv.cuinfo ELF note payload (desc uint16 at offset 4 encodes major*10+minor, e.g. 130 -> 13.0).

func ParseTkinfoVersion

func ParseTkinfoVersion(data []byte) (major, minor int, ok bool)

ParseTkinfoVersion extracts the CUDA toolkit major.minor from a .note.nv.tkinfo section payload (e.g. "Cuda compilation tools, release 13.0, V13.0.88").

func PatchFatbinCubins

func PatchFatbinCubins(data []byte, mode CapmercMode, patch func(entry FatbinEntry, cubin []byte) ([]byte, error)) ([]byte, error)

PatchFatbinCubins unwraps a fatbinary (or accepts a raw cubin directly), applies mode to any .nv.capmerc.* sections, invokes patch on each cubin, and re-wraps patched cubins back into a fatbinary if data was a fatbinary.

func RejectCapmerc

func RejectCapmerc(r io.ReaderAt, kernels ...string) error

RejectCapmerc returns *CapmercError if r contains any active .nv.capmerc.* section. When kernels is non-empty, only .nv.capmerc.text.<kernel> sections matching one of kernels are rejected.

func RewrapFatbin

func RewrapFatbin(orig []byte, replace func(FatbinEntry) ([]byte, error)) ([]byte, error)

RewrapFatbin rebuilds orig, calling replace for each entry. If replace is nil or returns nil, nil for an entry, that entry is preserved verbatim. Otherwise the returned bytes replace the entry payload, compression flags are cleared, and entry/container sizes are updated.

func SetDriverVersionFunc

func SetDriverVersionFunc(fn func() int)

SetDriverVersionFunc registers a callback returning the active CUDA driver version (as reported by cuDriverGetVersion, e.g. 13050 for CUDA 13.5, or 0 when no driver is loaded). Package cuda registers this at init time so host packages stay free of a driver import while still guarding live processes.

func WrapCubinFatbin

func WrapCubinFatbin(cubin []byte, archSpecific bool) ([]byte, error)

WrapCubinFatbin wraps a single ELF cubin image into a valid fatbinary container.

Types

type CapmercError

type CapmercError struct {
	Sections []CapmercSection
}

CapmercError reports .nv.capmerc.* sections that cannot be left stale when patching a cubin.

func (*CapmercError) Error

func (e *CapmercError) Error() string

func (*CapmercError) Unwrap

func (e *CapmercError) Unwrap() error

type CapmercMode

type CapmercMode uint8

CapmercMode controls how HandleCapmerc treats .nv.capmerc.* sections.

const (
	// CapmercReject fails with [*CapmercError] if matching .nv.capmerc.* sections exist.
	CapmercReject CapmercMode = iota
	// CapmercStrip neutralizes matching .nv.capmerc.* sections to SHT_NULL and zeros their bytes.
	CapmercStrip
	// CapmercKeep leaves matching .nv.capmerc.* sections untouched.
	CapmercKeep
)

type CapmercSection

type CapmercSection struct {
	Index  elf.SectionIndex
	Name   string
	Kernel string // kernel name after ".nv.capmerc.text.", if any
	Type   elf.SectionType
	Flags  elf.SectionFlag
	Offset uint64
	Size   uint64
}

CapmercSection describes one .nv.capmerc.* section in a cubin.

func DetectCapmerc

func DetectCapmerc(r io.ReaderAt) ([]CapmercSection, error)

DetectCapmerc returns all active .nv.capmerc.* sections in the cubin r. Stripped SHT_NULL sections are ignored.

func HandleCapmerc

func HandleCapmerc(cubin []byte, mode CapmercMode, kernels ...string) ([]byte, []CapmercSection, error)

HandleCapmerc applies mode to matching .nv.capmerc.* sections in cubin. It never mutates the input slice.

func StripCapmerc

func StripCapmerc(cubin []byte, kernels ...string) ([]byte, []CapmercSection, error)

StripCapmerc returns a copy of cubin with matching .nv.capmerc.* sections neutralized: their file bytes are zeroed and their section header entries are cleared to SHT_NULL, preserving all other section indices and offsets. When kernels is non-empty, only .nv.capmerc.text.<kernel> sections matching one of kernels are stripped.

When a CUDA >= 13.5 driver (version >= 13050) is active in this process, StripCapmerc refuses to strip pre-13.5 cubins (see StripCapmercForDriver).

func StripCapmercForDriver

func StripCapmercForDriver(cubin []byte, driverVersion int, kernels ...string) ([]byte, []CapmercSection, error)

StripCapmercForDriver behaves like StripCapmerc, validating compatibility against driverVersion (as reported by cuDriverGetVersion, or 0 to skip the driver check). When driverVersion >= 13050 and cubin was built with a pre-13.5 toolkit (such as CUDA 13.0), StripCapmercForDriver returns an error wrapping ErrCapmercStripUnsupported instead of emitting a cubin whose finalization failure poisons subsequent module loads.

type FatbinEntry

type FatbinEntry struct {
	ContainerIndex   int
	EntryIndex       int
	Offset           int // byte offset of the entry header in the fatbin
	Kind             FatbinKind
	Arch             int  // numerical SM, e.g. 121
	ArchSpecific     bool // true for sm_XYa
	Major, Minor     int
	Flags            uint64
	Compressed       bool
	UncompressedSize uint64
	Header           []byte
	Data             []byte
}

FatbinEntry describes one device image inside a fatbinary container. Header and Data alias the slice passed to UnwrapFatbin.

func UnwrapCubins

func UnwrapCubins(data []byte) ([]FatbinEntry, error)

UnwrapCubins returns all uncompressed FatbinKindCUBIN entries in data. It returns *FatbinError wrapping ErrCompressedFatbinEntry if any cubin entry is compressed.

func UnwrapFatbin

func UnwrapFatbin(data []byte) ([]FatbinEntry, error)

UnwrapFatbin parses one or more concatenated fatbinary containers in data. It returns *FatbinError wrapping ErrNotFatbin if data does not start with FatbinMagic.

type FatbinError

type FatbinError struct {
	Offset int
	Kind   FatbinKind
	Arch   int
	Err    error
}

FatbinError describes a fatbinary container or entry error.

func (*FatbinError) Error

func (e *FatbinError) Error() string

func (*FatbinError) Unwrap

func (e *FatbinError) Unwrap() error

type FatbinKind

type FatbinKind uint16

FatbinKind identifies the payload kind of a fatbinary entry.

const (
	FatbinKindPTX   FatbinKind = 1
	FatbinKindCUBIN FatbinKind = 2
)

func (FatbinKind) String

func (k FatbinKind) String() string

type Function

type Function struct {
	TableSection elf.SectionIndex
	Symbol       Symbol
	FileOffset   uint64
	Data         []byte
}

Function is a literal file range selected by a unique STT_FUNC entry. Data is an independent copy. Symbol preserves the original entry and section; TableSection identifies its symbol table. No relocation is applied.

func ReadFunction

func ReadFunction(data []byte, table elf.SectionType, name string) (*Function, error)

ReadFunction reads the unique function named name in table (SHT_SYMTAB or SHT_DYNSYM). It reuses Read's metadata validation, accepts ET_REL, ET_EXEC and ET_DYN, and requires a nonempty range in an uncompressed executable PROGBITS section fully backed by data. ET_REL values are section offsets; ET_EXEC and ET_DYN values are reduced by the section address. Architecture-specific symbol tags, function descriptors, aliases, relocations and vendor metadata are not interpreted. This is a literal file-byte selection, not proof of callable code, ABI equivalence, loaded instructions or runtime behavior. Call Read separately to disclose relocation and other section metadata. The caller must not mutate data concurrently with this call.

Example
f, err := ReadFunction(functionFixture(), elf.SHT_SYMTAB, "cache")
if err != nil {
	fmt.Println(err)
	return
}
fmt.Printf("symbol=%s file-offset=%d bytes=%q\n", f.Symbol.Name, f.FileOffset, f.Data)
Output:
symbol=cache file-offset=256 bytes="abcdefgh"

type Image

type Image struct {
	Header     elf.FileHeader
	Sections   []Section
	Segments   []elf.ProgHeader
	TableState TableState
	Tables     []SymbolTable
}

Image contains file metadata only. Its slices preserve file order.

func Read

func Read(r io.ReaderAt) (*Image, error)

Read decodes metadata from r without taking ownership of it. Missing symbol tables return TablesAbsent, not an empty successful symbol census. Malformed tables, extended symbol section indices, compressed tables, and overflowing ranges return errors. Each symbol/string table is limited to 8 MiB, with at most 65536 symbols and 8 MiB of aggregate decoded names per table.

Offset/size fields are file metadata: Read does not establish that symbol storage belongs to a PT_LOAD segment or that file storage is mapped at run time.

Example
image, err := Read(bytes.NewReader(fixture()))
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(image.TableState, len(image.Tables), len(image.Segments))
symbol := image.Tables[0].Symbols[0]
fmt.Printf("%s binding=%d section=%d\n", symbol.Name, symbol.Binding, symbol.Section.Index)
Output:
present 2 1
cache binding=10 section=1

type Kernel

type Kernel struct {
	Name string

	// ReqNTID is the CTA shape the kernel was compiled for
	// (.reqntid, or fixed by a compiler such as tileiras); a launch
	// with any other block shape fails. It is all zero when the
	// cubin requires none.
	ReqNTID [3]int

	// MaxNTID is the largest CTA shape (.maxntid); all zero when absent.
	MaxNTID [3]int

	MaxReg      int // register ceiling (EIATTR_MAXREG_COUNT); 0 when absent
	Registers   int // registers per thread (EIATTR_REGCOUNT); 0 when absent
	FrameBytes  int // per-thread stack frame (EIATTR_FRAME_SIZE); -1 when absent
	SharedBytes int // static shared memory: the size of .nv.shared.<name>
	ParamBytes  int // parameter bytes (EIATTR_CBANK_PARAM_SIZE); 0 when absent

	// ParamBank is the offset of the parameters in constant bank 0
	// (EIATTR_PARAM_CBANK), so parameter Offset o is read as
	// c[0x0][ParamBank+o]. It is 0x160 through Hopper and 0x380 on
	// sm_100 and later, and 0 when the attribute is absent.
	ParamBank int

	Params []Param // parameters (EIATTR_KPARAM_INFO), in ordinal order
}

A Kernel is what a cubin records about one entry point.

func Kernels

func Kernels(f *elf.File) ([]Kernel, error)

Kernels reads the entry points of a cubin opened with OpenCubin: one per .text.<name> section, with the facts of its .nv.info.<name> section and of the module-wide .nv.info. A malformed .nv.info section is an error naming it; an attribute Kernels does not decode is skipped.

Example
sec, _ := hex.DecodeString(tileirasNVInfo[1].hex)
cubin := testCubin(129, // CUDA 12.9 legacy header; debug/elf alone rejects it
	testSection{".text.mm_decode_2048_unrolled", make([]byte, 64)},
	testSection{".nv.info.mm_decode_2048_unrolled", sec})
f, err := OpenCubin(bytes.NewReader(cubin))
if err != nil {
	fmt.Println(err)
	return
}
kernels, err := Kernels(f)
if err != nil {
	fmt.Println(err)
	return
}
k := kernels[0]
fmt.Println(k.Name, k.ReqNTID, k.MaxReg, k.ParamBytes, len(k.Params))
Output:
mm_decode_2048_unrolled [128 1 1] 255 24 3

type NVInfoRecord

type NVInfoRecord struct {
	Format, Attr byte
	Value        []byte
}

An NVInfoRecord is one EIATTR record of a .nv.info section. For a FormatSVal record Value is its payload; for the others it is the 16-bit value, little-endian.

func NVInfoRecords

func NVInfoRecords(data []byte) ([]NVInfoRecord, error)

NVInfoRecords splits a .nv.info section into its records. At a record of unknown format, or one that runs past the section, it returns the records before it and an error wrapping ErrNVInfo.

type Param

type Param struct {
	Ordinal, Offset, Size int
}

A Param is one kernel parameter's place in the parameter buffer.

type Section

type Section struct {
	Index elf.SectionIndex
	elf.SectionHeader
}

Section preserves the section index, including section zero, and raw header.

type Symbol

type Symbol struct {
	Index        uint64
	Name         string
	Info, Other  byte
	Binding      elf.SymBind
	Type         elf.SymType
	SectionIndex elf.SectionIndex
	Section      *Section
	Value, Size  uint64
}

Symbol preserves an entry's raw fields and source-table entry index. Section is non-nil only for an ordinary defined section. Reserved indices, including UNDEF, ABS, COMMON, and processor-specific indices, remain in SectionIndex. Binding 10 is GNU-unique; Type STT_TLS remains TLS, not an ordinary object.

type SymbolTable

type SymbolTable struct {
	Section elf.SectionIndex
	Type    elf.SectionType
	Name    string
	Symbols []Symbol
}

SymbolTable identifies the source section of its entries. The mandatory null symbol is validated but omitted from Symbols, as in debug/elf.

type TableState

type TableState string

TableState distinguishes absent symbol tables from decoded tables.

const (
	// TablesAbsent means neither SHT_SYMTAB nor SHT_DYNSYM exists.
	TablesAbsent TableState = "absent"
	// TablesPresent means at least one symbol table was decoded successfully.
	TablesPresent TableState = "present"
)

Jump to

Keyboard shortcuts

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