[PATCH 1/2] pahole: avoid segfault when parsing bogus file

kkourt
2022-03-16T13:23:56Z

From: Kornilios Kourtis <kornilios@isovalent.com>

When trying to use btf encoding for an apparently problematic kernel
file, pahole segfaults. As can be seen below [1], the problem is that we
are trying to dereference a NULL decoder.

Fix this by checking the return value of dwfl_getmodules which [2] whill
return -1 on errors or an offset if one of the modules did not return
DWARF_CB_OK. (In this specific case, it was __cus__load_debug_types that
returned DWARF_CB_ABORT.)

[1]:
$ gdb -q --args ./pahole -J vmlinux-5.3.18-24.102-default.debug
Reading symbols from ./pahole...
(gdb) r
Starting program: /tmp/pahole/build/pahole -J vmlinux-5.3.18-24.102-default.debug
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff7f4000e in gobuffer__size (gb=0x18) at /tmp/pahole/gobuffer.h:39
39 return gb->index;
(gdb) bt
(gdb) frame 1
1042 if (gobuffer__size(&encoder->percpu_secinfo) != 0)
(gdb) list
1037
1038 int btf_encoder__encode(struct btf_encoder *encoder)
1039 {
1040 int err;
1041
1042 if (gobuffer__size(&encoder->percpu_secinfo) != 0)
1043 btf_encoder__add_datasec(encoder, PERCPU_SECTION);
1044
1045 /* Empty file, nothing to do, so... done! */
1046 if (btf__get_nr_types(encoder->btf) == 0)
(gdb) print encoder
$1 = (struct btf_encoder *) 0x0

[2] https://sourceware.org/git/?p=elfutils.git;a=blob;f=libdwfl/libdwfl.h;h=f98f1d525d94bc7bcfc7c816890de5907ee4bd6d;hb=HEAD#l200

Signed-off-by: Kornilios Kourtis <kornilios@isovalent.com>
---
dwarf_loader.c | 5 ++++-
1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/dwarf_loader.c b/dwarf_loader.c
index 151bc83..c87378b 100644
--- a/dwarf_loader.c
+++ b/dwarf_loader.c
@@ -3268,7 +3268,10 @@ static int cus__process_file(struct cus *cus, struct conf_load *conf, int fd,
};

/* Process the one or more modules gleaned from this file. */
- dwfl_getmodules(dwfl, cus__process_dwflmod, &parms, 0);
+ int err = dwfl_getmodules(dwfl, cus__process_dwflmod, &parms, 0);
+ if (err) {
+ return -1;
+ }

// We can't call dwfl_end(dwfl) here, as we keep pointers to strings
// allocated by libdw that will be freed at dwfl_end(), so leave this for
--
2.25.1