Skip to content

Commit 5c3320d

Browse files
anakryikoborkmann
authored andcommitted
libbpf: Fix memory leak and optimize BTF sanitization
Coverity's static analysis helpfully reported a memory leak introduced by 0f0e55d ("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: 0f0e55d ("libbpf: Improve BTF sanitization handling") Signed-off-by: Andrii Nakryiko <andriin@fb.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net> Link: https://lore.kernel.org/bpf/20200710011023.1655008-1-andriin@fb.com
1 parent 2977282 commit 5c3320d

3 files changed

Lines changed: 5 additions & 10 deletions

File tree

‎tools/lib/bpf/btf.c‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ void btf__free(struct btf *btf)
397397
free(btf);
398398
}
399399

400-
struct btf *btf__new(__u8 *data, __u32 size)
400+
struct btf *btf__new(const void *data, __u32 size)
401401
{
402402
struct btf *btf;
403403
int err;

‎tools/lib/bpf/btf.h‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ struct btf_ext_header {
6363
};
6464

6565
LIBBPF_API void btf__free(struct btf *btf);
66-
LIBBPF_API struct btf *btf__new(__u8 *data, __u32 size);
66+
LIBBPF_API struct btf *btf__new(const void *data, __u32 size);
6767
LIBBPF_API struct btf *btf__parse_elf(const char *path,
6868
struct btf_ext **btf_ext);
6969
LIBBPF_API int btf__finalize_data(struct bpf_object *obj, struct btf *btf);

‎tools/lib/bpf/libbpf.c‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2533,17 +2533,12 @@ static int bpf_object__sanitize_and_load_btf(struct bpf_object *obj)
25332533

25342534
sanitize = btf_needs_sanitization(obj);
25352535
if (sanitize) {
2536-
const void *orig_data;
2537-
void *san_data;
2536+
const void *raw_data;
25382537
__u32 sz;
25392538

25402539
/* clone BTF to sanitize a copy and leave the original intact */
2541-
orig_data = btf__get_raw_data(obj->btf, &sz);
2542-
san_data = malloc(sz);
2543-
if (!san_data)
2544-
return -ENOMEM;
2545-
memcpy(san_data, orig_data, sz);
2546-
kern_btf = btf__new(san_data, sz);
2540+
raw_data = btf__get_raw_data(obj->btf, &sz);
2541+
kern_btf = btf__new(raw_data, sz);
25472542
if (IS_ERR(kern_btf))
25482543
return PTR_ERR(kern_btf);
25492544

0 commit comments

Comments
 (0)