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

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

File Facts

System
Linux kernel
Corpus path
tools/testing/selftests/bpf/prog_tests/file_reader.c
Extension
.c
Size
2679 bytes
Lines
116
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) 2025 Meta Platforms, Inc. and affiliates. */

#include <test_progs.h>
#include <network_helpers.h>
#include "file_reader.skel.h"
#include "file_reader_fail.skel.h"
#include <dlfcn.h>
#include <sys/mman.h>

const char *user_ptr = "hello world";
char file_contents[256000];
void *addr;

void *get_executable_base_addr(void)
{
	Dl_info info;

	if (!dladdr((void *)&get_executable_base_addr, &info)) {
		fprintf(stderr, "dladdr failed\n");
		return NULL;
	}

	return info.dli_fbase;
}

static int initialize_file_contents(void)
{
	int fd, page_sz = sysconf(_SC_PAGESIZE);
	ssize_t n = 0, cur;

	fd = open("/proc/self/exe", O_RDONLY);
	if (!ASSERT_OK_FD(fd, "Open /proc/self/exe\n"))
		return 1;

	do {
		cur = read(fd, file_contents + n, sizeof(file_contents) - n);
		if (!ASSERT_GT(cur, 0, "read success"))
			break;
		n += cur;
	} while (n < sizeof(file_contents));

	close(fd);

	if (!ASSERT_EQ(n, sizeof(file_contents), "Read /proc/self/exe\n"))
		return 1;

	addr = get_executable_base_addr();
	if (!ASSERT_NEQ(addr, NULL, "get executable address"))
		return 1;

	/* page-align base file address */
	addr = (void *)((unsigned long)addr & ~(page_sz - 1));

	return 0;
}

static void run_test(const char *prog_name)
{
	struct file_reader *skel;
	struct bpf_program *prog;
	int err, fd;

	err = initialize_file_contents();
	if (!ASSERT_OK(err, "initialize file contents"))
		return;

	skel = file_reader__open();
	if (!ASSERT_OK_PTR(skel, "file_reader__open"))
		return;

	bpf_object__for_each_program(prog, skel->obj) {
		bpf_program__set_autoload(prog, strcmp(bpf_program__name(prog), prog_name) == 0);
	}

	memcpy(skel->bss->user_buf, file_contents, sizeof(file_contents));
	skel->bss->pid = getpid();

	err = file_reader__load(skel);
	if (!ASSERT_OK(err, "file_reader__load"))
		goto cleanup;

	/*
	 * Page out range 0..512K, use 0..256K for positive tests and
	 * 256K..512K for negative tests expecting page faults
	 */
	if (!ASSERT_OK(madvise(addr, sizeof(file_contents) * 2, MADV_PAGEOUT),
		       "madvise pageout"))
		goto cleanup;

Annotation

Implementation Notes