debugedit: fix segment fault while file's bss offset have a large number While ELF_C_RDWR_MMAP was used, elf_begin invoked mmap() to map file into memory. While the file's bss Offset has a large number, elf_update caculated file size by __elf64_updatenull_wrlock and the size was enlarged. In this situation, elf_update invoked ftruncate to enlarge the file, and memory size (elf->maximum_size) also was incorrectly updated. There was segment fault in elf_end which invoked munmap with the length is the enlarged file size, not the mmap's length. Before the above operations, invoke elf_begin/elf_update/elf_end with ELF_C_RDWR and ELF_F_LAYOUT set to enlarge the above file, it could make sure the file is safe for the following elf operations. Upstream-Status: Submitted [RPM5 maintainer] Signed-off-by: Hongxu Jia --- tools/debugedit.c | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) Index: rpm-5.4.14/tools/debugedit.c =================================================================== --- rpm-5.4.14.orig/tools/debugedit.c +++ rpm-5.4.14/tools/debugedit.c @@ -1525,6 +1525,28 @@ handle_build_id (DSO *dso, Elf_Data *bui } } +/* It avoided the segment fault while file's bss offset have a large number. + See https://bugzilla.redhat.com/show_bug.cgi?id=1019707 + https://bugzilla.redhat.com/show_bug.cgi?id=1020842 for detail. */ +void valid_file(int fd) +{ + Elf *elf = elf_begin (fd, ELF_C_RDWR, NULL); + if (elf == NULL) + { + error (1, 0, "elf_begin: %s", elf_errmsg (-1)); + return; + } + + elf_flagelf (elf, ELF_C_SET, ELF_F_LAYOUT); + + if (elf_update (elf, ELF_C_WRITE) < 0) + error (1, 0, "elf_update: %s", elf_errmsg (-1)); + + elf_end (elf); + + return; +} + int main (int argc, char *argv[]) { @@ -1621,6 +1643,9 @@ main (int argc, char *argv[]) exit (1); } + /* Make sure the file is valid. */ + valid_file(fd); + dso = fdopen_dso (fd, file); if (dso == NULL) exit (1);