xref: /linux/tools/lib/bpf/libbpf_errno.c (revision 9494a6c2e4f6ce21a1e6885145171f90c4492131)
1 // SPDX-License-Identifier: LGPL-2.1
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  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation;
12  * version 2.1 of the License (not later!)
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this program; if not,  see <http://www.gnu.org/licenses>
21  */
22 
23 #include <stdio.h>
24 #include <string.h>
25 
26 #include "libbpf.h"
27 
28 #define ERRNO_OFFSET(e)		((e) - __LIBBPF_ERRNO__START)
29 #define ERRCODE_OFFSET(c)	ERRNO_OFFSET(LIBBPF_ERRNO__##c)
30 #define NR_ERRNO	(__LIBBPF_ERRNO__END - __LIBBPF_ERRNO__START)
31 
32 static const char *libbpf_strerror_table[NR_ERRNO] = {
33 	[ERRCODE_OFFSET(LIBELF)]	= "Something wrong in libelf",
34 	[ERRCODE_OFFSET(FORMAT)]	= "BPF object format invalid",
35 	[ERRCODE_OFFSET(KVERSION)]	= "'version' section incorrect or lost",
36 	[ERRCODE_OFFSET(ENDIAN)]	= "Endian mismatch",
37 	[ERRCODE_OFFSET(INTERNAL)]	= "Internal error in libbpf",
38 	[ERRCODE_OFFSET(RELOC)]		= "Relocation failed",
39 	[ERRCODE_OFFSET(VERIFY)]	= "Kernel verifier blocks program loading",
40 	[ERRCODE_OFFSET(PROG2BIG)]	= "Program too big",
41 	[ERRCODE_OFFSET(KVER)]		= "Incorrect kernel version",
42 	[ERRCODE_OFFSET(PROGTYPE)]	= "Kernel doesn't support this program type",
43 	[ERRCODE_OFFSET(WRNGPID)]	= "Wrong pid in netlink message",
44 	[ERRCODE_OFFSET(INVSEQ)]	= "Invalid netlink sequence",
45 	[ERRCODE_OFFSET(NLPARSE)]	= "Incorrect netlink message parsing",
46 };
47 
48 int libbpf_strerror(int err, char *buf, size_t size)
49 {
50 	if (!buf || !size)
51 		return -1;
52 
53 	err = err > 0 ? err : -err;
54 
55 	if (err < __LIBBPF_ERRNO__START) {
56 		int ret;
57 
58 		ret = strerror_r(err, buf, size);
59 		buf[size - 1] = '\0';
60 		return ret;
61 	}
62 
63 	if (err < __LIBBPF_ERRNO__END) {
64 		const char *msg;
65 
66 		msg = libbpf_strerror_table[ERRNO_OFFSET(err)];
67 		snprintf(buf, size, "%s", msg);
68 		buf[size - 1] = '\0';
69 		return 0;
70 	}
71 
72 	snprintf(buf, size, "Unknown libbpf error %d", err);
73 	buf[size - 1] = '\0';
74 	return -1;
75 }
76