bpf_map__fd() handles NULL map gracefully and returns -EINVAL.
bpf_program__fd() and bpf_program__nth_fd() crash in this case.
Make the behaviour more consistent by validating prog pointer
as well.

Signed-off-by: Jakub Kicinski <[email protected]>
Reviewed-by: Quentin Monnet <[email protected]>
---
 tools/lib/bpf/libbpf.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/tools/lib/bpf/libbpf.c b/tools/lib/bpf/libbpf.c
index 955f8eafbf41..afa9860db755 100644
--- a/tools/lib/bpf/libbpf.c
+++ b/tools/lib/bpf/libbpf.c
@@ -1991,6 +1991,9 @@ int bpf_program__nth_fd(struct bpf_program *prog, int n)
 {
        int fd;
 
+       if (!prog)
+               return -EINVAL;
+
        if (n >= prog->instances.nr || n < 0) {
                pr_warning("Can't get the %dth fd from program %s: only %d 
instances\n",
                           n, prog->section_name, prog->instances.nr);
-- 
2.17.1

Reply via email to