OSDN Git Service

libbpf: Fix BTF-to-C converter's padding logic
authorAndrii Nakryiko <andrii@kernel.org>
Mon, 12 Dec 2022 21:15:04 +0000 (13:15 -0800)
committerDaniel Borkmann <daniel@iogearbox.net>
Wed, 14 Dec 2022 23:05:13 +0000 (00:05 +0100)
commitea2ce1ba99aa6a60c8d8a706e3abadf3de372163
treee1c485474b3bfcf0e19267caece0e3d3de68656a
parent25a4481b4136af7794e1df2d6c90ed2f354d60ce
libbpf: Fix BTF-to-C converter's padding logic

Turns out that btf_dump API doesn't handle a bunch of tricky corner
cases, as reported by Per, and further discovered using his testing
Python script ([0]).

This patch revamps btf_dump's padding logic significantly, making it
more correct and also avoiding unnecessary explicit padding, where
compiler would pad naturally. This overall topic turned out to be very
tricky and subtle, there are lots of subtle corner cases. The comments
in the code tries to give some clues, but comments themselves are
supposed to be paired with good understanding of C alignment and padding
rules. Plus some experimentation to figure out subtle things like
whether `long :0;` means that struct is now forced to be long-aligned
(no, it's not, turns out).

Anyways, Per's script, while not completely correct in some known
situations, doesn't show any obvious cases where this logic breaks, so
this is a nice improvement over the previous state of this logic.

Some selftests had to be adjusted to accommodate better use of natural
alignment rules, eliminating some unnecessary padding, or changing it to
`type: 0;` alignment markers.

Note also that for when we are in between bitfields, we emit explicit
bit size, while otherwise we use `: 0`, this feels much more natural in
practice.

Next patch will add few more test cases, found through randomized Per's
script.

  [0] https://lore.kernel.org/bpf/85f83c333f5355c8ac026f835b18d15060725fcb.camel@ericsson.com/

Reported-by: Per Sundström XP <per.xp.sundstrom@ericsson.com>
Signed-off-by: Andrii Nakryiko <andrii@kernel.org>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Link: https://lore.kernel.org/bpf/20221212211505.558851-6-andrii@kernel.org
tools/lib/bpf/btf_dump.c
tools/testing/selftests/bpf/progs/btf_dump_test_case_bitfields.c
tools/testing/selftests/bpf/progs/btf_dump_test_case_padding.c