mirror_iproute2/lib/bpf_glue.c
Hangbin Liu 503e9229b0 iproute2: add check_libbpf() and get_libbpf_version()
This patch aim to add basic checking functions for later iproute2
libbpf support.

First we add check_libbpf() in configure to see if we have bpf library
support. By default the system libbpf will be used, but static linking
against a custom libbpf version can be achieved by passing libbpf DESTDIR
to variable LIBBPF_DIR for configure.

Another variable LIBBPF_FORCE is used to control whether to build iproute2
with libbpf. If set to on, then force to build with libbpf and exit if
not available. If set to off, then force to not build with libbpf.

When dynamically linking against libbpf, we can't be sure that the
version we discovered at compile time is actually the one we are
using at runtime. This can lead to hard-to-debug errors. So we add
a new file lib/bpf_glue.c and a helper function get_libbpf_version()
to get correct libbpf version at runtime.

Signed-off-by: Hangbin Liu <haliu@redhat.com>
Signed-off-by: David Ahern <dsahern@gmail.com>
2020-11-24 22:14:02 -07:00

64 lines
1.8 KiB
C

/* SPDX-License-Identifier: GPL-2.0 */
/*
* bpf_glue.c: BPF code to call both legacy and libbpf code
* Authors: Hangbin Liu <haliu@redhat.com>
*
*/
#include "bpf_util.h"
#ifdef HAVE_LIBBPF
static const char *_libbpf_compile_version = LIBBPF_VERSION;
static char _libbpf_version[10] = {};
const char *get_libbpf_version(void)
{
/* Start by copying compile-time version into buffer so we have a
* fallback value in case we are dynamically linked, or can't find a
* version in /proc/self/maps below.
*/
strncpy(_libbpf_version, _libbpf_compile_version,
sizeof(_libbpf_version)-1);
#ifdef LIBBPF_DYNAMIC
char buf[PATH_MAX], *s;
bool found = false;
FILE *fp;
/* When dynamically linking against libbpf, we can't be sure that the
* version we discovered at compile time is actually the one we are
* using at runtime. This can lead to hard-to-debug errors, so we try to
* discover the correct version at runtime.
*
* The simple solution to this would be if libbpf itself exported a
* version in its API. But since it doesn't, we work around this by
* parsing the mappings of the binary at runtime, looking for the full
* filename of libbpf.so and using that.
*/
fp = fopen("/proc/self/maps", "r");
if (fp == NULL)
goto out;
while ((s = fgets(buf, sizeof(buf), fp)) != NULL) {
if ((s = strstr(buf, "libbpf.so.")) != NULL) {
strncpy(_libbpf_version, s+10, sizeof(_libbpf_version)-1);
strtok(_libbpf_version, "\n");
found = true;
break;
}
}
fclose(fp);
out:
if (!found)
fprintf(stderr, "Couldn't find runtime libbpf version - falling back to compile-time value!\n");
#endif /* LIBBPF_DYNAMIC */
_libbpf_version[sizeof(_libbpf_version)-1] = '\0';
return _libbpf_version;
}
#else
const char *get_libbpf_version(void)
{
return NULL;
}
#endif /* HAVE_LIBBPF */