tools/testing/selftests/bpf/prog_tests/xdp_attach.c

Source file repositories/reference/linux-study-clean/tools/testing/selftests/bpf/prog_tests/xdp_attach.c

File Facts

System
Linux kernel
Corpus path
tools/testing/selftests/bpf/prog_tests/xdp_attach.c
Extension
.c
Size
4444 bytes
Lines
160
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

struct xdp_errmsg {
	char msg[ERRMSG_LEN];
};

static void on_xdp_errmsg(void *ctx, int cpu, void *data, __u32 size)
{
	struct xdp_errmsg *ctx_errmg = ctx, *tp_errmsg = data;

	memcpy(&ctx_errmg->msg, &tp_errmsg->msg, ERRMSG_LEN);
}

static const char tgt_errmsg[] = "Invalid XDP flags for BPF link attachment";

static void test_xdp_attach_fail(const char *file)
{
	struct test_xdp_attach_fail *skel = NULL;
	struct xdp_errmsg errmsg = {};
	struct perf_buffer *pb = NULL;
	struct bpf_object *obj = NULL;
	int err, fd_xdp;

	LIBBPF_OPTS(bpf_link_create_opts, opts);

	skel = test_xdp_attach_fail__open_and_load();
	if (!ASSERT_OK_PTR(skel, "test_xdp_attach_fail__open_and_load"))
		goto out_close;

	err = test_xdp_attach_fail__attach(skel);
	if (!ASSERT_EQ(err, 0, "test_xdp_attach_fail__attach"))
		goto out_close;

	/* set up perf buffer */
	pb = perf_buffer__new(bpf_map__fd(skel->maps.xdp_errmsg_pb), 1,
			      on_xdp_errmsg, NULL, &errmsg, NULL);
	if (!ASSERT_OK_PTR(pb, "perf_buffer__new"))
		goto out_close;

	err = bpf_prog_test_load(file, BPF_PROG_TYPE_XDP, &obj, &fd_xdp);
	if (!ASSERT_EQ(err, 0, "bpf_prog_test_load"))
		goto out_close;

	opts.flags = 0xFF; // invalid flags to fail to attach XDP prog
	err = bpf_link_create(fd_xdp, IFINDEX_LO, BPF_XDP, &opts);
	if (!ASSERT_EQ(err, -EINVAL, "bpf_link_create"))
		goto out_close;

	/* read perf buffer */
	err = perf_buffer__poll(pb, 100);
	if (!ASSERT_GT(err, -1, "perf_buffer__poll"))
		goto out_close;

	ASSERT_STRNEQ((const char *) errmsg.msg, tgt_errmsg,
		      42 /* strlen(tgt_errmsg) */, "check error message");

out_close:
	perf_buffer__free(pb);
	bpf_object__close(obj);
	test_xdp_attach_fail__destroy(skel);
}

void serial_test_xdp_attach(void)
{
	if (test__start_subtest("xdp_attach"))
		test_xdp_attach("./test_xdp.bpf.o");
	if (test__start_subtest("xdp_attach_dynptr"))
		test_xdp_attach("./test_xdp_dynptr.bpf.o");
	if (test__start_subtest("xdp_attach_failed"))
		test_xdp_attach_fail("./xdp_dummy.bpf.o");
}

Annotation

Implementation Notes