tools/testing/selftests/bpf/progs/iters_state_safety.c

Source file repositories/reference/linux-study-clean/tools/testing/selftests/bpf/progs/iters_state_safety.c

File Facts

System
Linux kernel
Corpus path
tools/testing/selftests/bpf/progs/iters_state_safety.c
Extension
.c
Size
8604 bytes
Lines
427
Domain
Support Tooling And Documentation
Bucket
tools
Inferred role
Support Tooling And Documentation: implementation source
Status
source implementation candidate

Why This File Exists

Repository support layer: documentation, build tooling, samples, user-space helper tools, generated initramfs support, licenses, and validation utilities.

Dependency Surface

Detected Declarations

Annotated Snippet

// SPDX-License-Identifier: GPL-2.0
/* Copyright (c) 2022 Facebook */

#include <errno.h>
#include <string.h>
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include "bpf_misc.h"

char _license[] SEC("license") = "GPL";

#define ITER_HELPERS						\
	  __imm(bpf_iter_num_new),				\
	  __imm(bpf_iter_num_next),				\
	  __imm(bpf_iter_num_destroy)

SEC("?raw_tp")
__success
int force_clang_to_emit_btf_for_externs(void *ctx)
{
	/* we need this as a workaround to enforce compiler emitting BTF
	 * information for bpf_iter_num_{new,next,destroy}() kfuncs,
	 * as, apparently, it doesn't emit it for symbols only referenced from
	 * assembly (or cleanup attribute, for that matter, as well)
	 */
	bpf_repeat(0);

	return 0;
}

SEC("?raw_tp")
__success __log_level(2)
__msg("fp-8=iter_num(id=1,state=active,depth=0)")
int create_and_destroy(void *ctx)
{
	struct bpf_iter_num iter;

	asm volatile (
		/* create iterator */
		"r1 = %[iter];"
		"r2 = 0;"
		"r3 = 1000;"
		"call %[bpf_iter_num_new];"
		/* destroy iterator */
		"r1 = %[iter];"
		"call %[bpf_iter_num_destroy];"
		:
		: __imm_ptr(iter), ITER_HELPERS
		: __clobber_common
	);

	return 0;
}

SEC("?raw_tp")
__failure __msg("Unreleased reference id=1")
int create_and_forget_to_destroy_fail(void *ctx)
{
	struct bpf_iter_num iter;

	asm volatile (
		/* create iterator */
		"r1 = %[iter];"
		"r2 = 0;"
		"r3 = 1000;"
		"call %[bpf_iter_num_new];"
		:
		: __imm_ptr(iter), ITER_HELPERS
		: __clobber_common
	);

	return 0;
}

SEC("?raw_tp")
__failure __msg("expected an initialized iter_num as R1")
int destroy_without_creating_fail(void *ctx)
{
	/* init with zeros to stop verifier complaining about uninit stack */
	struct bpf_iter_num iter;

	asm volatile (
		"r1 = %[iter];"
		"call %[bpf_iter_num_destroy];"
		:
		: __imm_ptr(iter), ITER_HELPERS
		: __clobber_common
	);

	return 0;

Annotation

Implementation Notes