使用python+pyElftools从(avr)elf文件中获取内存布局

2024-09-30 01:36:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个ATXmega128A4U创建我自己的引导加载程序。要使用该引导加载程序,我想将固件的ELF文件转换为ATXmega中使用的内存映射。 为此,我使用python和模块“pyelftools”。它的文档很差,因此我遇到了一个问题:我不知道我可以使用什么信息从节的数据中获取地址、偏移量等。 我的目标是创建一个bytearray,将数据/代码复制到其中并将其传输到bootloader。以下是我的代码:

import sys

# If pyelftools is not installed, the example can also run from the root or
# examples/ dir of the source distribution.
sys.path[0:0] = ['.', '..']

from elftools.common.py3compat import bytes2str
from elftools.elf.elffile import ELFFile

# 128k flash for the ATXmega128a4u
flashsize = 128 * 1024


def process_file(filename):
    with open(filename, 'rb') as f:
        # get the data
        elffile = ELFFile(f)
        dataSec = elffile.get_section_by_name(b'.data')        
        textSec = elffile.get_section_by_name(b'.text')
        # prepare the memory
        flashMemory = bytearray(flashsize)
        # the data section
        startAddr = dataSec.header.sh_offset
        am = dataSec.header.sh_size
        i = 0
        while i < am:
            val = dataSec.stream.read(1)
            flashMemory[startAddr] = val[0]
            startAddr += 1
            i += 1
        # the text section
        startAddr = textSec.header.sh_offset
        am = textSec.header.sh_size
        i = 0
        while i < am:
            print(str(startAddr) + ' : ' + str(i))
            val = textSec.stream.read(1)
            flashMemory[startAddr] = val[0]
            startAddr += 1
            i += 1
    print('finished')

if __name__ == '__main__':
    process_file('firmware.elf')

希望有人能告诉我如何解决这个问题。在


Tags: thenamefromimportdatagetshsection
1条回答
网友
1楼 · 发布于 2024-09-30 01:36:24

我设法解决了这个问题。 不要手动从流中读取数据,方法是“文本sec.stream.read“使用”文本秒数据()”而不是。内在的(见“截面.py)文件中的查找操作已完成。然后读取数据。结果将是有效的数据块。 下面的代码读取atxmega固件的代码(文本)部分,并将其复制到具有atxmega128a4u设备闪存布局的bytearray中。 @弗拉斯·特佩什:不需要十六进制对话,避免了64k陷阱。在

^{1}$

坦克的评论!在

相关问题 更多 >

    热门问题