Path: blob/master/tools/testing/selftests/bpf/bpf_util.h
26285 views
/* SPDX-License-Identifier: GPL-2.0 */1#ifndef __BPF_UTIL__2#define __BPF_UTIL__34#include <stdio.h>5#include <stdlib.h>6#include <string.h>7#include <errno.h>8#include <syscall.h>9#include <bpf/libbpf.h> /* libbpf_num_possible_cpus */1011static inline unsigned int bpf_num_possible_cpus(void)12{13int possible_cpus = libbpf_num_possible_cpus();1415if (possible_cpus < 0) {16printf("Failed to get # of possible cpus: '%s'!\n",17strerror(-possible_cpus));18exit(1);19}20return possible_cpus;21}2223/* Copy up to sz - 1 bytes from zero-terminated src string and ensure that dst24* is zero-terminated string no matter what (unless sz == 0, in which case25* it's a no-op). It's conceptually close to FreeBSD's strlcpy(), but differs26* in what is returned. Given this is internal helper, it's trivial to extend27* this, when necessary. Use this instead of strncpy inside libbpf source code.28*/29static inline void bpf_strlcpy(char *dst, const char *src, size_t sz)30{31size_t i;3233if (sz == 0)34return;3536sz--;37for (i = 0; i < sz && src[i]; i++)38dst[i] = src[i];39dst[i] = '\0';40}4142#define __bpf_percpu_val_align __attribute__((__aligned__(8)))4344#define BPF_DECLARE_PERCPU(type, name) \45struct { type v; /* padding */ } __bpf_percpu_val_align \46name[bpf_num_possible_cpus()]47#define bpf_percpu(name, cpu) name[(cpu)].v4849#ifndef ARRAY_SIZE50# define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))51#endif5253#ifndef sizeof_field54#define sizeof_field(TYPE, MEMBER) sizeof((((TYPE *)0)->MEMBER))55#endif5657#ifndef offsetofend58#define offsetofend(TYPE, MEMBER) \59(offsetof(TYPE, MEMBER) + sizeof_field(TYPE, MEMBER))60#endif6162/* Availability of gettid across glibc versions is hit-and-miss, therefore63* fallback to syscall in this macro and use it everywhere.64*/65#ifndef sys_gettid66#define sys_gettid() syscall(SYS_gettid)67#endif6869#ifndef ENOTSUPP70#define ENOTSUPP 52471#endif7273#endif /* __BPF_UTIL__ */747576