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