Skip to content

Commit a871b04

Browse files
anakryikoAlexei Starovoitov
authored and
Alexei Starovoitov
committed
libbpf: Add btf__new_empty() to create an empty BTF object
Add an ability to create an empty BTF object from scratch. This is going to be used by pahole for BTF encoding. And also by selftest for convenient creation of BTF objects. Signed-off-by: Andrii Nakryiko <[email protected]> Signed-off-by: Alexei Starovoitov <[email protected]> Acked-by: John Fastabend <[email protected]> Link: https://lore.kernel.org/bpf/[email protected]
1 parent 919d2b1 commit a871b04

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

tools/lib/bpf/btf.c

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,36 @@ void btf__free(struct btf *btf)
565565
free(btf);
566566
}
567567

568+
struct btf *btf__new_empty(void)
569+
{
570+
struct btf *btf;
571+
572+
btf = calloc(1, sizeof(*btf));
573+
if (!btf)
574+
return ERR_PTR(-ENOMEM);
575+
btf->fd = -1;
576+
btf->ptr_sz = sizeof(void *);
577+
578+
/* +1 for empty string at offset 0 */
579+
btf->raw_size = sizeof(struct btf_header) + 1;
580+
btf->raw_data = calloc(1, btf->raw_size);
581+
if (!btf->raw_data) {
582+
free(btf);
583+
return ERR_PTR(-ENOMEM);
584+
}
585+
586+
btf->hdr = btf->raw_data;
587+
btf->hdr->hdr_len = sizeof(struct btf_header);
588+
btf->hdr->magic = BTF_MAGIC;
589+
btf->hdr->version = BTF_VERSION;
590+
591+
btf->types_data = btf->raw_data + btf->hdr->hdr_len;
592+
btf->strs_data = btf->raw_data + btf->hdr->hdr_len;
593+
btf->hdr->str_len = 1; /* empty string at offset 0 */
594+
595+
return btf;
596+
}
597+
568598
struct btf *btf__new(const void *data, __u32 size)
569599
{
570600
struct btf *btf;

tools/lib/bpf/btf.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ struct bpf_object;
2727

2828
LIBBPF_API void btf__free(struct btf *btf);
2929
LIBBPF_API struct btf *btf__new(const void *data, __u32 size);
30+
LIBBPF_API struct btf *btf__new_empty(void);
3031
LIBBPF_API struct btf *btf__parse(const char *path, struct btf_ext **btf_ext);
3132
LIBBPF_API struct btf *btf__parse_elf(const char *path, struct btf_ext **btf_ext);
3233
LIBBPF_API struct btf *btf__parse_raw(const char *path);

tools/lib/bpf/libbpf.map

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,7 @@ LIBBPF_0.2.0 {
307307
bpf_program__section_name;
308308
btf__add_str;
309309
btf__find_str;
310+
btf__new_empty;
310311
perf_buffer__buffer_cnt;
311312
perf_buffer__buffer_fd;
312313
perf_buffer__epoll_fd;

0 commit comments

Comments
 (0)