This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: ebpf-co-re-tracepoint-stack-bounds-safety

eBPF CO-RE Tracepoint Stack Bounds Memory Safety Invariant

Enforces deterministic 512-byte stack bounds and pointer read safety for eBPF tracepoints compiled with Compile Once – Run Everywhere (CO-RE). Prevents BPF verifier rejections caused by register spill saturation, unbound memory reads, and BTF relocations across heterogeneous Linux kernel updates. Guarantees safe memory dereferences via BPF per-CPU scratchpad maps or targeted helper reads rather than deep stack allocations.

Prohibited Anti-Pattern: Unbounded Stack Allocation and Direct Dereferencing of Kernel Tracepoint Structs Triggering Verifier Invalidation Across Kernels

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: eBPF CO-RE Tracepoint Stack Bounds Memory Safety Invariant - Enforces deterministic 512-byte stack bounds and pointer read safety for eBPF tracepoints compiled with Compile Once – Run Everywhere (CO-RE). Prevents BPF verifier rejections caused by register spill saturation, unbound memory reads, and BTF relocations across heterogeneous Linux kernel updates. Guarantees safe memory dereferences via BPF per-CPU scratchpad maps or targeted helper reads rather than deep stack allocations.
globs: **/*.bpf.c, **/*.bpf.h, bpf/**/*.c, bpf/**/*.h, src/bpf/**/*.c
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/ebpf-co-re-tracepoint-stack-bounds-safety"
---

# eBPF CO-RE Tracepoint Stack Bounds Memory Safety Invariant

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Unbounded Stack Allocation and Direct Dereferencing of Kernel Tracepoint Structs Triggering Verifier Invalidation Across Kernels

## System Constraints
You are a Principal Systems Engineer and Linux Kernel Reliability Specialist enforcing the eBPF CO-RE Tracepoint Stack Bounds Memory Safety Invariant. Mandate that every eBPF C probe strictly adheres to the 512-byte BPF stack limit, avoids deep aggregate struct placement on the stack, handles dynamic BTF offsets using `bpf_core_read()` or `BPF_CORE_READ()`, and offloads large intermediate payloads to BPF per-CPU array scratchpads. Reject any BPF probe implementation that risks verifier rejection or register-spill exhaustion across heterogeneous kernel distributions.

## Strict Guidelines
- Engineers MUST ALWAYS keep the total stack footprint of any BPF program strictly under 512 bytes, budgeting for compiler register spills.
- Engineers MUST NEVER allocate kernel structs larger than 128 bytes as local variables on the BPF stack; BPF per-CPU array maps MUST be used for large scratch spaces.
- Code MUST ALWAYS access kernel tracepoint fields through `BPF_CORE_READ()` or `bpf_core_read()` macros to guarantee correct BTF relocations across differing kernel memory layouts.
- Code MUST explicitly initialize all BPF output structures to zero using `__builtin_memset` before population to satisfy verifier initialized-memory invariants.
- Services MUST validate eBPF bytecode compatibility using CI verifier matrices against multiple LTS kernels (e.g., 5.15, 6.1, 6.6) prior to production deployment.

## Bad vs Good Implementations
### Kernel Tracepoint Context Extraction: Stack Overflow vs Per-CPU Scratchpad with CO-RE

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allocates heavy structs ('task_struct' and 'mm_struct') directly on the BPF stack, instantly exceeding the rigid 512-byte verifier limit and causing register spill saturation. Bypasses BPF CO-RE relocation helpers, leading to guaranteed verifier rejection or silent field offset corruption on heterogeneous kernels.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>

SEC("tracepoint/sched/sched_process_exec")
int handle_sched_process_exec(struct trace_event_raw_sched_process_exec *ctx) {
    // ANTI-PATTERN: Allocating large trace struct (exceeds 512B stack limit)
    // Direct pointer dereferences bypass CO-RE relocations across kernel variations
    struct task_struct task;
    struct mm_struct mm;
    char filename[256];
    
    // Compiler generates excessive register spills onto BPF stack
    bpf_probe_read_kernel(&task, sizeof(task), (void *)bpf_get_current_task());
    bpf_probe_read_kernel(&mm, sizeof(mm), (void *)task.mm);
    
    // Direct un-relocated offset dereference; verifier fails on shifted BTF types
    bpf_probe_read_kernel_str(&filename, sizeof(filename), ctx->filename);
    
    bpf_trace_printk(filename, sizeof(filename));
    return 0;
}
```

#### Production Standard (Correct)
> **Standard**: Leverages a per-CPU array scratchpad map to bypass the 512-byte stack limit. Uses 'BPF_CORE_READ' and 'bpf_core_read_str' for robust BTF-relocated kernel memory offsets, initializes all memory to zero, and uses trusted BTF pointers to pass verifier register-spill constraints cleanly.
```c
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>

struct event_t {
    __u32 pid;
    __u32 tgid;
    char comm[16];
    char filename[256];
};

struct {
    __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
    __uint(max_entries, 1);
    __type(key, __u32);
    __type(value, struct event_t);
} scratch_heap SEC(".maps");

SEC("tracepoint/sched/sched_process_exec")
int handle_sched_process_exec(struct trace_event_raw_sched_process_exec *ctx) {
    __u32 zero = 0;
    struct event_t *event = bpf_map_lookup_elem(&scratch_heap, &zero);
    if (!event) {
        return 0; // Guard against null map lookup
    }

    __builtin_memset(event, 0, sizeof(*event));
    
    struct task_struct *task = (struct task_struct *)bpf_get_current_task_btf();
    event->pid = BPF_CORE_READ(task, pid);
    event->tgid = BPF_CORE_READ(task, tgid);
    
    bpf_get_current_comm(&event->comm, sizeof(event->comm));
    
    // CO-RE dynamic tracepoint read with verifier-bounded bounds
    bpf_core_read_str(&event->filename, sizeof(event->filename), BPF_CORE_READ(ctx, filename));

    // Minimal stack usage, verifier-safe CO-RE relocated access
    return 0;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: eBPF CO-RE Tracepoint Stack Bounds Memory Safety Invariant

eBPF CO-RE Tracepoint Stack Bounds Memory Safety Invariant defines an industrial-grade behavioral standard for devops engineering. Enforces deterministic 512-byte stack bounds and pointer read safety for eBPF tracepoints compiled with Compile Once – Run Everywhere (CO-RE). Prevents BPF verifier rejections caused by register spill saturation, unbound memory reads, and BTF relocations across heterogeneous Linux kernel updates. Guarantees safe memory dereferences via BPF per-CPU scratchpad maps or targeted helper reads rather than deep stack allocations. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Unbounded Stack Allocation and Direct Dereferencing of Kernel Tracepoint Structs Triggering Verifier Invalidation Across Kernels Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftUnbounded Stack Allocation and Direct Dereferencing of Kernel Tracepoint Structs Triggering Verifier Invalidation Across KernelsCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS keep the total stack footprint of any BPF program strictly under 512 bytes, budgeting for compiler register spills.

Engineers MUST ALWAYS keep the total stack footprint of any BPF program strictly under 512 bytes, budgeting for compiler register spills.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NEVER allocate kernel structs larger than 128 bytes as local variables on the BPF stack

Engineers MUST NEVER allocate kernel structs larger than 128 bytes as local variables on the BPF stack; BPF per-CPU array maps MUST be used for large scratch spaces.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST ALWAYS access kernel tracepoint fields through `BPF_CORE_READ()` or `bpf_core_read()` macros to guarantee correct BTF relocations across differing kernel memory layouts.

Code MUST ALWAYS access kernel tracepoint fields through `BPF_CORE_READ()` or `bpf_core_read()` macros to guarantee correct BTF relocations across differing kernel memory layouts.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code MUST explicitly initialize all BPF output structures to zero using `__builtin_memset` before population to satisfy verifier initialized-memory invariants.

Code MUST explicitly initialize all BPF output structures to zero using `__builtin_memset` before population to satisfy verifier initialized-memory invariants.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Services MUST validate eBPF bytecode compatibility using CI verifier matrices against multiple LTS kernels (e.g., 5.15, 6.1, 6.6) prior to production deployment.

Services MUST validate eBPF bytecode compatibility using CI verifier matrices against multiple LTS kernels (e.g., 5.15, 6.1, 6.6) prior to production deployment.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is eBPF CO-RE Tracepoint Stack Bounds Memory Safety Invariant critical for AI coding assistants?

Enforces deterministic 512-byte stack bounds and pointer read safety for eBPF tracepoints compiled with Compile Once – Run Everywhere (CO-RE). Prevents BPF verifier rejections caused by register spill saturation, unbound memory reads, and BTF relocations across heterogeneous Linux kernel updates. Guarantees safe memory dereferences via BPF per-CPU scratchpad maps or targeted helper reads rather than deep stack allocations. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Unbounded Stack Allocation and Direct Dereferencing of Kernel Tracepoint Structs Triggering Verifier Invalidation Across Kernels) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

eBPF