• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
2 /* Copyright (c) 2018 Facebook */
3 
4 #include <byteswap.h>
5 #include <endian.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <errno.h>
12 #include <sys/utsname.h>
13 #include <sys/param.h>
14 #include <sys/stat.h>
15 #include <linux/kernel.h>
16 #include <linux/err.h>
17 #include <linux/btf.h>
18 #include <gelf.h>
19 #include "btf.h"
20 #include "bpf.h"
21 #include "libbpf.h"
22 #include "libbpf_internal.h"
23 #include "hashmap.h"
24 #include "strset.h"
25 
26 #define BTF_MAX_NR_TYPES 0x7fffffffU
27 #define BTF_MAX_STR_OFFSET 0x7fffffffU
28 
29 static struct btf_type btf_void;
30 
31 struct btf {
32 	/* raw BTF data in native endianness */
33 	void *raw_data;
34 	/* raw BTF data in non-native endianness */
35 	void *raw_data_swapped;
36 	__u32 raw_size;
37 	/* whether target endianness differs from the native one */
38 	bool swapped_endian;
39 
40 	/*
41 	 * When BTF is loaded from an ELF or raw memory it is stored
42 	 * in a contiguous memory block. The hdr, type_data, and, strs_data
43 	 * point inside that memory region to their respective parts of BTF
44 	 * representation:
45 	 *
46 	 * +--------------------------------+
47 	 * |  Header  |  Types  |  Strings  |
48 	 * +--------------------------------+
49 	 * ^          ^         ^
50 	 * |          |         |
51 	 * hdr        |         |
52 	 * types_data-+         |
53 	 * strs_data------------+
54 	 *
55 	 * If BTF data is later modified, e.g., due to types added or
56 	 * removed, BTF deduplication performed, etc, this contiguous
57 	 * representation is broken up into three independently allocated
58 	 * memory regions to be able to modify them independently.
59 	 * raw_data is nulled out at that point, but can be later allocated
60 	 * and cached again if user calls btf__get_raw_data(), at which point
61 	 * raw_data will contain a contiguous copy of header, types, and
62 	 * strings:
63 	 *
64 	 * +----------+  +---------+  +-----------+
65 	 * |  Header  |  |  Types  |  |  Strings  |
66 	 * +----------+  +---------+  +-----------+
67 	 * ^             ^            ^
68 	 * |             |            |
69 	 * hdr           |            |
70 	 * types_data----+            |
71 	 * strset__data(strs_set)-----+
72 	 *
73 	 *               +----------+---------+-----------+
74 	 *               |  Header  |  Types  |  Strings  |
75 	 * raw_data----->+----------+---------+-----------+
76 	 */
77 	struct btf_header *hdr;
78 
79 	void *types_data;
80 	size_t types_data_cap; /* used size stored in hdr->type_len */
81 
82 	/* type ID to `struct btf_type *` lookup index
83 	 * type_offs[0] corresponds to the first non-VOID type:
84 	 *   - for base BTF it's type [1];
85 	 *   - for split BTF it's the first non-base BTF type.
86 	 */
87 	__u32 *type_offs;
88 	size_t type_offs_cap;
89 	/* number of types in this BTF instance:
90 	 *   - doesn't include special [0] void type;
91 	 *   - for split BTF counts number of types added on top of base BTF.
92 	 */
93 	__u32 nr_types;
94 	/* if not NULL, points to the base BTF on top of which the current
95 	 * split BTF is based
96 	 */
97 	struct btf *base_btf;
98 	/* BTF type ID of the first type in this BTF instance:
99 	 *   - for base BTF it's equal to 1;
100 	 *   - for split BTF it's equal to biggest type ID of base BTF plus 1.
101 	 */
102 	int start_id;
103 	/* logical string offset of this BTF instance:
104 	 *   - for base BTF it's equal to 0;
105 	 *   - for split BTF it's equal to total size of base BTF's string section size.
106 	 */
107 	int start_str_off;
108 
109 	/* only one of strs_data or strs_set can be non-NULL, depending on
110 	 * whether BTF is in a modifiable state (strs_set is used) or not
111 	 * (strs_data points inside raw_data)
112 	 */
113 	void *strs_data;
114 	/* a set of unique strings */
115 	struct strset *strs_set;
116 	/* whether strings are already deduplicated */
117 	bool strs_deduped;
118 
119 	/* BTF object FD, if loaded into kernel */
120 	int fd;
121 
122 	/* Pointer size (in bytes) for a target architecture of this BTF */
123 	int ptr_sz;
124 };
125 
ptr_to_u64(const void * ptr)126 static inline __u64 ptr_to_u64(const void *ptr)
127 {
128 	return (__u64) (unsigned long) ptr;
129 }
130 
131 /* Ensure given dynamically allocated memory region pointed to by *data* with
132  * capacity of *cap_cnt* elements each taking *elem_sz* bytes has enough
133  * memory to accomodate *add_cnt* new elements, assuming *cur_cnt* elements
134  * are already used. At most *max_cnt* elements can be ever allocated.
135  * If necessary, memory is reallocated and all existing data is copied over,
136  * new pointer to the memory region is stored at *data, new memory region
137  * capacity (in number of elements) is stored in *cap.
138  * On success, memory pointer to the beginning of unused memory is returned.
139  * On error, NULL is returned.
140  */
libbpf_add_mem(void ** data,size_t * cap_cnt,size_t elem_sz,size_t cur_cnt,size_t max_cnt,size_t add_cnt)141 void *libbpf_add_mem(void **data, size_t *cap_cnt, size_t elem_sz,
142 		     size_t cur_cnt, size_t max_cnt, size_t add_cnt)
143 {
144 	size_t new_cnt;
145 	void *new_data;
146 
147 	if (cur_cnt + add_cnt <= *cap_cnt)
148 		return *data + cur_cnt * elem_sz;
149 
150 	/* requested more than the set limit */
151 	if (cur_cnt + add_cnt > max_cnt)
152 		return NULL;
153 
154 	new_cnt = *cap_cnt;
155 	new_cnt += new_cnt / 4;		  /* expand by 25% */
156 	if (new_cnt < 16)		  /* but at least 16 elements */
157 		new_cnt = 16;
158 	if (new_cnt > max_cnt)		  /* but not exceeding a set limit */
159 		new_cnt = max_cnt;
160 	if (new_cnt < cur_cnt + add_cnt)  /* also ensure we have enough memory */
161 		new_cnt = cur_cnt + add_cnt;
162 
163 	new_data = libbpf_reallocarray(*data, new_cnt, elem_sz);
164 	if (!new_data)
165 		return NULL;
166 
167 	/* zero out newly allocated portion of memory */
168 	memset(new_data + (*cap_cnt) * elem_sz, 0, (new_cnt - *cap_cnt) * elem_sz);
169 
170 	*data = new_data;
171 	*cap_cnt = new_cnt;
172 	return new_data + cur_cnt * elem_sz;
173 }
174 
175 /* Ensure given dynamically allocated memory region has enough allocated space
176  * to accommodate *need_cnt* elements of size *elem_sz* bytes each
177  */
libbpf_ensure_mem(void ** data,size_t * cap_cnt,size_t elem_sz,size_t need_cnt)178 int libbpf_ensure_mem(void **data, size_t *cap_cnt, size_t elem_sz, size_t need_cnt)
179 {
180 	void *p;
181 
182 	if (need_cnt <= *cap_cnt)
183 		return 0;
184 
185 	p = libbpf_add_mem(data, cap_cnt, elem_sz, *cap_cnt, SIZE_MAX, need_cnt - *cap_cnt);
186 	if (!p)
187 		return -ENOMEM;
188 
189 	return 0;
190 }
191 
btf_add_type_idx_entry(struct btf * btf,__u32 type_off)192 static int btf_add_type_idx_entry(struct btf *btf, __u32 type_off)
193 {
194 	__u32 *p;
195 
196 	p = libbpf_add_mem((void **)&btf->type_offs, &btf->type_offs_cap, sizeof(__u32),
197 			   btf->nr_types, BTF_MAX_NR_TYPES, 1);
198 	if (!p)
199 		return -ENOMEM;
200 
201 	*p = type_off;
202 	return 0;
203 }
204 
btf_bswap_hdr(struct btf_header * h)205 static void btf_bswap_hdr(struct btf_header *h)
206 {
207 	h->magic = bswap_16(h->magic);
208 	h->hdr_len = bswap_32(h->hdr_len);
209 	h->type_off = bswap_32(h->type_off);
210 	h->type_len = bswap_32(h->type_len);
211 	h->str_off = bswap_32(h->str_off);
212 	h->str_len = bswap_32(h->str_len);
213 }
214 
btf_parse_hdr(struct btf * btf)215 static int btf_parse_hdr(struct btf *btf)
216 {
217 	struct btf_header *hdr = btf->hdr;
218 	__u32 meta_left;
219 
220 	if (btf->raw_size < sizeof(struct btf_header)) {
221 		pr_debug("BTF header not found\n");
222 		return -EINVAL;
223 	}
224 
225 	if (hdr->magic == bswap_16(BTF_MAGIC)) {
226 		btf->swapped_endian = true;
227 		if (bswap_32(hdr->hdr_len) != sizeof(struct btf_header)) {
228 			pr_warn("Can't load BTF with non-native endianness due to unsupported header length %u\n",
229 				bswap_32(hdr->hdr_len));
230 			return -ENOTSUP;
231 		}
232 		btf_bswap_hdr(hdr);
233 	} else if (hdr->magic != BTF_MAGIC) {
234 		pr_debug("Invalid BTF magic: %x\n", hdr->magic);
235 		return -EINVAL;
236 	}
237 
238 	if (btf->raw_size < hdr->hdr_len) {
239 		pr_debug("BTF header len %u larger than data size %u\n",
240 			 hdr->hdr_len, btf->raw_size);
241 		return -EINVAL;
242 	}
243 
244 	meta_left = btf->raw_size - hdr->hdr_len;
245 	if (meta_left < (long long)hdr->str_off + hdr->str_len) {
246 		pr_debug("Invalid BTF total size: %u\n", btf->raw_size);
247 		return -EINVAL;
248 	}
249 
250 	if ((long long)hdr->type_off + hdr->type_len > hdr->str_off) {
251 		pr_debug("Invalid BTF data sections layout: type data at %u + %u, strings data at %u + %u\n",
252 			 hdr->type_off, hdr->type_len, hdr->str_off, hdr->str_len);
253 		return -EINVAL;
254 	}
255 
256 	if (hdr->type_off % 4) {
257 		pr_debug("BTF type section is not aligned to 4 bytes\n");
258 		return -EINVAL;
259 	}
260 
261 	return 0;
262 }
263 
btf_parse_str_sec(struct btf * btf)264 static int btf_parse_str_sec(struct btf *btf)
265 {
266 	const struct btf_header *hdr = btf->hdr;
267 	const char *start = btf->strs_data;
268 	const char *end = start + btf->hdr->str_len;
269 
270 	if (btf->base_btf && hdr->str_len == 0)
271 		return 0;
272 	if (!hdr->str_len || hdr->str_len - 1 > BTF_MAX_STR_OFFSET || end[-1]) {
273 		pr_debug("Invalid BTF string section\n");
274 		return -EINVAL;
275 	}
276 	if (!btf->base_btf && start[0]) {
277 		pr_debug("Invalid BTF string section\n");
278 		return -EINVAL;
279 	}
280 	return 0;
281 }
282 
btf_type_size(const struct btf_type * t)283 static int btf_type_size(const struct btf_type *t)
284 {
285 	const int base_size = sizeof(struct btf_type);
286 	__u16 vlen = btf_vlen(t);
287 
288 	switch (btf_kind(t)) {
289 	case BTF_KIND_FWD:
290 	case BTF_KIND_CONST:
291 	case BTF_KIND_VOLATILE:
292 	case BTF_KIND_RESTRICT:
293 	case BTF_KIND_PTR:
294 	case BTF_KIND_TYPEDEF:
295 	case BTF_KIND_FUNC:
296 	case BTF_KIND_FLOAT:
297 		return base_size;
298 	case BTF_KIND_INT:
299 		return base_size + sizeof(__u32);
300 	case BTF_KIND_ENUM:
301 		return base_size + vlen * sizeof(struct btf_enum);
302 	case BTF_KIND_ARRAY:
303 		return base_size + sizeof(struct btf_array);
304 	case BTF_KIND_STRUCT:
305 	case BTF_KIND_UNION:
306 		return base_size + vlen * sizeof(struct btf_member);
307 	case BTF_KIND_FUNC_PROTO:
308 		return base_size + vlen * sizeof(struct btf_param);
309 	case BTF_KIND_VAR:
310 		return base_size + sizeof(struct btf_var);
311 	case BTF_KIND_DATASEC:
312 		return base_size + vlen * sizeof(struct btf_var_secinfo);
313 	default:
314 		pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t));
315 		return -EINVAL;
316 	}
317 }
318 
btf_bswap_type_base(struct btf_type * t)319 static void btf_bswap_type_base(struct btf_type *t)
320 {
321 	t->name_off = bswap_32(t->name_off);
322 	t->info = bswap_32(t->info);
323 	t->type = bswap_32(t->type);
324 }
325 
btf_bswap_type_rest(struct btf_type * t)326 static int btf_bswap_type_rest(struct btf_type *t)
327 {
328 	struct btf_var_secinfo *v;
329 	struct btf_member *m;
330 	struct btf_array *a;
331 	struct btf_param *p;
332 	struct btf_enum *e;
333 	__u16 vlen = btf_vlen(t);
334 	int i;
335 
336 	switch (btf_kind(t)) {
337 	case BTF_KIND_FWD:
338 	case BTF_KIND_CONST:
339 	case BTF_KIND_VOLATILE:
340 	case BTF_KIND_RESTRICT:
341 	case BTF_KIND_PTR:
342 	case BTF_KIND_TYPEDEF:
343 	case BTF_KIND_FUNC:
344 	case BTF_KIND_FLOAT:
345 		return 0;
346 	case BTF_KIND_INT:
347 		*(__u32 *)(t + 1) = bswap_32(*(__u32 *)(t + 1));
348 		return 0;
349 	case BTF_KIND_ENUM:
350 		for (i = 0, e = btf_enum(t); i < vlen; i++, e++) {
351 			e->name_off = bswap_32(e->name_off);
352 			e->val = bswap_32(e->val);
353 		}
354 		return 0;
355 	case BTF_KIND_ARRAY:
356 		a = btf_array(t);
357 		a->type = bswap_32(a->type);
358 		a->index_type = bswap_32(a->index_type);
359 		a->nelems = bswap_32(a->nelems);
360 		return 0;
361 	case BTF_KIND_STRUCT:
362 	case BTF_KIND_UNION:
363 		for (i = 0, m = btf_members(t); i < vlen; i++, m++) {
364 			m->name_off = bswap_32(m->name_off);
365 			m->type = bswap_32(m->type);
366 			m->offset = bswap_32(m->offset);
367 		}
368 		return 0;
369 	case BTF_KIND_FUNC_PROTO:
370 		for (i = 0, p = btf_params(t); i < vlen; i++, p++) {
371 			p->name_off = bswap_32(p->name_off);
372 			p->type = bswap_32(p->type);
373 		}
374 		return 0;
375 	case BTF_KIND_VAR:
376 		btf_var(t)->linkage = bswap_32(btf_var(t)->linkage);
377 		return 0;
378 	case BTF_KIND_DATASEC:
379 		for (i = 0, v = btf_var_secinfos(t); i < vlen; i++, v++) {
380 			v->type = bswap_32(v->type);
381 			v->offset = bswap_32(v->offset);
382 			v->size = bswap_32(v->size);
383 		}
384 		return 0;
385 	default:
386 		pr_debug("Unsupported BTF_KIND:%u\n", btf_kind(t));
387 		return -EINVAL;
388 	}
389 }
390 
btf_parse_type_sec(struct btf * btf)391 static int btf_parse_type_sec(struct btf *btf)
392 {
393 	struct btf_header *hdr = btf->hdr;
394 	void *next_type = btf->types_data;
395 	void *end_type = next_type + hdr->type_len;
396 	int err, type_size;
397 
398 	while (next_type + sizeof(struct btf_type) <= end_type) {
399 		if (btf->swapped_endian)
400 			btf_bswap_type_base(next_type);
401 
402 		type_size = btf_type_size(next_type);
403 		if (type_size < 0)
404 			return type_size;
405 		if (next_type + type_size > end_type) {
406 			pr_warn("BTF type [%d] is malformed\n", btf->start_id + btf->nr_types);
407 			return -EINVAL;
408 		}
409 
410 		if (btf->swapped_endian && btf_bswap_type_rest(next_type))
411 			return -EINVAL;
412 
413 		err = btf_add_type_idx_entry(btf, next_type - btf->types_data);
414 		if (err)
415 			return err;
416 
417 		next_type += type_size;
418 		btf->nr_types++;
419 	}
420 
421 	if (next_type != end_type) {
422 		pr_warn("BTF types data is malformed\n");
423 		return -EINVAL;
424 	}
425 
426 	return 0;
427 }
428 
btf__get_nr_types(const struct btf * btf)429 __u32 btf__get_nr_types(const struct btf *btf)
430 {
431 	return btf->start_id + btf->nr_types - 1;
432 }
433 
btf__base_btf(const struct btf * btf)434 const struct btf *btf__base_btf(const struct btf *btf)
435 {
436 	return btf->base_btf;
437 }
438 
439 /* internal helper returning non-const pointer to a type */
btf_type_by_id(struct btf * btf,__u32 type_id)440 struct btf_type *btf_type_by_id(struct btf *btf, __u32 type_id)
441 {
442 	if (type_id == 0)
443 		return &btf_void;
444 	if (type_id < btf->start_id)
445 		return btf_type_by_id(btf->base_btf, type_id);
446 	return btf->types_data + btf->type_offs[type_id - btf->start_id];
447 }
448 
btf__type_by_id(const struct btf * btf,__u32 type_id)449 const struct btf_type *btf__type_by_id(const struct btf *btf, __u32 type_id)
450 {
451 	if (type_id >= btf->start_id + btf->nr_types)
452 		return errno = EINVAL, NULL;
453 	return btf_type_by_id((struct btf *)btf, type_id);
454 }
455 
determine_ptr_size(const struct btf * btf)456 static int determine_ptr_size(const struct btf *btf)
457 {
458 	const struct btf_type *t;
459 	const char *name;
460 	int i, n;
461 
462 	if (btf->base_btf && btf->base_btf->ptr_sz > 0)
463 		return btf->base_btf->ptr_sz;
464 
465 	n = btf__get_nr_types(btf);
466 	for (i = 1; i <= n; i++) {
467 		t = btf__type_by_id(btf, i);
468 		if (!btf_is_int(t))
469 			continue;
470 
471 		name = btf__name_by_offset(btf, t->name_off);
472 		if (!name)
473 			continue;
474 
475 		if (strcmp(name, "long int") == 0 ||
476 		    strcmp(name, "long unsigned int") == 0) {
477 			if (t->size != 4 && t->size != 8)
478 				continue;
479 			return t->size;
480 		}
481 	}
482 
483 	return -1;
484 }
485 
btf_ptr_sz(const struct btf * btf)486 static size_t btf_ptr_sz(const struct btf *btf)
487 {
488 	if (!btf->ptr_sz)
489 		((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
490 	return btf->ptr_sz < 0 ? sizeof(void *) : btf->ptr_sz;
491 }
492 
493 /* Return pointer size this BTF instance assumes. The size is heuristically
494  * determined by looking for 'long' or 'unsigned long' integer type and
495  * recording its size in bytes. If BTF type information doesn't have any such
496  * type, this function returns 0. In the latter case, native architecture's
497  * pointer size is assumed, so will be either 4 or 8, depending on
498  * architecture that libbpf was compiled for. It's possible to override
499  * guessed value by using btf__set_pointer_size() API.
500  */
btf__pointer_size(const struct btf * btf)501 size_t btf__pointer_size(const struct btf *btf)
502 {
503 	if (!btf->ptr_sz)
504 		((struct btf *)btf)->ptr_sz = determine_ptr_size(btf);
505 
506 	if (btf->ptr_sz < 0)
507 		/* not enough BTF type info to guess */
508 		return 0;
509 
510 	return btf->ptr_sz;
511 }
512 
513 /* Override or set pointer size in bytes. Only values of 4 and 8 are
514  * supported.
515  */
btf__set_pointer_size(struct btf * btf,size_t ptr_sz)516 int btf__set_pointer_size(struct btf *btf, size_t ptr_sz)
517 {
518 	if (ptr_sz != 4 && ptr_sz != 8)
519 		return libbpf_err(-EINVAL);
520 	btf->ptr_sz = ptr_sz;
521 	return 0;
522 }
523 
is_host_big_endian(void)524 static bool is_host_big_endian(void)
525 {
526 #if __BYTE_ORDER == __LITTLE_ENDIAN
527 	return false;
528 #elif __BYTE_ORDER == __BIG_ENDIAN
529 	return true;
530 #else
531 # error "Unrecognized __BYTE_ORDER__"
532 #endif
533 }
534 
btf__endianness(const struct btf * btf)535 enum btf_endianness btf__endianness(const struct btf *btf)
536 {
537 	if (is_host_big_endian())
538 		return btf->swapped_endian ? BTF_LITTLE_ENDIAN : BTF_BIG_ENDIAN;
539 	else
540 		return btf->swapped_endian ? BTF_BIG_ENDIAN : BTF_LITTLE_ENDIAN;
541 }
542 
btf__set_endianness(struct btf * btf,enum btf_endianness endian)543 int btf__set_endianness(struct btf *btf, enum btf_endianness endian)
544 {
545 	if (endian != BTF_LITTLE_ENDIAN && endian != BTF_BIG_ENDIAN)
546 		return libbpf_err(-EINVAL);
547 
548 	btf->swapped_endian = is_host_big_endian() != (endian == BTF_BIG_ENDIAN);
549 	if (!btf->swapped_endian) {
550 		free(btf->raw_data_swapped);
551 		btf->raw_data_swapped = NULL;
552 	}
553 	return 0;
554 }
555 
btf_type_is_void(const struct btf_type * t)556 static bool btf_type_is_void(const struct btf_type *t)
557 {
558 	return t == &btf_void || btf_is_fwd(t);
559 }
560 
btf_type_is_void_or_null(const struct btf_type * t)561 static bool btf_type_is_void_or_null(const struct btf_type *t)
562 {
563 	return !t || btf_type_is_void(t);
564 }
565 
566 #define MAX_RESOLVE_DEPTH 32
567 
btf__resolve_size(const struct btf * btf,__u32 type_id)568 __s64 btf__resolve_size(const struct btf *btf, __u32 type_id)
569 {
570 	const struct btf_array *array;
571 	const struct btf_type *t;
572 	__u32 nelems = 1;
573 	__s64 size = -1;
574 	int i;
575 
576 	t = btf__type_by_id(btf, type_id);
577 	for (i = 0; i < MAX_RESOLVE_DEPTH && !btf_type_is_void_or_null(t); i++) {
578 		switch (btf_kind(t)) {
579 		case BTF_KIND_INT:
580 		case BTF_KIND_STRUCT:
581 		case BTF_KIND_UNION:
582 		case BTF_KIND_ENUM:
583 		case BTF_KIND_DATASEC:
584 		case BTF_KIND_FLOAT:
585 			size = t->size;
586 			goto done;
587 		case BTF_KIND_PTR:
588 			size = btf_ptr_sz(btf);
589 			goto done;
590 		case BTF_KIND_TYPEDEF:
591 		case BTF_KIND_VOLATILE:
592 		case BTF_KIND_CONST:
593 		case BTF_KIND_RESTRICT:
594 		case BTF_KIND_VAR:
595 			type_id = t->type;
596 			break;
597 		case BTF_KIND_ARRAY:
598 			array = btf_array(t);
599 			if (nelems && array->nelems > UINT32_MAX / nelems)
600 				return libbpf_err(-E2BIG);
601 			nelems *= array->nelems;
602 			type_id = array->type;
603 			break;
604 		default:
605 			return libbpf_err(-EINVAL);
606 		}
607 
608 		t = btf__type_by_id(btf, type_id);
609 	}
610 
611 done:
612 	if (size < 0)
613 		return libbpf_err(-EINVAL);
614 	if (nelems && size > UINT32_MAX / nelems)
615 		return libbpf_err(-E2BIG);
616 
617 	return nelems * size;
618 }
619 
btf__align_of(const struct btf * btf,__u32 id)620 int btf__align_of(const struct btf *btf, __u32 id)
621 {
622 	const struct btf_type *t = btf__type_by_id(btf, id);
623 	__u16 kind = btf_kind(t);
624 
625 	switch (kind) {
626 	case BTF_KIND_INT:
627 	case BTF_KIND_ENUM:
628 	case BTF_KIND_FLOAT:
629 		return min(btf_ptr_sz(btf), (size_t)t->size);
630 	case BTF_KIND_PTR:
631 		return btf_ptr_sz(btf);
632 	case BTF_KIND_TYPEDEF:
633 	case BTF_KIND_VOLATILE:
634 	case BTF_KIND_CONST:
635 	case BTF_KIND_RESTRICT:
636 		return btf__align_of(btf, t->type);
637 	case BTF_KIND_ARRAY:
638 		return btf__align_of(btf, btf_array(t)->type);
639 	case BTF_KIND_STRUCT:
640 	case BTF_KIND_UNION: {
641 		const struct btf_member *m = btf_members(t);
642 		__u16 vlen = btf_vlen(t);
643 		int i, max_align = 1, align;
644 
645 		for (i = 0; i < vlen; i++, m++) {
646 			align = btf__align_of(btf, m->type);
647 			if (align <= 0)
648 				return libbpf_err(align);
649 			max_align = max(max_align, align);
650 
651 			/* if field offset isn't aligned according to field
652 			 * type's alignment, then struct must be packed
653 			 */
654 			if (btf_member_bitfield_size(t, i) == 0 &&
655 			    (m->offset % (8 * align)) != 0)
656 				return 1;
657 		}
658 
659 		/* if struct/union size isn't a multiple of its alignment,
660 		 * then struct must be packed
661 		 */
662 		if ((t->size % max_align) != 0)
663 			return 1;
664 
665 		return max_align;
666 	}
667 	default:
668 		pr_warn("unsupported BTF_KIND:%u\n", btf_kind(t));
669 		return errno = EINVAL, 0;
670 	}
671 }
672 
btf__resolve_type(const struct btf * btf,__u32 type_id)673 int btf__resolve_type(const struct btf *btf, __u32 type_id)
674 {
675 	const struct btf_type *t;
676 	int depth = 0;
677 
678 	t = btf__type_by_id(btf, type_id);
679 	while (depth < MAX_RESOLVE_DEPTH &&
680 	       !btf_type_is_void_or_null(t) &&
681 	       (btf_is_mod(t) || btf_is_typedef(t) || btf_is_var(t))) {
682 		type_id = t->type;
683 		t = btf__type_by_id(btf, type_id);
684 		depth++;
685 	}
686 
687 	if (depth == MAX_RESOLVE_DEPTH || btf_type_is_void_or_null(t))
688 		return libbpf_err(-EINVAL);
689 
690 	return type_id;
691 }
692 
btf__find_by_name(const struct btf * btf,const char * type_name)693 __s32 btf__find_by_name(const struct btf *btf, const char *type_name)
694 {
695 	__u32 i, nr_types = btf__get_nr_types(btf);
696 
697 	if (!strcmp(type_name, "void"))
698 		return 0;
699 
700 	for (i = 1; i <= nr_types; i++) {
701 		const struct btf_type *t = btf__type_by_id(btf, i);
702 		const char *name = btf__name_by_offset(btf, t->name_off);
703 
704 		if (name && !strcmp(type_name, name))
705 			return i;
706 	}
707 
708 	return libbpf_err(-ENOENT);
709 }
710 
btf__find_by_name_kind(const struct btf * btf,const char * type_name,__u32 kind)711 __s32 btf__find_by_name_kind(const struct btf *btf, const char *type_name,
712 			     __u32 kind)
713 {
714 	__u32 i, nr_types = btf__get_nr_types(btf);
715 
716 	if (kind == BTF_KIND_UNKN || !strcmp(type_name, "void"))
717 		return 0;
718 
719 	for (i = 1; i <= nr_types; i++) {
720 		const struct btf_type *t = btf__type_by_id(btf, i);
721 		const char *name;
722 
723 		if (btf_kind(t) != kind)
724 			continue;
725 		name = btf__name_by_offset(btf, t->name_off);
726 		if (name && !strcmp(type_name, name))
727 			return i;
728 	}
729 
730 	return libbpf_err(-ENOENT);
731 }
732 
btf_is_modifiable(const struct btf * btf)733 static bool btf_is_modifiable(const struct btf *btf)
734 {
735 	return (void *)btf->hdr != btf->raw_data;
736 }
737 
btf__free(struct btf * btf)738 void btf__free(struct btf *btf)
739 {
740 	if (IS_ERR_OR_NULL(btf))
741 		return;
742 
743 	if (btf->fd >= 0)
744 		close(btf->fd);
745 
746 	if (btf_is_modifiable(btf)) {
747 		/* if BTF was modified after loading, it will have a split
748 		 * in-memory representation for header, types, and strings
749 		 * sections, so we need to free all of them individually. It
750 		 * might still have a cached contiguous raw data present,
751 		 * which will be unconditionally freed below.
752 		 */
753 		free(btf->hdr);
754 		free(btf->types_data);
755 		strset__free(btf->strs_set);
756 	}
757 	free(btf->raw_data);
758 	free(btf->raw_data_swapped);
759 	free(btf->type_offs);
760 	free(btf);
761 }
762 
btf_new_empty(struct btf * base_btf)763 static struct btf *btf_new_empty(struct btf *base_btf)
764 {
765 	struct btf *btf;
766 
767 	btf = calloc(1, sizeof(*btf));
768 	if (!btf)
769 		return ERR_PTR(-ENOMEM);
770 
771 	btf->nr_types = 0;
772 	btf->start_id = 1;
773 	btf->start_str_off = 0;
774 	btf->fd = -1;
775 	btf->ptr_sz = sizeof(void *);
776 	btf->swapped_endian = false;
777 
778 	if (base_btf) {
779 		btf->base_btf = base_btf;
780 		btf->start_id = btf__get_nr_types(base_btf) + 1;
781 		btf->start_str_off = base_btf->hdr->str_len;
782 	}
783 
784 	/* +1 for empty string at offset 0 */
785 	btf->raw_size = sizeof(struct btf_header) + (base_btf ? 0 : 1);
786 	btf->raw_data = calloc(1, btf->raw_size);
787 	if (!btf->raw_data) {
788 		free(btf);
789 		return ERR_PTR(-ENOMEM);
790 	}
791 
792 	btf->hdr = btf->raw_data;
793 	btf->hdr->hdr_len = sizeof(struct btf_header);
794 	btf->hdr->magic = BTF_MAGIC;
795 	btf->hdr->version = BTF_VERSION;
796 
797 	btf->types_data = btf->raw_data + btf->hdr->hdr_len;
798 	btf->strs_data = btf->raw_data + btf->hdr->hdr_len;
799 	btf->hdr->str_len = base_btf ? 0 : 1; /* empty string at offset 0 */
800 
801 	return btf;
802 }
803 
btf__new_empty(void)804 struct btf *btf__new_empty(void)
805 {
806 	return libbpf_ptr(btf_new_empty(NULL));
807 }
808 
btf__new_empty_split(struct btf * base_btf)809 struct btf *btf__new_empty_split(struct btf *base_btf)
810 {
811 	return libbpf_ptr(btf_new_empty(base_btf));
812 }
813 
btf_new(const void * data,__u32 size,struct btf * base_btf)814 static struct btf *btf_new(const void *data, __u32 size, struct btf *base_btf)
815 {
816 	struct btf *btf;
817 	int err;
818 
819 	btf = calloc(1, sizeof(struct btf));
820 	if (!btf)
821 		return ERR_PTR(-ENOMEM);
822 
823 	btf->nr_types = 0;
824 	btf->start_id = 1;
825 	btf->start_str_off = 0;
826 	btf->fd = -1;
827 
828 	if (base_btf) {
829 		btf->base_btf = base_btf;
830 		btf->start_id = btf__get_nr_types(base_btf) + 1;
831 		btf->start_str_off = base_btf->hdr->str_len;
832 	}
833 
834 	btf->raw_data = malloc(size);
835 	if (!btf->raw_data) {
836 		err = -ENOMEM;
837 		goto done;
838 	}
839 	memcpy(btf->raw_data, data, size);
840 	btf->raw_size = size;
841 
842 	btf->hdr = btf->raw_data;
843 	err = btf_parse_hdr(btf);
844 	if (err)
845 		goto done;
846 
847 	btf->strs_data = btf->raw_data + btf->hdr->hdr_len + btf->hdr->str_off;
848 	btf->types_data = btf->raw_data + btf->hdr->hdr_len + btf->hdr->type_off;
849 
850 	err = btf_parse_str_sec(btf);
851 	err = err ?: btf_parse_type_sec(btf);
852 	if (err)
853 		goto done;
854 
855 done:
856 	if (err) {
857 		btf__free(btf);
858 		return ERR_PTR(err);
859 	}
860 
861 	return btf;
862 }
863 
btf__new(const void * data,__u32 size)864 struct btf *btf__new(const void *data, __u32 size)
865 {
866 	return libbpf_ptr(btf_new(data, size, NULL));
867 }
868 
btf_parse_elf(const char * path,struct btf * base_btf,struct btf_ext ** btf_ext)869 static struct btf *btf_parse_elf(const char *path, struct btf *base_btf,
870 				 struct btf_ext **btf_ext)
871 {
872 	Elf_Data *btf_data = NULL, *btf_ext_data = NULL;
873 	int err = 0, fd = -1, idx = 0;
874 	struct btf *btf = NULL;
875 	Elf_Scn *scn = NULL;
876 	Elf *elf = NULL;
877 	GElf_Ehdr ehdr;
878 	size_t shstrndx;
879 
880 	if (elf_version(EV_CURRENT) == EV_NONE) {
881 		pr_warn("failed to init libelf for %s\n", path);
882 		return ERR_PTR(-LIBBPF_ERRNO__LIBELF);
883 	}
884 
885 	fd = open(path, O_RDONLY);
886 	if (fd < 0) {
887 		err = -errno;
888 		pr_warn("failed to open %s: %s\n", path, strerror(errno));
889 		return ERR_PTR(err);
890 	}
891 
892 	err = -LIBBPF_ERRNO__FORMAT;
893 
894 	elf = elf_begin(fd, ELF_C_READ, NULL);
895 	if (!elf) {
896 		pr_warn("failed to open %s as ELF file\n", path);
897 		goto done;
898 	}
899 	if (!gelf_getehdr(elf, &ehdr)) {
900 		pr_warn("failed to get EHDR from %s\n", path);
901 		goto done;
902 	}
903 
904 	if (elf_getshdrstrndx(elf, &shstrndx)) {
905 		pr_warn("failed to get section names section index for %s\n",
906 			path);
907 		goto done;
908 	}
909 
910 	if (!elf_rawdata(elf_getscn(elf, shstrndx), NULL)) {
911 		pr_warn("failed to get e_shstrndx from %s\n", path);
912 		goto done;
913 	}
914 
915 	while ((scn = elf_nextscn(elf, scn)) != NULL) {
916 		GElf_Shdr sh;
917 		char *name;
918 
919 		idx++;
920 		if (gelf_getshdr(scn, &sh) != &sh) {
921 			pr_warn("failed to get section(%d) header from %s\n",
922 				idx, path);
923 			goto done;
924 		}
925 		name = elf_strptr(elf, shstrndx, sh.sh_name);
926 		if (!name) {
927 			pr_warn("failed to get section(%d) name from %s\n",
928 				idx, path);
929 			goto done;
930 		}
931 		if (strcmp(name, BTF_ELF_SEC) == 0) {
932 			btf_data = elf_getdata(scn, 0);
933 			if (!btf_data) {
934 				pr_warn("failed to get section(%d, %s) data from %s\n",
935 					idx, name, path);
936 				goto done;
937 			}
938 			continue;
939 		} else if (btf_ext && strcmp(name, BTF_EXT_ELF_SEC) == 0) {
940 			btf_ext_data = elf_getdata(scn, 0);
941 			if (!btf_ext_data) {
942 				pr_warn("failed to get section(%d, %s) data from %s\n",
943 					idx, name, path);
944 				goto done;
945 			}
946 			continue;
947 		}
948 	}
949 
950 	err = 0;
951 
952 	if (!btf_data) {
953 		err = -ENOENT;
954 		goto done;
955 	}
956 	btf = btf_new(btf_data->d_buf, btf_data->d_size, base_btf);
957 	err = libbpf_get_error(btf);
958 	if (err)
959 		goto done;
960 
961 	switch (gelf_getclass(elf)) {
962 	case ELFCLASS32:
963 		btf__set_pointer_size(btf, 4);
964 		break;
965 	case ELFCLASS64:
966 		btf__set_pointer_size(btf, 8);
967 		break;
968 	default:
969 		pr_warn("failed to get ELF class (bitness) for %s\n", path);
970 		break;
971 	}
972 
973 	if (btf_ext && btf_ext_data) {
974 		*btf_ext = btf_ext__new(btf_ext_data->d_buf, btf_ext_data->d_size);
975 		err = libbpf_get_error(*btf_ext);
976 		if (err)
977 			goto done;
978 	} else if (btf_ext) {
979 		*btf_ext = NULL;
980 	}
981 done:
982 	if (elf)
983 		elf_end(elf);
984 	close(fd);
985 
986 	if (!err)
987 		return btf;
988 
989 	if (btf_ext)
990 		btf_ext__free(*btf_ext);
991 	btf__free(btf);
992 
993 	return ERR_PTR(err);
994 }
995 
btf__parse_elf(const char * path,struct btf_ext ** btf_ext)996 struct btf *btf__parse_elf(const char *path, struct btf_ext **btf_ext)
997 {
998 	return libbpf_ptr(btf_parse_elf(path, NULL, btf_ext));
999 }
1000 
btf__parse_elf_split(const char * path,struct btf * base_btf)1001 struct btf *btf__parse_elf_split(const char *path, struct btf *base_btf)
1002 {
1003 	return libbpf_ptr(btf_parse_elf(path, base_btf, NULL));
1004 }
1005 
btf_parse_raw(const char * path,struct btf * base_btf)1006 static struct btf *btf_parse_raw(const char *path, struct btf *base_btf)
1007 {
1008 	struct btf *btf = NULL;
1009 	void *data = NULL;
1010 	FILE *f = NULL;
1011 	__u16 magic;
1012 	int err = 0;
1013 	long sz;
1014 
1015 	f = fopen(path, "rb");
1016 	if (!f) {
1017 		err = -errno;
1018 		goto err_out;
1019 	}
1020 
1021 	/* check BTF magic */
1022 	if (fread(&magic, 1, sizeof(magic), f) < sizeof(magic)) {
1023 		err = -EIO;
1024 		goto err_out;
1025 	}
1026 	if (magic != BTF_MAGIC && magic != bswap_16(BTF_MAGIC)) {
1027 		/* definitely not a raw BTF */
1028 		err = -EPROTO;
1029 		goto err_out;
1030 	}
1031 
1032 	/* get file size */
1033 	if (fseek(f, 0, SEEK_END)) {
1034 		err = -errno;
1035 		goto err_out;
1036 	}
1037 	sz = ftell(f);
1038 	if (sz < 0) {
1039 		err = -errno;
1040 		goto err_out;
1041 	}
1042 	/* rewind to the start */
1043 	if (fseek(f, 0, SEEK_SET)) {
1044 		err = -errno;
1045 		goto err_out;
1046 	}
1047 
1048 	/* pre-alloc memory and read all of BTF data */
1049 	data = malloc(sz);
1050 	if (!data) {
1051 		err = -ENOMEM;
1052 		goto err_out;
1053 	}
1054 	if (fread(data, 1, sz, f) < sz) {
1055 		err = -EIO;
1056 		goto err_out;
1057 	}
1058 
1059 	/* finally parse BTF data */
1060 	btf = btf_new(data, sz, base_btf);
1061 
1062 err_out:
1063 	free(data);
1064 	if (f)
1065 		fclose(f);
1066 	return err ? ERR_PTR(err) : btf;
1067 }
1068 
btf__parse_raw(const char * path)1069 struct btf *btf__parse_raw(const char *path)
1070 {
1071 	return libbpf_ptr(btf_parse_raw(path, NULL));
1072 }
1073 
btf__parse_raw_split(const char * path,struct btf * base_btf)1074 struct btf *btf__parse_raw_split(const char *path, struct btf *base_btf)
1075 {
1076 	return libbpf_ptr(btf_parse_raw(path, base_btf));
1077 }
1078 
btf_parse(const char * path,struct btf * base_btf,struct btf_ext ** btf_ext)1079 static struct btf *btf_parse(const char *path, struct btf *base_btf, struct btf_ext **btf_ext)
1080 {
1081 	struct btf *btf;
1082 	int err;
1083 
1084 	if (btf_ext)
1085 		*btf_ext = NULL;
1086 
1087 	btf = btf_parse_raw(path, base_btf);
1088 	err = libbpf_get_error(btf);
1089 	if (!err)
1090 		return btf;
1091 	if (err != -EPROTO)
1092 		return ERR_PTR(err);
1093 	return btf_parse_elf(path, base_btf, btf_ext);
1094 }
1095 
btf__parse(const char * path,struct btf_ext ** btf_ext)1096 struct btf *btf__parse(const char *path, struct btf_ext **btf_ext)
1097 {
1098 	return libbpf_ptr(btf_parse(path, NULL, btf_ext));
1099 }
1100 
btf__parse_split(const char * path,struct btf * base_btf)1101 struct btf *btf__parse_split(const char *path, struct btf *base_btf)
1102 {
1103 	return libbpf_ptr(btf_parse(path, base_btf, NULL));
1104 }
1105 
compare_vsi_off(const void * _a,const void * _b)1106 static int compare_vsi_off(const void *_a, const void *_b)
1107 {
1108 	const struct btf_var_secinfo *a = _a;
1109 	const struct btf_var_secinfo *b = _b;
1110 
1111 	return a->offset - b->offset;
1112 }
1113 
btf_fixup_datasec(struct bpf_object * obj,struct btf * btf,struct btf_type * t)1114 static int btf_fixup_datasec(struct bpf_object *obj, struct btf *btf,
1115 			     struct btf_type *t)
1116 {
1117 	__u32 size = 0, off = 0, i, vars = btf_vlen(t);
1118 	const char *name = btf__name_by_offset(btf, t->name_off);
1119 	const struct btf_type *t_var;
1120 	struct btf_var_secinfo *vsi;
1121 	const struct btf_var *var;
1122 	int ret;
1123 
1124 	if (!name) {
1125 		pr_debug("No name found in string section for DATASEC kind.\n");
1126 		return -ENOENT;
1127 	}
1128 
1129 	/* .extern datasec size and var offsets were set correctly during
1130 	 * extern collection step, so just skip straight to sorting variables
1131 	 */
1132 	if (t->size)
1133 		goto sort_vars;
1134 
1135 	ret = bpf_object__section_size(obj, name, &size);
1136 	if (ret || !size || (t->size && t->size != size)) {
1137 		pr_debug("Invalid size for section %s: %u bytes\n", name, size);
1138 		return -ENOENT;
1139 	}
1140 
1141 	t->size = size;
1142 
1143 	for (i = 0, vsi = btf_var_secinfos(t); i < vars; i++, vsi++) {
1144 		t_var = btf__type_by_id(btf, vsi->type);
1145 		var = btf_var(t_var);
1146 
1147 		if (!btf_is_var(t_var)) {
1148 			pr_debug("Non-VAR type seen in section %s\n", name);
1149 			return -EINVAL;
1150 		}
1151 
1152 		if (var->linkage == BTF_VAR_STATIC)
1153 			continue;
1154 
1155 		name = btf__name_by_offset(btf, t_var->name_off);
1156 		if (!name) {
1157 			pr_debug("No name found in string section for VAR kind\n");
1158 			return -ENOENT;
1159 		}
1160 
1161 		ret = bpf_object__variable_offset(obj, name, &off);
1162 		if (ret) {
1163 			pr_debug("No offset found in symbol table for VAR %s\n",
1164 				 name);
1165 			return -ENOENT;
1166 		}
1167 
1168 		vsi->offset = off;
1169 	}
1170 
1171 sort_vars:
1172 	qsort(btf_var_secinfos(t), vars, sizeof(*vsi), compare_vsi_off);
1173 	return 0;
1174 }
1175 
btf__finalize_data(struct bpf_object * obj,struct btf * btf)1176 int btf__finalize_data(struct bpf_object *obj, struct btf *btf)
1177 {
1178 	int err = 0;
1179 	__u32 i;
1180 
1181 	for (i = 1; i <= btf->nr_types; i++) {
1182 		struct btf_type *t = btf_type_by_id(btf, i);
1183 
1184 		/* Loader needs to fix up some of the things compiler
1185 		 * couldn't get its hands on while emitting BTF. This
1186 		 * is section size and global variable offset. We use
1187 		 * the info from the ELF itself for this purpose.
1188 		 */
1189 		if (btf_is_datasec(t)) {
1190 			err = btf_fixup_datasec(obj, btf, t);
1191 			if (err)
1192 				break;
1193 		}
1194 	}
1195 
1196 	return libbpf_err(err);
1197 }
1198 
1199 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian);
1200 
btf__load_into_kernel(struct btf * btf)1201 int btf__load_into_kernel(struct btf *btf)
1202 {
1203 	__u32 log_buf_size = 0, raw_size;
1204 	char *log_buf = NULL;
1205 	void *raw_data;
1206 	int err = 0;
1207 
1208 	if (btf->fd >= 0)
1209 		return libbpf_err(-EEXIST);
1210 
1211 retry_load:
1212 	if (log_buf_size) {
1213 		log_buf = malloc(log_buf_size);
1214 		if (!log_buf)
1215 			return libbpf_err(-ENOMEM);
1216 
1217 		*log_buf = 0;
1218 	}
1219 
1220 	raw_data = btf_get_raw_data(btf, &raw_size, false);
1221 	if (!raw_data) {
1222 		err = -ENOMEM;
1223 		goto done;
1224 	}
1225 	/* cache native raw data representation */
1226 	btf->raw_size = raw_size;
1227 	btf->raw_data = raw_data;
1228 
1229 	btf->fd = bpf_load_btf(raw_data, raw_size, log_buf, log_buf_size, false);
1230 	if (btf->fd < 0) {
1231 		if (!log_buf || errno == ENOSPC) {
1232 			log_buf_size = max((__u32)BPF_LOG_BUF_SIZE,
1233 					   log_buf_size << 1);
1234 			free(log_buf);
1235 			goto retry_load;
1236 		}
1237 
1238 		err = -errno;
1239 		pr_warn("Error loading BTF: %s(%d)\n", strerror(errno), errno);
1240 		if (*log_buf)
1241 			pr_warn("%s\n", log_buf);
1242 		goto done;
1243 	}
1244 
1245 done:
1246 	free(log_buf);
1247 	return libbpf_err(err);
1248 }
1249 int btf__load(struct btf *) __attribute__((alias("btf__load_into_kernel")));
1250 
btf__fd(const struct btf * btf)1251 int btf__fd(const struct btf *btf)
1252 {
1253 	return btf->fd;
1254 }
1255 
btf__set_fd(struct btf * btf,int fd)1256 void btf__set_fd(struct btf *btf, int fd)
1257 {
1258 	btf->fd = fd;
1259 }
1260 
btf_strs_data(const struct btf * btf)1261 static const void *btf_strs_data(const struct btf *btf)
1262 {
1263 	return btf->strs_data ? btf->strs_data : strset__data(btf->strs_set);
1264 }
1265 
btf_get_raw_data(const struct btf * btf,__u32 * size,bool swap_endian)1266 static void *btf_get_raw_data(const struct btf *btf, __u32 *size, bool swap_endian)
1267 {
1268 	struct btf_header *hdr = btf->hdr;
1269 	struct btf_type *t;
1270 	void *data, *p;
1271 	__u32 data_sz;
1272 	int i;
1273 
1274 	data = swap_endian ? btf->raw_data_swapped : btf->raw_data;
1275 	if (data) {
1276 		*size = btf->raw_size;
1277 		return data;
1278 	}
1279 
1280 	data_sz = hdr->hdr_len + hdr->type_len + hdr->str_len;
1281 	data = calloc(1, data_sz);
1282 	if (!data)
1283 		return NULL;
1284 	p = data;
1285 
1286 	memcpy(p, hdr, hdr->hdr_len);
1287 	if (swap_endian)
1288 		btf_bswap_hdr(p);
1289 	p += hdr->hdr_len;
1290 
1291 	memcpy(p, btf->types_data, hdr->type_len);
1292 	if (swap_endian) {
1293 		for (i = 0; i < btf->nr_types; i++) {
1294 			t = p + btf->type_offs[i];
1295 			/* btf_bswap_type_rest() relies on native t->info, so
1296 			 * we swap base type info after we swapped all the
1297 			 * additional information
1298 			 */
1299 			if (btf_bswap_type_rest(t))
1300 				goto err_out;
1301 			btf_bswap_type_base(t);
1302 		}
1303 	}
1304 	p += hdr->type_len;
1305 
1306 	memcpy(p, btf_strs_data(btf), hdr->str_len);
1307 	p += hdr->str_len;
1308 
1309 	*size = data_sz;
1310 	return data;
1311 err_out:
1312 	free(data);
1313 	return NULL;
1314 }
1315 
btf__get_raw_data(const struct btf * btf_ro,__u32 * size)1316 const void *btf__get_raw_data(const struct btf *btf_ro, __u32 *size)
1317 {
1318 	struct btf *btf = (struct btf *)btf_ro;
1319 	__u32 data_sz;
1320 	void *data;
1321 
1322 	data = btf_get_raw_data(btf, &data_sz, btf->swapped_endian);
1323 	if (!data)
1324 		return errno = -ENOMEM, NULL;
1325 
1326 	btf->raw_size = data_sz;
1327 	if (btf->swapped_endian)
1328 		btf->raw_data_swapped = data;
1329 	else
1330 		btf->raw_data = data;
1331 	*size = data_sz;
1332 	return data;
1333 }
1334 
btf__str_by_offset(const struct btf * btf,__u32 offset)1335 const char *btf__str_by_offset(const struct btf *btf, __u32 offset)
1336 {
1337 	if (offset < btf->start_str_off)
1338 		return btf__str_by_offset(btf->base_btf, offset);
1339 	else if (offset - btf->start_str_off < btf->hdr->str_len)
1340 		return btf_strs_data(btf) + (offset - btf->start_str_off);
1341 	else
1342 		return errno = EINVAL, NULL;
1343 }
1344 
btf__name_by_offset(const struct btf * btf,__u32 offset)1345 const char *btf__name_by_offset(const struct btf *btf, __u32 offset)
1346 {
1347 	return btf__str_by_offset(btf, offset);
1348 }
1349 
btf_get_from_fd(int btf_fd,struct btf * base_btf)1350 struct btf *btf_get_from_fd(int btf_fd, struct btf *base_btf)
1351 {
1352 	struct bpf_btf_info btf_info;
1353 	__u32 len = sizeof(btf_info);
1354 	__u32 last_size;
1355 	struct btf *btf;
1356 	void *ptr;
1357 	int err;
1358 
1359 	/* we won't know btf_size until we call bpf_obj_get_info_by_fd(). so
1360 	 * let's start with a sane default - 4KiB here - and resize it only if
1361 	 * bpf_obj_get_info_by_fd() needs a bigger buffer.
1362 	 */
1363 	last_size = 4096;
1364 	ptr = malloc(last_size);
1365 	if (!ptr)
1366 		return ERR_PTR(-ENOMEM);
1367 
1368 	memset(&btf_info, 0, sizeof(btf_info));
1369 	btf_info.btf = ptr_to_u64(ptr);
1370 	btf_info.btf_size = last_size;
1371 	err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
1372 
1373 	if (!err && btf_info.btf_size > last_size) {
1374 		void *temp_ptr;
1375 
1376 		last_size = btf_info.btf_size;
1377 		temp_ptr = realloc(ptr, last_size);
1378 		if (!temp_ptr) {
1379 			btf = ERR_PTR(-ENOMEM);
1380 			goto exit_free;
1381 		}
1382 		ptr = temp_ptr;
1383 
1384 		len = sizeof(btf_info);
1385 		memset(&btf_info, 0, sizeof(btf_info));
1386 		btf_info.btf = ptr_to_u64(ptr);
1387 		btf_info.btf_size = last_size;
1388 
1389 		err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
1390 	}
1391 
1392 	if (err || btf_info.btf_size > last_size) {
1393 		btf = err ? ERR_PTR(-errno) : ERR_PTR(-E2BIG);
1394 		goto exit_free;
1395 	}
1396 
1397 	btf = btf_new(ptr, btf_info.btf_size, base_btf);
1398 
1399 exit_free:
1400 	free(ptr);
1401 	return btf;
1402 }
1403 
btf__load_from_kernel_by_id_split(__u32 id,struct btf * base_btf)1404 struct btf *btf__load_from_kernel_by_id_split(__u32 id, struct btf *base_btf)
1405 {
1406 	struct btf *btf;
1407 	int btf_fd;
1408 
1409 	btf_fd = bpf_btf_get_fd_by_id(id);
1410 	if (btf_fd < 0)
1411 		return libbpf_err_ptr(-errno);
1412 
1413 	btf = btf_get_from_fd(btf_fd, base_btf);
1414 	close(btf_fd);
1415 
1416 	return libbpf_ptr(btf);
1417 }
1418 
btf__load_from_kernel_by_id(__u32 id)1419 struct btf *btf__load_from_kernel_by_id(__u32 id)
1420 {
1421 	return btf__load_from_kernel_by_id_split(id, NULL);
1422 }
1423 
btf__get_from_id(__u32 id,struct btf ** btf)1424 int btf__get_from_id(__u32 id, struct btf **btf)
1425 {
1426 	struct btf *res;
1427 	int err;
1428 
1429 	*btf = NULL;
1430 	res = btf__load_from_kernel_by_id(id);
1431 	err = libbpf_get_error(res);
1432 
1433 	if (err)
1434 		return libbpf_err(err);
1435 
1436 	*btf = res;
1437 	return 0;
1438 }
1439 
btf__get_map_kv_tids(const struct btf * btf,const char * map_name,__u32 expected_key_size,__u32 expected_value_size,__u32 * key_type_id,__u32 * value_type_id)1440 int btf__get_map_kv_tids(const struct btf *btf, const char *map_name,
1441 			 __u32 expected_key_size, __u32 expected_value_size,
1442 			 __u32 *key_type_id, __u32 *value_type_id)
1443 {
1444 	const struct btf_type *container_type;
1445 	const struct btf_member *key, *value;
1446 	const size_t max_name = 256;
1447 	char container_name[max_name];
1448 	__s64 key_size, value_size;
1449 	__s32 container_id;
1450 
1451 	if (snprintf(container_name, max_name, "____btf_map_%s", map_name) == max_name) {
1452 		pr_warn("map:%s length of '____btf_map_%s' is too long\n",
1453 			map_name, map_name);
1454 		return libbpf_err(-EINVAL);
1455 	}
1456 
1457 	container_id = btf__find_by_name(btf, container_name);
1458 	if (container_id < 0) {
1459 		pr_debug("map:%s container_name:%s cannot be found in BTF. Missing BPF_ANNOTATE_KV_PAIR?\n",
1460 			 map_name, container_name);
1461 		return libbpf_err(container_id);
1462 	}
1463 
1464 	container_type = btf__type_by_id(btf, container_id);
1465 	if (!container_type) {
1466 		pr_warn("map:%s cannot find BTF type for container_id:%u\n",
1467 			map_name, container_id);
1468 		return libbpf_err(-EINVAL);
1469 	}
1470 
1471 	if (!btf_is_struct(container_type) || btf_vlen(container_type) < 2) {
1472 		pr_warn("map:%s container_name:%s is an invalid container struct\n",
1473 			map_name, container_name);
1474 		return libbpf_err(-EINVAL);
1475 	}
1476 
1477 	key = btf_members(container_type);
1478 	value = key + 1;
1479 
1480 	key_size = btf__resolve_size(btf, key->type);
1481 	if (key_size < 0) {
1482 		pr_warn("map:%s invalid BTF key_type_size\n", map_name);
1483 		return libbpf_err(key_size);
1484 	}
1485 
1486 	if (expected_key_size != key_size) {
1487 		pr_warn("map:%s btf_key_type_size:%u != map_def_key_size:%u\n",
1488 			map_name, (__u32)key_size, expected_key_size);
1489 		return libbpf_err(-EINVAL);
1490 	}
1491 
1492 	value_size = btf__resolve_size(btf, value->type);
1493 	if (value_size < 0) {
1494 		pr_warn("map:%s invalid BTF value_type_size\n", map_name);
1495 		return libbpf_err(value_size);
1496 	}
1497 
1498 	if (expected_value_size != value_size) {
1499 		pr_warn("map:%s btf_value_type_size:%u != map_def_value_size:%u\n",
1500 			map_name, (__u32)value_size, expected_value_size);
1501 		return libbpf_err(-EINVAL);
1502 	}
1503 
1504 	*key_type_id = key->type;
1505 	*value_type_id = value->type;
1506 
1507 	return 0;
1508 }
1509 
btf_invalidate_raw_data(struct btf * btf)1510 static void btf_invalidate_raw_data(struct btf *btf)
1511 {
1512 	if (btf->raw_data) {
1513 		free(btf->raw_data);
1514 		btf->raw_data = NULL;
1515 	}
1516 	if (btf->raw_data_swapped) {
1517 		free(btf->raw_data_swapped);
1518 		btf->raw_data_swapped = NULL;
1519 	}
1520 }
1521 
1522 /* Ensure BTF is ready to be modified (by splitting into a three memory
1523  * regions for header, types, and strings). Also invalidate cached
1524  * raw_data, if any.
1525  */
btf_ensure_modifiable(struct btf * btf)1526 static int btf_ensure_modifiable(struct btf *btf)
1527 {
1528 	void *hdr, *types;
1529 	struct strset *set = NULL;
1530 	int err = -ENOMEM;
1531 
1532 	if (btf_is_modifiable(btf)) {
1533 		/* any BTF modification invalidates raw_data */
1534 		btf_invalidate_raw_data(btf);
1535 		return 0;
1536 	}
1537 
1538 	/* split raw data into three memory regions */
1539 	hdr = malloc(btf->hdr->hdr_len);
1540 	types = malloc(btf->hdr->type_len);
1541 	if (!hdr || !types)
1542 		goto err_out;
1543 
1544 	memcpy(hdr, btf->hdr, btf->hdr->hdr_len);
1545 	memcpy(types, btf->types_data, btf->hdr->type_len);
1546 
1547 	/* build lookup index for all strings */
1548 	set = strset__new(BTF_MAX_STR_OFFSET, btf->strs_data, btf->hdr->str_len);
1549 	if (IS_ERR(set)) {
1550 		err = PTR_ERR(set);
1551 		goto err_out;
1552 	}
1553 
1554 	/* only when everything was successful, update internal state */
1555 	btf->hdr = hdr;
1556 	btf->types_data = types;
1557 	btf->types_data_cap = btf->hdr->type_len;
1558 	btf->strs_data = NULL;
1559 	btf->strs_set = set;
1560 	/* if BTF was created from scratch, all strings are guaranteed to be
1561 	 * unique and deduplicated
1562 	 */
1563 	if (btf->hdr->str_len == 0)
1564 		btf->strs_deduped = true;
1565 	if (!btf->base_btf && btf->hdr->str_len == 1)
1566 		btf->strs_deduped = true;
1567 
1568 	/* invalidate raw_data representation */
1569 	btf_invalidate_raw_data(btf);
1570 
1571 	return 0;
1572 
1573 err_out:
1574 	strset__free(set);
1575 	free(hdr);
1576 	free(types);
1577 	return err;
1578 }
1579 
1580 /* Find an offset in BTF string section that corresponds to a given string *s*.
1581  * Returns:
1582  *   - >0 offset into string section, if string is found;
1583  *   - -ENOENT, if string is not in the string section;
1584  *   - <0, on any other error.
1585  */
btf__find_str(struct btf * btf,const char * s)1586 int btf__find_str(struct btf *btf, const char *s)
1587 {
1588 	int off;
1589 
1590 	if (btf->base_btf) {
1591 		off = btf__find_str(btf->base_btf, s);
1592 		if (off != -ENOENT)
1593 			return off;
1594 	}
1595 
1596 	/* BTF needs to be in a modifiable state to build string lookup index */
1597 	if (btf_ensure_modifiable(btf))
1598 		return libbpf_err(-ENOMEM);
1599 
1600 	off = strset__find_str(btf->strs_set, s);
1601 	if (off < 0)
1602 		return libbpf_err(off);
1603 
1604 	return btf->start_str_off + off;
1605 }
1606 
1607 /* Add a string s to the BTF string section.
1608  * Returns:
1609  *   - > 0 offset into string section, on success;
1610  *   - < 0, on error.
1611  */
btf__add_str(struct btf * btf,const char * s)1612 int btf__add_str(struct btf *btf, const char *s)
1613 {
1614 	int off;
1615 
1616 	if (btf->base_btf) {
1617 		off = btf__find_str(btf->base_btf, s);
1618 		if (off != -ENOENT)
1619 			return off;
1620 	}
1621 
1622 	if (btf_ensure_modifiable(btf))
1623 		return libbpf_err(-ENOMEM);
1624 
1625 	off = strset__add_str(btf->strs_set, s);
1626 	if (off < 0)
1627 		return libbpf_err(off);
1628 
1629 	btf->hdr->str_len = strset__data_size(btf->strs_set);
1630 
1631 	return btf->start_str_off + off;
1632 }
1633 
btf_add_type_mem(struct btf * btf,size_t add_sz)1634 static void *btf_add_type_mem(struct btf *btf, size_t add_sz)
1635 {
1636 	return libbpf_add_mem(&btf->types_data, &btf->types_data_cap, 1,
1637 			      btf->hdr->type_len, UINT_MAX, add_sz);
1638 }
1639 
btf_type_inc_vlen(struct btf_type * t)1640 static void btf_type_inc_vlen(struct btf_type *t)
1641 {
1642 	t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, btf_kflag(t));
1643 }
1644 
btf_commit_type(struct btf * btf,int data_sz)1645 static int btf_commit_type(struct btf *btf, int data_sz)
1646 {
1647 	int err;
1648 
1649 	err = btf_add_type_idx_entry(btf, btf->hdr->type_len);
1650 	if (err)
1651 		return libbpf_err(err);
1652 
1653 	btf->hdr->type_len += data_sz;
1654 	btf->hdr->str_off += data_sz;
1655 	btf->nr_types++;
1656 	return btf->start_id + btf->nr_types - 1;
1657 }
1658 
1659 struct btf_pipe {
1660 	const struct btf *src;
1661 	struct btf *dst;
1662 };
1663 
btf_rewrite_str(__u32 * str_off,void * ctx)1664 static int btf_rewrite_str(__u32 *str_off, void *ctx)
1665 {
1666 	struct btf_pipe *p = ctx;
1667 	int off;
1668 
1669 	if (!*str_off) /* nothing to do for empty strings */
1670 		return 0;
1671 
1672 	off = btf__add_str(p->dst, btf__str_by_offset(p->src, *str_off));
1673 	if (off < 0)
1674 		return off;
1675 
1676 	*str_off = off;
1677 	return 0;
1678 }
1679 
btf__add_type(struct btf * btf,const struct btf * src_btf,const struct btf_type * src_type)1680 int btf__add_type(struct btf *btf, const struct btf *src_btf, const struct btf_type *src_type)
1681 {
1682 	struct btf_pipe p = { .src = src_btf, .dst = btf };
1683 	struct btf_type *t;
1684 	int sz, err;
1685 
1686 	sz = btf_type_size(src_type);
1687 	if (sz < 0)
1688 		return libbpf_err(sz);
1689 
1690 	/* deconstruct BTF, if necessary, and invalidate raw_data */
1691 	if (btf_ensure_modifiable(btf))
1692 		return libbpf_err(-ENOMEM);
1693 
1694 	t = btf_add_type_mem(btf, sz);
1695 	if (!t)
1696 		return libbpf_err(-ENOMEM);
1697 
1698 	memcpy(t, src_type, sz);
1699 
1700 	err = btf_type_visit_str_offs(t, btf_rewrite_str, &p);
1701 	if (err)
1702 		return libbpf_err(err);
1703 
1704 	return btf_commit_type(btf, sz);
1705 }
1706 
1707 /*
1708  * Append new BTF_KIND_INT type with:
1709  *   - *name* - non-empty, non-NULL type name;
1710  *   - *sz* - power-of-2 (1, 2, 4, ..) size of the type, in bytes;
1711  *   - encoding is a combination of BTF_INT_SIGNED, BTF_INT_CHAR, BTF_INT_BOOL.
1712  * Returns:
1713  *   - >0, type ID of newly added BTF type;
1714  *   - <0, on error.
1715  */
btf__add_int(struct btf * btf,const char * name,size_t byte_sz,int encoding)1716 int btf__add_int(struct btf *btf, const char *name, size_t byte_sz, int encoding)
1717 {
1718 	struct btf_type *t;
1719 	int sz, name_off;
1720 
1721 	/* non-empty name */
1722 	if (!name || !name[0])
1723 		return libbpf_err(-EINVAL);
1724 	/* byte_sz must be power of 2 */
1725 	if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 16)
1726 		return libbpf_err(-EINVAL);
1727 	if (encoding & ~(BTF_INT_SIGNED | BTF_INT_CHAR | BTF_INT_BOOL))
1728 		return libbpf_err(-EINVAL);
1729 
1730 	/* deconstruct BTF, if necessary, and invalidate raw_data */
1731 	if (btf_ensure_modifiable(btf))
1732 		return libbpf_err(-ENOMEM);
1733 
1734 	sz = sizeof(struct btf_type) + sizeof(int);
1735 	t = btf_add_type_mem(btf, sz);
1736 	if (!t)
1737 		return libbpf_err(-ENOMEM);
1738 
1739 	/* if something goes wrong later, we might end up with an extra string,
1740 	 * but that shouldn't be a problem, because BTF can't be constructed
1741 	 * completely anyway and will most probably be just discarded
1742 	 */
1743 	name_off = btf__add_str(btf, name);
1744 	if (name_off < 0)
1745 		return name_off;
1746 
1747 	t->name_off = name_off;
1748 	t->info = btf_type_info(BTF_KIND_INT, 0, 0);
1749 	t->size = byte_sz;
1750 	/* set INT info, we don't allow setting legacy bit offset/size */
1751 	*(__u32 *)(t + 1) = (encoding << 24) | (byte_sz * 8);
1752 
1753 	return btf_commit_type(btf, sz);
1754 }
1755 
1756 /*
1757  * Append new BTF_KIND_FLOAT type with:
1758  *   - *name* - non-empty, non-NULL type name;
1759  *   - *sz* - size of the type, in bytes;
1760  * Returns:
1761  *   - >0, type ID of newly added BTF type;
1762  *   - <0, on error.
1763  */
btf__add_float(struct btf * btf,const char * name,size_t byte_sz)1764 int btf__add_float(struct btf *btf, const char *name, size_t byte_sz)
1765 {
1766 	struct btf_type *t;
1767 	int sz, name_off;
1768 
1769 	/* non-empty name */
1770 	if (!name || !name[0])
1771 		return libbpf_err(-EINVAL);
1772 
1773 	/* byte_sz must be one of the explicitly allowed values */
1774 	if (byte_sz != 2 && byte_sz != 4 && byte_sz != 8 && byte_sz != 12 &&
1775 	    byte_sz != 16)
1776 		return libbpf_err(-EINVAL);
1777 
1778 	if (btf_ensure_modifiable(btf))
1779 		return libbpf_err(-ENOMEM);
1780 
1781 	sz = sizeof(struct btf_type);
1782 	t = btf_add_type_mem(btf, sz);
1783 	if (!t)
1784 		return libbpf_err(-ENOMEM);
1785 
1786 	name_off = btf__add_str(btf, name);
1787 	if (name_off < 0)
1788 		return name_off;
1789 
1790 	t->name_off = name_off;
1791 	t->info = btf_type_info(BTF_KIND_FLOAT, 0, 0);
1792 	t->size = byte_sz;
1793 
1794 	return btf_commit_type(btf, sz);
1795 }
1796 
1797 /* it's completely legal to append BTF types with type IDs pointing forward to
1798  * types that haven't been appended yet, so we only make sure that id looks
1799  * sane, we can't guarantee that ID will always be valid
1800  */
validate_type_id(int id)1801 static int validate_type_id(int id)
1802 {
1803 	if (id < 0 || id > BTF_MAX_NR_TYPES)
1804 		return -EINVAL;
1805 	return 0;
1806 }
1807 
1808 /* generic append function for PTR, TYPEDEF, CONST/VOLATILE/RESTRICT */
btf_add_ref_kind(struct btf * btf,int kind,const char * name,int ref_type_id)1809 static int btf_add_ref_kind(struct btf *btf, int kind, const char *name, int ref_type_id)
1810 {
1811 	struct btf_type *t;
1812 	int sz, name_off = 0;
1813 
1814 	if (validate_type_id(ref_type_id))
1815 		return libbpf_err(-EINVAL);
1816 
1817 	if (btf_ensure_modifiable(btf))
1818 		return libbpf_err(-ENOMEM);
1819 
1820 	sz = sizeof(struct btf_type);
1821 	t = btf_add_type_mem(btf, sz);
1822 	if (!t)
1823 		return libbpf_err(-ENOMEM);
1824 
1825 	if (name && name[0]) {
1826 		name_off = btf__add_str(btf, name);
1827 		if (name_off < 0)
1828 			return name_off;
1829 	}
1830 
1831 	t->name_off = name_off;
1832 	t->info = btf_type_info(kind, 0, 0);
1833 	t->type = ref_type_id;
1834 
1835 	return btf_commit_type(btf, sz);
1836 }
1837 
1838 /*
1839  * Append new BTF_KIND_PTR type with:
1840  *   - *ref_type_id* - referenced type ID, it might not exist yet;
1841  * Returns:
1842  *   - >0, type ID of newly added BTF type;
1843  *   - <0, on error.
1844  */
btf__add_ptr(struct btf * btf,int ref_type_id)1845 int btf__add_ptr(struct btf *btf, int ref_type_id)
1846 {
1847 	return btf_add_ref_kind(btf, BTF_KIND_PTR, NULL, ref_type_id);
1848 }
1849 
1850 /*
1851  * Append new BTF_KIND_ARRAY type with:
1852  *   - *index_type_id* - type ID of the type describing array index;
1853  *   - *elem_type_id* - type ID of the type describing array element;
1854  *   - *nr_elems* - the size of the array;
1855  * Returns:
1856  *   - >0, type ID of newly added BTF type;
1857  *   - <0, on error.
1858  */
btf__add_array(struct btf * btf,int index_type_id,int elem_type_id,__u32 nr_elems)1859 int btf__add_array(struct btf *btf, int index_type_id, int elem_type_id, __u32 nr_elems)
1860 {
1861 	struct btf_type *t;
1862 	struct btf_array *a;
1863 	int sz;
1864 
1865 	if (validate_type_id(index_type_id) || validate_type_id(elem_type_id))
1866 		return libbpf_err(-EINVAL);
1867 
1868 	if (btf_ensure_modifiable(btf))
1869 		return libbpf_err(-ENOMEM);
1870 
1871 	sz = sizeof(struct btf_type) + sizeof(struct btf_array);
1872 	t = btf_add_type_mem(btf, sz);
1873 	if (!t)
1874 		return libbpf_err(-ENOMEM);
1875 
1876 	t->name_off = 0;
1877 	t->info = btf_type_info(BTF_KIND_ARRAY, 0, 0);
1878 	t->size = 0;
1879 
1880 	a = btf_array(t);
1881 	a->type = elem_type_id;
1882 	a->index_type = index_type_id;
1883 	a->nelems = nr_elems;
1884 
1885 	return btf_commit_type(btf, sz);
1886 }
1887 
1888 /* generic STRUCT/UNION append function */
btf_add_composite(struct btf * btf,int kind,const char * name,__u32 bytes_sz)1889 static int btf_add_composite(struct btf *btf, int kind, const char *name, __u32 bytes_sz)
1890 {
1891 	struct btf_type *t;
1892 	int sz, name_off = 0;
1893 
1894 	if (btf_ensure_modifiable(btf))
1895 		return libbpf_err(-ENOMEM);
1896 
1897 	sz = sizeof(struct btf_type);
1898 	t = btf_add_type_mem(btf, sz);
1899 	if (!t)
1900 		return libbpf_err(-ENOMEM);
1901 
1902 	if (name && name[0]) {
1903 		name_off = btf__add_str(btf, name);
1904 		if (name_off < 0)
1905 			return name_off;
1906 	}
1907 
1908 	/* start out with vlen=0 and no kflag; this will be adjusted when
1909 	 * adding each member
1910 	 */
1911 	t->name_off = name_off;
1912 	t->info = btf_type_info(kind, 0, 0);
1913 	t->size = bytes_sz;
1914 
1915 	return btf_commit_type(btf, sz);
1916 }
1917 
1918 /*
1919  * Append new BTF_KIND_STRUCT type with:
1920  *   - *name* - name of the struct, can be NULL or empty for anonymous structs;
1921  *   - *byte_sz* - size of the struct, in bytes;
1922  *
1923  * Struct initially has no fields in it. Fields can be added by
1924  * btf__add_field() right after btf__add_struct() succeeds.
1925  *
1926  * Returns:
1927  *   - >0, type ID of newly added BTF type;
1928  *   - <0, on error.
1929  */
btf__add_struct(struct btf * btf,const char * name,__u32 byte_sz)1930 int btf__add_struct(struct btf *btf, const char *name, __u32 byte_sz)
1931 {
1932 	return btf_add_composite(btf, BTF_KIND_STRUCT, name, byte_sz);
1933 }
1934 
1935 /*
1936  * Append new BTF_KIND_UNION type with:
1937  *   - *name* - name of the union, can be NULL or empty for anonymous union;
1938  *   - *byte_sz* - size of the union, in bytes;
1939  *
1940  * Union initially has no fields in it. Fields can be added by
1941  * btf__add_field() right after btf__add_union() succeeds. All fields
1942  * should have *bit_offset* of 0.
1943  *
1944  * Returns:
1945  *   - >0, type ID of newly added BTF type;
1946  *   - <0, on error.
1947  */
btf__add_union(struct btf * btf,const char * name,__u32 byte_sz)1948 int btf__add_union(struct btf *btf, const char *name, __u32 byte_sz)
1949 {
1950 	return btf_add_composite(btf, BTF_KIND_UNION, name, byte_sz);
1951 }
1952 
btf_last_type(struct btf * btf)1953 static struct btf_type *btf_last_type(struct btf *btf)
1954 {
1955 	return btf_type_by_id(btf, btf__get_nr_types(btf));
1956 }
1957 
1958 /*
1959  * Append new field for the current STRUCT/UNION type with:
1960  *   - *name* - name of the field, can be NULL or empty for anonymous field;
1961  *   - *type_id* - type ID for the type describing field type;
1962  *   - *bit_offset* - bit offset of the start of the field within struct/union;
1963  *   - *bit_size* - bit size of a bitfield, 0 for non-bitfield fields;
1964  * Returns:
1965  *   -  0, on success;
1966  *   - <0, on error.
1967  */
btf__add_field(struct btf * btf,const char * name,int type_id,__u32 bit_offset,__u32 bit_size)1968 int btf__add_field(struct btf *btf, const char *name, int type_id,
1969 		   __u32 bit_offset, __u32 bit_size)
1970 {
1971 	struct btf_type *t;
1972 	struct btf_member *m;
1973 	bool is_bitfield;
1974 	int sz, name_off = 0;
1975 
1976 	/* last type should be union/struct */
1977 	if (btf->nr_types == 0)
1978 		return libbpf_err(-EINVAL);
1979 	t = btf_last_type(btf);
1980 	if (!btf_is_composite(t))
1981 		return libbpf_err(-EINVAL);
1982 
1983 	if (validate_type_id(type_id))
1984 		return libbpf_err(-EINVAL);
1985 	/* best-effort bit field offset/size enforcement */
1986 	is_bitfield = bit_size || (bit_offset % 8 != 0);
1987 	if (is_bitfield && (bit_size == 0 || bit_size > 255 || bit_offset > 0xffffff))
1988 		return libbpf_err(-EINVAL);
1989 
1990 	/* only offset 0 is allowed for unions */
1991 	if (btf_is_union(t) && bit_offset)
1992 		return libbpf_err(-EINVAL);
1993 
1994 	/* decompose and invalidate raw data */
1995 	if (btf_ensure_modifiable(btf))
1996 		return libbpf_err(-ENOMEM);
1997 
1998 	sz = sizeof(struct btf_member);
1999 	m = btf_add_type_mem(btf, sz);
2000 	if (!m)
2001 		return libbpf_err(-ENOMEM);
2002 
2003 	if (name && name[0]) {
2004 		name_off = btf__add_str(btf, name);
2005 		if (name_off < 0)
2006 			return name_off;
2007 	}
2008 
2009 	m->name_off = name_off;
2010 	m->type = type_id;
2011 	m->offset = bit_offset | (bit_size << 24);
2012 
2013 	/* btf_add_type_mem can invalidate t pointer */
2014 	t = btf_last_type(btf);
2015 	/* update parent type's vlen and kflag */
2016 	t->info = btf_type_info(btf_kind(t), btf_vlen(t) + 1, is_bitfield || btf_kflag(t));
2017 
2018 	btf->hdr->type_len += sz;
2019 	btf->hdr->str_off += sz;
2020 	return 0;
2021 }
2022 
2023 /*
2024  * Append new BTF_KIND_ENUM type with:
2025  *   - *name* - name of the enum, can be NULL or empty for anonymous enums;
2026  *   - *byte_sz* - size of the enum, in bytes.
2027  *
2028  * Enum initially has no enum values in it (and corresponds to enum forward
2029  * declaration). Enumerator values can be added by btf__add_enum_value()
2030  * immediately after btf__add_enum() succeeds.
2031  *
2032  * Returns:
2033  *   - >0, type ID of newly added BTF type;
2034  *   - <0, on error.
2035  */
btf__add_enum(struct btf * btf,const char * name,__u32 byte_sz)2036 int btf__add_enum(struct btf *btf, const char *name, __u32 byte_sz)
2037 {
2038 	struct btf_type *t;
2039 	int sz, name_off = 0;
2040 
2041 	/* byte_sz must be power of 2 */
2042 	if (!byte_sz || (byte_sz & (byte_sz - 1)) || byte_sz > 8)
2043 		return libbpf_err(-EINVAL);
2044 
2045 	if (btf_ensure_modifiable(btf))
2046 		return libbpf_err(-ENOMEM);
2047 
2048 	sz = sizeof(struct btf_type);
2049 	t = btf_add_type_mem(btf, sz);
2050 	if (!t)
2051 		return libbpf_err(-ENOMEM);
2052 
2053 	if (name && name[0]) {
2054 		name_off = btf__add_str(btf, name);
2055 		if (name_off < 0)
2056 			return name_off;
2057 	}
2058 
2059 	/* start out with vlen=0; it will be adjusted when adding enum values */
2060 	t->name_off = name_off;
2061 	t->info = btf_type_info(BTF_KIND_ENUM, 0, 0);
2062 	t->size = byte_sz;
2063 
2064 	return btf_commit_type(btf, sz);
2065 }
2066 
2067 /*
2068  * Append new enum value for the current ENUM type with:
2069  *   - *name* - name of the enumerator value, can't be NULL or empty;
2070  *   - *value* - integer value corresponding to enum value *name*;
2071  * Returns:
2072  *   -  0, on success;
2073  *   - <0, on error.
2074  */
btf__add_enum_value(struct btf * btf,const char * name,__s64 value)2075 int btf__add_enum_value(struct btf *btf, const char *name, __s64 value)
2076 {
2077 	struct btf_type *t;
2078 	struct btf_enum *v;
2079 	int sz, name_off;
2080 
2081 	/* last type should be BTF_KIND_ENUM */
2082 	if (btf->nr_types == 0)
2083 		return libbpf_err(-EINVAL);
2084 	t = btf_last_type(btf);
2085 	if (!btf_is_enum(t))
2086 		return libbpf_err(-EINVAL);
2087 
2088 	/* non-empty name */
2089 	if (!name || !name[0])
2090 		return libbpf_err(-EINVAL);
2091 	if (value < INT_MIN || value > UINT_MAX)
2092 		return libbpf_err(-E2BIG);
2093 
2094 	/* decompose and invalidate raw data */
2095 	if (btf_ensure_modifiable(btf))
2096 		return libbpf_err(-ENOMEM);
2097 
2098 	sz = sizeof(struct btf_enum);
2099 	v = btf_add_type_mem(btf, sz);
2100 	if (!v)
2101 		return libbpf_err(-ENOMEM);
2102 
2103 	name_off = btf__add_str(btf, name);
2104 	if (name_off < 0)
2105 		return name_off;
2106 
2107 	v->name_off = name_off;
2108 	v->val = value;
2109 
2110 	/* update parent type's vlen */
2111 	t = btf_last_type(btf);
2112 	btf_type_inc_vlen(t);
2113 
2114 	btf->hdr->type_len += sz;
2115 	btf->hdr->str_off += sz;
2116 	return 0;
2117 }
2118 
2119 /*
2120  * Append new BTF_KIND_FWD type with:
2121  *   - *name*, non-empty/non-NULL name;
2122  *   - *fwd_kind*, kind of forward declaration, one of BTF_FWD_STRUCT,
2123  *     BTF_FWD_UNION, or BTF_FWD_ENUM;
2124  * Returns:
2125  *   - >0, type ID of newly added BTF type;
2126  *   - <0, on error.
2127  */
btf__add_fwd(struct btf * btf,const char * name,enum btf_fwd_kind fwd_kind)2128 int btf__add_fwd(struct btf *btf, const char *name, enum btf_fwd_kind fwd_kind)
2129 {
2130 	if (!name || !name[0])
2131 		return libbpf_err(-EINVAL);
2132 
2133 	switch (fwd_kind) {
2134 	case BTF_FWD_STRUCT:
2135 	case BTF_FWD_UNION: {
2136 		struct btf_type *t;
2137 		int id;
2138 
2139 		id = btf_add_ref_kind(btf, BTF_KIND_FWD, name, 0);
2140 		if (id <= 0)
2141 			return id;
2142 		t = btf_type_by_id(btf, id);
2143 		t->info = btf_type_info(BTF_KIND_FWD, 0, fwd_kind == BTF_FWD_UNION);
2144 		return id;
2145 	}
2146 	case BTF_FWD_ENUM:
2147 		/* enum forward in BTF currently is just an enum with no enum
2148 		 * values; we also assume a standard 4-byte size for it
2149 		 */
2150 		return btf__add_enum(btf, name, sizeof(int));
2151 	default:
2152 		return libbpf_err(-EINVAL);
2153 	}
2154 }
2155 
2156 /*
2157  * Append new BTF_KING_TYPEDEF type with:
2158  *   - *name*, non-empty/non-NULL name;
2159  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2160  * Returns:
2161  *   - >0, type ID of newly added BTF type;
2162  *   - <0, on error.
2163  */
btf__add_typedef(struct btf * btf,const char * name,int ref_type_id)2164 int btf__add_typedef(struct btf *btf, const char *name, int ref_type_id)
2165 {
2166 	if (!name || !name[0])
2167 		return libbpf_err(-EINVAL);
2168 
2169 	return btf_add_ref_kind(btf, BTF_KIND_TYPEDEF, name, ref_type_id);
2170 }
2171 
2172 /*
2173  * Append new BTF_KIND_VOLATILE type with:
2174  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2175  * Returns:
2176  *   - >0, type ID of newly added BTF type;
2177  *   - <0, on error.
2178  */
btf__add_volatile(struct btf * btf,int ref_type_id)2179 int btf__add_volatile(struct btf *btf, int ref_type_id)
2180 {
2181 	return btf_add_ref_kind(btf, BTF_KIND_VOLATILE, NULL, ref_type_id);
2182 }
2183 
2184 /*
2185  * Append new BTF_KIND_CONST type with:
2186  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2187  * Returns:
2188  *   - >0, type ID of newly added BTF type;
2189  *   - <0, on error.
2190  */
btf__add_const(struct btf * btf,int ref_type_id)2191 int btf__add_const(struct btf *btf, int ref_type_id)
2192 {
2193 	return btf_add_ref_kind(btf, BTF_KIND_CONST, NULL, ref_type_id);
2194 }
2195 
2196 /*
2197  * Append new BTF_KIND_RESTRICT type with:
2198  *   - *ref_type_id* - referenced type ID, it might not exist yet;
2199  * Returns:
2200  *   - >0, type ID of newly added BTF type;
2201  *   - <0, on error.
2202  */
btf__add_restrict(struct btf * btf,int ref_type_id)2203 int btf__add_restrict(struct btf *btf, int ref_type_id)
2204 {
2205 	return btf_add_ref_kind(btf, BTF_KIND_RESTRICT, NULL, ref_type_id);
2206 }
2207 
2208 /*
2209  * Append new BTF_KIND_FUNC type with:
2210  *   - *name*, non-empty/non-NULL name;
2211  *   - *proto_type_id* - FUNC_PROTO's type ID, it might not exist yet;
2212  * Returns:
2213  *   - >0, type ID of newly added BTF type;
2214  *   - <0, on error.
2215  */
btf__add_func(struct btf * btf,const char * name,enum btf_func_linkage linkage,int proto_type_id)2216 int btf__add_func(struct btf *btf, const char *name,
2217 		  enum btf_func_linkage linkage, int proto_type_id)
2218 {
2219 	int id;
2220 
2221 	if (!name || !name[0])
2222 		return libbpf_err(-EINVAL);
2223 	if (linkage != BTF_FUNC_STATIC && linkage != BTF_FUNC_GLOBAL &&
2224 	    linkage != BTF_FUNC_EXTERN)
2225 		return libbpf_err(-EINVAL);
2226 
2227 	id = btf_add_ref_kind(btf, BTF_KIND_FUNC, name, proto_type_id);
2228 	if (id > 0) {
2229 		struct btf_type *t = btf_type_by_id(btf, id);
2230 
2231 		t->info = btf_type_info(BTF_KIND_FUNC, linkage, 0);
2232 	}
2233 	return libbpf_err(id);
2234 }
2235 
2236 /*
2237  * Append new BTF_KIND_FUNC_PROTO with:
2238  *   - *ret_type_id* - type ID for return result of a function.
2239  *
2240  * Function prototype initially has no arguments, but they can be added by
2241  * btf__add_func_param() one by one, immediately after
2242  * btf__add_func_proto() succeeded.
2243  *
2244  * Returns:
2245  *   - >0, type ID of newly added BTF type;
2246  *   - <0, on error.
2247  */
btf__add_func_proto(struct btf * btf,int ret_type_id)2248 int btf__add_func_proto(struct btf *btf, int ret_type_id)
2249 {
2250 	struct btf_type *t;
2251 	int sz;
2252 
2253 	if (validate_type_id(ret_type_id))
2254 		return libbpf_err(-EINVAL);
2255 
2256 	if (btf_ensure_modifiable(btf))
2257 		return libbpf_err(-ENOMEM);
2258 
2259 	sz = sizeof(struct btf_type);
2260 	t = btf_add_type_mem(btf, sz);
2261 	if (!t)
2262 		return libbpf_err(-ENOMEM);
2263 
2264 	/* start out with vlen=0; this will be adjusted when adding enum
2265 	 * values, if necessary
2266 	 */
2267 	t->name_off = 0;
2268 	t->info = btf_type_info(BTF_KIND_FUNC_PROTO, 0, 0);
2269 	t->type = ret_type_id;
2270 
2271 	return btf_commit_type(btf, sz);
2272 }
2273 
2274 /*
2275  * Append new function parameter for current FUNC_PROTO type with:
2276  *   - *name* - parameter name, can be NULL or empty;
2277  *   - *type_id* - type ID describing the type of the parameter.
2278  * Returns:
2279  *   -  0, on success;
2280  *   - <0, on error.
2281  */
btf__add_func_param(struct btf * btf,const char * name,int type_id)2282 int btf__add_func_param(struct btf *btf, const char *name, int type_id)
2283 {
2284 	struct btf_type *t;
2285 	struct btf_param *p;
2286 	int sz, name_off = 0;
2287 
2288 	if (validate_type_id(type_id))
2289 		return libbpf_err(-EINVAL);
2290 
2291 	/* last type should be BTF_KIND_FUNC_PROTO */
2292 	if (btf->nr_types == 0)
2293 		return libbpf_err(-EINVAL);
2294 	t = btf_last_type(btf);
2295 	if (!btf_is_func_proto(t))
2296 		return libbpf_err(-EINVAL);
2297 
2298 	/* decompose and invalidate raw data */
2299 	if (btf_ensure_modifiable(btf))
2300 		return libbpf_err(-ENOMEM);
2301 
2302 	sz = sizeof(struct btf_param);
2303 	p = btf_add_type_mem(btf, sz);
2304 	if (!p)
2305 		return libbpf_err(-ENOMEM);
2306 
2307 	if (name && name[0]) {
2308 		name_off = btf__add_str(btf, name);
2309 		if (name_off < 0)
2310 			return name_off;
2311 	}
2312 
2313 	p->name_off = name_off;
2314 	p->type = type_id;
2315 
2316 	/* update parent type's vlen */
2317 	t = btf_last_type(btf);
2318 	btf_type_inc_vlen(t);
2319 
2320 	btf->hdr->type_len += sz;
2321 	btf->hdr->str_off += sz;
2322 	return 0;
2323 }
2324 
2325 /*
2326  * Append new BTF_KIND_VAR type with:
2327  *   - *name* - non-empty/non-NULL name;
2328  *   - *linkage* - variable linkage, one of BTF_VAR_STATIC,
2329  *     BTF_VAR_GLOBAL_ALLOCATED, or BTF_VAR_GLOBAL_EXTERN;
2330  *   - *type_id* - type ID of the type describing the type of the variable.
2331  * Returns:
2332  *   - >0, type ID of newly added BTF type;
2333  *   - <0, on error.
2334  */
btf__add_var(struct btf * btf,const char * name,int linkage,int type_id)2335 int btf__add_var(struct btf *btf, const char *name, int linkage, int type_id)
2336 {
2337 	struct btf_type *t;
2338 	struct btf_var *v;
2339 	int sz, name_off;
2340 
2341 	/* non-empty name */
2342 	if (!name || !name[0])
2343 		return libbpf_err(-EINVAL);
2344 	if (linkage != BTF_VAR_STATIC && linkage != BTF_VAR_GLOBAL_ALLOCATED &&
2345 	    linkage != BTF_VAR_GLOBAL_EXTERN)
2346 		return libbpf_err(-EINVAL);
2347 	if (validate_type_id(type_id))
2348 		return libbpf_err(-EINVAL);
2349 
2350 	/* deconstruct BTF, if necessary, and invalidate raw_data */
2351 	if (btf_ensure_modifiable(btf))
2352 		return libbpf_err(-ENOMEM);
2353 
2354 	sz = sizeof(struct btf_type) + sizeof(struct btf_var);
2355 	t = btf_add_type_mem(btf, sz);
2356 	if (!t)
2357 		return libbpf_err(-ENOMEM);
2358 
2359 	name_off = btf__add_str(btf, name);
2360 	if (name_off < 0)
2361 		return name_off;
2362 
2363 	t->name_off = name_off;
2364 	t->info = btf_type_info(BTF_KIND_VAR, 0, 0);
2365 	t->type = type_id;
2366 
2367 	v = btf_var(t);
2368 	v->linkage = linkage;
2369 
2370 	return btf_commit_type(btf, sz);
2371 }
2372 
2373 /*
2374  * Append new BTF_KIND_DATASEC type with:
2375  *   - *name* - non-empty/non-NULL name;
2376  *   - *byte_sz* - data section size, in bytes.
2377  *
2378  * Data section is initially empty. Variables info can be added with
2379  * btf__add_datasec_var_info() calls, after btf__add_datasec() succeeds.
2380  *
2381  * Returns:
2382  *   - >0, type ID of newly added BTF type;
2383  *   - <0, on error.
2384  */
btf__add_datasec(struct btf * btf,const char * name,__u32 byte_sz)2385 int btf__add_datasec(struct btf *btf, const char *name, __u32 byte_sz)
2386 {
2387 	struct btf_type *t;
2388 	int sz, name_off;
2389 
2390 	/* non-empty name */
2391 	if (!name || !name[0])
2392 		return libbpf_err(-EINVAL);
2393 
2394 	if (btf_ensure_modifiable(btf))
2395 		return libbpf_err(-ENOMEM);
2396 
2397 	sz = sizeof(struct btf_type);
2398 	t = btf_add_type_mem(btf, sz);
2399 	if (!t)
2400 		return libbpf_err(-ENOMEM);
2401 
2402 	name_off = btf__add_str(btf, name);
2403 	if (name_off < 0)
2404 		return name_off;
2405 
2406 	/* start with vlen=0, which will be update as var_secinfos are added */
2407 	t->name_off = name_off;
2408 	t->info = btf_type_info(BTF_KIND_DATASEC, 0, 0);
2409 	t->size = byte_sz;
2410 
2411 	return btf_commit_type(btf, sz);
2412 }
2413 
2414 /*
2415  * Append new data section variable information entry for current DATASEC type:
2416  *   - *var_type_id* - type ID, describing type of the variable;
2417  *   - *offset* - variable offset within data section, in bytes;
2418  *   - *byte_sz* - variable size, in bytes.
2419  *
2420  * Returns:
2421  *   -  0, on success;
2422  *   - <0, on error.
2423  */
btf__add_datasec_var_info(struct btf * btf,int var_type_id,__u32 offset,__u32 byte_sz)2424 int btf__add_datasec_var_info(struct btf *btf, int var_type_id, __u32 offset, __u32 byte_sz)
2425 {
2426 	struct btf_type *t;
2427 	struct btf_var_secinfo *v;
2428 	int sz;
2429 
2430 	/* last type should be BTF_KIND_DATASEC */
2431 	if (btf->nr_types == 0)
2432 		return libbpf_err(-EINVAL);
2433 	t = btf_last_type(btf);
2434 	if (!btf_is_datasec(t))
2435 		return libbpf_err(-EINVAL);
2436 
2437 	if (validate_type_id(var_type_id))
2438 		return libbpf_err(-EINVAL);
2439 
2440 	/* decompose and invalidate raw data */
2441 	if (btf_ensure_modifiable(btf))
2442 		return libbpf_err(-ENOMEM);
2443 
2444 	sz = sizeof(struct btf_var_secinfo);
2445 	v = btf_add_type_mem(btf, sz);
2446 	if (!v)
2447 		return libbpf_err(-ENOMEM);
2448 
2449 	v->type = var_type_id;
2450 	v->offset = offset;
2451 	v->size = byte_sz;
2452 
2453 	/* update parent type's vlen */
2454 	t = btf_last_type(btf);
2455 	btf_type_inc_vlen(t);
2456 
2457 	btf->hdr->type_len += sz;
2458 	btf->hdr->str_off += sz;
2459 	return 0;
2460 }
2461 
2462 struct btf_ext_sec_setup_param {
2463 	__u32 off;
2464 	__u32 len;
2465 	__u32 min_rec_size;
2466 	struct btf_ext_info *ext_info;
2467 	const char *desc;
2468 };
2469 
btf_ext_setup_info(struct btf_ext * btf_ext,struct btf_ext_sec_setup_param * ext_sec)2470 static int btf_ext_setup_info(struct btf_ext *btf_ext,
2471 			      struct btf_ext_sec_setup_param *ext_sec)
2472 {
2473 	const struct btf_ext_info_sec *sinfo;
2474 	struct btf_ext_info *ext_info;
2475 	__u32 info_left, record_size;
2476 	/* The start of the info sec (including the __u32 record_size). */
2477 	void *info;
2478 
2479 	if (ext_sec->len == 0)
2480 		return 0;
2481 
2482 	if (ext_sec->off & 0x03) {
2483 		pr_debug(".BTF.ext %s section is not aligned to 4 bytes\n",
2484 		     ext_sec->desc);
2485 		return -EINVAL;
2486 	}
2487 
2488 	info = btf_ext->data + btf_ext->hdr->hdr_len + ext_sec->off;
2489 	info_left = ext_sec->len;
2490 
2491 	if (btf_ext->data + btf_ext->data_size < info + ext_sec->len) {
2492 		pr_debug("%s section (off:%u len:%u) is beyond the end of the ELF section .BTF.ext\n",
2493 			 ext_sec->desc, ext_sec->off, ext_sec->len);
2494 		return -EINVAL;
2495 	}
2496 
2497 	/* At least a record size */
2498 	if (info_left < sizeof(__u32)) {
2499 		pr_debug(".BTF.ext %s record size not found\n", ext_sec->desc);
2500 		return -EINVAL;
2501 	}
2502 
2503 	/* The record size needs to meet the minimum standard */
2504 	record_size = *(__u32 *)info;
2505 	if (record_size < ext_sec->min_rec_size ||
2506 	    record_size & 0x03) {
2507 		pr_debug("%s section in .BTF.ext has invalid record size %u\n",
2508 			 ext_sec->desc, record_size);
2509 		return -EINVAL;
2510 	}
2511 
2512 	sinfo = info + sizeof(__u32);
2513 	info_left -= sizeof(__u32);
2514 
2515 	/* If no records, return failure now so .BTF.ext won't be used. */
2516 	if (!info_left) {
2517 		pr_debug("%s section in .BTF.ext has no records", ext_sec->desc);
2518 		return -EINVAL;
2519 	}
2520 
2521 	while (info_left) {
2522 		unsigned int sec_hdrlen = sizeof(struct btf_ext_info_sec);
2523 		__u64 total_record_size;
2524 		__u32 num_records;
2525 
2526 		if (info_left < sec_hdrlen) {
2527 			pr_debug("%s section header is not found in .BTF.ext\n",
2528 			     ext_sec->desc);
2529 			return -EINVAL;
2530 		}
2531 
2532 		num_records = sinfo->num_info;
2533 		if (num_records == 0) {
2534 			pr_debug("%s section has incorrect num_records in .BTF.ext\n",
2535 			     ext_sec->desc);
2536 			return -EINVAL;
2537 		}
2538 
2539 		total_record_size = sec_hdrlen +
2540 				    (__u64)num_records * record_size;
2541 		if (info_left < total_record_size) {
2542 			pr_debug("%s section has incorrect num_records in .BTF.ext\n",
2543 			     ext_sec->desc);
2544 			return -EINVAL;
2545 		}
2546 
2547 		info_left -= total_record_size;
2548 		sinfo = (void *)sinfo + total_record_size;
2549 	}
2550 
2551 	ext_info = ext_sec->ext_info;
2552 	ext_info->len = ext_sec->len - sizeof(__u32);
2553 	ext_info->rec_size = record_size;
2554 	ext_info->info = info + sizeof(__u32);
2555 
2556 	return 0;
2557 }
2558 
btf_ext_setup_func_info(struct btf_ext * btf_ext)2559 static int btf_ext_setup_func_info(struct btf_ext *btf_ext)
2560 {
2561 	struct btf_ext_sec_setup_param param = {
2562 		.off = btf_ext->hdr->func_info_off,
2563 		.len = btf_ext->hdr->func_info_len,
2564 		.min_rec_size = sizeof(struct bpf_func_info_min),
2565 		.ext_info = &btf_ext->func_info,
2566 		.desc = "func_info"
2567 	};
2568 
2569 	return btf_ext_setup_info(btf_ext, &param);
2570 }
2571 
btf_ext_setup_line_info(struct btf_ext * btf_ext)2572 static int btf_ext_setup_line_info(struct btf_ext *btf_ext)
2573 {
2574 	struct btf_ext_sec_setup_param param = {
2575 		.off = btf_ext->hdr->line_info_off,
2576 		.len = btf_ext->hdr->line_info_len,
2577 		.min_rec_size = sizeof(struct bpf_line_info_min),
2578 		.ext_info = &btf_ext->line_info,
2579 		.desc = "line_info",
2580 	};
2581 
2582 	return btf_ext_setup_info(btf_ext, &param);
2583 }
2584 
btf_ext_setup_core_relos(struct btf_ext * btf_ext)2585 static int btf_ext_setup_core_relos(struct btf_ext *btf_ext)
2586 {
2587 	struct btf_ext_sec_setup_param param = {
2588 		.off = btf_ext->hdr->core_relo_off,
2589 		.len = btf_ext->hdr->core_relo_len,
2590 		.min_rec_size = sizeof(struct bpf_core_relo),
2591 		.ext_info = &btf_ext->core_relo_info,
2592 		.desc = "core_relo",
2593 	};
2594 
2595 	return btf_ext_setup_info(btf_ext, &param);
2596 }
2597 
btf_ext_parse_hdr(__u8 * data,__u32 data_size)2598 static int btf_ext_parse_hdr(__u8 *data, __u32 data_size)
2599 {
2600 	const struct btf_ext_header *hdr = (struct btf_ext_header *)data;
2601 
2602 	if (data_size < offsetofend(struct btf_ext_header, hdr_len) ||
2603 	    data_size < hdr->hdr_len) {
2604 		pr_debug("BTF.ext header not found");
2605 		return -EINVAL;
2606 	}
2607 
2608 	if (hdr->magic == bswap_16(BTF_MAGIC)) {
2609 		pr_warn("BTF.ext in non-native endianness is not supported\n");
2610 		return -ENOTSUP;
2611 	} else if (hdr->magic != BTF_MAGIC) {
2612 		pr_debug("Invalid BTF.ext magic:%x\n", hdr->magic);
2613 		return -EINVAL;
2614 	}
2615 
2616 	if (hdr->version != BTF_VERSION) {
2617 		pr_debug("Unsupported BTF.ext version:%u\n", hdr->version);
2618 		return -ENOTSUP;
2619 	}
2620 
2621 	if (hdr->flags) {
2622 		pr_debug("Unsupported BTF.ext flags:%x\n", hdr->flags);
2623 		return -ENOTSUP;
2624 	}
2625 
2626 	if (data_size == hdr->hdr_len) {
2627 		pr_debug("BTF.ext has no data\n");
2628 		return -EINVAL;
2629 	}
2630 
2631 	return 0;
2632 }
2633 
btf_ext__free(struct btf_ext * btf_ext)2634 void btf_ext__free(struct btf_ext *btf_ext)
2635 {
2636 	if (IS_ERR_OR_NULL(btf_ext))
2637 		return;
2638 	free(btf_ext->data);
2639 	free(btf_ext);
2640 }
2641 
btf_ext__new(const __u8 * data,__u32 size)2642 struct btf_ext *btf_ext__new(const __u8 *data, __u32 size)
2643 {
2644 	struct btf_ext *btf_ext;
2645 	int err;
2646 
2647 	btf_ext = calloc(1, sizeof(struct btf_ext));
2648 	if (!btf_ext)
2649 		return libbpf_err_ptr(-ENOMEM);
2650 
2651 	btf_ext->data_size = size;
2652 	btf_ext->data = malloc(size);
2653 	if (!btf_ext->data) {
2654 		err = -ENOMEM;
2655 		goto done;
2656 	}
2657 	memcpy(btf_ext->data, data, size);
2658 
2659 	err = btf_ext_parse_hdr(btf_ext->data, size);
2660 	if (err)
2661 		goto done;
2662 
2663 	if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, line_info_len)) {
2664 		err = -EINVAL;
2665 		goto done;
2666 	}
2667 
2668 	err = btf_ext_setup_func_info(btf_ext);
2669 	if (err)
2670 		goto done;
2671 
2672 	err = btf_ext_setup_line_info(btf_ext);
2673 	if (err)
2674 		goto done;
2675 
2676 	if (btf_ext->hdr->hdr_len < offsetofend(struct btf_ext_header, core_relo_len)) {
2677 		err = -EINVAL;
2678 		goto done;
2679 	}
2680 
2681 	err = btf_ext_setup_core_relos(btf_ext);
2682 	if (err)
2683 		goto done;
2684 
2685 done:
2686 	if (err) {
2687 		btf_ext__free(btf_ext);
2688 		return libbpf_err_ptr(err);
2689 	}
2690 
2691 	return btf_ext;
2692 }
2693 
btf_ext__get_raw_data(const struct btf_ext * btf_ext,__u32 * size)2694 const void *btf_ext__get_raw_data(const struct btf_ext *btf_ext, __u32 *size)
2695 {
2696 	*size = btf_ext->data_size;
2697 	return btf_ext->data;
2698 }
2699 
btf_ext_reloc_info(const struct btf * btf,const struct btf_ext_info * ext_info,const char * sec_name,__u32 insns_cnt,void ** info,__u32 * cnt)2700 static int btf_ext_reloc_info(const struct btf *btf,
2701 			      const struct btf_ext_info *ext_info,
2702 			      const char *sec_name, __u32 insns_cnt,
2703 			      void **info, __u32 *cnt)
2704 {
2705 	__u32 sec_hdrlen = sizeof(struct btf_ext_info_sec);
2706 	__u32 i, record_size, existing_len, records_len;
2707 	struct btf_ext_info_sec *sinfo;
2708 	const char *info_sec_name;
2709 	__u64 remain_len;
2710 	void *data;
2711 
2712 	record_size = ext_info->rec_size;
2713 	sinfo = ext_info->info;
2714 	remain_len = ext_info->len;
2715 	while (remain_len > 0) {
2716 		records_len = sinfo->num_info * record_size;
2717 		info_sec_name = btf__name_by_offset(btf, sinfo->sec_name_off);
2718 		if (strcmp(info_sec_name, sec_name)) {
2719 			remain_len -= sec_hdrlen + records_len;
2720 			sinfo = (void *)sinfo + sec_hdrlen + records_len;
2721 			continue;
2722 		}
2723 
2724 		existing_len = (*cnt) * record_size;
2725 		data = realloc(*info, existing_len + records_len);
2726 		if (!data)
2727 			return libbpf_err(-ENOMEM);
2728 
2729 		memcpy(data + existing_len, sinfo->data, records_len);
2730 		/* adjust insn_off only, the rest data will be passed
2731 		 * to the kernel.
2732 		 */
2733 		for (i = 0; i < sinfo->num_info; i++) {
2734 			__u32 *insn_off;
2735 
2736 			insn_off = data + existing_len + (i * record_size);
2737 			*insn_off = *insn_off / sizeof(struct bpf_insn) + insns_cnt;
2738 		}
2739 		*info = data;
2740 		*cnt += sinfo->num_info;
2741 		return 0;
2742 	}
2743 
2744 	return libbpf_err(-ENOENT);
2745 }
2746 
btf_ext__reloc_func_info(const struct btf * btf,const struct btf_ext * btf_ext,const char * sec_name,__u32 insns_cnt,void ** func_info,__u32 * cnt)2747 int btf_ext__reloc_func_info(const struct btf *btf,
2748 			     const struct btf_ext *btf_ext,
2749 			     const char *sec_name, __u32 insns_cnt,
2750 			     void **func_info, __u32 *cnt)
2751 {
2752 	return btf_ext_reloc_info(btf, &btf_ext->func_info, sec_name,
2753 				  insns_cnt, func_info, cnt);
2754 }
2755 
btf_ext__reloc_line_info(const struct btf * btf,const struct btf_ext * btf_ext,const char * sec_name,__u32 insns_cnt,void ** line_info,__u32 * cnt)2756 int btf_ext__reloc_line_info(const struct btf *btf,
2757 			     const struct btf_ext *btf_ext,
2758 			     const char *sec_name, __u32 insns_cnt,
2759 			     void **line_info, __u32 *cnt)
2760 {
2761 	return btf_ext_reloc_info(btf, &btf_ext->line_info, sec_name,
2762 				  insns_cnt, line_info, cnt);
2763 }
2764 
btf_ext__func_info_rec_size(const struct btf_ext * btf_ext)2765 __u32 btf_ext__func_info_rec_size(const struct btf_ext *btf_ext)
2766 {
2767 	return btf_ext->func_info.rec_size;
2768 }
2769 
btf_ext__line_info_rec_size(const struct btf_ext * btf_ext)2770 __u32 btf_ext__line_info_rec_size(const struct btf_ext *btf_ext)
2771 {
2772 	return btf_ext->line_info.rec_size;
2773 }
2774 
2775 struct btf_dedup;
2776 
2777 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
2778 				       const struct btf_dedup_opts *opts);
2779 static void btf_dedup_free(struct btf_dedup *d);
2780 static int btf_dedup_prep(struct btf_dedup *d);
2781 static int btf_dedup_strings(struct btf_dedup *d);
2782 static int btf_dedup_prim_types(struct btf_dedup *d);
2783 static int btf_dedup_struct_types(struct btf_dedup *d);
2784 static int btf_dedup_ref_types(struct btf_dedup *d);
2785 static int btf_dedup_compact_types(struct btf_dedup *d);
2786 static int btf_dedup_remap_types(struct btf_dedup *d);
2787 
2788 /*
2789  * Deduplicate BTF types and strings.
2790  *
2791  * BTF dedup algorithm takes as an input `struct btf` representing `.BTF` ELF
2792  * section with all BTF type descriptors and string data. It overwrites that
2793  * memory in-place with deduplicated types and strings without any loss of
2794  * information. If optional `struct btf_ext` representing '.BTF.ext' ELF section
2795  * is provided, all the strings referenced from .BTF.ext section are honored
2796  * and updated to point to the right offsets after deduplication.
2797  *
2798  * If function returns with error, type/string data might be garbled and should
2799  * be discarded.
2800  *
2801  * More verbose and detailed description of both problem btf_dedup is solving,
2802  * as well as solution could be found at:
2803  * https://facebookmicrosites.github.io/bpf/blog/2018/11/14/btf-enhancement.html
2804  *
2805  * Problem description and justification
2806  * =====================================
2807  *
2808  * BTF type information is typically emitted either as a result of conversion
2809  * from DWARF to BTF or directly by compiler. In both cases, each compilation
2810  * unit contains information about a subset of all the types that are used
2811  * in an application. These subsets are frequently overlapping and contain a lot
2812  * of duplicated information when later concatenated together into a single
2813  * binary. This algorithm ensures that each unique type is represented by single
2814  * BTF type descriptor, greatly reducing resulting size of BTF data.
2815  *
2816  * Compilation unit isolation and subsequent duplication of data is not the only
2817  * problem. The same type hierarchy (e.g., struct and all the type that struct
2818  * references) in different compilation units can be represented in BTF to
2819  * various degrees of completeness (or, rather, incompleteness) due to
2820  * struct/union forward declarations.
2821  *
2822  * Let's take a look at an example, that we'll use to better understand the
2823  * problem (and solution). Suppose we have two compilation units, each using
2824  * same `struct S`, but each of them having incomplete type information about
2825  * struct's fields:
2826  *
2827  * // CU #1:
2828  * struct S;
2829  * struct A {
2830  *	int a;
2831  *	struct A* self;
2832  *	struct S* parent;
2833  * };
2834  * struct B;
2835  * struct S {
2836  *	struct A* a_ptr;
2837  *	struct B* b_ptr;
2838  * };
2839  *
2840  * // CU #2:
2841  * struct S;
2842  * struct A;
2843  * struct B {
2844  *	int b;
2845  *	struct B* self;
2846  *	struct S* parent;
2847  * };
2848  * struct S {
2849  *	struct A* a_ptr;
2850  *	struct B* b_ptr;
2851  * };
2852  *
2853  * In case of CU #1, BTF data will know only that `struct B` exist (but no
2854  * more), but will know the complete type information about `struct A`. While
2855  * for CU #2, it will know full type information about `struct B`, but will
2856  * only know about forward declaration of `struct A` (in BTF terms, it will
2857  * have `BTF_KIND_FWD` type descriptor with name `B`).
2858  *
2859  * This compilation unit isolation means that it's possible that there is no
2860  * single CU with complete type information describing structs `S`, `A`, and
2861  * `B`. Also, we might get tons of duplicated and redundant type information.
2862  *
2863  * Additional complication we need to keep in mind comes from the fact that
2864  * types, in general, can form graphs containing cycles, not just DAGs.
2865  *
2866  * While algorithm does deduplication, it also merges and resolves type
2867  * information (unless disabled throught `struct btf_opts`), whenever possible.
2868  * E.g., in the example above with two compilation units having partial type
2869  * information for structs `A` and `B`, the output of algorithm will emit
2870  * a single copy of each BTF type that describes structs `A`, `B`, and `S`
2871  * (as well as type information for `int` and pointers), as if they were defined
2872  * in a single compilation unit as:
2873  *
2874  * struct A {
2875  *	int a;
2876  *	struct A* self;
2877  *	struct S* parent;
2878  * };
2879  * struct B {
2880  *	int b;
2881  *	struct B* self;
2882  *	struct S* parent;
2883  * };
2884  * struct S {
2885  *	struct A* a_ptr;
2886  *	struct B* b_ptr;
2887  * };
2888  *
2889  * Algorithm summary
2890  * =================
2891  *
2892  * Algorithm completes its work in 6 separate passes:
2893  *
2894  * 1. Strings deduplication.
2895  * 2. Primitive types deduplication (int, enum, fwd).
2896  * 3. Struct/union types deduplication.
2897  * 4. Reference types deduplication (pointers, typedefs, arrays, funcs, func
2898  *    protos, and const/volatile/restrict modifiers).
2899  * 5. Types compaction.
2900  * 6. Types remapping.
2901  *
2902  * Algorithm determines canonical type descriptor, which is a single
2903  * representative type for each truly unique type. This canonical type is the
2904  * one that will go into final deduplicated BTF type information. For
2905  * struct/unions, it is also the type that algorithm will merge additional type
2906  * information into (while resolving FWDs), as it discovers it from data in
2907  * other CUs. Each input BTF type eventually gets either mapped to itself, if
2908  * that type is canonical, or to some other type, if that type is equivalent
2909  * and was chosen as canonical representative. This mapping is stored in
2910  * `btf_dedup->map` array. This map is also used to record STRUCT/UNION that
2911  * FWD type got resolved to.
2912  *
2913  * To facilitate fast discovery of canonical types, we also maintain canonical
2914  * index (`btf_dedup->dedup_table`), which maps type descriptor's signature hash
2915  * (i.e., hashed kind, name, size, fields, etc) into a list of canonical types
2916  * that match that signature. With sufficiently good choice of type signature
2917  * hashing function, we can limit number of canonical types for each unique type
2918  * signature to a very small number, allowing to find canonical type for any
2919  * duplicated type very quickly.
2920  *
2921  * Struct/union deduplication is the most critical part and algorithm for
2922  * deduplicating structs/unions is described in greater details in comments for
2923  * `btf_dedup_is_equiv` function.
2924  */
btf__dedup(struct btf * btf,struct btf_ext * btf_ext,const struct btf_dedup_opts * opts)2925 int btf__dedup(struct btf *btf, struct btf_ext *btf_ext,
2926 	       const struct btf_dedup_opts *opts)
2927 {
2928 	struct btf_dedup *d = btf_dedup_new(btf, btf_ext, opts);
2929 	int err;
2930 
2931 	if (IS_ERR(d)) {
2932 		pr_debug("btf_dedup_new failed: %ld", PTR_ERR(d));
2933 		return libbpf_err(-EINVAL);
2934 	}
2935 
2936 	if (btf_ensure_modifiable(btf)) {
2937 		err = -ENOMEM;
2938 		goto done;
2939 	}
2940 
2941 	err = btf_dedup_prep(d);
2942 	if (err) {
2943 		pr_debug("btf_dedup_prep failed:%d\n", err);
2944 		goto done;
2945 	}
2946 	err = btf_dedup_strings(d);
2947 	if (err < 0) {
2948 		pr_debug("btf_dedup_strings failed:%d\n", err);
2949 		goto done;
2950 	}
2951 	err = btf_dedup_prim_types(d);
2952 	if (err < 0) {
2953 		pr_debug("btf_dedup_prim_types failed:%d\n", err);
2954 		goto done;
2955 	}
2956 	err = btf_dedup_struct_types(d);
2957 	if (err < 0) {
2958 		pr_debug("btf_dedup_struct_types failed:%d\n", err);
2959 		goto done;
2960 	}
2961 	err = btf_dedup_ref_types(d);
2962 	if (err < 0) {
2963 		pr_debug("btf_dedup_ref_types failed:%d\n", err);
2964 		goto done;
2965 	}
2966 	err = btf_dedup_compact_types(d);
2967 	if (err < 0) {
2968 		pr_debug("btf_dedup_compact_types failed:%d\n", err);
2969 		goto done;
2970 	}
2971 	err = btf_dedup_remap_types(d);
2972 	if (err < 0) {
2973 		pr_debug("btf_dedup_remap_types failed:%d\n", err);
2974 		goto done;
2975 	}
2976 
2977 done:
2978 	btf_dedup_free(d);
2979 	return libbpf_err(err);
2980 }
2981 
2982 #define BTF_UNPROCESSED_ID ((__u32)-1)
2983 #define BTF_IN_PROGRESS_ID ((__u32)-2)
2984 
2985 struct btf_dedup {
2986 	/* .BTF section to be deduped in-place */
2987 	struct btf *btf;
2988 	/*
2989 	 * Optional .BTF.ext section. When provided, any strings referenced
2990 	 * from it will be taken into account when deduping strings
2991 	 */
2992 	struct btf_ext *btf_ext;
2993 	/*
2994 	 * This is a map from any type's signature hash to a list of possible
2995 	 * canonical representative type candidates. Hash collisions are
2996 	 * ignored, so even types of various kinds can share same list of
2997 	 * candidates, which is fine because we rely on subsequent
2998 	 * btf_xxx_equal() checks to authoritatively verify type equality.
2999 	 */
3000 	struct hashmap *dedup_table;
3001 	/* Canonical types map */
3002 	__u32 *map;
3003 	/* Hypothetical mapping, used during type graph equivalence checks */
3004 	__u32 *hypot_map;
3005 	__u32 *hypot_list;
3006 	size_t hypot_cnt;
3007 	size_t hypot_cap;
3008 	/* Whether hypothetical mapping, if successful, would need to adjust
3009 	 * already canonicalized types (due to a new forward declaration to
3010 	 * concrete type resolution). In such case, during split BTF dedup
3011 	 * candidate type would still be considered as different, because base
3012 	 * BTF is considered to be immutable.
3013 	 */
3014 	bool hypot_adjust_canon;
3015 	/* Various option modifying behavior of algorithm */
3016 	struct btf_dedup_opts opts;
3017 	/* temporary strings deduplication state */
3018 	struct strset *strs_set;
3019 };
3020 
hash_combine(long h,long value)3021 static long hash_combine(long h, long value)
3022 {
3023 	return h * 31 + value;
3024 }
3025 
3026 #define for_each_dedup_cand(d, node, hash) \
3027 	hashmap__for_each_key_entry(d->dedup_table, node, (void *)hash)
3028 
btf_dedup_table_add(struct btf_dedup * d,long hash,__u32 type_id)3029 static int btf_dedup_table_add(struct btf_dedup *d, long hash, __u32 type_id)
3030 {
3031 	return hashmap__append(d->dedup_table,
3032 			       (void *)hash, (void *)(long)type_id);
3033 }
3034 
btf_dedup_hypot_map_add(struct btf_dedup * d,__u32 from_id,__u32 to_id)3035 static int btf_dedup_hypot_map_add(struct btf_dedup *d,
3036 				   __u32 from_id, __u32 to_id)
3037 {
3038 	if (d->hypot_cnt == d->hypot_cap) {
3039 		__u32 *new_list;
3040 
3041 		d->hypot_cap += max((size_t)16, d->hypot_cap / 2);
3042 		new_list = libbpf_reallocarray(d->hypot_list, d->hypot_cap, sizeof(__u32));
3043 		if (!new_list)
3044 			return -ENOMEM;
3045 		d->hypot_list = new_list;
3046 	}
3047 	d->hypot_list[d->hypot_cnt++] = from_id;
3048 	d->hypot_map[from_id] = to_id;
3049 	return 0;
3050 }
3051 
btf_dedup_clear_hypot_map(struct btf_dedup * d)3052 static void btf_dedup_clear_hypot_map(struct btf_dedup *d)
3053 {
3054 	int i;
3055 
3056 	for (i = 0; i < d->hypot_cnt; i++)
3057 		d->hypot_map[d->hypot_list[i]] = BTF_UNPROCESSED_ID;
3058 	d->hypot_cnt = 0;
3059 	d->hypot_adjust_canon = false;
3060 }
3061 
btf_dedup_free(struct btf_dedup * d)3062 static void btf_dedup_free(struct btf_dedup *d)
3063 {
3064 	hashmap__free(d->dedup_table);
3065 	d->dedup_table = NULL;
3066 
3067 	free(d->map);
3068 	d->map = NULL;
3069 
3070 	free(d->hypot_map);
3071 	d->hypot_map = NULL;
3072 
3073 	free(d->hypot_list);
3074 	d->hypot_list = NULL;
3075 
3076 	free(d);
3077 }
3078 
btf_dedup_identity_hash_fn(const void * key,void * ctx)3079 static size_t btf_dedup_identity_hash_fn(const void *key, void *ctx)
3080 {
3081 	return (size_t)key;
3082 }
3083 
btf_dedup_collision_hash_fn(const void * key,void * ctx)3084 static size_t btf_dedup_collision_hash_fn(const void *key, void *ctx)
3085 {
3086 	return 0;
3087 }
3088 
btf_dedup_equal_fn(const void * k1,const void * k2,void * ctx)3089 static bool btf_dedup_equal_fn(const void *k1, const void *k2, void *ctx)
3090 {
3091 	return k1 == k2;
3092 }
3093 
btf_dedup_new(struct btf * btf,struct btf_ext * btf_ext,const struct btf_dedup_opts * opts)3094 static struct btf_dedup *btf_dedup_new(struct btf *btf, struct btf_ext *btf_ext,
3095 				       const struct btf_dedup_opts *opts)
3096 {
3097 	struct btf_dedup *d = calloc(1, sizeof(struct btf_dedup));
3098 	hashmap_hash_fn hash_fn = btf_dedup_identity_hash_fn;
3099 	int i, err = 0, type_cnt;
3100 
3101 	if (!d)
3102 		return ERR_PTR(-ENOMEM);
3103 
3104 	d->opts.dont_resolve_fwds = opts && opts->dont_resolve_fwds;
3105 	/* dedup_table_size is now used only to force collisions in tests */
3106 	if (opts && opts->dedup_table_size == 1)
3107 		hash_fn = btf_dedup_collision_hash_fn;
3108 
3109 	d->btf = btf;
3110 	d->btf_ext = btf_ext;
3111 
3112 	d->dedup_table = hashmap__new(hash_fn, btf_dedup_equal_fn, NULL);
3113 	if (IS_ERR(d->dedup_table)) {
3114 		err = PTR_ERR(d->dedup_table);
3115 		d->dedup_table = NULL;
3116 		goto done;
3117 	}
3118 
3119 	type_cnt = btf__get_nr_types(btf) + 1;
3120 	d->map = malloc(sizeof(__u32) * type_cnt);
3121 	if (!d->map) {
3122 		err = -ENOMEM;
3123 		goto done;
3124 	}
3125 	/* special BTF "void" type is made canonical immediately */
3126 	d->map[0] = 0;
3127 	for (i = 1; i < type_cnt; i++) {
3128 		struct btf_type *t = btf_type_by_id(d->btf, i);
3129 
3130 		/* VAR and DATASEC are never deduped and are self-canonical */
3131 		if (btf_is_var(t) || btf_is_datasec(t))
3132 			d->map[i] = i;
3133 		else
3134 			d->map[i] = BTF_UNPROCESSED_ID;
3135 	}
3136 
3137 	d->hypot_map = malloc(sizeof(__u32) * type_cnt);
3138 	if (!d->hypot_map) {
3139 		err = -ENOMEM;
3140 		goto done;
3141 	}
3142 	for (i = 0; i < type_cnt; i++)
3143 		d->hypot_map[i] = BTF_UNPROCESSED_ID;
3144 
3145 done:
3146 	if (err) {
3147 		btf_dedup_free(d);
3148 		return ERR_PTR(err);
3149 	}
3150 
3151 	return d;
3152 }
3153 
3154 /*
3155  * Iterate over all possible places in .BTF and .BTF.ext that can reference
3156  * string and pass pointer to it to a provided callback `fn`.
3157  */
btf_for_each_str_off(struct btf_dedup * d,str_off_visit_fn fn,void * ctx)3158 static int btf_for_each_str_off(struct btf_dedup *d, str_off_visit_fn fn, void *ctx)
3159 {
3160 	int i, r;
3161 
3162 	for (i = 0; i < d->btf->nr_types; i++) {
3163 		struct btf_type *t = btf_type_by_id(d->btf, d->btf->start_id + i);
3164 
3165 		r = btf_type_visit_str_offs(t, fn, ctx);
3166 		if (r)
3167 			return r;
3168 	}
3169 
3170 	if (!d->btf_ext)
3171 		return 0;
3172 
3173 	r = btf_ext_visit_str_offs(d->btf_ext, fn, ctx);
3174 	if (r)
3175 		return r;
3176 
3177 	return 0;
3178 }
3179 
strs_dedup_remap_str_off(__u32 * str_off_ptr,void * ctx)3180 static int strs_dedup_remap_str_off(__u32 *str_off_ptr, void *ctx)
3181 {
3182 	struct btf_dedup *d = ctx;
3183 	__u32 str_off = *str_off_ptr;
3184 	const char *s;
3185 	int off, err;
3186 
3187 	/* don't touch empty string or string in main BTF */
3188 	if (str_off == 0 || str_off < d->btf->start_str_off)
3189 		return 0;
3190 
3191 	s = btf__str_by_offset(d->btf, str_off);
3192 	if (d->btf->base_btf) {
3193 		err = btf__find_str(d->btf->base_btf, s);
3194 		if (err >= 0) {
3195 			*str_off_ptr = err;
3196 			return 0;
3197 		}
3198 		if (err != -ENOENT)
3199 			return err;
3200 	}
3201 
3202 	off = strset__add_str(d->strs_set, s);
3203 	if (off < 0)
3204 		return off;
3205 
3206 	*str_off_ptr = d->btf->start_str_off + off;
3207 	return 0;
3208 }
3209 
3210 /*
3211  * Dedup string and filter out those that are not referenced from either .BTF
3212  * or .BTF.ext (if provided) sections.
3213  *
3214  * This is done by building index of all strings in BTF's string section,
3215  * then iterating over all entities that can reference strings (e.g., type
3216  * names, struct field names, .BTF.ext line info, etc) and marking corresponding
3217  * strings as used. After that all used strings are deduped and compacted into
3218  * sequential blob of memory and new offsets are calculated. Then all the string
3219  * references are iterated again and rewritten using new offsets.
3220  */
btf_dedup_strings(struct btf_dedup * d)3221 static int btf_dedup_strings(struct btf_dedup *d)
3222 {
3223 	int err;
3224 
3225 	if (d->btf->strs_deduped)
3226 		return 0;
3227 
3228 	d->strs_set = strset__new(BTF_MAX_STR_OFFSET, NULL, 0);
3229 	if (IS_ERR(d->strs_set)) {
3230 		err = PTR_ERR(d->strs_set);
3231 		goto err_out;
3232 	}
3233 
3234 	if (!d->btf->base_btf) {
3235 		/* insert empty string; we won't be looking it up during strings
3236 		 * dedup, but it's good to have it for generic BTF string lookups
3237 		 */
3238 		err = strset__add_str(d->strs_set, "");
3239 		if (err < 0)
3240 			goto err_out;
3241 	}
3242 
3243 	/* remap string offsets */
3244 	err = btf_for_each_str_off(d, strs_dedup_remap_str_off, d);
3245 	if (err)
3246 		goto err_out;
3247 
3248 	/* replace BTF string data and hash with deduped ones */
3249 	strset__free(d->btf->strs_set);
3250 	d->btf->hdr->str_len = strset__data_size(d->strs_set);
3251 	d->btf->strs_set = d->strs_set;
3252 	d->strs_set = NULL;
3253 	d->btf->strs_deduped = true;
3254 	return 0;
3255 
3256 err_out:
3257 	strset__free(d->strs_set);
3258 	d->strs_set = NULL;
3259 
3260 	return err;
3261 }
3262 
btf_hash_common(struct btf_type * t)3263 static long btf_hash_common(struct btf_type *t)
3264 {
3265 	long h;
3266 
3267 	h = hash_combine(0, t->name_off);
3268 	h = hash_combine(h, t->info);
3269 	h = hash_combine(h, t->size);
3270 	return h;
3271 }
3272 
btf_equal_common(struct btf_type * t1,struct btf_type * t2)3273 static bool btf_equal_common(struct btf_type *t1, struct btf_type *t2)
3274 {
3275 	return t1->name_off == t2->name_off &&
3276 	       t1->info == t2->info &&
3277 	       t1->size == t2->size;
3278 }
3279 
3280 /* Calculate type signature hash of INT. */
btf_hash_int(struct btf_type * t)3281 static long btf_hash_int(struct btf_type *t)
3282 {
3283 	__u32 info = *(__u32 *)(t + 1);
3284 	long h;
3285 
3286 	h = btf_hash_common(t);
3287 	h = hash_combine(h, info);
3288 	return h;
3289 }
3290 
3291 /* Check structural equality of two INTs. */
btf_equal_int(struct btf_type * t1,struct btf_type * t2)3292 static bool btf_equal_int(struct btf_type *t1, struct btf_type *t2)
3293 {
3294 	__u32 info1, info2;
3295 
3296 	if (!btf_equal_common(t1, t2))
3297 		return false;
3298 	info1 = *(__u32 *)(t1 + 1);
3299 	info2 = *(__u32 *)(t2 + 1);
3300 	return info1 == info2;
3301 }
3302 
3303 /* Calculate type signature hash of ENUM. */
btf_hash_enum(struct btf_type * t)3304 static long btf_hash_enum(struct btf_type *t)
3305 {
3306 	long h;
3307 
3308 	/* don't hash vlen and enum members to support enum fwd resolving */
3309 	h = hash_combine(0, t->name_off);
3310 	h = hash_combine(h, t->info & ~0xffff);
3311 	h = hash_combine(h, t->size);
3312 	return h;
3313 }
3314 
3315 /* Check structural equality of two ENUMs. */
btf_equal_enum(struct btf_type * t1,struct btf_type * t2)3316 static bool btf_equal_enum(struct btf_type *t1, struct btf_type *t2)
3317 {
3318 	const struct btf_enum *m1, *m2;
3319 	__u16 vlen;
3320 	int i;
3321 
3322 	if (!btf_equal_common(t1, t2))
3323 		return false;
3324 
3325 	vlen = btf_vlen(t1);
3326 	m1 = btf_enum(t1);
3327 	m2 = btf_enum(t2);
3328 	for (i = 0; i < vlen; i++) {
3329 		if (m1->name_off != m2->name_off || m1->val != m2->val)
3330 			return false;
3331 		m1++;
3332 		m2++;
3333 	}
3334 	return true;
3335 }
3336 
btf_is_enum_fwd(struct btf_type * t)3337 static inline bool btf_is_enum_fwd(struct btf_type *t)
3338 {
3339 	return btf_is_enum(t) && btf_vlen(t) == 0;
3340 }
3341 
btf_compat_enum(struct btf_type * t1,struct btf_type * t2)3342 static bool btf_compat_enum(struct btf_type *t1, struct btf_type *t2)
3343 {
3344 	if (!btf_is_enum_fwd(t1) && !btf_is_enum_fwd(t2))
3345 		return btf_equal_enum(t1, t2);
3346 	/* ignore vlen when comparing */
3347 	return t1->name_off == t2->name_off &&
3348 	       (t1->info & ~0xffff) == (t2->info & ~0xffff) &&
3349 	       t1->size == t2->size;
3350 }
3351 
3352 /*
3353  * Calculate type signature hash of STRUCT/UNION, ignoring referenced type IDs,
3354  * as referenced type IDs equivalence is established separately during type
3355  * graph equivalence check algorithm.
3356  */
btf_hash_struct(struct btf_type * t)3357 static long btf_hash_struct(struct btf_type *t)
3358 {
3359 	const struct btf_member *member = btf_members(t);
3360 	__u32 vlen = btf_vlen(t);
3361 	long h = btf_hash_common(t);
3362 	int i;
3363 
3364 	for (i = 0; i < vlen; i++) {
3365 		h = hash_combine(h, member->name_off);
3366 		h = hash_combine(h, member->offset);
3367 		/* no hashing of referenced type ID, it can be unresolved yet */
3368 		member++;
3369 	}
3370 	return h;
3371 }
3372 
3373 /*
3374  * Check structural compatibility of two STRUCTs/UNIONs, ignoring referenced
3375  * type IDs. This check is performed during type graph equivalence check and
3376  * referenced types equivalence is checked separately.
3377  */
btf_shallow_equal_struct(struct btf_type * t1,struct btf_type * t2)3378 static bool btf_shallow_equal_struct(struct btf_type *t1, struct btf_type *t2)
3379 {
3380 	const struct btf_member *m1, *m2;
3381 	__u16 vlen;
3382 	int i;
3383 
3384 	if (!btf_equal_common(t1, t2))
3385 		return false;
3386 
3387 	vlen = btf_vlen(t1);
3388 	m1 = btf_members(t1);
3389 	m2 = btf_members(t2);
3390 	for (i = 0; i < vlen; i++) {
3391 		if (m1->name_off != m2->name_off || m1->offset != m2->offset)
3392 			return false;
3393 		m1++;
3394 		m2++;
3395 	}
3396 	return true;
3397 }
3398 
3399 /*
3400  * Calculate type signature hash of ARRAY, including referenced type IDs,
3401  * under assumption that they were already resolved to canonical type IDs and
3402  * are not going to change.
3403  */
btf_hash_array(struct btf_type * t)3404 static long btf_hash_array(struct btf_type *t)
3405 {
3406 	const struct btf_array *info = btf_array(t);
3407 	long h = btf_hash_common(t);
3408 
3409 	h = hash_combine(h, info->type);
3410 	h = hash_combine(h, info->index_type);
3411 	h = hash_combine(h, info->nelems);
3412 	return h;
3413 }
3414 
3415 /*
3416  * Check exact equality of two ARRAYs, taking into account referenced
3417  * type IDs, under assumption that they were already resolved to canonical
3418  * type IDs and are not going to change.
3419  * This function is called during reference types deduplication to compare
3420  * ARRAY to potential canonical representative.
3421  */
btf_equal_array(struct btf_type * t1,struct btf_type * t2)3422 static bool btf_equal_array(struct btf_type *t1, struct btf_type *t2)
3423 {
3424 	const struct btf_array *info1, *info2;
3425 
3426 	if (!btf_equal_common(t1, t2))
3427 		return false;
3428 
3429 	info1 = btf_array(t1);
3430 	info2 = btf_array(t2);
3431 	return info1->type == info2->type &&
3432 	       info1->index_type == info2->index_type &&
3433 	       info1->nelems == info2->nelems;
3434 }
3435 
3436 /*
3437  * Check structural compatibility of two ARRAYs, ignoring referenced type
3438  * IDs. This check is performed during type graph equivalence check and
3439  * referenced types equivalence is checked separately.
3440  */
btf_compat_array(struct btf_type * t1,struct btf_type * t2)3441 static bool btf_compat_array(struct btf_type *t1, struct btf_type *t2)
3442 {
3443 	if (!btf_equal_common(t1, t2))
3444 		return false;
3445 
3446 	return btf_array(t1)->nelems == btf_array(t2)->nelems;
3447 }
3448 
3449 /*
3450  * Calculate type signature hash of FUNC_PROTO, including referenced type IDs,
3451  * under assumption that they were already resolved to canonical type IDs and
3452  * are not going to change.
3453  */
btf_hash_fnproto(struct btf_type * t)3454 static long btf_hash_fnproto(struct btf_type *t)
3455 {
3456 	const struct btf_param *member = btf_params(t);
3457 	__u16 vlen = btf_vlen(t);
3458 	long h = btf_hash_common(t);
3459 	int i;
3460 
3461 	for (i = 0; i < vlen; i++) {
3462 		h = hash_combine(h, member->name_off);
3463 		h = hash_combine(h, member->type);
3464 		member++;
3465 	}
3466 	return h;
3467 }
3468 
3469 /*
3470  * Check exact equality of two FUNC_PROTOs, taking into account referenced
3471  * type IDs, under assumption that they were already resolved to canonical
3472  * type IDs and are not going to change.
3473  * This function is called during reference types deduplication to compare
3474  * FUNC_PROTO to potential canonical representative.
3475  */
btf_equal_fnproto(struct btf_type * t1,struct btf_type * t2)3476 static bool btf_equal_fnproto(struct btf_type *t1, struct btf_type *t2)
3477 {
3478 	const struct btf_param *m1, *m2;
3479 	__u16 vlen;
3480 	int i;
3481 
3482 	if (!btf_equal_common(t1, t2))
3483 		return false;
3484 
3485 	vlen = btf_vlen(t1);
3486 	m1 = btf_params(t1);
3487 	m2 = btf_params(t2);
3488 	for (i = 0; i < vlen; i++) {
3489 		if (m1->name_off != m2->name_off || m1->type != m2->type)
3490 			return false;
3491 		m1++;
3492 		m2++;
3493 	}
3494 	return true;
3495 }
3496 
3497 /*
3498  * Check structural compatibility of two FUNC_PROTOs, ignoring referenced type
3499  * IDs. This check is performed during type graph equivalence check and
3500  * referenced types equivalence is checked separately.
3501  */
btf_compat_fnproto(struct btf_type * t1,struct btf_type * t2)3502 static bool btf_compat_fnproto(struct btf_type *t1, struct btf_type *t2)
3503 {
3504 	const struct btf_param *m1, *m2;
3505 	__u16 vlen;
3506 	int i;
3507 
3508 	/* skip return type ID */
3509 	if (t1->name_off != t2->name_off || t1->info != t2->info)
3510 		return false;
3511 
3512 	vlen = btf_vlen(t1);
3513 	m1 = btf_params(t1);
3514 	m2 = btf_params(t2);
3515 	for (i = 0; i < vlen; i++) {
3516 		if (m1->name_off != m2->name_off)
3517 			return false;
3518 		m1++;
3519 		m2++;
3520 	}
3521 	return true;
3522 }
3523 
3524 /* Prepare split BTF for deduplication by calculating hashes of base BTF's
3525  * types and initializing the rest of the state (canonical type mapping) for
3526  * the fixed base BTF part.
3527  */
btf_dedup_prep(struct btf_dedup * d)3528 static int btf_dedup_prep(struct btf_dedup *d)
3529 {
3530 	struct btf_type *t;
3531 	int type_id;
3532 	long h;
3533 
3534 	if (!d->btf->base_btf)
3535 		return 0;
3536 
3537 	for (type_id = 1; type_id < d->btf->start_id; type_id++) {
3538 		t = btf_type_by_id(d->btf, type_id);
3539 
3540 		/* all base BTF types are self-canonical by definition */
3541 		d->map[type_id] = type_id;
3542 
3543 		switch (btf_kind(t)) {
3544 		case BTF_KIND_VAR:
3545 		case BTF_KIND_DATASEC:
3546 			/* VAR and DATASEC are never hash/deduplicated */
3547 			continue;
3548 		case BTF_KIND_CONST:
3549 		case BTF_KIND_VOLATILE:
3550 		case BTF_KIND_RESTRICT:
3551 		case BTF_KIND_PTR:
3552 		case BTF_KIND_FWD:
3553 		case BTF_KIND_TYPEDEF:
3554 		case BTF_KIND_FUNC:
3555 		case BTF_KIND_FLOAT:
3556 			h = btf_hash_common(t);
3557 			break;
3558 		case BTF_KIND_INT:
3559 			h = btf_hash_int(t);
3560 			break;
3561 		case BTF_KIND_ENUM:
3562 			h = btf_hash_enum(t);
3563 			break;
3564 		case BTF_KIND_STRUCT:
3565 		case BTF_KIND_UNION:
3566 			h = btf_hash_struct(t);
3567 			break;
3568 		case BTF_KIND_ARRAY:
3569 			h = btf_hash_array(t);
3570 			break;
3571 		case BTF_KIND_FUNC_PROTO:
3572 			h = btf_hash_fnproto(t);
3573 			break;
3574 		default:
3575 			pr_debug("unknown kind %d for type [%d]\n", btf_kind(t), type_id);
3576 			return -EINVAL;
3577 		}
3578 		if (btf_dedup_table_add(d, h, type_id))
3579 			return -ENOMEM;
3580 	}
3581 
3582 	return 0;
3583 }
3584 
3585 /*
3586  * Deduplicate primitive types, that can't reference other types, by calculating
3587  * their type signature hash and comparing them with any possible canonical
3588  * candidate. If no canonical candidate matches, type itself is marked as
3589  * canonical and is added into `btf_dedup->dedup_table` as another candidate.
3590  */
btf_dedup_prim_type(struct btf_dedup * d,__u32 type_id)3591 static int btf_dedup_prim_type(struct btf_dedup *d, __u32 type_id)
3592 {
3593 	struct btf_type *t = btf_type_by_id(d->btf, type_id);
3594 	struct hashmap_entry *hash_entry;
3595 	struct btf_type *cand;
3596 	/* if we don't find equivalent type, then we are canonical */
3597 	__u32 new_id = type_id;
3598 	__u32 cand_id;
3599 	long h;
3600 
3601 	switch (btf_kind(t)) {
3602 	case BTF_KIND_CONST:
3603 	case BTF_KIND_VOLATILE:
3604 	case BTF_KIND_RESTRICT:
3605 	case BTF_KIND_PTR:
3606 	case BTF_KIND_TYPEDEF:
3607 	case BTF_KIND_ARRAY:
3608 	case BTF_KIND_STRUCT:
3609 	case BTF_KIND_UNION:
3610 	case BTF_KIND_FUNC:
3611 	case BTF_KIND_FUNC_PROTO:
3612 	case BTF_KIND_VAR:
3613 	case BTF_KIND_DATASEC:
3614 		return 0;
3615 
3616 	case BTF_KIND_INT:
3617 		h = btf_hash_int(t);
3618 		for_each_dedup_cand(d, hash_entry, h) {
3619 			cand_id = (__u32)(long)hash_entry->value;
3620 			cand = btf_type_by_id(d->btf, cand_id);
3621 			if (btf_equal_int(t, cand)) {
3622 				new_id = cand_id;
3623 				break;
3624 			}
3625 		}
3626 		break;
3627 
3628 	case BTF_KIND_ENUM:
3629 		h = btf_hash_enum(t);
3630 		for_each_dedup_cand(d, hash_entry, h) {
3631 			cand_id = (__u32)(long)hash_entry->value;
3632 			cand = btf_type_by_id(d->btf, cand_id);
3633 			if (btf_equal_enum(t, cand)) {
3634 				new_id = cand_id;
3635 				break;
3636 			}
3637 			if (d->opts.dont_resolve_fwds)
3638 				continue;
3639 			if (btf_compat_enum(t, cand)) {
3640 				if (btf_is_enum_fwd(t)) {
3641 					/* resolve fwd to full enum */
3642 					new_id = cand_id;
3643 					break;
3644 				}
3645 				/* resolve canonical enum fwd to full enum */
3646 				d->map[cand_id] = type_id;
3647 			}
3648 		}
3649 		break;
3650 
3651 	case BTF_KIND_FWD:
3652 	case BTF_KIND_FLOAT:
3653 		h = btf_hash_common(t);
3654 		for_each_dedup_cand(d, hash_entry, h) {
3655 			cand_id = (__u32)(long)hash_entry->value;
3656 			cand = btf_type_by_id(d->btf, cand_id);
3657 			if (btf_equal_common(t, cand)) {
3658 				new_id = cand_id;
3659 				break;
3660 			}
3661 		}
3662 		break;
3663 
3664 	default:
3665 		return -EINVAL;
3666 	}
3667 
3668 	d->map[type_id] = new_id;
3669 	if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
3670 		return -ENOMEM;
3671 
3672 	return 0;
3673 }
3674 
btf_dedup_prim_types(struct btf_dedup * d)3675 static int btf_dedup_prim_types(struct btf_dedup *d)
3676 {
3677 	int i, err;
3678 
3679 	for (i = 0; i < d->btf->nr_types; i++) {
3680 		err = btf_dedup_prim_type(d, d->btf->start_id + i);
3681 		if (err)
3682 			return err;
3683 	}
3684 	return 0;
3685 }
3686 
3687 /*
3688  * Check whether type is already mapped into canonical one (could be to itself).
3689  */
is_type_mapped(struct btf_dedup * d,uint32_t type_id)3690 static inline bool is_type_mapped(struct btf_dedup *d, uint32_t type_id)
3691 {
3692 	return d->map[type_id] <= BTF_MAX_NR_TYPES;
3693 }
3694 
3695 /*
3696  * Resolve type ID into its canonical type ID, if any; otherwise return original
3697  * type ID. If type is FWD and is resolved into STRUCT/UNION already, follow
3698  * STRUCT/UNION link and resolve it into canonical type ID as well.
3699  */
resolve_type_id(struct btf_dedup * d,__u32 type_id)3700 static inline __u32 resolve_type_id(struct btf_dedup *d, __u32 type_id)
3701 {
3702 	while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
3703 		type_id = d->map[type_id];
3704 	return type_id;
3705 }
3706 
3707 /*
3708  * Resolve FWD to underlying STRUCT/UNION, if any; otherwise return original
3709  * type ID.
3710  */
resolve_fwd_id(struct btf_dedup * d,uint32_t type_id)3711 static uint32_t resolve_fwd_id(struct btf_dedup *d, uint32_t type_id)
3712 {
3713 	__u32 orig_type_id = type_id;
3714 
3715 	if (!btf_is_fwd(btf__type_by_id(d->btf, type_id)))
3716 		return type_id;
3717 
3718 	while (is_type_mapped(d, type_id) && d->map[type_id] != type_id)
3719 		type_id = d->map[type_id];
3720 
3721 	if (!btf_is_fwd(btf__type_by_id(d->btf, type_id)))
3722 		return type_id;
3723 
3724 	return orig_type_id;
3725 }
3726 
3727 
btf_fwd_kind(struct btf_type * t)3728 static inline __u16 btf_fwd_kind(struct btf_type *t)
3729 {
3730 	return btf_kflag(t) ? BTF_KIND_UNION : BTF_KIND_STRUCT;
3731 }
3732 
3733 /* Check if given two types are identical ARRAY definitions */
btf_dedup_identical_arrays(struct btf_dedup * d,__u32 id1,__u32 id2)3734 static bool btf_dedup_identical_arrays(struct btf_dedup *d, __u32 id1, __u32 id2)
3735 {
3736 	struct btf_type *t1, *t2;
3737 
3738 	t1 = btf_type_by_id(d->btf, id1);
3739 	t2 = btf_type_by_id(d->btf, id2);
3740 	if (!btf_is_array(t1) || !btf_is_array(t2))
3741 		return false;
3742 
3743 	return btf_equal_array(t1, t2);
3744 }
3745 
3746 /* Check if given two types are identical STRUCT/UNION definitions */
btf_dedup_identical_structs(struct btf_dedup * d,__u32 id1,__u32 id2)3747 static bool btf_dedup_identical_structs(struct btf_dedup *d, __u32 id1, __u32 id2)
3748 {
3749 	const struct btf_member *m1, *m2;
3750 	struct btf_type *t1, *t2;
3751 	int n, i;
3752 
3753 	t1 = btf_type_by_id(d->btf, id1);
3754 	t2 = btf_type_by_id(d->btf, id2);
3755 
3756 	if (!btf_is_composite(t1) || btf_kind(t1) != btf_kind(t2))
3757 		return false;
3758 
3759 	if (!btf_shallow_equal_struct(t1, t2))
3760 		return false;
3761 
3762 	m1 = btf_members(t1);
3763 	m2 = btf_members(t2);
3764 	for (i = 0, n = btf_vlen(t1); i < n; i++, m1++, m2++) {
3765 		if (m1->type != m2->type &&
3766 		    !btf_dedup_identical_arrays(d, m1->type, m2->type) &&
3767 		    !btf_dedup_identical_structs(d, m1->type, m2->type))
3768 			return false;
3769 	}
3770 	return true;
3771 }
3772 
3773 /*
3774  * Check equivalence of BTF type graph formed by candidate struct/union (we'll
3775  * call it "candidate graph" in this description for brevity) to a type graph
3776  * formed by (potential) canonical struct/union ("canonical graph" for brevity
3777  * here, though keep in mind that not all types in canonical graph are
3778  * necessarily canonical representatives themselves, some of them might be
3779  * duplicates or its uniqueness might not have been established yet).
3780  * Returns:
3781  *  - >0, if type graphs are equivalent;
3782  *  -  0, if not equivalent;
3783  *  - <0, on error.
3784  *
3785  * Algorithm performs side-by-side DFS traversal of both type graphs and checks
3786  * equivalence of BTF types at each step. If at any point BTF types in candidate
3787  * and canonical graphs are not compatible structurally, whole graphs are
3788  * incompatible. If types are structurally equivalent (i.e., all information
3789  * except referenced type IDs is exactly the same), a mapping from `canon_id` to
3790  * a `cand_id` is recored in hypothetical mapping (`btf_dedup->hypot_map`).
3791  * If a type references other types, then those referenced types are checked
3792  * for equivalence recursively.
3793  *
3794  * During DFS traversal, if we find that for current `canon_id` type we
3795  * already have some mapping in hypothetical map, we check for two possible
3796  * situations:
3797  *   - `canon_id` is mapped to exactly the same type as `cand_id`. This will
3798  *     happen when type graphs have cycles. In this case we assume those two
3799  *     types are equivalent.
3800  *   - `canon_id` is mapped to different type. This is contradiction in our
3801  *     hypothetical mapping, because same graph in canonical graph corresponds
3802  *     to two different types in candidate graph, which for equivalent type
3803  *     graphs shouldn't happen. This condition terminates equivalence check
3804  *     with negative result.
3805  *
3806  * If type graphs traversal exhausts types to check and find no contradiction,
3807  * then type graphs are equivalent.
3808  *
3809  * When checking types for equivalence, there is one special case: FWD types.
3810  * If FWD type resolution is allowed and one of the types (either from canonical
3811  * or candidate graph) is FWD and other is STRUCT/UNION (depending on FWD's kind
3812  * flag) and their names match, hypothetical mapping is updated to point from
3813  * FWD to STRUCT/UNION. If graphs will be determined as equivalent successfully,
3814  * this mapping will be used to record FWD -> STRUCT/UNION mapping permanently.
3815  *
3816  * Technically, this could lead to incorrect FWD to STRUCT/UNION resolution,
3817  * if there are two exactly named (or anonymous) structs/unions that are
3818  * compatible structurally, one of which has FWD field, while other is concrete
3819  * STRUCT/UNION, but according to C sources they are different structs/unions
3820  * that are referencing different types with the same name. This is extremely
3821  * unlikely to happen, but btf_dedup API allows to disable FWD resolution if
3822  * this logic is causing problems.
3823  *
3824  * Doing FWD resolution means that both candidate and/or canonical graphs can
3825  * consists of portions of the graph that come from multiple compilation units.
3826  * This is due to the fact that types within single compilation unit are always
3827  * deduplicated and FWDs are already resolved, if referenced struct/union
3828  * definiton is available. So, if we had unresolved FWD and found corresponding
3829  * STRUCT/UNION, they will be from different compilation units. This
3830  * consequently means that when we "link" FWD to corresponding STRUCT/UNION,
3831  * type graph will likely have at least two different BTF types that describe
3832  * same type (e.g., most probably there will be two different BTF types for the
3833  * same 'int' primitive type) and could even have "overlapping" parts of type
3834  * graph that describe same subset of types.
3835  *
3836  * This in turn means that our assumption that each type in canonical graph
3837  * must correspond to exactly one type in candidate graph might not hold
3838  * anymore and will make it harder to detect contradictions using hypothetical
3839  * map. To handle this problem, we allow to follow FWD -> STRUCT/UNION
3840  * resolution only in canonical graph. FWDs in candidate graphs are never
3841  * resolved. To see why it's OK, let's check all possible situations w.r.t. FWDs
3842  * that can occur:
3843  *   - Both types in canonical and candidate graphs are FWDs. If they are
3844  *     structurally equivalent, then they can either be both resolved to the
3845  *     same STRUCT/UNION or not resolved at all. In both cases they are
3846  *     equivalent and there is no need to resolve FWD on candidate side.
3847  *   - Both types in canonical and candidate graphs are concrete STRUCT/UNION,
3848  *     so nothing to resolve as well, algorithm will check equivalence anyway.
3849  *   - Type in canonical graph is FWD, while type in candidate is concrete
3850  *     STRUCT/UNION. In this case candidate graph comes from single compilation
3851  *     unit, so there is exactly one BTF type for each unique C type. After
3852  *     resolving FWD into STRUCT/UNION, there might be more than one BTF type
3853  *     in canonical graph mapping to single BTF type in candidate graph, but
3854  *     because hypothetical mapping maps from canonical to candidate types, it's
3855  *     alright, and we still maintain the property of having single `canon_id`
3856  *     mapping to single `cand_id` (there could be two different `canon_id`
3857  *     mapped to the same `cand_id`, but it's not contradictory).
3858  *   - Type in canonical graph is concrete STRUCT/UNION, while type in candidate
3859  *     graph is FWD. In this case we are just going to check compatibility of
3860  *     STRUCT/UNION and corresponding FWD, and if they are compatible, we'll
3861  *     assume that whatever STRUCT/UNION FWD resolves to must be equivalent to
3862  *     a concrete STRUCT/UNION from canonical graph. If the rest of type graphs
3863  *     turn out equivalent, we'll re-resolve FWD to concrete STRUCT/UNION from
3864  *     canonical graph.
3865  */
btf_dedup_is_equiv(struct btf_dedup * d,__u32 cand_id,__u32 canon_id)3866 static int btf_dedup_is_equiv(struct btf_dedup *d, __u32 cand_id,
3867 			      __u32 canon_id)
3868 {
3869 	struct btf_type *cand_type;
3870 	struct btf_type *canon_type;
3871 	__u32 hypot_type_id;
3872 	__u16 cand_kind;
3873 	__u16 canon_kind;
3874 	int i, eq;
3875 
3876 	/* if both resolve to the same canonical, they must be equivalent */
3877 	if (resolve_type_id(d, cand_id) == resolve_type_id(d, canon_id))
3878 		return 1;
3879 
3880 	canon_id = resolve_fwd_id(d, canon_id);
3881 
3882 	hypot_type_id = d->hypot_map[canon_id];
3883 	if (hypot_type_id <= BTF_MAX_NR_TYPES) {
3884 		if (hypot_type_id == cand_id)
3885 			return 1;
3886 		/* In some cases compiler will generate different DWARF types
3887 		 * for *identical* array type definitions and use them for
3888 		 * different fields within the *same* struct. This breaks type
3889 		 * equivalence check, which makes an assumption that candidate
3890 		 * types sub-graph has a consistent and deduped-by-compiler
3891 		 * types within a single CU. So work around that by explicitly
3892 		 * allowing identical array types here.
3893 		 */
3894 		if (btf_dedup_identical_arrays(d, hypot_type_id, cand_id))
3895 			return 1;
3896 		/* It turns out that similar situation can happen with
3897 		 * struct/union sometimes, sigh... Handle the case where
3898 		 * structs/unions are exactly the same, down to the referenced
3899 		 * type IDs. Anything more complicated (e.g., if referenced
3900 		 * types are different, but equivalent) is *way more*
3901 		 * complicated and requires a many-to-many equivalence mapping.
3902 		 */
3903 		if (btf_dedup_identical_structs(d, hypot_type_id, cand_id))
3904 			return 1;
3905 		return 0;
3906 	}
3907 
3908 	if (btf_dedup_hypot_map_add(d, canon_id, cand_id))
3909 		return -ENOMEM;
3910 
3911 	cand_type = btf_type_by_id(d->btf, cand_id);
3912 	canon_type = btf_type_by_id(d->btf, canon_id);
3913 	cand_kind = btf_kind(cand_type);
3914 	canon_kind = btf_kind(canon_type);
3915 
3916 	if (cand_type->name_off != canon_type->name_off)
3917 		return 0;
3918 
3919 	/* FWD <--> STRUCT/UNION equivalence check, if enabled */
3920 	if (!d->opts.dont_resolve_fwds
3921 	    && (cand_kind == BTF_KIND_FWD || canon_kind == BTF_KIND_FWD)
3922 	    && cand_kind != canon_kind) {
3923 		__u16 real_kind;
3924 		__u16 fwd_kind;
3925 
3926 		if (cand_kind == BTF_KIND_FWD) {
3927 			real_kind = canon_kind;
3928 			fwd_kind = btf_fwd_kind(cand_type);
3929 		} else {
3930 			real_kind = cand_kind;
3931 			fwd_kind = btf_fwd_kind(canon_type);
3932 			/* we'd need to resolve base FWD to STRUCT/UNION */
3933 			if (fwd_kind == real_kind && canon_id < d->btf->start_id)
3934 				d->hypot_adjust_canon = true;
3935 		}
3936 		return fwd_kind == real_kind;
3937 	}
3938 
3939 	if (cand_kind != canon_kind)
3940 		return 0;
3941 
3942 	switch (cand_kind) {
3943 	case BTF_KIND_INT:
3944 		return btf_equal_int(cand_type, canon_type);
3945 
3946 	case BTF_KIND_ENUM:
3947 		if (d->opts.dont_resolve_fwds)
3948 			return btf_equal_enum(cand_type, canon_type);
3949 		else
3950 			return btf_compat_enum(cand_type, canon_type);
3951 
3952 	case BTF_KIND_FWD:
3953 	case BTF_KIND_FLOAT:
3954 		return btf_equal_common(cand_type, canon_type);
3955 
3956 	case BTF_KIND_CONST:
3957 	case BTF_KIND_VOLATILE:
3958 	case BTF_KIND_RESTRICT:
3959 	case BTF_KIND_PTR:
3960 	case BTF_KIND_TYPEDEF:
3961 	case BTF_KIND_FUNC:
3962 		if (cand_type->info != canon_type->info)
3963 			return 0;
3964 		return btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
3965 
3966 	case BTF_KIND_ARRAY: {
3967 		const struct btf_array *cand_arr, *canon_arr;
3968 
3969 		if (!btf_compat_array(cand_type, canon_type))
3970 			return 0;
3971 		cand_arr = btf_array(cand_type);
3972 		canon_arr = btf_array(canon_type);
3973 		eq = btf_dedup_is_equiv(d, cand_arr->index_type, canon_arr->index_type);
3974 		if (eq <= 0)
3975 			return eq;
3976 		return btf_dedup_is_equiv(d, cand_arr->type, canon_arr->type);
3977 	}
3978 
3979 	case BTF_KIND_STRUCT:
3980 	case BTF_KIND_UNION: {
3981 		const struct btf_member *cand_m, *canon_m;
3982 		__u16 vlen;
3983 
3984 		if (!btf_shallow_equal_struct(cand_type, canon_type))
3985 			return 0;
3986 		vlen = btf_vlen(cand_type);
3987 		cand_m = btf_members(cand_type);
3988 		canon_m = btf_members(canon_type);
3989 		for (i = 0; i < vlen; i++) {
3990 			eq = btf_dedup_is_equiv(d, cand_m->type, canon_m->type);
3991 			if (eq <= 0)
3992 				return eq;
3993 			cand_m++;
3994 			canon_m++;
3995 		}
3996 
3997 		return 1;
3998 	}
3999 
4000 	case BTF_KIND_FUNC_PROTO: {
4001 		const struct btf_param *cand_p, *canon_p;
4002 		__u16 vlen;
4003 
4004 		if (!btf_compat_fnproto(cand_type, canon_type))
4005 			return 0;
4006 		eq = btf_dedup_is_equiv(d, cand_type->type, canon_type->type);
4007 		if (eq <= 0)
4008 			return eq;
4009 		vlen = btf_vlen(cand_type);
4010 		cand_p = btf_params(cand_type);
4011 		canon_p = btf_params(canon_type);
4012 		for (i = 0; i < vlen; i++) {
4013 			eq = btf_dedup_is_equiv(d, cand_p->type, canon_p->type);
4014 			if (eq <= 0)
4015 				return eq;
4016 			cand_p++;
4017 			canon_p++;
4018 		}
4019 		return 1;
4020 	}
4021 
4022 	default:
4023 		return -EINVAL;
4024 	}
4025 	return 0;
4026 }
4027 
4028 /*
4029  * Use hypothetical mapping, produced by successful type graph equivalence
4030  * check, to augment existing struct/union canonical mapping, where possible.
4031  *
4032  * If BTF_KIND_FWD resolution is allowed, this mapping is also used to record
4033  * FWD -> STRUCT/UNION correspondence as well. FWD resolution is bidirectional:
4034  * it doesn't matter if FWD type was part of canonical graph or candidate one,
4035  * we are recording the mapping anyway. As opposed to carefulness required
4036  * for struct/union correspondence mapping (described below), for FWD resolution
4037  * it's not important, as by the time that FWD type (reference type) will be
4038  * deduplicated all structs/unions will be deduped already anyway.
4039  *
4040  * Recording STRUCT/UNION mapping is purely a performance optimization and is
4041  * not required for correctness. It needs to be done carefully to ensure that
4042  * struct/union from candidate's type graph is not mapped into corresponding
4043  * struct/union from canonical type graph that itself hasn't been resolved into
4044  * canonical representative. The only guarantee we have is that canonical
4045  * struct/union was determined as canonical and that won't change. But any
4046  * types referenced through that struct/union fields could have been not yet
4047  * resolved, so in case like that it's too early to establish any kind of
4048  * correspondence between structs/unions.
4049  *
4050  * No canonical correspondence is derived for primitive types (they are already
4051  * deduplicated completely already anyway) or reference types (they rely on
4052  * stability of struct/union canonical relationship for equivalence checks).
4053  */
btf_dedup_merge_hypot_map(struct btf_dedup * d)4054 static void btf_dedup_merge_hypot_map(struct btf_dedup *d)
4055 {
4056 	__u32 canon_type_id, targ_type_id;
4057 	__u16 t_kind, c_kind;
4058 	__u32 t_id, c_id;
4059 	int i;
4060 
4061 	for (i = 0; i < d->hypot_cnt; i++) {
4062 		canon_type_id = d->hypot_list[i];
4063 		targ_type_id = d->hypot_map[canon_type_id];
4064 		t_id = resolve_type_id(d, targ_type_id);
4065 		c_id = resolve_type_id(d, canon_type_id);
4066 		t_kind = btf_kind(btf__type_by_id(d->btf, t_id));
4067 		c_kind = btf_kind(btf__type_by_id(d->btf, c_id));
4068 		/*
4069 		 * Resolve FWD into STRUCT/UNION.
4070 		 * It's ok to resolve FWD into STRUCT/UNION that's not yet
4071 		 * mapped to canonical representative (as opposed to
4072 		 * STRUCT/UNION <--> STRUCT/UNION mapping logic below), because
4073 		 * eventually that struct is going to be mapped and all resolved
4074 		 * FWDs will automatically resolve to correct canonical
4075 		 * representative. This will happen before ref type deduping,
4076 		 * which critically depends on stability of these mapping. This
4077 		 * stability is not a requirement for STRUCT/UNION equivalence
4078 		 * checks, though.
4079 		 */
4080 
4081 		/* if it's the split BTF case, we still need to point base FWD
4082 		 * to STRUCT/UNION in a split BTF, because FWDs from split BTF
4083 		 * will be resolved against base FWD. If we don't point base
4084 		 * canonical FWD to the resolved STRUCT/UNION, then all the
4085 		 * FWDs in split BTF won't be correctly resolved to a proper
4086 		 * STRUCT/UNION.
4087 		 */
4088 		if (t_kind != BTF_KIND_FWD && c_kind == BTF_KIND_FWD)
4089 			d->map[c_id] = t_id;
4090 
4091 		/* if graph equivalence determined that we'd need to adjust
4092 		 * base canonical types, then we need to only point base FWDs
4093 		 * to STRUCTs/UNIONs and do no more modifications. For all
4094 		 * other purposes the type graphs were not equivalent.
4095 		 */
4096 		if (d->hypot_adjust_canon)
4097 			continue;
4098 
4099 		if (t_kind == BTF_KIND_FWD && c_kind != BTF_KIND_FWD)
4100 			d->map[t_id] = c_id;
4101 
4102 		if ((t_kind == BTF_KIND_STRUCT || t_kind == BTF_KIND_UNION) &&
4103 		    c_kind != BTF_KIND_FWD &&
4104 		    is_type_mapped(d, c_id) &&
4105 		    !is_type_mapped(d, t_id)) {
4106 			/*
4107 			 * as a perf optimization, we can map struct/union
4108 			 * that's part of type graph we just verified for
4109 			 * equivalence. We can do that for struct/union that has
4110 			 * canonical representative only, though.
4111 			 */
4112 			d->map[t_id] = c_id;
4113 		}
4114 	}
4115 }
4116 
4117 /*
4118  * Deduplicate struct/union types.
4119  *
4120  * For each struct/union type its type signature hash is calculated, taking
4121  * into account type's name, size, number, order and names of fields, but
4122  * ignoring type ID's referenced from fields, because they might not be deduped
4123  * completely until after reference types deduplication phase. This type hash
4124  * is used to iterate over all potential canonical types, sharing same hash.
4125  * For each canonical candidate we check whether type graphs that they form
4126  * (through referenced types in fields and so on) are equivalent using algorithm
4127  * implemented in `btf_dedup_is_equiv`. If such equivalence is found and
4128  * BTF_KIND_FWD resolution is allowed, then hypothetical mapping
4129  * (btf_dedup->hypot_map) produced by aforementioned type graph equivalence
4130  * algorithm is used to record FWD -> STRUCT/UNION mapping. It's also used to
4131  * potentially map other structs/unions to their canonical representatives,
4132  * if such relationship hasn't yet been established. This speeds up algorithm
4133  * by eliminating some of the duplicate work.
4134  *
4135  * If no matching canonical representative was found, struct/union is marked
4136  * as canonical for itself and is added into btf_dedup->dedup_table hash map
4137  * for further look ups.
4138  */
btf_dedup_struct_type(struct btf_dedup * d,__u32 type_id)4139 static int btf_dedup_struct_type(struct btf_dedup *d, __u32 type_id)
4140 {
4141 	struct btf_type *cand_type, *t;
4142 	struct hashmap_entry *hash_entry;
4143 	/* if we don't find equivalent type, then we are canonical */
4144 	__u32 new_id = type_id;
4145 	__u16 kind;
4146 	long h;
4147 
4148 	/* already deduped or is in process of deduping (loop detected) */
4149 	if (d->map[type_id] <= BTF_MAX_NR_TYPES)
4150 		return 0;
4151 
4152 	t = btf_type_by_id(d->btf, type_id);
4153 	kind = btf_kind(t);
4154 
4155 	if (kind != BTF_KIND_STRUCT && kind != BTF_KIND_UNION)
4156 		return 0;
4157 
4158 	h = btf_hash_struct(t);
4159 	for_each_dedup_cand(d, hash_entry, h) {
4160 		__u32 cand_id = (__u32)(long)hash_entry->value;
4161 		int eq;
4162 
4163 		/*
4164 		 * Even though btf_dedup_is_equiv() checks for
4165 		 * btf_shallow_equal_struct() internally when checking two
4166 		 * structs (unions) for equivalence, we need to guard here
4167 		 * from picking matching FWD type as a dedup candidate.
4168 		 * This can happen due to hash collision. In such case just
4169 		 * relying on btf_dedup_is_equiv() would lead to potentially
4170 		 * creating a loop (FWD -> STRUCT and STRUCT -> FWD), because
4171 		 * FWD and compatible STRUCT/UNION are considered equivalent.
4172 		 */
4173 		cand_type = btf_type_by_id(d->btf, cand_id);
4174 		if (!btf_shallow_equal_struct(t, cand_type))
4175 			continue;
4176 
4177 		btf_dedup_clear_hypot_map(d);
4178 		eq = btf_dedup_is_equiv(d, type_id, cand_id);
4179 		if (eq < 0)
4180 			return eq;
4181 		if (!eq)
4182 			continue;
4183 		btf_dedup_merge_hypot_map(d);
4184 		if (d->hypot_adjust_canon) /* not really equivalent */
4185 			continue;
4186 		new_id = cand_id;
4187 		break;
4188 	}
4189 
4190 	d->map[type_id] = new_id;
4191 	if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
4192 		return -ENOMEM;
4193 
4194 	return 0;
4195 }
4196 
btf_dedup_struct_types(struct btf_dedup * d)4197 static int btf_dedup_struct_types(struct btf_dedup *d)
4198 {
4199 	int i, err;
4200 
4201 	for (i = 0; i < d->btf->nr_types; i++) {
4202 		err = btf_dedup_struct_type(d, d->btf->start_id + i);
4203 		if (err)
4204 			return err;
4205 	}
4206 	return 0;
4207 }
4208 
4209 /*
4210  * Deduplicate reference type.
4211  *
4212  * Once all primitive and struct/union types got deduplicated, we can easily
4213  * deduplicate all other (reference) BTF types. This is done in two steps:
4214  *
4215  * 1. Resolve all referenced type IDs into their canonical type IDs. This
4216  * resolution can be done either immediately for primitive or struct/union types
4217  * (because they were deduped in previous two phases) or recursively for
4218  * reference types. Recursion will always terminate at either primitive or
4219  * struct/union type, at which point we can "unwind" chain of reference types
4220  * one by one. There is no danger of encountering cycles because in C type
4221  * system the only way to form type cycle is through struct/union, so any chain
4222  * of reference types, even those taking part in a type cycle, will inevitably
4223  * reach struct/union at some point.
4224  *
4225  * 2. Once all referenced type IDs are resolved into canonical ones, BTF type
4226  * becomes "stable", in the sense that no further deduplication will cause
4227  * any changes to it. With that, it's now possible to calculate type's signature
4228  * hash (this time taking into account referenced type IDs) and loop over all
4229  * potential canonical representatives. If no match was found, current type
4230  * will become canonical representative of itself and will be added into
4231  * btf_dedup->dedup_table as another possible canonical representative.
4232  */
btf_dedup_ref_type(struct btf_dedup * d,__u32 type_id)4233 static int btf_dedup_ref_type(struct btf_dedup *d, __u32 type_id)
4234 {
4235 	struct hashmap_entry *hash_entry;
4236 	__u32 new_id = type_id, cand_id;
4237 	struct btf_type *t, *cand;
4238 	/* if we don't find equivalent type, then we are representative type */
4239 	int ref_type_id;
4240 	long h;
4241 
4242 	if (d->map[type_id] == BTF_IN_PROGRESS_ID)
4243 		return -ELOOP;
4244 	if (d->map[type_id] <= BTF_MAX_NR_TYPES)
4245 		return resolve_type_id(d, type_id);
4246 
4247 	t = btf_type_by_id(d->btf, type_id);
4248 	d->map[type_id] = BTF_IN_PROGRESS_ID;
4249 
4250 	switch (btf_kind(t)) {
4251 	case BTF_KIND_CONST:
4252 	case BTF_KIND_VOLATILE:
4253 	case BTF_KIND_RESTRICT:
4254 	case BTF_KIND_PTR:
4255 	case BTF_KIND_TYPEDEF:
4256 	case BTF_KIND_FUNC:
4257 		ref_type_id = btf_dedup_ref_type(d, t->type);
4258 		if (ref_type_id < 0)
4259 			return ref_type_id;
4260 		t->type = ref_type_id;
4261 
4262 		h = btf_hash_common(t);
4263 		for_each_dedup_cand(d, hash_entry, h) {
4264 			cand_id = (__u32)(long)hash_entry->value;
4265 			cand = btf_type_by_id(d->btf, cand_id);
4266 			if (btf_equal_common(t, cand)) {
4267 				new_id = cand_id;
4268 				break;
4269 			}
4270 		}
4271 		break;
4272 
4273 	case BTF_KIND_ARRAY: {
4274 		struct btf_array *info = btf_array(t);
4275 
4276 		ref_type_id = btf_dedup_ref_type(d, info->type);
4277 		if (ref_type_id < 0)
4278 			return ref_type_id;
4279 		info->type = ref_type_id;
4280 
4281 		ref_type_id = btf_dedup_ref_type(d, info->index_type);
4282 		if (ref_type_id < 0)
4283 			return ref_type_id;
4284 		info->index_type = ref_type_id;
4285 
4286 		h = btf_hash_array(t);
4287 		for_each_dedup_cand(d, hash_entry, h) {
4288 			cand_id = (__u32)(long)hash_entry->value;
4289 			cand = btf_type_by_id(d->btf, cand_id);
4290 			if (btf_equal_array(t, cand)) {
4291 				new_id = cand_id;
4292 				break;
4293 			}
4294 		}
4295 		break;
4296 	}
4297 
4298 	case BTF_KIND_FUNC_PROTO: {
4299 		struct btf_param *param;
4300 		__u16 vlen;
4301 		int i;
4302 
4303 		ref_type_id = btf_dedup_ref_type(d, t->type);
4304 		if (ref_type_id < 0)
4305 			return ref_type_id;
4306 		t->type = ref_type_id;
4307 
4308 		vlen = btf_vlen(t);
4309 		param = btf_params(t);
4310 		for (i = 0; i < vlen; i++) {
4311 			ref_type_id = btf_dedup_ref_type(d, param->type);
4312 			if (ref_type_id < 0)
4313 				return ref_type_id;
4314 			param->type = ref_type_id;
4315 			param++;
4316 		}
4317 
4318 		h = btf_hash_fnproto(t);
4319 		for_each_dedup_cand(d, hash_entry, h) {
4320 			cand_id = (__u32)(long)hash_entry->value;
4321 			cand = btf_type_by_id(d->btf, cand_id);
4322 			if (btf_equal_fnproto(t, cand)) {
4323 				new_id = cand_id;
4324 				break;
4325 			}
4326 		}
4327 		break;
4328 	}
4329 
4330 	default:
4331 		return -EINVAL;
4332 	}
4333 
4334 	d->map[type_id] = new_id;
4335 	if (type_id == new_id && btf_dedup_table_add(d, h, type_id))
4336 		return -ENOMEM;
4337 
4338 	return new_id;
4339 }
4340 
btf_dedup_ref_types(struct btf_dedup * d)4341 static int btf_dedup_ref_types(struct btf_dedup *d)
4342 {
4343 	int i, err;
4344 
4345 	for (i = 0; i < d->btf->nr_types; i++) {
4346 		err = btf_dedup_ref_type(d, d->btf->start_id + i);
4347 		if (err < 0)
4348 			return err;
4349 	}
4350 	/* we won't need d->dedup_table anymore */
4351 	hashmap__free(d->dedup_table);
4352 	d->dedup_table = NULL;
4353 	return 0;
4354 }
4355 
4356 /*
4357  * Compact types.
4358  *
4359  * After we established for each type its corresponding canonical representative
4360  * type, we now can eliminate types that are not canonical and leave only
4361  * canonical ones layed out sequentially in memory by copying them over
4362  * duplicates. During compaction btf_dedup->hypot_map array is reused to store
4363  * a map from original type ID to a new compacted type ID, which will be used
4364  * during next phase to "fix up" type IDs, referenced from struct/union and
4365  * reference types.
4366  */
btf_dedup_compact_types(struct btf_dedup * d)4367 static int btf_dedup_compact_types(struct btf_dedup *d)
4368 {
4369 	__u32 *new_offs;
4370 	__u32 next_type_id = d->btf->start_id;
4371 	const struct btf_type *t;
4372 	void *p;
4373 	int i, id, len;
4374 
4375 	/* we are going to reuse hypot_map to store compaction remapping */
4376 	d->hypot_map[0] = 0;
4377 	/* base BTF types are not renumbered */
4378 	for (id = 1; id < d->btf->start_id; id++)
4379 		d->hypot_map[id] = id;
4380 	for (i = 0, id = d->btf->start_id; i < d->btf->nr_types; i++, id++)
4381 		d->hypot_map[id] = BTF_UNPROCESSED_ID;
4382 
4383 	p = d->btf->types_data;
4384 
4385 	for (i = 0, id = d->btf->start_id; i < d->btf->nr_types; i++, id++) {
4386 		if (d->map[id] != id)
4387 			continue;
4388 
4389 		t = btf__type_by_id(d->btf, id);
4390 		len = btf_type_size(t);
4391 		if (len < 0)
4392 			return len;
4393 
4394 		memmove(p, t, len);
4395 		d->hypot_map[id] = next_type_id;
4396 		d->btf->type_offs[next_type_id - d->btf->start_id] = p - d->btf->types_data;
4397 		p += len;
4398 		next_type_id++;
4399 	}
4400 
4401 	/* shrink struct btf's internal types index and update btf_header */
4402 	d->btf->nr_types = next_type_id - d->btf->start_id;
4403 	d->btf->type_offs_cap = d->btf->nr_types;
4404 	d->btf->hdr->type_len = p - d->btf->types_data;
4405 	new_offs = libbpf_reallocarray(d->btf->type_offs, d->btf->type_offs_cap,
4406 				       sizeof(*new_offs));
4407 	if (d->btf->type_offs_cap && !new_offs)
4408 		return -ENOMEM;
4409 	d->btf->type_offs = new_offs;
4410 	d->btf->hdr->str_off = d->btf->hdr->type_len;
4411 	d->btf->raw_size = d->btf->hdr->hdr_len + d->btf->hdr->type_len + d->btf->hdr->str_len;
4412 	return 0;
4413 }
4414 
4415 /*
4416  * Figure out final (deduplicated and compacted) type ID for provided original
4417  * `type_id` by first resolving it into corresponding canonical type ID and
4418  * then mapping it to a deduplicated type ID, stored in btf_dedup->hypot_map,
4419  * which is populated during compaction phase.
4420  */
btf_dedup_remap_type_id(__u32 * type_id,void * ctx)4421 static int btf_dedup_remap_type_id(__u32 *type_id, void *ctx)
4422 {
4423 	struct btf_dedup *d = ctx;
4424 	__u32 resolved_type_id, new_type_id;
4425 
4426 	resolved_type_id = resolve_type_id(d, *type_id);
4427 	new_type_id = d->hypot_map[resolved_type_id];
4428 	if (new_type_id > BTF_MAX_NR_TYPES)
4429 		return -EINVAL;
4430 
4431 	*type_id = new_type_id;
4432 	return 0;
4433 }
4434 
4435 /*
4436  * Remap referenced type IDs into deduped type IDs.
4437  *
4438  * After BTF types are deduplicated and compacted, their final type IDs may
4439  * differ from original ones. The map from original to a corresponding
4440  * deduped type ID is stored in btf_dedup->hypot_map and is populated during
4441  * compaction phase. During remapping phase we are rewriting all type IDs
4442  * referenced from any BTF type (e.g., struct fields, func proto args, etc) to
4443  * their final deduped type IDs.
4444  */
btf_dedup_remap_types(struct btf_dedup * d)4445 static int btf_dedup_remap_types(struct btf_dedup *d)
4446 {
4447 	int i, r;
4448 
4449 	for (i = 0; i < d->btf->nr_types; i++) {
4450 		struct btf_type *t = btf_type_by_id(d->btf, d->btf->start_id + i);
4451 
4452 		r = btf_type_visit_type_ids(t, btf_dedup_remap_type_id, d);
4453 		if (r)
4454 			return r;
4455 	}
4456 
4457 	if (!d->btf_ext)
4458 		return 0;
4459 
4460 	r = btf_ext_visit_type_ids(d->btf_ext, btf_dedup_remap_type_id, d);
4461 	if (r)
4462 		return r;
4463 
4464 	return 0;
4465 }
4466 
4467 /*
4468  * Probe few well-known locations for vmlinux kernel image and try to load BTF
4469  * data out of it to use for target BTF.
4470  */
btf__load_vmlinux_btf(void)4471 struct btf *btf__load_vmlinux_btf(void)
4472 {
4473 	struct {
4474 		const char *path_fmt;
4475 		bool raw_btf;
4476 	} locations[] = {
4477 		/* try canonical vmlinux BTF through sysfs first */
4478 		{ "/sys/kernel/btf/vmlinux", true /* raw BTF */ },
4479 		/* fall back to trying to find vmlinux ELF on disk otherwise */
4480 		{ "/boot/vmlinux-%1$s" },
4481 		{ "/lib/modules/%1$s/vmlinux-%1$s" },
4482 		{ "/lib/modules/%1$s/build/vmlinux" },
4483 		{ "/usr/lib/modules/%1$s/kernel/vmlinux" },
4484 		{ "/usr/lib/debug/boot/vmlinux-%1$s" },
4485 		{ "/usr/lib/debug/boot/vmlinux-%1$s.debug" },
4486 		{ "/usr/lib/debug/lib/modules/%1$s/vmlinux" },
4487 	};
4488 	char path[PATH_MAX + 1];
4489 	struct utsname buf;
4490 	struct btf *btf;
4491 	int i, err;
4492 
4493 	uname(&buf);
4494 
4495 	for (i = 0; i < ARRAY_SIZE(locations); i++) {
4496 		snprintf(path, PATH_MAX, locations[i].path_fmt, buf.release);
4497 
4498 		if (access(path, R_OK))
4499 			continue;
4500 
4501 		if (locations[i].raw_btf)
4502 			btf = btf__parse_raw(path);
4503 		else
4504 			btf = btf__parse_elf(path, NULL);
4505 		err = libbpf_get_error(btf);
4506 		pr_debug("loading kernel BTF '%s': %d\n", path, err);
4507 		if (err)
4508 			continue;
4509 
4510 		return btf;
4511 	}
4512 
4513 	pr_warn("failed to find valid kernel BTF\n");
4514 	return libbpf_err_ptr(-ESRCH);
4515 }
4516 
4517 struct btf *libbpf_find_kernel_btf(void) __attribute__((alias("btf__load_vmlinux_btf")));
4518 
btf__load_module_btf(const char * module_name,struct btf * vmlinux_btf)4519 struct btf *btf__load_module_btf(const char *module_name, struct btf *vmlinux_btf)
4520 {
4521 	char path[80];
4522 
4523 	snprintf(path, sizeof(path), "/sys/kernel/btf/%s", module_name);
4524 	return btf__parse_split(path, vmlinux_btf);
4525 }
4526 
btf_type_visit_type_ids(struct btf_type * t,type_id_visit_fn visit,void * ctx)4527 int btf_type_visit_type_ids(struct btf_type *t, type_id_visit_fn visit, void *ctx)
4528 {
4529 	int i, n, err;
4530 
4531 	switch (btf_kind(t)) {
4532 	case BTF_KIND_INT:
4533 	case BTF_KIND_FLOAT:
4534 	case BTF_KIND_ENUM:
4535 		return 0;
4536 
4537 	case BTF_KIND_FWD:
4538 	case BTF_KIND_CONST:
4539 	case BTF_KIND_VOLATILE:
4540 	case BTF_KIND_RESTRICT:
4541 	case BTF_KIND_PTR:
4542 	case BTF_KIND_TYPEDEF:
4543 	case BTF_KIND_FUNC:
4544 	case BTF_KIND_VAR:
4545 		return visit(&t->type, ctx);
4546 
4547 	case BTF_KIND_ARRAY: {
4548 		struct btf_array *a = btf_array(t);
4549 
4550 		err = visit(&a->type, ctx);
4551 		err = err ?: visit(&a->index_type, ctx);
4552 		return err;
4553 	}
4554 
4555 	case BTF_KIND_STRUCT:
4556 	case BTF_KIND_UNION: {
4557 		struct btf_member *m = btf_members(t);
4558 
4559 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4560 			err = visit(&m->type, ctx);
4561 			if (err)
4562 				return err;
4563 		}
4564 		return 0;
4565 	}
4566 
4567 	case BTF_KIND_FUNC_PROTO: {
4568 		struct btf_param *m = btf_params(t);
4569 
4570 		err = visit(&t->type, ctx);
4571 		if (err)
4572 			return err;
4573 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4574 			err = visit(&m->type, ctx);
4575 			if (err)
4576 				return err;
4577 		}
4578 		return 0;
4579 	}
4580 
4581 	case BTF_KIND_DATASEC: {
4582 		struct btf_var_secinfo *m = btf_var_secinfos(t);
4583 
4584 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4585 			err = visit(&m->type, ctx);
4586 			if (err)
4587 				return err;
4588 		}
4589 		return 0;
4590 	}
4591 
4592 	default:
4593 		return -EINVAL;
4594 	}
4595 }
4596 
btf_type_visit_str_offs(struct btf_type * t,str_off_visit_fn visit,void * ctx)4597 int btf_type_visit_str_offs(struct btf_type *t, str_off_visit_fn visit, void *ctx)
4598 {
4599 	int i, n, err;
4600 
4601 	err = visit(&t->name_off, ctx);
4602 	if (err)
4603 		return err;
4604 
4605 	switch (btf_kind(t)) {
4606 	case BTF_KIND_STRUCT:
4607 	case BTF_KIND_UNION: {
4608 		struct btf_member *m = btf_members(t);
4609 
4610 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4611 			err = visit(&m->name_off, ctx);
4612 			if (err)
4613 				return err;
4614 		}
4615 		break;
4616 	}
4617 	case BTF_KIND_ENUM: {
4618 		struct btf_enum *m = btf_enum(t);
4619 
4620 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4621 			err = visit(&m->name_off, ctx);
4622 			if (err)
4623 				return err;
4624 		}
4625 		break;
4626 	}
4627 	case BTF_KIND_FUNC_PROTO: {
4628 		struct btf_param *m = btf_params(t);
4629 
4630 		for (i = 0, n = btf_vlen(t); i < n; i++, m++) {
4631 			err = visit(&m->name_off, ctx);
4632 			if (err)
4633 				return err;
4634 		}
4635 		break;
4636 	}
4637 	default:
4638 		break;
4639 	}
4640 
4641 	return 0;
4642 }
4643 
btf_ext_visit_type_ids(struct btf_ext * btf_ext,type_id_visit_fn visit,void * ctx)4644 int btf_ext_visit_type_ids(struct btf_ext *btf_ext, type_id_visit_fn visit, void *ctx)
4645 {
4646 	const struct btf_ext_info *seg;
4647 	struct btf_ext_info_sec *sec;
4648 	int i, err;
4649 
4650 	seg = &btf_ext->func_info;
4651 	for_each_btf_ext_sec(seg, sec) {
4652 		struct bpf_func_info_min *rec;
4653 
4654 		for_each_btf_ext_rec(seg, sec, i, rec) {
4655 			err = visit(&rec->type_id, ctx);
4656 			if (err < 0)
4657 				return err;
4658 		}
4659 	}
4660 
4661 	seg = &btf_ext->core_relo_info;
4662 	for_each_btf_ext_sec(seg, sec) {
4663 		struct bpf_core_relo *rec;
4664 
4665 		for_each_btf_ext_rec(seg, sec, i, rec) {
4666 			err = visit(&rec->type_id, ctx);
4667 			if (err < 0)
4668 				return err;
4669 		}
4670 	}
4671 
4672 	return 0;
4673 }
4674 
btf_ext_visit_str_offs(struct btf_ext * btf_ext,str_off_visit_fn visit,void * ctx)4675 int btf_ext_visit_str_offs(struct btf_ext *btf_ext, str_off_visit_fn visit, void *ctx)
4676 {
4677 	const struct btf_ext_info *seg;
4678 	struct btf_ext_info_sec *sec;
4679 	int i, err;
4680 
4681 	seg = &btf_ext->func_info;
4682 	for_each_btf_ext_sec(seg, sec) {
4683 		err = visit(&sec->sec_name_off, ctx);
4684 		if (err)
4685 			return err;
4686 	}
4687 
4688 	seg = &btf_ext->line_info;
4689 	for_each_btf_ext_sec(seg, sec) {
4690 		struct bpf_line_info_min *rec;
4691 
4692 		err = visit(&sec->sec_name_off, ctx);
4693 		if (err)
4694 			return err;
4695 
4696 		for_each_btf_ext_rec(seg, sec, i, rec) {
4697 			err = visit(&rec->file_name_off, ctx);
4698 			if (err)
4699 				return err;
4700 			err = visit(&rec->line_off, ctx);
4701 			if (err)
4702 				return err;
4703 		}
4704 	}
4705 
4706 	seg = &btf_ext->core_relo_info;
4707 	for_each_btf_ext_sec(seg, sec) {
4708 		struct bpf_core_relo *rec;
4709 
4710 		err = visit(&sec->sec_name_off, ctx);
4711 		if (err)
4712 			return err;
4713 
4714 		for_each_btf_ext_rec(seg, sec, i, rec) {
4715 			err = visit(&rec->access_str_off, ctx);
4716 			if (err)
4717 				return err;
4718 		}
4719 	}
4720 
4721 	return 0;
4722 }
4723