Commit 5c3320d7 authored by Andrii Nakryiko's avatar Andrii Nakryiko Committed by Daniel Borkmann

libbpf: Fix memory leak and optimize BTF sanitization

Coverity's static analysis helpfully reported a memory leak introduced by
0f0e55d8 ("libbpf: Improve BTF sanitization handling"). While fixing it,
I realized that btf__new() already creates a memory copy, so there is no need
to do this. So this patch also fixes misleading btf__new() signature to make
data into a `const void *` input parameter. And it avoids unnecessary memory
allocation and copy in BTF sanitization code altogether.

Fixes: 0f0e55d8 ("libbpf: Improve BTF sanitization handling")
Signed-off-by: default avatarAndrii Nakryiko <andriin@fb.com>
Signed-off-by: default avatarDaniel Borkmann <daniel@iogearbox.net>
Link: https://lore.kernel.org/bpf/20200710011023.1655008-1-andriin@fb.com
parent 2977282b
...@@ -397,7 +397,7 @@ void btf__free(struct btf *btf) ...@@ -397,7 +397,7 @@ void btf__free(struct btf *btf)
free(btf); free(btf);
} }
struct btf *btf__new(__u8 *data, __u32 size) struct btf *btf__new(const void *data, __u32 size)
{ {
struct btf *btf; struct btf *btf;
int err; int err;
......
...@@ -63,7 +63,7 @@ struct btf_ext_header { ...@@ -63,7 +63,7 @@ struct btf_ext_header {
}; };
LIBBPF_API void btf__free(struct btf *btf); LIBBPF_API void btf__free(struct btf *btf);
LIBBPF_API struct btf *btf__new(__u8 *data, __u32 size); LIBBPF_API struct btf *btf__new(const void *data, __u32 size);
LIBBPF_API struct btf *btf__parse_elf(const char *path, LIBBPF_API struct btf *btf__parse_elf(const char *path,
struct btf_ext **btf_ext); struct btf_ext **btf_ext);
LIBBPF_API int btf__finalize_data(struct bpf_object *obj, struct btf *btf); LIBBPF_API int btf__finalize_data(struct bpf_object *obj, struct btf *btf);
......
...@@ -2533,17 +2533,12 @@ static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj) ...@@ -2533,17 +2533,12 @@ static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
sanitize = btf_needs_sanitization(obj); sanitize = btf_needs_sanitization(obj);
if (sanitize) { if (sanitize) {
const void *orig_data; const void *raw_data;
void *san_data;
__u32 sz; __u32 sz;
/* clone BTF to sanitize a copy and leave the original intact */ /* clone BTF to sanitize a copy and leave the original intact */
orig_data = btf__get_raw_data(obj->btf, &sz); raw_data = btf__get_raw_data(obj->btf, &sz);
san_data = malloc(sz); kern_btf = btf__new(raw_data, sz);
if (!san_data)
return -ENOMEM;
memcpy(san_data, orig_data, sz);
kern_btf = btf__new(san_data, sz);
if (IS_ERR(kern_btf)) if (IS_ERR(kern_btf))
return PTR_ERR(kern_btf); return PTR_ERR(kern_btf);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment