xref: /openbmc/linux/tools/lib/bpf/libbpf_internal.h (revision 82df5b73)
1 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 
3 /*
4  * Internal libbpf helpers.
5  *
6  * Copyright (c) 2019 Facebook
7  */
8 
9 #ifndef __LIBBPF_LIBBPF_INTERNAL_H
10 #define __LIBBPF_LIBBPF_INTERNAL_H
11 
12 #include "libbpf.h"
13 
14 #define BTF_INFO_ENC(kind, kind_flag, vlen) \
15 	((!!(kind_flag) << 31) | ((kind) << 24) | ((vlen) & BTF_MAX_VLEN))
16 #define BTF_TYPE_ENC(name, info, size_or_type) (name), (info), (size_or_type)
17 #define BTF_INT_ENC(encoding, bits_offset, nr_bits) \
18 	((encoding) << 24 | (bits_offset) << 16 | (nr_bits))
19 #define BTF_TYPE_INT_ENC(name, encoding, bits_offset, bits, sz) \
20 	BTF_TYPE_ENC(name, BTF_INFO_ENC(BTF_KIND_INT, 0, 0), sz), \
21 	BTF_INT_ENC(encoding, bits_offset, bits)
22 #define BTF_MEMBER_ENC(name, type, bits_offset) (name), (type), (bits_offset)
23 #define BTF_PARAM_ENC(name, type) (name), (type)
24 #define BTF_VAR_SECINFO_ENC(type, offset, size) (type), (offset), (size)
25 
26 #ifndef min
27 # define min(x, y) ((x) < (y) ? (x) : (y))
28 #endif
29 #ifndef max
30 # define max(x, y) ((x) < (y) ? (y) : (x))
31 #endif
32 #ifndef offsetofend
33 # define offsetofend(TYPE, FIELD) \
34 	(offsetof(TYPE, FIELD) + sizeof(((TYPE *)0)->FIELD))
35 #endif
36 
37 /* Symbol versioning is different between static and shared library.
38  * Properly versioned symbols are needed for shared library, but
39  * only the symbol of the new version is needed for static library.
40  */
41 #ifdef SHARED
42 # define COMPAT_VERSION(internal_name, api_name, version) \
43 	asm(".symver " #internal_name "," #api_name "@" #version);
44 # define DEFAULT_VERSION(internal_name, api_name, version) \
45 	asm(".symver " #internal_name "," #api_name "@@" #version);
46 #else
47 # define COMPAT_VERSION(internal_name, api_name, version)
48 # define DEFAULT_VERSION(internal_name, api_name, version) \
49 	extern typeof(internal_name) api_name \
50 	__attribute__((alias(#internal_name)));
51 #endif
52 
53 extern void libbpf_print(enum libbpf_print_level level,
54 			 const char *format, ...)
55 	__attribute__((format(printf, 2, 3)));
56 
57 #define __pr(level, fmt, ...)	\
58 do {				\
59 	libbpf_print(level, "libbpf: " fmt, ##__VA_ARGS__);	\
60 } while (0)
61 
62 #define pr_warn(fmt, ...)	__pr(LIBBPF_WARN, fmt, ##__VA_ARGS__)
63 #define pr_info(fmt, ...)	__pr(LIBBPF_INFO, fmt, ##__VA_ARGS__)
64 #define pr_debug(fmt, ...)	__pr(LIBBPF_DEBUG, fmt, ##__VA_ARGS__)
65 
66 static inline bool libbpf_validate_opts(const char *opts,
67 					size_t opts_sz, size_t user_sz,
68 					const char *type_name)
69 {
70 	if (user_sz < sizeof(size_t)) {
71 		pr_warn("%s size (%zu) is too small\n", type_name, user_sz);
72 		return false;
73 	}
74 	if (user_sz > opts_sz) {
75 		size_t i;
76 
77 		for (i = opts_sz; i < user_sz; i++) {
78 			if (opts[i]) {
79 				pr_warn("%s has non-zero extra bytes\n",
80 					type_name);
81 				return false;
82 			}
83 		}
84 	}
85 	return true;
86 }
87 
88 #define OPTS_VALID(opts, type)						      \
89 	(!(opts) || libbpf_validate_opts((const char *)opts,		      \
90 					 offsetofend(struct type,	      \
91 						     type##__last_field),     \
92 					 (opts)->sz, #type))
93 #define OPTS_HAS(opts, field) \
94 	((opts) && opts->sz >= offsetofend(typeof(*(opts)), field))
95 #define OPTS_GET(opts, field, fallback_value) \
96 	(OPTS_HAS(opts, field) ? (opts)->field : fallback_value)
97 
98 int parse_cpu_mask_str(const char *s, bool **mask, int *mask_sz);
99 int parse_cpu_mask_file(const char *fcpu, bool **mask, int *mask_sz);
100 int libbpf__load_raw_btf(const char *raw_types, size_t types_len,
101 			 const char *str_sec, size_t str_len);
102 
103 int bpf_object__section_size(const struct bpf_object *obj, const char *name,
104 			     __u32 *size);
105 int bpf_object__variable_offset(const struct bpf_object *obj, const char *name,
106 				__u32 *off);
107 
108 struct nlattr;
109 typedef int (*libbpf_dump_nlmsg_t)(void *cookie, void *msg, struct nlattr **tb);
110 int libbpf_netlink_open(unsigned int *nl_pid);
111 int libbpf_nl_get_link(int sock, unsigned int nl_pid,
112 		       libbpf_dump_nlmsg_t dump_link_nlmsg, void *cookie);
113 int libbpf_nl_get_class(int sock, unsigned int nl_pid, int ifindex,
114 			libbpf_dump_nlmsg_t dump_class_nlmsg, void *cookie);
115 int libbpf_nl_get_qdisc(int sock, unsigned int nl_pid, int ifindex,
116 			libbpf_dump_nlmsg_t dump_qdisc_nlmsg, void *cookie);
117 int libbpf_nl_get_filter(int sock, unsigned int nl_pid, int ifindex, int handle,
118 			 libbpf_dump_nlmsg_t dump_filter_nlmsg, void *cookie);
119 
120 struct btf_ext_info {
121 	/*
122 	 * info points to the individual info section (e.g. func_info and
123 	 * line_info) from the .BTF.ext. It does not include the __u32 rec_size.
124 	 */
125 	void *info;
126 	__u32 rec_size;
127 	__u32 len;
128 };
129 
130 #define for_each_btf_ext_sec(seg, sec)					\
131 	for (sec = (seg)->info;						\
132 	     (void *)sec < (seg)->info + (seg)->len;			\
133 	     sec = (void *)sec + sizeof(struct btf_ext_info_sec) +	\
134 		   (seg)->rec_size * sec->num_info)
135 
136 #define for_each_btf_ext_rec(seg, sec, i, rec)				\
137 	for (i = 0, rec = (void *)&(sec)->data;				\
138 	     i < (sec)->num_info;					\
139 	     i++, rec = (void *)rec + (seg)->rec_size)
140 
141 struct btf_ext {
142 	union {
143 		struct btf_ext_header *hdr;
144 		void *data;
145 	};
146 	struct btf_ext_info func_info;
147 	struct btf_ext_info line_info;
148 	struct btf_ext_info field_reloc_info;
149 	__u32 data_size;
150 };
151 
152 struct btf_ext_info_sec {
153 	__u32	sec_name_off;
154 	__u32	num_info;
155 	/* Followed by num_info * record_size number of bytes */
156 	__u8	data[];
157 };
158 
159 /* The minimum bpf_func_info checked by the loader */
160 struct bpf_func_info_min {
161 	__u32   insn_off;
162 	__u32   type_id;
163 };
164 
165 /* The minimum bpf_line_info checked by the loader */
166 struct bpf_line_info_min {
167 	__u32	insn_off;
168 	__u32	file_name_off;
169 	__u32	line_off;
170 	__u32	line_col;
171 };
172 
173 /* bpf_field_info_kind encodes which aspect of captured field has to be
174  * adjusted by relocations. Currently supported values are:
175  *   - BPF_FIELD_BYTE_OFFSET: field offset (in bytes);
176  *   - BPF_FIELD_EXISTS: field existence (1, if field exists; 0, otherwise);
177  */
178 enum bpf_field_info_kind {
179 	BPF_FIELD_BYTE_OFFSET = 0,	/* field byte offset */
180 	BPF_FIELD_BYTE_SIZE = 1,
181 	BPF_FIELD_EXISTS = 2,		/* field existence in target kernel */
182 	BPF_FIELD_SIGNED = 3,
183 	BPF_FIELD_LSHIFT_U64 = 4,
184 	BPF_FIELD_RSHIFT_U64 = 5,
185 };
186 
187 /* The minimum bpf_field_reloc checked by the loader
188  *
189  * Field relocation captures the following data:
190  * - insn_off - instruction offset (in bytes) within a BPF program that needs
191  *   its insn->imm field to be relocated with actual field info;
192  * - type_id - BTF type ID of the "root" (containing) entity of a relocatable
193  *   field;
194  * - access_str_off - offset into corresponding .BTF string section. String
195  *   itself encodes an accessed field using a sequence of field and array
196  *   indicies, separated by colon (:). It's conceptually very close to LLVM's
197  *   getelementptr ([0]) instruction's arguments for identifying offset to
198  *   a field.
199  *
200  * Example to provide a better feel.
201  *
202  *   struct sample {
203  *       int a;
204  *       struct {
205  *           int b[10];
206  *       };
207  *   };
208  *
209  *   struct sample *s = ...;
210  *   int x = &s->a;     // encoded as "0:0" (a is field #0)
211  *   int y = &s->b[5];  // encoded as "0:1:0:5" (anon struct is field #1,
212  *                      // b is field #0 inside anon struct, accessing elem #5)
213  *   int z = &s[10]->b; // encoded as "10:1" (ptr is used as an array)
214  *
215  * type_id for all relocs in this example  will capture BTF type id of
216  * `struct sample`.
217  *
218  * Such relocation is emitted when using __builtin_preserve_access_index()
219  * Clang built-in, passing expression that captures field address, e.g.:
220  *
221  * bpf_probe_read(&dst, sizeof(dst),
222  *		  __builtin_preserve_access_index(&src->a.b.c));
223  *
224  * In this case Clang will emit field relocation recording necessary data to
225  * be able to find offset of embedded `a.b.c` field within `src` struct.
226  *
227  *   [0] https://llvm.org/docs/LangRef.html#getelementptr-instruction
228  */
229 struct bpf_field_reloc {
230 	__u32   insn_off;
231 	__u32   type_id;
232 	__u32   access_str_off;
233 	enum bpf_field_info_kind kind;
234 };
235 
236 #endif /* __LIBBPF_LIBBPF_INTERNAL_H */
237