This is the mail archive of the mailing list for the binutils project.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

ELF header clobbered when writing a file with no sections

If the linker writes out a file that contains no BFD-visible sections, the section headers are written out on top of the ELF header. I'm not exactly sure how this came up, and it isn't easy to reproduce, but the fix is trivial and seems like the right thing to do.

The assign_file_positions_for_segments function in elf.c places the first section immediately after the ELF header. It then sets the next_file_pos field to the offset just past the last section. However, if there are no sections that are visible to BFD (i.e., not counting the ELF symtab, string table, etc.), the next_file_pos is left set to 0. Subsequent contents of the output file may then overwrite the ELF header. The patch fixes this by setting next_file_pos just past the ELF header when there are no BFD-visible sections. I also ran the testsuites with an xtensa-elf target and verified that the patch causes no regressions there.

OK to commit?

If you want to reproduce this, I've included some files to demonstrate the problem. I used the xtensa-elf target, but other ELF targets may also work. The complication is that I can't find a way to generate an object file with no sections using mainline binutils. Instead, I assembled the sample.s file and then used an old version (2.11.2) of objcopy to remove the empty .text, .data, and .bss sections. I've included the resulting Xtensa ELF file, no-sections.o. If you then run the linker with "-T linker_script -o foo no-sections.o" and look at the ELF header of the "foo" output file, you will see that it is corrupted.

2004-11-03 Bob Wilson <>

        * elf.c (assign_file_positions_for_segments): Set next_file_pos even
        if there are no segments.

Index: elf.c
RCS file: /cvs/src/src/bfd/elf.c,v
retrieving revision 1.251
diff -u -p -r1.251 elf.c
--- elf.c	14 Oct 2004 23:38:08 -0000	1.251
+++ elf.c	3 Nov 2004 23:03:27 -0000
@@ -3871,7 +3871,10 @@ assign_file_positions_for_segments (bfd 
   elf_elfheader (abfd)->e_phnum = count;
   if (count == 0)
-    return TRUE;
+    {
+      elf_tdata (abfd)->next_file_pos = bed->s->sizeof_ehdr;
+      return TRUE;
+    }
   /* If we already counted the number of program segments, make sure
      that we allocated enough space.  This happens when SIZEOF_HEADERS

Attachment: elf-header-bug.tar.gz
Description: application/gzip

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]