Clone of official tools

Committer:
Anders Blomdell
Date:
Thu Feb 04 17:17:13 2021 +0100
Revision:
47:21ae3e5a7128
Parent:
44:bad0b339f97d
Add a few normpath calls

Who changed what in which revision?

UserRevisionLine numberNew contents of line
theotherjimmy 44:bad0b339f97d 1 #!/usr/bin/env python
theotherjimmy 44:bad0b339f97d 2 """
theotherjimmy 44:bad0b339f97d 3 mbed
theotherjimmy 44:bad0b339f97d 4 Copyright (c) 2017-2017 ARM Limited
theotherjimmy 44:bad0b339f97d 5
theotherjimmy 44:bad0b339f97d 6 Licensed under the Apache License, Version 2.0 (the "License");
theotherjimmy 44:bad0b339f97d 7 you may not use this file except in compliance with the License.
theotherjimmy 44:bad0b339f97d 8 You may obtain a copy of the License at
theotherjimmy 44:bad0b339f97d 9
theotherjimmy 44:bad0b339f97d 10 http://www.apache.org/licenses/LICENSE-2.0
theotherjimmy 44:bad0b339f97d 11
theotherjimmy 44:bad0b339f97d 12 Unless required by applicable law or agreed to in writing, software
theotherjimmy 44:bad0b339f97d 13 distributed under the License is distributed on an "AS IS" BASIS,
theotherjimmy 44:bad0b339f97d 14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
theotherjimmy 44:bad0b339f97d 15 See the License for the specific language governing permissions and
theotherjimmy 44:bad0b339f97d 16 limitations under the License.
theotherjimmy 44:bad0b339f97d 17 """
theotherjimmy 44:bad0b339f97d 18
theotherjimmy 44:bad0b339f97d 19 from __future__ import print_function
theotherjimmy 44:bad0b339f97d 20 import os
theotherjimmy 44:bad0b339f97d 21 import struct
theotherjimmy 44:bad0b339f97d 22 import binascii
theotherjimmy 44:bad0b339f97d 23 import argparse
theotherjimmy 44:bad0b339f97d 24 import logging
theotherjimmy 44:bad0b339f97d 25 try:
theotherjimmy 44:bad0b339f97d 26 from StringIO import StringIO
theotherjimmy 44:bad0b339f97d 27 except ImportError:
theotherjimmy 44:bad0b339f97d 28 from io import StringIO
theotherjimmy 44:bad0b339f97d 29 import jinja2
theotherjimmy 44:bad0b339f97d 30 from collections import namedtuple
theotherjimmy 44:bad0b339f97d 31 from itertools import count
theotherjimmy 44:bad0b339f97d 32
theotherjimmy 44:bad0b339f97d 33 from elftools.common.py3compat import bytes2str
theotherjimmy 44:bad0b339f97d 34 from elftools.elf.elffile import ELFFile
theotherjimmy 44:bad0b339f97d 35 from elftools.elf.sections import SymbolTableSection
theotherjimmy 44:bad0b339f97d 36
theotherjimmy 44:bad0b339f97d 37 logger = logging.getLogger(__name__)
theotherjimmy 44:bad0b339f97d 38 logger.addHandler(logging.NullHandler())
theotherjimmy 44:bad0b339f97d 39
theotherjimmy 44:bad0b339f97d 40
theotherjimmy 44:bad0b339f97d 41 def main():
theotherjimmy 44:bad0b339f97d 42 parser = argparse.ArgumentParser(description="Algo Extracter")
theotherjimmy 44:bad0b339f97d 43 parser.add_argument("input", help="File to extract flash algo from")
theotherjimmy 44:bad0b339f97d 44 parser.add_argument("template", default="py_blob.tmpl",
theotherjimmy 44:bad0b339f97d 45 help="Template to use")
theotherjimmy 44:bad0b339f97d 46 parser.add_argument("output", help="Output file")
theotherjimmy 44:bad0b339f97d 47 args = parser.parse_args()
theotherjimmy 44:bad0b339f97d 48
theotherjimmy 44:bad0b339f97d 49 with open(args.input, "rb") as file_handle:
theotherjimmy 44:bad0b339f97d 50 data = file_handle.read()
theotherjimmy 44:bad0b339f97d 51 algo = PackFlashAlgo(data)
theotherjimmy 44:bad0b339f97d 52 algo.process_template(args.template, args.output)
theotherjimmy 44:bad0b339f97d 53
theotherjimmy 44:bad0b339f97d 54
theotherjimmy 44:bad0b339f97d 55 class PackFlashAlgo(object):
theotherjimmy 44:bad0b339f97d 56 """
theotherjimmy 44:bad0b339f97d 57 Class to wrap a flash algo
theotherjimmy 44:bad0b339f97d 58
theotherjimmy 44:bad0b339f97d 59 This class is intended to provide easy access to the information
theotherjimmy 44:bad0b339f97d 60 provided by a flash algorithm, such as symbols and the flash
theotherjimmy 44:bad0b339f97d 61 algorithm itself.
theotherjimmy 44:bad0b339f97d 62 """
theotherjimmy 44:bad0b339f97d 63
theotherjimmy 44:bad0b339f97d 64 REQUIRED_SYMBOLS = set([
theotherjimmy 44:bad0b339f97d 65 "Init",
theotherjimmy 44:bad0b339f97d 66 "UnInit",
theotherjimmy 44:bad0b339f97d 67 "EraseSector",
theotherjimmy 44:bad0b339f97d 68 "ProgramPage",
theotherjimmy 44:bad0b339f97d 69 ])
theotherjimmy 44:bad0b339f97d 70
theotherjimmy 44:bad0b339f97d 71 EXTRA_SYMBOLS = set([
theotherjimmy 44:bad0b339f97d 72 "BlankCheck",
theotherjimmy 44:bad0b339f97d 73 "EraseChip",
theotherjimmy 44:bad0b339f97d 74 "Verify",
theotherjimmy 44:bad0b339f97d 75 ])
theotherjimmy 44:bad0b339f97d 76
theotherjimmy 44:bad0b339f97d 77 def __init__(self, data):
theotherjimmy 44:bad0b339f97d 78 """Construct a PackFlashAlgorithm from an ElfFileSimple"""
theotherjimmy 44:bad0b339f97d 79 self.elf = ElfFileSimple(data)
theotherjimmy 44:bad0b339f97d 80 self.flash_info = PackFlashInfo(self.elf)
theotherjimmy 44:bad0b339f97d 81
theotherjimmy 44:bad0b339f97d 82 self.flash_start = self.flash_info.start
theotherjimmy 44:bad0b339f97d 83 self.flash_size = self.flash_info.size
theotherjimmy 44:bad0b339f97d 84 self.page_size = self.flash_info.page_size
theotherjimmy 44:bad0b339f97d 85 self.sector_sizes = self.flash_info.sector_info_list
theotherjimmy 44:bad0b339f97d 86
theotherjimmy 44:bad0b339f97d 87 symbols = {}
theotherjimmy 44:bad0b339f97d 88 symbols.update(_extract_symbols(self.elf, self.REQUIRED_SYMBOLS))
theotherjimmy 44:bad0b339f97d 89 symbols.update(_extract_symbols(self.elf, self.EXTRA_SYMBOLS,
theotherjimmy 44:bad0b339f97d 90 default=0xFFFFFFFF))
theotherjimmy 44:bad0b339f97d 91 self.symbols = symbols
theotherjimmy 44:bad0b339f97d 92
theotherjimmy 44:bad0b339f97d 93 sections_to_find = (
theotherjimmy 44:bad0b339f97d 94 ("PrgCode", "SHT_PROGBITS"),
theotherjimmy 44:bad0b339f97d 95 ("PrgData", "SHT_PROGBITS"),
theotherjimmy 44:bad0b339f97d 96 ("PrgData", "SHT_NOBITS"),
theotherjimmy 44:bad0b339f97d 97 )
theotherjimmy 44:bad0b339f97d 98
theotherjimmy 44:bad0b339f97d 99 ro_rw_zi = _find_sections(self.elf, sections_to_find)
theotherjimmy 44:bad0b339f97d 100 ro_rw_zi = _algo_fill_zi_if_missing(ro_rw_zi)
theotherjimmy 44:bad0b339f97d 101 error_msg = _algo_check_for_section_problems(ro_rw_zi)
theotherjimmy 44:bad0b339f97d 102 if error_msg is not None:
theotherjimmy 44:bad0b339f97d 103 raise Exception(error_msg)
theotherjimmy 44:bad0b339f97d 104
theotherjimmy 44:bad0b339f97d 105 sect_ro, sect_rw, sect_zi = ro_rw_zi
theotherjimmy 44:bad0b339f97d 106 self.ro_start = sect_ro["sh_addr"]
theotherjimmy 44:bad0b339f97d 107 self.ro_size = sect_ro["sh_size"]
theotherjimmy 44:bad0b339f97d 108 self.rw_start = sect_rw["sh_addr"]
theotherjimmy 44:bad0b339f97d 109 self.rw_size = sect_rw["sh_size"]
theotherjimmy 44:bad0b339f97d 110 self.zi_start = sect_zi["sh_addr"]
theotherjimmy 44:bad0b339f97d 111 self.zi_size = sect_zi["sh_size"]
theotherjimmy 44:bad0b339f97d 112
theotherjimmy 44:bad0b339f97d 113 self.algo_data = _create_algo_bin(ro_rw_zi)
theotherjimmy 44:bad0b339f97d 114
theotherjimmy 44:bad0b339f97d 115 def format_algo_data(self, spaces, group_size, fmt):
theotherjimmy 44:bad0b339f97d 116 """"
theotherjimmy 44:bad0b339f97d 117 Return a string representing algo_data suitable for use in a template
theotherjimmy 44:bad0b339f97d 118
theotherjimmy 44:bad0b339f97d 119 The string is intended for use in a template.
theotherjimmy 44:bad0b339f97d 120
theotherjimmy 44:bad0b339f97d 121 :param spaces: The number of leading spaces for each line
theotherjimmy 44:bad0b339f97d 122 :param group_size: number of elements per line (element type
theotherjimmy 44:bad0b339f97d 123 depends of format)
theotherjimmy 44:bad0b339f97d 124 :param fmt: - format to create - can be either "hex" or "c"
theotherjimmy 44:bad0b339f97d 125 """
theotherjimmy 44:bad0b339f97d 126 padding = " " * spaces
theotherjimmy 44:bad0b339f97d 127 if fmt == "hex":
theotherjimmy 44:bad0b339f97d 128 blob = binascii.b2a_hex(self.algo_data)
theotherjimmy 44:bad0b339f97d 129 line_list = []
theotherjimmy 44:bad0b339f97d 130 for i in range(0, len(blob), group_size):
theotherjimmy 44:bad0b339f97d 131 line_list.append('"' + blob[i:i + group_size] + '"')
theotherjimmy 44:bad0b339f97d 132 return ("\n" + padding).join(line_list)
theotherjimmy 44:bad0b339f97d 133 elif fmt == "c":
theotherjimmy 44:bad0b339f97d 134 blob = self.algo_data[:]
theotherjimmy 44:bad0b339f97d 135 pad_size = 0 if len(blob) % 4 == 0 else 4 - len(blob) % 4
theotherjimmy 44:bad0b339f97d 136 blob = blob + "\x00" * pad_size
theotherjimmy 44:bad0b339f97d 137 integer_list = struct.unpack("<" + "L" * (len(blob) / 4), blob)
theotherjimmy 44:bad0b339f97d 138 line_list = []
theotherjimmy 44:bad0b339f97d 139 for pos in range(0, len(integer_list), group_size):
theotherjimmy 44:bad0b339f97d 140 group = ["0x%08x" % value for value in
theotherjimmy 44:bad0b339f97d 141 integer_list[pos:pos + group_size]]
theotherjimmy 44:bad0b339f97d 142 line_list.append(", ".join(group))
theotherjimmy 44:bad0b339f97d 143 return (",\n" + padding).join(line_list)
theotherjimmy 44:bad0b339f97d 144 else:
theotherjimmy 44:bad0b339f97d 145 raise Exception("Unsupported format %s" % fmt)
theotherjimmy 44:bad0b339f97d 146
theotherjimmy 44:bad0b339f97d 147 def process_template(self, template_path, output_path, data_dict=None):
theotherjimmy 44:bad0b339f97d 148 """
theotherjimmy 44:bad0b339f97d 149 Generate output from the supplied template
theotherjimmy 44:bad0b339f97d 150
theotherjimmy 44:bad0b339f97d 151 All the public methods and fields of this class can be accessed from
theotherjimmy 44:bad0b339f97d 152 the template via "algo".
theotherjimmy 44:bad0b339f97d 153
theotherjimmy 44:bad0b339f97d 154 :param template_path: Relative or absolute file path to the template
theotherjimmy 44:bad0b339f97d 155 :param output_path: Relative or absolute file path to create
theotherjimmy 44:bad0b339f97d 156 :param data_dict: Additional data to use when generating
theotherjimmy 44:bad0b339f97d 157 """
theotherjimmy 44:bad0b339f97d 158 if data_dict is None:
theotherjimmy 44:bad0b339f97d 159 data_dict = {}
theotherjimmy 44:bad0b339f97d 160 else:
theotherjimmy 44:bad0b339f97d 161 assert isinstance(data_dict, dict)
theotherjimmy 44:bad0b339f97d 162 data_dict = dict(data_dict)
theotherjimmy 44:bad0b339f97d 163 assert "algo" not in data_dict, "algo already set by user data"
theotherjimmy 44:bad0b339f97d 164 data_dict["algo"] = self
theotherjimmy 44:bad0b339f97d 165
theotherjimmy 44:bad0b339f97d 166 with open(template_path) as file_handle:
theotherjimmy 44:bad0b339f97d 167 template_text = file_handle.read()
theotherjimmy 44:bad0b339f97d 168
theotherjimmy 44:bad0b339f97d 169 template = jinja2.Template(template_text)
theotherjimmy 44:bad0b339f97d 170 target_text = template.render(data_dict)
theotherjimmy 44:bad0b339f97d 171
theotherjimmy 44:bad0b339f97d 172 with open(output_path, "wb") as file_handle:
theotherjimmy 44:bad0b339f97d 173 file_handle.write(target_text)
theotherjimmy 44:bad0b339f97d 174
theotherjimmy 44:bad0b339f97d 175
theotherjimmy 44:bad0b339f97d 176 def _extract_symbols(simple_elf, symbols, default=None):
theotherjimmy 44:bad0b339f97d 177 """Fill 'symbols' field with required flash algo symbols"""
theotherjimmy 44:bad0b339f97d 178 to_ret = {}
theotherjimmy 44:bad0b339f97d 179 for symbol in symbols:
theotherjimmy 44:bad0b339f97d 180 if symbol not in simple_elf.symbols:
theotherjimmy 44:bad0b339f97d 181 if default is not None:
theotherjimmy 44:bad0b339f97d 182 to_ret[symbol] = default
theotherjimmy 44:bad0b339f97d 183 continue
theotherjimmy 44:bad0b339f97d 184 raise Exception("Missing symbol %s" % symbol)
theotherjimmy 44:bad0b339f97d 185 to_ret[symbol] = simple_elf.symbols[symbol].value
theotherjimmy 44:bad0b339f97d 186 return to_ret
theotherjimmy 44:bad0b339f97d 187
theotherjimmy 44:bad0b339f97d 188
theotherjimmy 44:bad0b339f97d 189 def _find_sections(elf, name_type_pairs):
theotherjimmy 44:bad0b339f97d 190 """Return a list of sections the same length and order of the input list"""
theotherjimmy 44:bad0b339f97d 191 sections = [None] * len(name_type_pairs)
theotherjimmy 44:bad0b339f97d 192 for section in elf.iter_sections():
theotherjimmy 44:bad0b339f97d 193 section_name = bytes2str(section.name)
theotherjimmy 44:bad0b339f97d 194 section_type = section["sh_type"]
theotherjimmy 44:bad0b339f97d 195 for i, name_and_type in enumerate(name_type_pairs):
theotherjimmy 44:bad0b339f97d 196 if name_and_type != (section_name, section_type):
theotherjimmy 44:bad0b339f97d 197 continue
theotherjimmy 44:bad0b339f97d 198 if sections[i] is not None:
theotherjimmy 44:bad0b339f97d 199 raise Exception("Elf contains duplicate section %s attr %s" %
theotherjimmy 44:bad0b339f97d 200 (section_name, section_type))
theotherjimmy 44:bad0b339f97d 201 sections[i] = section
theotherjimmy 44:bad0b339f97d 202 return sections
theotherjimmy 44:bad0b339f97d 203
theotherjimmy 44:bad0b339f97d 204
theotherjimmy 44:bad0b339f97d 205 def _algo_fill_zi_if_missing(ro_rw_zi):
theotherjimmy 44:bad0b339f97d 206 """Create an empty zi section if it is missing"""
theotherjimmy 44:bad0b339f97d 207 s_ro, s_rw, s_zi = ro_rw_zi
theotherjimmy 44:bad0b339f97d 208 if s_rw is None:
theotherjimmy 44:bad0b339f97d 209 return ro_rw_zi
theotherjimmy 44:bad0b339f97d 210 if s_zi is not None:
theotherjimmy 44:bad0b339f97d 211 return ro_rw_zi
theotherjimmy 44:bad0b339f97d 212 s_zi = {
theotherjimmy 44:bad0b339f97d 213 "sh_addr": s_rw["sh_addr"] + s_rw["sh_size"],
theotherjimmy 44:bad0b339f97d 214 "sh_size": 0
theotherjimmy 44:bad0b339f97d 215 }
theotherjimmy 44:bad0b339f97d 216 return s_ro, s_rw, s_zi
theotherjimmy 44:bad0b339f97d 217
theotherjimmy 44:bad0b339f97d 218
theotherjimmy 44:bad0b339f97d 219 def _algo_check_for_section_problems(ro_rw_zi):
theotherjimmy 44:bad0b339f97d 220 """Return a string describing any errors with the layout or None if good"""
theotherjimmy 44:bad0b339f97d 221 s_ro, s_rw, s_zi = ro_rw_zi
theotherjimmy 44:bad0b339f97d 222 if s_ro is None:
theotherjimmy 44:bad0b339f97d 223 return "RO section is missing"
theotherjimmy 44:bad0b339f97d 224 if s_rw is None:
theotherjimmy 44:bad0b339f97d 225 return "RW section is missing"
theotherjimmy 44:bad0b339f97d 226 if s_zi is None:
theotherjimmy 44:bad0b339f97d 227 return "ZI section is missing"
theotherjimmy 44:bad0b339f97d 228 if s_ro["sh_addr"] != 0:
theotherjimmy 44:bad0b339f97d 229 return "RO section does not start at address 0"
theotherjimmy 44:bad0b339f97d 230 if s_ro["sh_addr"] + s_ro["sh_size"] != s_rw["sh_addr"]:
theotherjimmy 44:bad0b339f97d 231 return "RW section does not follow RO section"
theotherjimmy 44:bad0b339f97d 232 if s_rw["sh_addr"] + s_rw["sh_size"] != s_zi["sh_addr"]:
theotherjimmy 44:bad0b339f97d 233 return "ZI section does not follow RW section"
theotherjimmy 44:bad0b339f97d 234 return None
theotherjimmy 44:bad0b339f97d 235
theotherjimmy 44:bad0b339f97d 236
theotherjimmy 44:bad0b339f97d 237 def _create_algo_bin(ro_rw_zi):
theotherjimmy 44:bad0b339f97d 238 """Create a binary blob of the flash algo which can execute from ram"""
theotherjimmy 44:bad0b339f97d 239 sect_ro, sect_rw, sect_zi = ro_rw_zi
theotherjimmy 44:bad0b339f97d 240 algo_size = sect_ro["sh_size"] + sect_rw["sh_size"] + sect_zi["sh_size"]
theotherjimmy 44:bad0b339f97d 241 algo_data = bytearray(algo_size)
theotherjimmy 44:bad0b339f97d 242 for section in (sect_ro, sect_rw):
theotherjimmy 44:bad0b339f97d 243 start = section["sh_addr"]
theotherjimmy 44:bad0b339f97d 244 size = section["sh_size"]
theotherjimmy 44:bad0b339f97d 245 data = section.data()
theotherjimmy 44:bad0b339f97d 246 assert len(data) == size
theotherjimmy 44:bad0b339f97d 247 algo_data[start:start + size] = data
theotherjimmy 44:bad0b339f97d 248 return algo_data
theotherjimmy 44:bad0b339f97d 249
theotherjimmy 44:bad0b339f97d 250
theotherjimmy 44:bad0b339f97d 251 class PackFlashInfo(object):
theotherjimmy 44:bad0b339f97d 252 """Wrapper class for the non-executable information in an FLM file"""
theotherjimmy 44:bad0b339f97d 253
theotherjimmy 44:bad0b339f97d 254 FLASH_DEVICE_STRUCT = "<H128sHLLLLBxxxLL"
theotherjimmy 44:bad0b339f97d 255 FLASH_SECTORS_STRUCT = "<LL"
theotherjimmy 44:bad0b339f97d 256 FLASH_SECTORS_STRUCT_SIZE = struct.calcsize(FLASH_SECTORS_STRUCT)
theotherjimmy 44:bad0b339f97d 257 SECTOR_END = 0xFFFFFFFF
theotherjimmy 44:bad0b339f97d 258
theotherjimmy 44:bad0b339f97d 259 def __init__(self, elf_simple):
theotherjimmy 44:bad0b339f97d 260 dev_info = elf_simple.symbols["FlashDevice"]
theotherjimmy 44:bad0b339f97d 261 info_start = dev_info.value
theotherjimmy 44:bad0b339f97d 262 info_size = struct.calcsize(self.FLASH_DEVICE_STRUCT)
theotherjimmy 44:bad0b339f97d 263 data = elf_simple.read(info_start, info_size)
theotherjimmy 44:bad0b339f97d 264 values = struct.unpack(self.FLASH_DEVICE_STRUCT, data)
theotherjimmy 44:bad0b339f97d 265
theotherjimmy 44:bad0b339f97d 266 self.version = values[0]
theotherjimmy 44:bad0b339f97d 267 self.name = values[1].strip("\x00")
theotherjimmy 44:bad0b339f97d 268 self.type = values[2]
theotherjimmy 44:bad0b339f97d 269 self.start = values[3]
theotherjimmy 44:bad0b339f97d 270 self.size = values[4]
theotherjimmy 44:bad0b339f97d 271 self.page_size = values[5]
theotherjimmy 44:bad0b339f97d 272 self.value_empty = values[7]
theotherjimmy 44:bad0b339f97d 273 self.prog_timeout_ms = values[8]
theotherjimmy 44:bad0b339f97d 274 self.erase_timeout_ms = values[9]
theotherjimmy 44:bad0b339f97d 275
theotherjimmy 44:bad0b339f97d 276 sector_gen = self._sector_and_sz_itr(elf_simple,
theotherjimmy 44:bad0b339f97d 277 info_start + info_size)
theotherjimmy 44:bad0b339f97d 278 self.sector_info_list = list(sector_gen)
theotherjimmy 44:bad0b339f97d 279
theotherjimmy 44:bad0b339f97d 280 def __str__(self):
theotherjimmy 44:bad0b339f97d 281 desc = ""
theotherjimmy 44:bad0b339f97d 282 desc += "Flash Device:" + os.linesep
theotherjimmy 44:bad0b339f97d 283 desc += " name=%s" % self.name + os.linesep
theotherjimmy 44:bad0b339f97d 284 desc += " version=0x%x" % self.version + os.linesep
theotherjimmy 44:bad0b339f97d 285 desc += " type=%i" % self.type + os.linesep
theotherjimmy 44:bad0b339f97d 286 desc += " start=0x%x" % self.start + os.linesep
theotherjimmy 44:bad0b339f97d 287 desc += " size=0x%x" % self.size + os.linesep
theotherjimmy 44:bad0b339f97d 288 desc += " page_size=0x%x" % self.page_size + os.linesep
theotherjimmy 44:bad0b339f97d 289 desc += " value_empty=0x%x" % self.value_empty + os.linesep
theotherjimmy 44:bad0b339f97d 290 desc += " prog_timeout_ms=%i" % self.prog_timeout_ms + os.linesep
theotherjimmy 44:bad0b339f97d 291 desc += " erase_timeout_ms=%i" % self.erase_timeout_ms + os.linesep
theotherjimmy 44:bad0b339f97d 292 desc += " sectors:" + os.linesep
theotherjimmy 44:bad0b339f97d 293 for sector_start, sector_size in self.sector_info_list:
theotherjimmy 44:bad0b339f97d 294 desc += (" start=0x%x, size=0x%x" %
theotherjimmy 44:bad0b339f97d 295 (sector_start, sector_size) + os.linesep)
theotherjimmy 44:bad0b339f97d 296 return desc
theotherjimmy 44:bad0b339f97d 297
theotherjimmy 44:bad0b339f97d 298 def _sector_and_sz_itr(self, elf_simple, data_start):
theotherjimmy 44:bad0b339f97d 299 """Iterator which returns starting address and sector size"""
theotherjimmy 44:bad0b339f97d 300 for entry_start in count(data_start, self.FLASH_SECTORS_STRUCT_SIZE):
theotherjimmy 44:bad0b339f97d 301 data = elf_simple.read(entry_start, self.FLASH_SECTORS_STRUCT_SIZE)
theotherjimmy 44:bad0b339f97d 302 size, start = struct.unpack(self.FLASH_SECTORS_STRUCT, data)
theotherjimmy 44:bad0b339f97d 303 start_and_size = start, size
theotherjimmy 44:bad0b339f97d 304 if start_and_size == (self.SECTOR_END, self.SECTOR_END):
theotherjimmy 44:bad0b339f97d 305 return
theotherjimmy 44:bad0b339f97d 306 yield start_and_size
theotherjimmy 44:bad0b339f97d 307
theotherjimmy 44:bad0b339f97d 308
theotherjimmy 44:bad0b339f97d 309 SymbolSimple = namedtuple("SymbolSimple", "name, value, size")
theotherjimmy 44:bad0b339f97d 310
theotherjimmy 44:bad0b339f97d 311
theotherjimmy 44:bad0b339f97d 312 class ElfFileSimple(ELFFile):
theotherjimmy 44:bad0b339f97d 313 """Wrapper for elf object which allows easy access to symbols and rom"""
theotherjimmy 44:bad0b339f97d 314
theotherjimmy 44:bad0b339f97d 315 def __init__(self, data):
theotherjimmy 44:bad0b339f97d 316 """Construct a ElfFileSimple from bytes or a bytearray"""
theotherjimmy 44:bad0b339f97d 317 super(ElfFileSimple, self).__init__(StringIO(data))
theotherjimmy 44:bad0b339f97d 318 self.symbols = self._read_symbol_table()
theotherjimmy 44:bad0b339f97d 319
theotherjimmy 44:bad0b339f97d 320 def _read_symbol_table(self):
theotherjimmy 44:bad0b339f97d 321 """Read the symbol table into the field "symbols" for easy use"""
theotherjimmy 44:bad0b339f97d 322 section = self.get_section_by_name(b".symtab")
theotherjimmy 44:bad0b339f97d 323 if not section:
theotherjimmy 44:bad0b339f97d 324 raise Exception("Missing symbol table")
theotherjimmy 44:bad0b339f97d 325
theotherjimmy 44:bad0b339f97d 326 if not isinstance(section, SymbolTableSection):
theotherjimmy 44:bad0b339f97d 327 raise Exception("Invalid symbol table section")
theotherjimmy 44:bad0b339f97d 328
theotherjimmy 44:bad0b339f97d 329 symbols = {}
theotherjimmy 44:bad0b339f97d 330 for symbol in section.iter_symbols():
theotherjimmy 44:bad0b339f97d 331 name_str = bytes2str(symbol.name)
theotherjimmy 44:bad0b339f97d 332 if name_str in symbols:
theotherjimmy 44:bad0b339f97d 333 logging.debug("Duplicate symbol %s", name_str)
theotherjimmy 44:bad0b339f97d 334 symbols[name_str] = SymbolSimple(name_str, symbol["st_value"],
theotherjimmy 44:bad0b339f97d 335 symbol["st_size"])
theotherjimmy 44:bad0b339f97d 336 return symbols
theotherjimmy 44:bad0b339f97d 337
theotherjimmy 44:bad0b339f97d 338 def read(self, addr, size):
theotherjimmy 44:bad0b339f97d 339 """Read program data from the elf file
theotherjimmy 44:bad0b339f97d 340
theotherjimmy 44:bad0b339f97d 341 :param addr: physical address (load address) to read from
theotherjimmy 44:bad0b339f97d 342 :param size: number of bytes to read
theotherjimmy 44:bad0b339f97d 343 :return: Requested data or None if address is unmapped
theotherjimmy 44:bad0b339f97d 344 """
theotherjimmy 44:bad0b339f97d 345 for segment in self.iter_segments():
theotherjimmy 44:bad0b339f97d 346 seg_addr = segment["p_paddr"]
theotherjimmy 44:bad0b339f97d 347 seg_size = min(segment["p_memsz"], segment["p_filesz"])
theotherjimmy 44:bad0b339f97d 348 if addr >= seg_addr + seg_size:
theotherjimmy 44:bad0b339f97d 349 continue
theotherjimmy 44:bad0b339f97d 350 if addr + size <= seg_addr:
theotherjimmy 44:bad0b339f97d 351 continue
theotherjimmy 44:bad0b339f97d 352 # There is at least some overlap
theotherjimmy 44:bad0b339f97d 353
theotherjimmy 44:bad0b339f97d 354 if addr >= seg_addr and addr + size <= seg_addr + seg_size:
theotherjimmy 44:bad0b339f97d 355 # Region is fully contained
theotherjimmy 44:bad0b339f97d 356 data = segment.data()
theotherjimmy 44:bad0b339f97d 357 start = addr - seg_addr
theotherjimmy 44:bad0b339f97d 358 return data[start:start + size]
theotherjimmy 44:bad0b339f97d 359
theotherjimmy 44:bad0b339f97d 360
theotherjimmy 44:bad0b339f97d 361 if __name__ == '__main__':
theotherjimmy 44:bad0b339f97d 362 main()