Return the correct number of program headers when e_phnum is 0xffff (#326)
authorpagabuc <pagabuc@users.noreply.github.com>
Mon, 20 Jul 2020 21:21:49 +0000 (14:21 -0700)
committerGitHub <noreply@github.com>
Mon, 20 Jul 2020 21:21:49 +0000 (14:21 -0700)
* Return the correct number of program headers when e_phnum is 0xffff

* Added link and relevant text of the specification

elftools/elf/elffile.py
scripts/readelf.py

index b7868f2e379f873f6ab9a23a35ab8e962c3c1c4f..3c8ed519a9868292667043e46652c4fcb63756e5 100644 (file)
@@ -120,7 +120,17 @@ class ELFFile(object):
     def num_segments(self):
         """ Number of segments in the file
         """
-        return self['e_phnum']
+        # From: https://github.com/hjl-tools/x86-psABI/wiki/X86-psABI
+        # Section: 4.1.2 Number of Program Headers
+        # If the number of program headers is greater than or equal to
+        # PN_XNUM (0xffff), this member has the value PN_XNUM
+        # (0xffff). The actual number of program header table entries
+        # is contained in the sh_info field of the section header at
+        # index 0.
+        if self['e_phnum'] < 0xffff:
+            return self['e_phnum']
+        else:
+            return self.get_section(0)['sh_info']
 
     def get_segment(self, n):
         """ Get the segment at index #n from the file (Segment object)
index 9971b3b4c4005c5cd0a8cc9618cf96c250ef5844..366c50e832656c58ff1048fa2ddc9d1589ec9c4a 100755 (executable)
@@ -218,7 +218,7 @@ class ReadElf(object):
             # readelf weirness - why isn't e_phoff printed as hex? (for section
             # headers, it is...)
             self._emitline('There are %s program headers, starting at offset %s' % (
-                elfheader['e_phnum'], elfheader['e_phoff']))
+                self.elffile.num_segments(), elfheader['e_phoff']))
             self._emitline()
 
         self._emitline('Program Headers:')