Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

bpftool: btf: Validate root_type_ids early

Handle invalid root_type_ids early, as an invalid ID will cause dumpers
to half-emit valid boilerplate and then bail with an unclean exit. This
is ugly and possibly confusing for users, so preemptively handle the
common error case before any dumping begins.

Signed-off-by: Daniel Xu <dxu@dxuuu.xyz>
Signed-off-by: Andrii Nakryiko <andrii@kernel.org>
Reviewed-by: Quentin Monnet <qmo@kernel.org>
Link: https://lore.kernel.org/bpf/33e09a08a6072f8381cb976218a009709309b7e1.1734119028.git.dxu@dxuuu.xyz

authored by

Daniel Xu and committed by
Andrii Nakryiko
7f5819e1 5e3ad22d

+12
+12
tools/bpf/bpftool/btf.c
··· 886 886 const char *src; 887 887 int fd = -1; 888 888 int err = 0; 889 + int i; 889 890 890 891 if (!REQ_ARGS(2)) { 891 892 usage(); ··· 1014 1013 if (!btf) { 1015 1014 err = -errno; 1016 1015 p_err("get btf by id (%u): %s", btf_id, strerror(errno)); 1016 + goto done; 1017 + } 1018 + } 1019 + 1020 + /* Invalid root IDs causes half emitted boilerplate and then unclean 1021 + * exit. It's an ugly user experience, so handle common error here. 1022 + */ 1023 + for (i = 0; i < root_type_cnt; i++) { 1024 + if (root_type_ids[i] >= btf__type_cnt(btf)) { 1025 + err = -EINVAL; 1026 + p_err("invalid root ID: %u", root_type_ids[i]); 1017 1027 goto done; 1018 1028 } 1019 1029 }