C Fundamentals

Control Flow and Loops

Control flow and loops - loop restrictions in BPF are especially important.

1.4 Control Flow

  • if / else if / else
  • switch / case
  • Ternary operator (?:)

eBPFHub: In all exercises you will use if/else for filtering - PID checks, syscall number matching, branching after NULL checks.

See in xdp-tutorial: packet01-parsing/xdp_prog_kern.c - ETH_P_IP vs ETH_P_IPV6 check.


1.5 Loops

  • for, while, do-while
  • break, continue
  • Nested loops

BPF Restriction: Unbounded loops are forbidden! The verifier rejects them. Use bounded loops or #pragma unroll.

// DOES NOT WORK in BPF:
while (1) { ... }

// CORRECT: Fixed-bound loop
#pragma unroll
for (int i = 0; i < 10; i++) {
    if (condition) break;
}

eBPFHub: In the “DNS packet parsing” exercise, you will practice bounded loops - parsing DNS labels with #pragma unroll:

#pragma unroll
for (int i = 0; i < 10; i++) {  // Max 10 label
    u8 len = buf[pos++];
    if (len == 0) break;
    #pragma unroll
    for (int j = 0; j < 63; j++) {
        if (j >= len) break;
        domain[out++] = buf[pos++];
    }
}

See in xdp-tutorial: common/parsing_helpers.h:104-118 - VLAN parsing (with #pragma unroll).

Reading: