Commit 576d47bb authored by Daniel Xu's avatar Daniel Xu Committed by Alexei Starovoitov
Browse files

bpf: selftests: Add bpf_task_pt_regs() selftest



This test retrieves the uprobe's pt_regs in two different ways and
compares the contents in an arch-agnostic way.

Signed-off-by: default avatarDaniel Xu <dxu@dxuuu.xyz>
Signed-off-by: default avatarAlexei Starovoitov <ast@kernel.org>
Link: https://lore.kernel.org/bpf/5581eb8800f6625ec8813fe21e9dce1fbdef4937.1629772842.git.dxu@dxuuu.xyz
parent dd6e10fb
Loading
Loading
Loading
Loading
+47 −0
Original line number Diff line number Diff line
// SPDX-License-Identifier: GPL-2.0
#define _GNU_SOURCE
#include <test_progs.h>
#include <linux/ptrace.h>
#include "test_task_pt_regs.skel.h"

void test_task_pt_regs(void)
{
	struct test_task_pt_regs *skel;
	struct bpf_link *uprobe_link;
	size_t uprobe_offset;
	ssize_t base_addr;
	bool match;

	base_addr = get_base_addr();
	if (!ASSERT_GT(base_addr, 0, "get_base_addr"))
		return;
	uprobe_offset = get_uprobe_offset(&get_base_addr, base_addr);

	skel = test_task_pt_regs__open_and_load();
	if (!ASSERT_OK_PTR(skel, "skel_open"))
		return;
	if (!ASSERT_OK_PTR(skel->bss, "check_bss"))
		goto cleanup;

	uprobe_link = bpf_program__attach_uprobe(skel->progs.handle_uprobe,
						 false /* retprobe */,
						 0 /* self pid */,
						 "/proc/self/exe",
						 uprobe_offset);
	if (!ASSERT_OK_PTR(uprobe_link, "attach_uprobe"))
		goto cleanup;
	skel->links.handle_uprobe = uprobe_link;

	/* trigger & validate uprobe */
	get_base_addr();

	if (!ASSERT_EQ(skel->bss->uprobe_res, 1, "check_uprobe_res"))
		goto cleanup;

	match = !memcmp(&skel->bss->current_regs, &skel->bss->ctx_regs,
			sizeof(skel->bss->current_regs));
	ASSERT_TRUE(match, "check_regs_match");

cleanup:
	test_task_pt_regs__destroy(skel);
}
+29 −0
Original line number Diff line number Diff line
// SPDX-License-Identifier: GPL-2.0

#include <linux/ptrace.h>
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

struct pt_regs current_regs = {};
struct pt_regs ctx_regs = {};
int uprobe_res = 0;

SEC("uprobe/trigger_func")
int handle_uprobe(struct pt_regs *ctx)
{
	struct task_struct *current;
	struct pt_regs *regs;

	current = bpf_get_current_task_btf();
	regs = (struct pt_regs *) bpf_task_pt_regs(current);
	__builtin_memcpy(&current_regs, regs, sizeof(*regs));
	__builtin_memcpy(&ctx_regs, ctx, sizeof(*ctx));

	/* Prove that uprobe was run */
	uprobe_res = 1;

	return 0;
}

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