C Fundamentals

Pointers and Strings

Pointers and strings - the MOST CRITICAL C topic for BPF programs. Kernel memory access, packet parsing, and buffer reading are all done through pointers.

1.8 Pointers

Prerequisite: Complete arrays first.

  • Pointer declaration and dereferencing (*ptr)
  • Pointer arithmetic (what ptr + 1 means)
  • void* usage
  • Double pointers (**ptr)

Critical pattern in BPF - bounds checking:

// In XDP, before accessing packet data:
if (data + sizeof(struct ethhdr) > data_end)
    return XDP_DROP;

Two-Stage Pointer Dereference

A commonly encountered pattern in BPF - accessing each element in a pointer array:

// 1. Read the pointer from the array
bpf_probe_read_user(&arg_ptr, sizeof(arg_ptr), &argv[i]);
// 2. Read the string from the pointer
bpf_probe_read_user_str(arg_buf, sizeof(arg_buf), arg_ptr);

BPF Memory Read Helpers

Direct pointer dereference is forbidden in BPF. You must use helper functions:

  • bpf_probe_read_kernel(dst, size, src) - read from kernel memory
  • bpf_probe_read_kernel_str(dst, size, src) - read a string from kernel memory
  • bpf_probe_read_user(dst, size, src) - read from user space memory
  • bpf_probe_read_user_str(dst, size, src) - read a string from user space memory

Related eBPFHub exercises:

  • “Reading event data” - safe reading from kernel memory with bpf_probe_read_kernel_str
  • “Tracing a system call” - reading from user space memory with bpf_probe_read_user_str
  • “Reading syscall arrays” - two-stage pointer dereference practice
  • “Reading syscall buffers” - storing a buffer pointer in a map and dereferencing it at exit with (void *)*buf_ptr

See in xdp-tutorial: packet01-parsing/xdp_prog_kern.c:64-86 - data, data_end, bounds check.

Exercise:

  1. Create an int array and traverse it with a pointer
  2. Understand the difference between ptr + 1 and ptr + sizeof(*ptr) (NOT THE SAME!)

1.9 Strings

Prerequisite: Complete pointers first (string = char pointer).

  • char array vs char pointer
  • NULL terminator (\0)
  • String functions: strlen, strcpy, strcmp

Limited in BPF:

  • Read with bpf_probe_read_str or bpf_probe_read_user_str
  • Fixed size required (verifier)
  • No standard string functions

BPF string helpers:

  • bpf_strncmp(s1, s1_sz, s2) - compare a variable string with a constant
  • bpf_strstr(haystack, needle) - substring search (kernel 6.x+)
  • bpf_strchr(str, c) - character search (kernel 6.x+)

Related eBPFHub exercises:

  • “Process context” - filtering by process name with bpf_strncmp()
  • “Reading TCP packets” - searching for “Authorization: Bearer ” in HTTP headers with bpf_strstr(), extracting the token

Exercise: Write your own strlen function (traverse with a pointer, count until \0).