An ELF file without any section headers (not read with ELF_C_RDWR)
won't have any sections (not even section zero) allocated. And the
initial ScnList will have cnt == 0 and max == 0 to indicate a new
ScnList has to be created. The elf_newscn code assumed that if adding
a new ScnList the new section index was the index of the (max - 1)
section of the previous block plus one. Fix this by checking whether
the previous block had max == 0 and start the next section index at
zero in that case.

        * libelf/elf_newscn.c (elf_newscn): Check whether the max
        index of the previous ScnList is zero.

Signed-off-by: Mark Wielaard <[email protected]>
---
 libelf/elf_newscn.c | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/libelf/elf_newscn.c b/libelf/elf_newscn.c
index fbb897153ea3..dc1fca70be17 100644
--- a/libelf/elf_newscn.c
+++ b/libelf/elf_newscn.c
@@ -128,8 +128,18 @@ elf_newscn (Elf *elf)
       newp->max = elf->state.elf.scnincr;
 
       /* Remember the index for the first section in this block.  */
-      newp->data[0].index
-       = 1 + elf->state.elf.scns_last->data[elf->state.elf.scns_last->max - 
1].index;
+      size_t last_max = elf->state.elf.scns_last->max;
+      if (last_max == 0)
+       {
+         /* The last block was empty, so this is the first section
+            (section zero).  */
+         newp->data[0].index = 0;
+       }
+      else
+       {
+         size_t index = elf->state.elf.scns_last->data[last_max - 1].index;
+         newp->data[0].index = index + 1;
+       }
 
       /* Enqueue the new list element.  */
       elf->state.elf.scns_last = elf->state.elf.scns_last->next = newp;
-- 
2.56.1

Reply via email to