1 // SPDX-License-Identifier: GPL-2.0
3 #include <linux/kernel.h>
4 #include <linux/slab.h>
9 * Find a function proto type by name, and return the btf_type with its btf
10 * in *@btf_p. Return NULL if not found.
11 * Note that caller has to call btf_put(*@btf_p) after using the btf_type.
13 const struct btf_type *btf_find_func_proto(const char *func_name, struct btf **btf_p)
15 const struct btf_type *t;
18 id = bpf_find_btf_id(func_name, BTF_KIND_FUNC, btf_p);
22 /* Get BTF_KIND_FUNC type */
23 t = btf_type_by_id(*btf_p, id);
24 if (!t || !btf_type_is_func(t))
27 /* The type of BTF_KIND_FUNC is BTF_KIND_FUNC_PROTO */
28 t = btf_type_by_id(*btf_p, t->type);
29 if (!t || !btf_type_is_func_proto(t))
39 * Get function parameter with the number of parameters.
40 * This can return NULL if the function has no parameters.
41 * It can return -EINVAL if the @func_proto is not a function proto type.
43 const struct btf_param *btf_get_func_param(const struct btf_type *func_proto, s32 *nr)
45 if (!btf_type_is_func_proto(func_proto))
46 return ERR_PTR(-EINVAL);
48 *nr = btf_type_vlen(func_proto);
50 return (const struct btf_param *)(func_proto + 1);
55 #define BTF_ANON_STACK_MAX 16
57 struct btf_anon_stack {
63 * Find a member of data structure/union by name and return it.
64 * Return NULL if not found, or -EINVAL if parameter is invalid.
65 * If the member is an member of anonymous union/structure, the offset
66 * of that anonymous union/structure is stored into @anon_offset. Caller
67 * can calculate the correct offset from the root data structure by
68 * adding anon_offset to the member's offset.
70 const struct btf_member *btf_find_struct_member(struct btf *btf,
71 const struct btf_type *type,
72 const char *member_name,
75 struct btf_anon_stack *anon_stack;
76 const struct btf_member *member;
77 u32 tid, cur_offset = 0;
81 anon_stack = kcalloc(BTF_ANON_STACK_MAX, sizeof(*anon_stack), GFP_KERNEL);
83 return ERR_PTR(-ENOMEM);
86 if (!btf_type_is_struct(type)) {
87 member = ERR_PTR(-EINVAL);
91 for_each_member(i, type, member) {
92 if (!member->name_off) {
93 /* Anonymous union/struct: push it for later use */
94 if (btf_type_skip_modifiers(btf, member->type, &tid) &&
95 top < BTF_ANON_STACK_MAX) {
96 anon_stack[top].tid = tid;
97 anon_stack[top++].offset =
98 cur_offset + member->offset;
101 name = btf_name_by_offset(btf, member->name_off);
102 if (name && !strcmp(member_name, name)) {
104 *anon_offset = cur_offset;
110 /* Pop from the anonymous stack and retry */
111 tid = anon_stack[--top].tid;
112 cur_offset = anon_stack[top].offset;
113 type = btf_type_by_id(btf, tid);