Re: [PATCH bpf-next] selftests/bpf: remove string.h includes in bpf progs

Alexei Starovoitov
2026-04-22T00:57:17Z

On Tue Apr 21, 2026 at 5:15 PM PDT, David Faust wrote:
>
>
> On 4/21/26 14:07, Alexei Starovoitov wrote:
>> On Tue Apr 21, 2026 at 1:22 PM PDT, David Faust wrote:
>>> Sources for some BPF test programs currently include string.h, which
>>> is a glibc header and not a toolchain header. Since there is no BPF
>>> glibc, this means it is the native system glibc string.h which gets
>>> included when building the test programs.
>>>
>>> In all cases the include is only necessary for the prototypes of
>>> non-builtin versions of memset, memcpy, etc., and in every case both
>>> clang and gcc already replace these with the compiler built-in versions
>>> and expand them inline.
>>>
>>> In the case of gcc this replacement happens after initial debuginfo is
>>> generated, which includes the calls to the glibc routines. This means a
>>> BTF record for e.g. 'extern memset' is emitted, resulting in load
>>> failures like:
>>>
>>> libbpf: BTF loading error: -22
>>> ...
>>> [26] FUNC memset type_id=1 Invalid func linkage
>>
>> ...
>>
>>> - memcpy(&val, keys, sizeof(val));
>>> + __builtin_memcpy(&val, keys, sizeof(val));
>>
>> This is not an option. It works for llvm because it inlines it for small sizes.
>> GCC should do the same.
>
> GCC does the same inlining for small sizes.
> It is a bug in GCC that the FUNC record for the original is still emitted
> in this case, that shall be fixed.
>
>> For large sizes llvm will emit libcall to memset
>> that libbpf will error with "FUNC memset type_id=1 Invalid func linkage"
>> and that's a separate issue to deal with.
>
> It works now in both compilers (modulo above gcc bug) because at -O1 and above
> they recognize the memset/memcpy/etc. calls and attempt to replace them with
> builtin versions and expand inline.
> If the size is too big or non-constant, they will both fall back on libcalls.
>
> My point is that it is essentially working by chance, only because the compilers
> do this optimization. The progs as written are including a libc header, using
> routines from that header, but not linking to any actual implementation of
> those routines that they use.

No. It's not "by chance". It's working, because compilers have to do this optimization.
Just like
static void *(* const bpf_map_lookup_elem)(void *map, const void *key) = (void *) 1;
hack.
It "works" because compilers perform a set of optimizations.
There is no luck here. Compilers have to transform the code in a certain way
that the verifier expects.
BPF doesn't work with -O0. Just like kernel won't boot if compiled with -O0.
One can argue that kernel is working at -O2 "by chance" as well.

> Changing to __builtin versions makes the current behavior explicit.

Nope. Not doing gcc's helper_call extension either.