pyelftools“幻数不匹配”但ELF幻数是正确的

问题描述 投票:0回答:1

所以我有这个函数尝试返回 ELF 的长度。我的用途是从内存转储中提取 ELF。

from elftools.elf.elffile import ELFFile

def get_elf_size(start_loc, file_path):
    with open(file_path, 'rb') as f:
        f.seek(start_loc)
        magic_number = f.read(4)
        if magic_number != b'\x7fELF':
            raise ValueError(f"No ELF header found at offset {start_loc} in {file_path}")
        
        f.seek(start_loc)
        elf = ELFFile(f)
        max_offset = 0
        
        for segment in elf.iter_segments():
            segment_end = segment['p_offset'] + segment['p_filesz']
            if segment_end > max_offset:
                max_offset = segment_end

        return max_offset

但是,我不断收到此错误

...
File "/home/repos/math/venv/lib/python3.11/site-packages/elftools/elf/elffile.py", line 570, in _identify_file
    elf_assert(magic == b'\x7fELF', 'Magic number does not match')
  File "/home/repos/math/venv/lib/python3.11/site-packages/elftools/common/utils.py", line 80, in elf_assert
    _assert_with_exception(cond, msg, ELFError)
  File "/home/repos/math/venv/lib/python3.11/site-packages/elftools/common/utils.py", line 143, in _assert_with_exception
    raise exception_type(msg)
elftools.common.exceptions.ELFError: Magic number does not match

pyelftools
清楚地检查了幻数并说它与ELF幻数不匹配,但我的
ValueError
从未在函数中引发,当我打印用
magic_number = f.read(4)
读取的幻数时,它说神奇的数字是
'\x7fELF'
start_loc
是从
binwalk
生成的值,并且是准确的,因为我检查了幻数。只是
pyelftools
不喜欢。

所以我的问题是,为什么当我自己检查幻数时,它看起来并且我的

ValueError
没有出现,但是
pyelftools
抛出一个错误,表明幻数不正确?

python elf dump pyelftools
1个回答
0
投票

当您调用

f.seek(start_loc)
时,您正在将文件指针移动到 start_loc。然后你正确地读取了这个幻数,但在那之后,你再次寻求 start_loc ,这是不必要的,因为你已经处于那个位置了。

def get_elf_size(start_loc, file_path):
    with open(file_path, 'rb') as f:
        f.seek(start_loc)
        magic_number = f.read(4)
        if magic_number != b'\x7fELF':
            raise ValueError(f"No ELF header found at offset {start_loc} in {file_path}")

        # No need to seek again
        # f.seek(start_loc)
        # Instead of seeking again, just create ELFFile from current position
        elf = ELFFile(f)

© www.soinside.com 2019 - 2024. All rights reserved.