Ejemplo n.º 1
0
def read(ctx, address, length, mtype, compress, file):

    mem_id = 0 if mtype == 'INTERNAL' else ExtMemId[mtype]
    device = scan_interface(ctx.obj['TARGET'])

    click.echo(" Reading from MCU memory, please wait ! \n")

    with McuBoot(device, True) as mb:
        data = mb.read_memory(address, length, mem_id)

    if ctx.obj['DEBUG']:
        click.echo()

    if file is None:
        click.echo(hexdump(data, address, compress))
    else:
        try:
            if file.lower().endswith(('.srec', '.s19')):
                srec = bincopy.BinFile()
                srec.add_binary(data, address)
                srec.header = 'mboot'
                with open(file, "w") as f:
                    f.write(srec.as_srec())
            elif file.lower().endswith(('.hex', '.ihex')):
                ihex = bincopy.BinFile()
                ihex.add_binary(data, address)
                with open(file, "w") as f:
                    f.write(ihex.as_ihex())
            else:
                with open(file, "wb") as f:
                    f.write(data)
        except Exception as e:
            print_error(f"Could not write to file: {file} \n [{str(e)}]")

        click.echo(f"\n Successfully saved into: {file}")
Ejemplo n.º 2
0
 def _convertHexOrBinToSrec(self, appFilename, destSrecAppFilename,
                            appType):
     status = True
     fmtObj = None
     if appType.lower() in gendef.kAppImageFileExtensionList_Hex:
         fmtObj = bincopy.BinFile(str(appFilename))
     elif appType.lower() in gendef.kAppImageFileExtensionList_Bin:
         fmtObj = bincopy.BinFile()
         status, baseAddr = self.getUserBinaryBaseAddress()
         if status:
             fmtObj.add_binary_file(str(appFilename), baseAddr)
         else:
             appType = None
     if status:
         self.srcAppFilename = destSrecAppFilename
         with open(self.srcAppFilename, 'wb') as fileObj:
             # Prototype: as_srec(number_of_data_bytes=32, address_length_bits=32)
             #    Format the binary file as Motorola S-Records records and return them as a string.
             #    number_of_data_bytes is the number of data bytes in each record.
             #    address_length_bits is the number of address bits in each record.
             fileObj.write(
                 self._getSrecDataWithoutS6Frame(fmtObj.as_srec(16, 32)))
             fileObj.close()
         appFilename = self.srcAppFilename
         appType = gendef.kAppImageFileExtensionList_S19[0]
         self.isConvertedAppUsed = True
     return appFilename, appType
Ejemplo n.º 3
0
def resource(ctx, address, length, option, compress, file):

    device = scan_interface(ctx.obj['TARGET'])

    with McuBoot(device, True) as mb:
        data = mb.flash_read_resource(address, length, option)

    if ctx.obj['DEBUG']:
        click.echo()

    if file is None:
        click.echo(hexdump(data, address, compress))
    else:
        try:
            if file.lower().endswith(('.srec', '.s19')):
                srec = bincopy.BinFile()
                srec.add_binary(data, address)
                srec.header = 'mboot'
                with open(file, "w") as f:
                    f.write(srec.as_srec())
            elif file.lower().endswith(('.hex', '.ihex')):
                ihex = bincopy.BinFile()
                ihex.add_binary(data, address)
                with open(file, "w") as f:
                    f.write(ihex.as_ihex())
            else:
                with open(file, "wb") as f:
                    f.write(data)
        except Exception as e:
            print_error(f'Could not write to file: {file} \n [{str(e)}]')

        click.echo(f" Successfully saved into: {file}")
Ejemplo n.º 4
0
 def test_add_files(self):
     binfile = bincopy.BinFile()
     binfile_1_2 = bincopy.BinFile()
     binfile.add_binary(b'\x00')
     binfile_1_2.add_binary(b'\x01', address=1)
     binfile += binfile_1_2
     self.assertEqual(binfile.as_binary(), b'\x00\x01')
Ejemplo n.º 5
0
    def test_srec(self):
        binfile = bincopy.BinFile()

        with open('tests/files/in.s19', 'r') as fin:
            binfile.add_srec(fin.read())

        with open('tests/files/in.s19') as fin:
            self.assertEqual(binfile.as_srec(28, 16), fin.read())

        binfile = bincopy.BinFile()

        with open('tests/files/empty_main.s19', 'r') as fin:
            binfile.add_srec(fin.read())

        with open('tests/files/empty_main.bin', 'rb') as fin:
            self.assertEqual(binfile.as_binary(padding=b'\x00'), fin.read())

        # Add and overwrite the data.
        binfile = bincopy.BinFile()
        binfile.add_srec_file('tests/files/empty_main_rearranged.s19')
        binfile.add_srec_file('tests/files/empty_main_rearranged.s19',
                              overwrite=True)

        with open('tests/files/empty_main.bin', 'rb') as fin:
            self.assertEqual(binfile.as_binary(padding=b'\x00'), fin.read())

        with self.assertRaises(bincopy.Error) as cm:
            binfile.add_srec_file('tests/files/bad_crc.s19')

        self.assertEqual(
            str(cm.exception), "expected crc '25' in record "
            "S2144002640000000002000000060000001800000022, but got '22'")
Ejemplo n.º 6
0
def main():
    # Create data.s19.
    binfile = bincopy.BinFile()
    full, partial = divmod(0x40000, 5)
    binfile.add_binary(full * b'\x12\x34\x56\x78\x9a', 0x1d000000)
    binfile.add_binary(b'\x12\x34\x56\x78\x9a'[:partial],
                       0x1d000000 + 5 * full)
    binfile.add_binary(0x1800 * b'\x00', 0x1fc00000)

    with open('data.s19', 'w') as fout:
        fout.write(binfile.as_srec())

    # Create zeros.s19.
    binfile = bincopy.BinFile()
    binfile.add_binary(0x40000 * b'\x00', 0x1d000000)
    binfile.add_binary(0x1800 * b'\x00', 0x1fc00000)

    with open('zeros.s19', 'w') as fout:
        fout.write(binfile.as_srec())

    # Run pictools commands.
    run('programmer_ping')
    run('flash_erase_chip')
    run('ping')
    run('flash_write --chip-erase --verify data.s19')
    run('flash_read 0x1d000000 0x1000 memory.s19')
    run('flash_erase 0x1d000000 0x1000')
    run('flash_read_all memory.s19')
    run('configuration_print')
    run('device_id_print')
    run('udid_print')
    run('reset')
    run('flash_write --chip-erase zeros.s19', timed=True)
    run('flash_erase_chip')
    run('programmer_version')
Ejemplo n.º 7
0
    def test_add(self):
        binfile = bincopy.BinFile()
        with open('tests/files/in.s19', 'r') as fin:
            binfile.add(fin.read())
        with open('tests/files/in.s19') as fin:
            self.assertEqual(binfile.as_srec(28, 16), fin.read())

        binfile = bincopy.BinFile()
        with open('tests/files/in.hex', 'r') as fin:
            binfile.add(fin.read())
        with open('tests/files/in.hex') as fin:
            self.assertEqual(binfile.as_ihex(), fin.read())

        binfile = bincopy.BinFile()
        with self.assertRaises(bincopy.Error) as cm:
            binfile.add('invalid data')
        self.assertEqual(str(cm.exception), 'unsupported file format')

        binfile = bincopy.BinFile()
        with self.assertRaises(bincopy.Error) as cm:
            binfile.add('S214400420ED044000E8B7FFFFFFF4660F1F440000EE\n'
                        'invalid data')
        self.assertEqual(str(cm.exception),
                         "record 'invalid data' not starting with an 'S'")

        binfile = bincopy.BinFile()
        with self.assertRaises(bincopy.Error) as cm:
            binfile.add(':020000040040BA\n' 'invalid data')
        self.assertEqual(str(cm.exception),
                         "record 'invalid data' not starting with a ':'")
Ejemplo n.º 8
0
    def test_binary(self):
        # Add data to 0..2.
        binfile = bincopy.BinFile()
        with open('tests/files/binary1.bin', 'rb') as fin:
            binfile.add_binary(fin.read())
        with open('tests/files/binary1.bin', 'rb') as fin:
            self.assertEqual(binfile.as_binary(), fin.read())

        # Add and overwrite data to 15..179.
        binfile = bincopy.BinFile()
        binfile.add_binary_file('tests/files/binary2.bin', 15)
        binfile.add_binary_file('tests/files/binary2.bin', 15, overwrite=True)
        with self.assertRaises(bincopy.Error) as cm:
            # cannot add overlapping segments
            with open('tests/files/binary2.bin', 'rb') as fin:
                binfile.add_binary(fin.read(), 20)

        # Exclude the overlapping part and add.
        binfile.exclude(20, 1024)
        with open('tests/files/binary2.bin', 'rb') as fin:
            binfile.add_binary(fin.read(), 20)
        with open('tests/files/binary3.bin', 'rb') as fin:
            self.assertEqual(
                binfile.as_binary(minimum_address=0, padding=b'\x00'),
                fin.read())

        # Exclude first byte and read it to test adjecent add before.
        binfile.exclude(0, 1)
        binfile.add_binary(b'1')
        with open('tests/files/binary3.bin', 'rb') as fin:
            reference = b'1' + fin.read()[1:]
            self.assertEqual(
                binfile.as_binary(minimum_address=0, padding=b'\x00'),
                reference)

        # Basic checks.
        self.assertEqual(binfile.minimum_address, 0)
        self.assertEqual(binfile.maximum_address, 184)
        self.assertEqual(len(binfile), 184)

        # Dump with start address beyond end of binary.
        self.assertEqual(binfile.as_binary(minimum_address=512), b'')

        # Dump with start address one at maximum address.
        self.assertEqual(binfile.as_binary(minimum_address=184), b'')

        # Dump with start address one before maximum address.
        self.assertEqual(binfile.as_binary(minimum_address=183), b'\n')

        # Dump with start address one after minimum address.
        self.assertEqual(binfile.as_binary(minimum_address=1, padding=b'\x00'),
                         reference[1:])
Ejemplo n.º 9
0
    def test_ihex(self):
        binfile = bincopy.BinFile()
        with open('tests/files/in.hex', 'r') as fin:
            binfile.add_ihex(fin.read())
        with open('tests/files/in.hex') as fin:
            self.assertEqual(binfile.as_ihex(), fin.read())

        # Add and overwrite the data.
        binfile = bincopy.BinFile()
        binfile.add_ihex_file('tests/files/in.hex')
        binfile.add_ihex_file('tests/files/in.hex', overwrite=True)
        with open('tests/files/in.hex') as fin:
            self.assertEqual(binfile.as_ihex(), fin.read())
Ejemplo n.º 10
0
def read(ctx, address, length, size, compress, file):
    """ Read raw data from specified address in connected IMX device.
        The address value must be aligned to selected access size !
    """

    error = False
    # Create Flasher instance
    flasher = scan_usb(ctx.obj['TARGET'])

    try:
        # Connect IMX Device
        flasher.open()
        # Read data from IMX Device
        data = flasher.read(address, length, int(size))
    except Exception as e:
        error = True
        if ctx.obj['DEBUG']:
            error_msg = '\n' + traceback.format_exc()
        else:
            error_msg = ' - ERROR: %s' % str(e)

    # Disconnect IMX Device
    flasher.close()

    if not error:
        if file is None:
            if ctx.obj['DEBUG']: click.echo()
            click.echo(hexdump(data, address, compress))
        else:
            if file.lower().endswith(('.s19', '.srec')):
                srec = bincopy.BinFile()
                srec.add_binary(data, address)
                srec.header = 'imxsd'
                with open(file, "w") as f:
                    f.write(srec.as_srec())
            elif file.lower().endswith(('.hex', '.ihex')):
                ihex = bincopy.BinFile()
                ihex.add_binary(data, address)
                with open(file, "w") as f:
                    f.write(ihex.as_ihex())
            else:
                with open(file, "wb") as f:
                    f.write(data)

            if ctx.obj['DEBUG']: click.echo()
            click.secho(" - Successfully saved into: %s." % file)
    else:
        # Print Error Message and exit
        click.echo(error_msg)
        sys.exit(ERROR_CODE)
Ejemplo n.º 11
0
    def test_init_files(self):
        binfile = bincopy.BinFile('tests/files/empty_main_rearranged.s19')
        with open('tests/files/empty_main.bin', 'rb') as fin:
            self.assertEqual(binfile.as_binary(padding=b'\x00'), fin.read())

        binfile = bincopy.BinFile(['tests/files/in.hex', 'tests/files/in.hex'],
                                  overwrite=True)
        with open('tests/files/in.hex') as fin:
            self.assertEqual(binfile.as_ihex(), fin.read())

        with self.assertRaises(bincopy.Error) as cm:
            binfile = bincopy.BinFile('tests/files/hexdump.txt')

        self.assertEqual(str(cm.exception), 'unsupported file format')
Ejemplo n.º 12
0
def read_to_file(serial_connection, ranges, outfile):
    binfile = bincopy.BinFile()

    for address, size in ranges:
        left = size

        print('Reading 0x{:08x}-0x{:08x}.'.format(address, address + size))

        with tqdm(total=left, unit=' bytes') as progress:
            while left > 0:
                if left > READ_CHUNK_SIZE:
                    size = READ_CHUNK_SIZE
                else:
                    size = left

                payload = struct.pack('>II', address, size)
                binfile.add_binary(
                    execute_command(serial_connection, COMMAND_TYPE_READ,
                                    payload), address)
                address += size
                left -= size
                progress.update(size)

        print('Read complete.')

    with open(outfile, 'w') as fout:
        fout.write(binfile.as_srec())
Ejemplo n.º 13
0
    def test_flash_read(self):
        binfile = bincopy.BinFile('tests/files/test_flash_read.s19')
        flash_read_reads = []

        for _, data in binfile.segments.chunks(504):
            flash_read_reads += flash_read_read(data)

        flash_read_writes = []

        for address, data in binfile.segments.chunks(504):
            flash_read_writes.append(flash_read_write(address, len(data)))

        self.assert_command([
            'pictools', 'flash_read', '0x1d000020', '0xe80',
            'test_flash_read.s19'
        ], [
            *programmer_ping_read(), *connect_read(), *ping_read(),
            *flash_read_reads
        ], [
            programmer_ping_write(),
            connect_write(),
            ping_write(), *flash_read_writes
        ])

        with open('test_flash_read.s19', 'r') as fin:
            actual = fin.read()

        with open('tests/files/test_flash_read.s19', 'r') as fin:
            expected = fin.read()

        self.assertEqual(actual, expected)
Ejemplo n.º 14
0
    def test_i16hex(self):
        """I16HEX files use only record types 00 through 03 (20 bit
        addresses).

        """

        binfile = bincopy.BinFile()

        binfile.add_ihex(':0100000001FE\n'
                         ':01FFFF0002FF\n'
                         ':02000002FFFFFE\n'
                         ':0100000004FB\n'
                         ':01FFFF0005FC\n'
                         ':020000021000EC\n'
                         ':0100000003FC\n'
                         ':00000001FF\n')

        self.assertEqual(
            binfile.as_ihex(), ':0100000001FE\n'
            ':02FFFF000203FB\n'
            ':02000004000FEB\n'
            ':01FFF000040C\n'
            ':020000040010EA\n'
            ':01FFEF00050C\n'
            ':00000001FF\n')
        self.assertEqual(binfile.minimum_address, 0)
        self.assertEqual(binfile.maximum_address, 0x10fff0)
        self.assertEqual(binfile[0], 1)
        self.assertEqual(binfile[0xffff], 2)
        self.assertEqual(binfile[0x10000], 3)
        self.assertEqual(binfile[0xffff0], 4)
        self.assertEqual(binfile[0x10ffef], 5)
Ejemplo n.º 15
0
    def test_bad_word_size(self):
        with self.assertRaises(bincopy.Error) as cm:
            bincopy.BinFile(word_size_bits=7)

        self.assertEqual(
            str(cm.exception),
            'word size must be a multiple of 8 bits, but got 7 bits')
Ejemplo n.º 16
0
    def test_hexdump(self):
        binfile = bincopy.BinFile()
        binfile.add_binary(b'12', address=17)
        binfile.add_binary(b'34', address=26)
        binfile.add_binary(b'5678', address=30)
        binfile.add_binary(b'9', address=47)
        with open('tests/files/hexdump.txt') as fin:
            self.assertEqual(binfile.as_hexdump(), fin.read())

        binfile = bincopy.BinFile()
        binfile.add_binary(b'34', address=0x150)
        binfile.add_binary(b'3', address=0x163)
        binfile.add_binary(b'\x01', address=0x260)
        binfile.add_binary(b'3', address=0x263)
        with open('tests/files/hexdump2.txt') as fin:
            self.assertEqual(binfile.as_hexdump(), fin.read())
Ejemplo n.º 17
0
    def test_print(self):
        binfile = bincopy.BinFile()

        with open('tests/files/in.s19', 'r') as fin:
            binfile.add_srec(fin.read())

        print(binfile)
Ejemplo n.º 18
0
def main():
    parser = argparse.ArgumentParser(description='This tool converts Intel-hex file to a set of binary segments')
    parser.add_argument('-i', '--input', required=True, help='Input file in Intel-hex format')
    parser.add_argument('-o', '--output', required=True, help='Output directory path')
    parser.add_argument('-f', '--info', required=True, help='Output info file name')
    parser.add_argument('-v', '--fw_version', required=True, help='Firmware version')
    args = parser.parse_args()
    input_hex = args.input
    output_dir = args.output
    info_file_name = args.info
    fw_version = args.fw_version
    if os.path.exists(output_dir):
        if os.path.isfile(output_dir):
            print('Error: %s is a file, but it should be a dir' % output_dir, file=sys.stderr)
            sys.exit(1)
        print('Remove dir: %s' % output_dir)
        shutil.rmtree(output_dir)
    print('Create dir: %s' % output_dir)
    os.mkdir(output_dir)

    f = bincopy.BinFile()
    f.add_ihex_file(input_hex)
    print('Create: %s/%s' % (output_dir, info_file_name))
    with open('%s/%s' % (output_dir, info_file_name), 'w') as fd_info:
        fd_info.write('# %s\n' % fw_version)
        segment_num = 0
        for x in f.segments:
            segment_num += 1
            file_name = 'segment_%d.bin' % segment_num
            print('Segment %d: address 0x%08x, len %d -> %s/%s' %
                  (segment_num, x.address, len(x.data), output_dir, file_name))
            x_crc = binascii.crc32(x.data)
            fd_info.write('0x%08x %d %s 0x%08x\n' % (x.address, len(x.data), file_name, x_crc))
            with open('%s/%s' % (output_dir, file_name), 'wb') as fd_file:
                fd_file.write(x.data)
Ejemplo n.º 19
0
    def test_i32hex(self):
        """I32HEX files use only record types 00, 01, 04, and 05 (32 bit
         addresses).

        """

        binfile = bincopy.BinFile()

        binfile.add_ihex(':0100000001FE\n'
                         ':01FFFF0002FF\n'
                         ':02000004FFFFFC\n'
                         ':0100000004FB\n'
                         ':01FFFF0005FC\n'
                         ':020000040001F9\n'
                         ':0100000003FC\n'
                         ':00000001FF\n')

        self.assertEqual(
            binfile.as_ihex(), ':0100000001FE\n'
            ':02FFFF000203FB\n'
            ':02000004FFFFFC\n'
            ':0100000004FB\n'
            ':01FFFF0005FC\n'
            ':00000001FF\n')
        self.assertEqual(binfile.minimum_address, 0)
        self.assertEqual(binfile.maximum_address, 0x100000000)
        self.assertEqual(binfile[0], 1)
        self.assertEqual(binfile[0xffff], 2)
        self.assertEqual(binfile[0x10000], 3)
        self.assertEqual(binfile[0xffff0000], 4)
        self.assertEqual(binfile[0xffff0002:0xffff0004], b'\xff\xff')
        self.assertEqual(binfile[0xffffffff:0x100000000], b'\x05')
Ejemplo n.º 20
0
def parse_image_file(file_path: str) -> List[SegmentInfo]:
    """Parse image.

    :param file_path: path, where the image is stored
    :raises SPSDKError: When elf/axf files are used
    :raises SPSDKError: When binary file is used
    :raises SPSDKError: When unsupported file is used
    :return: SegmentInfo object
    """
    with open(file_path, "rb") as f:
        data = f.read(4)
    if data == b"\x7fELF":
        raise SPSDKError("Elf file is not supported")
    try:
        binfile = bincopy.BinFile(file_path)
        return [
            SegmentInfo(start=segment.address,
                        length=len(segment.data),
                        data_bin=segment.data) for segment in binfile.segments
        ]
    except UnicodeDecodeError as e:
        raise SPSDKError(
            "Error: please use write-memory command for binary file downloading."
        ) from e
    except Exception as e:
        raise SPSDKError("Error loading file") from e
Ejemplo n.º 21
0
    def test_flash_write_fast_data_packet_failure(self):
        argv = ['pictools', 'flash_write', 'test_flash_write.s19']

        chunk = bytes(range(256))
        serial.Serial.read.side_effect = [
            *programmer_ping_read(), *connect_read(), *ping_read(),
            b'\xff\xff', b'\x00\x04', b'\xff\xff\xfc\x10', b'\x49\x5b'
        ]

        with open('test_flash_write.s19', 'w') as fout:
            binfile = bincopy.BinFile()
            binfile.add_binary(chunk, 0x1d000000)
            fout.write(binfile.as_srec())

        with patch('sys.argv', argv):
            with self.assertRaises(SystemExit) as cm:
                pictools.main()

            self.assertEqual(str(cm.exception),
                             'error: 1008: flash write failed')

        expected_writes = [
            programmer_ping_write(),
            connect_write(),
            ping_write(),
            flash_write_fast_write(0x1d000000, 256, 0x3fbd, 0x54b7),
            flash_write_fast_data_write(chunk)
        ]

        self.assert_calls(serial.Serial.write.call_args_list, expected_writes)
Ejemplo n.º 22
0
    def test_srec_no_header_encoding(self):
        binfile = bincopy.BinFile(header_encoding=None)

        binfile.add_srec('S0080000018088AA90B4')

        self.assertEqual(binfile.as_srec().splitlines()[0],
                         'S0080000018088AA90B4')
Ejemplo n.º 23
0
 def _LPC_getImageInfo( self, srcAppFilename ):
     startAddress = None
     entryPointAddress = None
     lengthInByte = 0
     if os.path.isfile(srcAppFilename):
         appPath, appFilename = os.path.split(srcAppFilename)
         appName, appType = os.path.splitext(appFilename)
         srcAppFilename, appType = self.convertImageFormatToSrec(srcAppFilename, appName, appType)
         isConvSuccessed = False
         if appType.lower() in gendef.kAppImageFileExtensionList_S19:
             try:
                 srecObj = bincopy.BinFile(str(srcAppFilename))
                 startAddress = srecObj.minimum_address
                 entryPointAddress = self.getVal32FromByteArray(srecObj.as_binary(startAddress + 0x4, startAddress  + 0x8))
                 lengthInByte = len(srecObj.as_binary())
                 self._LPC_generatePlainImageBinary(srecObj.as_binary(), appName, startAddress, lengthInByte)
                 isConvSuccessed = True
             except:
                 pass
         else:
             pass
         if not isConvSuccessed:
             startAddress = None
             entryPointAddress = None
             lengthInByte = 0
             self.popupMsgBox(uilang.kMsgLanguageContentDict['genImgError_formatNotValid'][self.languageIndex] + srcAppFilename.encode('utf-8'))
     return startAddress, entryPointAddress, lengthInByte
Ejemplo n.º 24
0
    def test_set_get_item_16(self):
        binfile = bincopy.BinFile(word_size_bits=16)

        binfile.add_binary(b'\x01\x02\x03\x04', address=1)

        self.assertEqual(binfile[:], b'\x01\x02\x03\x04')

        with self.assertRaises(IndexError):
            binfile[0]

        self.assertEqual(binfile[1], 0x0102)
        self.assertEqual(binfile[2], 0x0304)

        with self.assertRaises(IndexError):
            binfile[3]

        self.assertEqual(binfile[1:3], b'\x01\x02\x03\x04')
        self.assertEqual(binfile[1:4], b'\x01\x02\x03\x04')

        binfile[1:2] = b'\x05\x06'
        self.assertEqual(binfile[:], b'\x05\x06\x03\x04')

        binfile[2:] = b'\x07\x08\x09\xa0'
        self.assertEqual(binfile[:], b'\x05\x06\x07\x08\x09\xa0')

        binfile[5] = 0x1718
        self.assertEqual(binfile[:], b'\x05\x06\x07\x08\t\xa0\xff\xff\x17\x18')
        self.assertEqual(binfile[4], 0xffff)
        self.assertEqual(binfile[4:5], b'\xff\xff')
        self.assertEqual(binfile[3:8], b'\t\xa0\xff\xff\x17\x18')
Ejemplo n.º 25
0
    def test_overwrite(self):
        binfile = bincopy.BinFile()

        # overwrite in empty file
        binfile.add_binary(b'1234', address=512, overwrite=True)
        self.assertEqual(binfile.as_binary(minimum_address=512), b'1234')

        # test setting data with multiple existing segments
        binfile.add_binary(b'123456', address=1024)
        binfile.add_binary(b'99', address=1026, overwrite=True)
        self.assertEqual(binfile.as_binary(minimum_address=512),
                         b'1234' + 508 * b'\xff' + b'129956')

        # test setting data crossing the original segment limits
        binfile.add_binary(b'abc', address=1022, overwrite=True)
        binfile.add_binary(b'def', address=1029, overwrite=True)
        self.assertEqual(binfile.as_binary(minimum_address=512),
                         b'1234' + 506 * b'\xff' + b'abc2995def')

        # overwrite a segment and write outside it
        binfile.add_binary(b'111111111111', address=1021, overwrite=True)
        self.assertEqual(binfile.as_binary(minimum_address=512),
                         b'1234' + 505 * b'\xff' + b'111111111111')

        # overwrite multiple segments (all segments in this test)
        binfile.add_binary(1024 * b'1', address=256, overwrite=True)
        self.assertEqual(binfile.as_binary(minimum_address=256), 1024 * b'1')
Ejemplo n.º 26
0
 def _RTxxx_getImageInfo(self, srcAppFilename):
     startAddress = None
     entryPointAddress = None
     lengthInByte = 0
     if os.path.isfile(srcAppFilename):
         appPath, appFilename = os.path.split(srcAppFilename)
         appName, appType = os.path.splitext(appFilename)
         srcAppFilename, appType = self.convertImageFormatToSrec(
             srcAppFilename, appName, appType)
         isConvSuccessed = False
         if appType.lower() in gendef.kAppImageFileExtensionList_S19:
             try:
                 srecObj = bincopy.BinFile(str(srcAppFilename))
                 startAddress = srecObj.minimum_address
                 initialLoadAppBytes = srecObj.as_binary(
                     startAddress,
                     startAddress + self.destAppInitialLoadSize)
                 if (self.bootDevice == RTxxx_uidef.kBootDevice_FlexspiNor
                         or self.bootDevice
                         == RTxxx_uidef.kBootDevice_QuadspiNor):
                     isSrcAppBootableImage, fdcbOffsetInApp = self._RTxxx_isSrcAppBootableImage(
                         initialLoadAppBytes)
                     if isSrcAppBootableImage:
                         self.extractFdcbDataFromSrcApp(
                             initialLoadAppBytes, fdcbOffsetInApp)
                         startAddress += RTxxx_gendef.kBootImageOffset_NOR_SD_EEPROM - (
                             self.tgt.xspiNorCfgInfoOffset -
                             fdcbOffsetInApp)
                         entryPointAddress = self.getVal32FromByteArray(
                             srecObj.as_binary(startAddress + 0x4,
                                               startAddress + 0x8))
                         lengthInByte = len(srecObj.as_binary()) - (
                             memdef.kMemBlockSize_FDCB + fdcbOffsetInApp)
                         self._RTxxx_generatePlainImageBinary(
                             srecObj.as_binary(startAddress,
                                               startAddress + lengthInByte),
                             appName, startAddress, lengthInByte)
                         isConvSuccessed = True
                 if not isConvSuccessed:
                     entryPointAddress = self.getVal32FromByteArray(
                         srecObj.as_binary(startAddress + 0x4,
                                           startAddress + 0x8))
                     lengthInByte = len(srecObj.as_binary())
                     self._RTxxx_generatePlainImageBinary(
                         srecObj.as_binary(), appName, startAddress,
                         lengthInByte)
                 isConvSuccessed = True
             except:
                 pass
         else:
             pass
         if not isConvSuccessed:
             startAddress = None
             entryPointAddress = None
             lengthInByte = 0
             self.popupMsgBox(uilang.kMsgLanguageContentDict[
                 'genImgError_formatNotValid'][self.languageIndex] +
                              srcAppFilename.encode('utf-8'))
     return startAddress, entryPointAddress, lengthInByte
Ejemplo n.º 27
0
    def test_word_size_default_padding(self):
        binfile = bincopy.BinFile(word_size_bits=16)

        with open('tests/files/in_16bits_word_padding.hex', 'r') as fin:
            binfile.add_ihex(fin.read())

        with open('tests/files/out_16bits_word_padding.bin', 'rb') as fin:
            self.assertEqual(binfile.as_binary(), fin.read())
Ejemplo n.º 28
0
    def test_header_default_encoding(self):
        binfile = bincopy.BinFile()
        binfile.add_file('tests/files/empty_main.s19')

        self.assertEqual(binfile.header, 'bincopy/empty_main.s19')

        binfile.header = 'bincopy/empty_main.s20'
        self.assertEqual(binfile.header, 'bincopy/empty_main.s20')
Ejemplo n.º 29
0
    def test_issue_4_2(self):
        binfile = bincopy.BinFile()

        with open('tests/files/empty_main.s19', 'r') as fin:
            binfile.add_srec(fin.read())

        with open('tests/files/empty_main.hex', 'r') as fin:
            self.assertEqual(binfile.as_ihex(), fin.read())
Ejemplo n.º 30
0
    def test_issue_4_1(self):
        binfile = bincopy.BinFile()

        with open('tests/files/issue_4_in.hex', 'r') as fin:
            binfile.add_ihex(fin.read())

        with open('tests/files/issue_4_out.hex', 'r') as fin:
            self.assertEqual(binfile.as_ihex(), fin.read())