Skip to content

Commit

Permalink
Correctly parse ELF for musllinux on Big Endian (pypa#538)
Browse files Browse the repository at this point in the history
  • Loading branch information
uranusjr authored and hrnciar committed Jun 24, 2022
1 parent 0524bb3 commit bf1c1ae
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
8 changes: 5 additions & 3 deletions packaging/_musllinux.py
Expand Up @@ -39,9 +39,11 @@ def _parse_ld_musl_from_elf(f: IO[bytes]) -> Optional[str]:
# p_fmt: Format for section header.
# p_idx: Indexes to find p_type, p_offset, and p_filesz.
e_fmt, p_fmt, p_idx = {
1: ("IIIIHHH", "IIIIIIII", (0, 1, 4)), # 32-bit.
2: ("QQQIHHH", "IIQQQQQQ", (0, 2, 5)), # 64-bit.
}[ident[4]]
(1, 1): ("<IIIIHHH", "<IIIIIIII", (0, 1, 4)), # 32-bit LSB.
(1, 2): (">IIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB.
(2, 1): ("<QQQIHHH", "<IIQQQQQQ", (0, 2, 5)), # 64-bit LSB.
(2, 2): (">QQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB.
}[(ident[4], ident[5])]
except KeyError:
return None
else:
Expand Down
9 changes: 5 additions & 4 deletions tests/test_musllinux.py
Expand Up @@ -101,14 +101,15 @@ def test_parse_ld_musl_from_elf_no_interpreter_section():
with BIN_MUSL_X86_64.open("rb") as f:
data = f.read()

# Change all sections to *not* PT_INTERP.
unpacked = struct.unpack("16BHHIQQQIHHH", data[:58])
# Change all sections to *not* PT_INTERP. We are explicitly using LSB rules
# because the binaries are in LSB.
unpacked = struct.unpack("<16BHHIQQQIHHH", data[:58])
*_, e_phoff, _, _, _, e_phentsize, e_phnum = unpacked
for i in range(e_phnum + 1):
sb = e_phoff + e_phentsize * i
se = sb + 56
section = struct.unpack("IIQQQQQQ", data[sb:se])
data = data[:sb] + struct.pack("IIQQQQQQ", 0, *section[1:]) + data[se:]
section = struct.unpack("<IIQQQQQQ", data[sb:se])
data = data[:sb] + struct.pack("<IIQQQQQQ", 0, *section[1:]) + data[se:]

assert _parse_ld_musl_from_elf(io.BytesIO(data)) is None

Expand Down

0 comments on commit bf1c1ae

Please sign in to comment.