xref: /openbmc/linux/tools/lib/bpf/libbpf_errno.c (revision de528723)
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 
3 /*
4  * Copyright (C) 2013-2015 Alexei Starovoitov <ast@kernel.org>
5  * Copyright (C) 2015 Wang Nan <wangnan0@huawei.com>
6  * Copyright (C) 2015 Huawei Inc.
7  * Copyright (C) 2017 Nicira, Inc.
8  */
9 
10 #undef _GNU_SOURCE
11 #include <stdio.h>
12 #include <string.h>
13 
14 #include "libbpf.h"
15 
16 #define ERRNO_OFFSET(e)		((e) - __LIBBPF_ERRNO__START)
17 #define ERRCODE_OFFSET(c)	ERRNO_OFFSET(LIBBPF_ERRNO__##c)
18 #define NR_ERRNO	(__LIBBPF_ERRNO__END - __LIBBPF_ERRNO__START)
19 
20 static const char *libbpf_strerror_table[NR_ERRNO] = {
21 	[ERRCODE_OFFSET(LIBELF)]	= "Something wrong in libelf",
22 	[ERRCODE_OFFSET(FORMAT)]	= "BPF object format invalid",
23 	[ERRCODE_OFFSET(KVERSION)]	= "'version' section incorrect or lost",
24 	[ERRCODE_OFFSET(ENDIAN)]	= "Endian mismatch",
25 	[ERRCODE_OFFSET(INTERNAL)]	= "Internal error in libbpf",
26 	[ERRCODE_OFFSET(RELOC)]		= "Relocation failed",
27 	[ERRCODE_OFFSET(VERIFY)]	= "Kernel verifier blocks program loading",
28 	[ERRCODE_OFFSET(PROG2BIG)]	= "Program too big",
29 	[ERRCODE_OFFSET(KVER)]		= "Incorrect kernel version",
30 	[ERRCODE_OFFSET(PROGTYPE)]	= "Kernel doesn't support this program type",
31 	[ERRCODE_OFFSET(WRNGPID)]	= "Wrong pid in netlink message",
32 	[ERRCODE_OFFSET(INVSEQ)]	= "Invalid netlink sequence",
33 	[ERRCODE_OFFSET(NLPARSE)]	= "Incorrect netlink message parsing",
34 };
35 
36 int libbpf_strerror(int err, char *buf, size_t size)
37 {
38 	if (!buf || !size)
39 		return -1;
40 
41 	err = err > 0 ? err : -err;
42 
43 	if (err < __LIBBPF_ERRNO__START) {
44 		int ret;
45 
46 		ret = strerror_r(err, buf, size);
47 		buf[size - 1] = '\0';
48 		return ret;
49 	}
50 
51 	if (err < __LIBBPF_ERRNO__END) {
52 		const char *msg;
53 
54 		msg = libbpf_strerror_table[ERRNO_OFFSET(err)];
55 		snprintf(buf, size, "%s", msg);
56 		buf[size - 1] = '\0';
57 		return 0;
58 	}
59 
60 	snprintf(buf, size, "Unknown libbpf error %d", err);
61 	buf[size - 1] = '\0';
62 	return -1;
63 }
64