[PATCH bpf-next v4 2/2] libbpf: linker: Avoid using object file as both input and output

From: Rong Tao
Date: Thu Dec 05 2024 - 21:02:07 EST


From: Rong Tao <rongtao@xxxxxxxx>

When the target file is used as input and output at the same time, the
input file will read a null value, resulting in a segmentation fault.

$ bpftool gen object prog.o prog.o
libbpf: failed to get ELF header for prog.o: invalid `Elf' handle
Segmentation fault

(gdb) bt
#0 0x0000000000450285 in linker_append_elf_syms (linker=0x4feda0, obj=0x7fffffffe100) at linker.c:1296
#1 bpf_linker__add_file (linker=0x4feda0, filename=<optimized out>, opts=<optimized out>) at linker.c:453
#2 0x000000000040c235 in do_object ()
#3 0x00000000004021d7 in main ()
(gdb) frame 0
#0 0x0000000000450285 in linker_append_elf_syms (linker=0x4feda0, obj=0x7fffffffe100) at linker.c:1296
1296 Elf64_Sym *sym = symtab->data->d_buf;

Signed-off-by: Rong Tao <rongtao@xxxxxxxx>
---
tools/lib/bpf/linker.c | 5 +++++
1 file changed, 5 insertions(+)

diff --git a/tools/lib/bpf/linker.c b/tools/lib/bpf/linker.c
index cf71d149fe26..0b117cc5b6e4 100644
--- a/tools/lib/bpf/linker.c
+++ b/tools/lib/bpf/linker.c
@@ -448,6 +448,11 @@ int bpf_linker__add_file(struct bpf_linker *linker, const char *filename,
if (!linker->elf)
return libbpf_err(-EINVAL);

+ if (!strcmp(filename, linker->filename)) {
+ pr_warn_elf("Input and output files cannot be the same");
+ return libbpf_err(-EINVAL);
+ }
+
err = err ?: linker_load_obj_file(linker, filename, opts, &obj);
err = err ?: linker_append_sec_data(linker, &obj);
err = err ?: linker_append_elf_syms(linker, &obj);
--
2.47.1