[PATCH 1/2] LoongArch: Avoid heap-buffer-overflow in loongarch_elf_relocate_section

Xi Ruoyao xry111@xry111.site
Wed Sep 14 10:15:57 GMT 2022


On Wed, 2022-09-14 at 16:57 +0800, liuzhensong wrote:
> 在 2022/9/13 下午11:44, Xi Ruoyao 写道:
>  
> > If a and b are different sections, we cannot access something in b
> > with
> > "a->contents + (offset from a)" because "a->contents" and "b-
> > >contents"
> > are heap buffers allocated separately, not slices of a large buffer.
> > 
> > The issue was found during an attempt to add static-pie support to
> > the
> > toolchain with ASAN.
> Can you provide compile parameters?

To reproduce it easily, add a check to detect the heap buffer overflow:

diff --git a/bfd/elfnn-loongarch.c b/bfd/elfnn-loongarch.c
index a9bb66a1e04..716e3d5a246 100644
--- a/bfd/elfnn-loongarch.c
+++ b/bfd/elfnn-loongarch.c
@@ -3202,6 +3202,7 @@ loongarch_elf_relocate_section (bfd *output_bfd, struct bfd_link_info *info,
                    }
                }
 
+             BFD_ASSERT (got_off < got->size);
              bfd_put_NN (output_bfd, relocation, got->contents + got_off);
 
              relocation = got_off + sec_addr (got);

Then

$ cat test.S
.text
.align 2

.local ifunc
.type ifunc, @gnu_indirect_function
.set ifunc, resolver

resolver:
  la.local $a0, impl
  jr $ra

impl:
  li.w $a0, 42
  jr $ra

.global test
.type test, @function
test:
  move $s0, $ra
  la.got $t0, ifunc
  jirl $ra, $t0, 0
  xori $a0, $a0, 42
  jr $s0
$ cc test.S -c
$ ld/ld-new test.o -shared
ld/ld-new: BFD (GNU Binutils) 2.39.50.20220914 assertion fail elfnn-loongarch.c:3205

And if GDB is used with a breakpoint at bfd_assert, we can see got_off
is "18446744073709551608" (-8).

> Shouldn't write to got table when using hidden ifunc.

Perhaps it's true, using RELA to resolve a GOT entry should not depend
on any "initial" value of the entry...
-- 
Xi Ruoyao <xry111@xry111.site>
School of Aerospace Science and Technology, Xidian University


More information about the Binutils mailing list