Add libbpf-provided extern variables support
Subsystems (7)
v2 cover Add libbpf-provided extern variables support
It's often important for BPF program to know kernel version or some specific config values (e.g., CONFIG_HZ to convert jiffies to seconds) and change or adjust program logic based on their values. As of today, any such need has to be resolved by recompiling BPF program for specific kernel and kernel configuration. In practice this is usually achieved by using BCC and its embedded LLVM/Clang. With such set up #ifdef CONFIG_XXX and similar compile-time constructs allow to deal with kernel varieties.
With CO-RE (Compile Once – Run Everywhere) approach, this is not an option, unfortunately. All such logic variations have to be done as a normal C language constructs (i.e., if/else, variables, etc), not a preprocessor directives. This patch series add support for such advanced scenarios through C extern variables. These extern variables will be recognized by libbpf and supplied through extra .extern internal map, similarly to global data. This .extern map is read-only, which allows BPF verifier to track its content precisely as constants. That gives an opportunity to have pre-compiled BPF program, which can potentially use BPF functionality (e.g., BPF helpers) or kernel features (types, fields, etc), that are available only on a subset of targeted kernels, while effectively eleminating (through verifier's dead code detection) such unsupported functionality for other kernels (typically, older versions). Patch #3 explicitly tests a scenario of using unsupported BPF helper, to validate the approach.
This patch set heavily relies on BTF type information emitted by compiler for each extern variable declaration. Based on specific types, libbpf does strict checks of config data values correctness. See patch #1 for details.
Outline of the patch set:
- patch #1 adds all of the libbpf internal machinery for externs support, including setting up BTF information for .extern data section;
- patch #2 adds support for .extern into BPF skeleton;
- patch #3 adds externs selftests, as well as enhances test_skeleton.c test to validate mmap()-ed .extern datasection functionality.
This patch set is based off BPF skeleton patch set ([0]).
[0] https://patchwork.ozlabs.org/project/netdev/list/?series=147459&state=*
v1->v2:
- use BTF type information for externs (Alexei);
- add strings support;
- add BPF skeleton support for .extern.
Andrii Nakryiko (3):
libbpf: support libbpf-provided extern variables
bpftool: generate externs datasec in BPF skeleton selftests/bpf: add tests for libbpf-provided externs
include/uapi/linux/btf.h | 3 +- tools/bpf/bpftool/gen.c | 4 + tools/include/uapi/linux/btf.h | 7 +- tools/lib/bpf/Makefile | 15 +- tools/lib/bpf/bpf_helpers.h | 9 + tools/lib/bpf/btf.c | 9 +- tools/lib/bpf/libbpf.c | 769 ++++++++++++++++-- tools/lib/bpf/libbpf.h | 6 +- tools/lib/bpf/libbpf_internal.h | 6 + tools/testing/selftests/bpf/Makefile | 2 +- .../selftests/bpf/prog_tests/core_extern.c | 192 +++++ .../selftests/bpf/prog_tests/skeleton.c | 18 +- .../selftests/bpf/progs/test_core_extern.c | 62 ++ .../selftests/bpf/progs/test_skeleton.c | 9 + 14 files changed, 1024 insertions(+), 87 deletions(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/core_extern.c create mode 100644 tools/testing/selftests/bpf/progs/test_core_extern.c
Signature · 1 line
2.17.1
PATCH v2 1/3 libbpf: support libbpf-provided extern variables
Add support for extern variables, provided to BPF program by libbpf. Currently the following extern variables are supported:
- LINUX_KERNEL_VERSION; version of a kernel in which BPF program is executing, follows KERNEL_VERSION() macro convention, can be 4- and 8-byte long;
- CONFIG_xxx values; a set of values of actual kernel config. Tristate, boolean, strings, and integer values are supported.
Set of possible values is determined by declared type of extern variable. Supported types of variables are:
- Tristate values. Are represented as enum libbpf_tristate. Accepted values are **strictly** 'y', 'n', or 'm', which are represented as TRI_YES, TRI_NO, or TRI_MODULE, respectively.
- Boolean values. Are represented as bool (_Bool) types. Accepted values are 'y' and 'n' only, turning into true/false values, respectively.
- Single-character values. Can be used both as a substritute for bool/tristate, or as a small-range integer:
- 'y'/'n'/'m' are represented as is, as characters 'y', 'n', or 'm';
- integers in a range [-128, 127] or [0, 255] (depending on signedness of char in target architecture) are recognized and represented with respective values of char type.
- Strings. String values are declared as fixed-length char arrays. String of up to that length will be accepted and put in first N bytes of char array, with the rest of bytes zeroed out. Char array is always zero terminated. If config string is longer, than can be fit in character array, it's an error, and program load will fail. String literals in config have to be enclosed in double quotes, just like C-style string literals.
- Integers. 8-, 16-, 32-, and 64-bit integers are supported, both signed and unsigned variants. Libbpf enforces parsed config value to be in the supported range of corresponding integer type. Integers values in config can be:
- decimal integers, with optional + and - signs;
- hexadecimal integers, prefixed with 0x or 0X;
- octal integers, starting with 0.
Config file itself is searched in /boot/config-$(uname -r) location with fallback to /proc/config.gz, unless config path is specified explicitly through bpf_object_open_opts' kernel_config_path option. Both gzipped and plain text formats are supported. Libbpf adds explicit dependency on zlib because of this, but this shouldn't be a problem, given libelf already depends on zlib.
All detected extern variables, are put into a separate .extern internal map. It, similarly to .rodata map, is marked as read-only from BPF program side, as well as is frozen on load. This allows BPF verifier to track extern values as constants and perform enhanced branch prediction and dead code elimination. This can be relied upon for doing kernel version/feature detection and using potentially unsupported field relocations or BPF helpers in a CO-RE-based BPF program, while still having a single version of BPF program running on old and new kernels. Selftests are validating this explicitly for unexisting BPF helper.
--- include/uapi/linux/btf.h | 3 +- tools/include/uapi/linux/btf.h | 7 +- tools/lib/bpf/Makefile | 15 +- tools/lib/bpf/bpf_helpers.h | 9 + tools/lib/bpf/btf.c | 9 +- tools/lib/bpf/libbpf.c | 759 ++++++++++++++++++++++++--- tools/lib/bpf/libbpf.h | 6 +- tools/lib/bpf/libbpf_internal.h | 6 + tools/testing/selftests/bpf/Makefile | 2 +- 9 files changed, 735 insertions(+), 81 deletions(-)
include/uapi/linux/btf.h +2 -1
@@ -142,7 +142,8 @@ struct btf_param {enum {BTF_VAR_STATIC =0 , -BTF_VAR_GLOBAL_ALLOCATED , +BTF_VAR_GLOBAL_ALLOCATED =1 , +BTF_VAR_GLOBAL_EXTERN =2 , };/* BTF_KIND_VAR is followed by a single "struct btf_var" to describe
tools/include/uapi/linux/btf.h +4 -3
@@ -22,9 +22,9 @@ struct btf_header { };/* Max # of type identifier */ -#define BTF_MAX_TYPE 0x0000ffff +#define BTF_MAX_TYPE 0x000fffff/* Max offset into the string section */ -#define BTF_MAX_NAME_OFFSET 0x0000ffff +#define BTF_MAX_NAME_OFFSET 0x00ffffff/* Max # of struct/union/enum members or func args */ #define BTF_MAX_VLEN 0xffff
@@ -142,7 +142,8 @@ struct btf_param {enum {BTF_VAR_STATIC =0 , -BTF_VAR_GLOBAL_ALLOCATED , +BTF_VAR_GLOBAL_ALLOCATED =1 , +BTF_VAR_GLOBAL_EXTERN =2 , };/* BTF_KIND_VAR is followed by a single "struct btf_var" to describe
tools/lib/bpf/Makefile +9 -6
@@ -56,8 +56,8 @@ ifndef VERBOSE endif FEATURE_USER = .libbpf -FEATURE_TESTS = libelf libelf-mmap bpf reallocarray -FEATURE_DISPLAY = libelf bpf +FEATURE_TESTS = libelf libelf-mmap zlib bpf reallocarray +FEATURE_DISPLAY = libelf zlib bpf INCLUDES = -I. -I$(srctree)/tools/include -I$(srctree)/tools/arch/$(ARCH)/include/uapi -I$(srctree)/tools/include/uapi FEATURE_CHECK_CFLAGS-bpf = $(INCLUDES)
@@ -159,7 +159,7 @@ all: fixdep all_cmd: $(CMD_TARGETS) check -$(BPF_IN_SHARED): force elfdep bpfdep bpf_helper_defs.h +$(BPF_IN_SHARED): force elfdep zdep bpfdep bpf_helper_defs.h @(test -f ../../include/uapi/linux/bpf.h -a -f ../../../include/uapi/linux/bpf.h && ( \ (diff -B ../../include/uapi/linux/bpf.h ../../../include/uapi/linux/bpf.h >/dev/null) || \ echo "Warning: Kernel ABI header at 'tools/include/uapi/linux/bpf.h' differs from latest version at 'include/uapi/linux/bpf.h'" >&2 )) || true
@@ -177,7 +177,7 @@ $(BPF_IN_SHARED): force elfdep bpfdep bpf_helper_defs.h echo "Warning: Kernel ABI header at 'tools/include/uapi/linux/if_xdp.h' differs from latest version at 'include/uapi/linux/if_xdp.h'" >&2 )) || true $(Q)$(MAKE) $(build)=libbpf OUTPUT=$(SHARED_OBJDIR) CFLAGS="$(CFLAGS) $(SHLIB_FLAGS)" -$(BPF_IN_STATIC): force elfdep bpfdep bpf_helper_defs.h +$(BPF_IN_STATIC): force elfdep zdep bpfdep bpf_helper_defs.h $(Q)$(MAKE) $(build)=libbpf OUTPUT=$(STATIC_OBJDIR) bpf_helper_defs.h: $(srctree)/tools/include/uapi/linux/bpf.h
@@ -189,7 +189,7 @@ $(OUTPUT)libbpf.so: $(OUTPUT)libbpf.so.$(LIBBPF_VERSION) $(OUTPUT)libbpf.so.$(LIBBPF_VERSION): $(BPF_IN_SHARED) $(QUIET_LINK)$(CC) $(LDFLAGS) \ --shared -Wl,-soname,libbpf.so.$(LIBBPF_MAJOR_VERSION) \ - -Wl,--version-script=$(VERSION_SCRIPT) $^ -lelf -o $@ + -Wl,--version-script=$(VERSION_SCRIPT) $^ -lelf -lz -o $@ @ln -sf $(@F) $(OUTPUT)libbpf.so @ln -sf $(@F) $(OUTPUT)libbpf.so.$(LIBBPF_MAJOR_VERSION)
@@ -277,12 +277,15 @@ clean: -PHONY += force elfdep bpfdep cscope tags +PHONY += force elfdep zdep bpfdep cscope tags force: elfdep: @if [ "$(feature-libelf)" != "1" ]; then echo "No libelf found"; exit 1 ; fi +zdep: + @if [ "$(feature-zlib)" != "1" ]; then echo "No zlib found"; exit 1 ; fi + bpfdep: @if [ "$(feature-bpf)" != "1" ]; then echo "BPF API too old"; exit 1 ; fi
tools/lib/bpf/bpf_helpers.h +9 -0
@@ -25,6 +25,9 @@#ifndef __always_inline#define __always_inline __attribute__((always_inline))#endif +#ifndef __weak +#define __weak __attribute__((weak)) +#endif /* * Helper structure used by eBPF C program
@@ -44,4 +47,10 @@ enum libbpf_pin_type { LIBBPF_PIN_BY_NAME, }; +enum libbpf_tristate { +TRI_NO =0 , +TRI_YES =1 , +TRI_MODULE =2 , +}; +#endif
tools/lib/bpf/btf.c +8 -1
@@ -539,6 +539,12 @@ static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,return -ENOENT ; } +/* .extern datasec size and var offsets were set correctly during +* extern collection step, so just skip straight to sorting variables +*/ +if (t->size) + goto sort_vars; + ret =bpf_object__section_size (obj, name, &size);if (ret || !size || (t->size && t->size != size)) {pr_debug ("Invalid size for section %s: %u bytes\n" , name, size);
@@ -575,7 +581,8 @@ static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf, vsi->offset = off; } -qsort (t +1 , vars,sizeof (*vsi), compare_vsi_off); +sort_vars: +qsort (btf_var_secinfos (t), vars,sizeof (*vsi), compare_vsi_off);return 0 ; }
tools/lib/bpf/libbpf.c +691 -68
1,003 lines not on this page · raw message
tools/lib/bpf/libbpf.h +5 -1
@@ -109,8 +109,12 @@ struct bpf_object_open_opts {*/ const char *pin_root_path;__u32 attach_prog_fd; +/* kernel config file path override (for CONFIG_ externs); can point +* to either uncompressed text file or .gz file +*/ +const char *kconfig_path; }; -#define bpf_object_open_opts__last_field attach_prog_fd +#define bpf_object_open_opts__last_field kconfig_path LIBBPF_API struct bpf_object *bpf_object__open(const char *path); LIBBPF_API struct bpf_object *
tools/lib/bpf/libbpf_internal.h +6 -0
@@ -275,4 +275,10 @@ int bpf_object__attach_skeleton(struct bpf_object_skeleton *s);void bpf_object__detach_skeleton (struct bpf_object_skeleton *s);void bpf_object__destroy_skeleton (struct bpf_object_skeleton *s); +enum libbpf_tristate { +TRI_NO =0 , +TRI_YES =1 , +TRI_MODULE =2 , +}; +#endif /* __LIBBPF_LIBBPF_INTERNAL_H */
tools/testing/selftests/bpf/Makefile +1 -1
@@ -24,7 +24,7 @@ CFLAGS += -g -Wall -O2 $(GENFLAGS) -I$(APIDIR) -I$(LIBDIR) -I$(BPFDIR) \ -I$(GENDIR) -I$(TOOLSINCDIR) -I$(CURDIR) \ -Dbpf_prog_load=bpf_prog_test_load \ -Dbpf_load_program=bpf_test_load_program -LDLIBS += -lcap -lelf -lrt -lpthread +LDLIBS += -lcap -lelf -lz -lrt -lpthread # Order correspond to 'make run_tests' order TEST_GEN_PROGS = test_verifier test_tag test_maps test_lru_map test_lpm_map test_progs \
Signature · 1 line
2.17.1
Re: [PATCH v2 bpf-next 1/3] libbpf: support libbpf-provided extern variables
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 989
Quoted 11 lines · Andrii Nakryiko
tools/lib/bpf/libbpf.c +11
-0+static int set_ext_value_tri (struct extern_desc *ext,void *ext_val, +char value) +{ +switch (ext->type) { +case EXT_BOOL : +if (value =='m' ) { +pr_warn ("extern %s=%c should be tristate or char\n" , + ext->name, value); +return -EINVAL ; + } + *(bool *)ext_val = value =='y' ? true : false;
may be check for strict y/n ?
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 997
Quoted 8 lines
tools/lib/bpf/libbpf.c +8
-0+break ; +case EXT_TRISTATE : +if (value =='y' ) + *(enum libbpf_tristate *)ext_val =TRI_YES ; +else if (value =='m' ) + *(enum libbpf_tristate *)ext_val =TRI_MODULE ; +else /* value == 'n' */ + *(enum libbpf_tristate *)ext_val =TRI_NO ;
same here ?
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 1004
Quoted 7 lines
tools/lib/bpf/libbpf.c +7
-0+break ; +case EXT_CHAR : + *(char *)ext_val = value; +break ; +case EXT_UNKNOWN : +case EXT_INT : +case EXT_CHAR_ARR :
why enumerate them when there is a default ?
Quoted 13 lines
tools/lib/bpf/libbpf.c +13
-0+static int set_ext_value_str (struct extern_desc *ext,void *ext_val, +const char *value) +{ +size_t len; + +if (ext->type !=EXT_CHAR_ARR ) { +pr_warn ("extern %s=%s should char array\n" , ext->name, value); +return -EINVAL ; + } + + len =strlen (value); +if (value[len -1 ] !='"' ) { + pr_warn("extern '%s': invalid string config '%s'\n",
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 1036
Quoted 10 lines
tools/lib/bpf/libbpf.c +10
-0+ ext->name, value); +return -EINVAL ; + } + +/* strip quotes */ + len -=2 ; +if (len +1 > ext->sz) { +pr_warn ("extern '%s': too long string config %s (%zu bytes), up to %d expected\n" , + ext->name, value, len +1 , ext->sz); +return -EINVAL ;
may be print warning and truncate instead of hard error?
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 1073
Quoted 11 lines
tools/lib/bpf/libbpf.c +11
-0+static bool is_ext_value_in_range (const struct extern_desc *ext,__u64 v) +{ +int bit_sz = ext->sz *8 ; + +if (ext->sz ==8 ) +return true; + +if (ext->is_signed) +return v + (1ULL << (bit_sz -1 )) < (1ULL << bit_sz); +else +return (v >> bit_sz) ==0 ;
a comment would be helpful.
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 1169
Quoted 5 lines
tools/lib/bpf/libbpf.c +5
-0+ ext_val = data + ext->data_off; + value = sep +1 ; + +switch (*value) { +case 'y' :case 'n' :case 'm' :
I don't think config.gz has 'n', but it's good to have it here.
tools/lib/bpf/libbpf.c static int bpf_object__elf_collect(struct bpf_object *obj) · line 2004
Quoted 6 lines
tools/lib/bpf/libbpf.c +2
-2- }else if (strcmp (name,".data" ) ==0 ) { + }else if (strcmp (name,DATA_SEC ) ==0 ) { obj->efile.data = data; obj->efile.data_shndx = idx; - }else if (strcmp (name,".rodata" ) ==0 ) { + }else if (strcmp (name,RODATA_SEC ) ==0 ) {
such cleanup changes should be in separate patch.
tools/lib/bpf/libbpf.c static int bpf_object__sanitize_maps(struct bpf_object *obj) · line 4688
Quoted 9 lines
tools/lib/bpf/libbpf.c +9
-0+if (strcmp (ext->name,"LINUX_KERNEL_VERSION" ) ==0 ) { +void *ext_val = data + ext->data_off; +__u32 kver =get_kernel_version (); + +if (!kver) { +pr_warn ("failed to get kernel version\n" ); +return -EINVAL ; + } + err =set_ext_value_num (ext, ext_val, kver);
I think it should work when kern_ver is not 'int'. Could you add a test for u64 ?
Or it will fail on big endian?
Re: [PATCH v2 bpf-next 1/3] libbpf: support libbpf-provided extern variables
Quoted 15 lines · Alexei Starovoitov
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 989
Quoted 11 lines · Andrii Nakryiko
tools/lib/bpf/libbpf.c +11
-0+static int set_ext_value_tri (struct extern_desc *ext,void *ext_val, +char value) +{ +switch (ext->type) { +case EXT_BOOL : +if (value =='m' ) { +pr_warn ("extern %s=%c should be tristate or char\n" , + ext->name, value); +return -EINVAL ; + } + *(bool *)ext_val = value =='y' ? true : false;may be check for strict y/n ?
Can't be anything else due to case 'y': case 'n': case 'm': check in the caller.
Quoted 20 lines
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 997
Quoted 9 lines
tools/lib/bpf/libbpf.c +8
-0+break ; +case EXT_TRISTATE : +if (value =='y' ) + *(enum libbpf_tristate *)ext_val =TRI_YES ; +else if (value =='m' ) + *(enum libbpf_tristate *)ext_val =TRI_MODULE ; +else /* value == 'n' */ + *(enum libbpf_tristate *)ext_val =TRI_NO ;same here ?
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 1004
Quoted 7 lines
tools/lib/bpf/libbpf.c +7
-0+break ; +case EXT_CHAR : + *(char *)ext_val = value; +break ; +case EXT_UNKNOWN : +case EXT_INT : +case EXT_CHAR_ARR :
Quoted 1 line
why enumerate them when there is a default ?
Because compiler is too smart and strict. Otherwise getting:
libbpf.c: In function ‘set_ext_value_tri’:
libbpf.c:982:2: error: enumeration value ‘EXT_UNKNOWN’ not handled in switch [-Werror=switch-enum]
switch (ext->type) {
^~~~~~
libbpf.c:982:2: error: enumeration value ‘EXT_INT’ not handled in switch [-Werror=switch-enum]
libbpf.c:982:2: error: enumeration value ‘EXT_CHAR_ARR’ not handled in switch [-Werror=switch-enum]
Quoted 18 lines
Quoted 18 lines
tools/lib/bpf/libbpf.c +17
-0+static int set_ext_value_str (struct extern_desc *ext,void *ext_val, +const char *value) +{ +size_t len; + +if (ext->type !=EXT_CHAR_ARR ) { +pr_warn ("extern %s=%s should char array\n" , ext->name, value); +return -EINVAL ; + } + + len =strlen (value); +if (value[len -1 ] !='"' ) { +pr_warn ("extern '%s': invalid string config '%s'\n" , + ext->name, value); +return -EINVAL ; + } +
Quoted 8 lines
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 1036
Quoted 6 lines
tools/lib/bpf/libbpf.c +6
-0+/* strip quotes */ + len -=2 ; +if (len +1 > ext->sz) { +pr_warn ("extern '%s': too long string config %s (%zu bytes), up to %d expected\n" , + ext->name, value, len +1 , ext->sz); +return -EINVAL ;may be print warning and truncate instead of hard error?
Could do. I erred on the side of being strict. I don't mind relaxing this, though.
Quoted 14 lines
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 1073
Quoted 12 lines
tools/lib/bpf/libbpf.c +11
-0+static bool is_ext_value_in_range (const struct extern_desc *ext,__u64 v) +{ +int bit_sz = ext->sz *8 ; + +if (ext->sz ==8 ) +return true; + +if (ext->is_signed) +return v + (1ULL << (bit_sz -1 )) < (1ULL << bit_sz); +else +return (v >> bit_sz) ==0 ;a comment would be helpful.
will add
Quoted 9 lines
tools/lib/bpf/libbpf.c static int bpf_object__init_global_data_maps(struct bpf_object *obj) · line 1169
Quoted 6 lines
tools/lib/bpf/libbpf.c +5
-0+ ext_val = data + ext->data_off; + value = sep +1 ; + +switch (*value) { +case 'y' :case 'n' :case 'm' :I don't think config.gz has 'n', but it's good to have it here.
Quoted 8 lines
tools/lib/bpf/libbpf.c static int bpf_object__elf_collect(struct bpf_object *obj) · line 2004
Quoted 6 lines
tools/lib/bpf/libbpf.c +2
-2- }else if (strcmp (name,".data" ) ==0 ) { + }else if (strcmp (name,DATA_SEC ) ==0 ) { obj->efile.data = data; obj->efile.data_shndx = idx; - }else if (strcmp (name,".rodata" ) ==0 ) { + }else if (strcmp (name,RODATA_SEC ) ==0 ) {such cleanup changes should be in separate patch.
Ok, will split out. Needed that for .extern, decided to complete for others in the same go.
Quoted 11 lines
tools/lib/bpf/libbpf.c static int bpf_object__sanitize_maps(struct bpf_object *obj) · line 4688
Quoted 10 lines
tools/lib/bpf/libbpf.c +9
-0+if (strcmp (ext->name,"LINUX_KERNEL_VERSION" ) ==0 ) { +void *ext_val = data + ext->data_off; +__u32 kver =get_kernel_version (); + +if (!kver) { +pr_warn ("failed to get kernel version\n" ); +return -EINVAL ; + } + err =set_ext_value_num (ext, ext_val, kver);
Quoted 4 lines
I think it should work when
kern_veris not 'int'. Could you add a test for u64 ?
Or it will fail on big endian?
Yeah, it is handled inside set_ext_value_num just the same as any CONFIG_xxx integers. I will make sure that test_core_extern and test_skeleton use both u32 and u64.
PATCH v2 2/3 bpftool: generate externs datasec in BPF skeleton
In reply to Andrii NakryikoAdd support for generation of mmap()-ed read-only view of libbpf-provided extern variables. As externs are not supposed to be provided by user code (that's what .data, .bss, and .rodata is for), don't mmap() it initially. Only after skeleton load is performed, map .extern contents as read-only memory.
--- tools/bpf/bpftool/gen.c | 4 ++++ tools/lib/bpf/libbpf.c | 10 +++++----- 2 files changed, 9 insertions(+), 5 deletions(-)
tools/bpf/bpftool/gen.c +4 -0
@@ -82,6 +82,8 @@ static const char *get_map_ident(const struct bpf_map *map)return "rodata" ; else if (str_has_suffix(name, ".bss")) return "bss"; + else if (str_has_suffix(name, ".extern")) + return "externs"; /* extern is a C keyword */ else return NULL; }
@@ -109,6 +111,8 @@ static int codegen_datasec_def(struct bpf_object *obj, sec_ident ="bss" ; else if (strcmp(sec_name, ".rodata") == 0) sec_ident = "rodata"; + else if (strcmp(sec_name, ".extern") == 0) + sec_ident = "externs"; /* extern is a C keyword */ else return 0;
tools/lib/bpf/libbpf.c +5 -5
@@ -7392,7 +7392,8 @@ int bpf_object__open_skeleton(struct bpf_object_skeleton *s,return -ESRCH ; } -if (mmaped) +/* externs shouldn't be pre-setup from user code */ +if (mmaped && (*map)->libbpf_type !=LIBBPF_MAP_EXTERN ) *mmaped = (*map)->mmaped; }
@@ -7425,7 +7426,6 @@ int bpf_object__load_skeleton(struct bpf_object_skeleton *s)size_t mmap_sz =bpf_map_mmap_sz (map);int prot, map_fd =bpf_map__fd (map);void **mmaped = s->maps[i].mmaped; -void *remapped;if (!mmaped)continue ;
@@ -7450,9 +7450,9 @@ int bpf_object__load_skeleton(struct bpf_object_skeleton *s)* as per normal clean up procedure, so we don't need to worry * about it from skeleton's clean up perspective. */ - remapped =mmap (*mmaped, mmap_sz, prot,MAP_SHARED |MAP_FIXED , - map_fd,0 ); -if (remapped ==MAP_FAILED ) { + *mmaped =mmap (map->mmaped, mmap_sz, prot, +MAP_SHARED |MAP_FIXED , map_fd,0 ); +if (*mmaped ==MAP_FAILED ) { err = -errno; *mmaped =NULL ; pr_warn("failed to re-mmap() map '%s': %d\n",
Signature · 1 line
2.17.1
PATCH v2 3/3 selftests/bpf: add tests for libbpf-provided externs
In reply to Andrii NakryikoAdd a set of tests validating libbpf-provided extern variables. One crucial feature that's tested is dead code elimination together with using invalid BPF helper. CONFIG_MISSING is not supposed to exist and should always be specified by libbpf as zero, which allows BPF verifier to correctly do branch pruning and not fail validation, when invalid BPF helper is called from dead if branch.
--- .../selftests/bpf/prog_tests/core_extern.c | 192 ++++++++++++++++++ .../selftests/bpf/prog_tests/skeleton.c | 18 +- .../selftests/bpf/progs/test_core_extern.c | 62 ++++++ .../selftests/bpf/progs/test_skeleton.c | 9 + 4 files changed, 280 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/bpf/prog_tests/core_extern.c create mode 100644 tools/testing/selftests/bpf/progs/test_core_extern.c
tools/testing/selftests/bpf/prog_tests/core_extern.c new file +192 -0
@@ -0,0 +1,192 @@ +// SPDX-License-Identifier: GPL-2.0 +#include <test_progs.h> +#include <sys/mman.h> +#include <sys/utsname.h> +#include <linux/version.h> +#include "test_core_extern.skel.h" + +static uint32_t get_kernel_version (void ) +{ +uint32_t major, minor, patch; +struct utsname info; + +uname (&info); +if (sscanf (info.release,"%u.%u.%u" , &major, &minor, &patch) !=3 ) +return 0 ; +return KERNEL_VERSION (major, minor, patch); +} + +#define CFG "CONFIG_BPF_SYSCALL=n\n" + +static struct test_case { +const char *name; +const char *cfg; +const char *cfg_path; +bool fails; +struct test_core_extern__data data; +} test_cases[] = { + { .name ="default search path" , .cfg_path =NULL , + .data = { .bpf_syscall = true } }, + { .name ="/proc/config.gz" , .cfg_path ="/proc/config.gz" , + .data = { .bpf_syscall = true } }, + { .name ="missing config" , .fails = true, + .cfg_path ="/proc/invalid-config.gz" }, + { + .name ="custom values" , + .cfg ="CONFIG_BPF_SYSCALL=y\n" +"CONFIG_TRISTATE=m\n" +"CONFIG_BOOL=y\n" +"CONFIG_CHAR=100\n" +"CONFIG_USHORT=30000\n" +"CONFIG_INT=123456\n" +"CONFIG_ULONG=0xDEADBEEFC0DE\n" +"CONFIG_STR=\"abracad\"\n" +"CONFIG_MISSING=0" , + .data = { + .bpf_syscall = true, + .tristate_val =TRI_MODULE , + .bool_val = true, + .char_val =100 , + .ushort_val =30000 , + .int_val =123456 , + .ulong_val =0xDEADBEEFC0DE , + .str_val ="abracad" , + }, + }, +/* TRISTATE */ + { .name ="tristate (y)" , .cfg =CFG "CONFIG_TRISTATE=y\n" , + .data = { .tristate_val =TRI_YES } }, + { .name ="tristate (n)" , .cfg =CFG "CONFIG_TRISTATE=n\n" , + .data = { .tristate_val =TRI_NO } }, + { .name ="tristate (m)" , .cfg =CFG "CONFIG_TRISTATE=m\n" , + .data = { .tristate_val =TRI_MODULE } }, + { .name ="tristate (int)" , .fails =1 , .cfg =CFG "CONFIG_TRISTATE=1" }, + { .name ="tristate (bad)" , .fails =1 , .cfg =CFG "CONFIG_TRISTATE=M" }, +/* BOOL */ + { .name ="bool (y)" , .cfg =CFG "CONFIG_BOOL=y\n" , + .data = { .bool_val = true } }, + { .name ="bool (n)" , .cfg =CFG "CONFIG_BOOL=n\n" , + .data = { .bool_val = false } }, + { .name ="bool (tristate)" , .fails =1 , .cfg =CFG "CONFIG_BOOL=m" }, + { .name ="bool (int)" , .fails =1 , .cfg =CFG "CONFIG_BOOL=1" }, +/* CHAR */ + { .name ="char (tristate)" , .cfg =CFG "CONFIG_CHAR=m\n" , + .data = { .char_val ='m' } }, + { .name ="char (bad)" , .fails =1 , .cfg =CFG "CONFIG_CHAR=q\n" }, + { .name ="char (empty)" , .fails =1 , .cfg =CFG "CONFIG_CHAR=\n" }, + { .name ="char (str)" , .fails =1 , .cfg =CFG "CONFIG_CHAR=\"y\"\n" }, +/* STRING */ + { .name ="str (empty)" , .cfg =CFG "CONFIG_STR=\"\"\n" , + .data = { .str_val ="\0\0\0\0\0\0\0" } }, + { .name ="str (padded)" , .cfg =CFG "CONFIG_STR=\"abra\"\n" , + .data = { .str_val ="abra\0\0\0" } }, + { .name ="str (no value)" , .fails =1 , .cfg =CFG "CONFIG_STR=\n" }, + { .name ="str (bad value)" , .fails =1 , .cfg =CFG "CONFIG_STR=bla\n" }, + { .name ="str (too long)" , .fails =1 , .cfg =CFG "CONFIG_STR=\"abracada\"\n" }, +/* INTEGERS */ + { + .name ="integer forms" , + .cfg =CFG +"CONFIG_CHAR=0xA\n" +"CONFIG_USHORT=0462\n" +"CONFIG_INT=-100\n" +"CONFIG_ULONG=+1000000000000" , + .data = { + .char_val =0xA , + .ushort_val =0462 , + .int_val =-100 , + .ulong_val =1000000000000 , + }, + }, + { .name ="int (bad)" , .fails =1 , .cfg =CFG "CONFIG_INT=abc" }, + { .name ="int (str)" , .fails =1 , .cfg =CFG "CONFIG_INT=\"abc\"" }, + { .name ="int (empty)" , .fails =1 , .cfg =CFG "CONFIG_INT=" }, + { .name ="int (mixed)" , .fails =1 , .cfg =CFG "CONFIG_INT=123abc" }, + { .name ="int (max)" , .cfg =CFG "CONFIG_INT=2147483647" , + .data = { .int_val =2147483647 } }, + { .name ="int (min)" , .cfg =CFG "CONFIG_INT=-2147483648" , + .data = { .int_val =-2147483648 } }, + { .name ="int (max+1)" , .fails =1 , .cfg =CFG "CONFIG_INT=2147483648" }, + { .name ="int (min-1)" , .fails =1 , .cfg =CFG "CONFIG_INT=-2147483649" }, + { .name ="ushort (max)" , .cfg =CFG "CONFIG_USHORT=65535" , + .data = { .ushort_val =65535 } }, + { .name ="ushort (min)" , .cfg =CFG "CONFIG_USHORT=0" , + .data = { .ushort_val =0 } }, + { .name ="ushort (max+1)" , .fails =1 , .cfg =CFG "CONFIG_USHORT=65536" }, + { .name ="ushort (min-1)" , .fails =1 , .cfg =CFG "CONFIG_USHORT=-1" }, + { .name ="u64 (max)" , .cfg =CFG "CONFIG_ULONG=0xffffffffffffffff" , + .data = { .ulong_val =0xffffffffffffffff } }, + { .name ="u64 (min)" , .cfg =CFG "CONFIG_ULONG=0" , + .data = { .ulong_val =0 } }, + { .name ="u64 (max+1)" , .fails =1 , .cfg =CFG "CONFIG_ULONG=0x10000000000000000" }, +}; + +BPF_EMBED_OBJ (core_extern,"test_core_extern.o" ); + +void test_core_extern (void ) +{ +const uint32_t kern_ver =get_kernel_version (); +int err, duration =0 , i, j; +struct test_core_extern *skel =NULL ; +uint64_t *got, *exp; +int n =sizeof (*skel->data) /sizeof (uint64_t ); + +for (i =0 ; i <ARRAY_SIZE (test_cases); i++) { +char tmp_cfg_path[] ="/tmp/test_core_extern_cfg.XXXXXX" ; +struct test_case *t = &test_cases[i]; +DECLARE_LIBBPF_OPTS (bpf_object_open_opts, opts, + .kconfig_path = t->cfg_path, + ); + +if (!test__start_subtest (t->name)) +continue ; + +if (t->cfg) { +size_t n =strlen (t->cfg) +1 ; +int fd =mkstemp (tmp_cfg_path); +int written; + +if (CHECK (fd <0 ,"mkstemp" ,"errno: %d\n" , errno)) +continue ; +printf ("using '%s' as config file\n" , tmp_cfg_path); + written =write (fd, t->cfg, n); +close (fd); +if (CHECK_FAIL (written != n)) + goto cleanup; + opts.kconfig_path = tmp_cfg_path; + } + + skel =test_core_extern__open_opts (&core_extern_embed, &opts); +if (CHECK (!skel,"skel_open" ,"skeleton open failed\n" )) + goto cleanup; + err =test_core_extern__load (skel); +if (t->fails) { +CHECK (!err,"skel_load" , +"shouldn't succeed open/load of skeleton\n" ); + goto cleanup; + }else if (CHECK (err,"skel_load" , +"failed to open/load skeleton\n" )) { + goto cleanup; + } + err =test_core_extern__attach (skel); +if (CHECK (err,"attach_raw_tp" ,"failed attach: %d\n" , err)) + goto cleanup; + +usleep (1 ); + + t->data.kern_ver = kern_ver; + t->data.missing_val =0xDEADC0DE ; + got = (uint64_t *)skel->data; + exp = (uint64_t *)&t->data; +for (j =0 ; j < n; j++) { +CHECK (got[j] != exp[j],"check_res" , +"result #%d: expected %lx, but got %lx\n" , + j, exp[j], got[j]); + } +cleanup: +if (t->cfg) +unlink (tmp_cfg_path); +test_core_extern__destroy (skel); + skel =NULL ; + } +}
tools/testing/selftests/bpf/prog_tests/skeleton.c +17 -1
@@ -15,11 +15,21 @@ void test_skeleton(void)int duration =0 , err;struct test_skeleton * skel;struct test_skeleton__bss *bss; +struct test_skeleton__externs *exts; - skel =test_skeleton__open_and_load (&skeleton_embed); + skel =test_skeleton__open (&skeleton_embed);if (CHECK (!skel,"skel_open" ,"failed to open skeleton\n" ))return ; +printf ("EXTERNS BEFORE: %p\n" , skel->externs); +if (CHECK (skel->externs,"skel_externs" ,"externs are mmaped()!\n" )) + goto cleanup; + + err =test_skeleton__load (skel); +if (CHECK (err,"skel_load" ,"failed to load skeleton: %d\n" , err)) + goto cleanup; +printf ("EXTERNS AFTER: %p\n" , skel->externs); + bss = skel->bss; bss->in1 =1 ; bss->in2 =2 ;
@@ -27,6 +37,7 @@ void test_skeleton(void) bss->in4 =4 ; bss->in5.a =5 ; bss->in5.b =6 ; + exts = skel->externs; err =test_skeleton__attach (skel);if (CHECK (err,"skel_attach" ,"skeleton attach failed: %d\n" , err))
@@ -44,6 +55,11 @@ void test_skeleton(void)CHECK (bss->handler_out5.b !=6 ,"res6" ,"got %lld != exp %d\n" , bss->handler_out5.b,6 ); +CHECK (bss->bpf_syscall != exts->CONFIG_BPF_SYSCALL,"ext1" , +"got %d != exp %d\n" , bss->bpf_syscall, exts->CONFIG_BPF_SYSCALL); +CHECK (bss->kern_ver != exts->LINUX_KERNEL_VERSION,"ext2" , +"got %d != exp %d\n" , bss->kern_ver, exts->LINUX_KERNEL_VERSION); + cleanup:test_skeleton__destroy (skel); }
tools/testing/selftests/bpf/progs/test_core_extern.c new file +62 -0
62 lines not on this page · raw message
tools/testing/selftests/bpf/progs/test_skeleton.c +9 -0
@@ -1,6 +1,7 @@// SPDX-License-Identifier: GPL-2.0 // Copyright (c) 2017 Facebook +#include <stdbool.h> #include <linux/bpf.h> #include "bpf_helpers.h"
@@ -20,6 +21,10 @@ char out3 = 0;long long out4 =0 ;int out1 =0 ; +extern bool CONFIG_BPF_SYSCALL ; +extern int LINUX_KERNEL_VERSION ; +bool bpf_syscall =0 ; +int kern_ver =0 ; SEC("raw_tp/sys_enter")int handler (const void *ctx)
@@ -31,6 +36,10 @@ int handler(const void *ctx) out3 = in3; out4 = in4; out5 = in5; + + bpf_syscall =CONFIG_BPF_SYSCALL ; + kern_ver =LINUX_KERNEL_VERSION ; +return 0 ; }
Signature · 1 line
2.17.1