python-intelhex / intelhex

Python IntelHex library
BSD 3-Clause "New" or "Revised" License
198 stars 106 forks source link

Add option for strictly incrementing addresses #49

Closed noahp closed 3 years ago

noahp commented 3 years ago

Add an option to enforce strictly monotonically incrementing addresses when loading a hex file.

Added example bad file, added --strict option to the hex_info.py script to enable the option, which will stacktrace on error:

 # non-strict
❯ python scripts/hexinfo.py testfiles/nonlinear_hexfile.hex
- file: 'testfiles/nonlinear_hexfile.hex'
  data:
  - { first: 0x00000000, last: 0x00000000, length: 0x00000001 }
  - { first: 0x00000010, last: 0x00000010, length: 0x00000001 }
  - { first: 0x00000110, last: 0x00000110, length: 0x00000001 }

 # --strict
❯ python scripts/hexinfo.py --strict testfiles/nonlinear_hexfile.hex
- file: 'testfiles/nonlinear_hexfile.hex'
Traceback (most recent call last):
  File "scripts/hexinfo.py", line 116, in <module>
    sys.exit(main())
  File "scripts/hexinfo.py", line 113, in main
    summarize_yaml(fname, options["strict"])
  File "scripts/hexinfo.py", line 61, in summarize_yaml
    ih = IntelHex(fname, strict_address_increment=strict)
...
    raise AddressDecrementError(address=addr, line=line)
intelhex.AddressDecrementError: Hex file has skipback address 0x10 on line 3
bialix commented 3 years ago

Why do you need such behavior?

noahp commented 3 years ago

In my use case, I'm writing hex data into a flash chip and it's useful to not have to handle the scenario where flash address decrements. I added this option to use in a build check to ensure the generated hex files won't have non-monotonically-incrementing addresses, and figured I'd offer it here if there's any interest!

bialix commented 3 years ago

In my use case, I'm writing hex data into a flash chip and it's useful to not have to handle the scenario where flash address decrements. I added this option to use in a build check to ensure the generated hex files won't have non-monotonically-incrementing addresses, and figured I'd offer it here if there's any interest!

I don't really understand. Are you send hex file "as is" into your firmware?

noahp commented 3 years ago

No worries, I decided to hack it at runtime like this instead:

    from collections import OrderedDict
    ih = IntelHex()
    ih._buf = OrderedDict()
    ih.loadhex(filename)

    lastaddr = None
    for addr in ih._buf:
        assert (
            (lastaddr is None) or (addr > lastaddr)
        ), "Error decrementing address at 0x{:x}".format(addr)
        lastaddr = addr

Closing!