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

libbpf: Optimized return value in libbpf_strerror when errno is libbpf errno

This is a small improvement in libbpf_strerror. When libbpf_strerror
is used to obtain the system error description, if the length of the
buf is insufficient, libbpf_sterror returns ERANGE and sets errno to
ERANGE.

However, this processing is not performed when the error code
customized by libbpf is obtained. Make some minor improvements here,
return -ERANGE and set errno to ERANGE when buf is not enough for
custom description.

Signed-off-by: Xin Liu <liuxin350@huawei.com>
Signed-off-by: Andrii Nakryiko <andrii@kernel.org>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
Link: https://lore.kernel.org/bpf/20221210082045.233697-1-liuxin350@huawei.com

authored by

Xin Liu and committed by
Daniel Borkmann
c9883ee9 7e68dd7d

+12 -4
+12 -4
tools/lib/bpf/libbpf_errno.c
··· 39 39 40 40 int libbpf_strerror(int err, char *buf, size_t size) 41 41 { 42 + int ret; 43 + 42 44 if (!buf || !size) 43 45 return libbpf_err(-EINVAL); 44 46 45 47 err = err > 0 ? err : -err; 46 48 47 49 if (err < __LIBBPF_ERRNO__START) { 48 - int ret; 49 - 50 50 ret = strerror_r(err, buf, size); 51 51 buf[size - 1] = '\0'; 52 52 return libbpf_err_errno(ret); ··· 56 56 const char *msg; 57 57 58 58 msg = libbpf_strerror_table[ERRNO_OFFSET(err)]; 59 - snprintf(buf, size, "%s", msg); 59 + ret = snprintf(buf, size, "%s", msg); 60 60 buf[size - 1] = '\0'; 61 + /* The length of the buf and msg is positive. 62 + * A negative number may be returned only when the 63 + * size exceeds INT_MAX. Not likely to appear. 64 + */ 65 + if (ret >= size) 66 + return libbpf_err(-ERANGE); 61 67 return 0; 62 68 } 63 69 64 - snprintf(buf, size, "Unknown libbpf error %d", err); 70 + ret = snprintf(buf, size, "Unknown libbpf error %d", err); 65 71 buf[size - 1] = '\0'; 72 + if (ret >= size) 73 + return libbpf_err(-ERANGE); 66 74 return libbpf_err(-ENOENT); 67 75 }