Ejemplo n.º 1
0
 def write_flash_file(self, filename, check = True):
     self.go_bootloader()
     self.get_target_info()
     self.client.write_register(self.MB_MAGIC_REG, self.MB_MAGIC_WORD, unit=self.id)
     startaddr = 0x04000000
     f = IntelHex16bit(filename)
     minaddr = f.minaddr()
     skip = minaddr - startaddr
     skip = (skip//self.mb_page_size)*self.mb_page_size
     last = f.maxaddr()
     last = last - startaddr
     last = (last//self.mb_page_size + 1)*self.mb_page_size
     spage = skip // self.mb_page_size
     s = last-skip
     d = []
     logging.info(f"skip  {skip}")
     logging.info(f"last  {last}")
     logging.info(f"s     {s}")
     logging.info(f"write {s*2} Bytes")
     logging.info(f"spage {spage}")
     for i in range(s):
         d.append(f[startaddr+i+skip])
     for i in range(s//self.mb_page_size+1):
         self.erase_page(skip//self.mb_page_size+i)
     #print(d)
     return self.write_flash(spage,d,check)
Ejemplo n.º 2
0
def main(argv):
    if len(argv) != 2:
        print('ota_image.py <ihexfile> <binfile>')
        sys.exit(2)

    # Check if hexfile exists
    hexfile = argv[0]
    if not os.path.isfile(hexfile):
        print("ERROR: File not found:", hexfile)
        sys.exit(2)

    # Target binfile
    binfile = argv[1]

    # Start parsing ihex
    ih = IntelHex16bit(hexfile)

    # Get data end == total .text + .data size
    dataend = ih[metadata_offset]

    # Calculate word size of metadata section
    meta_size = 3  # base size
    meta_size += ih[metadata_offset + 2]  # len(unsafe_2ndword)
    meta_size += 10  # HMAC

    # Start filling file
    f = open(binfile, 'wb')

    # First write metadata to beginning of file (!!Word addresses!!)
    ih.tobinfile(f, metadata_offset * 2, (metadata_offset + meta_size) * 2 - 1)
    # Write .text + .data after
    ih.tobinfile(f, 0, dataend - 1)

    f.close()
Ejemplo n.º 3
0
def intelhex(file):
    """
    A partir del fitxer hex extreu l'array d'enters

    :param file: el nom del fitxer .hex
    :return: L'array de dades
    """
    ih = IntelHex16bit()
    ih.fromfile(file, format='hex')
    return ih.tobinarray()
Ejemplo n.º 4
0
 def read_flash_file(self, page, size, filename):
     self.go_bootloader()
     self.get_target_info()
     f = IntelHex16bit()
     data = self.read_flash(page, size)
     startaddr = 0x04000000
     for i,d in zip(range(len(data)),data):
         f[i+startaddr+page*self.mb_page_size] = d
     f.tofile(filename, format = 'hex' )
     return (page,size)
Ejemplo n.º 5
0
def arm9_cli_handler(client, argv):
    if (argv[1] == "info"):
        client.halt()
        print >> sys.stderr, client.ARMidentstr()
        print >> sys.stderr, "Debug Status:\t%s" % client.statusstr()
        print >> sys.stderr, "CPSR: (%s) %s\n" % (client.ARMget_regCPSRstr())
        client.resume()

    if (argv[1] == "dump"):
        f = sys.argv[2]
        start = 0x00000000
        stop = 0xFFFFFFFF
        if (len(sys.argv) > 3):
            start = int(sys.argv[3], 16)
        if (len(sys.argv) > 4):
            stop = int(sys.argv[4], 16)

        print "Dumping from %04x to %04x as %s." % (start, stop, f)
        #h = IntelHex16bit(None)
        # FIXME: get mcu state and return it to that state
        client.halt()

        try:
            h = IntelHex(None)
            i = start
            while i <= stop:
                #data=client.ARMreadMem(i, 48)
                data = client.ARMreadChunk(i, 48, verbose=0)
                print "Dumped %06x." % i
                for dword in data:
                    if i <= stop and dword != 0xdeadbeef:
                        h.puts(i, struct.pack("<I", dword))
                    i += 4
            # FIXME: get mcu state and return it to that state
        except:
            print "Unknown error during read. Writing results to output file."
            print "Rename file with last address dumped %06x." % i
            pass

        client.resume()
        h.write_hex_file(f)
    '''
    if(sys.argv[1]=="erase"):
        print "Erasing main flash memory."
        client.ARMmasserase()

    if(sys.argv[1]=="eraseinfo"):
        print "Erasing info memory."
        client.ARMinfoerase()

        
    '''
    if (sys.argv[1] == "ivt"):
        client.halt()
        client.ARMprintChunk(0x0, 0x20)
        client.resume()

    if (sys.argv[1] == "regs"):
        client.halt()
        for i in range(0, 16):
            print "r%i=%04x" % (i, client.ARMget_register(i))
        client.resume()

    if (sys.argv[1] == "flash"):
        f = sys.argv[2]
        start = 0
        stop = 0x10000
        if (len(sys.argv) > 3):
            start = int(sys.argv[3], 16)
        if (len(sys.argv) > 4):
            stop = int(sys.argv[4], 16)

        client.halt()
        h = IntelHex16bit(f)

        #Should this be default?
        #Makes flashing multiple images inconvenient.
        #client.ARMmasserase()

        count = 0
        #Bytes in commit.
        first = 0
        vals = []
        last = 0
        #Last address committed.
        for i in h._buf.keys():
            if ((count > 0x40 or last + 2 != i) and count > 0 and i & 1 == 0):
                #print "%i, %x, %x" % (len(vals), last, i)
                client.ARMpokeflashblock(first, vals)
                count = 0
                first = 0
                last = 0
                vals = []
            if (i >= start and i < stop and i & 1 == 0):
                val = h[i >> 1]
                if (count == 0):
                    first = i
                last = i
                count += 2
                vals += [val & 0xff, (val & 0xff00) >> 8]
                if (i % 0x100 == 0):
                    print "%04x" % i
        if count > 0:  #last commit, ivt
            client.ARMpokeflashblock(first, vals)
        client.resume()

    if (sys.argv[1] == "verify"):
        f = sys.argv[2]
        start = 0
        stop = 0xFFFF
        if (len(sys.argv) > 3):
            start = int(sys.argv[3], 16)
        if (len(sys.argv) > 4):
            stop = int(sys.argv[4], 16)

        client.halt()
        h = IntelHex16bit(f)
        for i in h._buf.keys():
            if (i >= start and i < stop and i & 1 == 0):
                peek = client.peek(i)
                if (h[i >> 1] != peek):
                    print "ERROR at %04x, found %04x not %04x" % (i, peek,
                                                                  h[i >> 1])
                if (i % 0x100 == 0):
                    print "%04x" % i
        client.resume()

    if (sys.argv[1] == "peek"):
        start = 0x0000
        if (len(sys.argv) > 2):
            start = int(sys.argv[2], 16)

        stop = start + 4
        if (len(sys.argv) > 3):
            stop = int(sys.argv[3], 16)

        print "Peeking from %04x to %04x." % (start, stop)
        client.halt()
        for dword in client.ARMreadChunk(start, (stop - start) / 4, verbose=0):
            print "%.4x: %.8x" % (start, dword)
            start += 4
        client.resume()

    if (sys.argv[1] == "poke"):
        start = 0x0000
        val = 0x00
        if (len(sys.argv) > 2):
            start = int(sys.argv[2], 16)
        if (len(sys.argv) > 3):
            val = int(sys.argv[3], 16)

        print "Poking %06x to become %04x." % (start, val)
        client.halt()
        #???while client.ARMreadMem(start)[0]&(~val)>0:
        client.ARMwriteChunk(start, [val])
        print "Poked to %.8x" % client.ARMreadMem(start)[0]
        client.resume()

    if (sys.argv[1] == "reset"):
        #Set PC to RESET vector's value.

        #client.ARMsetPC(0x00000000)
        #client.ARMset_regCPSR(0)
        #client.ARMreleasecpu()
        client.ARMresettarget(1000)
Ejemplo n.º 6
0
from intelhex import IntelHex16bit

ih = IntelHex16bit()

ih.loadhex('usb.hex')

# ih.dump()
for addr in ih.todict().keys():
    print("0x{:08X}".format(addr))
# print(ih.todict()[0x1F810788])
Ejemplo n.º 7
0
 def __init__(self, filename):
     self.ih = IntelHex16bit()
     self.ih.fromfile(filename, format='hex')
Ejemplo n.º 8
0
parser = argparse.ArgumentParser(
    description='Writes hex images to Padauk PFS154 chips')
parser.add_argument(
    '--erase',
    action='store_true',
    help=
    'Forces a chip erase. If no specified, only if the flash is occupied currently it will be formatted'
)
parser.add_argument('--no-verify',
                    action='store_true',
                    help='Skips verification')
parser.add_argument('hex', type=argparse.FileType('r'), help='hex file')
parser.add_argument('com', help='serial port')
args = parser.parse_args()

ih = IntelHex16bit(args.hex)

with Programmer(args.com) as p:
    try:
        p.start_write()
        for start, end in ih.segments():
            # Convert to words
            start = start // 2
            end = end // 2 - 1

            print('Writing %04X-%04X... ' % (start, end), end='')
            wordarray = ih.tobinarray(start=start, end=end)
            p.write(start, wordarray)
            print('done')
        if not args.no_verify:
            p.start_read()
Ejemplo n.º 9
0
def main(argv):
    if len(argv) != 3:
        print('hex_patch_metadata.py <ihexfile> <datastart> <dataend>')
        sys.exit(2)

    # Check if hexfile exists
    hexfile = argv[0]
    if not os.path.isfile(hexfile):
        print("ERROR: File not found:", hexfile)
        sys.exit(2)

    # Parse data offset
    try:
        datastart = int(argv[1],
                        16)  # in hex, first byte of .data. == size .text
        dataend = int(
            argv[2], 16
        )  # in hex, end of .data last byte not included. == total size .text + .data
    except:
        print("ERROR: Offsets not valid:", argv[1], argv[2])
        sys.exit(2)

    # Start parsing ihex
    ih = IntelHex16bit(hexfile)

    # Look for opcodes that __can__ be unsafe as 2nd word and log them
    unsafe_2ndword = list()
    prev_op_long = 0
    for addr in range(datastart // 2):
        if ih[addr] in two_word_ops and not prev_op_long:
            prev_op_long = 1
        elif prev_op_long:
            prev_op_long = 0
            if ((ih[addr] & branch_ops_mask) in branch_ops
                    or (ih[addr] & rel_ops_mask) in rel_ops
                    or (ih[addr] & lpm_mask) in lpm_ops
                    or ih[addr] in unsafe_ops or ih[addr] in two_word_ops):
                print("Unsafe 2nd word, adding to list!")
                print(ih[addr])
                print(addr)
                unsafe_2ndword.append(addr)

    # Start patching hex
    ih[metadata_offset] = dataend  # total .text + .data size
    ih[metadata_offset + 1] = datastart  # .data start address == .text size
    ih[metadata_offset + 2] = len(unsafe_2ndword)
    for idx, addr in enumerate(unsafe_2ndword):
        ih[metadata_offset + 3 + idx] = addr

    # Calculate word size of metadata section
    meta_size = 3  # base size
    meta_size += len(unsafe_2ndword)

    # Calculate hmac
    hmac_gen = hmac.new(key, None, hashlib.sha1)
    hmac_gen.update(ih.tobinstr(
        0,
        dataend - 1))  # tobinstr uses byteaddr, even on an IntelHex16 object
    hmac_gen.update(
        ih.tobinstr(metadata_offset * 2,
                    (metadata_offset + meta_size) * 2 - 1))
    print(hmac_gen.hexdigest())

    # Add hmac after regular metadata (frombytes uses byteaddr, even on IntelHex16 objects)
    ih.frombytes(hmac_gen.digest(), (metadata_offset + meta_size) * 2)

    # Write out file
    ih.write_hex_file(hexfile)
Ejemplo n.º 10
0
def main() -> None:
    parser = init_argparse()
    args = parser.parse_args()

    if args.verbose:
        print("verbosity turned on")
        print("Input: " + args.infile.name)
        print("Output: " + args.outfile.name)
        print("Start address: " + hex(args.start))
        print("Length: " + hex(args.length))
        print("Length bytes:", args.length + args.length // 2)
        print("CRC Store address: " + hex(args.crcaddress))

    assert (
        args.start % 2
    ) == 0, "[START_ADDRESS] must be even. This paramter is according to dsPIC architecture program counter. See dsPIC architecture and classB lib CRC documentation."
    assert (
        args.length % 2
    ) == 0, "[LENGTH] must be specified as program counter's length. So must be multiple of 2. See dsPIC architecture and classB lib CRC documentation."
    assert (
        args.crcaddress % 2
    ) == 0, "[CRC_STORE_ADDRESS] must be even. This paramter is according to dsPIC architecture program counter.. So must be multiple of 2. See dsPIC architecture and classB lib CRC documentation."

    ih = IntelHex16bit(args.infile)  #Open file
    ih.padding = 0xFF  #change default padding
    if args.verbose:
        print("Max address in the", args.infile.name, "file:",
              hex(ih.maxaddr()))
    assert (
        args.start + args.length <= ih.maxaddr()
    ), "Address overflow. Check [START_ADDRESS], [LENGTH] and loaded hex file max address"

    #Read hex and rearrange data to array
    crcInput = ExtractHexData(args.start, args.length, ih)

    #create crc calculator function
    crc16_func = crcmod.mkCrcFun(0x18005,
                                 rev=False,
                                 initCrc=0xFFFF,
                                 xorOut=0x0000)

    #calculate the crc
    crcResult = crc16_func(crcInput)
    if args.verbose:
        print("CRC Result:", hex(crcResult))

    #Store the CRC to the selected address
    assert (crcResult <= 0xFFFFF), "Data must fit in 24bit"

    ih[args.crcaddress] = crcResult & 0xFFFF
    #load higher and lower byte
    ih[args.crcaddress + 1] = (crcResult >> 16) & 0xFF
    # load upper byte

    if args.verbose:
        print("Edited address:", hex(args.crcaddress))
        print("Higher and lower byte new data: ", hex(ih[args.crcaddress]))
        print("Upper byte new data: ", hex(ih[args.crcaddress + 1]))

    #write out the edited file
    ih.write_hex_file(args.outfile, write_start_addr=False)