Introduction
If the code has uninitialized variable(s), the compiler may take advantage of it
by assuming any value to generate final code which may not be what user expects.
The flags “-Wall -Werror” intends to issue warnings for such cases. But currently
compiler may not issue such warnings in some cases.
In the BPF context, the generated buggy code will be load into the kernel and
likely verification will pass. When the bpf program actually runs, its result
may not be expected and user will then need to check source or asm code to
find reasons. So ideally users really want to get a signal during compilation
where compiler has taken advantage of some uninitialized variables for its
transformation.
A Test Case
Marc Suñé (Isovalent, part of Cisco) reported this issue where an uninitialized
variable caused generated bpf prog binary code not working as expected. See
clang_bpf/Makefile at main · msune/clang_bpf · GitHub
The flags “-Wall -Werror” are enabled, but there is no warning.
The following is a simple code using latest upstram clang20:
$ cat test.c
void bar(int *val) {
int n = *val;
for (int i = 0; i < 5; i++) {
switch(n) {
case 0:
case 1:
return;
case 2:
n = 3; break;
default:
*val = n; return;
}
}
return;
}
int foo(void) {
int val;
bar(&val);
if (val == 1) return 6;
return 8;
}
$ clang --target=bpf -O2 -g -c -Wall -Werror test.c
$ llvm-objdump --no-show-raw-insn -d test.o
test.o: file format elf64-bpf
Disassembly of section .text:
0000000000000000 <bar>:
0: w2 = *(u32 *)(r1 + 0x0)
1: if w2 < 0x2 goto +0x3 <bar+0x28>
2: if w2 != 0x2 goto +0x1 <bar+0x20>
3: w2 = 0x3
4: *(u32 *)(r1 + 0x0) = w2
5: exit
0000000000000030 <foo>:
6: w0 = 0x8
7: exit
You can see that even with “-Wall -Werror”, there is no warning.
Possible Solutions
The ideal case is that compiler issue warnings with uninitialized variables.
“-Wall -Werror” implies “-Wunitialized”. gcc has “-Wmaybe-unitialized” which
dumps out possible unitialized variables. Could clang supports this whenever
an unitialized variable may impact generted codes?
Another option is option “-fsanitize=undefined”. Currently it is not clear how
this can be supported in bpf. So compiler warnings are still preferred.
Any other suggestions are also welcome.