1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2019 Facebook */
11 #include <linux/err.h>
17 #include <bpf/libbpf.h>
18 #include <bpf/libbpf_internal.h>
19 #include <sys/types.h>
24 #include "json_writer.h"
27 #define MAX_OBJ_NAME_LEN 64
29 static void sanitize_identifier(char *name
)
33 for (i
= 0; name
[i
]; i
++)
34 if (!isalnum(name
[i
]) && name
[i
] != '_')
38 static bool str_has_prefix(const char *str
, const char *prefix
)
40 return strncmp(str
, prefix
, strlen(prefix
)) == 0;
43 static bool str_has_suffix(const char *str
, const char *suffix
)
45 size_t i
, n1
= strlen(str
), n2
= strlen(suffix
);
50 for (i
= 0; i
< n2
; i
++) {
51 if (str
[n1
- i
- 1] != suffix
[n2
- i
- 1])
58 static const struct btf_type
*
59 resolve_func_ptr(const struct btf
*btf
, __u32 id
, __u32
*res_id
)
61 const struct btf_type
*t
;
63 t
= skip_mods_and_typedefs(btf
, id
, NULL
);
67 t
= skip_mods_and_typedefs(btf
, t
->type
, res_id
);
69 return btf_is_func_proto(t
) ? t
: NULL
;
72 static void get_obj_name(char *name
, const char *file
)
74 char file_copy
[PATH_MAX
];
76 /* Using basename() POSIX version to be more portable. */
77 strncpy(file_copy
, file
, PATH_MAX
- 1)[PATH_MAX
- 1] = '\0';
78 strncpy(name
, basename(file_copy
), MAX_OBJ_NAME_LEN
- 1)[MAX_OBJ_NAME_LEN
- 1] = '\0';
79 if (str_has_suffix(name
, ".o"))
80 name
[strlen(name
) - 2] = '\0';
81 sanitize_identifier(name
);
84 static void get_header_guard(char *guard
, const char *obj_name
, const char *suffix
)
88 sprintf(guard
, "__%s_%s__", obj_name
, suffix
);
89 for (i
= 0; guard
[i
]; i
++)
90 guard
[i
] = toupper(guard
[i
]);
93 static bool get_map_ident(const struct bpf_map
*map
, char *buf
, size_t buf_sz
)
95 static const char *sfxs
[] = { ".data", ".rodata", ".bss", ".kconfig" };
96 const char *name
= bpf_map__name(map
);
99 if (!bpf_map__is_internal(map
)) {
100 snprintf(buf
, buf_sz
, "%s", name
);
104 for (i
= 0, n
= ARRAY_SIZE(sfxs
); i
< n
; i
++) {
105 const char *sfx
= sfxs
[i
], *p
;
107 p
= strstr(name
, sfx
);
109 snprintf(buf
, buf_sz
, "%s", p
+ 1);
110 sanitize_identifier(buf
);
118 static bool get_datasec_ident(const char *sec_name
, char *buf
, size_t buf_sz
)
120 static const char *pfxs
[] = { ".data", ".rodata", ".bss", ".kconfig" };
123 /* recognize hard coded LLVM section name */
124 if (strcmp(sec_name
, ".addr_space.1") == 0) {
125 /* this is the name to use in skeleton */
126 snprintf(buf
, buf_sz
, "arena");
129 for (i
= 0, n
= ARRAY_SIZE(pfxs
); i
< n
; i
++) {
130 const char *pfx
= pfxs
[i
];
132 if (str_has_prefix(sec_name
, pfx
)) {
133 snprintf(buf
, buf_sz
, "%s", sec_name
+ 1);
134 sanitize_identifier(buf
);
142 static void codegen_btf_dump_printf(void *ctx
, const char *fmt
, va_list args
)
147 static int codegen_datasec_def(struct bpf_object
*obj
,
150 const struct btf_type
*sec
,
151 const char *obj_name
)
153 const char *sec_name
= btf__name_by_offset(btf
, sec
->name_off
);
154 const struct btf_var_secinfo
*sec_var
= btf_var_secinfos(sec
);
155 int i
, err
, off
= 0, pad_cnt
= 0, vlen
= btf_vlen(sec
);
156 char var_ident
[256], sec_ident
[256];
157 bool strip_mods
= false;
159 if (!get_datasec_ident(sec_name
, sec_ident
, sizeof(sec_ident
)))
162 if (strcmp(sec_name
, ".kconfig") != 0)
165 printf(" struct %s__%s {\n", obj_name
, sec_ident
);
166 for (i
= 0; i
< vlen
; i
++, sec_var
++) {
167 const struct btf_type
*var
= btf__type_by_id(btf
, sec_var
->type
);
168 const char *var_name
= btf__name_by_offset(btf
, var
->name_off
);
169 DECLARE_LIBBPF_OPTS(btf_dump_emit_type_decl_opts
, opts
,
170 .field_name
= var_ident
,
172 .strip_mods
= strip_mods
,
174 int need_off
= sec_var
->offset
, align_off
, align
;
175 __u32 var_type_id
= var
->type
;
177 /* static variables are not exposed through BPF skeleton */
178 if (btf_var(var
)->linkage
== BTF_VAR_STATIC
)
181 if (off
> need_off
) {
182 p_err("Something is wrong for %s's variable #%d: need offset %d, already at %d.\n",
183 sec_name
, i
, need_off
, off
);
187 align
= btf__align_of(btf
, var
->type
);
189 p_err("Failed to determine alignment of variable '%s': %d",
193 /* Assume 32-bit architectures when generating data section
194 * struct memory layout. Given bpftool can't know which target
195 * host architecture it's emitting skeleton for, we need to be
196 * conservative and assume 32-bit one to ensure enough padding
197 * bytes are generated for pointer and long types. This will
198 * still work correctly for 64-bit architectures, because in
199 * the worst case we'll generate unnecessary padding field,
200 * which on 64-bit architectures is not strictly necessary and
201 * would be handled by natural 8-byte alignment. But it still
202 * will be a correct memory layout, based on recorded offsets
208 align_off
= (off
+ align
- 1) / align
* align
;
209 if (align_off
!= need_off
) {
210 printf("\t\tchar __pad%d[%d];\n",
211 pad_cnt
, need_off
- off
);
215 /* sanitize variable name, e.g., for static vars inside
216 * a function, it's name is '<function name>.<variable name>',
217 * which we'll turn into a '<function name>_<variable name>'
220 strncat(var_ident
, var_name
, sizeof(var_ident
) - 1);
221 sanitize_identifier(var_ident
);
224 err
= btf_dump__emit_type_decl(d
, var_type_id
, &opts
);
229 off
= sec_var
->offset
+ sec_var
->size
;
231 printf(" } *%s;\n", sec_ident
);
235 static const struct btf_type
*find_type_for_map(struct btf
*btf
, const char *map_ident
)
237 int n
= btf__type_cnt(btf
), i
;
240 for (i
= 1; i
< n
; i
++) {
241 const struct btf_type
*t
= btf__type_by_id(btf
, i
);
244 if (!btf_is_datasec(t
))
247 name
= btf__str_by_offset(btf
, t
->name_off
);
248 if (!get_datasec_ident(name
, sec_ident
, sizeof(sec_ident
)))
251 if (strcmp(sec_ident
, map_ident
) == 0)
257 static bool is_mmapable_map(const struct bpf_map
*map
, char *buf
, size_t sz
)
261 if (bpf_map__type(map
) == BPF_MAP_TYPE_ARENA
&& bpf_map__initial_value(map
, &tmp_sz
)) {
262 snprintf(buf
, sz
, "arena");
266 if (!bpf_map__is_internal(map
) || !(bpf_map__map_flags(map
) & BPF_F_MMAPABLE
))
269 if (!get_map_ident(map
, buf
, sz
))
275 static int codegen_datasecs(struct bpf_object
*obj
, const char *obj_name
)
277 struct btf
*btf
= bpf_object__btf(obj
);
280 const struct btf_type
*sec
;
284 d
= btf_dump__new(btf
, codegen_btf_dump_printf
, NULL
, NULL
);
288 bpf_object__for_each_map(map
, obj
) {
289 /* only generate definitions for memory-mapped internal maps */
290 if (!is_mmapable_map(map
, map_ident
, sizeof(map_ident
)))
293 sec
= find_type_for_map(btf
, map_ident
);
295 /* In some cases (e.g., sections like .rodata.cst16 containing
296 * compiler allocated string constants only) there will be
297 * special internal maps with no corresponding DATASEC BTF
298 * type. In such case, generate empty structs for each such
299 * map. It will still be memory-mapped and its contents
300 * accessible from user-space through BPF skeleton.
303 printf(" struct %s__%s {\n", obj_name
, map_ident
);
304 printf(" } *%s;\n", map_ident
);
306 err
= codegen_datasec_def(obj
, btf
, d
, sec
, obj_name
);
318 static bool btf_is_ptr_to_func_proto(const struct btf
*btf
,
319 const struct btf_type
*v
)
321 return btf_is_ptr(v
) && btf_is_func_proto(btf__type_by_id(btf
, v
->type
));
324 static int codegen_subskel_datasecs(struct bpf_object
*obj
, const char *obj_name
)
326 struct btf
*btf
= bpf_object__btf(obj
);
329 const struct btf_type
*sec
, *var
;
330 const struct btf_var_secinfo
*sec_var
;
331 int i
, err
= 0, vlen
;
332 char map_ident
[256], sec_ident
[256];
333 bool strip_mods
= false, needs_typeof
= false;
334 const char *sec_name
, *var_name
;
337 d
= btf_dump__new(btf
, codegen_btf_dump_printf
, NULL
, NULL
);
341 bpf_object__for_each_map(map
, obj
) {
342 /* only generate definitions for memory-mapped internal maps */
343 if (!is_mmapable_map(map
, map_ident
, sizeof(map_ident
)))
346 sec
= find_type_for_map(btf
, map_ident
);
350 sec_name
= btf__name_by_offset(btf
, sec
->name_off
);
351 if (!get_datasec_ident(sec_name
, sec_ident
, sizeof(sec_ident
)))
354 strip_mods
= strcmp(sec_name
, ".kconfig") != 0;
355 printf(" struct %s__%s {\n", obj_name
, sec_ident
);
357 sec_var
= btf_var_secinfos(sec
);
358 vlen
= btf_vlen(sec
);
359 for (i
= 0; i
< vlen
; i
++, sec_var
++) {
360 DECLARE_LIBBPF_OPTS(btf_dump_emit_type_decl_opts
, opts
,
362 .strip_mods
= strip_mods
,
363 /* we'll print the name separately */
367 var
= btf__type_by_id(btf
, sec_var
->type
);
368 var_name
= btf__name_by_offset(btf
, var
->name_off
);
369 var_type_id
= var
->type
;
371 /* static variables are not exposed through BPF skeleton */
372 if (btf_var(var
)->linkage
== BTF_VAR_STATIC
)
375 /* The datasec member has KIND_VAR but we want the
376 * underlying type of the variable (e.g. KIND_INT).
378 var
= skip_mods_and_typedefs(btf
, var
->type
, NULL
);
381 /* Func and array members require special handling.
382 * Instead of producing `typename *var`, they produce
383 * `typeof(typename) *var`. This allows us to keep a
384 * similar syntax where the identifier is just prefixed
385 * by *, allowing us to ignore C declaration minutiae.
387 needs_typeof
= btf_is_array(var
) || btf_is_ptr_to_func_proto(btf
, var
);
389 printf("__typeof__(");
391 err
= btf_dump__emit_type_decl(d
, var_type_id
, &opts
);
398 printf(" *%s;\n", var_name
);
400 printf(" } %s;\n", sec_ident
);
408 static void codegen(const char *template, ...)
410 const char *src
, *end
;
411 int skip_tabs
= 0, n
;
416 n
= strlen(template);
423 /* find out "baseline" indentation to skip */
424 while ((c
= *src
++)) {
427 } else if (c
== '\n') {
430 p_err("unrecognized character at pos %td in template '%s': '%c'",
431 src
- template - 1, template, c
);
438 /* skip baseline indentation tabs */
439 for (n
= skip_tabs
; n
> 0; n
--, src
++) {
441 p_err("not enough tabs at pos %td in template '%s'",
442 src
- template - 1, template);
447 /* trim trailing whitespace */
448 end
= strchrnul(src
, '\n');
449 for (n
= end
- src
; n
> 0 && isspace(src
[n
- 1]); n
--)
455 src
= *end
? end
+ 1 : end
;
459 /* print out using adjusted template */
460 va_start(args
, template);
461 n
= vprintf(s
, args
);
467 static void print_hex(const char *data
, int data_sz
)
471 for (i
= 0, len
= 0; i
< data_sz
; i
++) {
472 int w
= data
[i
] ? 4 : 2;
482 printf("\\x%02x", (unsigned char)data
[i
]);
486 static size_t bpf_map_mmap_sz(const struct bpf_map
*map
)
488 long page_sz
= sysconf(_SC_PAGE_SIZE
);
491 map_sz
= (size_t)roundup(bpf_map__value_size(map
), 8) * bpf_map__max_entries(map
);
492 map_sz
= roundup(map_sz
, page_sz
);
496 /* Emit type size asserts for all top-level fields in memory-mapped internal maps. */
497 static void codegen_asserts(struct bpf_object
*obj
, const char *obj_name
)
499 struct btf
*btf
= bpf_object__btf(obj
);
501 struct btf_var_secinfo
*sec_var
;
503 const struct btf_type
*sec
;
504 char map_ident
[256], var_ident
[256];
511 __attribute__((unused)) static void \n\
512 %1$s__assert(struct %1$s *s __attribute__((unused))) \n\
514 #ifdef __cplusplus \n\
515 #define _Static_assert static_assert \n\
519 bpf_object__for_each_map(map
, obj
) {
520 if (!is_mmapable_map(map
, map_ident
, sizeof(map_ident
)))
523 sec
= find_type_for_map(btf
, map_ident
);
525 /* best effort, couldn't find the type for this map */
529 sec_var
= btf_var_secinfos(sec
);
530 vlen
= btf_vlen(sec
);
532 for (i
= 0; i
< vlen
; i
++, sec_var
++) {
533 const struct btf_type
*var
= btf__type_by_id(btf
, sec_var
->type
);
534 const char *var_name
= btf__name_by_offset(btf
, var
->name_off
);
537 /* static variables are not exposed through BPF skeleton */
538 if (btf_var(var
)->linkage
== BTF_VAR_STATIC
)
541 var_size
= btf__resolve_size(btf
, var
->type
);
546 strncat(var_ident
, var_name
, sizeof(var_ident
) - 1);
547 sanitize_identifier(var_ident
);
549 printf("\t_Static_assert(sizeof(s->%s->%s) == %ld, \"unexpected size of '%s'\");\n",
550 map_ident
, var_ident
, var_size
, var_ident
);
555 #ifdef __cplusplus \n\
556 #undef _Static_assert \n\
562 static void codegen_attach_detach(struct bpf_object
*obj
, const char *obj_name
)
564 struct bpf_program
*prog
;
566 bpf_object__for_each_program(prog
, obj
) {
572 static inline int \n\
573 %1$s__%2$s__attach(struct %1$s *skel) \n\
575 int prog_fd = skel->progs.%2$s.prog_fd; \n\
576 ", obj_name
, bpf_program__name(prog
));
578 switch (bpf_program__type(prog
)) {
579 case BPF_PROG_TYPE_RAW_TRACEPOINT
:
580 tp_name
= strchr(bpf_program__section_name(prog
), '/') + 1;
581 printf("\tint fd = skel_raw_tracepoint_open(\"%s\", prog_fd);\n", tp_name
);
583 case BPF_PROG_TYPE_TRACING
:
584 case BPF_PROG_TYPE_LSM
:
585 if (bpf_program__expected_attach_type(prog
) == BPF_TRACE_ITER
)
586 printf("\tint fd = skel_link_create(prog_fd, 0, BPF_TRACE_ITER);\n");
588 printf("\tint fd = skel_raw_tracepoint_open(NULL, prog_fd);\n");
591 printf("\tint fd = ((void)prog_fd, 0); /* auto-attach not supported */\n");
598 skel->links.%1$s_fd = fd; \n\
601 ", bpf_program__name(prog
));
607 static inline int \n\
608 %1$s__attach(struct %1$s *skel) \n\
614 bpf_object__for_each_program(prog
, obj
) {
617 ret = ret < 0 ? ret : %1$s__%2$s__attach(skel); \n\
618 ", obj_name
, bpf_program__name(prog
));
623 return ret < 0 ? ret : 0; \n\
626 static inline void \n\
627 %1$s__detach(struct %1$s *skel) \n\
631 bpf_object__for_each_program(prog
, obj
) {
634 skel_closenz(skel->links.%1$s_fd); \n\
635 ", bpf_program__name(prog
));
644 static void codegen_destroy(struct bpf_object
*obj
, const char *obj_name
)
646 struct bpf_program
*prog
;
653 %1$s__destroy(struct %1$s *skel) \n\
657 %1$s__detach(skel); \n\
661 bpf_object__for_each_program(prog
, obj
) {
664 skel_closenz(skel->progs.%1$s.prog_fd); \n\
665 ", bpf_program__name(prog
));
668 bpf_object__for_each_map(map
, obj
) {
669 if (!get_map_ident(map
, ident
, sizeof(ident
)))
671 if (bpf_map__is_internal(map
) &&
672 (bpf_map__map_flags(map
) & BPF_F_MMAPABLE
))
673 printf("\tskel_free_map_data(skel->%1$s, skel->maps.%1$s.initial_value, %2$zd);\n",
674 ident
, bpf_map_mmap_sz(map
));
677 skel_closenz(skel->maps.%1$s.map_fd); \n\
688 static int gen_trace(struct bpf_object
*obj
, const char *obj_name
, const char *header_guard
)
690 DECLARE_LIBBPF_OPTS(gen_loader_opts
, opts
);
695 err
= bpf_object__gen_loader(obj
, &opts
);
699 err
= bpf_object__load(obj
);
701 p_err("failed to load object file");
704 /* If there was no error during load then gen_loader_opts
705 * are populated with the loader program.
708 /* finish generating 'struct skel' */
715 codegen_attach_detach(obj
, obj_name
);
717 codegen_destroy(obj
, obj_name
);
721 static inline struct %1$s * \n\
724 struct %1$s *skel; \n\
726 skel = skel_alloc(sizeof(*skel)); \n\
729 skel->ctx.sz = (void *)&skel->links - (void *)skel; \n\
731 obj_name
, opts
.data_sz
);
732 bpf_object__for_each_map(map
, obj
) {
733 const void *mmap_data
= NULL
;
734 size_t mmap_size
= 0;
736 if (!is_mmapable_map(map
, ident
, sizeof(ident
)))
742 static const char data[] __attribute__((__aligned__(8))) = \"\\\n\
744 mmap_data
= bpf_map__initial_value(map
, &mmap_size
);
745 print_hex(mmap_data
, mmap_size
);
750 skel->%1$s = skel_prep_map_data((void *)data, %2$zd,\n\
751 sizeof(data) - 1);\n\
754 skel->maps.%1$s.initial_value = (__u64) (long) skel->%1$s;\n\
756 ", ident
, bpf_map_mmap_sz(map
));
762 %1$s__destroy(skel); \n\
766 static inline int \n\
767 %1$s__load(struct %1$s *skel) \n\
769 struct bpf_load_and_run_opts opts = {}; \n\
771 static const char opts_data[] __attribute__((__aligned__(8))) = \"\\\n\
774 print_hex(opts
.data
, opts
.data_sz
);
778 static const char opts_insn[] __attribute__((__aligned__(8))) = \"\\\n\
780 print_hex(opts
.insns
, opts
.insns_sz
);
785 opts.ctx = (struct bpf_loader_ctx *)skel; \n\
786 opts.data_sz = sizeof(opts_data) - 1; \n\
787 opts.data = (void *)opts_data; \n\
788 opts.insns_sz = sizeof(opts_insn) - 1; \n\
789 opts.insns = (void *)opts_insn; \n\
791 err = bpf_load_and_run(&opts); \n\
795 bpf_object__for_each_map(map
, obj
) {
796 const char *mmap_flags
;
798 if (!is_mmapable_map(map
, ident
, sizeof(ident
)))
801 if (bpf_map__map_flags(map
) & BPF_F_RDONLY_PROG
)
802 mmap_flags
= "PROT_READ";
804 mmap_flags
= "PROT_READ | PROT_WRITE";
808 skel->%1$s = skel_finalize_map_data(&skel->maps.%1$s.initial_value, \n\
809 %2$zd, %3$s, skel->maps.%1$s.map_fd);\n\
813 ident
, bpf_map_mmap_sz(map
), mmap_flags
);
820 static inline struct %1$s * \n\
821 %1$s__open_and_load(void) \n\
823 struct %1$s *skel; \n\
825 skel = %1$s__open(); \n\
828 if (%1$s__load(skel)) { \n\
829 %1$s__destroy(skel); \n\
837 codegen_asserts(obj
, obj_name
);
851 codegen_maps_skeleton(struct bpf_object
*obj
, size_t map_cnt
, bool mmaped
, bool populate_links
)
860 /* for backward compatibility with old libbpf versions that don't
861 * handle new BPF skeleton with new struct bpf_map_skeleton definition
862 * that includes link field, avoid specifying new increased size,
863 * unless we absolutely have to (i.e., if there are struct_ops maps
866 map_sz
= offsetof(struct bpf_map_skeleton
, link
);
867 if (populate_links
) {
868 bpf_object__for_each_map(map
, obj
) {
869 if (bpf_map__type(map
) == BPF_MAP_TYPE_STRUCT_OPS
) {
870 map_sz
= sizeof(struct bpf_map_skeleton
);
880 s->map_cnt = %zu; \n\
881 s->map_skel_sz = %zu; \n\
882 s->maps = (struct bpf_map_skeleton *)calloc(s->map_cnt,\n\
883 sizeof(*s->maps) > %zu ? sizeof(*s->maps) : %zu);\n\
889 map_cnt
, map_sz
, map_sz
, map_sz
892 bpf_object__for_each_map(map
, obj
) {
893 if (!get_map_ident(map
, ident
, sizeof(ident
)))
899 map = (struct bpf_map_skeleton *)((char *)s->maps + %zu * s->map_skel_sz);\n\
900 map->name = \"%s\"; \n\
901 map->map = &obj->maps.%s; \n\
903 i
, bpf_map__name(map
), ident
);
904 /* memory-mapped internal maps */
905 if (mmaped
&& is_mmapable_map(map
, ident
, sizeof(ident
))) {
906 printf("\tmap->mmaped = (void **)&obj->%s;\n", ident
);
909 if (populate_links
&& bpf_map__type(map
) == BPF_MAP_TYPE_STRUCT_OPS
) {
912 map->link = &obj->links.%s; \n\
920 codegen_progs_skeleton(struct bpf_object
*obj
, size_t prog_cnt
, bool populate_links
)
922 struct bpf_program
*prog
;
932 s->prog_cnt = %zu; \n\
933 s->prog_skel_sz = sizeof(*s->progs); \n\
934 s->progs = (struct bpf_prog_skeleton *)calloc(s->prog_cnt, s->prog_skel_sz);\n\
943 bpf_object__for_each_program(prog
, obj
) {
947 s->progs[%1$zu].name = \"%2$s\"; \n\
948 s->progs[%1$zu].prog = &obj->progs.%2$s;\n\
950 i
, bpf_program__name(prog
));
952 if (populate_links
) {
955 s->progs[%1$zu].link = &obj->links.%2$s;\n\
957 i
, bpf_program__name(prog
));
963 static int walk_st_ops_shadow_vars(struct btf
*btf
, const char *ident
,
964 const struct btf_type
*map_type
, __u32 map_type_id
)
966 LIBBPF_OPTS(btf_dump_emit_type_decl_opts
, opts
, .indent_level
= 3);
967 const struct btf_type
*member_type
;
968 __u32 offset
, next_offset
= 0;
969 const struct btf_member
*m
;
970 struct btf_dump
*d
= NULL
;
971 const char *member_name
;
972 __u32 member_type_id
;
976 d
= btf_dump__new(btf
, codegen_btf_dump_printf
, NULL
, NULL
);
980 n
= btf_vlen(map_type
);
981 for (i
= 0, m
= btf_members(map_type
); i
< n
; i
++, m
++) {
982 member_type
= skip_mods_and_typedefs(btf
, m
->type
, &member_type_id
);
983 member_name
= btf__name_by_offset(btf
, m
->name_off
);
985 offset
= m
->offset
/ 8;
986 if (next_offset
< offset
)
987 printf("\t\t\tchar __padding_%d[%d];\n", i
, offset
- next_offset
);
989 switch (btf_kind(member_type
)) {
993 case BTF_KIND_ENUM64
:
996 opts
.field_name
= member_name
;
997 err
= btf_dump__emit_type_decl(d
, member_type_id
, &opts
);
999 p_err("Failed to emit type declaration for %s: %d", member_name
, err
);
1004 size
= btf__resolve_size(btf
, member_type_id
);
1006 p_err("Failed to resolve size of %s: %d\n", member_name
, size
);
1011 next_offset
= offset
+ size
;
1015 if (resolve_func_ptr(btf
, m
->type
, NULL
)) {
1016 /* Function pointer */
1017 printf("\t\t\tstruct bpf_program *%s;\n", member_name
);
1019 next_offset
= offset
+ sizeof(void *);
1022 /* All pointer types are unsupported except for
1023 * function pointers.
1028 /* Unsupported types
1030 * Types other than scalar types and function
1031 * pointers are currently not supported in order to
1032 * prevent conflicts in the generated code caused
1033 * by multiple definitions. For instance, if the
1034 * struct type FOO is used in a struct_ops map,
1035 * bpftool has to generate definitions for FOO,
1036 * which may result in conflicts if FOO is defined
1037 * in different skeleton files.
1039 size
= btf__resolve_size(btf
, member_type_id
);
1041 p_err("Failed to resolve size of %s: %d\n", member_name
, size
);
1045 printf("\t\t\tchar __unsupported_%d[%d];\n", i
, size
);
1047 next_offset
= offset
+ size
;
1052 /* Cannot fail since it must be a struct type */
1053 size
= btf__resolve_size(btf
, map_type_id
);
1054 if (next_offset
< (__u32
)size
)
1055 printf("\t\t\tchar __padding_end[%d];\n", size
- next_offset
);
1063 /* Generate the pointer of the shadow type for a struct_ops map.
1065 * This function adds a pointer of the shadow type for a struct_ops map.
1066 * The members of a struct_ops map can be exported through a pointer to a
1067 * shadow type. The user can access these members through the pointer.
1069 * A shadow type includes not all members, only members of some types.
1070 * They are scalar types and function pointers. The function pointers are
1071 * translated to the pointer of the struct bpf_program. The scalar types
1072 * are translated to the original type without any modifiers.
1074 * Unsupported types will be translated to a char array to occupy the same
1075 * space as the original field, being renamed as __unsupported_*. The user
1076 * should treat these fields as opaque data.
1078 static int gen_st_ops_shadow_type(const char *obj_name
, struct btf
*btf
, const char *ident
,
1079 const struct bpf_map
*map
)
1081 const struct btf_type
*map_type
;
1082 const char *type_name
;
1086 map_type_id
= bpf_map__btf_value_type_id(map
);
1087 if (map_type_id
== 0)
1089 map_type
= btf__type_by_id(btf
, map_type_id
);
1093 type_name
= btf__name_by_offset(btf
, map_type
->name_off
);
1095 printf("\t\tstruct %s__%s__%s {\n", obj_name
, ident
, type_name
);
1097 err
= walk_st_ops_shadow_vars(btf
, ident
, map_type
, map_type_id
);
1101 printf("\t\t} *%s;\n", ident
);
1106 static int gen_st_ops_shadow(const char *obj_name
, struct btf
*btf
, struct bpf_object
*obj
)
1108 int err
, st_ops_cnt
= 0;
1109 struct bpf_map
*map
;
1115 /* Generate the pointers to shadow types of
1118 bpf_object__for_each_map(map
, obj
) {
1119 if (bpf_map__type(map
) != BPF_MAP_TYPE_STRUCT_OPS
)
1121 if (!get_map_ident(map
, ident
, sizeof(ident
)))
1124 if (st_ops_cnt
== 0) /* first struct_ops map */
1125 printf("\tstruct {\n");
1128 err
= gen_st_ops_shadow_type(obj_name
, btf
, ident
, map
);
1134 printf("\t} struct_ops;\n");
1139 /* Generate the code to initialize the pointers of shadow types. */
1140 static void gen_st_ops_shadow_init(struct btf
*btf
, struct bpf_object
*obj
)
1142 struct bpf_map
*map
;
1148 /* Initialize the pointers to_ops shadow types of
1151 bpf_object__for_each_map(map
, obj
) {
1152 if (bpf_map__type(map
) != BPF_MAP_TYPE_STRUCT_OPS
)
1154 if (!get_map_ident(map
, ident
, sizeof(ident
)))
1158 obj->struct_ops.%1$s = (__typeof__(obj->struct_ops.%1$s))\n\
1159 bpf_map__initial_value(obj->maps.%1$s, NULL);\n\
1165 static int do_skeleton(int argc
, char **argv
)
1167 char header_guard
[MAX_OBJ_NAME_LEN
+ sizeof("__SKEL_H__")];
1168 size_t map_cnt
= 0, prog_cnt
= 0, attach_map_cnt
= 0, file_sz
, mmap_sz
;
1169 DECLARE_LIBBPF_OPTS(bpf_object_open_opts
, opts
);
1170 char obj_name
[MAX_OBJ_NAME_LEN
] = "", *obj_data
;
1171 struct bpf_object
*obj
= NULL
;
1174 struct bpf_program
*prog
;
1176 struct bpf_map
*map
;
1190 if (is_prefix(*argv
, "name")) {
1193 if (obj_name
[0] != '\0') {
1194 p_err("object name already specified");
1198 strncpy(obj_name
, *argv
, MAX_OBJ_NAME_LEN
- 1);
1199 obj_name
[MAX_OBJ_NAME_LEN
- 1] = '\0';
1201 p_err("unknown arg %s", *argv
);
1209 p_err("extra unknown arguments");
1213 if (stat(file
, &st
)) {
1214 p_err("failed to stat() %s: %s", file
, strerror(errno
));
1217 file_sz
= st
.st_size
;
1218 mmap_sz
= roundup(file_sz
, sysconf(_SC_PAGE_SIZE
));
1219 fd
= open(file
, O_RDONLY
);
1221 p_err("failed to open() %s: %s", file
, strerror(errno
));
1224 obj_data
= mmap(NULL
, mmap_sz
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1225 if (obj_data
== MAP_FAILED
) {
1227 p_err("failed to mmap() %s: %s", file
, strerror(errno
));
1230 if (obj_name
[0] == '\0')
1231 get_obj_name(obj_name
, file
);
1232 opts
.object_name
= obj_name
;
1234 /* log_level1 + log_level2 + stats, but not stable UAPI */
1235 opts
.kernel_log_level
= 1 + 2 + 4;
1236 obj
= bpf_object__open_mem(obj_data
, file_sz
, &opts
);
1241 libbpf_strerror(err
, err_buf
, sizeof(err_buf
));
1242 p_err("failed to open BPF object file: %s", err_buf
);
1246 bpf_object__for_each_map(map
, obj
) {
1247 if (!get_map_ident(map
, ident
, sizeof(ident
))) {
1248 p_err("ignoring unrecognized internal map '%s'...",
1249 bpf_map__name(map
));
1253 if (bpf_map__type(map
) == BPF_MAP_TYPE_STRUCT_OPS
)
1258 bpf_object__for_each_program(prog
, obj
) {
1262 get_header_guard(header_guard
, obj_name
, "SKEL_H");
1266 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ \n\
1267 /* THIS FILE IS AUTOGENERATED BY BPFTOOL! */ \n\
1271 #include <bpf/skel_internal.h> \n\
1274 struct bpf_loader_ctx ctx; \n\
1276 obj_name
, header_guard
1281 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ \n\
1283 /* THIS FILE IS AUTOGENERATED BY BPFTOOL! */ \n\
1287 #include <errno.h> \n\
1288 #include <stdlib.h> \n\
1289 #include <bpf/libbpf.h> \n\
1291 #define BPF_SKEL_SUPPORTS_MAP_AUTO_ATTACH 1 \n\
1294 struct bpf_object_skeleton *skeleton; \n\
1295 struct bpf_object *obj; \n\
1297 obj_name
, header_guard
1302 printf("\tstruct {\n");
1303 bpf_object__for_each_map(map
, obj
) {
1304 if (!get_map_ident(map
, ident
, sizeof(ident
)))
1307 printf("\t\tstruct bpf_map_desc %s;\n", ident
);
1309 printf("\t\tstruct bpf_map *%s;\n", ident
);
1311 printf("\t} maps;\n");
1314 btf
= bpf_object__btf(obj
);
1315 err
= gen_st_ops_shadow(obj_name
, btf
, obj
);
1320 printf("\tstruct {\n");
1321 bpf_object__for_each_program(prog
, obj
) {
1323 printf("\t\tstruct bpf_prog_desc %s;\n",
1324 bpf_program__name(prog
));
1326 printf("\t\tstruct bpf_program *%s;\n",
1327 bpf_program__name(prog
));
1329 printf("\t} progs;\n");
1332 if (prog_cnt
+ attach_map_cnt
) {
1333 printf("\tstruct {\n");
1334 bpf_object__for_each_program(prog
, obj
) {
1336 printf("\t\tint %s_fd;\n",
1337 bpf_program__name(prog
));
1339 printf("\t\tstruct bpf_link *%s;\n",
1340 bpf_program__name(prog
));
1343 bpf_object__for_each_map(map
, obj
) {
1344 if (!get_map_ident(map
, ident
, sizeof(ident
)))
1346 if (bpf_map__type(map
) != BPF_MAP_TYPE_STRUCT_OPS
)
1350 printf("t\tint %s_fd;\n", ident
);
1352 printf("\t\tstruct bpf_link *%s;\n", ident
);
1355 printf("\t} links;\n");
1359 err
= codegen_datasecs(obj
, obj_name
);
1364 err
= gen_trace(obj
, obj_name
, header_guard
);
1371 #ifdef __cplusplus \n\
1372 static inline struct %1$s *open(const struct bpf_object_open_opts *opts = nullptr);\n\
1373 static inline struct %1$s *open_and_load(); \n\
1374 static inline int load(struct %1$s *skel); \n\
1375 static inline int attach(struct %1$s *skel); \n\
1376 static inline void detach(struct %1$s *skel); \n\
1377 static inline void destroy(struct %1$s *skel); \n\
1378 static inline const void *elf_bytes(size_t *sz); \n\
1379 #endif /* __cplusplus */ \n\
1383 %1$s__destroy(struct %1$s *obj) \n\
1387 if (obj->skeleton) \n\
1388 bpf_object__destroy_skeleton(obj->skeleton);\n\
1392 static inline int \n\
1393 %1$s__create_skeleton(struct %1$s *obj); \n\
1395 static inline struct %1$s * \n\
1396 %1$s__open_opts(const struct bpf_object_open_opts *opts) \n\
1398 struct %1$s *obj; \n\
1401 obj = (struct %1$s *)calloc(1, sizeof(*obj)); \n\
1407 err = %1$s__create_skeleton(obj); \n\
1411 err = bpf_object__open_skeleton(obj->skeleton, opts);\n\
1417 gen_st_ops_shadow_init(btf
, obj
);
1423 %1$s__destroy(obj); \n\
1428 static inline struct %1$s * \n\
1429 %1$s__open(void) \n\
1431 return %1$s__open_opts(NULL); \n\
1434 static inline int \n\
1435 %1$s__load(struct %1$s *obj) \n\
1437 return bpf_object__load_skeleton(obj->skeleton); \n\
1440 static inline struct %1$s * \n\
1441 %1$s__open_and_load(void) \n\
1443 struct %1$s *obj; \n\
1446 obj = %1$s__open(); \n\
1449 err = %1$s__load(obj); \n\
1451 %1$s__destroy(obj); \n\
1458 static inline int \n\
1459 %1$s__attach(struct %1$s *obj) \n\
1461 return bpf_object__attach_skeleton(obj->skeleton); \n\
1464 static inline void \n\
1465 %1$s__detach(struct %1$s *obj) \n\
1467 bpf_object__detach_skeleton(obj->skeleton); \n\
1476 static inline const void *%1$s__elf_bytes(size_t *sz); \n\
1478 static inline int \n\
1479 %1$s__create_skeleton(struct %1$s *obj) \n\
1481 struct bpf_object_skeleton *s; \n\
1482 struct bpf_map_skeleton *map __attribute__((unused));\n\
1485 s = (struct bpf_object_skeleton *)calloc(1, sizeof(*s));\n\
1491 s->sz = sizeof(*s); \n\
1492 s->name = \"%1$s\"; \n\
1493 s->obj = &obj->obj; \n\
1498 codegen_maps_skeleton(obj
, map_cnt
, true /*mmaped*/, true /*links*/);
1499 codegen_progs_skeleton(obj
, prog_cnt
, true /*populate_links*/);
1504 s->data = %1$s__elf_bytes(&s->data_sz); \n\
1506 obj->skeleton = s; \n\
1509 bpf_object__destroy_skeleton(s); \n\
1513 static inline const void *%1$s__elf_bytes(size_t *sz) \n\
1515 static const char data[] __attribute__((__aligned__(8))) = \"\\\n\
1520 /* embed contents of BPF object file */
1521 print_hex(obj_data
, file_sz
);
1527 *sz = sizeof(data) - 1; \n\
1528 return (const void *)data; \n\
1531 #ifdef __cplusplus \n\
1532 struct %1$s *%1$s::open(const struct bpf_object_open_opts *opts) { return %1$s__open_opts(opts); }\n\
1533 struct %1$s *%1$s::open_and_load() { return %1$s__open_and_load(); } \n\
1534 int %1$s::load(struct %1$s *skel) { return %1$s__load(skel); } \n\
1535 int %1$s::attach(struct %1$s *skel) { return %1$s__attach(skel); } \n\
1536 void %1$s::detach(struct %1$s *skel) { %1$s__detach(skel); } \n\
1537 void %1$s::destroy(struct %1$s *skel) { %1$s__destroy(skel); } \n\
1538 const void *%1$s::elf_bytes(size_t *sz) { return %1$s__elf_bytes(sz); } \n\
1539 #endif /* __cplusplus */ \n\
1544 codegen_asserts(obj
, obj_name
);
1549 #endif /* %1$s */ \n\
1554 bpf_object__close(obj
);
1556 munmap(obj_data
, mmap_sz
);
1561 /* Subskeletons are like skeletons, except they don't own the bpf_object,
1562 * associated maps, links, etc. Instead, they know about the existence of
1563 * variables, maps, programs and are able to find their locations
1564 * _at runtime_ from an already loaded bpf_object.
1566 * This allows for library-like BPF objects to have userspace counterparts
1567 * with access to their own items without having to know anything about the
1568 * final BPF object that the library was linked into.
1570 static int do_subskeleton(int argc
, char **argv
)
1572 char header_guard
[MAX_OBJ_NAME_LEN
+ sizeof("__SUBSKEL_H__")];
1573 size_t i
, len
, file_sz
, map_cnt
= 0, prog_cnt
= 0, mmap_sz
, var_cnt
= 0, var_idx
= 0;
1574 DECLARE_LIBBPF_OPTS(bpf_object_open_opts
, opts
);
1575 char obj_name
[MAX_OBJ_NAME_LEN
] = "", *obj_data
;
1576 struct bpf_object
*obj
= NULL
;
1577 const char *file
, *var_name
;
1579 int fd
, err
= -1, map_type_id
;
1580 const struct bpf_map
*map
;
1581 struct bpf_program
*prog
;
1583 const struct btf_type
*map_type
, *var_type
;
1584 const struct btf_var_secinfo
*var
;
1597 if (is_prefix(*argv
, "name")) {
1600 if (obj_name
[0] != '\0') {
1601 p_err("object name already specified");
1605 strncpy(obj_name
, *argv
, MAX_OBJ_NAME_LEN
- 1);
1606 obj_name
[MAX_OBJ_NAME_LEN
- 1] = '\0';
1608 p_err("unknown arg %s", *argv
);
1616 p_err("extra unknown arguments");
1621 p_err("cannot use loader for subskeletons");
1625 if (stat(file
, &st
)) {
1626 p_err("failed to stat() %s: %s", file
, strerror(errno
));
1629 file_sz
= st
.st_size
;
1630 mmap_sz
= roundup(file_sz
, sysconf(_SC_PAGE_SIZE
));
1631 fd
= open(file
, O_RDONLY
);
1633 p_err("failed to open() %s: %s", file
, strerror(errno
));
1636 obj_data
= mmap(NULL
, mmap_sz
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1637 if (obj_data
== MAP_FAILED
) {
1639 p_err("failed to mmap() %s: %s", file
, strerror(errno
));
1642 if (obj_name
[0] == '\0')
1643 get_obj_name(obj_name
, file
);
1645 /* The empty object name allows us to use bpf_map__name and produce
1646 * ELF section names out of it. (".data" instead of "obj.data")
1648 opts
.object_name
= "";
1649 obj
= bpf_object__open_mem(obj_data
, file_sz
, &opts
);
1653 libbpf_strerror(errno
, err_buf
, sizeof(err_buf
));
1654 p_err("failed to open BPF object file: %s", err_buf
);
1659 btf
= bpf_object__btf(obj
);
1662 p_err("need btf type information for %s", obj_name
);
1666 bpf_object__for_each_program(prog
, obj
) {
1670 /* First, count how many variables we have to find.
1671 * We need this in advance so the subskel can allocate the right
1672 * amount of storage.
1674 bpf_object__for_each_map(map
, obj
) {
1675 if (!get_map_ident(map
, ident
, sizeof(ident
)))
1678 /* Also count all maps that have a name */
1681 if (!is_mmapable_map(map
, ident
, sizeof(ident
)))
1684 map_type_id
= bpf_map__btf_value_type_id(map
);
1685 if (map_type_id
<= 0) {
1689 map_type
= btf__type_by_id(btf
, map_type_id
);
1691 var
= btf_var_secinfos(map_type
);
1692 len
= btf_vlen(map_type
);
1693 for (i
= 0; i
< len
; i
++, var
++) {
1694 var_type
= btf__type_by_id(btf
, var
->type
);
1696 if (btf_var(var_type
)->linkage
== BTF_VAR_STATIC
)
1703 get_header_guard(header_guard
, obj_name
, "SUBSKEL_H");
1706 /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */ \n\
1708 /* THIS FILE IS AUTOGENERATED! */ \n\
1712 #include <errno.h> \n\
1713 #include <stdlib.h> \n\
1714 #include <bpf/libbpf.h> \n\
1717 struct bpf_object *obj; \n\
1718 struct bpf_object_subskeleton *subskel; \n\
1719 ", obj_name
, header_guard
);
1722 printf("\tstruct {\n");
1723 bpf_object__for_each_map(map
, obj
) {
1724 if (!get_map_ident(map
, ident
, sizeof(ident
)))
1726 printf("\t\tstruct bpf_map *%s;\n", ident
);
1728 printf("\t} maps;\n");
1731 err
= gen_st_ops_shadow(obj_name
, btf
, obj
);
1736 printf("\tstruct {\n");
1737 bpf_object__for_each_program(prog
, obj
) {
1738 printf("\t\tstruct bpf_program *%s;\n",
1739 bpf_program__name(prog
));
1741 printf("\t} progs;\n");
1744 err
= codegen_subskel_datasecs(obj
, obj_name
);
1748 /* emit code that will allocate enough storage for all symbols */
1752 #ifdef __cplusplus \n\
1753 static inline struct %1$s *open(const struct bpf_object *src);\n\
1754 static inline void destroy(struct %1$s *skel); \n\
1755 #endif /* __cplusplus */ \n\
1758 static inline void \n\
1759 %1$s__destroy(struct %1$s *skel) \n\
1763 if (skel->subskel) \n\
1764 bpf_object__destroy_subskeleton(skel->subskel);\n\
1768 static inline struct %1$s * \n\
1769 %1$s__open(const struct bpf_object *src) \n\
1771 struct %1$s *obj; \n\
1772 struct bpf_object_subskeleton *s; \n\
1773 struct bpf_map_skeleton *map __attribute__((unused));\n\
1776 obj = (struct %1$s *)calloc(1, sizeof(*obj)); \n\
1781 s = (struct bpf_object_subskeleton *)calloc(1, sizeof(*s));\n\
1786 s->sz = sizeof(*s); \n\
1788 s->var_skel_sz = sizeof(*s->vars); \n\
1789 obj->subskel = s; \n\
1792 s->var_cnt = %2$d; \n\
1793 s->vars = (struct bpf_var_skeleton *)calloc(%2$d, sizeof(*s->vars));\n\
1802 /* walk through each symbol and emit the runtime representation */
1803 bpf_object__for_each_map(map
, obj
) {
1804 if (!is_mmapable_map(map
, ident
, sizeof(ident
)))
1807 map_type_id
= bpf_map__btf_value_type_id(map
);
1808 if (map_type_id
<= 0)
1809 /* skip over internal maps with no type*/
1812 map_type
= btf__type_by_id(btf
, map_type_id
);
1813 var
= btf_var_secinfos(map_type
);
1814 len
= btf_vlen(map_type
);
1815 for (i
= 0; i
< len
; i
++, var
++) {
1816 var_type
= btf__type_by_id(btf
, var
->type
);
1817 var_name
= btf__name_by_offset(btf
, var_type
->name_off
);
1819 if (btf_var(var_type
)->linkage
== BTF_VAR_STATIC
)
1822 /* Note that we use the dot prefix in .data as the
1823 * field access operator i.e. maps%s becomes maps.data
1828 s->vars[%3$d].name = \"%1$s\"; \n\
1829 s->vars[%3$d].map = &obj->maps.%2$s; \n\
1830 s->vars[%3$d].addr = (void **) &obj->%2$s.%1$s;\n\
1831 ", var_name
, ident
, var_idx
);
1837 codegen_maps_skeleton(obj
, map_cnt
, false /*mmaped*/, false /*links*/);
1838 codegen_progs_skeleton(obj
, prog_cnt
, false /*links*/);
1843 err = bpf_object__open_subskeleton(s); \n\
1849 gen_st_ops_shadow_init(btf
, obj
);
1855 %1$s__destroy(obj); \n\
1860 #ifdef __cplusplus \n\
1861 struct %1$s *%1$s::open(const struct bpf_object *src) { return %1$s__open(src); }\n\
1862 void %1$s::destroy(struct %1$s *skel) { %1$s__destroy(skel); }\n\
1863 #endif /* __cplusplus */ \n\
1865 #endif /* %2$s */ \n\
1867 obj_name
, header_guard
);
1870 bpf_object__close(obj
);
1872 munmap(obj_data
, mmap_sz
);
1877 static int do_object(int argc
, char **argv
)
1879 struct bpf_linker
*linker
;
1880 const char *output_file
, *file
;
1888 output_file
= GET_ARG();
1890 linker
= bpf_linker__new(output_file
, NULL
);
1892 p_err("failed to create BPF linker instance");
1899 err
= bpf_linker__add_file(linker
, file
, NULL
);
1901 p_err("failed to link '%s': %s (%d)", file
, strerror(errno
), errno
);
1906 err
= bpf_linker__finalize(linker
);
1908 p_err("failed to finalize ELF file: %s (%d)", strerror(errno
), errno
);
1914 bpf_linker__free(linker
);
1918 static int do_help(int argc
, char **argv
)
1921 jsonw_null(json_wtr
);
1926 "Usage: %1$s %2$s object OUTPUT_FILE INPUT_FILE [INPUT_FILE...]\n"
1927 " %1$s %2$s skeleton FILE [name OBJECT_NAME]\n"
1928 " %1$s %2$s subskeleton FILE [name OBJECT_NAME]\n"
1929 " %1$s %2$s min_core_btf INPUT OUTPUT OBJECT [OBJECT...]\n"
1932 " " HELP_SPEC_OPTIONS
" |\n"
1933 " {-L|--use-loader} }\n"
1940 static int btf_save_raw(const struct btf
*btf
, const char *path
)
1947 data
= btf__raw_data(btf
, &data_sz
);
1951 f
= fopen(path
, "wb");
1955 if (fwrite(data
, 1, data_sz
, f
) != data_sz
)
1962 struct btfgen_info
{
1963 struct btf
*src_btf
;
1964 struct btf
*marked_btf
; /* btf structure used to mark used types */
1967 static size_t btfgen_hash_fn(long key
, void *ctx
)
1972 static bool btfgen_equal_fn(long k1
, long k2
, void *ctx
)
1977 static void btfgen_free_info(struct btfgen_info
*info
)
1982 btf__free(info
->src_btf
);
1983 btf__free(info
->marked_btf
);
1988 static struct btfgen_info
*
1989 btfgen_new_info(const char *targ_btf_path
)
1991 struct btfgen_info
*info
;
1994 info
= calloc(1, sizeof(*info
));
1998 info
->src_btf
= btf__parse(targ_btf_path
, NULL
);
1999 if (!info
->src_btf
) {
2001 p_err("failed parsing '%s' BTF file: %s", targ_btf_path
, strerror(errno
));
2005 info
->marked_btf
= btf__parse(targ_btf_path
, NULL
);
2006 if (!info
->marked_btf
) {
2008 p_err("failed parsing '%s' BTF file: %s", targ_btf_path
, strerror(errno
));
2015 btfgen_free_info(info
);
2020 #define MARKED UINT32_MAX
2022 static void btfgen_mark_member(struct btfgen_info
*info
, int type_id
, int idx
)
2024 const struct btf_type
*t
= btf__type_by_id(info
->marked_btf
, type_id
);
2025 struct btf_member
*m
= btf_members(t
) + idx
;
2027 m
->name_off
= MARKED
;
2031 btfgen_mark_type(struct btfgen_info
*info
, unsigned int type_id
, bool follow_pointers
)
2033 const struct btf_type
*btf_type
= btf__type_by_id(info
->src_btf
, type_id
);
2034 struct btf_type
*cloned_type
;
2035 struct btf_param
*param
;
2036 struct btf_array
*array
;
2042 /* mark type on cloned BTF as used */
2043 cloned_type
= (struct btf_type
*) btf__type_by_id(info
->marked_btf
, type_id
);
2044 cloned_type
->name_off
= MARKED
;
2046 /* recursively mark other types needed by it */
2047 switch (btf_kind(btf_type
)) {
2050 case BTF_KIND_FLOAT
:
2052 case BTF_KIND_ENUM64
:
2053 case BTF_KIND_STRUCT
:
2054 case BTF_KIND_UNION
:
2057 if (follow_pointers
) {
2058 err
= btfgen_mark_type(info
, btf_type
->type
, follow_pointers
);
2063 case BTF_KIND_CONST
:
2064 case BTF_KIND_RESTRICT
:
2065 case BTF_KIND_VOLATILE
:
2066 case BTF_KIND_TYPEDEF
:
2067 err
= btfgen_mark_type(info
, btf_type
->type
, follow_pointers
);
2071 case BTF_KIND_ARRAY
:
2072 array
= btf_array(btf_type
);
2074 /* mark array type */
2075 err
= btfgen_mark_type(info
, array
->type
, follow_pointers
);
2076 /* mark array's index type */
2077 err
= err
? : btfgen_mark_type(info
, array
->index_type
, follow_pointers
);
2081 case BTF_KIND_FUNC_PROTO
:
2083 err
= btfgen_mark_type(info
, btf_type
->type
, follow_pointers
);
2087 /* mark parameters types */
2088 param
= btf_params(btf_type
);
2089 for (i
= 0; i
< btf_vlen(btf_type
); i
++) {
2090 err
= btfgen_mark_type(info
, param
->type
, follow_pointers
);
2096 /* tells if some other type needs to be handled */
2098 p_err("unsupported kind: %s (%d)", btf_kind_str(btf_type
), type_id
);
2105 static int btfgen_record_field_relo(struct btfgen_info
*info
, struct bpf_core_spec
*targ_spec
)
2107 struct btf
*btf
= info
->src_btf
;
2108 const struct btf_type
*btf_type
;
2109 struct btf_member
*btf_member
;
2110 struct btf_array
*array
;
2111 unsigned int type_id
= targ_spec
->root_type_id
;
2114 /* mark root type */
2115 btf_type
= btf__type_by_id(btf
, type_id
);
2116 err
= btfgen_mark_type(info
, type_id
, false);
2120 /* mark types for complex types (arrays, unions, structures) */
2121 for (int i
= 1; i
< targ_spec
->raw_len
; i
++) {
2122 /* skip typedefs and mods */
2123 while (btf_is_mod(btf_type
) || btf_is_typedef(btf_type
)) {
2124 type_id
= btf_type
->type
;
2125 btf_type
= btf__type_by_id(btf
, type_id
);
2128 switch (btf_kind(btf_type
)) {
2129 case BTF_KIND_STRUCT
:
2130 case BTF_KIND_UNION
:
2131 idx
= targ_spec
->raw_spec
[i
];
2132 btf_member
= btf_members(btf_type
) + idx
;
2135 btfgen_mark_member(info
, type_id
, idx
);
2137 /* mark member's type */
2138 type_id
= btf_member
->type
;
2139 btf_type
= btf__type_by_id(btf
, type_id
);
2140 err
= btfgen_mark_type(info
, type_id
, false);
2144 case BTF_KIND_ARRAY
:
2145 array
= btf_array(btf_type
);
2146 type_id
= array
->type
;
2147 btf_type
= btf__type_by_id(btf
, type_id
);
2150 p_err("unsupported kind: %s (%d)",
2151 btf_kind_str(btf_type
), btf_type
->type
);
2159 /* Mark types, members, and member types. Compared to btfgen_record_field_relo,
2160 * this function does not rely on the target spec for inferring members, but
2161 * uses the associated BTF.
2163 * The `behind_ptr` argument is used to stop marking of composite types reached
2164 * through a pointer. This way, we can keep BTF size in check while providing
2165 * reasonable match semantics.
2167 static int btfgen_mark_type_match(struct btfgen_info
*info
, __u32 type_id
, bool behind_ptr
)
2169 const struct btf_type
*btf_type
;
2170 struct btf
*btf
= info
->src_btf
;
2171 struct btf_type
*cloned_type
;
2177 btf_type
= btf__type_by_id(btf
, type_id
);
2178 /* mark type on cloned BTF as used */
2179 cloned_type
= (struct btf_type
*)btf__type_by_id(info
->marked_btf
, type_id
);
2180 cloned_type
->name_off
= MARKED
;
2182 switch (btf_kind(btf_type
)) {
2185 case BTF_KIND_FLOAT
:
2187 case BTF_KIND_ENUM64
:
2189 case BTF_KIND_STRUCT
:
2190 case BTF_KIND_UNION
: {
2191 struct btf_member
*m
= btf_members(btf_type
);
2192 __u16 vlen
= btf_vlen(btf_type
);
2197 for (i
= 0; i
< vlen
; i
++, m
++) {
2199 btfgen_mark_member(info
, type_id
, i
);
2201 /* mark member's type */
2202 err
= btfgen_mark_type_match(info
, m
->type
, false);
2208 case BTF_KIND_CONST
:
2210 case BTF_KIND_RESTRICT
:
2211 case BTF_KIND_TYPEDEF
:
2212 case BTF_KIND_VOLATILE
:
2213 return btfgen_mark_type_match(info
, btf_type
->type
, behind_ptr
);
2215 return btfgen_mark_type_match(info
, btf_type
->type
, true);
2216 case BTF_KIND_ARRAY
: {
2217 struct btf_array
*array
;
2219 array
= btf_array(btf_type
);
2220 /* mark array type */
2221 err
= btfgen_mark_type_match(info
, array
->type
, false);
2222 /* mark array's index type */
2223 err
= err
? : btfgen_mark_type_match(info
, array
->index_type
, false);
2228 case BTF_KIND_FUNC_PROTO
: {
2229 __u16 vlen
= btf_vlen(btf_type
);
2230 struct btf_param
*param
;
2233 err
= btfgen_mark_type_match(info
, btf_type
->type
, false);
2237 /* mark parameters types */
2238 param
= btf_params(btf_type
);
2239 for (i
= 0; i
< vlen
; i
++) {
2240 err
= btfgen_mark_type_match(info
, param
->type
, false);
2247 /* tells if some other type needs to be handled */
2249 p_err("unsupported kind: %s (%d)", btf_kind_str(btf_type
), type_id
);
2256 /* Mark types, members, and member types. Compared to btfgen_record_field_relo,
2257 * this function does not rely on the target spec for inferring members, but
2258 * uses the associated BTF.
2260 static int btfgen_record_type_match_relo(struct btfgen_info
*info
, struct bpf_core_spec
*targ_spec
)
2262 return btfgen_mark_type_match(info
, targ_spec
->root_type_id
, false);
2265 static int btfgen_record_type_relo(struct btfgen_info
*info
, struct bpf_core_spec
*targ_spec
)
2267 return btfgen_mark_type(info
, targ_spec
->root_type_id
, true);
2270 static int btfgen_record_enumval_relo(struct btfgen_info
*info
, struct bpf_core_spec
*targ_spec
)
2272 return btfgen_mark_type(info
, targ_spec
->root_type_id
, false);
2275 static int btfgen_record_reloc(struct btfgen_info
*info
, struct bpf_core_spec
*res
)
2277 switch (res
->relo_kind
) {
2278 case BPF_CORE_FIELD_BYTE_OFFSET
:
2279 case BPF_CORE_FIELD_BYTE_SIZE
:
2280 case BPF_CORE_FIELD_EXISTS
:
2281 case BPF_CORE_FIELD_SIGNED
:
2282 case BPF_CORE_FIELD_LSHIFT_U64
:
2283 case BPF_CORE_FIELD_RSHIFT_U64
:
2284 return btfgen_record_field_relo(info
, res
);
2285 case BPF_CORE_TYPE_ID_LOCAL
: /* BPF_CORE_TYPE_ID_LOCAL doesn't require kernel BTF */
2287 case BPF_CORE_TYPE_ID_TARGET
:
2288 case BPF_CORE_TYPE_EXISTS
:
2289 case BPF_CORE_TYPE_SIZE
:
2290 return btfgen_record_type_relo(info
, res
);
2291 case BPF_CORE_TYPE_MATCHES
:
2292 return btfgen_record_type_match_relo(info
, res
);
2293 case BPF_CORE_ENUMVAL_EXISTS
:
2294 case BPF_CORE_ENUMVAL_VALUE
:
2295 return btfgen_record_enumval_relo(info
, res
);
2301 static struct bpf_core_cand_list
*
2302 btfgen_find_cands(const struct btf
*local_btf
, const struct btf
*targ_btf
, __u32 local_id
)
2304 const struct btf_type
*local_type
;
2305 struct bpf_core_cand_list
*cands
= NULL
;
2306 struct bpf_core_cand local_cand
= {};
2307 size_t local_essent_len
;
2308 const char *local_name
;
2311 local_cand
.btf
= local_btf
;
2312 local_cand
.id
= local_id
;
2314 local_type
= btf__type_by_id(local_btf
, local_id
);
2320 local_name
= btf__name_by_offset(local_btf
, local_type
->name_off
);
2325 local_essent_len
= bpf_core_essential_name_len(local_name
);
2327 cands
= calloc(1, sizeof(*cands
));
2331 err
= bpf_core_add_cands(&local_cand
, local_essent_len
, targ_btf
, "vmlinux", 1, cands
);
2338 bpf_core_free_cands(cands
);
2343 /* Record relocation information for a single BPF object */
2344 static int btfgen_record_obj(struct btfgen_info
*info
, const char *obj_path
)
2346 const struct btf_ext_info_sec
*sec
;
2347 const struct bpf_core_relo
*relo
;
2348 const struct btf_ext_info
*seg
;
2349 struct hashmap_entry
*entry
;
2350 struct hashmap
*cand_cache
= NULL
;
2351 struct btf_ext
*btf_ext
= NULL
;
2352 unsigned int relo_idx
;
2353 struct btf
*btf
= NULL
;
2357 btf
= btf__parse(obj_path
, &btf_ext
);
2360 p_err("failed to parse BPF object '%s': %s", obj_path
, strerror(errno
));
2365 p_err("failed to parse BPF object '%s': section %s not found",
2366 obj_path
, BTF_EXT_ELF_SEC
);
2371 if (btf_ext
->core_relo_info
.len
== 0) {
2376 cand_cache
= hashmap__new(btfgen_hash_fn
, btfgen_equal_fn
, NULL
);
2377 if (IS_ERR(cand_cache
)) {
2378 err
= PTR_ERR(cand_cache
);
2382 seg
= &btf_ext
->core_relo_info
;
2383 for_each_btf_ext_sec(seg
, sec
) {
2384 for_each_btf_ext_rec(seg
, sec
, relo_idx
, relo
) {
2385 struct bpf_core_spec specs_scratch
[3] = {};
2386 struct bpf_core_relo_res targ_res
= {};
2387 struct bpf_core_cand_list
*cands
= NULL
;
2388 const char *sec_name
= btf__name_by_offset(btf
, sec
->sec_name_off
);
2390 if (relo
->kind
!= BPF_CORE_TYPE_ID_LOCAL
&&
2391 !hashmap__find(cand_cache
, relo
->type_id
, &cands
)) {
2392 cands
= btfgen_find_cands(btf
, info
->src_btf
, relo
->type_id
);
2398 err
= hashmap__set(cand_cache
, relo
->type_id
, cands
,
2404 err
= bpf_core_calc_relo_insn(sec_name
, relo
, relo_idx
, btf
, cands
,
2405 specs_scratch
, &targ_res
);
2409 /* specs_scratch[2] is the target spec */
2410 err
= btfgen_record_reloc(info
, &specs_scratch
[2]);
2418 btf_ext__free(btf_ext
);
2420 if (!IS_ERR_OR_NULL(cand_cache
)) {
2421 hashmap__for_each_entry(cand_cache
, entry
, i
) {
2422 bpf_core_free_cands(entry
->pvalue
);
2424 hashmap__free(cand_cache
);
2430 /* Generate BTF from relocation information previously recorded */
2431 static struct btf
*btfgen_get_btf(struct btfgen_info
*info
)
2433 struct btf
*btf_new
= NULL
;
2434 unsigned int *ids
= NULL
;
2435 unsigned int i
, n
= btf__type_cnt(info
->marked_btf
);
2438 btf_new
= btf__new_empty();
2444 ids
= calloc(n
, sizeof(*ids
));
2450 /* first pass: add all marked types to btf_new and add their new ids to the ids map */
2451 for (i
= 1; i
< n
; i
++) {
2452 const struct btf_type
*cloned_type
, *type
;
2456 cloned_type
= btf__type_by_id(info
->marked_btf
, i
);
2458 if (cloned_type
->name_off
!= MARKED
)
2461 type
= btf__type_by_id(info
->src_btf
, i
);
2463 /* add members for struct and union */
2464 if (btf_is_composite(type
)) {
2465 struct btf_member
*cloned_m
, *m
;
2466 unsigned short vlen
;
2469 name
= btf__str_by_offset(info
->src_btf
, type
->name_off
);
2471 if (btf_is_struct(type
))
2472 err
= btf__add_struct(btf_new
, name
, type
->size
);
2474 err
= btf__add_union(btf_new
, name
, type
->size
);
2480 cloned_m
= btf_members(cloned_type
);
2481 m
= btf_members(type
);
2482 vlen
= btf_vlen(cloned_type
);
2483 for (idx_src
= 0; idx_src
< vlen
; idx_src
++, cloned_m
++, m
++) {
2484 /* add only members that are marked as used */
2485 if (cloned_m
->name_off
!= MARKED
)
2488 name
= btf__str_by_offset(info
->src_btf
, m
->name_off
);
2489 err
= btf__add_field(btf_new
, name
, m
->type
,
2490 btf_member_bit_offset(cloned_type
, idx_src
),
2491 btf_member_bitfield_size(cloned_type
, idx_src
));
2496 err
= btf__add_type(btf_new
, info
->src_btf
, type
);
2502 /* add ID mapping */
2506 /* second pass: fix up type ids */
2507 for (i
= 1; i
< btf__type_cnt(btf_new
); i
++) {
2508 struct btf_type
*btf_type
= (struct btf_type
*) btf__type_by_id(btf_new
, i
);
2509 struct btf_field_iter it
;
2512 err
= btf_field_iter_init(&it
, btf_type
, BTF_FIELD_ITER_IDS
);
2516 while ((type_id
= btf_field_iter_next(&it
)))
2517 *type_id
= ids
[*type_id
];
2530 /* Create minimized BTF file for a set of BPF objects.
2532 * The BTFGen algorithm is divided in two main parts: (1) collect the
2533 * BTF types that are involved in relocations and (2) generate the BTF
2534 * object using the collected types.
2536 * In order to collect the types involved in the relocations, we parse
2537 * the BTF and BTF.ext sections of the BPF objects and use
2538 * bpf_core_calc_relo_insn() to get the target specification, this
2539 * indicates how the types and fields are used in a relocation.
2541 * Types are recorded in different ways according to the kind of the
2542 * relocation. For field-based relocations only the members that are
2543 * actually used are saved in order to reduce the size of the generated
2544 * BTF file. For type-based relocations empty struct / unions are
2545 * generated and for enum-based relocations the whole type is saved.
2547 * The second part of the algorithm generates the BTF object. It creates
2548 * an empty BTF object and fills it with the types recorded in the
2549 * previous step. This function takes care of only adding the structure
2550 * and union members that were marked as used and it also fixes up the
2551 * type IDs on the generated BTF object.
2553 static int minimize_btf(const char *src_btf
, const char *dst_btf
, const char *objspaths
[])
2555 struct btfgen_info
*info
;
2556 struct btf
*btf_new
= NULL
;
2559 info
= btfgen_new_info(src_btf
);
2562 p_err("failed to allocate info structure: %s", strerror(errno
));
2566 for (i
= 0; objspaths
[i
] != NULL
; i
++) {
2567 err
= btfgen_record_obj(info
, objspaths
[i
]);
2569 p_err("error recording relocations for %s: %s", objspaths
[i
],
2575 btf_new
= btfgen_get_btf(info
);
2578 p_err("error generating BTF: %s", strerror(errno
));
2582 err
= btf_save_raw(btf_new
, dst_btf
);
2584 p_err("error saving btf file: %s", strerror(errno
));
2590 btfgen_free_info(info
);
2595 static int do_min_core_btf(int argc
, char **argv
)
2597 const char *input
, *output
, **objs
;
2608 objs
= (const char **) calloc(argc
+ 1, sizeof(*objs
));
2610 p_err("failed to allocate array for object names");
2616 objs
[i
++] = GET_ARG();
2618 err
= minimize_btf(input
, output
, objs
);
2623 static const struct cmd cmds
[] = {
2624 { "object", do_object
},
2625 { "skeleton", do_skeleton
},
2626 { "subskeleton", do_subskeleton
},
2627 { "min_core_btf", do_min_core_btf
},
2628 { "help", do_help
},
2632 int do_gen(int argc
, char **argv
)
2634 return cmd_select(cmds
, argc
, argv
, do_help
);