Path: blob/master/tools/testing/selftests/bpf/bpftool_helpers.c
121838 views
// SPDX-License-Identifier: GPL-2.0-only1#include <unistd.h>2#include <string.h>3#include <stdbool.h>45#include "bpf_util.h"6#include "bpftool_helpers.h"78#define BPFTOOL_PATH_MAX_LEN 649#define BPFTOOL_FULL_CMD_MAX_LEN 5121011#define BPFTOOL_DEFAULT_PATH "tools/sbin/bpftool"1213static int detect_bpftool_path(char *buffer, size_t size)14{15char tmp[BPFTOOL_PATH_MAX_LEN];16const char *env_path;1718/* First, check if BPFTOOL environment variable is set */19env_path = getenv("BPFTOOL");20if (env_path && access(env_path, X_OK) == 0) {21strscpy(buffer, env_path, size);22return 0;23} else if (env_path) {24fprintf(stderr, "bpftool '%s' doesn't exist or is not executable\n", env_path);25return 1;26}2728/* Check default bpftool location (will work if we are running the29* default flavor of test_progs)30*/31snprintf(tmp, BPFTOOL_PATH_MAX_LEN, "./%s", BPFTOOL_DEFAULT_PATH);32if (access(tmp, X_OK) == 0) {33strscpy(buffer, tmp, size);34return 0;35}3637/* Check alternate bpftool location (will work if we are running a38* specific flavor of test_progs, e.g. cpuv4 or no_alu32)39*/40snprintf(tmp, BPFTOOL_PATH_MAX_LEN, "../%s", BPFTOOL_DEFAULT_PATH);41if (access(tmp, X_OK) == 0) {42strscpy(buffer, tmp, size);43return 0;44}4546fprintf(stderr, "Failed to detect bpftool path, use BPFTOOL env var to override\n");47return 1;48}4950static int run_command(char *args, char *output_buf, size_t output_max_len)51{52static char bpftool_path[BPFTOOL_PATH_MAX_LEN] = {0};53bool suppress_output = !(output_buf && output_max_len);54char command[BPFTOOL_FULL_CMD_MAX_LEN];55FILE *f;56int ret;5758/* Detect and cache bpftool binary location */59if (bpftool_path[0] == 0 && detect_bpftool_path(bpftool_path, sizeof(bpftool_path)))60return 1;6162ret = snprintf(command, BPFTOOL_FULL_CMD_MAX_LEN, "%s %s%s",63bpftool_path, args,64suppress_output ? " > /dev/null 2>&1" : "");6566f = popen(command, "r");67if (!f)68return 1;6970if (!suppress_output)71fread(output_buf, 1, output_max_len, f);72ret = pclose(f);7374return ret;75}7677int run_bpftool_command(char *args)78{79return run_command(args, NULL, 0);80}8182int get_bpftool_command_output(char *args, char *output_buf, size_t output_max_len)83{84return run_command(args, output_buf, output_max_len);85}86878889