code starts up

This commit is contained in:
Emil Lerch 2023-04-20 14:04:18 -07:00
parent bb81a685ed
commit 9cd262ed57
64 changed files with 12325 additions and 7154 deletions

1
.gitignore vendored
View File

@ -3,3 +3,4 @@ bin/
lib/ lib/
lib64 lib64
pyvenv.cfg pyvenv.cfg
log/

219
config.py Normal file

File diff suppressed because one or more lines are too long

View File

@ -16,45 +16,45 @@ from .base import bflb_base_eflash_loader
from .base import bflb_img_create from .base import bflb_img_create
from .base import bflb_serial from .base import bflb_serial
from .base import bflb_img_loader from .base import bflb_img_loader
from base.bl602 import flash_select_do from .base.bl602 import flash_select_do
from base.bl602 import bootheader_cfg_keys from .base.bl602 import bootheader_cfg_keys
from base.bl602 import jlink_load_cfg from .base.bl602 import jlink_load_cfg
from base.bl602 import cklink_load_cfg from .base.bl602 import cklink_load_cfg
from base.bl602 import openocd_load_cfg from .base.bl602 import openocd_load_cfg
from base.bl602 import img_create_do from .base.bl602 import img_create_do
from base.bl702 import chiptype_patch from .base.bl702 import chiptype_patch
from base.bl702 import flash_select_do from .base.bl702 import flash_select_do
from base.bl702 import bootheader_cfg_keys from .base.bl702 import bootheader_cfg_keys
from base.bl702 import jlink_load_cfg from .base.bl702 import jlink_load_cfg
from base.bl702 import cklink_load_cfg from .base.bl702 import cklink_load_cfg
from base.bl702 import openocd_load_cfg from .base.bl702 import openocd_load_cfg
from base.bl702 import img_create_do from .base.bl702 import img_create_do
from base.bl808 import chiptype_patch from .base.bl808 import chiptype_patch
from base.bl808 import flash_select_do from .base.bl808 import flash_select_do
from base.bl808 import bootheader_cfg_keys from .base.bl808 import bootheader_cfg_keys
from base.bl808 import jlink_load_cfg from .base.bl808 import jlink_load_cfg
from base.bl808 import cklink_load_cfg from .base.bl808 import cklink_load_cfg
from base.bl808 import openocd_load_cfg from .base.bl808 import openocd_load_cfg
from base.bl808 import img_create_do from .base.bl808 import img_create_do
from base.bl616 import chiptype_patch from .base.bl616 import chiptype_patch
from base.bl616 import flash_select_do from .base.bl616 import flash_select_do
from base.bl616 import bootheader_cfg_keys from .base.bl616 import bootheader_cfg_keys
from base.bl616 import jlink_load_cfg from .base.bl616 import jlink_load_cfg
from base.bl616 import cklink_load_cfg from .base.bl616 import cklink_load_cfg
from base.bl616 import openocd_load_cfg from .base.bl616 import openocd_load_cfg
from base.bl616 import img_create_do from .base.bl616 import img_create_do
from base.wb03 import chiptype_patch from .base.wb03 import chiptype_patch
from base.wb03 import flash_select_do from .base.wb03 import flash_select_do
from base.wb03 import bootheader_cfg_keys from .base.wb03 import bootheader_cfg_keys
from base.wb03 import jlink_load_cfg from .base.wb03 import jlink_load_cfg
from base.wb03 import cklink_load_cfg from .base.wb03 import cklink_load_cfg
from base.wb03 import openocd_load_cfg from .base.wb03 import openocd_load_cfg
from base.wb03 import img_create_do from .base.wb03 import img_create_do
from base.bl702l import chiptype_patch from .base.bl702l import chiptype_patch
from base.bl702l import flash_select_do from .base.bl702l import flash_select_do
from base.bl702l import bootheader_cfg_keys from .base.bl702l import bootheader_cfg_keys
from base.bl702l import jlink_load_cfg from .base.bl702l import jlink_load_cfg
from base.bl702l import cklink_load_cfg from .base.bl702l import cklink_load_cfg
from base.bl702l import openocd_load_cfg from .base.bl702l import openocd_load_cfg
from base.bl702l import img_create_do from .base.bl702l import img_create_do
# okay decompiling ./libs/__init__.pyc # okay decompiling ./libs/__init__.pyc

View File

@ -1,7 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: -
pass
# okay decompiling ./libs/base.pyc

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,241 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bflb_efuse_boothd_create.py
import os, sys, shutil, traceback
from libs import bflb_utils
from libs.bflb_utils import app_path, chip_path, convert_path
from libs.bflb_configobj import BFConfigParser
def bootheader_update_flash_pll_crc(bootheader_data, chiptype):
flash_cfg_start = 8
flash_cfg_len = 92
if chiptype == 'wb03':
flash_cfg_start += 208
flash_cfg = bootheader_data[flash_cfg_start + 4:flash_cfg_start + flash_cfg_len - 4]
crcarray = bflb_utils.get_crc32_bytearray(flash_cfg)
bootheader_data[flash_cfg_start + flash_cfg_len - 4:flash_cfg_start + flash_cfg_len] = crcarray
pll_cfg_start = flash_cfg_start + flash_cfg_len
pll_cfg_len = 16
if chiptype == 'bl808':
pll_cfg_len = 28
else:
if chiptype == 'bl616' or chiptype == 'wb03':
pll_cfg_len = 20
pll_cfg = bootheader_data[pll_cfg_start + 4:pll_cfg_start + pll_cfg_len - 4]
crcarray = bflb_utils.get_crc32_bytearray(pll_cfg)
bootheader_data[pll_cfg_start + pll_cfg_len - 4:pll_cfg_start + pll_cfg_len] = crcarray
return bootheader_data
def get_int_mask(pos, length):
ones = '11111111111111111111111111111111'
zeros = '00000000000000000000000000000000'
mask = ones[0:32 - pos - length] + zeros[0:length] + ones[0:pos]
return int(mask, 2)
def update_data_from_cfg(config_keys, config_file, section):
bflb_utils.printf('Updating data according to <' + config_file + '[' + section + ']>')
cfg = BFConfigParser()
cfg.read(config_file)
filelen = 0
for key in config_keys:
offset = int(config_keys.get(key)['offset'], 10)
if offset > filelen:
filelen = offset
filelen += 4
bflb_utils.printf('Created file len:' + str(filelen))
data = bytearray(filelen)
data_mask = bytearray(filelen)
for key in cfg.options(section):
if config_keys.get(key) is None:
bflb_utils.printf(key + ' not exist')
continue
else:
val = cfg.get(section, key)
if val.startswith('0x'):
val = int(val, 16)
else:
val = int(val, 10)
offset = int(config_keys.get(key)['offset'], 10)
pos = int(config_keys.get(key)['pos'], 10)
bitlen = int(config_keys.get(key)['bitlen'], 10)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
oldval_mask = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data_mask[offset:offset + 4]))
newval = (oldval & get_int_mask(pos, bitlen)) + (val << pos)
if val != 0:
newval_mask = oldval_mask | ~get_int_mask(pos, bitlen)
else:
newval_mask = oldval_mask
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
data_mask[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval_mask)
return (data, data_mask)
def bootheader_create_do(chipname, chiptype, config_file, section, output_file=None, if_img=False):
efuse_bootheader_path = os.path.join(chip_path, chipname, 'efuse_bootheader')
try:
bflb_utils.printf('Create bootheader using ', config_file)
sub_module = __import__(('libs.' + chiptype), fromlist=[chiptype])
bh_data, tmp = update_data_from_cfg(sub_module.bootheader_cfg_keys.bootheader_cfg_keys, config_file, section)
bh_data = bootheader_update_flash_pll_crc(bh_data, chiptype)
if output_file is None:
fp = open(efuse_bootheader_path + '/' + section.lower().replace('_cfg', '.bin'), 'wb+')
else:
fp = open(output_file, 'wb+')
if section == 'BOOTHEADER_CFG':
if chiptype == 'bl60x':
final_data = bytearray(8192)
bh_data[118] = bh_data[118] | 4
final_data[0:176] = bh_data
final_data[4096:4272] = bh_data
final_data[4098] = 65
final_data[117] = final_data[117] | 240
final_data[4214] = final_data[4214] | 3
bh_data = final_data
if if_img is True:
bh_data[8:12] = bytearray(4)
bh_data[100:104] = bytearray(4)
if chiptype == 'bl808':
fp.write(bh_data[0:384])
else:
if chiptype == 'bl616':
fp.write(bh_data[0:256])
else:
if chiptype == 'wb03':
fp.write(bh_data[0:464])
else:
if chiptype == 'bl702l':
fp.write(bh_data[0:240])
else:
fp.write(bh_data[0:176])
else:
fp.write(bh_data)
fp.close()
if chiptype == 'bl808':
if section == 'BOOTHEADER_GROUP0_CFG':
fp = open(efuse_bootheader_path + '/clock_para.bin', 'wb+')
fp.write(bh_data[100:128])
fp.close()
fp = open(efuse_bootheader_path + '/flash_para.bin', 'wb+')
fp.write(bh_data[12:96])
fp.close()
else:
if chiptype == 'bl616':
if section == 'BOOTHEADER_GROUP0_CFG':
fp = open(efuse_bootheader_path + '/clock_para.bin', 'wb+')
fp.write(bh_data[100:120])
fp.close()
fp = open(efuse_bootheader_path + '/flash_para.bin', 'wb+')
fp.write(bh_data[12:96])
fp.close()
else:
if chiptype == 'wb03':
if section == 'BOOTHEADER_GROUP0_CFG':
fp = open(efuse_bootheader_path + '/clock_para.bin', 'wb+')
fp.write(bh_data[308:328])
fp.close()
fp = open(efuse_bootheader_path + '/flash_para.bin', 'wb+')
fp.write(bh_data[220:304])
fp.close()
else:
if chiptype == 'bl702l':
if section == 'BOOTHEADER_CFG':
fp = open(efuse_bootheader_path + '/clock_para.bin', 'wb+')
fp.write(bh_data[100:116])
fp.close()
fp = open(efuse_bootheader_path + '/flash_para.bin', 'wb+')
fp.write(bh_data[12:96])
fp.close()
else:
fp = open(efuse_bootheader_path + '/flash_para.bin', 'wb+')
fp.write(bh_data[12:96])
fp.close()
except Exception as e:
try:
bflb_utils.printf('bootheader_create_do fail!!')
bflb_utils.printf(e)
traceback.print_exc(limit=5, file=(sys.stdout))
finally:
e = None
del e
def bootheader_create_process(chipname, chiptype, config_file, output_file1=None, output_file2=None, if_img=False):
fp = open(config_file, 'r')
data = fp.read()
fp.close()
if 'BOOTHEADER_CFG' in data:
bootheader_create_do(chipname, chiptype, config_file, 'BOOTHEADER_CFG', output_file1, if_img)
if 'BOOTHEADER_CPU0_CFG' in data:
bootheader_create_do(chipname, chiptype, config_file, 'BOOTHEADER_CPU0_CFG', output_file1, if_img)
if 'BOOTHEADER_CPU1_CFG' in data:
bootheader_create_do(chipname, chiptype, config_file, 'BOOTHEADER_CPU1_CFG', output_file2, if_img)
if 'BOOTHEADER_GROUP0_CFG' in data:
bootheader_create_do(chipname, chiptype, config_file, 'BOOTHEADER_GROUP0_CFG', output_file1, if_img)
if 'BOOTHEADER_GROUP1_CFG' in data:
bootheader_create_do(chipname, chiptype, config_file, 'BOOTHEADER_GROUP1_CFG', output_file2, if_img)
def efuse_create_process(chipname, chiptype, config_file, output_file=None):
efuse_bootheader_path = os.path.join(chip_path, chipname, 'efuse_bootheader')
eflash_loader_path = os.path.join(chip_path, chipname, 'eflash_loader')
filedir = ''
bflb_utils.printf('Create efuse using ', config_file)
cfgfile = eflash_loader_path + '/eflash_loader_cfg.ini'
if os.path.isfile(cfgfile) is False:
shutil.copyfile(eflash_loader_path + '/eflash_loader_cfg.conf', cfgfile)
cfg = BFConfigParser()
cfg.read(cfgfile)
sub_module = __import__(('libs.' + chiptype), fromlist=[chiptype])
efuse_data, mask = update_data_from_cfg(sub_module.efuse_cfg_keys.efuse_cfg_keys, config_file, 'EFUSE_CFG')
if output_file is None:
filedir = efuse_bootheader_path + '/efusedata.bin'
else:
filedir = output_file
fp = open(filedir, 'wb+')
fp.write(efuse_data)
fp.close()
bflb_utils.update_cfg(cfg, 'EFUSE_CFG', 'file', convert_path(os.path.relpath(filedir, app_path)))
if output_file is None:
filedir = efuse_bootheader_path + '/efusedata_mask.bin'
else:
filedir = output_file.replace('.bin', '_mask.bin')
fp = open(filedir, 'wb+')
fp.write(mask)
fp.close()
bflb_utils.update_cfg(cfg, 'EFUSE_CFG', 'maskfile', convert_path(os.path.relpath(filedir, app_path)))
cfg.write(cfgfile, 'w+')
def efuse_boothd_create_process(chipname, chiptype, config_file):
bootheader_create_process(chipname, chiptype, config_file)
efuse_create_process(chipname, chiptype, config_file)
def run():
chip_dict = {
'bl56x': 'bl60x',
'bl60x': 'bl60x',
'bl562': 'bl602',
'bl602': 'bl602',
'bl702': 'bl702',
'bl702l': 'bl702l',
'bl808': 'bl808',
'bl616': 'bl616',
'wb03': 'wb03'}
chipname = sys.argv[1]
chiptype = chip_dict[chipname]
img_create_path = os.path.join(chip_path, chipname, 'img_create_mcu')
bh_cfg_file = img_create_path + '/efuse_bootheader_cfg.ini'
bh_file = img_create_path + '/bootheader.bin'
bootheader_create_process(chipname, chiptype, bh_cfg_file, bh_file, img_create_path + '/bootheader_dummy.bin')
if __name__ == '__main__':
run()
# okay decompiling ./libs/base/bflb_efuse_boothd_create.pyc

View File

@ -0,0 +1,170 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bflb_flash_select.py
import os, re
from libs import bflb_utils
from libs.bflb_utils import app_path, chip_path, conf_sign
from libs.bflb_configobj import BFConfigParser
def get_int_mask(pos, length):
ones = '11111111111111111111111111111111'
zeros = '00000000000000000000000000000000'
mask = ones[0:32 - pos - length] + zeros[0:length] + ones[0:pos]
return int(mask, 2)
def update_flash_para_from_cfg(config_keys, config_file):
section = 'FLASH_CFG'
cfg = BFConfigParser()
cfg.read(config_file)
filelen = 0
offset = 0
minOffset = 4294967295
maxOffset = 0
flashCrcOffset = 0
crcOffset = 0
if config_keys.get('crc32') != None:
crcOffset = int(config_keys.get('crc32')['offset'], 10)
if config_keys.get('flashcfg_crc32') != None:
flashCrcOffset = int(config_keys.get('flashcfg_crc32')['offset'], 10)
for key in cfg.options(section):
if config_keys.get(key) == None:
continue
else:
offset = int(config_keys.get(key)['offset'], 10)
if offset < minOffset:
minOffset = offset
if offset > maxOffset:
maxOffset = offset
filelen = maxOffset - minOffset + 4
data = bytearray(filelen)
for key in cfg.options(section):
if config_keys.get(key) == None:
bflb_utils.printf(key + ' not exist')
continue
else:
val = cfg.get(section, key)
if val.startswith('0x'):
val = int(val, 16)
else:
val = int(val, 10)
offset = int(config_keys.get(key)['offset'], 10) - minOffset
pos = int(config_keys.get(key)['pos'], 10)
bitlen = int(config_keys.get(key)['bitlen'], 10)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = (oldval & get_int_mask(pos, bitlen)) + (val << pos)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
return (minOffset, filelen, data, flashCrcOffset, crcOffset)
def update_flash_cfg_data_do(chiptype, flash_id):
cfg_dir = app_path + '/utils/flash/' + chiptype + '/'
sub_module = __import__(('libs.base.' + chiptype), fromlist=[chiptype])
conf_name = sub_module.flash_select_do.get_suitable_file_name(cfg_dir, flash_id)
if os.path.isfile(cfg_dir + conf_name) == False:
return (None, None, None, None, None)
return update_flash_para_from_cfg(sub_module.bootheader_cfg_keys.bootheader_cfg_keys, cfg_dir + conf_name)
def flash_bootheader_config_check(chiptype, flashid, file, parafile):
magic_code = 1347307074
flash_magic_code = 1195787078
offset, flashCfgLen, data, flashCrcOffset, crcOffset = update_flash_cfg_data_do(chiptype, flashid)
if data is None:
offset = 12
flashCfgLen = 84
if parafile != '':
if data != None:
fp = open(os.path.join(app_path, parafile), 'wb')
fp.write(data)
fp.close()
fp = open(os.path.join(app_path, file), 'rb')
rdata = bytearray(fp.read())
fp.close()
i = 0
length = 128
flashCfg = bytearray(256)
while i < length:
if rdata[i:i + 4] == bflb_utils.int_to_4bytearray_l(magic_code):
if rdata[i + 8:i + 12] == bflb_utils.int_to_4bytearray_l(flash_magic_code):
if data != None:
data[2:4] = rdata[i + 14:i + 16]
flashCfg = rdata[i + offset:i + offset + flashCfgLen]
if data != None:
if not data != flashCfg and flashCfg[13:14] != b'\xff' or flashCfg[13:14] != b'\x00':
return False
else:
if flashCfg[13:14] != b'\xff':
if flashCfg[13:14] != b'\x00':
return False
i += 4
return True
def update_flash_cfg_data(chiptype, flash_id, cfg, bh_cfg_file, cfg_key):
cfg2 = BFConfigParser()
cfg2.read(bh_cfg_file)
magic_code = cfg2.get(cfg_key, 'magic_code')
magic_code = int(magic_code, 16)
flash_magic_code = cfg2.get(cfg_key, 'flashcfg_magic_code')
flash_magic_code = int(flash_magic_code, 16)
sub_module = __import__(('libs.' + chiptype), fromlist=[chiptype])
offset, flashCfgLen, data, flashCrcOffset, crcOffset = update_flash_cfg_data_do(chiptype, flash_id)
para_file = cfg.get('FLASH_CFG', 'flash_para')
if para_file != '':
fp = open(os.path.join(app_path, para_file), 'wb')
fp.write(data)
fp.close()
flash_file = re.compile('\\s+').split(cfg.get('FLASH_CFG', 'file'))
for f in flash_file:
fp = open(os.path.join(app_path, f), 'rb')
rdata = bytearray(fp.read())
fp.close()
i = 0
length = len(rdata)
while i < length:
if rdata[i:i + 4] == bflb_utils.int_to_4bytearray_l(magic_code):
if rdata[i + 8:i + 12] == bflb_utils.int_to_4bytearray_l(flash_magic_code):
data[2:4] = rdata[i + 14:i + 16]
flashCfg = rdata[i + offset:i + offset + flashCfgLen]
if data != flashCfg:
return False
i += 4
return True
def check_basic_flash_cfg(cfg_file, section):
if os.path.isfile(cfg_file) is False:
return False
cfg = BFConfigParser()
cfg.read(cfg_file)
if cfg.has_option(section, 'mfg_id'):
if cfg.get(section, 'mfg_id') == '0xff' or cfg.get(section, 'mfg_id') == '0xFF':
cfg.set(section, 'io_mode', '0x10')
cfg.set(section, 'cont_read_support', '0')
cfg.write(cfg_file, 'w+')
return True
if cfg.get(section, 'mfg_id') == '0x00':
return True
return False
def update_flash_cfg(chipname, chiptype, flash_id, file=None, create=False, section=None):
sub_module = __import__(('libs.' + chiptype), fromlist=[chiptype])
if check_basic_flash_cfg(file, section):
return True
if sub_module.flash_select_do.update_flash_cfg_do(chipname, chiptype, flash_id, file, create, section) == False:
return False
return True
def get_supported_flash(chiptype):
sub_module = __import__(('libs.' + chiptype), fromlist=[chiptype])
return sub_module.flash_select_do.get_supported_flash_do()
# okay decompiling ./libs/base/bflb_flash_select.pyc

View File

@ -0,0 +1,179 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bflb_img_create.py
import re, os, sys, time, shutil, zipfile
from libs import bflb_utils
from libs.bflb_utils import app_path, chip_path, set_error_code, convert_path
from libs.bflb_configobj import BFConfigParser
from libs.base import bflb_efuse_boothd_create
def take_second(elem):
return elem[1]
def factory_mode_set(file, value):
cfg = BFConfigParser()
cfg.read(file)
if cfg.has_option('EFUSE_CFG', 'factory_mode'):
cfg.set('EFUSE_CFG', 'factory_mode', value)
cfg.write(file, 'w')
def check_pt_file(file, addr):
if len(file) > 0:
i = 0
L = []
while i < len(file):
L.append([convert_path(file[i]), int(addr[i], 16)])
i += 1
L.sort(key=take_second)
i = 0
try:
while i < len(L) - 1:
address = L[i][1]
address_next = L[i + 1][1]
file_size = os.path.getsize(os.path.join(app_path, L[i][0]))
if address_next < address + file_size:
bflb_utils.printf('pt check fail, %s is overlayed with %s in flash layout, please check your partition table to fix this issue' % (
L[i][0], L[i + 1][0]))
return False
else:
i += 1
except Exception as e:
try:
bflb_utils.printf(e)
return False
finally:
e = None
del e
return True
def compress_dir(chipname, zippath, efuse_load=False, address=None, flash_file=None, efuse_file=None, efuse_mask_file=None):
zip_file = os.path.join(chip_path, chipname, zippath, 'whole_img.pack')
dir_path = os.path.join(chip_path, chipname, chipname)
cfg_file = os.path.join(chip_path, chipname, 'eflash_loader/eflash_loader_cfg.ini')
cfg = BFConfigParser()
cfg.read(cfg_file)
if not address:
address = []
if not flash_file:
flash_file = []
if check_pt_file(flash_file, address) is not True:
bflb_utils.printf('PT Check Fail')
set_error_code('0082')
return False
flash_file.append(os.path.join(chip_path, chipname, 'eflash_loader/eflash_loader_cfg.ini'))
if efuse_load:
if efuse_file:
flash_file.append(efuse_file)
if efuse_mask_file:
flash_file.append(efuse_mask_file)
if len(flash_file) > 0:
i = 0
try:
while i < len(flash_file):
if chip_path in flash_file[i]:
relpath = os.path.relpath(os.path.join(app_path, convert_path(flash_file[i])), chip_path)
dir = os.path.join(chip_path, chipname, relpath)
if os.path.isdir(os.path.dirname(dir)) is False:
os.makedirs(os.path.dirname(dir))
shutil.copyfile(os.path.join(app_path, convert_path(flash_file[i])), dir)
else:
relpath = os.path.relpath(os.path.join(chipname, 'img_create', os.path.basename(flash_file[i])))
dir = os.path.join(chip_path, chipname, relpath)
if os.path.isdir(os.path.dirname(dir)) is False:
os.makedirs(os.path.dirname(dir))
shutil.copyfile(flash_file[i], dir)
i += 1
verfile = os.path.join(chip_path, chipname, chipname, 'version.txt')
with open(verfile, mode='w') as f:
f.write(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
except Exception as e:
try:
bflb_utils.printf(e)
return False
finally:
e = None
del e
try:
z = zipfile.ZipFile(zip_file, 'w')
for dirpath, dirnames, filenames in os.walk(dir_path):
for file in filenames:
z.write(os.path.join(dirpath, file), os.path.relpath(os.path.join(dirpath, file), os.path.join(chip_path, chipname)))
z.close()
shutil.rmtree(dir_path)
except Exception as e:
try:
bflb_utils.printf(e)
return False
finally:
e = None
del e
return True
def img_create(args, chipname='bl60x', chiptype='bl60x', img_dir=None, config_file=None):
sub_module = __import__(('libs.' + chiptype), fromlist=[chiptype])
img_dir_path = os.path.join(chip_path, chipname, 'img_create')
if img_dir is None:
sub_module.img_create_do.img_create_do(args, img_dir_path, config_file)
else:
sub_module.img_create_do.img_create_do(args, img_dir, config_file)
def create_sp_media_image_file(config, chiptype='bl60x', cpu_type=None):
sub_module = __import__(('libs.' + chiptype), fromlist=[chiptype])
sub_module.img_create_do.create_sp_media_image(config, cpu_type)
def encrypt_loader_bin(chiptype, file, sign, encrypt, encrypt_key, encrypt_iv, publickey_file, privatekey_file):
sub_module = __import__(('libs.base.' + chiptype), fromlist=[chiptype])
return sub_module.img_create_do.encrypt_loader_bin_do(file, sign, encrypt, encrypt_key, encrypt_iv, publickey_file, privatekey_file)
def run():
parser_image = bflb_utils.image_create_parser_init()
args = parser_image.parse_args()
bflb_utils.printf('Chipname: %s' % args.chipname)
if args.chipname:
chip_dict = { 'bl56x': 'bl60x',
'bl60x': 'bl60x',
'bl562': 'bl602',
'bl602': 'bl602',
'bl702': 'bl702',
'bl702l': 'bl702l',
'bl808': 'bl808',
'bl606p': 'bl808',
'bl616': 'bl616',
'wb03': 'wb03'}
chipname = args.chipname
chiptype = chip_dict[chipname]
img_create_path = os.path.join(chip_path, chipname, 'img_create_mcu')
img_create_cfg = os.path.join(chip_path, chipname, 'img_create_mcu') + '/img_create_cfg.ini'
bh_cfg_file = img_create_path + '/efuse_bootheader_cfg.ini'
bh_file = img_create_path + '/bootheader.bin'
if args.imgfile:
imgbin = args.imgfile
cfg = BFConfigParser()
cfg.read(img_create_cfg)
cfg.set('Img_Cfg', 'segdata_file', imgbin)
cfg.write(img_create_cfg, 'w')
bflb_efuse_boothd_create.bootheader_create_process(chipname, chiptype, bh_cfg_file, bh_file, img_create_path + '/bootheader_dummy.bin')
img_create(args, chipname, chiptype, img_create_path, img_create_cfg)
else:
bflb_utils.printf('Please set chipname config, exit')
if __name__ == '__main__':
run()
# okay decompiling ./libs/base/bflb_img_create.pyc

View File

@ -0,0 +1,787 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bflb_img_loader.py
import os, sys, time, hashlib, binascii, traceback, threading
from Crypto.Cipher import AES
from libs import bflb_utils
from libs.base import bflb_img_create
from libs.base import bflb_serial
import config as gol
from libs.bflb_utils import app_path
class BflbImgLoader(object):
def __init__(self, device, speed, boot_speed, interface='uart', chip_type='bl602', chip_name='bl602', eflash_loader_file1='', eflash_loader_file2='', callback=None, do_reset=False, reset_hold_time=100, shake_hand_delay=100, reset_revert=True, cutoff_time=0, shake_hand_retry=2, isp_mode_sign=False, isp_timeout=0, encrypt_key=None, encrypt_iv=None, public_key=None, private_key=None):
self._device = device
self._speed = speed
self._interface = interface.lower()
self._chip_type = chip_type
self._chip_name = chip_name
self._eflash_loader_file1 = eflash_loader_file1
self._eflash_loader_file2 = eflash_loader_file2
self._callback = callback
self._do_reset = do_reset
self._reset_hold_time = reset_hold_time
self._shake_hand_delay = shake_hand_delay
self._reset_revert = reset_revert
self._cutoff_time = cutoff_time
self._shake_hand_retry = shake_hand_retry
self._isp_mode_sign = isp_mode_sign
self._isp_timeout = isp_timeout
self._boot_speed = boot_speed
self.encrypt_key = encrypt_key
self.encrypt_iv = encrypt_iv
self.public_key = public_key
self.private_key = private_key
self._boot_load = True
self._record_bootinfo = None
self.bflb_serial_object = None
self._imge_fp = None
self._segcnt = 0
self._602a0_dln_fix = False
self.isp_baudrate = 2000000
if interface == 'uart':
self.bflb_serial_object = bflb_serial.BLSerialUart(rts_state=True, dtr_state=True)
self._bootrom_cmds = {'get_chip_id':{'cmd_id':'05',
'data_len':'0000',
'callback':None},
'get_boot_info':{'cmd_id':'10',
'data_len':'0000',
'callback':None},
'load_boot_header':{'cmd_id':'11',
'data_len':'00b0',
'callback':None},
'808_load_boot_header':{'cmd_id':'11',
'data_len':'0160',
'callback':None},
'628_load_boot_header':{'cmd_id':'11',
'data_len':'0100',
'callback':None},
'616_load_boot_header':{'cmd_id':'11',
'data_len':'0100',
'callback':None},
'702l_load_boot_header':{'cmd_id':'11',
'data_len':'00F0',
'callback':None},
'load_publick_key':{'cmd_id':'12',
'data_len':'0044',
'callback':None},
'load_publick_key2':{'cmd_id':'13',
'data_len':'0044',
'callback':None},
'load_signature':{'cmd_id':'14',
'data_len':'0004',
'callback':None},
'load_signature2':{'cmd_id':'15',
'data_len':'0004',
'callback':None},
'load_aes_iv':{'cmd_id':'16',
'data_len':'0014',
'callback':None},
'load_seg_header':{'cmd_id':'17',
'data_len':'0010',
'callback':None},
'load_seg_data':{'cmd_id':'18',
'data_len':'0100',
'callback':None},
'check_image':{'cmd_id':'19',
'data_len':'0000',
'callback':None},
'run_image':{'cmd_id':'1a',
'data_len':'0000',
'callback':None},
'change_rate':{'cmd_id':'20',
'data_len':'0008',
'callback':None},
'reset':{'cmd_id':'21',
'data_len':'0000',
'callback':None},
'flash_erase':{'cmd_id':'30',
'data_len':'0000',
'callback':None},
'flash_write':{'cmd_id':'31',
'data_len':'0100',
'callback':None},
'flash_read':{'cmd_id':'32',
'data_len':'0100',
'callback':None},
'flash_boot':{'cmd_id':'33',
'data_len':'0000',
'callback':None},
'efuse_write':{'cmd_id':'40',
'data_len':'0080',
'callback':None},
'efuse_read':{'cmd_id':'41',
'data_len':'0000',
'callback':None}}
def close_port(self):
if self.bflb_serial_object is not None:
self.bflb_serial_object.close()
def boot_process_load_cmd(self, section, read_len):
read_data = bytearray(0)
if read_len != 0:
read_data = bytearray(self._imge_fp.read(read_len))
if len(read_data) != read_len:
bflb_utils.printf('read error,expected len=', read_len, 'read len=', len(read_data))
return bytearray(0)
if section == 'load_boot_header':
tmp = bflb_utils.bytearray_reverse(read_data[120:124])
self._segcnt = bflb_utils.bytearray_to_int(tmp)
bflb_utils.printf('segcnt is ', self._segcnt)
else:
if section == '808_load_boot_header':
tmp = bflb_utils.bytearray_reverse(read_data[140:144])
self._segcnt = bflb_utils.bytearray_to_int(tmp)
bflb_utils.printf('segcnt is ', self._segcnt)
else:
if section == '628_load_boot_header':
tmp = bflb_utils.bytearray_reverse(read_data[136:140])
self._segcnt = bflb_utils.bytearray_to_int(tmp)
bflb_utils.printf('segcnt is ', self._segcnt)
else:
if section == '616_load_boot_header':
tmp = bflb_utils.bytearray_reverse(read_data[132:136])
self._segcnt = bflb_utils.bytearray_to_int(tmp)
bflb_utils.printf('segcnt is ', self._segcnt)
else:
if section == '702l_load_boot_header':
tmp = bflb_utils.bytearray_reverse(read_data[120:124])
self._segcnt = bflb_utils.bytearray_to_int(tmp)
bflb_utils.printf('segcnt is ', self._segcnt)
if section == 'load_signature' or section == 'load_signature2':
tmp = bflb_utils.bytearray_reverse(read_data[0:4])
sig_len = bflb_utils.bytearray_to_int(tmp)
read_data = read_data + bytearray(self._imge_fp.read(sig_len + 4))
if len(read_data) != sig_len + 8:
bflb_utils.printf('read signature error,expected len=', sig_len + 4, 'read len=', len(read_data))
return read_data
def boot_process_one_cmd(self, section, cmd_id, cmd_len):
read_len = bflb_utils.bytearray_to_int(cmd_len)
read_data = self._bootrom_cmds.get(section)['callback'](section, read_len)
tmp = bytearray(2)
tmp[0] = cmd_len[1]
tmp[1] = cmd_len[0]
data_read = bytearray(0)
tmp = bflb_utils.int_to_2bytearray_l(len(read_data))
data = cmd_id + bytearray(1) + tmp + read_data
if self._chip_type == 'bl702':
if section == 'run_image':
sub_module = __import__(('libs.base.' + self._chip_type), fromlist=[self._chip_type])
data = sub_module.chiptype_patch.img_load_create_predata_before_run_img()
self.bflb_serial_object.write(data)
if section == 'get_boot_info' or section == 'load_seg_header' or section == 'get_chip_id':
res, data_read = self.bflb_serial_object.deal_response()
else:
res = self.bflb_serial_object.deal_ack()
if res.startswith('OK') is True:
pass
else:
try:
bflb_utils.printf('result: ', res)
except IOError:
bflb_utils.printf('python IO error')
return (res, data_read)
def boot_process_one_section(self, section, data_len):
cmd_id = bflb_utils.hexstr_to_bytearray(self._bootrom_cmds.get(section)['cmd_id'])
if data_len == 0:
length = bflb_utils.hexstr_to_bytearray(self._bootrom_cmds.get(section)['data_len'])
else:
length = bflb_utils.int_to_2bytearray_b(data_len)
return self.boot_process_one_cmd(section, cmd_id, length)
def boot_inf_change_rate(self, comnum, section, newrate):
cmd_id = bflb_utils.hexstr_to_bytearray(self._bootrom_cmds.get(section)['cmd_id'])
cmd_len = bflb_utils.hexstr_to_bytearray(self._bootrom_cmds.get(section)['data_len'])
bflb_utils.printf('process', section, ',cmd=', binascii.hexlify(cmd_id), ',data len=', binascii.hexlify(cmd_len))
baudrate = self.bflb_serial_object.if_get_rate()
oldv = bflb_utils.int_to_4bytearray_l(baudrate)
newv = bflb_utils.int_to_4bytearray_l(newrate)
tmp = bytearray(3)
tmp[1] = cmd_len[1]
tmp[2] = cmd_len[0]
data = cmd_id + tmp + oldv + newv
self.bflb_serial_object.if_write(data)
bflb_utils.printf()
stime = 110 / float(baudrate) * 2
if stime < 0.003:
stime = 0.003
time.sleep(stime)
self.bflb_serial_object.if_close()
self.bflb_serial_object.if_init(comnum, newrate, self._chip_type, self._chip_name)
return self.bflb_serial_object.if_deal_ack(dmy_data=False)
def boot_install_cmds_callback(self):
self._bootrom_cmds.get('get_chip_id')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('get_boot_info')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('load_boot_header')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('808_load_boot_header')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('628_load_boot_header')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('616_load_boot_header')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('702l_load_boot_header')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('load_publick_key')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('load_publick_key2')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('load_signature')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('load_signature2')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('load_aes_iv')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('load_seg_header')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('load_seg_data')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('check_image')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('run_image')['callback'] = self.boot_process_load_cmd
self._bootrom_cmds.get('reset')['callback'] = self.boot_process_load_cmd
def issue_log_print(self):
bflb_utils.printf('########################################################################')
bflb_utils.printf('请按照以下描述排查问题:')
if self._chip_type == 'bl60x':
bflb_utils.printf('GPIO24是否上拉到板子自身的3.3V而不是外部的3.3V')
bflb_utils.printf('GPIO7(RX)是否连接到USB转串口的TX引脚')
bflb_utils.printf('GPIO14(TX)是否连接到USB转串口的RX引脚')
bflb_utils.printf('在使用烧录软件进行烧录前是否在GPIO24拉高的情况下使用Reset/Chip_En复位了芯片')
else:
if self._chip_type == 'bl602':
bflb_utils.printf('GPIO8是否上拉到板子自身的3.3V而不是外部的3.3V')
bflb_utils.printf('GPIO7(RX)是否连接到USB转串口的TX引脚')
bflb_utils.printf('GPIO16(TX)是否连接到USB转串口的RX引脚')
bflb_utils.printf('在使用烧录软件进行烧录前是否在GPIO8拉高的情况下使用Reset/Chip_En复位了芯片')
else:
if self._chip_type == 'bl702':
bflb_utils.printf('GPIO28是否上拉到板子自身的3.3V而不是外部的3.3V')
bflb_utils.printf('GPIO15(RX)是否连接到USB转串口的TX引脚')
bflb_utils.printf('GPIO14(TX)是否连接到USB转串口的RX引脚')
bflb_utils.printf('在使用烧录软件进行烧录前是否在GPIO28拉高的情况下使用Reset/Chip_En复位了芯片')
else:
bflb_utils.printf('Boot pin是否上拉到板子自身的3.3V而不是外部的3.3V')
bflb_utils.printf('UART RX是否连接到USB转串口的TX引脚')
bflb_utils.printf('UART TX是否连接到USB转串口的RX引脚')
bflb_utils.printf('在使用烧录软件进行烧录前是否在Boot pin拉高的情况下使用Reset/Chip_En复位了芯片')
bflb_utils.printf('烧录软件所选择的COM口是否是连接芯片的串口')
bflb_utils.printf('烧录软件上选择的波特率是否是USB转串口支持的波特率')
bflb_utils.printf('3.3V供电是否正常')
bflb_utils.printf('板子供电电流是否正常(烧录模式下芯片耗电电流5-7mA)')
bflb_utils.printf('########################################################################')
def send_55_command(self, speed):
try:
while True:
if self._shakehand_flag is True:
break
if not self._chip_type == 'bl702' or self._chip_type == 'bl702l':
self.bflb_serial_object.write(self.get_sync_bytes(int(0.003 * speed / 10)))
else:
self.bflb_serial_object.write(self.get_sync_bytes(int(0.006 * speed / 10)))
except Exception as e:
try:
bflb_utils.printf('Error: %s' % e)
finally:
e = None
del e
def get_sync_bytes(self, length):
try:
data = bytearray(length)
i = 0
while i < length:
data[i] = 85
i += 1
return data
except Exception as e:
try:
bflb_utils.printf('Error: %s' % e)
finally:
e = None
del e
def set_isp_baudrate(self, isp_baudrate):
bflb_utils.printf('isp mode speed: ', isp_baudrate)
self.isp_baudrate = isp_baudrate
def toggle_boot_or_shake_hand(self, run_sign, do_reset=False, reset_hold_time=100, shake_hand_delay=100, reset_revert=True, cutoff_time=0, isp_mode_sign=False, isp_timeout=0, boot_load=False, shake_hand_retry=2):
"""
When run_sign is 2, it run shakehand.
"""
device = self._device
speed = self._speed
if run_sign == 2:
shake_hand_retry = shake_hand_retry
else:
if run_sign == 1:
shake_hand_retry = 1
if self.bflb_serial_object:
try:
timeout = self.bflb_serial_object.get_timeout()
blusbserialwriteflag = False
if isp_mode_sign:
if isp_timeout > 0:
wait_timeout = isp_timeout
self.bflb_serial_object.set_timeout(0.1)
self._shakehand_flag = False
cutoff_time = 0
do_reset = False
self.bflb_serial_object.repeat_init(device, self.isp_baudrate, self._chip_type, self._chip_name)
self.bflb_serial_object.write(b'\r\nispboot if\r\nreboot\r\n')
fl_thrx = None
fl_thrx = threading.Thread(target=(self.send_55_command), args=(speed,))
fl_thrx.setDaemon(True)
fl_thrx.start()
bflb_utils.printf('Please Press Reset Key!')
self.bflb_serial_object.setRTS(1)
time.sleep(0.2)
self.bflb_serial_object.setRTS(0)
time_stamp = time.time()
while time.time() - time_stamp < wait_timeout:
if self._chip_type == 'bl602' or self._chip_type == 'bl702':
self.bflb_serial_object.set_timeout(0.01)
success, ack = self.bflb_serial_object.read(3000)
if ack.find(b'Boot2 ISP Shakehand Suss') != -1:
self._shakehand_flag = True
if ack.find(b'Boot2 ISP Ready') != -1:
bflb_utils.printf('isp ready')
self.bflb_serial_object.write(bytearray.fromhex('a0000000'))
self.bflb_serial_object.set_timeout(timeout)
return 'OK'
else:
success, ack = self.bflb_serial_object.read(3000)
if ack.find(b'Boot2 ISP Ready') != -1:
bflb_utils.printf('isp ready')
self._shakehand_flag = True
if self._shakehand_flag is True:
self.bflb_serial_object.set_timeout(timeout)
tmp_timeout = self.bflb_serial_object.get_timeout()
self.bflb_serial_object.set_timeout(0.1)
if self._chip_type == 'bl602' or self._chip_type == 'bl702':
self.bflb_serial_object.set_timeout(0.5)
success, ack = self.bflb_serial_object.read(15)
self.bflb_serial_object.set_timeout(0.005)
ack += self.bflb_serial_object.read(15)[1]
self.bflb_serial_object.set_timeout(tmp_timeout)
bflb_utils.printf('read ready')
if ack.find(b'Boot2 ISP Ready') == -1:
bflb_utils.printf('Boot2 isp is not ready')
return 'FL'
self.bflb_serial_object.write(bytearray.fromhex('a0000000'))
return 'OK'
else:
while 1:
ack = self.bflb_serial_object.raw_read()
if len(ack) == 0:
break
time.sleep(0.1)
while True:
ack = self.bflb_serial_object.raw_read()
if len(ack) == 0:
break
self.bflb_serial_object.set_timeout(tmp_timeout)
break
self._shakehand_flag = True
self.bflb_serial_object.set_timeout(timeout)
self.bflb_serial_object.repeat_init(device, speed, self._chip_type, self._chip_name)
time.sleep(2.2)
if self.bflb_serial_object._is_bouffalo_chip():
if boot_load:
blusbserialwriteflag = True
while shake_hand_retry > 0:
if cutoff_time != 0 and blusbserialwriteflag is not True:
cutoff_revert = False
if cutoff_time > 1000:
cutoff_revert = True
cutoff_time = cutoff_time - 1000
self.bflb_serial_object.setRTS(1)
time.sleep(0.2)
self.bflb_serial_object.setRTS(0)
time.sleep(0.05)
self.bflb_serial_object.setRTS(1)
if cutoff_revert:
self.bflb_serial_object.setDTR(0)
else:
self.bflb_serial_object.setDTR(1)
bflb_utils.printf('tx rx and power off, press the machine!')
bflb_utils.printf('cutoff time is ', cutoff_time / 1000.0)
time.sleep(cutoff_time / 1000.0)
if cutoff_revert:
self.bflb_serial_object.setDTR(1)
else:
self.bflb_serial_object.setDTR(0)
bflb_utils.printf('power on tx and rx ')
time.sleep(0.1)
else:
if run_sign == 2:
self.bflb_serial_object.setDTR(0)
bflb_utils.printf('default set DTR high ')
time.sleep(0.1)
if do_reset is True:
if blusbserialwriteflag is not True:
self.bflb_serial_object.setRTS(0)
time.sleep(0.2)
if reset_revert:
self.bflb_serial_object.setRTS(1)
time.sleep(0.001)
reset_cnt = 2
if reset_hold_time > 1000:
reset_cnt = int(reset_hold_time // 1000)
reset_hold_time = reset_hold_time % 1000
while reset_cnt > 0:
if reset_revert:
self.bflb_serial_object.setRTS(0)
else:
self.bflb_serial_object.setRTS(1)
time.sleep(reset_hold_time / 1000.0)
if reset_revert:
self.bflb_serial_object.setRTS(1)
else:
self.bflb_serial_object.setRTS(0)
if shake_hand_delay > 0:
time.sleep(shake_hand_delay / 1000.0)
else:
time.sleep(0.005)
if reset_revert:
self.bflb_serial_object.setRTS(0)
else:
self.bflb_serial_object.setRTS(1)
time.sleep(reset_hold_time / 1000.0)
if reset_revert:
self.bflb_serial_object.setRTS(1)
else:
self.bflb_serial_object.setRTS(0)
if shake_hand_delay > 0:
time.sleep(shake_hand_delay / 1000.0)
else:
time.sleep(0.005)
reset_cnt -= 1
bflb_utils.printf('reset cnt: ' + str(reset_cnt) + ', reset hold: ' + str(reset_hold_time / 1000.0) + ', shake hand delay: ' + str(shake_hand_delay / 1000.0))
if blusbserialwriteflag:
self.bflb_serial_object.bl_usb_serial_write(cutoff_time, reset_revert)
else:
bflb_utils.printf('clean buf')
self.bflb_serial_object.set_timeout(0.1)
self.bflb_serial_object.clear_buf()
if run_sign == 1:
self.bflb_serial_object.set_timeout(timeout)
return 'OK'
if self._602a0_dln_fix:
self.bflb_serial_object.set_timeout(0.5)
else:
self.bflb_serial_object.set_timeout(0.1)
bflb_utils.printf('send sync')
if self._chip_type == 'bl702' or self._chip_type == 'bl702l':
self.bflb_serial_object.write(self.get_sync_bytes(int(0.003 * speed / 10)))
else:
self.bflb_serial_object.write(self.get_sync_bytes(int(0.006 * speed / 10)))
if self._chip_type == 'bl808':
time.sleep(0.3)
self.bflb_serial_object.write(bflb_utils.hexstr_to_bytearray('5000080038F0002000000018'))
if self._602a0_dln_fix:
time.sleep(4)
success, ack = self.bflb_serial_object.read(1000)
bflb_utils.printf('ack is ', binascii.hexlify(ack))
if ack.find(b'O') != -1 or ack.find(b'K') != -1:
self.bflb_serial_object.set_timeout(timeout)
if self._602a0_dln_fix:
self.bflb_serial_object.write(bytearray(2))
time.sleep(0.03)
return 'OK'
if len(ack) != 0:
bflb_utils.printf('reshake')
if do_reset is False:
bflb_utils.printf('sleep')
time.sleep(3)
else:
bflb_utils.printf('retry')
shake_hand_retry -= 1
self.bflb_serial_object.set_timeout(timeout)
return 'FL'
except Exception as e:
try:
bflb_utils.printf('Error: %s' % e)
finally:
e = None
del e
else:
return 'FL'
def img_load_shake_hand(self, sh_baudrate, wk_baudrate, do_reset=False, reset_hold_time=100, shake_hand_delay=100, reset_revert=True, cutoff_time=0, shake_hand_retry=2, isp_mode_sign=False, isp_timeout=0, boot_load=True):
self.bflb_serial_object.repeat_init(self._device, sh_baudrate, self._chip_type, self._chip_name)
self.boot_install_cmds_callback()
if self._chip_type == 'wb03':
self.toggle_boot_or_shake_hand(1, do_reset, reset_hold_time, shake_hand_delay, reset_revert, cutoff_time, isp_mode_sign, isp_timeout, boot_load)
bflb_utils.printf('get_chip_id')
ret, data_read = self.boot_process_one_section('get_chip_id', 0)
if ret.startswith('OK') is False:
bflb_utils.printf('fail')
return (
ret, None)
data_read = binascii.hexlify(data_read)
bflb_utils.printf('data read is ', data_read)
chip_id = data_read.decode('utf-8')
if chip_id != '43484950574230334130305f424c0000':
if chip_id != '43484950574230334130305F424C0000':
return 'shake hand fail'
else:
if self._chip_type == 'bl602':
self._602a0_dln_fix = False
ret = self.toggle_boot_or_shake_hand(2, do_reset, reset_hold_time, shake_hand_delay, reset_revert, cutoff_time, isp_mode_sign, isp_timeout, boot_load, shake_hand_retry)
if self._chip_type == 'bl602':
self._602a0_dln_fix = False
if ret != 'OK':
bflb_utils.printf('shake hand fail')
self.issue_log_print()
bflb_utils.set_error_code('0050')
return 'shake hand fail'
if sh_baudrate != wk_baudrate:
if self.boot_inf_change_rate(self._device, 'change_rate', wk_baudrate) != 'OK':
bflb_utils.printf('change rate fail')
return 'change rate fail'
bflb_utils.printf('shake hand success')
return ret
def img_load_main_process(self, file, group, record_bootinfo=None):
encrypt_blk_size = 16
bflb_utils.printf('get_boot_info')
ret, data_read = self.boot_process_one_section('get_boot_info', 0)
if ret.startswith('OK') is False:
bflb_utils.printf('fail')
return (
ret, None)
data_read = binascii.hexlify(data_read)
bflb_utils.printf('data read is ', data_read)
bootinfo = data_read.decode('utf-8')
chipid = ''
if self._chip_type == 'bl702' or self._chip_type == 'bl702l':
chipid = bootinfo[32:34] + bootinfo[34:36] + bootinfo[36:38] + bootinfo[38:40] + bootinfo[40:42] + bootinfo[42:44] + bootinfo[44:46] + bootinfo[46:48]
else:
chipid = bootinfo[34:36] + bootinfo[32:34] + bootinfo[30:32] + bootinfo[28:30] + bootinfo[26:28] + bootinfo[24:26]
bflb_utils.printf('========= ChipID: ', chipid, ' =========')
bflb_utils.printf('last boot info: ', record_bootinfo)
if record_bootinfo != None:
if bootinfo[8:] == record_bootinfo[8:]:
bflb_utils.printf('repeated chip')
return (
'repeat_burn', bootinfo)
if bootinfo[:8] == 'FFFFFFFF' or bootinfo[:8] == 'ffffffff':
bflb_utils.printf('eflash loader present')
return (
'error_shakehand', bootinfo)
sign = 0
encrypt = 0
if self._chip_type == 'bl60x':
sign = int(data_read[8:10], 16) & 3
encrypt = (int(data_read[8:10], 16) & 12) >> 2
else:
if self._chip_type == 'bl602' or self._chip_type == 'bl702' or self._chip_type == 'bl702l':
sign = int(data_read[8:10], 16)
encrypt = int(data_read[10:12], 16)
else:
if self._chip_type == 'bl808' or self._chip_type == 'bl628':
if group == 0:
sign = int(data_read[8:10], 16)
encrypt = int(data_read[12:14], 16)
else:
sign = int(data_read[10:12], 16)
encrypt = int(data_read[14:16], 16)
else:
sign = int(data_read[8:10], 16)
encrypt = int(data_read[10:12], 16)
bflb_utils.printf('sign is ', sign, ' encrypt is ', encrypt)
if encrypt == 1 or sign == 1:
if encrypt == 1 and self.encrypt_key != None and self.encrypt_iv != None and sign == 1 and self.encrypt_key != None and self.private_key != None:
ret, encrypted_data = bflb_img_create.encrypt_loader_bin(self._chip_type, file, sign, encrypt, self.encrypt_key, self.encrypt_iv, self.public_key, self.private_key)
else:
if encrypt == 1and self.encrypt_key != None and self.encrypt_key != None and sign == 0:
ret, encrypted_data = bflb_img_create.encrypt_loader_bin(self._chip_type, file, sign, encrypt, self.encrypt_key, self.encrypt_iv, self.public_key, self.private_key)
else:
if encrypt == 0and sign == 1 and sign == 1 and self.private_key != None:
ret, encrypted_data = bflb_img_create.encrypt_loader_bin(self._chip_type, file, sign, encrypt, self.encrypt_key, self.encrypt_iv, self.public_key, self.private_key)
else:
if encrypt == 1 and sign == 1:
bflb_utils.printf('Error: Aes-encrypt and ecc-signature is None!')
else:
if encrypt == 1 and sign == 0:
bflb_utils.printf('Error: Aes-encrypt is None!')
else:
if encrypt == 0:
if sign == 1:
bflb_utils.printf('Error: Ecc-signature is None!')
return (
'', bootinfo)
if ret == True:
filename, ext = os.path.splitext(file)
file_encrypt = filename + '_encrypt' + ext
fp = open(file_encrypt, 'wb')
fp.write(encrypted_data)
fp.close()
self._imge_fp = open(file_encrypt, 'rb')
else:
file = os.path.join(bflb_utils.app_path, file)
self._imge_fp = open(file, 'rb')
else:
file = os.path.join(bflb_utils.app_path, file)
self._imge_fp = open(file, 'rb')
if self._chip_type == 'wb03':
self._imge_fp.read(208)
if self._chip_type == 'bl808':
ret, dmy = self.boot_process_one_section('808_load_boot_header', 0)
else:
if self._chip_type == 'bl628':
ret, dmy = self.boot_process_one_section('628_load_boot_header', 0)
else:
if self._chip_type == 'bl616' or self._chip_type == 'wb03':
ret, dmy = self.boot_process_one_section('616_load_boot_header', 0)
else:
if self._chip_type == 'bl702l':
ret, dmy = self.boot_process_one_section('702l_load_boot_header', 0)
else:
ret, dmy = self.boot_process_one_section('load_boot_header', 0)
if ret.startswith('OK') is False:
return (ret, bootinfo)
if sign != 0:
ret, dmy = self.boot_process_one_section('load_publick_key', 0)
if ret.startswith('OK') is False:
return (ret, bootinfo)
if self._chip_type == 'bl60x' or self._chip_type == 'bl808' or self._chip_type == 'bl628':
ret, dmy = self.boot_process_one_section('load_publick_key2', 0)
if ret.startswith('OK') is False:
return (ret, bootinfo)
ret, dmy = self.boot_process_one_section('load_signature', 0)
if ret.startswith('OK') is False:
return (ret, bootinfo)
if self._chip_type == 'bl60x' or self._chip_type == 'bl808' or self._chip_type == 'bl628':
ret, dmy = self.boot_process_one_section('load_signature2', 0)
if ret.startswith('OK') is False:
return (ret, bootinfo)
if encrypt != 0:
ret, dmy = self.boot_process_one_section('load_aes_iv', 0)
if ret.startswith('OK') is False:
return (ret, bootinfo)
segs = 0
while segs < self._segcnt:
send_len = 0
segdata_len = 0
ret, data_read = self.boot_process_one_section('load_seg_header', 0)
if ret.startswith('OK') is False:
return (ret, bootinfo)
else:
tmp = bflb_utils.bytearray_reverse(data_read[4:8])
segdata_len = bflb_utils.bytearray_to_int(tmp)
bflb_utils.printf('segdata_len is ', segdata_len)
if encrypt == 1:
if segdata_len % encrypt_blk_size != 0:
segdata_len = segdata_len + encrypt_blk_size - segdata_len % encrypt_blk_size
while send_len < segdata_len:
left = segdata_len - send_len
if left > 4080:
left = 4080
ret, dmy = self.boot_process_one_section('load_seg_data', left)
if ret.startswith('OK') is False:
return (ret, bootinfo)
send_len = send_len + left
bflb_utils.printf(send_len, '/', segdata_len)
if self._callback is not None:
self._callback(send_len, segdata_len, sys._getframe().f_code.co_name)
segs = segs + 1
ret, dmy = self.boot_process_one_section('check_image', 0)
return (
ret, bootinfo)
def img_get_bootinfo(self, sh_baudrate, wk_baudrate, callback=None, do_reset=False, reset_hold_time=100, shake_hand_delay=100, reset_revert=True, cutoff_time=0, shake_hand_retry=2, isp_mode_sign=False, isp_timeout=0, boot_load=True):
bflb_utils.printf('========= image get bootinfo =========')
ret = self.img_load_shake_hand(sh_baudrate, wk_baudrate, do_reset, reset_hold_time, shake_hand_delay, reset_revert, cutoff_time, shake_hand_retry, isp_mode_sign, isp_timeout, boot_load)
if ret == 'shake hand fail' or ret == 'change rate fail':
bflb_utils.printf('shake hand fail')
self.bflb_serial_object.close()
return (False, b'')
time.sleep(0.5)
ret, data_read = self.boot_process_one_section('get_boot_info', 0)
if ret.startswith('OK') is False:
bflb_utils.printf('get_boot_info no ok')
return (
ret, b'')
data_read = binascii.hexlify(data_read)
bflb_utils.printf('data read is ', data_read)
return (
True, data_read)
def img_loader_reset_cpu(self):
bflb_utils.printf('========= reset cpu =========')
ret, data_read = self.boot_process_one_section('reset', 0)
if ret.startswith('OK') is False:
bflb_utils.printf('reset cpu fail')
return False
return True
def img_load_process(self, sh_baudrate, wk_baudrate, callback=None, do_reset=False, reset_hold_time=100, shake_hand_delay=100, reset_revert=True, cutoff_time=0, shake_hand_retry=2, isp_mode_sign=False, isp_timeout=0, boot_load=True, record_bootinfo=None):
bflb_utils.printf('========= image load =========')
success = True
bootinfo = None
try:
ret = self.img_load_shake_hand(sh_baudrate, wk_baudrate, do_reset, reset_hold_time, shake_hand_delay, reset_revert, cutoff_time, shake_hand_retry, isp_mode_sign, isp_timeout, boot_load)
if ret == 'shake hand fail' or ret == 'change rate fail':
bflb_utils.printf('shake hand fail')
self.bflb_serial_object.close()
return (
False, bootinfo, ret)
time.sleep(0.01)
if self._eflash_loader_file1 is not None:
if self._eflash_loader_file1 != '':
res, bootinfo = self.img_load_main_process(self._eflash_loader_file1, 0, record_bootinfo)
if res.startswith('OK') is False:
if res.startswith('repeat_burn') is True:
return (False, bootinfo, res)
bflb_utils.printf('Img load fail')
if res.startswith('error_shakehand') is True:
bflb_utils.printf('shakehand with eflash loader found')
return (False, bootinfo, res)
if self._eflash_loader_file2 is not None:
if self._eflash_loader_file2 != '':
res, bootinfo = self.img_load_main_process(self._eflash_loader_file2, 1, record_bootinfo)
if res.startswith('OK') is False:
if res.startswith('repeat_burn') is True:
return (False, bootinfo, res)
bflb_utils.printf('Img load fail')
if res.startswith('error_shakehand') is True:
bflb_utils.printf('shakehand with eflash loader found')
return (False, bootinfo, res)
bflb_utils.printf('Run img')
self._imge_fp.close()
res, dmy = self.boot_process_one_section('run_image', 0)
if res.startswith('OK') is False:
bflb_utils.printf('Img run fail')
success = False
time.sleep(0.1)
except Exception as e:
try:
bflb_utils.printf(e)
traceback.print_exc(limit=5, file=(sys.stdout))
return (
False, bootinfo, '')
finally:
e = None
del e
return (
success, bootinfo, '')
if __name__ == '__main__':
img_load_t = BflbImgLoader()
if len(sys.argv) == 3:
img_load_t.img_load_process(sys.argv[1], 115200, 115200, sys.argv[2], '')
else:
if len(sys.argv) == 4:
img_load_t.img_load_process(sys.argv[1], 115200, 115200, sys.argv[2], sys.argv[3])
# okay decompiling ./libs/base/bflb_img_loader.pyc

714
libs/base/bflb_serial.py Normal file
View File

@ -0,0 +1,714 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bflb_serial.py
__doc__ = '\nCreated on 20220830\n\n@author: Dillon\n'
import re, os, sys, time, serial, struct, pylink, cklink, subprocess
from glob import glob
from libs.bflb_utils import *
from serial.tools.list_ports import comports
import config as gol
class BLSerialUart(object):
__doc__ = '\n Bouffalolab serial package\n '
def __init__(self, rts_state=False, dtr_state=False):
self._device = 'COM1'
self._baudrate = 115200
self._isp_baudrate = 2000000
self._ser = None
self._shakehand_flag = False
self._chiptype = 'bl602'
self.rts_state = rts_state
self.dtr_state = dtr_state
def repeat_init(self, device, rate=0, _chip_type='bl602', _chip_name='bl602'):
try:
if not rate:
rate = self._isp_baudrate
if self._ser is None:
self._baudrate = rate
if ' (' in device:
dev = device[:device.find(' (')]
else:
dev = device
self._device = dev.upper()
for i in range(3):
try:
self._ser = serial.Serial(dev, rate, timeout=2.0, xonxoff=False, rtscts=False, write_timeout=None, dsrdtr=False)
except Exception as error:
try:
printf(error)
time.sleep(1)
finally:
error = None
del error
else:
break
else:
self._ser.baudrate = rate
self._baudrate = rate
self._602a0_dln_fix = False
self._chiptype = _chip_type
self._chipname = _chip_name
except Exception as e:
try:
printf('Error: %s' % e)
finally:
e = None
del e
def write(self, message):
if self._ser:
self._ser.write(message)
def read(self, length=1):
try:
data = bytearray(0)
received = 0
while received < length:
tmp = self._ser.read(length - received)
if len(tmp) == 0:
break
else:
data += tmp
received += len(tmp)
if len(data) != length:
return (0, data)
return (1, data)
except Exception as e:
try:
printf('Error: %s' % e)
finally:
e = None
del e
def raw_read(self):
return self._ser.read(self._ser.in_waiting or 1)
def clear_buf(self):
if self._ser:
self._ser.read_all()
def close(self):
if self._ser:
self._ser.close()
def _is_bouffalo_chip(self):
bl_sign = False
if sys.platform.startswith('win'):
for port, data, info in comports():
if not port:
continue
if self._device.upper() == port.upper():
if not 'VID:PID=42BF:B210' in info.upper():
if 'VID:PID=FFFF:FFFF' in info.upper():
pass
bl_sign = True
break
else:
if sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
ports = []
for port, data, info in comports():
if not port:
continue
if self._device.upper() == port.upper():
if not 'PID=FFFF' in info.upper():
if 'PID=42BF:B210' in info.upper():
pass
bl_sign = True
break
return bl_sign
def bl_usb_serial_write(self, cutoff_time, reset_revert):
try:
boot_revert = 0
printf('usb serial port')
if cutoff_time != 0:
boot_revert = 0
if cutoff_time > 1000:
boot_revert = 1
data = bytearray()
specialstr = string_to_bytearray('BOUFFALOLAB5555RESET')
for b in specialstr:
data.append(b)
data.append(boot_revert)
data.append(reset_revert)
self._ser.write(data)
time.sleep(0.05)
except Exception as e:
try:
printf('Error: %s' % e)
finally:
e = None
del e
def set_dtr(self, dtr):
"""
dtr: If dtr is 1, it shows high. If dtr is 0, it shows low.
"""
try:
if sys.platform.startswith('darwin'):
self._ser.write(b'BOUFFALOLAB5555DTR' + str(dtr).encode())
self.clear_buf()
if dtr == 1:
self._ser.setDTR(0)
else:
if dtr == 0:
self._ser.setDTR(1)
else:
bl_sign = self._is_bouffalo_chip()
if bl_sign:
self._ser.write(b'BOUFFALOLAB5555DTR' + str(dtr).encode())
else:
if dtr == 1:
self._ser.setDTR(0)
else:
if dtr == 0:
self._ser.setDTR(1)
except:
pass
def setDTR(self, dtr):
self._ser.setDTR(dtr)
def set_rts(self, rts):
"""
rts: If rts is 1, it shows high. If rts is 0, it shows low.
"""
try:
if sys.platform.startswith('darwin'):
self._ser.write(b'BOUFFALOLAB5555RTS' + str(rts).encode())
self.clear_buf()
if rts == 1:
self._ser.setRTS(0)
else:
if rts == 0:
self._ser.setRTS(1)
else:
bl_sign = self._is_bouffalo_chip()
if bl_sign:
self._ser.write(b'BOUFFALOLAB5555RTS' + str(rts).encode())
else:
if rts == 1:
self._ser.setRTS(0)
else:
if rts == 0:
self._ser.setRTS(1)
except:
pass
def setRTS(self, rts):
self._ser.setRTS(rts)
def reset(self):
if sys.platform.startswith('darwin'):
self._ser.write(b'BOUFFALOLAB5555DTR0')
time.sleep(0.05)
self._ser.write(b'BOUFFALOLAB5555RTS0')
time.sleep(0.05)
self._ser.write(b'BOUFFALOLAB5555RTS1')
self.clear_buf()
self._ser.setDTR(1)
time.sleep(0.05)
self._ser.setRTS(1)
time.sleep(0.05)
self._ser.setRTS(0)
else:
bl_sign = self._is_bouffalo_chip()
if bl_sign:
self._ser.write(b'BOUFFALOLAB5555DTR0')
time.sleep(0.05)
self._ser.write(b'BOUFFALOLAB5555RTS0')
time.sleep(0.05)
self._ser.write(b'BOUFFALOLAB5555RTS1')
else:
self._ser.setDTR(1)
time.sleep(0.05)
self._ser.setRTS(1)
time.sleep(0.05)
self._ser.setRTS(0)
def set_isp_baudrate(self, baudrate):
printf('isp mode speed: ', baudrate)
self._isp_baudrate = baudrate
def set_timeout(self, timeout):
self._ser.timeout = timeout
def get_timeout(self):
return self._ser.timeout
def deal_ack(self):
try:
success, ack = self.read(2)
if success == 0:
printf('ack is ', str(binascii.hexlify(ack)))
return ack.decode('utf-8')
if ack.find(b'O') != -1 or ack.find(b'K') != -1:
return 'OK'
if ack.find(b'P') != -1 or ack.find(b'D') != -1:
return 'PD'
success, err_code = self.read(2)
if success == 0:
printf('err code is ', str(binascii.hexlify(err_code)))
return 'FL'
err_code_str = str(binascii.hexlify(err_code[1:2] + err_code[0:1]).decode('utf-8'))
ack = 'FL'
try:
ret = ack + err_code_str + '(' + get_bflb_error_code(err_code_str) + ')'
except Exception as e:
try:
printf(e)
ret = ack + err_code_str + ' unknown'
finally:
e = None
del e
printf(ret)
return ret
except Exception as e:
try:
printf('Error: %s' % e)
finally:
e = None
del e
def deal_response(self):
try:
ack = self.deal_ack()
if ack == 'OK':
success, len_bytes = self.read(2)
if success == 0:
printf('Get length error')
printf('len error is ', binascii.hexlify(len_bytes))
return (
'Get length error', len_bytes)
tmp = bytearray_reverse(len_bytes)
data_len = bytearray_to_int(tmp)
success, data_bytes = self.read(data_len)
if success == 0 or len(data_bytes) != data_len:
printf('Read data error,maybe not get excepted length')
return (
'Read data error,maybe not get excepted length', data_bytes)
return (
ack, data_bytes)
printf('Not ack OK')
printf(ack)
return (
ack, None)
except Exception as e:
try:
printf('Error: %s' % e)
finally:
e = None
del e
class BLSerialJLink(object):
def __init__(self, device, speed, jlink_shake_hand_addr, jlink_data_addr, jlink_set_tif, jlink_core_type, jlink_run_addr):
self.device = device
self.speed = speed
self.jlink_shake_hand_addr = jlink_shake_hand_addr
self.jlink_data_addr = jlink_data_addr
self.jlink_run_addr = jlink_run_addr
self._rx_timeout = 10000
self._chiptype = 'bl602'
if sys.platform == 'win32':
obj_dll = pylink.Library(dllpath=path_dll)
self._jlink = pylink.JLink(lib=obj_dll)
self.jlink_path = os.path.join(app_path, 'utils/jlink', 'JLink.exe')
else:
self._jlink = pylink.JLink()
self.jlink_path = 'JLinkExe'
match = re.search('\\d{8,10}', device, re.I)
if match is not None:
self._jlink.open(serial_no=(int(self.device)))
else:
self._jlink.open()
self._jlink.set_tif(jlink_set_tif)
self._jlink.connect(jlink_core_type, self.speed)
def set_chip_type(self, chiptype):
self._chiptype = chiptype
def write(self, message):
self.raw_write(self.jlink_data_addr, message)
data_list = []
data_list.append(int('59445248', 16))
self._jlink.memory_write((int(self.jlink_shake_hand_addr, 16)), data_list, nbits=32)
def raw_write(self, addr, data_send):
addr_int = int(addr, 16)
len2 = len(data_send) % 4
len1 = len(data_send) - len2
if len1 != 0:
data_list = []
for i in range(int(len1 / 4)):
data_list.append(data_send[4 * i] + (data_send[4 * i + 1] << 8) + (data_send[4 * i + 2] << 16) + (data_send[4 * i + 3] << 24))
self._jlink.memory_write(addr_int, data_list, nbits=32)
if len2 != 0:
data_list = []
for i in range(len2):
data_list.append(data_send[len1 + i])
self._jlink.memory_write((addr_int + len1), data_list, nbits=8)
def raw_write_8(self, addr, data_send):
data_list = []
for data in data_send:
data_list.append(data)
self._jlink.memory_write((int(addr, 16)), data_list, nbits=8)
def raw_write_16(self, addr, data_send):
data_list = []
for i in range(int(len(data_send) / 2)):
data_list.append(data_send[2 * i] + (data_send[2 * i + 1] << 8))
self._jlink.memory_write((int(addr, 16)), data_list, nbits=16)
def raw_write_32(self, addr, data_send):
data_list = []
for i in range(int(len(data_send) / 4)):
data_list.append(data_send[4 * i] + (data_send[4 * i + 1] << 8) + (data_send[4 * i + 2] << 16) + (data_send[4 * i + 3] << 24))
self._jlink.memory_write((int(addr, 16)), data_list, nbits=32)
def read(self, length):
start_time = time.time() * 1000
while True:
ready = self._jlink.memory_read((int(self.jlink_shake_hand_addr, 16)), 1, nbits=32)
if len(ready) >= 1:
if ready[0] == int('4B434153', 16):
break
elapsed = time.time() * 1000 - start_time
if elapsed >= self._rx_timeout:
return 'waiting response time out'.encode('utf-8')
else:
time.sleep(0.001)
data = self._raw_read(self.jlink_data_addr, length)
if len(data) != length:
return (0, data)
return (1, data)
def _raw_read(self, addr, data_len):
addr_int = int(addr, 16)
if addr_int % 4 == 0:
len2 = data_len % 4
len1 = data_len - len2
data1 = bytearray(0)
data2 = bytearray(0)
if len1 != 0:
data1 = self._jlink.memory_read(addr_int, (int(len1 / 4)), nbits=32)
if len2 != 0:
data2 = self._jlink.memory_read((addr_int + len1), len2, nbits=8)
data = bytearray(0)
for tmp in data1:
data += int_to_4bytearray_l(tmp)
data += bytearray(data2)
return data
return self._raw_read8(addr, data_len)
def _raw_read8(self, addr, data_len):
data = self._jlink.memory_read((int(addr, 16)), data_len, nbits=8)
return bytearray(data)
def _raw_read16(self, addr, data_len):
raw_data = self._jlink.memory_read((int(addr, 16)), (data_len / 2), nbits=16)
data = bytearray(0)
for tmp in raw_data:
data += int_to_2bytearray_l(tmp)
return bytearray(data)
def _raw_read32(self, addr, data_len):
raw_data = self._jlink.memory_read((int(addr, 16)), (data_len / 4), nbits=32)
data = bytearray(0)
for tmp in raw_data:
data += int_to_4bytearray_l(tmp)
return bytearray(data)
def set_rx_timeout(self, val):
self._rx_timeout = val * 1000
def halt_cpu(self):
if self._jlink.halted() is False:
self._jlink.halt()
if self._jlink.halted():
return True
printf("couldn't halt cpu")
return False
def reset_cpu(self, ms=0, halt=True):
if self._chiptype != 'bl60x':
self._jlink.set_reset_pin_low()
self._jlink.set_reset_pin_high()
return self._jlink.reset(ms, False)
def set_pc_msp(self, pc, msp):
if self._jlink.halted() is False:
self._jlink.halt()
if self._jlink.halted():
if self._chiptype == 'bl602' or self._chiptype == 'bl702' or self._chiptype == 'bl702l':
jlink_script = 'jlink.cmd'
fp = open(jlink_script, 'w+')
cmd = 'h\r\nSetPC ' + str(self._jlink_run_addr) + '\r\nexit'
printf(cmd)
fp.write(cmd)
fp.close()
if self._device:
jlink_cmd = self.jlink_path + ' -device RISC-V -Speed {0} -SelectEmuBySN {1} -IF JTAG -jtagconf -1,-1 -autoconnect 1 -CommanderScript jlink.cmd'.format(str(self._speed), str(self._device))
else:
jlink_cmd = self.jlink_path + ' -device RISC-V -Speed {0} -IF JTAG -jtagconf -1,-1 -autoconnect 1 -CommanderScript jlink.cmd'.format(str(self._speed))
printf(jlink_cmd)
p = subprocess.Popen(jlink_cmd, shell=True, stdin=(subprocess.PIPE), stdout=(subprocess.PIPE), stderr=(subprocess.PIPE))
out, err = p.communicate()
printf(out, err)
os.remove(jlink_script)
else:
self._jlink.register_write(15, int(pc, 16))
self._jlink.register_write(13, int(msp, 16))
self._jlink.restart()
else:
printf("couldn't halt cpu")
def shakehand(self, do_reset=False, reset_hold_time=100, shake_hand_delay=100, reset_revert=True, cutoff_time=0, shake_hand_retry=2, isp_timeout=0, boot_load=False):
self.write(bytearray(1))
success, ack = self.if_read(2)
printf(binascii.hexlify(ack))
if ack.find(b'O') != -1 or ack.find(b'K') != -1:
time.sleep(0.03)
return 'OK'
return 'FL'
def deal_ack(self):
success, ack = self.read(2)
if success == 0:
printf('ack:' + str(binascii.hexlify(ack)))
return ack.decode('utf-8')
if ack.find(b'O') != -1 or ack.find(b'K') != -1:
return 'OK'
if ack.find(b'P') != -1 or ack.find(b'D') != -1:
return 'PD'
success, err_code = self.read(4)
if success == 0:
printf('err_code:' + str(binascii.hexlify(err_code)))
return 'FL'
err_code_str = str(binascii.hexlify(err_code[3:4] + err_code[2:3]).decode('utf-8'))
ack = 'FL'
try:
ret = ack + err_code_str + '(' + get_bflb_error_code(err_code_str) + ')'
except Exception:
ret = ack + err_code_str + ' unknown'
printf(ret)
return ret
def deal_response(self):
ack = self.if_deal_ack()
if ack == 'OK':
success, len_bytes = self.read(4)
if success == 0:
printf('Get length error')
printf(binascii.hexlify(len_bytes))
return (
'Get length error', len_bytes)
tmp = bytearray_reverse(len_bytes[2:4])
data_len = bytearray_to_int(tmp)
success, data_bytes = self.read(data_len + 4)
if success == 0:
printf('Read data error')
return (
'Read data error', data_bytes)
data_bytes = data_bytes[4:]
if len(data_bytes) != data_len:
printf('Not get excepted length')
return (
'Not get excepted length', data_bytes)
return (ack, data_bytes)
printf('Not ack OK')
printf(ack)
return (
ack, None)
def close(self):
self._jlink.close()
class BLSerialCKLink(object):
def __init__(self, device, serial, speed, rx_timeout, cklink_shake_hand_addr='20000000', cklink_data_addr='20000004', cklink_run_addr='22010000'):
self.device = device
self.serial = serial
self._speed = speed
self._rx_timeout = rx_timeout
self._inited = False
self._cklink_reg_pc = 32
self._cklink_shake_hand_addr = cklink_shake_hand_addr
self._cklink_data_addr = cklink_data_addr
self._cklink_run_addr = cklink_run_addr
self._chiptype = 'bl602'
self.link = gol.obj_cklink
self.temp_init()
def temp_init(self):
if self._inited is False:
dev = self.device.split('|')
vid = int(dev[0].replace('0x', ''), 16)
pid = int(dev[1].replace('0x', ''), 16)
printf('SN is ' + str(self.serial))
self._cklink_vid = vid
self._cklink_pid = pid
self._inited = True
if not self.link:
self.link = cklink.CKLink(dlldir=cklink_dll, vid=(self._cklink_vid), pid=(self._cklink_pid), sn=serial, arch=2, cdi=0)
gol.obj_cklink = self.link
self.link.open()
if self.link.connected():
self.link.reset(1)
return False
def set_chip_type(self, chiptype):
self._chiptype = chiptype
def set_rx_timeout(self, val):
self._rx_timeout = val * 1000
def halt_cpu(self):
return self.link.halt()
def resume_cpu(self):
return self.link.resume()
def reset_cpu(self):
return self.link.reset(1)
def set_pc_msp(self):
self.halt_cpu()
if self._chiptype == 'bl602' or self._chiptype == 'bl702' or self._chiptype == 'bl702l':
addr = int(self._cklink_run_addr, 16)
self.link.write_cpu_reg(self._cklink_reg_pc, addr)
def write(self, message):
self.if_raw_write(self._cklink_data_addr, message)
self.if_raw_write(self._cklink_shake_hand_addr, binascii.unhexlify('48524459'))
def _raw_write(self, addr, data_send):
self.halt_cpu()
addr_int = int(addr, 16)
data_send = bytes(data_send)
self.link.write_memory(addr_int, data_send)
self.resume_cpu()
def read(self, length):
start_time = time.time() * 1000
while True:
self.halt_cpu()
ready = self.link.read_memory(int(self._cklink_shake_hand_addr, 16), 4)
if len(ready) >= 1:
ready = binascii.hexlify(ready).decode()
if ready == '5341434b':
self.resume_cpu()
break
elapsed = time.time() * 1000 - start_time
if elapsed >= self._rx_timeout:
return (0, 'waiting response time out'.encode('utf-8'))
else:
self.resume_cpu()
time.sleep(0.001)
data = self._raw_read(self._cklink_data_addr, length)
if len(data) != length:
return (0, data)
return (1, data)
def _raw_read(self, addr, data_len):
return self.if_raw_read8(addr, data_len)
def _raw_read8(self, addr, data_len):
self.halt_cpu()
data = self.link.read_memory(int(addr, 16), data_len)
self.resume_cpu()
return bytearray(data)
def if_shakehand(self):
self.if_write(bytearray(1))
success, ack = self.read(2)
printf(binascii.hexlify(ack))
if ack.find(b'O') != -1 or ack.find(b'K') != -1:
time.sleep(0.03)
return 'OK'
return 'FL'
def deal_ack(self):
success, ack = self.read(2)
if success == 0:
printf('ack:' + str(binascii.hexlify(ack)))
return ack.decode('utf-8')
if ack.find(b'O') != -1 or ack.find(b'K') != -1:
return 'OK'
if ack.find(b'P') != -1 or ack.find(b'D') != -1:
return 'PD'
success, err_code = self.if_read(4)
if success == 0:
printf('err_code:' + str(binascii.hexlify(err_code)))
return 'FL'
err_code_str = str(binascii.hexlify(err_code[3:4] + err_code[2:3]).decode('utf-8'))
ack = 'FL'
try:
ret = ack + err_code_str + '(' + get_bflb_error_code(err_code_str) + ')'
except Exception:
ret = ack + err_code_str + ' unknown'
printf(ret)
return ret
def deal_response(self):
ack = self.deal_ack()
if ack == 'OK':
success, len_bytes = self.read(16)
if success == 0:
printf('Get length error')
printf(binascii.hexlify(len_bytes))
return (
'Get length error', len_bytes)
tmp = bytearray_reverse(len_bytes[2:4])
data_len = bytearray_to_int(tmp)
success, data_bytes = self.if_read(data_len + 4)
if success == 0:
printf('Read data error')
return (
'Read data error', data_bytes)
data_bytes = data_bytes[4:]
if len(data_bytes) != data_len:
printf('Not get excepted length')
return (
'Not get excepted length', data_bytes)
return (ack, data_bytes)
printf('Not ack OK')
printf(ack)
return (
ack, None)
if __name__ == '__main__':
print(pylink_enumerate())
ls = BLSerialUart('COM28', 2000000, '4201BFF0', '4201C000', 0, 'RISC-V', '22010000')
ls.set_dtr(0)
time.sleep(10)
ls.set_dtr(1)
ls.close()
# okay decompiling ./libs/base/bflb_serial.pyc

View File

@ -0,0 +1,331 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl602/bootheader_cfg_keys.py
bootheader_len = 176
bootheader_cfg_keys = {'magic_code':{'offset':'0',
'pos':'0',
'bitlen':'32'},
'revision':{'offset':'4',
'pos':'0',
'bitlen':'32'},
'flashcfg_magic_code':{'offset':'8',
'pos':'0',
'bitlen':'32'},
'io_mode':{'offset':'12',
'pos':'0',
'bitlen':'8'},
'cont_read_support':{'offset':'12',
'pos':'8',
'bitlen':'8'},
'sfctrl_clk_delay':{'offset':'12',
'pos':'16',
'bitlen':'8'},
'sfctrl_clk_invert':{'offset':'12',
'pos':'24',
'bitlen':'8'},
'reset_en_cmd':{'offset':'16',
'pos':'0',
'bitlen':'8'},
'reset_cmd':{'offset':'16',
'pos':'8',
'bitlen':'8'},
'exit_contread_cmd':{'offset':'16',
'pos':'16',
'bitlen':'8'},
'exit_contread_cmd_size':{'offset':'16',
'pos':'24',
'bitlen':'8'},
'jedecid_cmd':{'offset':'20',
'pos':'0',
'bitlen':'8'},
'jedecid_cmd_dmy_clk':{'offset':'20',
'pos':'8',
'bitlen':'8'},
'qpi_jedecid_cmd':{'offset':'20',
'pos':'16',
'bitlen':'8'},
'qpi_jedecid_dmy_clk':{'offset':'20',
'pos':'24',
'bitlen':'8'},
'sector_size':{'offset':'24',
'pos':'0',
'bitlen':'8'},
'mfg_id':{'offset':'24',
'pos':'8',
'bitlen':'8'},
'page_size':{'offset':'24',
'pos':'16',
'bitlen':'16'},
'chip_erase_cmd':{'offset':'28',
'pos':'0',
'bitlen':'8'},
'sector_erase_cmd':{'offset':'28',
'pos':'8',
'bitlen':'8'},
'blk32k_erase_cmd':{'offset':'28',
'pos':'16',
'bitlen':'8'},
'blk64k_erase_cmd':{'offset':'28',
'pos':'24',
'bitlen':'8'},
'write_enable_cmd':{'offset':'32',
'pos':'0',
'bitlen':'8'},
'page_prog_cmd':{'offset':'32',
'pos':'8',
'bitlen':'8'},
'qpage_prog_cmd':{'offset':'32',
'pos':'16',
'bitlen':'8'},
'qual_page_prog_addr_mode':{'offset':'32',
'pos':'24',
'bitlen':'8'},
'fast_read_cmd':{'offset':'36',
'pos':'0',
'bitlen':'8'},
'fast_read_dmy_clk':{'offset':'36',
'pos':'8',
'bitlen':'8'},
'qpi_fast_read_cmd':{'offset':'36',
'pos':'16',
'bitlen':'8'},
'qpi_fast_read_dmy_clk':{'offset':'36',
'pos':'24',
'bitlen':'8'},
'fast_read_do_cmd':{'offset':'40',
'pos':'0',
'bitlen':'8'},
'fast_read_do_dmy_clk':{'offset':'40',
'pos':'8',
'bitlen':'8'},
'fast_read_dio_cmd':{'offset':'40',
'pos':'16',
'bitlen':'8'},
'fast_read_dio_dmy_clk':{'offset':'40',
'pos':'24',
'bitlen':'8'},
'fast_read_qo_cmd':{'offset':'44',
'pos':'0',
'bitlen':'8'},
'fast_read_qo_dmy_clk':{'offset':'44',
'pos':'8',
'bitlen':'8'},
'fast_read_qio_cmd':{'offset':'44',
'pos':'16',
'bitlen':'8'},
'fast_read_qio_dmy_clk':{'offset':'44',
'pos':'24',
'bitlen':'8'},
'qpi_fast_read_qio_cmd':{'offset':'48',
'pos':'0',
'bitlen':'8'},
'qpi_fast_read_qio_dmy_clk':{'offset':'48',
'pos':'8',
'bitlen':'8'},
'qpi_page_prog_cmd':{'offset':'48',
'pos':'16',
'bitlen':'8'},
'write_vreg_enable_cmd':{'offset':'48',
'pos':'24',
'bitlen':'8'},
'wel_reg_index':{'offset':'52',
'pos':'0',
'bitlen':'8'},
'qe_reg_index':{'offset':'52',
'pos':'8',
'bitlen':'8'},
'busy_reg_index':{'offset':'52',
'pos':'16',
'bitlen':'8'},
'wel_bit_pos':{'offset':'52',
'pos':'24',
'bitlen':'8'},
'qe_bit_pos':{'offset':'56',
'pos':'0',
'bitlen':'8'},
'busy_bit_pos':{'offset':'56',
'pos':'8',
'bitlen':'8'},
'wel_reg_write_len':{'offset':'56',
'pos':'16',
'bitlen':'8'},
'wel_reg_read_len':{'offset':'56',
'pos':'24',
'bitlen':'8'},
'qe_reg_write_len':{'offset':'60',
'pos':'0',
'bitlen':'8'},
'qe_reg_read_len':{'offset':'60',
'pos':'8',
'bitlen':'8'},
'release_power_down':{'offset':'60',
'pos':'16',
'bitlen':'8'},
'busy_reg_read_len':{'offset':'60',
'pos':'24',
'bitlen':'8'},
'reg_read_cmd0':{'offset':'64',
'pos':'0',
'bitlen':'8'},
'reg_read_cmd1':{'offset':'64',
'pos':'8',
'bitlen':'8'},
'reg_write_cmd0':{'offset':'68',
'pos':'0',
'bitlen':'8'},
'reg_write_cmd1':{'offset':'68',
'pos':'8',
'bitlen':'8'},
'enter_qpi_cmd':{'offset':'72',
'pos':'0',
'bitlen':'8'},
'exit_qpi_cmd':{'offset':'72',
'pos':'8',
'bitlen':'8'},
'cont_read_code':{'offset':'72',
'pos':'16',
'bitlen':'8'},
'cont_read_exit_code':{'offset':'72',
'pos':'24',
'bitlen':'8'},
'burst_wrap_cmd':{'offset':'76',
'pos':'0',
'bitlen':'8'},
'burst_wrap_dmy_clk':{'offset':'76',
'pos':'8',
'bitlen':'8'},
'burst_wrap_data_mode':{'offset':'76',
'pos':'16',
'bitlen':'8'},
'burst_wrap_code':{'offset':'76',
'pos':'24',
'bitlen':'8'},
'de_burst_wrap_cmd':{'offset':'80',
'pos':'0',
'bitlen':'8'},
'de_burst_wrap_cmd_dmy_clk':{'offset':'80',
'pos':'8',
'bitlen':'8'},
'de_burst_wrap_code_mode':{'offset':'80',
'pos':'16',
'bitlen':'8'},
'de_burst_wrap_code':{'offset':'80',
'pos':'24',
'bitlen':'8'},
'sector_erase_time':{'offset':'84',
'pos':'0',
'bitlen':'16'},
'blk32k_erase_time':{'offset':'84',
'pos':'16',
'bitlen':'16'},
'blk64k_erase_time':{'offset':'88',
'pos':'0',
'bitlen':'16'},
'page_prog_time':{'offset':'88',
'pos':'16',
'bitlen':'16'},
'chip_erase_time':{'offset':'92',
'pos':'0',
'bitlen':'16'},
'power_down_delay':{'offset':'92',
'pos':'16',
'bitlen':'8'},
'qe_data':{'offset':'92',
'pos':'24',
'bitlen':'8'},
'flashcfg_crc32':{'offset':'96',
'pos':'0',
'bitlen':'32'},
'clkcfg_magic_code':{'offset':'100',
'pos':'0',
'bitlen':'32'},
'xtal_type':{'offset':'104',
'pos':'0',
'bitlen':'8'},
'pll_clk':{'offset':'104',
'pos':'8',
'bitlen':'8'},
'hclk_div':{'offset':'104',
'pos':'16',
'bitlen':'8'},
'bclk_div':{'offset':'104',
'pos':'24',
'bitlen':'8'},
'flash_clk_type':{'offset':'108',
'pos':'0',
'bitlen':'8'},
'flash_clk_div':{'offset':'108',
'pos':'8',
'bitlen':'8'},
'clkcfg_crc32':{'offset':'112',
'pos':'0',
'bitlen':'32'},
'sign':{'offset':'116',
'pos':'0',
'bitlen':'2'},
'encrypt_type':{'offset':'116',
'pos':'2',
'bitlen':'2'},
'key_sel':{'offset':'116',
'pos':'4',
'bitlen':'2'},
'no_segment':{'offset':'116',
'pos':'8',
'bitlen':'1'},
'cache_enable':{'offset':'116',
'pos':'9',
'bitlen':'1'},
'notload_in_bootrom':{'offset':'116',
'pos':'10',
'bitlen':'1'},
'aes_region_lock':{'offset':'116',
'pos':'11',
'bitlen':'1'},
'cache_way_disable':{'offset':'116',
'pos':'12',
'bitlen':'4'},
'crc_ignore':{'offset':'116',
'pos':'16',
'bitlen':'1'},
'hash_ignore':{'offset':'116',
'pos':'17',
'bitlen':'1'},
'img_len':{'offset':'120',
'pos':'0',
'bitlen':'32'},
'bootentry':{'offset':'124',
'pos':'0',
'bitlen':'32'},
'img_start':{'offset':'128',
'pos':'0',
'bitlen':'32'},
'hash_0':{'offset':'132',
'pos':'0',
'bitlen':'32'},
'hash_1':{'offset':'136',
'pos':'0',
'bitlen':'32'},
'hash_2':{'offset':'140',
'pos':'0',
'bitlen':'32'},
'hash_3':{'offset':'144',
'pos':'0',
'bitlen':'32'},
'hash_4':{'offset':'148',
'pos':'0',
'bitlen':'32'},
'hash_5':{'offset':'152',
'pos':'0',
'bitlen':'32'},
'hash_6':{'offset':'156',
'pos':'0',
'bitlen':'32'},
'hash_7':{'offset':'160',
'pos':'0',
'bitlen':'32'},
'crc32':{'offset':'172',
'pos':'0',
'bitlen':'32'}}
# okay decompiling ./libs/base/bl602/bootheader_cfg_keys.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl602/cklink_load_cfg.py
cklink_shake_hand_addr = '4201BFF0'
cklink_data_addr = '4201C000'
cklink_load_addr = '22010000'
cklink_core_type = 'RISC-V'
cklink_set_tif = 0
cklink_run_addr = '22010000'
# okay decompiling ./libs/base/bl602/cklink_load_cfg.pyc

View File

@ -0,0 +1,64 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl602/flash_select_do.py
import os, config as gol
from libs import bflb_utils
from libs.bflb_utils import app_path, conf_sign
from libs.bflb_configobj import BFConfigParser
def get_suitable_file_name(cfg_dir, flash_id):
conf_files = []
for home, dirs, files in os.walk(cfg_dir):
for filename in files:
if filename.split('_')[-1] == flash_id + '.conf':
conf_files.append(filename)
if len(conf_files) > 1:
bflb_utils.printf('Flash id duplicate and alternative is:')
for i in range(len(conf_files)):
tmp = conf_files[i].split('.')[0]
bflb_utils.printf('%d:%s' % (i + 1, tmp))
return conf_files[i]
if len(conf_files) == 1:
return conf_files[0]
return ''
def update_flash_cfg_do(chipname, chiptype, flash_id, file=None, create=False, section=None):
if conf_sign:
cfg_dir = app_path + '/utils/flash/' + chipname + '/'
else:
cfg_dir = app_path + '/utils/flash/' + gol.flash_dict[chipname] + '/'
conf_name = get_suitable_file_name(cfg_dir, flash_id)
value_key = []
if os.path.isfile(cfg_dir + conf_name) is False:
return False
fp = open(cfg_dir + conf_name, 'r')
for line in fp.readlines():
value = line.split('=')[0].strip()
if value == '[FLASH_CFG]':
continue
else:
value_key.append(value)
cfg1 = BFConfigParser()
cfg1.read(cfg_dir + conf_name)
cfg2 = BFConfigParser()
cfg2.read(file)
for i in range(len(value_key)):
if cfg1.has_option('FLASH_CFG', value_key[i]):
if cfg2.has_option(section, value_key[i]):
tmp_value = cfg1.get('FLASH_CFG', value_key[i])
bflb_utils.update_cfg(cfg2, section, value_key[i], tmp_value)
cfg2.write(file, 'w+')
bflb_utils.printf('Update flash cfg finished')
def get_supported_flash_do():
flash_type = []
return flash_type
# okay decompiling ./libs/base/bl602/flash_select_do.pyc

View File

@ -0,0 +1,524 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl602/img_create_do.py
import hashlib, binascii, ecdsa
from libs import bflb_utils
from libs.bflb_utils import open_file, img_create_sha256_data, img_create_encrypt_data
from libs.bflb_configobj import BFConfigParser
from libs.base.bl602.bootheader_cfg_keys import bootheader_len as header_len
keyslot0 = 28
keyslot1 = keyslot0 + 16
keyslot2 = keyslot1 + 16
keyslot3 = keyslot2 + 16
keyslot4 = keyslot3 + 16
keyslot5 = keyslot4 + 16
keyslot6 = keyslot5 + 16
wr_lock_key_slot_4_l = 13
wr_lock_key_slot_5_l = 14
wr_lock_boot_mode = 15
wr_lock_dbg_pwd = 16
wr_lock_sw_usage_0 = 17
wr_lock_wifi_mac = 18
wr_lock_key_slot_0 = 19
wr_lock_key_slot_1 = 20
wr_lock_key_slot_2 = 21
wr_lock_key_slot_3 = 22
wr_lock_key_slot_4_h = 23
wr_lock_key_slot_5_h = 24
rd_lock_dbg_pwd = 25
rd_lock_key_slot_0 = 26
rd_lock_key_slot_1 = 27
rd_lock_key_slot_2 = 28
rd_lock_key_slot_3 = 29
rd_lock_key_slot_4 = 30
rd_lock_key_slot_5 = 31
def img_update_efuse(cfg, sign, pk_hash, flash_encryp_type, flash_key, sec_eng_key_sel, sec_eng_key, security=False):
efuse_data = bytearray(128)
efuse_mask_data = bytearray(128)
if cfg != None:
fp = open(cfg.get('Img_Cfg', 'efuse_file'), 'rb')
efuse_data = bytearray(fp.read()) + bytearray(0)
fp.close()
fp = open(cfg.get('Img_Cfg', 'efuse_mask_file'), 'rb')
efuse_mask_data = bytearray(fp.read()) + bytearray(0)
fp.close()
mask_4bytes = bytearray.fromhex('FFFFFFFF')
efuse_data[0] |= flash_encryp_type
efuse_data[0] |= sign << 2
if flash_encryp_type > 0:
efuse_data[0] |= 128
efuse_data[0] |= 48
efuse_mask_data[0] |= 255
rw_lock = 0
if pk_hash is not None:
efuse_data[keyslot0:keyslot2] = pk_hash
efuse_mask_data[keyslot0:keyslot2] = mask_4bytes * 8
rw_lock |= 1 << wr_lock_key_slot_0
rw_lock |= 1 << wr_lock_key_slot_1
if flash_key is not None:
if flash_encryp_type == 1:
efuse_data[keyslot2:keyslot3] = flash_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
else:
if flash_encryp_type == 2:
efuse_data[keyslot2:keyslot4] = flash_key
efuse_mask_data[keyslot2:keyslot4] = mask_4bytes * 8
rw_lock |= 1 << wr_lock_key_slot_3
rw_lock |= 1 << rd_lock_key_slot_3
else:
if flash_encryp_type == 3:
efuse_data[keyslot2:keyslot4] = flash_key
efuse_mask_data[keyslot2:keyslot4] = mask_4bytes * 8
rw_lock |= 1 << wr_lock_key_slot_3
rw_lock |= 1 << rd_lock_key_slot_3
rw_lock |= 1 << wr_lock_key_slot_2
rw_lock |= 1 << rd_lock_key_slot_2
if sec_eng_key is not None:
if flash_encryp_type == 0:
if sec_eng_key_sel == 0:
efuse_data[keyslot3:keyslot4] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot4] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_3
rw_lock |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 1:
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_2
rw_lock |= 1 << rd_lock_key_slot_2
if flash_encryp_type == 1:
if sec_eng_key_sel == 0:
efuse_data[keyslot4:keyslot5] = sec_eng_key[0:16]
efuse_mask_data[keyslot4:keyslot5] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_4_l
rw_lock |= 1 << wr_lock_key_slot_4_h
rw_lock |= 1 << rd_lock_key_slot_4
if sec_eng_key_sel == 1:
efuse_data[keyslot4:keyslot5] = sec_eng_key[0:16]
efuse_mask_data[keyslot4:keyslot5] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_4_l
rw_lock |= 1 << wr_lock_key_slot_4_h
rw_lock |= 1 << rd_lock_key_slot_4
efuse_data[124:128] = bflb_utils.int_to_4bytearray_l(rw_lock)
efuse_mask_data[124:128] = bflb_utils.int_to_4bytearray_l(rw_lock)
if cfg != None:
if security is True:
bflb_utils.printf('Encrypt efuse data')
security_key, security_iv = bflb_utils.get_security_key()
efuse_data = img_create_encrypt_data(efuse_data, security_key, security_iv, 0)
efuse_data = bytearray(4096) + efuse_data
fp = open(cfg.get('Img_Cfg', 'efuse_file'), 'wb+')
fp.write(efuse_data)
fp.close()
fp = open(cfg.get('Img_Cfg', 'efuse_mask_file'), 'wb+')
fp.write(efuse_mask_data)
fp.close()
return efuse_data
def img_create_get_sign_encrypt_info(bootheader_data):
sign = bootheader_data[116] & 3
encrypt = bootheader_data[116] >> 2 & 3
key_sel = bootheader_data[116] >> 4 & 3
return (
sign, encrypt, key_sel)
def img_create_get_hash_ignore(bootheader_data):
return bootheader_data[118] >> 1 & 1
def img_create_get_crc_ignore(bootheader_data):
return bootheader_data[118] & 1
def img_create_update_bootheader_if(bootheader_data, hash, seg_cnt):
bootheader_data[120:124] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign = bootheader_data[116] & 3
encrypt = bootheader_data[116] >> 2 & 3
key_sel = bootheader_data[116] >> 4 & 3
if bootheader_data[118] >> 1 & 1 == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[132:164] = hash
if bootheader_data[118] & 1 == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[0:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data
def img_create_update_bootheader(bootheader_data, hash, seg_cnt):
bootheader_data[120:124] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign, encrypt, key_sel = img_create_get_sign_encrypt_info(bootheader_data)
if img_create_get_hash_ignore(bootheader_data) == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[132:164] = hash
if img_create_get_crc_ignore(bootheader_data) == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[0:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data[0:header_len]
def img_create_update_segheader(segheader, segdatalen, segdatacrc):
segheader[4:8] = segdatalen
segheader[8:12] = segdatacrc
return segheader
def img_create_sign_data(data_bytearray, privatekey_file_uecc, publickey_file):
sk = ecdsa.SigningKey.from_pem(open(privatekey_file_uecc).read())
vk = ecdsa.VerifyingKey.from_pem(open(publickey_file).read())
pk_data = vk.to_string()
bflb_utils.printf('Private key: ', binascii.hexlify(sk.to_string()))
bflb_utils.printf('Public key: ', binascii.hexlify(pk_data))
pk_hash = img_create_sha256_data(pk_data)
bflb_utils.printf('Public key hash=', binascii.hexlify(pk_hash))
signature = sk.sign(data_bytearray, hashfunc=(hashlib.sha256), sigencode=(ecdsa.util.sigencode_string))
bflb_utils.printf('Signature=', binascii.hexlify(signature))
len_array = bflb_utils.int_to_4bytearray_l(len(signature))
sig_field = len_array + signature
crcarray = bflb_utils.get_crc32_bytearray(sig_field)
return (
pk_data, pk_hash, sig_field + crcarray)
def img_create_read_file_append_crc(file, crc):
fp = open(file, 'rb')
read_data = bytearray(fp.read())
crcarray = bytearray(0)
if crc:
crcarray = bflb_utils.get_crc32_bytearray(read_data)
fp.close()
return read_data + crcarray
def encrypt_loader_bin_do(file, sign, encrypt, temp_encrypt_key, temp_encrypt_iv, publickey_file, privatekey_file):
if encrypt != 0 or sign != 0:
encrypt_key = bytearray(0)
encrypt_iv = bytearray(0)
load_helper_bin_header = bytearray(0)
load_helper_bin_body = bytearray(0)
offset = 116
sign_pos = 0
encrypt_type_pos = 2
key_sel_pos = 4
pk_data = bytearray(0)
signature = bytearray(0)
aesiv_data = bytearray(0)
data_tohash = bytearray(0)
with open(file, 'rb') as fp:
load_helper_bin = fp.read()
load_helper_bin_header = load_helper_bin[0:header_len]
load_helper_bin_body = load_helper_bin[header_len:]
if load_helper_bin_header != bytearray(0):
if load_helper_bin_body != bytearray(0):
load_helper_bin_body = bflb_utils.add_to_16(load_helper_bin_body)
if encrypt != 0:
encrypt_key = bflb_utils.hexstr_to_bytearray(temp_encrypt_key)
encrypt_iv = bflb_utils.hexstr_to_bytearray(temp_encrypt_iv)
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
load_helper_bin_body_encrypt = bflb_utils.img_create_encrypt_data(load_helper_bin_body, encrypt_key, encrypt_iv, 0)
else:
load_helper_bin_body_encrypt = load_helper_bin_body
data = bytearray(load_helper_bin_header)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = oldval
if encrypt != 0:
newval = newval | 1 << encrypt_type_pos
newval = newval | 0 << key_sel_pos
if sign != 0:
newval = newval | 1 << sign_pos
data_tohash += load_helper_bin_body_encrypt
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
load_helper_bin_header = data
load_helper_bin_encrypt = load_helper_bin_header + pk_data + signature + aesiv_data + load_helper_bin_body_encrypt
hash = img_create_sha256_data(data_tohash)
bflb_utils.printf('Image hash is ', binascii.hexlify(hash))
load_helper_bin_data = bytearray(load_helper_bin_encrypt)
load_helper_bin_encrypt = img_create_update_bootheader_if(load_helper_bin_data, hash, 1)
return (
True, load_helper_bin_encrypt)
return (False, None)
def create_encryptandsign_flash_data(data, offset, key, iv, publickey, privatekey):
encrypt = 0
encrypt_type = 0
sign = 0
data_len = len(data)
aesiv_data = bytearray(0)
pk_data = bytearray(0)
data_tohash = bytearray(0)
efuse_data = bytearray(128)
bootheader_data = data[0:176]
img_len = bflb_utils.bytearray_to_int(data[120:121]) + (bflb_utils.bytearray_to_int(data[121:122]) << 8) + (bflb_utils.bytearray_to_int(data[122:123]) << 16) + (bflb_utils.bytearray_to_int(data[123:124]) << 24)
img_data = data[offset:offset + img_len]
if key:
if iv:
encrypt = 1
if len(key) == 32:
encrypt_type = 1
else:
if len(key) == 64:
encrypt_type = 2
else:
if len(key) == 48:
encrypt_type = 3
bootheader_data[116] |= encrypt_type
if publickey:
if privatekey:
sign = 1
bootheader_data[116] |= 4
if encrypt:
encrypt_key = bflb_utils.hexstr_to_bytearray(key)
encrypt_iv = bflb_utils.hexstr_to_bytearray(iv)
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
mfgBin = False
if img_data[img_len - 16:img_len - 12] == bytearray('0mfg'.encode('utf-8')):
bflb_utils.printf('mfg bin')
mfgBin = True
data_toencrypt = bytearray(0)
if mfgBin:
data_toencrypt += img_data[:img_len - 16]
else:
data_toencrypt += img_data
if encrypt:
data_toencrypt = img_create_encrypt_data(data_toencrypt, encrypt_key, encrypt_iv, 1)
if mfgBin:
data_toencrypt += img_data[img_len - 16:img_len]
fw_data = bytearray(0)
data_tohash += data_toencrypt
fw_data = data_toencrypt
seg_cnt = len(data_toencrypt)
hash = img_create_sha256_data(data_tohash)
bflb_utils.printf('Image hash is ', binascii.hexlify(hash))
bootheader_data = img_create_update_bootheader(bootheader_data, hash, seg_cnt)
signature = bytearray(0)
pk_hash = None
if sign:
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey, publickey)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
bflb_utils.printf('Write flash img')
bootinfo = bootheader_data + pk_data + signature + aesiv_data
output_data = bytearray(data_len)
for i in range(data_len):
output_data[i] = 255
output_data[0:len(bootinfo)] = bootinfo
output_data[offset:offset + seg_cnt] = fw_data
if encrypt != 0:
if encrypt_type == 1:
efuse_data = img_update_efuse(None, sign, pk_hash, 1, encrypt_key + bytearray(32 - len(encrypt_key)), 0, encrypt_key + bytearray(32 - len(encrypt_key)))
if encrypt_type == 2:
efuse_data = img_update_efuse(None, sign, pk_hash, 3, encrypt_key + bytearray(32 - len(encrypt_key)), 0, encrypt_key + bytearray(32 - len(encrypt_key)))
if encrypt_type == 3:
efuse_data = img_update_efuse(None, sign, pk_hash, 2, encrypt_key + bytearray(32 - len(encrypt_key)), 0, encrypt_key + bytearray(32 - len(encrypt_key)))
return (
output_data, efuse_data, seg_cnt)
def img_creat_process(flash_img, cfg, security=False):
encrypt_blk_size = 16
padding = bytearray(encrypt_blk_size)
data_tohash = bytearray(0)
cfg_section = 'Img_Cfg'
segheader_file = []
if flash_img == 0:
for files in cfg.get(cfg_section, 'segheader_file').split(' '):
segheader_file.append(str(files))
segdata_file = []
for files in cfg.get(cfg_section, 'segdata_file').split('|'):
segdata_file.append(str(files))
if flash_img == 1:
break
boot_header_file = cfg.get(cfg_section, 'boot_header_file')
bootheader_data = img_create_read_file_append_crc(boot_header_file, 0)
encrypt = 0
sign, encrypt, key_sel = img_create_get_sign_encrypt_info(bootheader_data)
aesiv_data = bytearray(0)
pk_data = bytearray(0)
if sign != 0:
bflb_utils.printf('Image need sign')
publickey_file = cfg.get(cfg_section, 'publickey_file')
privatekey_file_uecc = cfg.get(cfg_section, 'privatekey_file_uecc')
if encrypt != 0:
bflb_utils.printf('Image need encrypt ', encrypt)
encrypt_key_org = bflb_utils.hexstr_to_bytearray(cfg.get(cfg_section, 'aes_key_org'))
if encrypt == 1:
encrypt_key = encrypt_key_org[0:16]
else:
if encrypt == 2:
encrypt_key = encrypt_key_org[0:32]
else:
if encrypt == 3:
encrypt_key = encrypt_key_org[0:24]
bflb_utils.printf('Key= ', binascii.hexlify(encrypt_key))
encrypt_iv = bflb_utils.hexstr_to_bytearray(cfg.get(cfg_section, 'aes_iv'))
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
seg_cnt = len(segheader_file)
if flash_img == 0:
if seg_cnt != len(segdata_file):
bflb_utils.printf('Segheader count and segdata count not match')
return (
'FAIL', data_tohash)
mfgBin = False
data_toencrypt = bytearray(0)
if flash_img == 0:
i = 0
seg_header_list = []
seg_data_list = []
while i < seg_cnt:
seg_data = img_create_read_file_append_crc(segdata_file[i], 0)
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
else:
segdata_crcarray = bflb_utils.get_crc32_bytearray(seg_data)
seg_data_list.append(seg_data)
seg_header = img_create_read_file_append_crc(segheader_file[i], 0)
seg_header = img_create_update_segheader(seg_header, bflb_utils.int_to_4bytearray_l(len(seg_data)), segdata_crcarray)
segheader_crcarray = bflb_utils.get_crc32_bytearray(seg_header)
seg_header = seg_header + segheader_crcarray
seg_header_list.append(seg_header)
i = i + 1
i = 0
while i < seg_cnt:
data_toencrypt += seg_header_list[i]
data_toencrypt += seg_data_list[i]
i += 1
else:
seg_data = img_create_read_file_append_crc(segdata_file[0], 0)
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
if seg_data[len(seg_data) - 16:len(seg_data) - 12] == bytearray('0mfg'.encode('utf-8')):
mfgBin = True
if mfgBin:
data_toencrypt += seg_data[:len(seg_data) - 16]
else:
data_toencrypt += seg_data
seg_cnt = len(data_toencrypt)
if mfgBin:
seg_cnt += 16
if encrypt != 0:
data_toencrypt = img_create_encrypt_data(data_toencrypt, encrypt_key, encrypt_iv, flash_img)
if mfgBin:
data_toencrypt += seg_data[len(seg_data) - 16:len(seg_data)]
fw_data = bytearray(0)
data_tohash += data_toencrypt
fw_data = data_toencrypt
hash = img_create_sha256_data(data_tohash)
bflb_utils.printf('Image hash is ', binascii.hexlify(hash))
bootheader_data = img_create_update_bootheader(bootheader_data, hash, seg_cnt)
signature = bytearray(0)
pk_hash = None
if sign == 1:
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file_uecc, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
if flash_img == 1:
bflb_utils.printf('Write flash img')
bootinfo_file_name = cfg.get(cfg_section, 'bootinfo_file')
fp = open(bootinfo_file_name, 'wb+')
bootinfo = bootheader_data + pk_data + signature + aesiv_data
fp.write(bootinfo)
fp.close()
fw_file_name = cfg.get(cfg_section, 'img_file')
fp = open(fw_file_name, 'wb+')
fp.write(fw_data)
fp.close()
fw_data_hash = img_create_sha256_data(fw_data)
fp = open(fw_file_name.replace('.bin', '_withhash.bin'), 'wb+')
fp.write(fw_data + fw_data_hash)
fp.close()
if encrypt != 0:
if encrypt == 1:
img_update_efuse(cfg, sign, pk_hash, 1, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 2:
img_update_efuse(cfg, sign, pk_hash, 3, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 3:
img_update_efuse(cfg, sign, pk_hash, 2, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
else:
img_update_efuse(cfg, sign, pk_hash, encrypt, None, key_sel, None, security)
else:
bflb_utils.printf('Write if img')
whole_img_file_name = cfg.get(cfg_section, 'whole_img_file')
fp = open(whole_img_file_name, 'wb+')
img_data = bootheader_data + pk_data + signature + aesiv_data + fw_data
fp.write(img_data)
fp.close()
if encrypt != 0:
if encrypt == 1:
img_update_efuse(cfg, sign, pk_hash, 1, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 2:
img_update_efuse(cfg, sign, pk_hash, 3, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 3:
img_update_efuse(cfg, sign, pk_hash, 2, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
else:
img_update_efuse(cfg, sign, pk_hash, 0, None, key_sel, bytearray(32), security)
return (
'OK', data_tohash)
def img_create_do(args, img_dir_path=None, config_file=None):
bflb_utils.printf('Image create path: ', img_dir_path)
if config_file is None:
config_file = img_dir_path + '/img_create_cfg.ini'
bflb_utils.printf('Config file: ', config_file)
cfg = BFConfigParser()
cfg.read(config_file)
img_type = 'media'
signer = 'none'
security = False
data_tohash = bytearray(0)
try:
if args.image:
img_type = args.image
if args.signer:
signer = args.signer
if args.security:
security = args.security == 'efuse'
except Exception as e:
try:
bflb_utils.printf(e)
finally:
e = None
del e
if img_type == 'media':
flash_img = 1
else:
flash_img = 0
ret, data_tohash = img_creat_process(flash_img, cfg, security)
if ret != 'OK':
bflb_utils.printf('Fail to create images!')
def create_sp_media_image(config, cpu_type=None, security=False):
bflb_utils.printf('========= sp image create =========')
cfg = BFConfigParser()
cfg.read(config)
img_creat_process(1, cfg, security)
# okay decompiling ./libs/base/bl602/img_create_do.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl602/jlink_load_cfg.py
jlink_shake_hand_addr = '4201BFF0'
jlink_data_addr = '4201C000'
jlink_load_addr = '22010000'
jlink_core_type = 'RISC-V'
jlink_set_tif = 0
jlink_run_addr = '22010000'
# okay decompiling ./libs/base/bl602/jlink_load_cfg.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl602/openocd_load_cfg.py
openocd_shake_hand_addr = '4201BFF0'
openocd_data_addr = '4201C000'
openocd_load_addr = '22010000'
openocd_core_type = 'RISC-V'
openocd_set_tif = 0
openocd_run_addr = '22010000'
# okay decompiling ./libs/base/bl602/openocd_load_cfg.pyc

View File

@ -0,0 +1,482 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl616/bootheader_cfg_keys.py
clock_start_pos = 100
bootcfg_start_pos = 120
bootcfg_len = 48
bootcpucfg_start_pos = bootcfg_start_pos + bootcfg_len
bootcpucfg_len = 16
bootcpucfg_m0_index = 0
bootcpucfg_d0_index = 1
bootcpucfg_lp_index = 2
boot2_start_pos = bootcpucfg_start_pos + bootcpucfg_len * (bootcpucfg_m0_index + 1)
boot2_len = 8
flashcfg_table_start_pos = boot2_start_pos + boot2_len
flashcfg_table_len = 8
patch_on_read_start_pos = flashcfg_table_start_pos + flashcfg_table_len
patch_on_read_len = 24
patch_on_jump_start_pos = patch_on_read_start_pos + patch_on_read_len
patch_on_jump_len = 24
rsvd_start_pos = patch_on_jump_start_pos + patch_on_jump_len
rsvd_len = 4
crc32_start_pos = rsvd_start_pos + rsvd_len
bootheader_len = crc32_start_pos + 4
bootheader_cfg_keys = {'magic_code':{'offset':'0',
'pos':'0',
'bitlen':'32'},
'revision':{'offset':'4',
'pos':'0',
'bitlen':'32'},
'flashcfg_magic_code':{'offset':'8',
'pos':'0',
'bitlen':'32'},
'io_mode':{'offset':'12',
'pos':'0',
'bitlen':'8'},
'cont_read_support':{'offset':'12',
'pos':'8',
'bitlen':'8'},
'sfctrl_clk_delay':{'offset':'12',
'pos':'16',
'bitlen':'8'},
'sfctrl_clk_invert':{'offset':'12',
'pos':'24',
'bitlen':'8'},
'reset_en_cmd':{'offset':'16',
'pos':'0',
'bitlen':'8'},
'reset_cmd':{'offset':'16',
'pos':'8',
'bitlen':'8'},
'exit_contread_cmd':{'offset':'16',
'pos':'16',
'bitlen':'8'},
'exit_contread_cmd_size':{'offset':'16',
'pos':'24',
'bitlen':'8'},
'jedecid_cmd':{'offset':'20',
'pos':'0',
'bitlen':'8'},
'jedecid_cmd_dmy_clk':{'offset':'20',
'pos':'8',
'bitlen':'8'},
'enter_32bits_addr_cmd':{'offset':'20',
'pos':'16',
'bitlen':'8'},
'exit_32bits_addr_clk':{'offset':'20',
'pos':'24',
'bitlen':'8'},
'sector_size':{'offset':'24',
'pos':'0',
'bitlen':'8'},
'mfg_id':{'offset':'24',
'pos':'8',
'bitlen':'8'},
'page_size':{'offset':'24',
'pos':'16',
'bitlen':'16'},
'chip_erase_cmd':{'offset':'28',
'pos':'0',
'bitlen':'8'},
'sector_erase_cmd':{'offset':'28',
'pos':'8',
'bitlen':'8'},
'blk32k_erase_cmd':{'offset':'28',
'pos':'16',
'bitlen':'8'},
'blk64k_erase_cmd':{'offset':'28',
'pos':'24',
'bitlen':'8'},
'write_enable_cmd':{'offset':'32',
'pos':'0',
'bitlen':'8'},
'page_prog_cmd':{'offset':'32',
'pos':'8',
'bitlen':'8'},
'qpage_prog_cmd':{'offset':'32',
'pos':'16',
'bitlen':'8'},
'qual_page_prog_addr_mode':{'offset':'32',
'pos':'24',
'bitlen':'8'},
'fast_read_cmd':{'offset':'36',
'pos':'0',
'bitlen':'8'},
'fast_read_dmy_clk':{'offset':'36',
'pos':'8',
'bitlen':'8'},
'qpi_fast_read_cmd':{'offset':'36',
'pos':'16',
'bitlen':'8'},
'qpi_fast_read_dmy_clk':{'offset':'36',
'pos':'24',
'bitlen':'8'},
'fast_read_do_cmd':{'offset':'40',
'pos':'0',
'bitlen':'8'},
'fast_read_do_dmy_clk':{'offset':'40',
'pos':'8',
'bitlen':'8'},
'fast_read_dio_cmd':{'offset':'40',
'pos':'16',
'bitlen':'8'},
'fast_read_dio_dmy_clk':{'offset':'40',
'pos':'24',
'bitlen':'8'},
'fast_read_qo_cmd':{'offset':'44',
'pos':'0',
'bitlen':'8'},
'fast_read_qo_dmy_clk':{'offset':'44',
'pos':'8',
'bitlen':'8'},
'fast_read_qio_cmd':{'offset':'44',
'pos':'16',
'bitlen':'8'},
'fast_read_qio_dmy_clk':{'offset':'44',
'pos':'24',
'bitlen':'8'},
'qpi_fast_read_qio_cmd':{'offset':'48',
'pos':'0',
'bitlen':'8'},
'qpi_fast_read_qio_dmy_clk':{'offset':'48',
'pos':'8',
'bitlen':'8'},
'qpi_page_prog_cmd':{'offset':'48',
'pos':'16',
'bitlen':'8'},
'write_vreg_enable_cmd':{'offset':'48',
'pos':'24',
'bitlen':'8'},
'wel_reg_index':{'offset':'52',
'pos':'0',
'bitlen':'8'},
'qe_reg_index':{'offset':'52',
'pos':'8',
'bitlen':'8'},
'busy_reg_index':{'offset':'52',
'pos':'16',
'bitlen':'8'},
'wel_bit_pos':{'offset':'52',
'pos':'24',
'bitlen':'8'},
'qe_bit_pos':{'offset':'56',
'pos':'0',
'bitlen':'8'},
'busy_bit_pos':{'offset':'56',
'pos':'8',
'bitlen':'8'},
'wel_reg_write_len':{'offset':'56',
'pos':'16',
'bitlen':'8'},
'wel_reg_read_len':{'offset':'56',
'pos':'24',
'bitlen':'8'},
'qe_reg_write_len':{'offset':'60',
'pos':'0',
'bitlen':'8'},
'qe_reg_read_len':{'offset':'60',
'pos':'8',
'bitlen':'8'},
'release_power_down':{'offset':'60',
'pos':'16',
'bitlen':'8'},
'busy_reg_read_len':{'offset':'60',
'pos':'24',
'bitlen':'8'},
'reg_read_cmd0':{'offset':'64',
'pos':'0',
'bitlen':'8'},
'reg_read_cmd1':{'offset':'64',
'pos':'8',
'bitlen':'8'},
'reg_write_cmd0':{'offset':'68',
'pos':'0',
'bitlen':'8'},
'reg_write_cmd1':{'offset':'68',
'pos':'8',
'bitlen':'8'},
'enter_qpi_cmd':{'offset':'72',
'pos':'0',
'bitlen':'8'},
'exit_qpi_cmd':{'offset':'72',
'pos':'8',
'bitlen':'8'},
'cont_read_code':{'offset':'72',
'pos':'16',
'bitlen':'8'},
'cont_read_exit_code':{'offset':'72',
'pos':'24',
'bitlen':'8'},
'burst_wrap_cmd':{'offset':'76',
'pos':'0',
'bitlen':'8'},
'burst_wrap_dmy_clk':{'offset':'76',
'pos':'8',
'bitlen':'8'},
'burst_wrap_data_mode':{'offset':'76',
'pos':'16',
'bitlen':'8'},
'burst_wrap_code':{'offset':'76',
'pos':'24',
'bitlen':'8'},
'de_burst_wrap_cmd':{'offset':'80',
'pos':'0',
'bitlen':'8'},
'de_burst_wrap_cmd_dmy_clk':{'offset':'80',
'pos':'8',
'bitlen':'8'},
'de_burst_wrap_code_mode':{'offset':'80',
'pos':'16',
'bitlen':'8'},
'de_burst_wrap_code':{'offset':'80',
'pos':'24',
'bitlen':'8'},
'sector_erase_time':{'offset':'84',
'pos':'0',
'bitlen':'16'},
'blk32k_erase_time':{'offset':'84',
'pos':'16',
'bitlen':'16'},
'blk64k_erase_time':{'offset':'88',
'pos':'0',
'bitlen':'16'},
'page_prog_time':{'offset':'88',
'pos':'16',
'bitlen':'16'},
'chip_erase_time':{'offset':'92',
'pos':'0',
'bitlen':'16'},
'power_down_delay':{'offset':'92',
'pos':'16',
'bitlen':'8'},
'qe_data':{'offset':'92',
'pos':'24',
'bitlen':'8'},
'flashcfg_crc32':{'offset':'96',
'pos':'0',
'bitlen':'32'},
'clkcfg_magic_code':{'offset':str(int(clock_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'xtal_type':{'offset':str(int(clock_start_pos) + 4),
'pos':'0',
'bitlen':'8'},
'mcu_clk':{'offset':str(int(clock_start_pos) + 4),
'pos':'8',
'bitlen':'8'},
'mcu_clk_div':{'offset':str(int(clock_start_pos) + 4),
'pos':'16',
'bitlen':'8'},
'mcu_bclk_div':{'offset':str(int(clock_start_pos) + 4),
'pos':'24',
'bitlen':'8'},
'mcu_pbclk_div':{'offset':str(int(clock_start_pos) + 8),
'pos':'0',
'bitlen':'8'},
'emi_clk':{'offset':str(int(clock_start_pos) + 8),
'pos':'8',
'bitlen':'8'},
'emi_clk_div':{'offset':str(int(clock_start_pos) + 8),
'pos':'16',
'bitlen':'8'},
'flash_clk_type':{'offset':str(int(clock_start_pos) + 8),
'pos':'24',
'bitlen':'8'},
'flash_clk_div':{'offset':str(int(clock_start_pos) + 12),
'pos':'0',
'bitlen':'8'},
'wifipll_pu':{'offset':str(int(clock_start_pos) + 12),
'pos':'8',
'bitlen':'8'},
'aupll_pu':{'offset':str(int(clock_start_pos) + 12),
'pos':'16',
'bitlen':'8'},
'rsvd0':{'offset':str(int(clock_start_pos) + 12),
'pos':'24',
'bitlen':'8'},
'clkcfg_crc32':{'offset':str(int(clock_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'sign':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'0',
'bitlen':'2'},
'encrypt_type':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'2',
'bitlen':'2'},
'key_sel':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'4',
'bitlen':'2'},
'xts_mode':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'6',
'bitlen':'1'},
'aes_region_lock':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'7',
'bitlen':'1'},
'no_segment':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'8',
'bitlen':'1'},
'boot2_enable':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'9',
'bitlen':'1'},
'boot2_rollback':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'10',
'bitlen':'1'},
'cpu_master_id':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'11',
'bitlen':'4'},
'notload_in_bootrom':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'15',
'bitlen':'1'},
'crc_ignore':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'16',
'bitlen':'1'},
'hash_ignore':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'17',
'bitlen':'1'},
'power_on_mm':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'18',
'bitlen':'1'},
'em_sel':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'19',
'bitlen':'3'},
'cmds_en':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'22',
'bitlen':'1'},
'cmds_wrap_mode':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'23',
'bitlen':'2'},
'cmds_wrap_len':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'25',
'bitlen':'4'},
'icache_invalid':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'29',
'bitlen':'1'},
'dcache_invalid':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'30',
'bitlen':'1'},
'fpga_halt_release':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'31',
'bitlen':'1'},
'group_image_offset':{'offset':str(int(bootcfg_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'aes_region_len':{'offset':str(int(bootcfg_start_pos) + 8),
'pos':'0',
'bitlen':'32'},
'img_len_cnt':{'offset':str(int(bootcfg_start_pos) + 12),
'pos':'0',
'bitlen':'32'},
'hash_0':{'offset':str(int(bootcfg_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'hash_1':{'offset':str(int(bootcfg_start_pos) + 20),
'pos':'0',
'bitlen':'32'},
'hash_2':{'offset':str(int(bootcfg_start_pos) + 24),
'pos':'0',
'bitlen':'32'},
'hash_3':{'offset':str(int(bootcfg_start_pos) + 28),
'pos':'0',
'bitlen':'32'},
'hash_4':{'offset':str(int(bootcfg_start_pos) + 32),
'pos':'0',
'bitlen':'32'},
'hash_5':{'offset':str(int(bootcfg_start_pos) + 36),
'pos':'0',
'bitlen':'32'},
'hash_6':{'offset':str(int(bootcfg_start_pos) + 40),
'pos':'0',
'bitlen':'32'},
'hash_7':{'offset':str(int(bootcfg_start_pos) + 44),
'pos':'0',
'bitlen':'32'},
'm0_config_enable':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'0',
'bitlen':'8'},
'm0_halt_cpu':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'8',
'bitlen':'8'},
'm0_cache_enable':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'16',
'bitlen':'1'},
'm0_cache_wa':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'17',
'bitlen':'1'},
'm0_cache_wb':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'18',
'bitlen':'1'},
'm0_cache_wt':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'19',
'bitlen':'1'},
'm0_cache_way_dis':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'20',
'bitlen':'4'},
'm0_reserved':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'24',
'bitlen':'8'},
'm0_image_address_offset':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 4),
'pos':'0',
'bitlen':'32'},
'm0_boot_entry':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 8),
'pos':'0',
'bitlen':'32'},
'm0_msp_val':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 12),
'pos':'0',
'bitlen':'32'},
'boot2_pt_table_0':{'offset':str(int(boot2_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'boot2_pt_table_1':{'offset':str(int(boot2_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'flashCfgTableAddr':{'offset':str(int(flashcfg_table_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'flashCfgTableLen':{'offset':str(int(flashcfg_table_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'patch_read_addr0':{'offset':str(int(patch_on_read_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'patch_read_value0':{'offset':str(int(patch_on_read_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'patch_read_addr1':{'offset':str(int(patch_on_read_start_pos) + 8),
'pos':'0',
'bitlen':'32'},
'patch_read_value1':{'offset':str(int(patch_on_read_start_pos) + 12),
'pos':'0',
'bitlen':'32'},
'patch_read_addr2':{'offset':str(int(patch_on_read_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'patch_read_value2':{'offset':str(int(patch_on_read_start_pos) + 20),
'pos':'0',
'bitlen':'32'},
'patch_jump_addr0':{'offset':str(int(patch_on_jump_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'patch_jump_value0':{'offset':str(int(patch_on_jump_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'patch_jump_addr1':{'offset':str(int(patch_on_jump_start_pos) + 8),
'pos':'0',
'bitlen':'32'},
'patch_jump_value1':{'offset':str(int(patch_on_jump_start_pos) + 12),
'pos':'0',
'bitlen':'32'},
'patch_jump_addr2':{'offset':str(int(patch_on_jump_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'patch_jump_value2':{'offset':str(int(patch_on_jump_start_pos) + 20),
'pos':'0',
'bitlen':'32'},
'reserved':{'offset':str(int(rsvd_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'crc32':{'offset':str(int(crc32_start_pos) + 0),
'pos':'0',
'bitlen':'32'}}
# okay decompiling ./libs/base/bl616/bootheader_cfg_keys.pyc

View File

@ -0,0 +1,10 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl616/chiptype_patch.py
def img_load_create_predata_before_run_img():
return bytearray(0)
# okay decompiling ./libs/base/bl616/chiptype_patch.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl616/cklink_load_cfg.py
cklink_shake_hand_addr = '2204BBEC'
cklink_data_addr = '2204CC88'
cklink_load_addr = '22010000'
cklink_core_type = 'RISC-V'
cklink_set_tif = 0
cklink_run_addr = '22010000'
# okay decompiling ./libs/base/bl616/cklink_load_cfg.pyc

View File

@ -0,0 +1,147 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl616/flash_select_do.py
import os, csv
from re import I
import config as gol
from libs import bflb_utils
from libs.bflb_utils import app_path, conf_sign
from libs.bflb_configobj import BFConfigParser
from libs.base.bl616.bootheader_cfg_keys import bootheader_cfg_keys as flash_cfg_keys
def get_suitable_file_name(cfg_dir, flash_id):
conf_files = []
for home, dirs, files in os.walk(cfg_dir):
for filename in files:
if filename.split('_')[-1] == flash_id + '.conf':
conf_files.append(filename)
if len(conf_files) > 1:
bflb_utils.printf('Flash id duplicate and alternative is:')
for i in range(len(conf_files)):
tmp = conf_files[i].split('.')[0]
bflb_utils.printf('%d:%s' % (i + 1, tmp))
return conf_files[i]
if len(conf_files) == 1:
return conf_files[0]
return ''
def update_flash_cfg_do(chipname, chiptype, flash_id, file=None, create=False, section=None):
if conf_sign:
cfg_dir = app_path + '/utils/flash/' + chipname + '/'
else:
cfg_dir = app_path + '/utils/flash/' + gol.flash_dict[chipname] + '/'
conf_name = get_suitable_file_name(cfg_dir, flash_id)
value_key = []
if os.path.isfile(cfg_dir + conf_name) is False:
return False
fp = open(cfg_dir + conf_name, 'r')
for line in fp.readlines():
value = line.split('=')[0].strip()
if value == '[FLASH_CFG]':
continue
else:
value_key.append(value)
cfg1 = BFConfigParser()
cfg1.read(cfg_dir + conf_name)
cfg2 = BFConfigParser()
cfg2.read(file)
for i in range(len(value_key)):
if cfg1.has_option('FLASH_CFG', value_key[i]):
if cfg2.has_option(section, value_key[i]):
tmp_value = cfg1.get('FLASH_CFG', value_key[i])
bflb_utils.update_cfg(cfg2, section, value_key[i], tmp_value)
cfg2.write(file, 'w+')
bflb_utils.printf('Update flash cfg finished')
def get_supported_flash_do():
flash_type = []
return flash_type
def get_int_mask(pos, length):
ones = '11111111111111111111111111111111'
zeros = '00000000000000000000000000000000'
mask = ones[0:32 - pos - length] + zeros[0:length] + ones[0:pos]
return int(mask, 2)
def create_flashcfg_data_from_cfg(cfg_len, cfgfile):
section = 'FLASH_CFG'
cfg = BFConfigParser()
cfg.read(cfgfile)
data = bytearray(cfg_len)
minOffset = int(flash_cfg_keys.get('io_mode')['offset'], 10)
for key in cfg.options(section):
if flash_cfg_keys.get(key) == None:
bflb_utils.printf(key + ' not exist')
continue
else:
val = cfg.get(section, key)
if val.startswith('0x'):
val = int(val, 16)
else:
val = int(val, 10)
offset = int(flash_cfg_keys.get(key)['offset'], 10) - minOffset
pos = int(flash_cfg_keys.get(key)['pos'], 10)
bitlen = int(flash_cfg_keys.get(key)['bitlen'], 10)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = (oldval & get_int_mask(pos, bitlen)) + (val << pos)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
crcarray = bflb_utils.get_crc32_bytearray(data)
data = bflb_utils.int_to_4bytearray_l(1195787078) + data + crcarray
return data
def create_flashcfg_table(start_addr):
single_flashcfg_len = 92
flash_table_list = bytearray(0)
flash_table_data = bytearray(0)
table_file = os.path.join(app_path, 'utils', 'flash', 'bl616', 'flashcfg_list.csv')
with open(table_file, 'r', encoding='utf-8-sig') as csvfile:
table_list = []
cfgfile_list = []
reader = csv.DictReader(csvfile)
cnt = 0
for row in reader:
row_dict = {}
row_dict['jid'] = row.get('flashJedecID', '')
row_dict['cfgfile'] = row.get('configFile', '')
if row_dict['cfgfile'] not in cfgfile_list:
cfgfile_list.append(row_dict['cfgfile'])
else:
table_list.append(row_dict)
cnt += 1
table_list_len = 4 + cnt * 8 + 4
for cfgfile in cfgfile_list:
cfgfile = os.path.join(app_path, 'utils', 'flash', 'bl616', cfgfile)
data = create_flashcfg_data_from_cfg(single_flashcfg_len - 8, cfgfile)
flash_table_data += data
for dict in table_list:
flash_table_list += bflb_utils.int_to_4bytearray_b(int(dict['jid'] + '00', 16))
i = 0
offset = 0
for cfgfile in cfgfile_list:
if cfgfile == dict['cfgfile']:
offset = start_addr + table_list_len + single_flashcfg_len * i
break
else:
i += 1
flash_table_list += bflb_utils.int_to_4bytearray_l(offset)
crcarray = bflb_utils.get_crc32_bytearray(flash_table_list)
flash_table_list = bflb_utils.int_to_4bytearray_l(1196704582) + flash_table_list + crcarray
return (
flash_table_list, flash_table_data, len(flash_table_list))
# okay decompiling ./libs/base/bl616/flash_select_do.pyc

View File

@ -0,0 +1,753 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl616/img_create_do.py
import os, sys, hashlib, binascii, codecs, ecdsa
from CryptoPlus.Cipher import AES as AES_XTS
from libs import bflb_utils
from libs.bflb_utils import img_create_sha256_data, img_create_encrypt_data
from libs.bflb_configobj import BFConfigParser
from libs.base.bl616.flash_select_do import create_flashcfg_table
from libs.base.bl616.bootheader_cfg_keys import flashcfg_table_start_pos as flashcfg_table_start
from libs.base.bl616.bootheader_cfg_keys import bootcpucfg_start_pos as bootcpucfg_start
from libs.base.bl616.bootheader_cfg_keys import bootcpucfg_len as bootcpucfg_length
from libs.base.bl616.bootheader_cfg_keys import bootcpucfg_m0_index as bootcpucfg_m0_index_number
from libs.base.bl616.bootheader_cfg_keys import bootcpucfg_d0_index as bootcpucfg_d0_index_number
from libs.base.bl616.bootheader_cfg_keys import bootcpucfg_lp_index as bootcpucfg_lp_index_number
from libs.base.bl616.bootheader_cfg_keys import bootcfg_start_pos as bootcfg_start
from libs.base.bl616.bootheader_cfg_keys import bootheader_len as header_len
keyslot0 = 28
keyslot1 = keyslot0 + 16
keyslot2 = keyslot1 + 16
keyslot3 = keyslot2 + 16
keyslot3_end = keyslot3 + 16
keyslot4 = 128
keyslot5 = keyslot4 + 16
keyslot6 = keyslot5 + 16
keyslot7 = keyslot6 + 16
keyslot8 = keyslot7 + 16
keyslot9 = keyslot8 + 16
keyslot10 = keyslot9 + 16
keyslot10_end = keyslot10 + 16
keyslot11 = keyslot3_end + 16
keyslot11_end = keyslot11 + 16
wr_lock_boot_mode = 14
wr_lock_dbg_pwd = 15
wr_lock_wifi_mac = 16
wr_lock_key_slot_0 = 17
wr_lock_key_slot_1 = 18
wr_lock_key_slot_2 = 19
wr_lock_key_slot_3 = 20
wr_lock_sw_usage_0 = 21
wr_lock_sw_usage_1 = 22
wr_lock_sw_usage_2 = 23
wr_lock_sw_usage_3 = 24
wr_lock_key_slot_11 = 25
rd_lock_dbg_pwd = 26
rd_lock_key_slot_0 = 27
rd_lock_key_slot_1 = 28
rd_lock_key_slot_2 = 29
rd_lock_key_slot_3 = 30
rd_lock_key_slot_11 = 31
wr_lock_key_slot_4 = 15
wr_lock_key_slot_5 = 16
wr_lock_key_slot_6 = 17
wr_lock_key_slot_7 = 18
wr_lock_key_slot_8 = 19
wr_lock_key_slot_9 = 20
wr_lock_key_slot_10 = 21
rd_lock_key_slot_4 = 25
rd_lock_key_slot_5 = 26
rd_lock_key_slot_6 = 27
rd_lock_key_slot_7 = 28
rd_lock_key_slot_8 = 29
rd_lock_key_slot_9 = 30
rd_lock_key_slot_10 = 31
def bytearray_data_merge(data1, data2, len):
for i in range(len):
data1[i] |= data2[i]
return data1
def img_update_efuse_group0(cfg, sign, pk_hash, flash_encryp_type, flash_key, sec_eng_key_sel, sec_eng_key, security=False):
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_file'), 'rb')
efuse_data = bytearray(fp.read()) + bytearray(0)
fp.close()
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_mask_file'), 'rb')
efuse_mask_data = bytearray(fp.read()) + bytearray(0)
fp.close()
mask_4bytes = bytearray.fromhex('FFFFFFFF')
if flash_encryp_type >= 3:
efuse_data[0] |= 3
else:
efuse_data[0] |= flash_encryp_type
if sign > 0:
efuse_data[92] |= sign << 7
efuse_mask_data[92] |= 255
if flash_encryp_type > 0:
efuse_data[0] |= 48
efuse_mask_data[0] |= 255
rw_lock0 = 0
rw_lock1 = 0
if pk_hash is not None:
efuse_data[keyslot0:keyslot2] = pk_hash
efuse_mask_data[keyslot0:keyslot2] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_0
rw_lock0 |= 1 << wr_lock_key_slot_1
if flash_key is not None:
if flash_encryp_type == 1:
efuse_data[keyslot2:keyslot3] = flash_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
else:
if flash_encryp_type == 2:
efuse_data[keyslot2:keyslot3_end] = flash_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
else:
if flash_encryp_type == 3:
efuse_data[keyslot2:keyslot3_end] = flash_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
else:
if flash_encryp_type == 4 or flash_encryp_type == 5 or flash_encryp_type == 6:
efuse_data[keyslot2:keyslot3_end] = flash_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
if sec_eng_key is not None:
if flash_encryp_type == 0:
if sec_eng_key_sel == 0:
efuse_data[keyslot2:keyslot3] = sec_eng_key[16:32]
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 1:
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[16:32]
efuse_data[keyslot4:keyslot5] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot3_end] = mask_4bytes * 4
efuse_mask_data[keyslot4:keyslot5] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock0 |= 1 << rd_lock_key_slot_3
rw_lock1 |= 1 << rd_lock_key_slot_4
if sec_eng_key_sel == 2:
efuse_data[keyslot4:keyslot5] = sec_eng_key[16:32]
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot5] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock0 |= 1 << rd_lock_key_slot_2
if sec_eng_key_sel == 3:
efuse_data[keyslot4:keyslot5] = sec_eng_key[16:32]
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot5] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock0 |= 1 << rd_lock_key_slot_2
if flash_encryp_type == 1:
if sec_eng_key_sel == 0:
efuse_data[keyslot5:keyslot6] = sec_eng_key[0:16]
efuse_mask_data[keyslot5:keyslot6] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_5
if sec_eng_key_sel == 1:
efuse_data[keyslot4:keyslot5] = sec_eng_key[0:16]
efuse_mask_data[keyslot4:keyslot5] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock1 |= 1 << rd_lock_key_slot_4
if sec_eng_key_sel == 2:
if flash_key is not None:
pass
else:
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot3_end] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 3:
if flash_key is not None:
pass
else:
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
if flash_encryp_type == 2 or flash_encryp_type == 3 or flash_encryp_type == 4 or flash_encryp_type == 5 or flash_encryp_type == 6:
if sec_eng_key_sel == 0:
efuse_data[keyslot6:keyslot7] = sec_eng_key[16:32]
efuse_data[keyslot10:keyslot10_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot6:keyslot7] = mask_4bytes * 4
efuse_mask_data[keyslot10:keyslot10_end] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_6
rw_lock1 |= 1 << wr_lock_key_slot_10
rw_lock1 |= 1 << rd_lock_key_slot_6
rw_lock1 |= 1 << rd_lock_key_slot_10
if sec_eng_key_sel == 1:
efuse_data[keyslot10:keyslot10_end] = sec_eng_key[16:32]
efuse_data[keyslot6:keyslot7] = sec_eng_key[0:16]
efuse_mask_data[keyslot6:keyslot7] = mask_4bytes * 4
efuse_mask_data[keyslot10:keyslot10_end] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_6
rw_lock1 |= 1 << wr_lock_key_slot_10
rw_lock1 |= 1 << rd_lock_key_slot_6
rw_lock1 |= 1 << rd_lock_key_slot_10
if sec_eng_key_sel == 2:
if flash_key is not None:
pass
else:
efuse_data[keyslot2:keyslot3] = sec_eng_key[16:32]
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 3:
if flash_key is not None:
pass
else:
efuse_data[keyslot2:keyslot3_end] = sec_eng_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
efuse_data[124:128] = bytearray_data_merge(efuse_data[124:128], bflb_utils.int_to_4bytearray_l(rw_lock0), 4)
efuse_mask_data[124:128] = bytearray_data_merge(efuse_mask_data[124:128], bflb_utils.int_to_4bytearray_l(rw_lock0), 4)
efuse_data[252:256] = bytearray_data_merge(efuse_data[252:256], bflb_utils.int_to_4bytearray_l(rw_lock1), 4)
efuse_mask_data[252:256] = bytearray_data_merge(efuse_mask_data[252:256], bflb_utils.int_to_4bytearray_l(rw_lock1), 4)
if security is True:
bflb_utils.printf('Encrypt efuse data')
security_key, security_iv = bflb_utils.get_security_key()
efuse_data = img_create_encrypt_data(efuse_data, security_key, security_iv, 0)
efuse_data = bytearray(4096) + efuse_data
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_file'), 'wb+')
fp.write(efuse_data)
fp.close()
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_mask_file'), 'wb+')
fp.write(efuse_mask_data)
fp.close()
def img_create_get_sign_encrypt_info(bootheader_data):
sign = bootheader_data[bootcfg_start] & 3
encrypt = bootheader_data[bootcfg_start] >> 2 & 3
key_sel = bootheader_data[bootcfg_start] >> 4 & 3
xts_mode = bootheader_data[bootcfg_start] >> 6 & 1
return (
sign, encrypt, key_sel, xts_mode)
def img_create_get_img_start_addr(bootheader_data):
bootentry = []
bootentry.append(bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(bootheader_data[bootcpucfg_start + bootcpucfg_length * bootcpucfg_m0_index_number + 16:bootcpucfg_start + bootcpucfg_length * bootcpucfg_m0_index_number + 16 + 4])))
return bootentry
def img_create_flash_default_data(length):
datas = bytearray(length)
for i in range(length):
datas[i] = 255
return datas
def img_get_file_data(files):
datas = []
for file in files:
if file == 'UNUSED':
datas.append(bytearray(0))
continue
else:
with open(file, 'rb') as fp:
data = fp.read()
datas.append(data)
return datas
def img_get_largest_addr(addrs, files):
min = 67108863
maxlen = 0
datalen = 0
for i in range(len(addrs)):
if files[i] == 'UNUSED':
continue
else:
addr = addrs[i] & 67108863
if addr >= maxlen:
maxlen = addr
datalen = os.path.getsize(files[i])
if addr <= min:
min = addr
if maxlen == 0:
if datalen == 0:
return (0, 0)
return (
maxlen + datalen - min, min)
def img_get_one_group_img(d_addrs, d_files):
whole_img_len, min = img_get_largest_addr(d_addrs, d_files)
whole_img_len &= 67108863
whole_img_data = img_create_flash_default_data(whole_img_len)
filedatas = img_get_file_data(d_files)
for i in range(len(d_addrs)):
if d_files[i] == 'UNUSED':
continue
else:
start_addr = d_addrs[i]
start_addr &= 67108863
start_addr -= min
whole_img_data[start_addr:start_addr + len(filedatas[i])] = filedatas[i]
return whole_img_data
def img_create_get_hash_ignore(bootheader_data):
return bootheader_data[bootcfg_start + 2] >> 1 & 1
def img_create_get_crc_ignore(bootheader_data):
return bootheader_data[bootcfg_start + 2] & 1
def img_create_update_bootheader_if(bootheader_data, hash, seg_cnt):
bootheader_data[bootcfg_start + 12:bootcfg_start + 12 + 4] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign = bootheader_data[bootcfg_start] & 3
encrypt = bootheader_data[bootcfg_start] >> 2 & 3
key_sel = bootheader_data[bootcfg_start] >> 4 & 3
xts_mode = bootheader_data[bootcfg_start] >> 6 & 1
if bootheader_data[bootcfg_start + 2] >> 1 & 1 == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[bootcfg_start + 16:bootcfg_start + 16 + 32] = hash
if bootheader_data[bootcfg_start + 2] & 1 == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[0:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data
def img_create_update_bootheader(bootheader_data, hash, seg_cnt, flashcfg_table_addr, flashcfg_table_len):
bootheader_data[flashcfg_table_start:flashcfg_table_start + 4] = bflb_utils.int_to_4bytearray_l(flashcfg_table_addr)
bootheader_data[flashcfg_table_start + 4:flashcfg_table_start + 8] = bflb_utils.int_to_4bytearray_l(flashcfg_table_len)
bootheader_data[bootcfg_start + 12:bootcfg_start + 12 + 4] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign, encrypt, key_sel, xts_mode = img_create_get_sign_encrypt_info(bootheader_data)
if img_create_get_hash_ignore(bootheader_data) == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[bootcfg_start + 16:bootcfg_start + 16 + 32] = hash
if img_create_get_crc_ignore(bootheader_data) == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[0:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data[0:header_len]
def img_create_update_segheader(segheader, segdatalen, segdatacrc):
segheader[4:8] = segdatalen
segheader[8:12] = segdatacrc
return segheader
def reverse_str_data_unit_number(str_data_unit_number):
"""
high position low data
data unit number:00000280
storage format: 80020000
"""
reverse_str = ''
if len(str_data_unit_number) == 8:
str_part1 = str_data_unit_number[0:2]
str_part2 = str_data_unit_number[2:4]
str_part3 = str_data_unit_number[4:6]
str_part4 = str_data_unit_number[6:8]
reverse_str = str_part4 + str_part3 + str_part2 + str_part1
return reverse_str
def reverse_iv(need_reverse_iv_bytearray):
temp_reverse_iv_bytearray = binascii.hexlify(need_reverse_iv_bytearray).decode()
if temp_reverse_iv_bytearray[24:32] != '00000000':
bflb_utils.printf('The lower 4 bytes of IV should be set 0, if set IV is less than 16 bytes, make up 0 for the low 4 bytes of IV ')
sys.exit()
reverse_iv_bytearray = '00000000' + temp_reverse_iv_bytearray[0:24]
return reverse_iv_bytearray
def img_create_encrypt_data_xts(data_bytearray, key_bytearray, iv_bytearray, encrypt):
counter = binascii.hexlify(iv_bytearray[4:16]).decode()
data_unit_number = 0
key = (
key_bytearray[0:16], key_bytearray[16:32])
if encrypt == 2 or encrypt == 3:
key = (
key_bytearray, key_bytearray)
cipher = AES_XTS.new(key, AES_XTS.MODE_XTS)
total_len = len(data_bytearray)
ciphertext = bytearray(0)
deal_len = 0
while deal_len < total_len:
data_unit_number = str(hex(data_unit_number)).replace('0x', '')
data_unit_number_to_str = str(data_unit_number)
right_justify_str = data_unit_number_to_str.rjust(8, '0')
reverse_data_unit_number_str = reverse_str_data_unit_number(right_justify_str)
tweak = reverse_data_unit_number_str + counter
tweak = bflb_utils.hexstr_to_bytearray('0' * (32 - len(tweak)) + tweak)
if 32 + deal_len <= total_len:
cur_block = data_bytearray[0 + deal_len:32 + deal_len]
ciphertext += cipher.encrypt(cur_block, tweak)
else:
cur_block = data_bytearray[0 + deal_len:16 + deal_len] + bytearray(16)
ciphertext += cipher.encrypt(cur_block, tweak)[0:16]
deal_len += 32
data_unit_number = int(data_unit_number, 16)
data_unit_number += 1
return ciphertext
def img_create_sign_data(data_bytearray, privatekey_file_uecc, publickey_file):
sk = ecdsa.SigningKey.from_pem(open(privatekey_file_uecc).read())
vk = ecdsa.VerifyingKey.from_pem(open(publickey_file).read())
pk_data = vk.to_string()
bflb_utils.printf('Private key: ', binascii.hexlify(sk.to_string()))
bflb_utils.printf('Public key: ', binascii.hexlify(pk_data))
pk_hash = img_create_sha256_data(pk_data)
bflb_utils.printf('Public key hash=', binascii.hexlify(pk_hash))
signature = sk.sign(data_bytearray, hashfunc=(hashlib.sha256), sigencode=(ecdsa.util.sigencode_string))
bflb_utils.printf('Signature=', binascii.hexlify(signature))
len_array = bflb_utils.int_to_4bytearray_l(len(signature))
sig_field = len_array + signature
crcarray = bflb_utils.get_crc32_bytearray(sig_field)
return (
pk_data, pk_hash, sig_field + crcarray)
def img_create_read_file_append_crc(file, crc):
fp = open(file, 'rb')
read_data = bytearray(fp.read())
crcarray = bytearray(0)
if crc:
crcarray = bflb_utils.get_crc32_bytearray(read_data)
fp.close()
return read_data + crcarray
def encrypt_loader_bin_do(file, sign, encrypt, temp_encrypt_key, temp_encrypt_iv, publickey_file, privatekey_file):
if encrypt != 0 or sign != 0:
encrypt_key = bytearray(0)
encrypt_iv = bytearray(0)
load_helper_bin_header = bytearray(0)
load_helper_bin_body = bytearray(0)
offset = bootcfg_start
sign_pos = 0
encrypt_type_pos = 2
pk_data = bytearray(0)
signature = bytearray(0)
aesiv_data = bytearray(0)
data_tohash = bytearray(0)
with open(file, 'rb') as fp:
load_helper_bin = fp.read()
load_helper_bin_header = load_helper_bin[0:header_len]
load_helper_bin_body = load_helper_bin[header_len:]
if load_helper_bin_header != bytearray(0):
if load_helper_bin_body != bytearray(0):
load_helper_bin_body = bflb_utils.add_to_16(load_helper_bin_body)
if encrypt != 0:
encrypt_key = bflb_utils.hexstr_to_bytearray(temp_encrypt_key)
encrypt_iv = bflb_utils.hexstr_to_bytearray(temp_encrypt_iv)
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
load_helper_bin_body_encrypt = bflb_utils.img_create_encrypt_data(load_helper_bin_body, encrypt_key, encrypt_iv, 0)
else:
load_helper_bin_body_encrypt = load_helper_bin_body
data = bytearray(load_helper_bin_header)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = oldval
if encrypt != 0:
newval = newval | 1 << encrypt_type_pos
if sign != 0:
newval = newval | 1 << sign_pos
data_tohash += load_helper_bin_body_encrypt
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
load_helper_bin_header = data
load_helper_bin_encrypt = load_helper_bin_header + pk_data + signature + aesiv_data + load_helper_bin_body_encrypt
hashfun = hashlib.sha256()
hashfun.update(load_helper_bin_body_encrypt)
hash = bflb_utils.hexstr_to_bytearray(hashfun.hexdigest())
load_helper_bin_data = bytearray(load_helper_bin_encrypt)
load_helper_bin_encrypt = img_create_update_bootheader_if(load_helper_bin_data, hash, 1)
return (
True, load_helper_bin_encrypt)
return (False, None)
def img_creat_process(group_type, flash_img, cfg, security=False):
encrypt_blk_size = 16
padding = bytearray(encrypt_blk_size)
data_tohash = bytearray(0)
cfg_section = ''
img_update_efuse_fun = img_update_efuse_group0
cfg_section = 'Img_Group0_Cfg'
segheader_file = []
if flash_img == 0:
for files in cfg.get(cfg_section, 'segheader_file').split(' '):
segheader_file.append(str(files))
segdata_file = []
for files in cfg.get(cfg_section, 'segdata_file').split('|'):
if files:
segdata_file.append(str(files))
boot_header_file = cfg.get(cfg_section, 'boot_header_file')
bootheader_data = img_create_read_file_append_crc(boot_header_file, 0)
encrypt = 0
sign, encrypt, key_sel, xts_mode = img_create_get_sign_encrypt_info(bootheader_data)
boot_entry = img_create_get_img_start_addr(bootheader_data)
aesiv_data = bytearray(0)
pk_data = bytearray(0)
publickey_file = ''
privatekey_file_uecc = ''
if sign != 0:
bflb_utils.printf('Image need sign')
publickey_file = cfg.get(cfg_section, 'publickey_file')
privatekey_file_uecc = cfg.get(cfg_section, 'privatekey_file_uecc')
if encrypt != 0:
bflb_utils.printf('Image need encrypt ', encrypt)
if xts_mode == 1:
bflb_utils.printf('Enable xts mode')
encrypt_key_org = bflb_utils.hexstr_to_bytearray(cfg.get(cfg_section, 'aes_key_org'))
if encrypt == 1:
if xts_mode == 1:
encrypt_key = encrypt_key_org[0:32]
else:
encrypt_key = encrypt_key_org[0:16]
else:
if encrypt == 2:
if xts_mode == 1:
encrypt_key = encrypt_key_org[0:32]
else:
encrypt_key = encrypt_key_org[0:32]
else:
if encrypt == 3:
if xts_mode == 1:
encrypt_key = encrypt_key_org[0:24]
else:
encrypt_key = encrypt_key_org[0:24]
bflb_utils.printf('Key= ', binascii.hexlify(encrypt_key))
iv_value = cfg.get(cfg_section, 'aes_iv')
if xts_mode == 1:
iv_value = iv_value[24:32] + iv_value[:24]
encrypt_iv = bflb_utils.hexstr_to_bytearray(iv_value)
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
seg_cnt = len(segheader_file)
segdata_cnt = len(segdata_file)
if flash_img == 0:
if seg_cnt != segdata_cnt:
bflb_utils.printf('Segheader count and segdata count not match')
return (
'FAIL', data_tohash)
data_toencrypt = bytearray(0)
if flash_img == 0:
i = 0
seg_header_list = []
seg_data_list = []
while i < seg_cnt:
seg_data = bytearray(0)
if segdata_file[i] != 'UNUSED':
seg_data = img_create_read_file_append_crc(segdata_file[i], 0)
else:
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
segdata_crcarray = bflb_utils.get_crc32_bytearray(seg_data)
seg_data_list.append(seg_data)
seg_header = img_create_read_file_append_crc(segheader_file[i], 0)
seg_header = img_create_update_segheader(seg_header, bflb_utils.int_to_4bytearray_l(len(seg_data)), segdata_crcarray)
segheader_crcarray = bflb_utils.get_crc32_bytearray(seg_header)
seg_header = seg_header + segheader_crcarray
seg_header_list.append(seg_header)
i = i + 1
i = 0
cnt = 0
while i < seg_cnt:
if seg_header_list[i][4:8] != bytearray(4):
data_toencrypt += seg_header_list[i]
data_toencrypt += seg_data_list[i]
cnt += 1
else:
i += 1
seg_cnt = cnt
else:
seg_data = img_get_one_group_img(boot_entry, segdata_file)
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
data_toencrypt += seg_data
seg_cnt = len(data_toencrypt)
if encrypt != 0:
unencrypt_mfg_data = bytearray(0)
if seg_cnt >= 8192:
if data_toencrypt[4096:4100] == bytearray('0mfg'.encode('utf-8')):
unencrypt_mfg_data = data_toencrypt[4096:8192]
if xts_mode != 0:
data_toencrypt = img_create_encrypt_data_xts(data_toencrypt, encrypt_key, encrypt_iv, encrypt)
else:
data_toencrypt = img_create_encrypt_data(data_toencrypt, encrypt_key, encrypt_iv, flash_img)
if unencrypt_mfg_data != bytearray(0):
data_toencrypt = data_toencrypt[0:4096] + unencrypt_mfg_data + data_toencrypt[8192:]
fw_data = bytearray(0)
data_tohash += data_toencrypt
fw_data = data_toencrypt
hash = img_create_sha256_data(data_tohash)
bflb_utils.printf('Image hash is ', binascii.hexlify(hash))
signature = bytearray(0)
pk_hash = None
if sign == 1:
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file_uecc, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
flashCfgAddr = len(bootheader_data + pk_data + signature + aesiv_data)
flashCfgListLen = 0
flashCfgList = bytearray(0)
flashCfgTable = bytearray(0)
if flash_img == 1:
if bootheader_data[25:26] == b'\xff':
flashCfgList, flashCfgTable, flashCfgListLen = create_flashcfg_table(flashCfgAddr)
bootheader_data = img_create_update_bootheader(bootheader_data, hash, seg_cnt, flashCfgAddr, flashCfgListLen)
if flash_img == 1:
bflb_utils.printf('Write flash img')
bootinfo_file_name = cfg.get(cfg_section, 'bootinfo_file')
fp = open(bootinfo_file_name, 'wb+')
bootinfo = bootheader_data + pk_data + signature + aesiv_data + flashCfgList + flashCfgTable
fp.write(bootinfo)
fp.close()
fw_file_name = cfg.get(cfg_section, 'img_file')
fp = open(fw_file_name, 'wb+')
fp.write(fw_data)
fp.close()
fw_data_hash = img_create_sha256_data(fw_data)
fp = open(fw_file_name.replace('.bin', '_withhash.bin'), 'wb+')
fp.write(fw_data + fw_data_hash)
fp.close()
if encrypt != 0:
flash_encrypt_type = 0
if encrypt == 1:
flash_encrypt_type = 1
if encrypt == 2:
flash_encrypt_type = 3
if encrypt == 3:
flash_encrypt_type = 2
if xts_mode == 1:
flash_encrypt_type += 3
img_update_efuse_fun(cfg, sign, pk_hash, flash_encrypt_type, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, None, security)
else:
img_update_efuse_fun(cfg, sign, pk_hash, encrypt, None, key_sel, None, security)
else:
bflb_utils.printf('Write if img')
whole_img_file_name = cfg.get(cfg_section, 'whole_img_file')
fp = open(whole_img_file_name, 'wb+')
img_data = bootheader_data + pk_data + signature + aesiv_data + fw_data
fp.write(img_data)
fp.close()
if encrypt != 0:
if_encrypt_type = 0
if encrypt == 1:
if_encrypt_type = 1
if encrypt == 2:
if_encrypt_type = 3
if encrypt == 3:
if_encrypt_type = 2
if xts_mode == 1:
if_encrypt_type += 3
img_update_efuse_fun(cfg, sign, pk_hash, if_encrypt_type, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
else:
img_update_efuse_fun(cfg, sign, pk_hash, 0, None, key_sel, bytearray(32), security)
return (
'OK', data_tohash)
def img_create_do(args, img_dir_path=None, config_file=None):
bflb_utils.printf('Image create path: ', img_dir_path)
if config_file is None:
config_file = img_dir_path + '/img_create_cfg.ini'
bflb_utils.printf('Config file: ', config_file)
cfg = BFConfigParser()
cfg.read(config_file)
group_type = 'all'
img_type = 'media'
signer = 'none'
security = False
data_tohash = bytearray(0)
try:
if args.image:
img_type = args.image
if args.group:
group_type = args.group
if args.signer:
signer = args.signer
if args.security:
security = args.security == 'efuse'
except Exception as e:
try:
bflb_utils.printf(e)
finally:
e = None
del e
if img_type == 'media':
flash_img = 1
else:
flash_img = 0
ret0 = ret1 = 'OK'
if group_type == 'group0' or group_type == 'all':
ret0, data_tohash0 = img_creat_process('group0', flash_img, cfg, security)
else:
img_creat_process('', flash_img, cfg, security)
if ret0 != 'OK':
bflb_utils.printf('Fail to create group0 images!')
return
if ret1 != 'OK':
bflb_utils.printf('Fail to create group1 images!')
def create_sp_media_image(config, cpu_type=None, security=False):
bflb_utils.printf('========= sp image create =========')
cfg = BFConfigParser()
cfg.read(config)
img_creat_process('group0', 1, cfg, security)
if __name__ == '__main__':
data_bytearray = codecs.decode('42464E500100000046434647040101036699FF039F00B7E904EF0001C72052D8060232000B010B013B01BB006B01EB02EB02025000010001010002010101AB01053500000131000038FF20FF77030240770302F02C01B004B0040500FFFF030036C3DD9E5043464704040001010105000101050000010101A612AC86000144650020000000000000503100007A6345494BCABEC7307FD8F8396729EB67DDC8C63B7AD69B797B08564E982A8701000000000000000000000000000000000000D80000000000010000000000000000000000200100000001D80000000000010000000000000000000000200200000002580000000000010000000000000000000000200300000003580000000000010000D0C57503C09E750300200400000004580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000935F92BB', 'hex')
key_bytearray = codecs.decode('fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0000102030405060708090a0b0c0d0e0f', 'hex')
need_reverse_iv_bytearray = codecs.decode('01000000000000000000000000000000', 'hex')
iv_bytearray = codecs.decode(reverse_iv(need_reverse_iv_bytearray), 'hex')
img_create_encrypt_data_xts(data_bytearray, key_bytearray, iv_bytearray, 0)
# okay decompiling ./libs/base/bl616/img_create_do.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl616/jlink_load_cfg.py
jlink_shake_hand_addr = '4201BFF0'
jlink_data_addr = '4201C000'
jlink_load_addr = '22010000'
jlink_core_type = 'RISC-V'
jlink_set_tif = 0
jlink_run_addr = '22010000'
# okay decompiling ./libs/base/bl616/jlink_load_cfg.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl616/openocd_load_cfg.py
openocd_shake_hand_addr = '4201BFF0'
openocd_data_addr = '4201C000'
openocd_load_addr = '22010000'
openocd_core_type = 'RISC-V'
openocd_set_tif = 0
openocd_run_addr = '22010000'
# okay decompiling ./libs/base/bl616/openocd_load_cfg.pyc

View File

@ -0,0 +1,343 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702/bootheader_cfg_keys.py
bootheader_len = 176
bootheader_cfg_keys = {'magic_code':{'offset':'0',
'pos':'0',
'bitlen':'32'},
'revision':{'offset':'4',
'pos':'0',
'bitlen':'32'},
'flashcfg_magic_code':{'offset':'8',
'pos':'0',
'bitlen':'32'},
'io_mode':{'offset':'12',
'pos':'0',
'bitlen':'8'},
'cont_read_support':{'offset':'12',
'pos':'8',
'bitlen':'8'},
'sfctrl_clk_delay':{'offset':'12',
'pos':'16',
'bitlen':'8'},
'sfctrl_clk_invert':{'offset':'12',
'pos':'24',
'bitlen':'8'},
'reset_en_cmd':{'offset':'16',
'pos':'0',
'bitlen':'8'},
'reset_cmd':{'offset':'16',
'pos':'8',
'bitlen':'8'},
'exit_contread_cmd':{'offset':'16',
'pos':'16',
'bitlen':'8'},
'exit_contread_cmd_size':{'offset':'16',
'pos':'24',
'bitlen':'8'},
'jedecid_cmd':{'offset':'20',
'pos':'0',
'bitlen':'8'},
'jedecid_cmd_dmy_clk':{'offset':'20',
'pos':'8',
'bitlen':'8'},
'qpi_jedecid_cmd':{'offset':'20',
'pos':'16',
'bitlen':'8'},
'qpi_jedecid_dmy_clk':{'offset':'20',
'pos':'24',
'bitlen':'8'},
'sector_size':{'offset':'24',
'pos':'0',
'bitlen':'8'},
'mfg_id':{'offset':'24',
'pos':'8',
'bitlen':'8'},
'page_size':{'offset':'24',
'pos':'16',
'bitlen':'16'},
'chip_erase_cmd':{'offset':'28',
'pos':'0',
'bitlen':'8'},
'sector_erase_cmd':{'offset':'28',
'pos':'8',
'bitlen':'8'},
'blk32k_erase_cmd':{'offset':'28',
'pos':'16',
'bitlen':'8'},
'blk64k_erase_cmd':{'offset':'28',
'pos':'24',
'bitlen':'8'},
'write_enable_cmd':{'offset':'32',
'pos':'0',
'bitlen':'8'},
'page_prog_cmd':{'offset':'32',
'pos':'8',
'bitlen':'8'},
'qpage_prog_cmd':{'offset':'32',
'pos':'16',
'bitlen':'8'},
'qual_page_prog_addr_mode':{'offset':'32',
'pos':'24',
'bitlen':'8'},
'fast_read_cmd':{'offset':'36',
'pos':'0',
'bitlen':'8'},
'fast_read_dmy_clk':{'offset':'36',
'pos':'8',
'bitlen':'8'},
'qpi_fast_read_cmd':{'offset':'36',
'pos':'16',
'bitlen':'8'},
'qpi_fast_read_dmy_clk':{'offset':'36',
'pos':'24',
'bitlen':'8'},
'fast_read_do_cmd':{'offset':'40',
'pos':'0',
'bitlen':'8'},
'fast_read_do_dmy_clk':{'offset':'40',
'pos':'8',
'bitlen':'8'},
'fast_read_dio_cmd':{'offset':'40',
'pos':'16',
'bitlen':'8'},
'fast_read_dio_dmy_clk':{'offset':'40',
'pos':'24',
'bitlen':'8'},
'fast_read_qo_cmd':{'offset':'44',
'pos':'0',
'bitlen':'8'},
'fast_read_qo_dmy_clk':{'offset':'44',
'pos':'8',
'bitlen':'8'},
'fast_read_qio_cmd':{'offset':'44',
'pos':'16',
'bitlen':'8'},
'fast_read_qio_dmy_clk':{'offset':'44',
'pos':'24',
'bitlen':'8'},
'qpi_fast_read_qio_cmd':{'offset':'48',
'pos':'0',
'bitlen':'8'},
'qpi_fast_read_qio_dmy_clk':{'offset':'48',
'pos':'8',
'bitlen':'8'},
'qpi_page_prog_cmd':{'offset':'48',
'pos':'16',
'bitlen':'8'},
'write_vreg_enable_cmd':{'offset':'48',
'pos':'24',
'bitlen':'8'},
'wel_reg_index':{'offset':'52',
'pos':'0',
'bitlen':'8'},
'qe_reg_index':{'offset':'52',
'pos':'8',
'bitlen':'8'},
'busy_reg_index':{'offset':'52',
'pos':'16',
'bitlen':'8'},
'wel_bit_pos':{'offset':'52',
'pos':'24',
'bitlen':'8'},
'qe_bit_pos':{'offset':'56',
'pos':'0',
'bitlen':'8'},
'busy_bit_pos':{'offset':'56',
'pos':'8',
'bitlen':'8'},
'wel_reg_write_len':{'offset':'56',
'pos':'16',
'bitlen':'8'},
'wel_reg_read_len':{'offset':'56',
'pos':'24',
'bitlen':'8'},
'qe_reg_write_len':{'offset':'60',
'pos':'0',
'bitlen':'8'},
'qe_reg_read_len':{'offset':'60',
'pos':'8',
'bitlen':'8'},
'release_power_down':{'offset':'60',
'pos':'16',
'bitlen':'8'},
'busy_reg_read_len':{'offset':'60',
'pos':'24',
'bitlen':'8'},
'reg_read_cmd0':{'offset':'64',
'pos':'0',
'bitlen':'8'},
'reg_read_cmd1':{'offset':'64',
'pos':'8',
'bitlen':'8'},
'reg_write_cmd0':{'offset':'68',
'pos':'0',
'bitlen':'8'},
'reg_write_cmd1':{'offset':'68',
'pos':'8',
'bitlen':'8'},
'enter_qpi_cmd':{'offset':'72',
'pos':'0',
'bitlen':'8'},
'exit_qpi_cmd':{'offset':'72',
'pos':'8',
'bitlen':'8'},
'cont_read_code':{'offset':'72',
'pos':'16',
'bitlen':'8'},
'cont_read_exit_code':{'offset':'72',
'pos':'24',
'bitlen':'8'},
'burst_wrap_cmd':{'offset':'76',
'pos':'0',
'bitlen':'8'},
'burst_wrap_dmy_clk':{'offset':'76',
'pos':'8',
'bitlen':'8'},
'burst_wrap_data_mode':{'offset':'76',
'pos':'16',
'bitlen':'8'},
'burst_wrap_code':{'offset':'76',
'pos':'24',
'bitlen':'8'},
'de_burst_wrap_cmd':{'offset':'80',
'pos':'0',
'bitlen':'8'},
'de_burst_wrap_cmd_dmy_clk':{'offset':'80',
'pos':'8',
'bitlen':'8'},
'de_burst_wrap_code_mode':{'offset':'80',
'pos':'16',
'bitlen':'8'},
'de_burst_wrap_code':{'offset':'80',
'pos':'24',
'bitlen':'8'},
'sector_erase_time':{'offset':'84',
'pos':'0',
'bitlen':'16'},
'blk32k_erase_time':{'offset':'84',
'pos':'16',
'bitlen':'16'},
'blk64k_erase_time':{'offset':'88',
'pos':'0',
'bitlen':'16'},
'page_prog_time':{'offset':'88',
'pos':'16',
'bitlen':'16'},
'chip_erase_time':{'offset':'92',
'pos':'0',
'bitlen':'16'},
'power_down_delay':{'offset':'92',
'pos':'16',
'bitlen':'8'},
'qe_data':{'offset':'92',
'pos':'24',
'bitlen':'8'},
'flashcfg_crc32':{'offset':'96',
'pos':'0',
'bitlen':'32'},
'clkcfg_magic_code':{'offset':'100',
'pos':'0',
'bitlen':'32'},
'xtal_type':{'offset':'104',
'pos':'0',
'bitlen':'8'},
'pll_clk':{'offset':'104',
'pos':'8',
'bitlen':'8'},
'hclk_div':{'offset':'104',
'pos':'16',
'bitlen':'8'},
'bclk_div':{'offset':'104',
'pos':'24',
'bitlen':'8'},
'flash_clk_type':{'offset':'108',
'pos':'0',
'bitlen':'8'},
'flash_clk_div':{'offset':'108',
'pos':'8',
'bitlen':'8'},
'clkcfg_crc32':{'offset':'112',
'pos':'0',
'bitlen':'32'},
'sign':{'offset':'116',
'pos':'0',
'bitlen':'2'},
'encrypt_type':{'offset':'116',
'pos':'2',
'bitlen':'2'},
'key_sel':{'offset':'116',
'pos':'4',
'bitlen':'2'},
'no_segment':{'offset':'116',
'pos':'8',
'bitlen':'1'},
'cache_enable':{'offset':'116',
'pos':'9',
'bitlen':'1'},
'notload_in_bootrom':{'offset':'116',
'pos':'10',
'bitlen':'1'},
'aes_region_lock':{'offset':'116',
'pos':'11',
'bitlen':'1'},
'cache_way_disable':{'offset':'116',
'pos':'12',
'bitlen':'4'},
'crc_ignore':{'offset':'116',
'pos':'16',
'bitlen':'1'},
'hash_ignore':{'offset':'116',
'pos':'17',
'bitlen':'1'},
'boot2_enable':{'offset':'116',
'pos':'19',
'bitlen':'1'},
'boot2_rollback':{'offset':'116',
'pos':'20',
'bitlen':'1'},
'img_len':{'offset':'120',
'pos':'0',
'bitlen':'32'},
'bootentry':{'offset':'124',
'pos':'0',
'bitlen':'32'},
'img_start':{'offset':'128',
'pos':'0',
'bitlen':'32'},
'hash_0':{'offset':'132',
'pos':'0',
'bitlen':'32'},
'hash_1':{'offset':'136',
'pos':'0',
'bitlen':'32'},
'hash_2':{'offset':'140',
'pos':'0',
'bitlen':'32'},
'hash_3':{'offset':'144',
'pos':'0',
'bitlen':'32'},
'hash_4':{'offset':'148',
'pos':'0',
'bitlen':'32'},
'hash_5':{'offset':'152',
'pos':'0',
'bitlen':'32'},
'hash_6':{'offset':'156',
'pos':'0',
'bitlen':'32'},
'hash_7':{'offset':'160',
'pos':'0',
'bitlen':'32'},
'boot2_pt_table_0':{'offset':'164',
'pos':'0',
'bitlen':'32'},
'boot2_pt_table_1':{'offset':'168',
'pos':'0',
'bitlen':'32'},
'crc32':{'offset':'172',
'pos':'0',
'bitlen':'32'}}
# okay decompiling ./libs/base/bl702/bootheader_cfg_keys.pyc

View File

@ -0,0 +1,62 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702/chiptype_patch.py
def img_load_create_predata_before_run_img():
pre_data = bytearray(12)
pre_data[0] = 80
pre_data[1] = 0
pre_data[2] = 8
pre_data[3] = 0
pre_data[4] = 0
pre_data[5] = 241
pre_data[6] = 0
pre_data[7] = 64
pre_data[8] = 69
pre_data[9] = 72
pre_data[10] = 66
pre_data[11] = 78
pre_data2 = bytearray(12)
pre_data2[0] = 80
pre_data2[1] = 0
pre_data2[2] = 8
pre_data2[3] = 0
pre_data2[4] = 4
pre_data2[5] = 241
pre_data2[6] = 0
pre_data2[7] = 64
pre_data2[8] = 0
pre_data2[9] = 0
pre_data2[10] = 1
pre_data2[11] = 34
pre_data3 = bytearray(12)
pre_data3[0] = 80
pre_data3[1] = 0
pre_data3[2] = 8
pre_data3[3] = 0
pre_data3[4] = 24
pre_data3[5] = 0
pre_data3[6] = 0
pre_data3[7] = 64
pre_data3[8] = 0
pre_data3[9] = 0
pre_data3[10] = 0
pre_data3[11] = 0
pre_data4 = bytearray(12)
pre_data4[0] = 80
pre_data4[1] = 0
pre_data4[2] = 8
pre_data4[3] = 0
pre_data4[4] = 24
pre_data4[5] = 0
pre_data4[6] = 0
pre_data4[7] = 64
pre_data4[8] = 2
pre_data4[9] = 0
pre_data4[10] = 0
pre_data4[11] = 0
return pre_data + pre_data2 + pre_data3 + pre_data4
# okay decompiling ./libs/base/bl702/chiptype_patch.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702/cklink_load_cfg.py
cklink_shake_hand_addr = '4202BFF0'
cklink_data_addr = '4202C000'
cklink_load_addr = '22010000'
cklink_core_type = 'RISC-V'
cklink_set_tif = 0
cklink_run_addr = '22010000'
# okay decompiling ./libs/base/bl702/cklink_load_cfg.pyc

View File

@ -0,0 +1,64 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702/flash_select_do.py
import os, config as gol
from libs import bflb_utils
from libs.bflb_utils import app_path, conf_sign
from libs.bflb_configobj import BFConfigParser
def get_suitable_file_name(cfg_dir, flash_id):
conf_files = []
for home, dirs, files in os.walk(cfg_dir):
for filename in files:
if filename.split('_')[-1] == flash_id + '.conf':
conf_files.append(filename)
if len(conf_files) > 1:
bflb_utils.printf('Flash id duplicate and alternative is:')
for i in range(len(conf_files)):
tmp = conf_files[i].split('.')[0]
bflb_utils.printf('%d:%s' % (i + 1, tmp))
return conf_files[i]
if len(conf_files) == 1:
return conf_files[0]
return ''
def update_flash_cfg_do(chipname, chiptype, flash_id, file=None, create=False, section=None):
if conf_sign:
cfg_dir = app_path + '/utils/flash/' + chipname + '/'
else:
cfg_dir = app_path + '/utils/flash/' + gol.flash_dict[chipname] + '/'
conf_name = get_suitable_file_name(cfg_dir, flash_id)
value_key = []
if os.path.isfile(cfg_dir + conf_name) is False:
return False
fp = open(cfg_dir + conf_name, 'r')
for line in fp.readlines():
value = line.split('=')[0].strip()
if value == '[FLASH_CFG]':
continue
else:
value_key.append(value)
cfg1 = BFConfigParser()
cfg1.read(cfg_dir + conf_name)
cfg2 = BFConfigParser()
cfg2.read(file)
for i in range(len(value_key)):
if cfg1.has_option('FLASH_CFG', value_key[i]):
if cfg2.has_option(section, value_key[i]):
tmp_value = cfg1.get('FLASH_CFG', value_key[i])
bflb_utils.update_cfg(cfg2, section, value_key[i], tmp_value)
cfg2.write(file, 'w+')
bflb_utils.printf('Update flash cfg finished')
def get_supported_flash_do():
flash_type = []
return flash_type
# okay decompiling ./libs/base/bl702/flash_select_do.pyc

View File

@ -0,0 +1,428 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702/img_create_do.py
import hashlib, binascii, ecdsa
from libs import bflb_utils
from libs.bflb_utils import img_create_sha256_data, img_create_encrypt_data
from libs.bflb_configobj import BFConfigParser
from libs.base.bl702.bootheader_cfg_keys import bootheader_len as header_len
keyslot0 = 28
keyslot1 = keyslot0 + 16
keyslot2 = keyslot1 + 16
keyslot3 = keyslot2 + 16
keyslot4 = keyslot3 + 16
keyslot5 = keyslot4 + 16
keyslot6 = keyslot5 + 16
wr_lock_key_slot_4_l = 13
wr_lock_key_slot_5_l = 14
wr_lock_boot_mode = 15
wr_lock_dbg_pwd = 16
wr_lock_sw_usage_0 = 17
wr_lock_wifi_mac = 18
wr_lock_key_slot_0 = 19
wr_lock_key_slot_1 = 20
wr_lock_key_slot_2 = 21
wr_lock_key_slot_3 = 22
wr_lock_key_slot_4_h = 23
wr_lock_key_slot_5_h = 24
rd_lock_dbg_pwd = 25
rd_lock_key_slot_0 = 26
rd_lock_key_slot_1 = 27
rd_lock_key_slot_2 = 28
rd_lock_key_slot_3 = 29
rd_lock_key_slot_4 = 30
rd_lock_key_slot_5 = 31
def img_update_efuse(cfg, sign, pk_hash, flash_encryp_type, flash_key, sec_eng_key_sel, sec_eng_key, security=False):
fp = open(cfg.get('Img_Cfg', 'efuse_file'), 'rb')
efuse_data = bytearray(fp.read()) + bytearray(0)
fp.close()
fp = open(cfg.get('Img_Cfg', 'efuse_mask_file'), 'rb')
efuse_mask_data = bytearray(fp.read()) + bytearray(0)
fp.close()
mask_4bytes = bytearray.fromhex('FFFFFFFF')
efuse_data[0] |= flash_encryp_type
efuse_data[0] |= sign << 2
if flash_encryp_type > 0:
efuse_data[0] |= 128
efuse_data[0] |= 48
efuse_mask_data[0] |= 255
rw_lock = 0
if pk_hash is not None:
efuse_data[keyslot0:keyslot2] = pk_hash
efuse_mask_data[keyslot0:keyslot2] = mask_4bytes * 8
rw_lock |= 1 << wr_lock_key_slot_0
rw_lock |= 1 << wr_lock_key_slot_1
if flash_key is not None:
if flash_encryp_type == 1:
efuse_data[keyslot2:keyslot3] = flash_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
else:
if flash_encryp_type == 2:
efuse_data[keyslot2:keyslot4] = flash_key
efuse_mask_data[keyslot2:keyslot4] = mask_4bytes * 8
rw_lock |= 1 << wr_lock_key_slot_3
rw_lock |= 1 << rd_lock_key_slot_3
else:
if flash_encryp_type == 3:
efuse_data[keyslot2:keyslot4] = flash_key
efuse_mask_data[keyslot2:keyslot4] = mask_4bytes * 8
rw_lock |= 1 << wr_lock_key_slot_3
rw_lock |= 1 << rd_lock_key_slot_3
rw_lock |= 1 << wr_lock_key_slot_2
rw_lock |= 1 << rd_lock_key_slot_2
if sec_eng_key is not None:
if flash_encryp_type == 0:
if sec_eng_key_sel == 0:
efuse_data[keyslot3:keyslot4] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot4] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_3
rw_lock |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 1:
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_2
rw_lock |= 1 << rd_lock_key_slot_2
if flash_encryp_type == 1:
if sec_eng_key_sel == 0:
efuse_data[keyslot5:keyslot6] = sec_eng_key[0:16]
efuse_mask_data[keyslot5:keyslot6] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_5_l
rw_lock |= 1 << wr_lock_key_slot_5_h
rw_lock |= 1 << rd_lock_key_slot_5
if sec_eng_key_sel == 1:
efuse_data[keyslot4:keyslot5] = sec_eng_key[0:16]
efuse_mask_data[keyslot4:keyslot5] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_4_l
rw_lock |= 1 << wr_lock_key_slot_4_h
rw_lock |= 1 << rd_lock_key_slot_4
efuse_data[124:128] = bflb_utils.int_to_4bytearray_l(rw_lock)
efuse_mask_data[124:128] = bflb_utils.int_to_4bytearray_l(rw_lock)
if security is True:
bflb_utils.printf('Encrypt efuse data')
security_key, security_iv = bflb_utils.get_security_key()
efuse_data = img_create_encrypt_data(efuse_data, security_key, security_iv, 0)
efuse_data = bytearray(4096) + efuse_data
fp = open(cfg.get('Img_Cfg', 'efuse_file'), 'wb+')
fp.write(efuse_data)
fp.close()
fp = open(cfg.get('Img_Cfg', 'efuse_mask_file'), 'wb+')
fp.write(efuse_mask_data)
fp.close()
def img_create_get_sign_encrypt_info(bootheader_data):
sign = bootheader_data[116] & 3
encrypt = bootheader_data[116] >> 2 & 3
key_sel = bootheader_data[116] >> 4 & 3
return (
sign, encrypt, key_sel)
def img_create_get_hash_ignore(bootheader_data):
return bootheader_data[118] >> 1 & 1
def img_create_get_crc_ignore(bootheader_data):
return bootheader_data[118] & 1
def img_create_update_bootheader_if(bootheader_data, hash, seg_cnt):
bootheader_data[120:124] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign = bootheader_data[116] & 3
encrypt = bootheader_data[116] >> 2 & 3
key_sel = bootheader_data[116] >> 4 & 3
if bootheader_data[118] >> 1 & 1 == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[132:164] = hash
if bootheader_data[118] & 1 == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[0:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data
def img_create_update_bootheader(bootheader_data, hash, seg_cnt):
bootheader_data[120:124] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign, encrypt, key_sel = img_create_get_sign_encrypt_info(bootheader_data)
if img_create_get_hash_ignore(bootheader_data) == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[132:164] = hash
if img_create_get_crc_ignore(bootheader_data) == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[0:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data[0:header_len]
def img_create_update_segheader(segheader, segdatalen, segdatacrc):
segheader[4:8] = segdatalen
segheader[8:12] = segdatacrc
return segheader
def img_create_sign_data(data_bytearray, privatekey_file_uecc, publickey_file):
sk = ecdsa.SigningKey.from_pem(open(privatekey_file_uecc).read())
vk = ecdsa.VerifyingKey.from_pem(open(publickey_file).read())
pk_data = vk.to_string()
bflb_utils.printf('Private key: ', binascii.hexlify(sk.to_string()))
bflb_utils.printf('Public key: ', binascii.hexlify(pk_data))
pk_hash = img_create_sha256_data(pk_data)
bflb_utils.printf('Public key hash=', binascii.hexlify(pk_hash))
signature = sk.sign(data_bytearray, hashfunc=(hashlib.sha256), sigencode=(ecdsa.util.sigencode_string))
bflb_utils.printf('Signature=', binascii.hexlify(signature))
len_array = bflb_utils.int_to_4bytearray_l(len(signature))
sig_field = len_array + signature
crcarray = bflb_utils.get_crc32_bytearray(sig_field)
return (
pk_data, pk_hash, sig_field + crcarray)
def img_create_read_file_append_crc(file, crc):
fp = open(file, 'rb')
read_data = bytearray(fp.read())
crcarray = bytearray(0)
if crc:
crcarray = bflb_utils.get_crc32_bytearray(read_data)
fp.close()
return read_data + crcarray
def encrypt_loader_bin_do(file, sign, encrypt, temp_encrypt_key, temp_encrypt_iv, publickey_file, privatekey_file):
if encrypt != 0 or sign != 0:
encrypt_key = bytearray(0)
encrypt_iv = bytearray(0)
load_helper_bin_header = bytearray(0)
load_helper_bin_body = bytearray(0)
offset = 116
sign_pos = 0
encrypt_type_pos = 2
key_sel_pos = 4
pk_data = bytearray(0)
signature = bytearray(0)
aesiv_data = bytearray(0)
data_tohash = bytearray(0)
with open(file, 'rb') as fp:
load_helper_bin = fp.read()
load_helper_bin_header = load_helper_bin[0:header_len]
load_helper_bin_body = load_helper_bin[header_len:]
if load_helper_bin_header != bytearray(0):
if load_helper_bin_body != bytearray(0):
load_helper_bin_body = bflb_utils.add_to_16(load_helper_bin_body)
if encrypt != 0:
encrypt_key = bflb_utils.hexstr_to_bytearray(temp_encrypt_key)
encrypt_iv = bflb_utils.hexstr_to_bytearray(temp_encrypt_iv)
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
load_helper_bin_body_encrypt = bflb_utils.img_create_encrypt_data(load_helper_bin_body, encrypt_key, encrypt_iv, 0)
else:
load_helper_bin_body_encrypt = load_helper_bin_body
data = bytearray(load_helper_bin_header)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = oldval
if encrypt != 0:
newval = newval | 1 << encrypt_type_pos
newval = newval | 1 << key_sel_pos
if sign != 0:
newval = newval | 1 << sign_pos
data_tohash += load_helper_bin_body_encrypt
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
load_helper_bin_header = data
load_helper_bin_encrypt = load_helper_bin_header + pk_data + signature + aesiv_data + load_helper_bin_body_encrypt
hashfun = hashlib.sha256()
hashfun.update(data_tohash)
hash = bflb_utils.hexstr_to_bytearray(hashfun.hexdigest())
load_helper_bin_data = bytearray(load_helper_bin_encrypt)
load_helper_bin_encrypt = img_create_update_bootheader_if(load_helper_bin_data, hash, 1)
return (
True, load_helper_bin_encrypt)
return (False, None)
def img_creat_process(flash_img, cfg, security=False):
encrypt_blk_size = 16
padding = bytearray(encrypt_blk_size)
data_tohash = bytearray(0)
cfg_section = 'Img_Cfg'
segheader_file = []
if flash_img == 0:
for files in cfg.get(cfg_section, 'segheader_file').split(' '):
segheader_file.append(str(files))
segdata_file = []
for files in cfg.get(cfg_section, 'segdata_file').split('|'):
segdata_file.append(str(files))
if flash_img == 1:
break
boot_header_file = cfg.get(cfg_section, 'boot_header_file')
bootheader_data = img_create_read_file_append_crc(boot_header_file, 0)
encrypt = 0
sign, encrypt, key_sel = img_create_get_sign_encrypt_info(bootheader_data)
aesiv_data = bytearray(0)
pk_data = bytearray(0)
if sign != 0:
bflb_utils.printf('Image need sign')
publickey_file = cfg.get(cfg_section, 'publickey_file')
privatekey_file_uecc = cfg.get(cfg_section, 'privatekey_file_uecc')
if encrypt != 0:
bflb_utils.printf('Image need encrypt ', encrypt)
encrypt_key_org = bflb_utils.hexstr_to_bytearray(cfg.get(cfg_section, 'aes_key_org'))
if encrypt == 1:
encrypt_key = encrypt_key_org[0:16]
else:
if encrypt == 2:
encrypt_key = encrypt_key_org[0:32]
else:
if encrypt == 3:
encrypt_key = encrypt_key_org[0:24]
bflb_utils.printf('Key= ', binascii.hexlify(encrypt_key))
encrypt_iv = bflb_utils.hexstr_to_bytearray(cfg.get(cfg_section, 'aes_iv'))
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
seg_cnt = len(segheader_file)
if flash_img == 0:
if seg_cnt != len(segdata_file):
bflb_utils.printf('Segheader count and segdata count not match')
return (
'FAIL', data_tohash)
data_toencrypt = bytearray(0)
if flash_img == 0:
i = 0
seg_header_list = []
seg_data_list = []
while i < seg_cnt:
seg_data = img_create_read_file_append_crc(segdata_file[i], 0)
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
else:
segdata_crcarray = bflb_utils.get_crc32_bytearray(seg_data)
seg_data_list.append(seg_data)
seg_header = img_create_read_file_append_crc(segheader_file[i], 0)
seg_header = img_create_update_segheader(seg_header, bflb_utils.int_to_4bytearray_l(len(seg_data)), segdata_crcarray)
segheader_crcarray = bflb_utils.get_crc32_bytearray(seg_header)
seg_header = seg_header + segheader_crcarray
seg_header_list.append(seg_header)
i = i + 1
i = 0
while i < seg_cnt:
data_toencrypt += seg_header_list[i]
data_toencrypt += seg_data_list[i]
i += 1
else:
seg_data = img_create_read_file_append_crc(segdata_file[0], 0)
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
data_toencrypt += seg_data
seg_cnt = len(data_toencrypt)
if encrypt != 0:
data_toencrypt = img_create_encrypt_data(data_toencrypt, encrypt_key, encrypt_iv, flash_img)
fw_data = bytearray(0)
data_tohash += data_toencrypt
fw_data = data_toencrypt
hash = img_create_sha256_data(data_tohash)
bflb_utils.printf('Image hash is ', binascii.hexlify(hash))
bootheader_data = img_create_update_bootheader(bootheader_data, hash, seg_cnt)
signature = bytearray(0)
pk_hash = None
if sign == 1:
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file_uecc, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
if flash_img == 1:
bflb_utils.printf('Write flash img')
bootinfo_file_name = cfg.get(cfg_section, 'bootinfo_file')
fp = open(bootinfo_file_name, 'wb+')
bootinfo = bootheader_data + pk_data + signature + aesiv_data
fp.write(bootinfo)
fp.close()
fw_file_name = cfg.get(cfg_section, 'img_file')
fp = open(fw_file_name, 'wb+')
fp.write(fw_data)
fp.close()
if encrypt != 0:
if encrypt == 1:
img_update_efuse(cfg, sign, pk_hash, 1, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 2:
img_update_efuse(cfg, sign, pk_hash, 3, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 3:
img_update_efuse(cfg, sign, pk_hash, 2, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
else:
img_update_efuse(cfg, sign, pk_hash, encrypt, None, key_sel, None, security)
else:
bflb_utils.printf('Write if img')
whole_img_file_name = cfg.get(cfg_section, 'whole_img_file')
fp = open(whole_img_file_name, 'wb+')
img_data = bootheader_data + pk_data + signature + aesiv_data + fw_data
fp.write(img_data)
fp.close()
if encrypt != 0:
if encrypt == 1:
img_update_efuse(cfg, sign, pk_hash, 1, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 2:
img_update_efuse(cfg, sign, pk_hash, 3, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 3:
img_update_efuse(cfg, sign, pk_hash, 2, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
else:
img_update_efuse(cfg, sign, pk_hash, 0, None, key_sel, bytearray(32), security)
return (
'OK', data_tohash)
def img_create_do(args, img_dir_path=None, config_file=None):
bflb_utils.printf('Image create path: ', img_dir_path)
if config_file is None:
config_file = img_dir_path + '/img_create_cfg.ini'
bflb_utils.printf('Config file: ', config_file)
cfg = BFConfigParser()
cfg.read(config_file)
img_type = 'media'
signer = 'none'
security = False
data_tohash = bytearray(0)
try:
if args.image:
img_type = args.image
if args.signer:
signer = args.signer
if args.security:
security = args.security == 'efuse'
except Exception as e:
try:
bflb_utils.printf(e)
finally:
e = None
del e
if img_type == 'media':
flash_img = 1
else:
flash_img = 0
ret, data_tohash = img_creat_process(flash_img, cfg, security)
if ret != 'OK':
bflb_utils.printf('Fail to create images!')
def create_sp_media_image(config, cpu_type=None, security=False):
bflb_utils.printf('========= sp image create =========')
cfg = BFConfigParser()
cfg.read(config)
img_creat_process(1, cfg, security)
# okay decompiling ./libs/base/bl702/img_create_do.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702/jlink_load_cfg.py
jlink_shake_hand_addr = '4202BFF0'
jlink_data_addr = '4202C000'
jlink_load_addr = '22010000'
jlink_core_type = 'RISC-V'
jlink_set_tif = 0
jlink_run_addr = '22010000'
# okay decompiling ./libs/base/bl702/jlink_load_cfg.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702/openocd_load_cfg.py
openocd_shake_hand_addr = '4202BFF0'
openocd_data_addr = '4202C000'
openocd_load_addr = '22010000'
openocd_core_type = 'RISC-V'
openocd_set_tif = 0
openocd_run_addr = '22010000'
# okay decompiling ./libs/base/bl702/openocd_load_cfg.pyc

View File

@ -0,0 +1,391 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702l/bootheader_cfg_keys.py
bootheader_len = 240
bootheader_cfg_keys = {'magic_code':{'offset':'0',
'pos':'0',
'bitlen':'32'},
'revision':{'offset':'4',
'pos':'0',
'bitlen':'32'},
'flashcfg_magic_code':{'offset':'8',
'pos':'0',
'bitlen':'32'},
'io_mode':{'offset':'12',
'pos':'0',
'bitlen':'8'},
'cont_read_support':{'offset':'12',
'pos':'8',
'bitlen':'8'},
'sfctrl_clk_delay':{'offset':'12',
'pos':'16',
'bitlen':'8'},
'sfctrl_clk_invert':{'offset':'12',
'pos':'24',
'bitlen':'8'},
'reset_en_cmd':{'offset':'16',
'pos':'0',
'bitlen':'8'},
'reset_cmd':{'offset':'16',
'pos':'8',
'bitlen':'8'},
'exit_contread_cmd':{'offset':'16',
'pos':'16',
'bitlen':'8'},
'exit_contread_cmd_size':{'offset':'16',
'pos':'24',
'bitlen':'8'},
'jedecid_cmd':{'offset':'20',
'pos':'0',
'bitlen':'8'},
'jedecid_cmd_dmy_clk':{'offset':'20',
'pos':'8',
'bitlen':'8'},
'qpi_jedecid_cmd':{'offset':'20',
'pos':'16',
'bitlen':'8'},
'qpi_jedecid_dmy_clk':{'offset':'20',
'pos':'24',
'bitlen':'8'},
'sector_size':{'offset':'24',
'pos':'0',
'bitlen':'8'},
'mfg_id':{'offset':'24',
'pos':'8',
'bitlen':'8'},
'page_size':{'offset':'24',
'pos':'16',
'bitlen':'16'},
'chip_erase_cmd':{'offset':'28',
'pos':'0',
'bitlen':'8'},
'sector_erase_cmd':{'offset':'28',
'pos':'8',
'bitlen':'8'},
'blk32k_erase_cmd':{'offset':'28',
'pos':'16',
'bitlen':'8'},
'blk64k_erase_cmd':{'offset':'28',
'pos':'24',
'bitlen':'8'},
'write_enable_cmd':{'offset':'32',
'pos':'0',
'bitlen':'8'},
'page_prog_cmd':{'offset':'32',
'pos':'8',
'bitlen':'8'},
'qpage_prog_cmd':{'offset':'32',
'pos':'16',
'bitlen':'8'},
'qual_page_prog_addr_mode':{'offset':'32',
'pos':'24',
'bitlen':'8'},
'fast_read_cmd':{'offset':'36',
'pos':'0',
'bitlen':'8'},
'fast_read_dmy_clk':{'offset':'36',
'pos':'8',
'bitlen':'8'},
'qpi_fast_read_cmd':{'offset':'36',
'pos':'16',
'bitlen':'8'},
'qpi_fast_read_dmy_clk':{'offset':'36',
'pos':'24',
'bitlen':'8'},
'fast_read_do_cmd':{'offset':'40',
'pos':'0',
'bitlen':'8'},
'fast_read_do_dmy_clk':{'offset':'40',
'pos':'8',
'bitlen':'8'},
'fast_read_dio_cmd':{'offset':'40',
'pos':'16',
'bitlen':'8'},
'fast_read_dio_dmy_clk':{'offset':'40',
'pos':'24',
'bitlen':'8'},
'fast_read_qo_cmd':{'offset':'44',
'pos':'0',
'bitlen':'8'},
'fast_read_qo_dmy_clk':{'offset':'44',
'pos':'8',
'bitlen':'8'},
'fast_read_qio_cmd':{'offset':'44',
'pos':'16',
'bitlen':'8'},
'fast_read_qio_dmy_clk':{'offset':'44',
'pos':'24',
'bitlen':'8'},
'qpi_fast_read_qio_cmd':{'offset':'48',
'pos':'0',
'bitlen':'8'},
'qpi_fast_read_qio_dmy_clk':{'offset':'48',
'pos':'8',
'bitlen':'8'},
'qpi_page_prog_cmd':{'offset':'48',
'pos':'16',
'bitlen':'8'},
'write_vreg_enable_cmd':{'offset':'48',
'pos':'24',
'bitlen':'8'},
'wel_reg_index':{'offset':'52',
'pos':'0',
'bitlen':'8'},
'qe_reg_index':{'offset':'52',
'pos':'8',
'bitlen':'8'},
'busy_reg_index':{'offset':'52',
'pos':'16',
'bitlen':'8'},
'wel_bit_pos':{'offset':'52',
'pos':'24',
'bitlen':'8'},
'qe_bit_pos':{'offset':'56',
'pos':'0',
'bitlen':'8'},
'busy_bit_pos':{'offset':'56',
'pos':'8',
'bitlen':'8'},
'wel_reg_write_len':{'offset':'56',
'pos':'16',
'bitlen':'8'},
'wel_reg_read_len':{'offset':'56',
'pos':'24',
'bitlen':'8'},
'qe_reg_write_len':{'offset':'60',
'pos':'0',
'bitlen':'8'},
'qe_reg_read_len':{'offset':'60',
'pos':'8',
'bitlen':'8'},
'release_power_down':{'offset':'60',
'pos':'16',
'bitlen':'8'},
'busy_reg_read_len':{'offset':'60',
'pos':'24',
'bitlen':'8'},
'reg_read_cmd0':{'offset':'64',
'pos':'0',
'bitlen':'8'},
'reg_read_cmd1':{'offset':'64',
'pos':'8',
'bitlen':'8'},
'reg_write_cmd0':{'offset':'68',
'pos':'0',
'bitlen':'8'},
'reg_write_cmd1':{'offset':'68',
'pos':'8',
'bitlen':'8'},
'enter_qpi_cmd':{'offset':'72',
'pos':'0',
'bitlen':'8'},
'exit_qpi_cmd':{'offset':'72',
'pos':'8',
'bitlen':'8'},
'cont_read_code':{'offset':'72',
'pos':'16',
'bitlen':'8'},
'cont_read_exit_code':{'offset':'72',
'pos':'24',
'bitlen':'8'},
'burst_wrap_cmd':{'offset':'76',
'pos':'0',
'bitlen':'8'},
'burst_wrap_dmy_clk':{'offset':'76',
'pos':'8',
'bitlen':'8'},
'burst_wrap_data_mode':{'offset':'76',
'pos':'16',
'bitlen':'8'},
'burst_wrap_code':{'offset':'76',
'pos':'24',
'bitlen':'8'},
'de_burst_wrap_cmd':{'offset':'80',
'pos':'0',
'bitlen':'8'},
'de_burst_wrap_cmd_dmy_clk':{'offset':'80',
'pos':'8',
'bitlen':'8'},
'de_burst_wrap_code_mode':{'offset':'80',
'pos':'16',
'bitlen':'8'},
'de_burst_wrap_code':{'offset':'80',
'pos':'24',
'bitlen':'8'},
'sector_erase_time':{'offset':'84',
'pos':'0',
'bitlen':'16'},
'blk32k_erase_time':{'offset':'84',
'pos':'16',
'bitlen':'16'},
'blk64k_erase_time':{'offset':'88',
'pos':'0',
'bitlen':'16'},
'page_prog_time':{'offset':'88',
'pos':'16',
'bitlen':'16'},
'chip_erase_time':{'offset':'92',
'pos':'0',
'bitlen':'16'},
'power_down_delay':{'offset':'92',
'pos':'16',
'bitlen':'8'},
'qe_data':{'offset':'92',
'pos':'24',
'bitlen':'8'},
'flashcfg_crc32':{'offset':'96',
'pos':'0',
'bitlen':'32'},
'clkcfg_magic_code':{'offset':'100',
'pos':'0',
'bitlen':'32'},
'xtal_type':{'offset':'104',
'pos':'0',
'bitlen':'8'},
'pll_clk':{'offset':'104',
'pos':'8',
'bitlen':'8'},
'hclk_div':{'offset':'104',
'pos':'16',
'bitlen':'8'},
'bclk_div':{'offset':'104',
'pos':'24',
'bitlen':'8'},
'flash_clk_type':{'offset':'108',
'pos':'0',
'bitlen':'8'},
'flash_clk_div':{'offset':'108',
'pos':'8',
'bitlen':'8'},
'clkcfg_crc32':{'offset':'112',
'pos':'0',
'bitlen':'32'},
'sign':{'offset':'116',
'pos':'0',
'bitlen':'2'},
'encrypt_type':{'offset':'116',
'pos':'2',
'bitlen':'2'},
'key_sel':{'offset':'116',
'pos':'4',
'bitlen':'2'},
'no_segment':{'offset':'116',
'pos':'8',
'bitlen':'1'},
'cache_enable':{'offset':'116',
'pos':'9',
'bitlen':'1'},
'notload_in_bootrom':{'offset':'116',
'pos':'10',
'bitlen':'1'},
'aes_region_lock':{'offset':'116',
'pos':'11',
'bitlen':'1'},
'cache_way_disable':{'offset':'116',
'pos':'12',
'bitlen':'4'},
'crc_ignore':{'offset':'116',
'pos':'16',
'bitlen':'1'},
'hash_ignore':{'offset':'116',
'pos':'17',
'bitlen':'1'},
'boot2_enable':{'offset':'116',
'pos':'19',
'bitlen':'1'},
'boot2_rollback':{'offset':'116',
'pos':'20',
'bitlen':'1'},
'img_len':{'offset':'120',
'pos':'0',
'bitlen':'32'},
'bootentry':{'offset':'124',
'pos':'0',
'bitlen':'32'},
'img_start':{'offset':'128',
'pos':'0',
'bitlen':'32'},
'hash_0':{'offset':'132',
'pos':'0',
'bitlen':'32'},
'hash_1':{'offset':'136',
'pos':'0',
'bitlen':'32'},
'hash_2':{'offset':'140',
'pos':'0',
'bitlen':'32'},
'hash_3':{'offset':'144',
'pos':'0',
'bitlen':'32'},
'hash_4':{'offset':'148',
'pos':'0',
'bitlen':'32'},
'hash_5':{'offset':'152',
'pos':'0',
'bitlen':'32'},
'hash_6':{'offset':'156',
'pos':'0',
'bitlen':'32'},
'hash_7':{'offset':'160',
'pos':'0',
'bitlen':'32'},
'boot2_pt_table_0':{'offset':'164',
'pos':'0',
'bitlen':'32'},
'boot2_pt_table_1':{'offset':'168',
'pos':'0',
'bitlen':'32'},
'flashCfgTableAddr':{'offset':'172',
'pos':'0',
'bitlen':'32'},
'flashCfgTableLen':{'offset':'176',
'pos':'0',
'bitlen':'32'},
'patch_read_addr0':{'offset':'180',
'pos':'0',
'bitlen':'32'},
'patch_read_value0':{'offset':'184',
'pos':'0',
'bitlen':'32'},
'patch_read_addr1':{'offset':'188',
'pos':'0',
'bitlen':'32'},
'patch_read_value1':{'offset':'192',
'pos':'0',
'bitlen':'32'},
'patch_read_addr2':{'offset':'196',
'pos':'0',
'bitlen':'32'},
'patch_read_value2':{'offset':'200',
'pos':'0',
'bitlen':'32'},
'patch_jump_addr0':{'offset':'204',
'pos':'0',
'bitlen':'32'},
'patch_jump_value0':{'offset':'208',
'pos':'0',
'bitlen':'32'},
'patch_jump_addr1':{'offset':'212',
'pos':'0',
'bitlen':'32'},
'patch_jump_value1':{'offset':'216',
'pos':'0',
'bitlen':'32'},
'patch_jump_addr2':{'offset':'220',
'pos':'0',
'bitlen':'32'},
'patch_jump_value2':{'offset':'224',
'pos':'0',
'bitlen':'32'},
'reserved1':{'offset':'228',
'pos':'0',
'bitlen':'32'},
'reserved2':{'offset':'232',
'pos':'0',
'bitlen':'32'},
'crc32':{'offset':'236',
'pos':'0',
'bitlen':'32'}}
# okay decompiling ./libs/base/bl702l/bootheader_cfg_keys.pyc

View File

@ -0,0 +1,62 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702l/chiptype_patch.py
def img_load_create_predata_before_run_img():
pre_data = bytearray(12)
pre_data[0] = 80
pre_data[1] = 0
pre_data[2] = 8
pre_data[3] = 0
pre_data[4] = 0
pre_data[5] = 241
pre_data[6] = 0
pre_data[7] = 64
pre_data[8] = 69
pre_data[9] = 72
pre_data[10] = 66
pre_data[11] = 78
pre_data2 = bytearray(12)
pre_data2[0] = 80
pre_data2[1] = 0
pre_data2[2] = 8
pre_data2[3] = 0
pre_data2[4] = 4
pre_data2[5] = 241
pre_data2[6] = 0
pre_data2[7] = 64
pre_data2[8] = 0
pre_data2[9] = 0
pre_data2[10] = 1
pre_data2[11] = 34
pre_data3 = bytearray(12)
pre_data3[0] = 80
pre_data3[1] = 0
pre_data3[2] = 8
pre_data3[3] = 0
pre_data3[4] = 24
pre_data3[5] = 0
pre_data3[6] = 0
pre_data3[7] = 64
pre_data3[8] = 0
pre_data3[9] = 0
pre_data3[10] = 0
pre_data3[11] = 0
pre_data4 = bytearray(12)
pre_data4[0] = 80
pre_data4[1] = 0
pre_data4[2] = 8
pre_data4[3] = 0
pre_data4[4] = 24
pre_data4[5] = 0
pre_data4[6] = 0
pre_data4[7] = 64
pre_data4[8] = 2
pre_data4[9] = 0
pre_data4[10] = 0
pre_data4[11] = 0
return pre_data + pre_data2 + pre_data3 + pre_data4
# okay decompiling ./libs/base/bl702l/chiptype_patch.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702l/cklink_load_cfg.py
cklink_shake_hand_addr = '4202BFF0'
cklink_data_addr = '4202C000'
cklink_load_addr = '22010000'
cklink_core_type = 'RISC-V'
cklink_set_tif = 0
cklink_run_addr = '22010000'
# okay decompiling ./libs/base/bl702l/cklink_load_cfg.pyc

View File

@ -0,0 +1,151 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702l/flash_select_do.py
import os, csv, config as gol
from libs import bflb_utils
from libs.bflb_utils import app_path, conf_sign
from libs.bflb_configobj import BFConfigParser
from libs.base.bl702l.bootheader_cfg_keys import bootheader_cfg_keys as flash_cfg_keys
def get_suitable_file_name(cfg_dir, flash_id):
conf_files = []
for home, dirs, files in os.walk(cfg_dir):
for filename in files:
if filename.split('_')[-1] == flash_id + '.conf':
conf_files.append(filename)
if len(conf_files) > 1:
bflb_utils.printf('Flash id duplicate and alternative is:')
for i in range(len(conf_files)):
tmp = conf_files[i].split('.')[0]
bflb_utils.printf('%d:%s' % (i + 1, tmp))
return conf_files[i]
if len(conf_files) == 1:
return conf_files[0]
return ''
def update_flash_cfg_do(chipname, chiptype, flash_id, file=None, create=False, section=None):
if conf_sign:
cfg_dir = app_path + '/utils/flash/' + chipname + '/'
else:
cfg_dir = app_path + '/utils/flash/' + gol.flash_dict[chipname] + '/'
conf_name = get_suitable_file_name(cfg_dir, flash_id)
value_key = []
if os.path.isfile(cfg_dir + conf_name) is False:
return False
fp = open(cfg_dir + conf_name, 'r')
for line in fp.readlines():
value = line.split('=')[0].strip()
if value == '[FLASH_CFG]':
continue
else:
value_key.append(value)
cfg1 = BFConfigParser()
cfg1.read(cfg_dir + conf_name)
cfg2 = BFConfigParser()
cfg2.read(file)
for i in range(len(value_key)):
if cfg1.has_option('FLASH_CFG', value_key[i]):
if cfg2.has_option(section, value_key[i]):
tmp_value = cfg1.get('FLASH_CFG', value_key[i])
bflb_utils.update_cfg(cfg2, section, value_key[i], tmp_value)
cfg2.write(file, 'w+')
bflb_utils.printf('Update flash cfg finished')
def get_supported_flash_do():
flash_type = []
return flash_type
def get_int_mask(pos, length):
ones = '11111111111111111111111111111111'
zeros = '00000000000000000000000000000000'
mask = ones[0:32 - pos - length] + zeros[0:length] + ones[0:pos]
return int(mask, 2)
def create_flashcfg_data_from_cfg(cfg_len, cfgfile):
section = 'FLASH_CFG'
cfg = BFConfigParser()
cfg.read(cfgfile)
data = bytearray(cfg_len)
minOffset = int(flash_cfg_keys.get('io_mode')['offset'], 10)
for key in cfg.options(section):
if flash_cfg_keys.get(key) == None:
bflb_utils.printf(key + ' not exist')
continue
else:
val = cfg.get(section, key)
if val.startswith('0x'):
val = int(val, 16)
else:
val = int(val, 10)
offset = int(flash_cfg_keys.get(key)['offset'], 10) - minOffset
pos = int(flash_cfg_keys.get(key)['pos'], 10)
bitlen = int(flash_cfg_keys.get(key)['bitlen'], 10)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = (oldval & get_int_mask(pos, bitlen)) + (val << pos)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
crcarray = bflb_utils.get_crc32_bytearray(data)
data = bflb_utils.int_to_4bytearray_l(1195787078) + data + crcarray
return data
def create_flashcfg_table(start_addr):
single_flashcfg_len = 92
flash_table_list = bytearray(0)
flash_table_data = bytearray(0)
if conf_sign:
table_file = os.path.join(app_path, 'utils', 'flash', 'bl702l', 'flashcfg_list.csv')
else:
table_file = os.path.join(app_path, 'utils', 'flash', 'bl702l', 'flashcfg_list.csv')
with open(table_file, 'r', encoding='utf-8-sig') as csvfile:
table_list = []
cfgfile_list = []
reader = csv.DictReader(csvfile)
cnt = 0
for row in reader:
row_dict = {}
row_dict['jid'] = row.get('flashJedecID', '')
row_dict['cfgfile'] = row.get('configFile', '')
if row_dict['cfgfile'] not in cfgfile_list:
cfgfile_list.append(row_dict['cfgfile'])
else:
table_list.append(row_dict)
cnt += 1
table_list_len = 4 + cnt * 8 + 4
for cfgfile in cfgfile_list:
if conf_sign:
cfgfile = os.path.join(app_path, 'utils', 'flash', 'bl702l', cfgfile)
else:
cfgfile = os.path.join(app_path, 'utils', 'flash', 'bl702l', cfgfile)
data = create_flashcfg_data_from_cfg(single_flashcfg_len - 8, cfgfile)
flash_table_data += data
for dict in table_list:
flash_table_list += bflb_utils.int_to_4bytearray_b(int(dict['jid'] + '00', 16))
i = 0
offset = 0
for cfgfile in cfgfile_list:
if cfgfile == dict['cfgfile']:
offset = start_addr + table_list_len + single_flashcfg_len * i
break
else:
i += 1
flash_table_list += bflb_utils.int_to_4bytearray_l(offset)
crcarray = bflb_utils.get_crc32_bytearray(flash_table_list)
flash_table_list = bflb_utils.int_to_4bytearray_l(1196704582) + flash_table_list + crcarray
return (
flash_table_list, flash_table_data, len(flash_table_list))
# okay decompiling ./libs/base/bl702l/flash_select_do.pyc

View File

@ -0,0 +1,438 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702l/img_create_do.py
import hashlib, binascii, ecdsa
from libs import bflb_utils
from libs.bflb_utils import img_create_sha256_data, img_create_encrypt_data
from libs.bflb_configobj import BFConfigParser
from libs.base.bl702l.flash_select_do import create_flashcfg_table
from libs.base.bl702l.bootheader_cfg_keys import bootheader_len as header_len
keyslot0 = 28
keyslot1 = keyslot0 + 16
keyslot2 = keyslot1 + 16
keyslot3 = keyslot2 + 16
keyslot4 = keyslot3 + 16
keyslot5 = keyslot4 + 16
keyslot6 = keyslot5 + 16
wr_lock_key_slot_4_l = 13
wr_lock_key_slot_5_l = 14
wr_lock_boot_mode = 15
wr_lock_dbg_pwd = 16
wr_lock_sw_usage_0 = 17
wr_lock_wifi_mac = 18
wr_lock_key_slot_0 = 19
wr_lock_key_slot_1 = 20
wr_lock_key_slot_2 = 21
wr_lock_key_slot_3 = 22
wr_lock_key_slot_4_h = 23
wr_lock_key_slot_5_h = 24
rd_lock_dbg_pwd = 25
rd_lock_key_slot_0 = 26
rd_lock_key_slot_1 = 27
rd_lock_key_slot_2 = 28
rd_lock_key_slot_3 = 29
rd_lock_key_slot_4 = 30
rd_lock_key_slot_5 = 31
def img_update_efuse(cfg, sign, pk_hash, flash_encryp_type, flash_key, sec_eng_key_sel, sec_eng_key, security=False):
fp = open(cfg.get('Img_Cfg', 'efuse_file'), 'rb')
efuse_data = bytearray(fp.read()) + bytearray(0)
fp.close()
fp = open(cfg.get('Img_Cfg', 'efuse_mask_file'), 'rb')
efuse_mask_data = bytearray(fp.read()) + bytearray(0)
fp.close()
mask_4bytes = bytearray.fromhex('FFFFFFFF')
efuse_data[0] |= flash_encryp_type
efuse_data[0] |= sign << 2
if flash_encryp_type > 0:
efuse_data[0] |= 128
efuse_data[0] |= 48
efuse_mask_data[0] |= 255
rw_lock = 0
if pk_hash is not None:
efuse_data[keyslot0:keyslot2] = pk_hash
efuse_mask_data[keyslot0:keyslot2] = mask_4bytes * 8
rw_lock |= 1 << wr_lock_key_slot_0
rw_lock |= 1 << wr_lock_key_slot_1
if flash_key is not None:
if flash_encryp_type == 1:
efuse_data[keyslot2:keyslot3] = flash_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
else:
if flash_encryp_type == 2:
efuse_data[keyslot2:keyslot4] = flash_key
efuse_mask_data[keyslot2:keyslot4] = mask_4bytes * 8
rw_lock |= 1 << wr_lock_key_slot_3
rw_lock |= 1 << rd_lock_key_slot_3
else:
if flash_encryp_type == 3:
efuse_data[keyslot2:keyslot4] = flash_key
efuse_mask_data[keyslot2:keyslot4] = mask_4bytes * 8
rw_lock |= 1 << wr_lock_key_slot_3
rw_lock |= 1 << rd_lock_key_slot_3
rw_lock |= 1 << wr_lock_key_slot_2
rw_lock |= 1 << rd_lock_key_slot_2
if sec_eng_key is not None:
if flash_encryp_type == 0:
if sec_eng_key_sel == 0:
efuse_data[keyslot3:keyslot4] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot4] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_3
rw_lock |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 1:
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_2
rw_lock |= 1 << rd_lock_key_slot_2
if flash_encryp_type == 1:
if sec_eng_key_sel == 0:
efuse_data[keyslot5:keyslot6] = sec_eng_key[0:16]
efuse_mask_data[keyslot5:keyslot6] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_5_l
rw_lock |= 1 << wr_lock_key_slot_5_h
rw_lock |= 1 << rd_lock_key_slot_5
if sec_eng_key_sel == 1:
efuse_data[keyslot4:keyslot5] = sec_eng_key[0:16]
efuse_mask_data[keyslot4:keyslot5] = mask_4bytes * 4
rw_lock |= 1 << wr_lock_key_slot_4_l
rw_lock |= 1 << wr_lock_key_slot_4_h
rw_lock |= 1 << rd_lock_key_slot_4
efuse_data[124:128] = bflb_utils.int_to_4bytearray_l(rw_lock)
efuse_mask_data[124:128] = bflb_utils.int_to_4bytearray_l(rw_lock)
if security is True:
bflb_utils.printf('Encrypt efuse data')
security_key, security_iv = bflb_utils.get_security_key()
efuse_data = img_create_encrypt_data(efuse_data, security_key, security_iv, 0)
efuse_data = bytearray(4096) + efuse_data
fp = open(cfg.get('Img_Cfg', 'efuse_file'), 'wb+')
fp.write(efuse_data)
fp.close()
fp = open(cfg.get('Img_Cfg', 'efuse_mask_file'), 'wb+')
fp.write(efuse_mask_data)
fp.close()
def img_create_get_sign_encrypt_info(bootheader_data):
sign = bootheader_data[116] & 3
encrypt = bootheader_data[116] >> 2 & 3
key_sel = bootheader_data[116] >> 4 & 3
return (
sign, encrypt, key_sel)
def img_create_get_hash_ignore(bootheader_data):
return bootheader_data[118] >> 1 & 1
def img_create_get_crc_ignore(bootheader_data):
return bootheader_data[118] & 1
def img_create_update_bootheader_if(bootheader_data, hash, seg_cnt):
bootheader_data[120:124] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign = bootheader_data[116] & 3
encrypt = bootheader_data[116] >> 2 & 3
key_sel = bootheader_data[116] >> 4 & 3
if bootheader_data[118] >> 1 & 1 == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[132:164] = hash
if bootheader_data[118] & 1 == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[0:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data
def img_create_update_bootheader(bootheader_data, hash, seg_cnt, flashcfg_table_addr, flashcfg_table_len):
bootheader_data[172:176] = bflb_utils.int_to_4bytearray_l(flashcfg_table_addr)
bootheader_data[176:180] = bflb_utils.int_to_4bytearray_l(flashcfg_table_len)
bootheader_data[120:124] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign, encrypt, key_sel = img_create_get_sign_encrypt_info(bootheader_data)
if img_create_get_hash_ignore(bootheader_data) == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[132:164] = hash
if img_create_get_crc_ignore(bootheader_data) == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[0:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data[0:header_len]
def img_create_update_segheader(segheader, segdatalen, segdatacrc):
segheader[4:8] = segdatalen
segheader[8:12] = segdatacrc
return segheader
def img_create_sign_data(data_bytearray, privatekey_file_uecc, publickey_file):
sk = ecdsa.SigningKey.from_pem(open(privatekey_file_uecc).read())
vk = ecdsa.VerifyingKey.from_pem(open(publickey_file).read())
pk_data = vk.to_string()
bflb_utils.printf('Private key: ', binascii.hexlify(sk.to_string()))
bflb_utils.printf('Public key: ', binascii.hexlify(pk_data))
pk_hash = img_create_sha256_data(pk_data)
bflb_utils.printf('Public key hash=', binascii.hexlify(pk_hash))
signature = sk.sign(data_bytearray, hashfunc=(hashlib.sha256), sigencode=(ecdsa.util.sigencode_string))
bflb_utils.printf('Signature=', binascii.hexlify(signature))
len_array = bflb_utils.int_to_4bytearray_l(len(signature))
sig_field = len_array + signature
crcarray = bflb_utils.get_crc32_bytearray(sig_field)
return (
pk_data, pk_hash, sig_field + crcarray)
def img_create_read_file_append_crc(file, crc):
fp = open(file, 'rb')
read_data = bytearray(fp.read())
crcarray = bytearray(0)
if crc:
crcarray = bflb_utils.get_crc32_bytearray(read_data)
fp.close()
return read_data + crcarray
def encrypt_loader_bin_do(file, sign, encrypt, temp_encrypt_key, temp_encrypt_iv, publickey_file, privatekey_file):
if encrypt != 0 or sign != 0:
encrypt_key = bytearray(0)
encrypt_iv = bytearray(0)
load_helper_bin_header = bytearray(0)
load_helper_bin_body = bytearray(0)
offset = 116
sign_pos = 0
encrypt_type_pos = 2
key_sel_pos = 4
pk_data = bytearray(0)
signature = bytearray(0)
aesiv_data = bytearray(0)
data_tohash = bytearray(0)
with open(file, 'rb') as fp:
load_helper_bin = fp.read()
load_helper_bin_header = load_helper_bin[0:header_len]
load_helper_bin_body = load_helper_bin[header_len:]
if load_helper_bin_header != bytearray(0):
if load_helper_bin_body != bytearray(0):
load_helper_bin_body = bflb_utils.add_to_16(load_helper_bin_body)
if encrypt != 0:
encrypt_key = bflb_utils.hexstr_to_bytearray(temp_encrypt_key)
encrypt_iv = bflb_utils.hexstr_to_bytearray(temp_encrypt_iv)
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
load_helper_bin_body_encrypt = bflb_utils.img_create_encrypt_data(load_helper_bin_body, encrypt_key, encrypt_iv, 0)
else:
load_helper_bin_body_encrypt = load_helper_bin_body
data = bytearray(load_helper_bin_header)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = oldval
if encrypt != 0:
newval = newval | 1 << encrypt_type_pos
newval = newval | 1 << key_sel_pos
if sign != 0:
newval = newval | 1 << sign_pos
data_tohash += load_helper_bin_body_encrypt
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
load_helper_bin_header = data
load_helper_bin_encrypt = load_helper_bin_header + pk_data + signature + aesiv_data + load_helper_bin_body_encrypt
hashfun = hashlib.sha256()
hashfun.update(data_tohash)
hash = bflb_utils.hexstr_to_bytearray(hashfun.hexdigest())
load_helper_bin_data = bytearray(load_helper_bin_encrypt)
load_helper_bin_encrypt = img_create_update_bootheader_if(load_helper_bin_data, hash, 1)
return (
True, load_helper_bin_encrypt)
return (False, None)
def img_creat_process(flash_img, cfg, security=False):
encrypt_blk_size = 16
padding = bytearray(encrypt_blk_size)
data_tohash = bytearray(0)
cfg_section = 'Img_Cfg'
segheader_file = []
if flash_img == 0:
for files in cfg.get(cfg_section, 'segheader_file').split(' '):
segheader_file.append(str(files))
segdata_file = []
for files in cfg.get(cfg_section, 'segdata_file').split('|'):
segdata_file.append(str(files))
if flash_img == 1:
break
boot_header_file = cfg.get(cfg_section, 'boot_header_file')
bootheader_data = img_create_read_file_append_crc(boot_header_file, 0)
encrypt = 0
sign, encrypt, key_sel = img_create_get_sign_encrypt_info(bootheader_data)
aesiv_data = bytearray(0)
pk_data = bytearray(0)
if sign != 0:
bflb_utils.printf('Image need sign')
publickey_file = cfg.get(cfg_section, 'publickey_file')
privatekey_file_uecc = cfg.get(cfg_section, 'privatekey_file_uecc')
if encrypt != 0:
bflb_utils.printf('Image need encrypt ', encrypt)
encrypt_key_org = bflb_utils.hexstr_to_bytearray(cfg.get(cfg_section, 'aes_key_org'))
if encrypt == 1:
encrypt_key = encrypt_key_org[0:16]
else:
if encrypt == 2:
encrypt_key = encrypt_key_org[0:32]
else:
if encrypt == 3:
encrypt_key = encrypt_key_org[0:24]
bflb_utils.printf('Key= ', binascii.hexlify(encrypt_key))
encrypt_iv = bflb_utils.hexstr_to_bytearray(cfg.get(cfg_section, 'aes_iv'))
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
seg_cnt = len(segheader_file)
if flash_img == 0:
if seg_cnt != len(segdata_file):
bflb_utils.printf('Segheader count and segdata count not match')
return (
'FAIL', data_tohash)
data_toencrypt = bytearray(0)
if flash_img == 0:
i = 0
seg_header_list = []
seg_data_list = []
while i < seg_cnt:
seg_data = img_create_read_file_append_crc(segdata_file[i], 0)
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
else:
segdata_crcarray = bflb_utils.get_crc32_bytearray(seg_data)
seg_data_list.append(seg_data)
seg_header = img_create_read_file_append_crc(segheader_file[i], 0)
seg_header = img_create_update_segheader(seg_header, bflb_utils.int_to_4bytearray_l(len(seg_data)), segdata_crcarray)
segheader_crcarray = bflb_utils.get_crc32_bytearray(seg_header)
seg_header = seg_header + segheader_crcarray
seg_header_list.append(seg_header)
i = i + 1
i = 0
while i < seg_cnt:
data_toencrypt += seg_header_list[i]
data_toencrypt += seg_data_list[i]
i += 1
else:
seg_data = img_create_read_file_append_crc(segdata_file[0], 0)
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
data_toencrypt += seg_data
seg_cnt = len(data_toencrypt)
if encrypt != 0:
data_toencrypt = img_create_encrypt_data(data_toencrypt, encrypt_key, encrypt_iv, flash_img)
fw_data = bytearray(0)
data_tohash += data_toencrypt
fw_data = data_toencrypt
hash = img_create_sha256_data(data_tohash)
bflb_utils.printf('Image hash is ', binascii.hexlify(hash))
signature = bytearray(0)
pk_hash = None
if sign == 1:
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file_uecc, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
flashCfgAddr = len(bootheader_data + pk_data + signature + aesiv_data)
flashCfgListLen = 0
flashCfgList = bytearray(0)
flashCfgTable = bytearray(0)
if flash_img == 1:
if bootheader_data[25:26] == b'\xff':
flashCfgList, flashCfgTable, flashCfgListLen = create_flashcfg_table(flashCfgAddr)
bootheader_data = img_create_update_bootheader(bootheader_data, hash, seg_cnt, flashCfgAddr, flashCfgListLen)
if flash_img == 1:
bflb_utils.printf('Write flash img')
bootinfo_file_name = cfg.get(cfg_section, 'bootinfo_file')
fp = open(bootinfo_file_name, 'wb+')
bootinfo = bootheader_data + pk_data + signature + aesiv_data + flashCfgList + flashCfgTable
fp.write(bootinfo)
fp.close()
fw_file_name = cfg.get(cfg_section, 'img_file')
fp = open(fw_file_name, 'wb+')
fp.write(fw_data)
fp.close()
if encrypt != 0:
if encrypt == 1:
img_update_efuse(cfg, sign, pk_hash, 1, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 2:
img_update_efuse(cfg, sign, pk_hash, 3, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 3:
img_update_efuse(cfg, sign, pk_hash, 2, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
else:
img_update_efuse(cfg, sign, pk_hash, encrypt, None, key_sel, None, security)
else:
bflb_utils.printf('Write if img')
whole_img_file_name = cfg.get(cfg_section, 'whole_img_file')
fp = open(whole_img_file_name, 'wb+')
img_data = bootheader_data + pk_data + signature + aesiv_data + fw_data
fp.write(img_data)
fp.close()
if encrypt != 0:
if encrypt == 1:
img_update_efuse(cfg, sign, pk_hash, 1, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 2:
img_update_efuse(cfg, sign, pk_hash, 3, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
if encrypt == 3:
img_update_efuse(cfg, sign, pk_hash, 2, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
else:
img_update_efuse(cfg, sign, pk_hash, 0, None, key_sel, bytearray(32), security)
return (
'OK', data_tohash)
def img_create_do(args, img_dir_path=None, config_file=None):
bflb_utils.printf('Image create path: ', img_dir_path)
if config_file is None:
config_file = img_dir_path + '/img_create_cfg.ini'
bflb_utils.printf('Config file: ', config_file)
cfg = BFConfigParser()
cfg.read(config_file)
img_type = 'media'
signer = 'none'
security = False
data_tohash = bytearray(0)
try:
if args.image:
img_type = args.image
if args.signer:
signer = args.signer
if args.security:
security = args.security == 'efuse'
except Exception as e:
try:
bflb_utils.printf(e)
finally:
e = None
del e
if img_type == 'media':
flash_img = 1
else:
flash_img = 0
ret, data_tohash = img_creat_process(flash_img, cfg, security)
if ret != 'OK':
bflb_utils.printf('Fail to create images!')
def create_sp_media_image(config, cpu_type=None, security=False):
bflb_utils.printf('========= sp image create =========')
cfg = BFConfigParser()
cfg.read(config)
img_creat_process(1, cfg, security)
# okay decompiling ./libs/base/bl702l/img_create_do.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702l/jlink_load_cfg.py
jlink_shake_hand_addr = '4202BFF0'
jlink_data_addr = '4202C000'
jlink_load_addr = '22010000'
jlink_core_type = 'RISC-V'
jlink_set_tif = 0
jlink_run_addr = '22010000'
# okay decompiling ./libs/base/bl702l/jlink_load_cfg.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl702l/openocd_load_cfg.py
openocd_shake_hand_addr = '4202BFF0'
openocd_data_addr = '4202C000'
openocd_load_addr = '22010000'
openocd_core_type = 'RISC-V'
openocd_set_tif = 0
openocd_run_addr = '22010000'
# okay decompiling ./libs/base/bl702l/openocd_load_cfg.pyc

View File

@ -0,0 +1,614 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl808/bootheader_cfg_keys.py
clock_start_pos = 100
bootcfg_start_pos = 128
bootcfg_len = 48
bootcpucfg_start_pos = bootcfg_start_pos + bootcfg_len
bootcpucfg_len = 24
bootcpucfg_m0_index = 0
bootcpucfg_d0_index = 1
bootcpucfg_lp_index = 2
boot2_start_pos = bootcpucfg_start_pos + bootcpucfg_len * (bootcpucfg_lp_index + 1)
boot2_len = 8
flashcfg_table_start_pos = boot2_start_pos + boot2_len
flashcfg_table_len = 8
patch_on_read_start_pos = flashcfg_table_start_pos + flashcfg_table_len
patch_on_read_len = 32
patch_on_jump_start_pos = patch_on_read_start_pos + patch_on_read_len
patch_on_jump_len = 32
rsvd_start_pos = patch_on_jump_start_pos + patch_on_jump_len
rsvd_len = 20
crc32_start_pos = rsvd_start_pos + rsvd_len
bootheader_len = crc32_start_pos + 4
bootheader_cfg_keys = {'magic_code':{'offset':'0',
'pos':'0',
'bitlen':'32'},
'revision':{'offset':'4',
'pos':'0',
'bitlen':'32'},
'flashcfg_magic_code':{'offset':'8',
'pos':'0',
'bitlen':'32'},
'io_mode':{'offset':'12',
'pos':'0',
'bitlen':'8'},
'cont_read_support':{'offset':'12',
'pos':'8',
'bitlen':'8'},
'sfctrl_clk_delay':{'offset':'12',
'pos':'16',
'bitlen':'8'},
'sfctrl_clk_invert':{'offset':'12',
'pos':'24',
'bitlen':'8'},
'reset_en_cmd':{'offset':'16',
'pos':'0',
'bitlen':'8'},
'reset_cmd':{'offset':'16',
'pos':'8',
'bitlen':'8'},
'exit_contread_cmd':{'offset':'16',
'pos':'16',
'bitlen':'8'},
'exit_contread_cmd_size':{'offset':'16',
'pos':'24',
'bitlen':'8'},
'jedecid_cmd':{'offset':'20',
'pos':'0',
'bitlen':'8'},
'jedecid_cmd_dmy_clk':{'offset':'20',
'pos':'8',
'bitlen':'8'},
'enter_32bits_addr_cmd':{'offset':'20',
'pos':'16',
'bitlen':'8'},
'exit_32bits_addr_clk':{'offset':'20',
'pos':'24',
'bitlen':'8'},
'sector_size':{'offset':'24',
'pos':'0',
'bitlen':'8'},
'mfg_id':{'offset':'24',
'pos':'8',
'bitlen':'8'},
'page_size':{'offset':'24',
'pos':'16',
'bitlen':'16'},
'chip_erase_cmd':{'offset':'28',
'pos':'0',
'bitlen':'8'},
'sector_erase_cmd':{'offset':'28',
'pos':'8',
'bitlen':'8'},
'blk32k_erase_cmd':{'offset':'28',
'pos':'16',
'bitlen':'8'},
'blk64k_erase_cmd':{'offset':'28',
'pos':'24',
'bitlen':'8'},
'write_enable_cmd':{'offset':'32',
'pos':'0',
'bitlen':'8'},
'page_prog_cmd':{'offset':'32',
'pos':'8',
'bitlen':'8'},
'qpage_prog_cmd':{'offset':'32',
'pos':'16',
'bitlen':'8'},
'qual_page_prog_addr_mode':{'offset':'32',
'pos':'24',
'bitlen':'8'},
'fast_read_cmd':{'offset':'36',
'pos':'0',
'bitlen':'8'},
'fast_read_dmy_clk':{'offset':'36',
'pos':'8',
'bitlen':'8'},
'qpi_fast_read_cmd':{'offset':'36',
'pos':'16',
'bitlen':'8'},
'qpi_fast_read_dmy_clk':{'offset':'36',
'pos':'24',
'bitlen':'8'},
'fast_read_do_cmd':{'offset':'40',
'pos':'0',
'bitlen':'8'},
'fast_read_do_dmy_clk':{'offset':'40',
'pos':'8',
'bitlen':'8'},
'fast_read_dio_cmd':{'offset':'40',
'pos':'16',
'bitlen':'8'},
'fast_read_dio_dmy_clk':{'offset':'40',
'pos':'24',
'bitlen':'8'},
'fast_read_qo_cmd':{'offset':'44',
'pos':'0',
'bitlen':'8'},
'fast_read_qo_dmy_clk':{'offset':'44',
'pos':'8',
'bitlen':'8'},
'fast_read_qio_cmd':{'offset':'44',
'pos':'16',
'bitlen':'8'},
'fast_read_qio_dmy_clk':{'offset':'44',
'pos':'24',
'bitlen':'8'},
'qpi_fast_read_qio_cmd':{'offset':'48',
'pos':'0',
'bitlen':'8'},
'qpi_fast_read_qio_dmy_clk':{'offset':'48',
'pos':'8',
'bitlen':'8'},
'qpi_page_prog_cmd':{'offset':'48',
'pos':'16',
'bitlen':'8'},
'write_vreg_enable_cmd':{'offset':'48',
'pos':'24',
'bitlen':'8'},
'wel_reg_index':{'offset':'52',
'pos':'0',
'bitlen':'8'},
'qe_reg_index':{'offset':'52',
'pos':'8',
'bitlen':'8'},
'busy_reg_index':{'offset':'52',
'pos':'16',
'bitlen':'8'},
'wel_bit_pos':{'offset':'52',
'pos':'24',
'bitlen':'8'},
'qe_bit_pos':{'offset':'56',
'pos':'0',
'bitlen':'8'},
'busy_bit_pos':{'offset':'56',
'pos':'8',
'bitlen':'8'},
'wel_reg_write_len':{'offset':'56',
'pos':'16',
'bitlen':'8'},
'wel_reg_read_len':{'offset':'56',
'pos':'24',
'bitlen':'8'},
'qe_reg_write_len':{'offset':'60',
'pos':'0',
'bitlen':'8'},
'qe_reg_read_len':{'offset':'60',
'pos':'8',
'bitlen':'8'},
'release_power_down':{'offset':'60',
'pos':'16',
'bitlen':'8'},
'busy_reg_read_len':{'offset':'60',
'pos':'24',
'bitlen':'8'},
'reg_read_cmd0':{'offset':'64',
'pos':'0',
'bitlen':'8'},
'reg_read_cmd1':{'offset':'64',
'pos':'8',
'bitlen':'8'},
'reg_write_cmd0':{'offset':'68',
'pos':'0',
'bitlen':'8'},
'reg_write_cmd1':{'offset':'68',
'pos':'8',
'bitlen':'8'},
'enter_qpi_cmd':{'offset':'72',
'pos':'0',
'bitlen':'8'},
'exit_qpi_cmd':{'offset':'72',
'pos':'8',
'bitlen':'8'},
'cont_read_code':{'offset':'72',
'pos':'16',
'bitlen':'8'},
'cont_read_exit_code':{'offset':'72',
'pos':'24',
'bitlen':'8'},
'burst_wrap_cmd':{'offset':'76',
'pos':'0',
'bitlen':'8'},
'burst_wrap_dmy_clk':{'offset':'76',
'pos':'8',
'bitlen':'8'},
'burst_wrap_data_mode':{'offset':'76',
'pos':'16',
'bitlen':'8'},
'burst_wrap_code':{'offset':'76',
'pos':'24',
'bitlen':'8'},
'de_burst_wrap_cmd':{'offset':'80',
'pos':'0',
'bitlen':'8'},
'de_burst_wrap_cmd_dmy_clk':{'offset':'80',
'pos':'8',
'bitlen':'8'},
'de_burst_wrap_code_mode':{'offset':'80',
'pos':'16',
'bitlen':'8'},
'de_burst_wrap_code':{'offset':'80',
'pos':'24',
'bitlen':'8'},
'sector_erase_time':{'offset':'84',
'pos':'0',
'bitlen':'16'},
'blk32k_erase_time':{'offset':'84',
'pos':'16',
'bitlen':'16'},
'blk64k_erase_time':{'offset':'88',
'pos':'0',
'bitlen':'16'},
'page_prog_time':{'offset':'88',
'pos':'16',
'bitlen':'16'},
'chip_erase_time':{'offset':'92',
'pos':'0',
'bitlen':'16'},
'power_down_delay':{'offset':'92',
'pos':'16',
'bitlen':'8'},
'qe_data':{'offset':'92',
'pos':'24',
'bitlen':'8'},
'flashcfg_crc32':{'offset':'96',
'pos':'0',
'bitlen':'32'},
'clkcfg_magic_code':{'offset':str(int(clock_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'xtal_type':{'offset':str(int(clock_start_pos) + 4),
'pos':'0',
'bitlen':'8'},
'mcu_clk':{'offset':str(int(clock_start_pos) + 4),
'pos':'8',
'bitlen':'8'},
'mcu_clk_div':{'offset':str(int(clock_start_pos) + 4),
'pos':'16',
'bitlen':'8'},
'mcu_bclk_div':{'offset':str(int(clock_start_pos) + 4),
'pos':'24',
'bitlen':'8'},
'mcu_pbclk_div':{'offset':str(int(clock_start_pos) + 8),
'pos':'0',
'bitlen':'8'},
'lp_div':{'offset':str(int(clock_start_pos) + 8),
'pos':'8',
'bitlen':'8'},
'dsp_clk':{'offset':str(int(clock_start_pos) + 8),
'pos':'16',
'bitlen':'8'},
'dsp_clk_div':{'offset':str(int(clock_start_pos) + 8),
'pos':'24',
'bitlen':'8'},
'dsp_bclk_div':{'offset':str(int(clock_start_pos) + 12),
'pos':'0',
'bitlen':'8'},
'dsp_pbclk':{'offset':str(int(clock_start_pos) + 12),
'pos':'8',
'bitlen':'8'},
'dsp_pbclk_div':{'offset':str(int(clock_start_pos) + 12),
'pos':'16',
'bitlen':'8'},
'emi_clk':{'offset':str(int(clock_start_pos) + 12),
'pos':'24',
'bitlen':'8'},
'emi_clk_div':{'offset':str(int(clock_start_pos) + 16),
'pos':'0',
'bitlen':'8'},
'flash_clk_type':{'offset':str(int(clock_start_pos) + 16),
'pos':'8',
'bitlen':'8'},
'flash_clk_div':{'offset':str(int(clock_start_pos) + 16),
'pos':'16',
'bitlen':'8'},
'wifipll_pu':{'offset':str(int(clock_start_pos) + 16),
'pos':'24',
'bitlen':'8'},
'aupll_pu':{'offset':str(int(clock_start_pos) + 20),
'pos':'0',
'bitlen':'8'},
'cpupll_pu':{'offset':str(int(clock_start_pos) + 20),
'pos':'8',
'bitlen':'8'},
'mipipll_pu':{'offset':str(int(clock_start_pos) + 20),
'pos':'16',
'bitlen':'8'},
'uhspll_pu':{'offset':str(int(clock_start_pos) + 20),
'pos':'24',
'bitlen':'8'},
'clkcfg_crc32':{'offset':str(int(clock_start_pos) + 24),
'pos':'0',
'bitlen':'32'},
'sign':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'0',
'bitlen':'2'},
'encrypt_type':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'2',
'bitlen':'2'},
'key_sel':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'4',
'bitlen':'2'},
'xts_mode':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'6',
'bitlen':'1'},
'aes_region_lock':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'7',
'bitlen':'1'},
'no_segment':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'8',
'bitlen':'1'},
'boot2_enable':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'9',
'bitlen':'1'},
'boot2_rollback':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'10',
'bitlen':'1'},
'cpu_master_id':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'11',
'bitlen':'4'},
'notload_in_bootrom':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'15',
'bitlen':'1'},
'crc_ignore':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'16',
'bitlen':'1'},
'hash_ignore':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'17',
'bitlen':'1'},
'power_on_mm':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'18',
'bitlen':'1'},
'em_sel':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'19',
'bitlen':'3'},
'cmds_en':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'22',
'bitlen':'1'},
'cmds_wrap_mode':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'23',
'bitlen':'2'},
'cmds_wrap_len':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'25',
'bitlen':'4'},
'icache_invalid':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'29',
'bitlen':'1'},
'dcache_invalid':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'30',
'bitlen':'1'},
'fpga_halt_release':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'31',
'bitlen':'1'},
'group_image_offset':{'offset':str(int(bootcfg_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'aes_region_len':{'offset':str(int(bootcfg_start_pos) + 8),
'pos':'0',
'bitlen':'32'},
'img_len_cnt':{'offset':str(int(bootcfg_start_pos) + 12),
'pos':'0',
'bitlen':'32'},
'hash_0':{'offset':str(int(bootcfg_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'hash_1':{'offset':str(int(bootcfg_start_pos) + 20),
'pos':'0',
'bitlen':'32'},
'hash_2':{'offset':str(int(bootcfg_start_pos) + 24),
'pos':'0',
'bitlen':'32'},
'hash_3':{'offset':str(int(bootcfg_start_pos) + 28),
'pos':'0',
'bitlen':'32'},
'hash_4':{'offset':str(int(bootcfg_start_pos) + 32),
'pos':'0',
'bitlen':'32'},
'hash_5':{'offset':str(int(bootcfg_start_pos) + 36),
'pos':'0',
'bitlen':'32'},
'hash_6':{'offset':str(int(bootcfg_start_pos) + 40),
'pos':'0',
'bitlen':'32'},
'hash_7':{'offset':str(int(bootcfg_start_pos) + 44),
'pos':'0',
'bitlen':'32'},
'm0_config_enable':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'0',
'bitlen':'8'},
'm0_halt_cpu':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'8',
'bitlen':'8'},
'm0_cache_enable':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'16',
'bitlen':'1'},
'm0_cache_wa':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'17',
'bitlen':'1'},
'm0_cache_wb':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'18',
'bitlen':'1'},
'm0_cache_wt':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'19',
'bitlen':'1'},
'm0_cache_way_dis':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'20',
'bitlen':'4'},
'm0_reserved':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'24',
'bitlen':'8'},
'm0_cache_range_h':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 4),
'pos':'0',
'bitlen':'32'},
'm0_cache_range_l':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 8),
'pos':'0',
'bitlen':'32'},
'm0_image_address_offset':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 12),
'pos':'0',
'bitlen':'32'},
'm0_boot_entry':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 16),
'pos':'0',
'bitlen':'32'},
'm0_msp_val':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 20),
'pos':'0',
'bitlen':'32'},
'd0_config_enable':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 0),
'pos':'0',
'bitlen':'8'},
'd0_halt_cpu':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 0),
'pos':'8',
'bitlen':'8'},
'd0_cache_enable':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 0),
'pos':'16',
'bitlen':'1'},
'd0_cache_wa':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 0),
'pos':'17',
'bitlen':'1'},
'd0_cache_wb':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 0),
'pos':'18',
'bitlen':'1'},
'd0_cache_wt':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 0),
'pos':'19',
'bitlen':'1'},
'd0_cache_way_dis':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 0),
'pos':'20',
'bitlen':'4'},
'd0_reserved':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 0),
'pos':'24',
'bitlen':'8'},
'd0_cache_range_h':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 4),
'pos':'0',
'bitlen':'32'},
'd0_cache_range_l':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 8),
'pos':'0',
'bitlen':'32'},
'd0_image_address_offset':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 12),
'pos':'0',
'bitlen':'32'},
'd0_boot_entry':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 16),
'pos':'0',
'bitlen':'32'},
'd0_msp_val':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_d0_index) + 20),
'pos':'0',
'bitlen':'32'},
'lp_config_enable':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 0),
'pos':'0',
'bitlen':'8'},
'lp_halt_cpu':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 0),
'pos':'8',
'bitlen':'8'},
'lp_cache_enable':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 0),
'pos':'16',
'bitlen':'1'},
'lp_cache_wa':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 0),
'pos':'17',
'bitlen':'1'},
'lp_cache_wb':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 0),
'pos':'18',
'bitlen':'1'},
'lp_cache_wt':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 0),
'pos':'19',
'bitlen':'1'},
'lp_cache_way_dis':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 0),
'pos':'20',
'bitlen':'4'},
'lp_reserved':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 0),
'pos':'24',
'bitlen':'8'},
'lp_cache_range_h':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 4),
'pos':'0',
'bitlen':'32'},
'lp_cache_range_l':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 8),
'pos':'0',
'bitlen':'32'},
'lp_image_address_offset':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 12),
'pos':'0',
'bitlen':'32'},
'lp_boot_entry':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 16),
'pos':'0',
'bitlen':'32'},
'lp_msp_val':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_lp_index) + 20),
'pos':'0',
'bitlen':'32'},
'boot2_pt_table_0':{'offset':str(int(boot2_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'boot2_pt_table_1':{'offset':str(int(boot2_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'flashCfgTableAddr':{'offset':str(int(flashcfg_table_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'flashCfgTableLen':{'offset':str(int(flashcfg_table_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'patch_read_addr0':{'offset':str(int(patch_on_read_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'patch_read_value0':{'offset':str(int(patch_on_read_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'patch_read_addr1':{'offset':str(int(patch_on_read_start_pos) + 8),
'pos':'0',
'bitlen':'32'},
'patch_read_value1':{'offset':str(int(patch_on_read_start_pos) + 12),
'pos':'0',
'bitlen':'32'},
'patch_read_addr2':{'offset':str(int(patch_on_read_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'patch_read_value2':{'offset':str(int(patch_on_read_start_pos) + 20),
'pos':'0',
'bitlen':'32'},
'patch_read_addr3':{'offset':str(int(patch_on_read_start_pos) + 24),
'pos':'0',
'bitlen':'32'},
'patch_read_value3':{'offset':str(int(patch_on_read_start_pos) + 28),
'pos':'0',
'bitlen':'32'},
'patch_jump_addr0':{'offset':str(int(patch_on_jump_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'patch_jump_value0':{'offset':str(int(patch_on_jump_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'patch_jump_addr1':{'offset':str(int(patch_on_jump_start_pos) + 8),
'pos':'0',
'bitlen':'32'},
'patch_jump_value1':{'offset':str(int(patch_on_jump_start_pos) + 12),
'pos':'0',
'bitlen':'32'},
'patch_jump_addr2':{'offset':str(int(patch_on_jump_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'patch_jump_value2':{'offset':str(int(patch_on_jump_start_pos) + 20),
'pos':'0',
'bitlen':'32'},
'patch_jump_addr3':{'offset':str(int(patch_on_jump_start_pos) + 24),
'pos':'0',
'bitlen':'32'},
'patch_jump_value3':{'offset':str(int(patch_on_jump_start_pos) + 28),
'pos':'0',
'bitlen':'32'},
'reserved1':{'offset':str(int(rsvd_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'reserved2':{'offset':str(int(rsvd_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'reserved3':{'offset':str(int(rsvd_start_pos) + 8),
'pos':'0',
'bitlen':'32'},
'reserved4':{'offset':str(int(rsvd_start_pos) + 12),
'pos':'0',
'bitlen':'32'},
'reserved5':{'offset':str(int(rsvd_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'crc32':{'offset':str(int(crc32_start_pos) + 0),
'pos':'0',
'bitlen':'32'}}
# okay decompiling ./libs/base/bl808/bootheader_cfg_keys.pyc

View File

@ -0,0 +1,10 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl808/chiptype_patch.py
def img_load_create_predata_before_run_img():
return bytearray(0)
# okay decompiling ./libs/base/bl808/chiptype_patch.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl808/cklink_load_cfg.py
cklink_shake_hand_addr = '2204BBE8'
cklink_data_addr = '2204CC88'
cklink_load_addr = '22010000'
cklink_core_type = 'RISC-V'
cklink_set_tif = 0
cklink_run_addr = '22010000'
# okay decompiling ./libs/base/bl808/cklink_load_cfg.pyc

View File

@ -0,0 +1,153 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl808/flash_select_do.py
import os, csv
from re import I
import config as gol
from libs import bflb_utils
from libs.bflb_utils import app_path, conf_sign, cgc
from libs.bflb_configobj import BFConfigParser
from libs.base.bl808.bootheader_cfg_keys import bootheader_cfg_keys as flash_cfg_keys
def get_suitable_file_name(cfg_dir, flash_id):
conf_files = []
for home, dirs, files in os.walk(cfg_dir):
for filename in files:
if filename.split('_')[-1] == flash_id + '.conf':
conf_files.append(filename)
if len(conf_files) > 1:
bflb_utils.printf('Flash id duplicate and alternative is:')
for i in range(len(conf_files)):
tmp = conf_files[i].split('.')[0]
bflb_utils.printf('%d:%s' % (i + 1, tmp))
return conf_files[i]
if len(conf_files) == 1:
return conf_files[0]
return ''
def update_flash_cfg_do(chipname, chiptype, flash_id, file=None, create=False, section=None):
if conf_sign:
cfg_dir = app_path + '/utils/flash/' + chipname + '/'
else:
cfg_dir = app_path + '/utils/flash/' + gol.flash_dict[chipname] + '/'
conf_name = get_suitable_file_name(cfg_dir, flash_id)
value_key = []
if os.path.isfile(cfg_dir + conf_name) is False:
return False
fp = open(cfg_dir + conf_name, 'r')
for line in fp.readlines():
value = line.split('=')[0].strip()
if value == '[FLASH_CFG]':
continue
else:
value_key.append(value)
cfg1 = BFConfigParser()
cfg1.read(cfg_dir + conf_name)
cfg2 = BFConfigParser()
cfg2.read(file)
for i in range(len(value_key)):
if cfg1.has_option('FLASH_CFG', value_key[i]):
if cfg2.has_option(section, value_key[i]):
tmp_value = cfg1.get('FLASH_CFG', value_key[i])
bflb_utils.update_cfg(cfg2, section, value_key[i], tmp_value)
cfg2.write(file, 'w+')
bflb_utils.printf('Update flash cfg finished')
def get_supported_flash_do():
flash_type = []
return flash_type
def get_int_mask(pos, length):
ones = '11111111111111111111111111111111'
zeros = '00000000000000000000000000000000'
mask = ones[0:32 - pos - length] + zeros[0:length] + ones[0:pos]
return int(mask, 2)
def create_flashcfg_data_from_cfg(cfg_len, cfgfile):
section = 'FLASH_CFG'
cfg = BFConfigParser()
cfg.read(cfgfile)
data = bytearray(cfg_len)
minOffset = int(flash_cfg_keys.get('io_mode')['offset'], 10)
for key in cfg.options(section):
if flash_cfg_keys.get(key) == None:
bflb_utils.printf(key + ' not exist')
continue
else:
val = cfg.get(section, key)
if val.startswith('0x'):
val = int(val, 16)
else:
val = int(val, 10)
offset = int(flash_cfg_keys.get(key)['offset'], 10) - minOffset
pos = int(flash_cfg_keys.get(key)['pos'], 10)
bitlen = int(flash_cfg_keys.get(key)['bitlen'], 10)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = (oldval & get_int_mask(pos, bitlen)) + (val << pos)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
crcarray = bflb_utils.get_crc32_bytearray(data)
data = bflb_utils.int_to_4bytearray_l(1195787078) + data + crcarray
return data
def create_flashcfg_table(start_addr):
single_flashcfg_len = 92
flash_table_list = bytearray(0)
flash_table_data = bytearray(0)
if conf_sign:
table_file = os.path.join(app_path, 'utils', 'flash', 'tg6210a', 'flashcfg_list.csv')
else:
table_file = os.path.join(app_path, 'utils', 'flash', 'bl808', 'flashcfg_list.csv')
with open(table_file, 'r', encoding='utf-8-sig') as csvfile:
table_list = []
cfgfile_list = []
reader = csv.DictReader(csvfile)
cnt = 0
for row in reader:
row_dict = {}
row_dict['jid'] = row.get('flashJedecID', '')
row_dict['cfgfile'] = row.get('configFile', '')
if row_dict['cfgfile'] not in cfgfile_list:
cfgfile_list.append(row_dict['cfgfile'])
else:
table_list.append(row_dict)
cnt += 1
table_list_len = 4 + cnt * 8 + 4
for cfgfile in cfgfile_list:
if conf_sign:
cfgfile = os.path.join(app_path, 'utils', 'flash', 'tg6210a', cfgfile)
else:
cfgfile = os.path.join(app_path, 'utils', 'flash', 'bl808', cfgfile)
data = create_flashcfg_data_from_cfg(single_flashcfg_len - 8, cfgfile)
flash_table_data += data
for dict in table_list:
flash_table_list += bflb_utils.int_to_4bytearray_b(int(dict['jid'] + '00', 16))
i = 0
offset = 0
for cfgfile in cfgfile_list:
if cfgfile == dict['cfgfile']:
offset = start_addr + table_list_len + single_flashcfg_len * i
break
else:
i += 1
flash_table_list += bflb_utils.int_to_4bytearray_l(offset)
crcarray = bflb_utils.get_crc32_bytearray(flash_table_list)
flash_table_list = bflb_utils.int_to_4bytearray_l(1196704582) + flash_table_list + crcarray
return (
flash_table_list, flash_table_data, len(flash_table_list))
# okay decompiling ./libs/base/bl808/flash_select_do.pyc

View File

@ -0,0 +1,950 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl808/img_create_do.py
import os, sys, hashlib, binascii, codecs, ecdsa
from CryptoPlus.Cipher import AES as AES_XTS
from libs import bflb_utils
from libs.bflb_utils import img_create_sha256_data, img_create_encrypt_data
from libs.bflb_configobj import BFConfigParser
from libs.base.bl808.flash_select_do import create_flashcfg_table
from libs.base.bl808.bootheader_cfg_keys import flashcfg_table_start_pos as flashcfg_table_start
from libs.base.bl808.bootheader_cfg_keys import bootcpucfg_start_pos as bootcpucfg_start
from libs.base.bl808.bootheader_cfg_keys import bootcpucfg_len as bootcpucfg_length
from libs.base.bl808.bootheader_cfg_keys import bootcpucfg_m0_index as bootcpucfg_m0_index_number
from libs.base.bl808.bootheader_cfg_keys import bootcpucfg_d0_index as bootcpucfg_d0_index_number
from libs.base.bl808.bootheader_cfg_keys import bootcpucfg_lp_index as bootcpucfg_lp_index_number
from libs.base.bl808.bootheader_cfg_keys import bootcfg_start_pos as bootcfg_start
from libs.base.bl808.bootheader_cfg_keys import bootheader_len as header_len
keyslot0 = 28
keyslot1 = keyslot0 + 16
keyslot2 = keyslot1 + 16
keyslot3 = keyslot2 + 16
keyslot3_end = keyslot3 + 16
keyslot4 = 128
keyslot5 = keyslot4 + 16
keyslot6 = keyslot5 + 16
keyslot7 = keyslot6 + 16
keyslot8 = keyslot7 + 16
keyslot9 = keyslot8 + 16
keyslot10 = keyslot9 + 16
keyslot10_end = keyslot10 + 16
keyslot11 = keyslot3_end + 16
keyslot11_end = keyslot11 + 16
wr_lock_boot_mode = 14
wr_lock_dbg_pwd = 15
wr_lock_wifi_mac = 16
wr_lock_key_slot_0 = 17
wr_lock_key_slot_1 = 18
wr_lock_key_slot_2 = 19
wr_lock_key_slot_3 = 20
wr_lock_sw_usage_0 = 21
wr_lock_sw_usage_1 = 22
wr_lock_sw_usage_2 = 23
wr_lock_sw_usage_3 = 24
wr_lock_key_slot_11 = 25
rd_lock_dbg_pwd = 26
rd_lock_key_slot_0 = 27
rd_lock_key_slot_1 = 28
rd_lock_key_slot_2 = 29
rd_lock_key_slot_3 = 30
rd_lock_key_slot_11 = 31
wr_lock_key_slot_4 = 15
wr_lock_key_slot_5 = 16
wr_lock_key_slot_6 = 17
wr_lock_key_slot_7 = 18
wr_lock_key_slot_8 = 19
wr_lock_key_slot_9 = 20
wr_lock_key_slot_10 = 21
rd_lock_key_slot_4 = 25
rd_lock_key_slot_5 = 26
rd_lock_key_slot_6 = 27
rd_lock_key_slot_7 = 28
rd_lock_key_slot_8 = 29
rd_lock_key_slot_9 = 30
rd_lock_key_slot_10 = 31
def bytearray_data_merge(data1, data2, len):
for i in range(len):
data1[i] |= data2[i]
return data1
def img_update_efuse_group0(cfg, sign, pk_hash, flash_encryp_type, flash_key, sec_eng_key_sel, sec_eng_key, security=False):
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_file'), 'rb')
efuse_data = bytearray(fp.read()) + bytearray(0)
fp.close()
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_mask_file'), 'rb')
efuse_mask_data = bytearray(fp.read()) + bytearray(0)
fp.close()
mask_4bytes = bytearray.fromhex('FFFFFFFF')
if flash_encryp_type >= 3:
efuse_data[0] |= 3
else:
efuse_data[0] |= flash_encryp_type
if sign > 0:
efuse_data[93] |= sign
efuse_mask_data[93] |= 255
if flash_encryp_type > 0:
efuse_data[0] |= 48
efuse_mask_data[0] |= 255
rw_lock0 = 0
rw_lock1 = 0
if pk_hash is not None:
efuse_data[keyslot0:keyslot2] = pk_hash
efuse_mask_data[keyslot0:keyslot2] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_0
rw_lock0 |= 1 << wr_lock_key_slot_1
if flash_key is not None:
if flash_encryp_type == 1:
efuse_data[keyslot2:keyslot3] = flash_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
else:
if flash_encryp_type == 2:
efuse_data[keyslot2:keyslot3_end] = flash_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
else:
if flash_encryp_type == 3:
efuse_data[keyslot2:keyslot3_end] = flash_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
else:
if flash_encryp_type == 4 or flash_encryp_type == 5 or flash_encryp_type == 6:
efuse_data[keyslot2:keyslot3_end] = flash_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
if sec_eng_key is not None:
if flash_encryp_type == 0:
if sec_eng_key_sel == 0:
efuse_data[keyslot2:keyslot3] = sec_eng_key[16:32]
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 1:
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[16:32]
efuse_data[keyslot4:keyslot5] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot3_end] = mask_4bytes * 4
efuse_mask_data[keyslot4:keyslot5] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock0 |= 1 << rd_lock_key_slot_3
rw_lock1 |= 1 << rd_lock_key_slot_4
if sec_eng_key_sel == 2:
efuse_data[keyslot4:keyslot5] = sec_eng_key[16:32]
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot5] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock0 |= 1 << rd_lock_key_slot_2
if sec_eng_key_sel == 3:
efuse_data[keyslot4:keyslot5] = sec_eng_key[16:32]
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot5] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock0 |= 1 << rd_lock_key_slot_2
if flash_encryp_type == 1:
if sec_eng_key_sel == 0:
efuse_data[keyslot5:keyslot6] = sec_eng_key[0:16]
efuse_mask_data[keyslot5:keyslot6] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_5
if sec_eng_key_sel == 1:
efuse_data[keyslot4:keyslot5] = sec_eng_key[0:16]
efuse_mask_data[keyslot4:keyslot5] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock1 |= 1 << rd_lock_key_slot_4
if sec_eng_key_sel == 2:
if flash_key is not None:
pass
else:
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot3_end] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 3:
if flash_key is not None:
pass
else:
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
if flash_encryp_type == 2 or flash_encryp_type == 3 or flash_encryp_type == 4 or flash_encryp_type == 5 or flash_encryp_type == 6:
if sec_eng_key_sel == 0:
efuse_data[keyslot6:keyslot7] = sec_eng_key[16:32]
efuse_data[keyslot10:keyslot10_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot6:keyslot7] = mask_4bytes * 4
efuse_mask_data[keyslot10:keyslot10_end] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_6
rw_lock1 |= 1 << wr_lock_key_slot_10
rw_lock1 |= 1 << rd_lock_key_slot_6
rw_lock1 |= 1 << rd_lock_key_slot_10
if sec_eng_key_sel == 1:
efuse_data[keyslot10:keyslot10_end] = sec_eng_key[16:32]
efuse_data[keyslot6:keyslot7] = sec_eng_key[0:16]
efuse_mask_data[keyslot6:keyslot7] = mask_4bytes * 4
efuse_mask_data[keyslot10:keyslot10_end] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_6
rw_lock1 |= 1 << wr_lock_key_slot_10
rw_lock1 |= 1 << rd_lock_key_slot_6
rw_lock1 |= 1 << rd_lock_key_slot_10
if sec_eng_key_sel == 2:
if flash_key is not None:
pass
else:
efuse_data[keyslot2:keyslot3] = sec_eng_key[16:32]
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 3:
if flash_key is not None:
pass
else:
efuse_data[keyslot2:keyslot3_end] = sec_eng_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
efuse_data[124:128] = bytearray_data_merge(efuse_data[124:128], bflb_utils.int_to_4bytearray_l(rw_lock0), 4)
efuse_mask_data[124:128] = bytearray_data_merge(efuse_mask_data[124:128], bflb_utils.int_to_4bytearray_l(rw_lock0), 4)
efuse_data[252:256] = bytearray_data_merge(efuse_data[252:256], bflb_utils.int_to_4bytearray_l(rw_lock1), 4)
efuse_mask_data[252:256] = bytearray_data_merge(efuse_mask_data[252:256], bflb_utils.int_to_4bytearray_l(rw_lock1), 4)
if security is True:
bflb_utils.printf('Encrypt efuse data')
security_key, security_iv = bflb_utils.get_security_key()
efuse_data = img_create_encrypt_data(efuse_data, security_key, security_iv, 0)
efuse_data = bytearray(4096) + efuse_data
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_file'), 'wb+')
fp.write(efuse_data)
fp.close()
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_mask_file'), 'wb+')
fp.write(efuse_mask_data)
fp.close()
def img_update_efuse_group1(cfg, sign, pk_hash, flash_encryp_type, flash_key, sec_eng_key_sel, sec_eng_key, security=False):
fp = open(cfg.get('Img_Group1_Cfg', 'efuse_file'), 'rb')
efuse_data = bytearray(fp.read()) + bytearray(0)
fp.close()
fp = open(cfg.get('Img_Group1_Cfg', 'efuse_mask_file'), 'rb')
efuse_mask_data = bytearray(fp.read()) + bytearray(0)
fp.close()
mask_4bytes = bytearray.fromhex('FFFFFFFF')
if flash_encryp_type >= 3:
efuse_data[0] |= 3
else:
efuse_data[0] |= flash_encryp_type
if sign > 0:
efuse_data[93] |= sign
efuse_mask_data[93] |= 255
if flash_encryp_type > 0:
efuse_data[0] |= 48
efuse_mask_data[0] |= 255
rw_lock0 = 0
rw_lock1 = 0
if pk_hash is not None:
efuse_data[keyslot8:keyslot10] = pk_hash
efuse_mask_data[keyslot8:keyslot10] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_8
rw_lock1 |= 1 << wr_lock_key_slot_9
if flash_key is not None:
if flash_encryp_type == 1:
efuse_data[keyslot3:keyslot3_end] = flash_key[0:16]
efuse_mask_data[keyslot3:keyslot3_end] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
else:
pass
if flash_encryp_type == 2:
efuse_data[keyslot4:keyslot6] = flash_key
efuse_mask_data[keyslot4:keyslot6] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock1 |= 1 << rd_lock_key_slot_5
else:
if flash_encryp_type == 3:
efuse_data[keyslot4:keyslot6] = flash_key
efuse_mask_data[keyslot4:keyslot6] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock1 |= 1 << rd_lock_key_slot_5
else:
if flash_encryp_type == 4 or flash_encryp_type == 5 or flash_encryp_type == 6:
efuse_data[keyslot4:keyslot6] = flash_key
efuse_mask_data[keyslot4:keyslot6] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock1 |= 1 << rd_lock_key_slot_5
if sec_eng_key is not None:
if flash_encryp_type == 0:
if sec_eng_key_sel == 0:
efuse_data[keyslot5:keyslot6] = sec_eng_key[16:32]
efuse_data[keyslot6:keyslot7] = sec_eng_key[0:16]
efuse_mask_data[keyslot5:keyslot7] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << wr_lock_key_slot_6
rw_lock1 |= 1 << rd_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_6
if sec_eng_key_sel == 1:
efuse_data[keyslot6:keyslot7] = sec_eng_key[16:32]
efuse_data[keyslot7:keyslot8] = sec_eng_key[0:16]
efuse_mask_data[keyslot6:keyslot8] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_6
rw_lock1 |= 1 << wr_lock_key_slot_7
rw_lock1 |= 1 << rd_lock_key_slot_6
rw_lock1 |= 1 << rd_lock_key_slot_7
if sec_eng_key_sel == 2:
efuse_data[keyslot7:keyslot8] = sec_eng_key[16:32]
efuse_data[keyslot5:keyslot6] = sec_eng_key[0:16]
efuse_mask_data[keyslot7:keyslot8] = mask_4bytes * 4
efuse_mask_data[keyslot5:keyslot6] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_7
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_7
rw_lock1 |= 1 << rd_lock_key_slot_5
if sec_eng_key_sel == 3:
efuse_data[keyslot7:keyslot8] = sec_eng_key[16:32]
efuse_data[keyslot5:keyslot6] = sec_eng_key[0:16]
efuse_mask_data[keyslot7:keyslot8] = mask_4bytes * 4
efuse_mask_data[keyslot5:keyslot6] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_7
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_7
rw_lock1 |= 1 << rd_lock_key_slot_5
if flash_encryp_type == 1:
if sec_eng_key_sel == 0:
efuse_data[keyslot7:keyslot8] = sec_eng_key[0:16]
efuse_mask_data[keyslot7:keyslot8] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_7
rw_lock1 |= 1 << rd_lock_key_slot_7
if sec_eng_key_sel == 1:
efuse_data[keyslot6:keyslot7] = sec_eng_key[0:16]
efuse_mask_data[keyslot6:keyslot7] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_6
rw_lock1 |= 1 << rd_lock_key_slot_6
if sec_eng_key_sel == 2:
if flash_key is not None:
pass
else:
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot3_end] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 3:
if flash_key is not None:
pass
else:
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
if flash_encryp_type == 2 or flash_encryp_type == 3 or flash_encryp_type == 4 or flash_encryp_type == 5 or flash_encryp_type == 6:
if sec_eng_key_sel == 0:
efuse_data[keyslot7:keyslot8] = sec_eng_key[16:32]
efuse_data[keyslot11:keyslot11_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot7:keyslot8] = mask_4bytes * 4
efuse_mask_data[keyslot11:keyslot11_end] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_7
rw_lock0 |= 1 << rd_lock_key_slot_11
rw_lock1 |= 1 << wr_lock_key_slot_7
rw_lock0 |= 1 << rd_lock_key_slot_11
if sec_eng_key_sel == 1:
efuse_data[keyslot11:keyslot11_end] = sec_eng_key[16:32]
efuse_data[keyslot7:keyslot8] = sec_eng_key[0:16]
efuse_mask_data[keyslot7:keyslot8] = mask_4bytes * 4
efuse_mask_data[keyslot11:keyslot11_end] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_7
rw_lock0 |= 1 << rd_lock_key_slot_11
rw_lock1 |= 1 << wr_lock_key_slot_7
rw_lock0 |= 1 << rd_lock_key_slot_11
if sec_eng_key_sel == 2:
if flash_key is not None:
pass
else:
efuse_data[keyslot4:keyslot5] = sec_eng_key[16:32]
efuse_data[keyslot5:keyslot6] = sec_eng_key[0:16]
efuse_mask_data[keyslot4:keyslot6] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock1 |= 1 << rd_lock_key_slot_5
if sec_eng_key_sel == 3:
if flash_key is not None:
pass
else:
efuse_data[keyslot4:keyslot6] = sec_eng_key
efuse_mask_data[keyslot4:keyslot6] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock1 |= 1 << rd_lock_key_slot_5
efuse_data[124:128] = bytearray_data_merge(efuse_data[124:128], bflb_utils.int_to_4bytearray_l(rw_lock0), 4)
efuse_mask_data[124:128] = bytearray_data_merge(efuse_mask_data[124:128], bflb_utils.int_to_4bytearray_l(rw_lock0), 4)
efuse_data[252:256] = bytearray_data_merge(efuse_data[252:256], bflb_utils.int_to_4bytearray_l(rw_lock1), 4)
efuse_mask_data[252:256] = bytearray_data_merge(efuse_mask_data[252:256], bflb_utils.int_to_4bytearray_l(rw_lock1), 4)
if security is True:
bflb_utils.printf('Encrypt efuse data')
security_key, security_iv = bflb_utils.get_security_key()
efuse_data = img_create_encrypt_data(efuse_data, security_key, security_iv, 0)
efuse_data = bytearray(4096) + efuse_data
fp = open(cfg.get('Img_Group1_Cfg', 'efuse_file'), 'wb+')
fp.write(efuse_data)
fp.close()
fp = open(cfg.get('Img_Group1_Cfg', 'efuse_mask_file'), 'wb+')
fp.write(efuse_mask_data)
fp.close()
def img_create_get_sign_encrypt_info(bootheader_data):
sign = bootheader_data[bootcfg_start] & 3
encrypt = bootheader_data[bootcfg_start] >> 2 & 3
key_sel = bootheader_data[bootcfg_start] >> 4 & 3
xts_mode = bootheader_data[bootcfg_start] >> 6 & 1
return (
sign, encrypt, key_sel, xts_mode)
def img_create_get_img_start_addr(bootheader_data):
bootentry = []
bootentry.append(bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(bootheader_data[bootcpucfg_start + bootcpucfg_length * bootcpucfg_m0_index_number + 16:bootcpucfg_start + bootcpucfg_length * bootcpucfg_m0_index_number + 16 + 4])))
bootentry.append(bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(bootheader_data[bootcpucfg_start + bootcpucfg_length * bootcpucfg_d0_index_number + 16:bootcpucfg_start + bootcpucfg_length * bootcpucfg_d0_index_number + 16 + 4])))
bootentry.append(bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(bootheader_data[bootcpucfg_start + bootcpucfg_length * bootcpucfg_lp_index_number + 16:bootcpucfg_start + bootcpucfg_length * bootcpucfg_lp_index_number + 16 + 4])))
return bootentry
def img_create_flash_default_data(length):
datas = bytearray(length)
for i in range(length):
datas[i] = 255
return datas
def img_get_file_data(files):
datas = []
for file in files:
if file == 'UNUSED':
datas.append(bytearray(0))
continue
else:
with open(file, 'rb') as fp:
data = fp.read()
datas.append(data)
return datas
def img_get_largest_addr(addrs, files):
min = 67108863
maxlen = 0
datalen = 0
for i in range(len(addrs)):
if files[i] == 'UNUSED':
continue
else:
addr = addrs[i] & 67108863
if addr >= maxlen:
maxlen = addr
datalen = os.path.getsize(files[i])
if addr <= min:
min = addr
if maxlen == 0:
if datalen == 0:
return (0, 0)
return (
maxlen + datalen - min, min)
def img_get_one_group_img(d_addrs, d_files):
whole_img_len, min = img_get_largest_addr(d_addrs, d_files)
whole_img_len &= 67108863
whole_img_data = img_create_flash_default_data(whole_img_len)
filedatas = img_get_file_data(d_files)
for i in range(len(d_addrs)):
if d_files[i] == 'UNUSED':
continue
else:
start_addr = d_addrs[i]
start_addr &= 67108863
start_addr -= min
whole_img_data[start_addr:start_addr + len(filedatas[i])] = filedatas[i]
return whole_img_data
def img_create_get_hash_ignore(bootheader_data):
return bootheader_data[bootcfg_start + 2] >> 1 & 1
def img_create_get_crc_ignore(bootheader_data):
return bootheader_data[bootcfg_start + 2] & 1
def img_create_update_bootheader_if(bootheader_data, hash, seg_cnt):
bootheader_data[bootcfg_start + 12:bootcfg_start + 12 + 4] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign = bootheader_data[bootcfg_start] & 3
encrypt = bootheader_data[bootcfg_start] >> 2 & 3
key_sel = bootheader_data[bootcfg_start] >> 4 & 3
xts_mode = bootheader_data[bootcfg_start] >> 6 & 1
if bootheader_data[bootcfg_start + 2] >> 1 & 1 == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[bootcfg_start + 16:bootcfg_start + 16 + 32] = hash
if bootheader_data[bootcfg_start + 2] & 1 == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[0:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data
def img_create_update_bootheader(bootheader_data, hash, seg_cnt, flashcfg_table_addr, flashcfg_table_len):
bootheader_data[flashcfg_table_start:flashcfg_table_start + 4] = bflb_utils.int_to_4bytearray_l(flashcfg_table_addr)
bootheader_data[flashcfg_table_start + 4:flashcfg_table_start + 8] = bflb_utils.int_to_4bytearray_l(flashcfg_table_len)
bootheader_data[bootcfg_start + 12:bootcfg_start + 12 + 4] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign, encrypt, key_sel, xts_mode = img_create_get_sign_encrypt_info(bootheader_data)
if img_create_get_hash_ignore(bootheader_data) == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[bootcfg_start + 16:bootcfg_start + 16 + 32] = hash
if img_create_get_crc_ignore(bootheader_data) == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[0:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data[0:header_len]
def img_create_update_segheader(segheader, segdatalen, segdatacrc):
segheader[4:8] = segdatalen
segheader[8:12] = segdatacrc
return segheader
def reverse_str_data_unit_number(str_data_unit_number):
"""
high position low data
data unit number:00000280
storage format: 80020000
"""
reverse_str = ''
if len(str_data_unit_number) == 8:
str_part1 = str_data_unit_number[0:2]
str_part2 = str_data_unit_number[2:4]
str_part3 = str_data_unit_number[4:6]
str_part4 = str_data_unit_number[6:8]
reverse_str = str_part4 + str_part3 + str_part2 + str_part1
return reverse_str
def reverse_iv(need_reverse_iv_bytearray):
temp_reverse_iv_bytearray = binascii.hexlify(need_reverse_iv_bytearray).decode()
if temp_reverse_iv_bytearray[24:32] != '00000000':
bflb_utils.printf('The lower 4 bytes of IV should be set 0, if set IV is less than 16 bytes, make up 0 for the low 4 bytes of IV ')
sys.exit()
reverse_iv_bytearray = '00000000' + temp_reverse_iv_bytearray[0:24]
return reverse_iv_bytearray
def img_create_encrypt_data_xts(data_bytearray, key_bytearray, iv_bytearray, encrypt):
counter = binascii.hexlify(iv_bytearray[4:16]).decode()
data_unit_number = 0
key = (
key_bytearray[0:16], key_bytearray[16:32])
if encrypt == 2 or encrypt == 3:
key = (
key_bytearray, key_bytearray)
cipher = AES_XTS.new(key, AES_XTS.MODE_XTS)
total_len = len(data_bytearray)
ciphertext = bytearray(0)
deal_len = 0
while deal_len < total_len:
data_unit_number = str(hex(data_unit_number)).replace('0x', '')
data_unit_number_to_str = str(data_unit_number)
right_justify_str = data_unit_number_to_str.rjust(8, '0')
reverse_data_unit_number_str = reverse_str_data_unit_number(right_justify_str)
tweak = reverse_data_unit_number_str + counter
tweak = bflb_utils.hexstr_to_bytearray('0' * (32 - len(tweak)) + tweak)
if 32 + deal_len <= total_len:
cur_block = data_bytearray[0 + deal_len:32 + deal_len]
ciphertext += cipher.encrypt(cur_block, tweak)
else:
cur_block = data_bytearray[0 + deal_len:16 + deal_len] + bytearray(16)
ciphertext += cipher.encrypt(cur_block, tweak)[0:16]
deal_len += 32
data_unit_number = int(data_unit_number, 16)
data_unit_number += 1
return ciphertext
def img_create_sign_data(data_bytearray, privatekey_file_uecc, publickey_file):
sk = ecdsa.SigningKey.from_pem(open(privatekey_file_uecc).read())
vk = ecdsa.VerifyingKey.from_pem(open(publickey_file).read())
pk_data = vk.to_string()
bflb_utils.printf('Private key: ', binascii.hexlify(sk.to_string()))
bflb_utils.printf('Public key: ', binascii.hexlify(pk_data))
pk_hash = img_create_sha256_data(pk_data)
bflb_utils.printf('Public key hash=', binascii.hexlify(pk_hash))
signature = sk.sign(data_bytearray, hashfunc=(hashlib.sha256), sigencode=(ecdsa.util.sigencode_string))
bflb_utils.printf('Signature=', binascii.hexlify(signature))
len_array = bflb_utils.int_to_4bytearray_l(len(signature))
sig_field = len_array + signature
crcarray = bflb_utils.get_crc32_bytearray(sig_field)
return (
pk_data, pk_hash, sig_field + crcarray)
def img_create_read_file_append_crc(file, crc):
fp = open(file, 'rb')
read_data = bytearray(fp.read())
crcarray = bytearray(0)
if crc:
crcarray = bflb_utils.get_crc32_bytearray(read_data)
fp.close()
return read_data + crcarray
def encrypt_loader_bin_do(file, sign, encrypt, temp_encrypt_key, temp_encrypt_iv, publickey_file, privatekey_file):
if encrypt != 0 or sign != 0:
encrypt_key = bytearray(0)
encrypt_iv = bytearray(0)
load_helper_bin_header = bytearray(0)
load_helper_bin_body = bytearray(0)
offset = bootcfg_start
sign_pos = 0
encrypt_type_pos = 2
pk_data = bytearray(0)
signature = bytearray(0)
aesiv_data = bytearray(0)
data_tohash = bytearray(0)
with open(file, 'rb') as fp:
load_helper_bin = fp.read()
load_helper_bin_header = load_helper_bin[0:header_len]
load_helper_bin_body = load_helper_bin[header_len:]
if load_helper_bin_header != bytearray(0):
if load_helper_bin_body != bytearray(0):
load_helper_bin_body = bflb_utils.add_to_16(load_helper_bin_body)
if encrypt != 0:
encrypt_key = bflb_utils.hexstr_to_bytearray(temp_encrypt_key)
encrypt_iv = bflb_utils.hexstr_to_bytearray(temp_encrypt_iv)
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
load_helper_bin_body_encrypt = bflb_utils.img_create_encrypt_data(load_helper_bin_body, encrypt_key, encrypt_iv, 0)
else:
load_helper_bin_body_encrypt = load_helper_bin_body
data = bytearray(load_helper_bin_header)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = oldval
if encrypt != 0:
newval = newval | 1 << encrypt_type_pos
if sign != 0:
newval = newval | 1 << sign_pos
data_tohash += load_helper_bin_body_encrypt
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
load_helper_bin_header = data
load_helper_bin_encrypt = load_helper_bin_header + pk_data + signature + aesiv_data + load_helper_bin_body_encrypt
hashfun = hashlib.sha256()
hashfun.update(load_helper_bin_body_encrypt)
hash = bflb_utils.hexstr_to_bytearray(hashfun.hexdigest())
load_helper_bin_data = bytearray(load_helper_bin_encrypt)
load_helper_bin_encrypt = img_create_update_bootheader_if(load_helper_bin_data, hash, 1)
return (
True, load_helper_bin_encrypt)
return (False, None)
def img_creat_process(group_type, flash_img, cfg, security=False):
encrypt_blk_size = 16
padding = bytearray(encrypt_blk_size)
data_tohash = bytearray(0)
cfg_section = ''
if group_type == 'group0':
img_update_efuse_fun = img_update_efuse_group0
cfg_section = 'Img_Group0_Cfg'
else:
if group_type == 'group1':
img_update_efuse_fun = img_update_efuse_group1
cfg_section = 'Img_Group1_Cfg'
else:
bflb_utils.printf('group type wrong')
return (
'FAIL', data_tohash)
segheader_file = []
if flash_img == 0:
for files in cfg.get(cfg_section, 'segheader_file').split(' '):
segheader_file.append(str(files))
segdata_file = []
for files in cfg.get(cfg_section, 'segdata_file').split('|'):
if files:
segdata_file.append(str(files))
boot_header_file = cfg.get(cfg_section, 'boot_header_file')
bootheader_data = img_create_read_file_append_crc(boot_header_file, 0)
encrypt = 0
sign, encrypt, key_sel, xts_mode = img_create_get_sign_encrypt_info(bootheader_data)
boot_entry = img_create_get_img_start_addr(bootheader_data)
aesiv_data = bytearray(0)
pk_data = bytearray(0)
publickey_file = ''
privatekey_file_uecc = ''
if sign != 0:
bflb_utils.printf('Image need sign')
publickey_file = cfg.get(cfg_section, 'publickey_file')
privatekey_file_uecc = cfg.get(cfg_section, 'privatekey_file_uecc')
if encrypt != 0:
bflb_utils.printf('Image need encrypt ', encrypt)
if xts_mode == 1:
bflb_utils.printf('Enable xts mode')
encrypt_key_org = bflb_utils.hexstr_to_bytearray(cfg.get(cfg_section, 'aes_key_org'))
if encrypt == 1:
if xts_mode == 1:
encrypt_key = encrypt_key_org[0:32]
else:
encrypt_key = encrypt_key_org[0:16]
else:
if encrypt == 2:
if xts_mode == 1:
encrypt_key = encrypt_key_org[0:32]
else:
encrypt_key = encrypt_key_org[0:32]
else:
if encrypt == 3:
if xts_mode == 1:
encrypt_key = encrypt_key_org[0:24]
else:
encrypt_key = encrypt_key_org[0:24]
bflb_utils.printf('Key= ', binascii.hexlify(encrypt_key))
iv_value = cfg.get(cfg_section, 'aes_iv')
if xts_mode == 1:
iv_value = iv_value[24:32] + iv_value[:24]
encrypt_iv = bflb_utils.hexstr_to_bytearray(iv_value)
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
seg_cnt = len(segheader_file)
segdata_cnt = len(segdata_file)
if flash_img == 0:
if seg_cnt != segdata_cnt:
bflb_utils.printf('Segheader count and segdata count not match')
return (
'FAIL', data_tohash)
data_toencrypt = bytearray(0)
if flash_img == 0:
i = 0
seg_header_list = []
seg_data_list = []
while i < seg_cnt:
seg_data = bytearray(0)
if segdata_file[i] != 'UNUSED':
seg_data = img_create_read_file_append_crc(segdata_file[i], 0)
else:
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
segdata_crcarray = bflb_utils.get_crc32_bytearray(seg_data)
seg_data_list.append(seg_data)
seg_header = img_create_read_file_append_crc(segheader_file[i], 0)
seg_header = img_create_update_segheader(seg_header, bflb_utils.int_to_4bytearray_l(len(seg_data)), segdata_crcarray)
segheader_crcarray = bflb_utils.get_crc32_bytearray(seg_header)
seg_header = seg_header + segheader_crcarray
seg_header_list.append(seg_header)
i = i + 1
i = 0
cnt = 0
while i < seg_cnt:
if seg_header_list[i][4:8] != bytearray(4):
data_toencrypt += seg_header_list[i]
data_toencrypt += seg_data_list[i]
cnt += 1
else:
i += 1
seg_cnt = cnt
else:
seg_data = img_get_one_group_img(boot_entry, segdata_file)
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
data_toencrypt += seg_data
seg_cnt = len(data_toencrypt)
if encrypt != 0:
unencrypt_mfg_data = bytearray(0)
if seg_cnt >= 8192:
if data_toencrypt[4096:4100] == bytearray('0mfg'.encode('utf-8')):
unencrypt_mfg_data = data_toencrypt[4096:8192]
if xts_mode != 0:
data_toencrypt = img_create_encrypt_data_xts(data_toencrypt, encrypt_key, encrypt_iv, encrypt)
else:
data_toencrypt = img_create_encrypt_data(data_toencrypt, encrypt_key, encrypt_iv, flash_img)
if unencrypt_mfg_data != bytearray(0):
data_toencrypt = data_toencrypt[0:4096] + unencrypt_mfg_data + data_toencrypt[8192:]
fw_data = bytearray(0)
data_tohash += data_toencrypt
fw_data = data_toencrypt
hash = img_create_sha256_data(data_tohash)
bflb_utils.printf('Image hash is ', binascii.hexlify(hash))
signature = bytearray(0)
pk_hash = None
if sign == 1:
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file_uecc, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
flashCfgAddr = len(bootheader_data + pk_data + pk_data + signature + signature + aesiv_data)
flashCfgListLen = 0
flashCfgList = bytearray(0)
flashCfgTable = bytearray(0)
if flash_img == 1:
if bootheader_data[25:26] == b'\xff':
flashCfgList, flashCfgTable, flashCfgListLen = create_flashcfg_table(flashCfgAddr)
bootheader_data = img_create_update_bootheader(bootheader_data, hash, seg_cnt, flashCfgAddr, flashCfgListLen)
if flash_img == 1:
bflb_utils.printf('Write flash img')
bootinfo_file_name = cfg.get(cfg_section, 'bootinfo_file')
fp = open(bootinfo_file_name, 'wb+')
bootinfo = bootheader_data + pk_data + pk_data + signature + signature + aesiv_data + flashCfgList + flashCfgTable
fp.write(bootinfo)
fp.close()
fw_file_name = cfg.get(cfg_section, 'img_file')
fp = open(fw_file_name, 'wb+')
fp.write(fw_data)
fp.close()
fw_data_hash = img_create_sha256_data(fw_data)
fp = open(fw_file_name.replace('.bin', '_withhash.bin'), 'wb+')
fp.write(fw_data + fw_data_hash)
fp.close()
if encrypt != 0:
flash_encrypt_type = 0
if encrypt == 1:
flash_encrypt_type = 1
if encrypt == 2:
flash_encrypt_type = 3
if encrypt == 3:
flash_encrypt_type = 2
if xts_mode == 1:
flash_encrypt_type += 3
img_update_efuse_fun(cfg, sign, pk_hash, flash_encrypt_type, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, None, security)
else:
img_update_efuse_fun(cfg, sign, pk_hash, encrypt, None, key_sel, None, security)
else:
bflb_utils.printf('Write if img')
whole_img_file_name = cfg.get(cfg_section, 'whole_img_file')
fp = open(whole_img_file_name, 'wb+')
img_data = bootheader_data + pk_data + pk_data + signature + signature + aesiv_data + fw_data
fp.write(img_data)
fp.close()
if encrypt != 0:
if_encrypt_type = 0
if encrypt == 1:
if_encrypt_type = 1
if encrypt == 2:
if_encrypt_type = 3
if encrypt == 3:
if_encrypt_type = 2
if xts_mode == 1:
if_encrypt_type += 3
img_update_efuse_fun(cfg, sign, pk_hash, if_encrypt_type, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
else:
img_update_efuse_fun(cfg, sign, pk_hash, 0, None, key_sel, bytearray(32), security)
return (
'OK', data_tohash)
def img_create_do(args, img_dir_path=None, config_file=None):
bflb_utils.printf('Image create path: ', img_dir_path)
if config_file is None:
config_file = img_dir_path + '/img_create_cfg.ini'
bflb_utils.printf('Config file: ', config_file)
cfg = BFConfigParser()
cfg.read(config_file)
group_type = 'all'
img_type = 'media'
signer = 'none'
security = False
data_tohash = bytearray(0)
try:
if args.image:
img_type = args.image
if args.group:
group_type = args.group
if args.signer:
signer = args.signer
if args.security:
security = args.security == 'efuse'
except Exception as e:
try:
bflb_utils.printf(e)
finally:
e = None
del e
if img_type == 'media':
flash_img = 1
else:
flash_img = 0
ret0 = ret1 = 'OK'
if group_type == 'group0':
ret0, data_tohash0 = img_creat_process('group0', flash_img, cfg, security)
else:
if group_type == 'group1':
ret1, data_tohash1 = img_creat_process('group1', flash_img, cfg, security)
else:
if group_type == 'all':
ret0, data_tohash0 = img_creat_process('group0', flash_img, cfg, False)
ret1, data_tohash1 = img_creat_process('group1', flash_img, cfg, security)
else:
img_creat_process('', flash_img, cfg, security)
if ret0 != 'OK':
bflb_utils.printf('Fail to create group0 images!')
return
if ret1 != 'OK':
bflb_utils.printf('Fail to create group1 images!')
def create_sp_media_image(config, cpu_type=None, security=False):
bflb_utils.printf('========= sp image create =========')
cfg = BFConfigParser()
cfg.read(config)
if cpu_type == 'Group1':
img_creat_process('group1', 1, cfg, security)
else:
img_creat_process('group0', 1, cfg, security)
if __name__ == '__main__':
data_bytearray = codecs.decode('42464E500100000046434647040101036699FF039F00B7E904EF0001C72052D8060232000B010B013B01BB006B01EB02EB02025000010001010002010101AB01053500000131000038FF20FF77030240770302F02C01B004B0040500FFFF030036C3DD9E5043464704040001010105000101050000010101A612AC86000144650020000000000000503100007A6345494BCABEC7307FD8F8396729EB67DDC8C63B7AD69B797B08564E982A8701000000000000000000000000000000000000D80000000000010000000000000000000000200100000001D80000000000010000000000000000000000200200000002580000000000010000000000000000000000200300000003580000000000010000D0C57503C09E750300200400000004580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000935F92BB', 'hex')
key_bytearray = codecs.decode('fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0000102030405060708090a0b0c0d0e0f', 'hex')
need_reverse_iv_bytearray = codecs.decode('01000000000000000000000000000000', 'hex')
iv_bytearray = codecs.decode(reverse_iv(need_reverse_iv_bytearray), 'hex')
img_create_encrypt_data_xts(data_bytearray, key_bytearray, iv_bytearray, 0)
# okay decompiling ./libs/base/bl808/img_create_do.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl808/jlink_load_cfg.py
jlink_shake_hand_addr = '2204BBE8'
jlink_data_addr = '2204CC88'
jlink_load_addr = '22010000'
jlink_core_type = 'RISC-V'
jlink_set_tif = 0
jlink_run_addr = '22010000'
# okay decompiling ./libs/base/bl808/jlink_load_cfg.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/bl808/openocd_load_cfg.py
openocd_shake_hand_addr = '2204BBE8'
openocd_data_addr = '2204CC88'
openocd_load_addr = '22010000'
openocd_core_type = 'RISC-V'
openocd_set_tif = 0
openocd_run_addr = '22010000'
# okay decompiling ./libs/base/bl808/openocd_load_cfg.pyc

View File

@ -0,0 +1,645 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/wb03/bootheader_cfg_keys.py
custom_config_len = 208
clock_start_pos = 100 + custom_config_len
bootcfg_start_pos = 120 + custom_config_len
bootcfg_len = 48
bootcpucfg_start_pos = bootcfg_start_pos + bootcfg_len
bootcpucfg_len = 16
bootcpucfg_m0_index = 0
bootcpucfg_d0_index = 1
bootcpucfg_lp_index = 2
boot2_start_pos = bootcpucfg_start_pos + bootcpucfg_len * (bootcpucfg_m0_index + 1)
boot2_len = 8
flashcfg_table_start_pos = boot2_start_pos + boot2_len
flashcfg_table_len = 8
patch_on_read_start_pos = flashcfg_table_start_pos + flashcfg_table_len
patch_on_read_len = 24
patch_on_jump_start_pos = patch_on_read_start_pos + patch_on_read_len
patch_on_jump_len = 24
rsvd_start_pos = patch_on_jump_start_pos + patch_on_jump_len
rsvd_len = 4
crc32_start_pos = rsvd_start_pos + rsvd_len
bootheader_len = crc32_start_pos + 4
bootheader_cfg_keys = {'custom_magic_code':{'offset':'0',
'pos':'0',
'bitlen':'32'},
'custom_crc32':{'offset':'4',
'pos':'0',
'bitlen':'32'},
'custom_vendor_id':{'offset':'8',
'pos':'0',
'bitlen':'32'},
'custom_version':{'offset':'12',
'pos':'0',
'bitlen':'32'},
'custom_vendor_boot_offset':{'offset':'16',
'pos':'0',
'bitlen':'32'},
'custom_vendor_boot_len':{'offset':'20',
'pos':'0',
'bitlen':'32'},
'custom_ecc_type':{'offset':'24',
'pos':'0',
'bitlen':'8'},
'custom_aes_type':{'offset':'24',
'pos':'8',
'bitlen':'8'},
'custom_rsvd2':{'offset':'24',
'pos':'16',
'bitlen':'16'},
'custom_hash_0':{'offset':'28',
'pos':'0',
'bitlen':'32'},
'custom_hash_1':{'offset':'32',
'pos':'0',
'bitlen':'32'},
'custom_hash_2':{'offset':'36',
'pos':'0',
'bitlen':'32'},
'custom_hash_3':{'offset':'40',
'pos':'0',
'bitlen':'32'},
'custom_hash_4':{'offset':'44',
'pos':'0',
'bitlen':'32'},
'custom_hash_5':{'offset':'48',
'pos':'0',
'bitlen':'32'},
'custom_hash_6':{'offset':'52',
'pos':'0',
'bitlen':'32'},
'custom_hash_7':{'offset':'56',
'pos':'0',
'bitlen':'32'},
'custom_signature_0':{'offset':'60',
'pos':'0',
'bitlen':'32'},
'custom_signature_1':{'offset':'64',
'pos':'0',
'bitlen':'32'},
'custom_signature_2':{'offset':'68',
'pos':'0',
'bitlen':'32'},
'custom_signature_3':{'offset':'72',
'pos':'0',
'bitlen':'32'},
'custom_signature_4':{'offset':'76',
'pos':'0',
'bitlen':'32'},
'custom_signature_5':{'offset':'80',
'pos':'0',
'bitlen':'32'},
'custom_signature_6':{'offset':'84',
'pos':'0',
'bitlen':'32'},
'custom_signature_7':{'offset':'88',
'pos':'0',
'bitlen':'32'},
'custom_signature_8':{'offset':'92',
'pos':'0',
'bitlen':'32'},
'custom_signature_9':{'offset':'96',
'pos':'0',
'bitlen':'32'},
'custom_signature_10':{'offset':'100',
'pos':'0',
'bitlen':'32'},
'custom_signature_11':{'offset':'104',
'pos':'0',
'bitlen':'32'},
'custom_signature_12':{'offset':'108',
'pos':'0',
'bitlen':'32'},
'custom_signature_13':{'offset':'112',
'pos':'0',
'bitlen':'32'},
'custom_signature_14':{'offset':'116',
'pos':'0',
'bitlen':'32'},
'custom_signature_15':{'offset':'120',
'pos':'0',
'bitlen':'32'},
'custom_pk_0':{'offset':'124',
'pos':'0',
'bitlen':'32'},
'custom_pk_1':{'offset':'128',
'pos':'0',
'bitlen':'32'},
'custom_pk_2':{'offset':'132',
'pos':'0',
'bitlen':'32'},
'custom_pk_3':{'offset':'136',
'pos':'0',
'bitlen':'32'},
'custom_pk_4':{'offset':'140',
'pos':'0',
'bitlen':'32'},
'custom_pk_5':{'offset':'144',
'pos':'0',
'bitlen':'32'},
'custom_pk_6':{'offset':'148',
'pos':'0',
'bitlen':'32'},
'custom_pk_7':{'offset':'152',
'pos':'0',
'bitlen':'32'},
'custom_pk_8':{'offset':'156',
'pos':'0',
'bitlen':'32'},
'custom_pk_9':{'offset':'160',
'pos':'0',
'bitlen':'32'},
'custom_pk_10':{'offset':'164',
'pos':'0',
'bitlen':'32'},
'custom_pk_11':{'offset':'168',
'pos':'0',
'bitlen':'32'},
'custom_pk_12':{'offset':'172',
'pos':'0',
'bitlen':'32'},
'custom_pk_13':{'offset':'176',
'pos':'0',
'bitlen':'32'},
'custom_pk_14':{'offset':'180',
'pos':'0',
'bitlen':'32'},
'custom_pk_15':{'offset':'184',
'pos':'0',
'bitlen':'32'},
'custom_aes_iv_0':{'offset':'188',
'pos':'0',
'bitlen':'32'},
'custom_aes_iv_1':{'offset':'192',
'pos':'0',
'bitlen':'32'},
'custom_aes_iv_2':{'offset':'196',
'pos':'0',
'bitlen':'32'},
'custom_aes_iv_3':{'offset':'200',
'pos':'0',
'bitlen':'32'},
'custom_rsvd4':{'offset':'204',
'pos':'0',
'bitlen':'32'},
'magic_code':{'offset':str(int(custom_config_len) + 0),
'pos':'0',
'bitlen':'32'},
'revision':{'offset':str(int(custom_config_len) + 4),
'pos':'0',
'bitlen':'32'},
'flashcfg_magic_code':{'offset':str(int(custom_config_len) + 8),
'pos':'0',
'bitlen':'32'},
'io_mode':{'offset':str(int(custom_config_len) + 12),
'pos':'0',
'bitlen':'8'},
'cont_read_support':{'offset':str(int(custom_config_len) + 12),
'pos':'8',
'bitlen':'8'},
'sfctrl_clk_delay':{'offset':str(int(custom_config_len) + 12),
'pos':'16',
'bitlen':'8'},
'sfctrl_clk_invert':{'offset':str(int(custom_config_len) + 12),
'pos':'24',
'bitlen':'8'},
'reset_en_cmd':{'offset':str(int(custom_config_len) + 16),
'pos':'0',
'bitlen':'8'},
'reset_cmd':{'offset':str(int(custom_config_len) + 16),
'pos':'8',
'bitlen':'8'},
'exit_contread_cmd':{'offset':str(int(custom_config_len) + 16),
'pos':'16',
'bitlen':'8'},
'exit_contread_cmd_size':{'offset':str(int(custom_config_len) + 16),
'pos':'24',
'bitlen':'8'},
'jedecid_cmd':{'offset':str(int(custom_config_len) + 20),
'pos':'0',
'bitlen':'8'},
'jedecid_cmd_dmy_clk':{'offset':str(int(custom_config_len) + 20),
'pos':'8',
'bitlen':'8'},
'enter_32bits_addr_cmd':{'offset':str(int(custom_config_len) + 20),
'pos':'16',
'bitlen':'8'},
'exit_32bits_addr_clk':{'offset':str(int(custom_config_len) + 20),
'pos':'24',
'bitlen':'8'},
'sector_size':{'offset':str(int(custom_config_len) + 24),
'pos':'0',
'bitlen':'8'},
'mfg_id':{'offset':str(int(custom_config_len) + 24),
'pos':'8',
'bitlen':'8'},
'page_size':{'offset':str(int(custom_config_len) + 24),
'pos':'16',
'bitlen':'16'},
'chip_erase_cmd':{'offset':str(int(custom_config_len) + 28),
'pos':'0',
'bitlen':'8'},
'sector_erase_cmd':{'offset':str(int(custom_config_len) + 28),
'pos':'8',
'bitlen':'8'},
'blk32k_erase_cmd':{'offset':str(int(custom_config_len) + 28),
'pos':'16',
'bitlen':'8'},
'blk64k_erase_cmd':{'offset':str(int(custom_config_len) + 28),
'pos':'24',
'bitlen':'8'},
'write_enable_cmd':{'offset':str(int(custom_config_len) + 32),
'pos':'0',
'bitlen':'8'},
'page_prog_cmd':{'offset':str(int(custom_config_len) + 32),
'pos':'8',
'bitlen':'8'},
'qpage_prog_cmd':{'offset':str(int(custom_config_len) + 32),
'pos':'16',
'bitlen':'8'},
'qual_page_prog_addr_mode':{'offset':str(int(custom_config_len) + 32),
'pos':'24',
'bitlen':'8'},
'fast_read_cmd':{'offset':str(int(custom_config_len) + 36),
'pos':'0',
'bitlen':'8'},
'fast_read_dmy_clk':{'offset':str(int(custom_config_len) + 36),
'pos':'8',
'bitlen':'8'},
'qpi_fast_read_cmd':{'offset':str(int(custom_config_len) + 36),
'pos':'16',
'bitlen':'8'},
'qpi_fast_read_dmy_clk':{'offset':str(int(custom_config_len) + 36),
'pos':'24',
'bitlen':'8'},
'fast_read_do_cmd':{'offset':str(int(custom_config_len) + 40),
'pos':'0',
'bitlen':'8'},
'fast_read_do_dmy_clk':{'offset':str(int(custom_config_len) + 40),
'pos':'8',
'bitlen':'8'},
'fast_read_dio_cmd':{'offset':str(int(custom_config_len) + 40),
'pos':'16',
'bitlen':'8'},
'fast_read_dio_dmy_clk':{'offset':str(int(custom_config_len) + 40),
'pos':'24',
'bitlen':'8'},
'fast_read_qo_cmd':{'offset':str(int(custom_config_len) + 44),
'pos':'0',
'bitlen':'8'},
'fast_read_qo_dmy_clk':{'offset':str(int(custom_config_len) + 44),
'pos':'8',
'bitlen':'8'},
'fast_read_qio_cmd':{'offset':str(int(custom_config_len) + 44),
'pos':'16',
'bitlen':'8'},
'fast_read_qio_dmy_clk':{'offset':str(int(custom_config_len) + 44),
'pos':'24',
'bitlen':'8'},
'qpi_fast_read_qio_cmd':{'offset':str(int(custom_config_len) + 48),
'pos':'0',
'bitlen':'8'},
'qpi_fast_read_qio_dmy_clk':{'offset':str(int(custom_config_len) + 48),
'pos':'8',
'bitlen':'8'},
'qpi_page_prog_cmd':{'offset':str(int(custom_config_len) + 48),
'pos':'16',
'bitlen':'8'},
'write_vreg_enable_cmd':{'offset':str(int(custom_config_len) + 48),
'pos':'24',
'bitlen':'8'},
'wel_reg_index':{'offset':str(int(custom_config_len) + 52),
'pos':'0',
'bitlen':'8'},
'qe_reg_index':{'offset':str(int(custom_config_len) + 52),
'pos':'8',
'bitlen':'8'},
'busy_reg_index':{'offset':str(int(custom_config_len) + 52),
'pos':'16',
'bitlen':'8'},
'wel_bit_pos':{'offset':str(int(custom_config_len) + 52),
'pos':'24',
'bitlen':'8'},
'qe_bit_pos':{'offset':str(int(custom_config_len) + 56),
'pos':'0',
'bitlen':'8'},
'busy_bit_pos':{'offset':str(int(custom_config_len) + 56),
'pos':'8',
'bitlen':'8'},
'wel_reg_write_len':{'offset':str(int(custom_config_len) + 56),
'pos':'16',
'bitlen':'8'},
'wel_reg_read_len':{'offset':str(int(custom_config_len) + 56),
'pos':'24',
'bitlen':'8'},
'qe_reg_write_len':{'offset':str(int(custom_config_len) + 60),
'pos':'0',
'bitlen':'8'},
'qe_reg_read_len':{'offset':str(int(custom_config_len) + 60),
'pos':'8',
'bitlen':'8'},
'release_power_down':{'offset':str(int(custom_config_len) + 60),
'pos':'16',
'bitlen':'8'},
'busy_reg_read_len':{'offset':str(int(custom_config_len) + 60),
'pos':'24',
'bitlen':'8'},
'reg_read_cmd0':{'offset':str(int(custom_config_len) + 64),
'pos':'0',
'bitlen':'8'},
'reg_read_cmd1':{'offset':str(int(custom_config_len) + 64),
'pos':'8',
'bitlen':'8'},
'reg_write_cmd0':{'offset':str(int(custom_config_len) + 68),
'pos':'0',
'bitlen':'8'},
'reg_write_cmd1':{'offset':str(int(custom_config_len) + 68),
'pos':'8',
'bitlen':'8'},
'enter_qpi_cmd':{'offset':str(int(custom_config_len) + 72),
'pos':'0',
'bitlen':'8'},
'exit_qpi_cmd':{'offset':str(int(custom_config_len) + 72),
'pos':'8',
'bitlen':'8'},
'cont_read_code':{'offset':str(int(custom_config_len) + 72),
'pos':'16',
'bitlen':'8'},
'cont_read_exit_code':{'offset':str(int(custom_config_len) + 72),
'pos':'24',
'bitlen':'8'},
'burst_wrap_cmd':{'offset':str(int(custom_config_len) + 76),
'pos':'0',
'bitlen':'8'},
'burst_wrap_dmy_clk':{'offset':str(int(custom_config_len) + 76),
'pos':'8',
'bitlen':'8'},
'burst_wrap_data_mode':{'offset':str(int(custom_config_len) + 76),
'pos':'16',
'bitlen':'8'},
'burst_wrap_code':{'offset':str(int(custom_config_len) + 76),
'pos':'24',
'bitlen':'8'},
'de_burst_wrap_cmd':{'offset':str(int(custom_config_len) + 80),
'pos':'0',
'bitlen':'8'},
'de_burst_wrap_cmd_dmy_clk':{'offset':str(int(custom_config_len) + 80),
'pos':'8',
'bitlen':'8'},
'de_burst_wrap_code_mode':{'offset':str(int(custom_config_len) + 80),
'pos':'16',
'bitlen':'8'},
'de_burst_wrap_code':{'offset':str(int(custom_config_len) + 80),
'pos':'24',
'bitlen':'8'},
'sector_erase_time':{'offset':str(int(custom_config_len) + 84),
'pos':'0',
'bitlen':'16'},
'blk32k_erase_time':{'offset':str(int(custom_config_len) + 84),
'pos':'16',
'bitlen':'16'},
'blk64k_erase_time':{'offset':str(int(custom_config_len) + 88),
'pos':'0',
'bitlen':'16'},
'page_prog_time':{'offset':str(int(custom_config_len) + 88),
'pos':'16',
'bitlen':'16'},
'chip_erase_time':{'offset':str(int(custom_config_len) + 92),
'pos':'0',
'bitlen':'16'},
'power_down_delay':{'offset':str(int(custom_config_len) + 92),
'pos':'16',
'bitlen':'8'},
'qe_data':{'offset':str(int(custom_config_len) + 92),
'pos':'24',
'bitlen':'8'},
'flashcfg_crc32':{'offset':str(int(custom_config_len) + 96),
'pos':'0',
'bitlen':'32'},
'clkcfg_magic_code':{'offset':str(int(clock_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'xtal_type':{'offset':str(int(clock_start_pos) + 4),
'pos':'0',
'bitlen':'8'},
'mcu_clk':{'offset':str(int(clock_start_pos) + 4),
'pos':'8',
'bitlen':'8'},
'mcu_clk_div':{'offset':str(int(clock_start_pos) + 4),
'pos':'16',
'bitlen':'8'},
'mcu_bclk_div':{'offset':str(int(clock_start_pos) + 4),
'pos':'24',
'bitlen':'8'},
'mcu_pbclk_div':{'offset':str(int(clock_start_pos) + 8),
'pos':'0',
'bitlen':'8'},
'emi_clk':{'offset':str(int(clock_start_pos) + 8),
'pos':'8',
'bitlen':'8'},
'emi_clk_div':{'offset':str(int(clock_start_pos) + 8),
'pos':'16',
'bitlen':'8'},
'flash_clk_type':{'offset':str(int(clock_start_pos) + 8),
'pos':'24',
'bitlen':'8'},
'flash_clk_div':{'offset':str(int(clock_start_pos) + 12),
'pos':'0',
'bitlen':'8'},
'wifipll_pu':{'offset':str(int(clock_start_pos) + 12),
'pos':'8',
'bitlen':'8'},
'aupll_pu':{'offset':str(int(clock_start_pos) + 12),
'pos':'16',
'bitlen':'8'},
'rsvd0':{'offset':str(int(clock_start_pos) + 12),
'pos':'24',
'bitlen':'8'},
'clkcfg_crc32':{'offset':str(int(clock_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'sign':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'0',
'bitlen':'2'},
'encrypt_type':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'2',
'bitlen':'2'},
'key_sel':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'4',
'bitlen':'2'},
'xts_mode':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'6',
'bitlen':'1'},
'aes_region_lock':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'7',
'bitlen':'1'},
'no_segment':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'8',
'bitlen':'1'},
'boot2_enable':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'9',
'bitlen':'1'},
'boot2_rollback':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'10',
'bitlen':'1'},
'cpu_master_id':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'11',
'bitlen':'4'},
'notload_in_bootrom':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'15',
'bitlen':'1'},
'crc_ignore':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'16',
'bitlen':'1'},
'hash_ignore':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'17',
'bitlen':'1'},
'power_on_mm':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'18',
'bitlen':'1'},
'em_sel':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'19',
'bitlen':'3'},
'cmds_en':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'22',
'bitlen':'1'},
'cmds_wrap_mode':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'23',
'bitlen':'2'},
'cmds_wrap_len':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'25',
'bitlen':'4'},
'icache_invalid':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'29',
'bitlen':'1'},
'dcache_invalid':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'30',
'bitlen':'1'},
'fpga_halt_release':{'offset':str(int(bootcfg_start_pos) + 0),
'pos':'31',
'bitlen':'1'},
'group_image_offset':{'offset':str(int(bootcfg_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'aes_region_len':{'offset':str(int(bootcfg_start_pos) + 8),
'pos':'0',
'bitlen':'32'},
'img_len_cnt':{'offset':str(int(bootcfg_start_pos) + 12),
'pos':'0',
'bitlen':'32'},
'hash_0':{'offset':str(int(bootcfg_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'hash_1':{'offset':str(int(bootcfg_start_pos) + 20),
'pos':'0',
'bitlen':'32'},
'hash_2':{'offset':str(int(bootcfg_start_pos) + 24),
'pos':'0',
'bitlen':'32'},
'hash_3':{'offset':str(int(bootcfg_start_pos) + 28),
'pos':'0',
'bitlen':'32'},
'hash_4':{'offset':str(int(bootcfg_start_pos) + 32),
'pos':'0',
'bitlen':'32'},
'hash_5':{'offset':str(int(bootcfg_start_pos) + 36),
'pos':'0',
'bitlen':'32'},
'hash_6':{'offset':str(int(bootcfg_start_pos) + 40),
'pos':'0',
'bitlen':'32'},
'hash_7':{'offset':str(int(bootcfg_start_pos) + 44),
'pos':'0',
'bitlen':'32'},
'm0_config_enable':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'0',
'bitlen':'8'},
'm0_halt_cpu':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'8',
'bitlen':'8'},
'm0_cache_enable':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'16',
'bitlen':'1'},
'm0_cache_wa':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'17',
'bitlen':'1'},
'm0_cache_wb':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'18',
'bitlen':'1'},
'm0_cache_wt':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'19',
'bitlen':'1'},
'm0_cache_way_dis':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'20',
'bitlen':'4'},
'm0_reserved':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 0),
'pos':'24',
'bitlen':'8'},
'm0_image_address_offset':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 4),
'pos':'0',
'bitlen':'32'},
'm0_boot_entry':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 8),
'pos':'0',
'bitlen':'32'},
'm0_msp_val':{'offset':str(int(bootcpucfg_start_pos + bootcpucfg_len * bootcpucfg_m0_index) + 12),
'pos':'0',
'bitlen':'32'},
'boot2_pt_table_0':{'offset':str(int(boot2_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'boot2_pt_table_1':{'offset':str(int(boot2_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'flashCfgTableAddr':{'offset':str(int(flashcfg_table_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'flashCfgTableLen':{'offset':str(int(flashcfg_table_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'patch_read_addr0':{'offset':str(int(patch_on_read_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'patch_read_value0':{'offset':str(int(patch_on_read_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'patch_read_addr1':{'offset':str(int(patch_on_read_start_pos) + 8),
'pos':'0',
'bitlen':'32'},
'patch_read_value1':{'offset':str(int(patch_on_read_start_pos) + 12),
'pos':'0',
'bitlen':'32'},
'patch_read_addr2':{'offset':str(int(patch_on_read_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'patch_read_value2':{'offset':str(int(patch_on_read_start_pos) + 20),
'pos':'0',
'bitlen':'32'},
'patch_jump_addr0':{'offset':str(int(patch_on_jump_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'patch_jump_value0':{'offset':str(int(patch_on_jump_start_pos) + 4),
'pos':'0',
'bitlen':'32'},
'patch_jump_addr1':{'offset':str(int(patch_on_jump_start_pos) + 8),
'pos':'0',
'bitlen':'32'},
'patch_jump_value1':{'offset':str(int(patch_on_jump_start_pos) + 12),
'pos':'0',
'bitlen':'32'},
'patch_jump_addr2':{'offset':str(int(patch_on_jump_start_pos) + 16),
'pos':'0',
'bitlen':'32'},
'patch_jump_value2':{'offset':str(int(patch_on_jump_start_pos) + 20),
'pos':'0',
'bitlen':'32'},
'reserved':{'offset':str(int(rsvd_start_pos) + 0),
'pos':'0',
'bitlen':'32'},
'crc32':{'offset':str(int(crc32_start_pos) + 0),
'pos':'0',
'bitlen':'32'}}
# okay decompiling ./libs/base/wb03/bootheader_cfg_keys.pyc

View File

@ -0,0 +1,10 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/wb03/chiptype_patch.py
def img_load_create_predata_before_run_img():
return bytearray(0)
# okay decompiling ./libs/base/wb03/chiptype_patch.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/wb03/cklink_load_cfg.py
cklink_shake_hand_addr = '2204BBEC'
cklink_data_addr = '2204CC88'
cklink_load_addr = '22010000'
cklink_core_type = 'RISC-V'
cklink_set_tif = 0
cklink_run_addr = '22010000'
# okay decompiling ./libs/base/wb03/cklink_load_cfg.pyc

View File

@ -0,0 +1,147 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/wb03/flash_select_do.py
import os, csv
from re import I
import config as gol
from libs import bflb_utils
from libs.bflb_utils import app_path, conf_sign
from libs.bflb_configobj import BFConfigParser
from libs.base.wb03.bootheader_cfg_keys import bootheader_cfg_keys as flash_cfg_keys
def get_suitable_file_name(cfg_dir, flash_id):
conf_files = []
for home, dirs, files in os.walk(cfg_dir):
for filename in files:
if filename.split('_')[-1] == flash_id + '.conf':
conf_files.append(filename)
if len(conf_files) > 1:
bflb_utils.printf('Flash id duplicate and alternative is:')
for i in range(len(conf_files)):
tmp = conf_files[i].split('.')[0]
bflb_utils.printf('%d:%s' % (i + 1, tmp))
return conf_files[i]
if len(conf_files) == 1:
return conf_files[0]
return ''
def update_flash_cfg_do(chipname, chiptype, flash_id, file=None, create=False, section=None):
if conf_sign:
cfg_dir = app_path + '/utils/flash/' + chipname + '/'
else:
cfg_dir = app_path + '/utils/flash/' + gol.flash_dict[chipname] + '/'
conf_name = get_suitable_file_name(cfg_dir, flash_id)
value_key = []
if os.path.isfile(cfg_dir + conf_name) is False:
return False
fp = open(cfg_dir + conf_name, 'r')
for line in fp.readlines():
value = line.split('=')[0].strip()
if value == '[FLASH_CFG]':
continue
else:
value_key.append(value)
cfg1 = BFConfigParser()
cfg1.read(cfg_dir + conf_name)
cfg2 = BFConfigParser()
cfg2.read(file)
for i in range(len(value_key)):
if cfg1.has_option('FLASH_CFG', value_key[i]):
if cfg2.has_option(section, value_key[i]):
tmp_value = cfg1.get('FLASH_CFG', value_key[i])
bflb_utils.update_cfg(cfg2, section, value_key[i], tmp_value)
cfg2.write(file, 'w+')
bflb_utils.printf('Update flash cfg finished')
def get_supported_flash_do():
flash_type = []
return flash_type
def get_int_mask(pos, length):
ones = '11111111111111111111111111111111'
zeros = '00000000000000000000000000000000'
mask = ones[0:32 - pos - length] + zeros[0:length] + ones[0:pos]
return int(mask, 2)
def create_flashcfg_data_from_cfg(cfg_len, cfgfile):
section = 'FLASH_CFG'
cfg = BFConfigParser()
cfg.read(cfgfile)
data = bytearray(cfg_len)
minOffset = int(flash_cfg_keys.get('io_mode')['offset'], 10)
for key in cfg.options(section):
if flash_cfg_keys.get(key) == None:
bflb_utils.printf(key + ' not exist')
continue
else:
val = cfg.get(section, key)
if val.startswith('0x'):
val = int(val, 16)
else:
val = int(val, 10)
offset = int(flash_cfg_keys.get(key)['offset'], 10) - minOffset
pos = int(flash_cfg_keys.get(key)['pos'], 10)
bitlen = int(flash_cfg_keys.get(key)['bitlen'], 10)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = (oldval & get_int_mask(pos, bitlen)) + (val << pos)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
crcarray = bflb_utils.get_crc32_bytearray(data)
data = bflb_utils.int_to_4bytearray_l(1195787078) + data + crcarray
return data
def create_flashcfg_table(start_addr):
single_flashcfg_len = 92
flash_table_list = bytearray(0)
flash_table_data = bytearray(0)
table_file = os.path.join(app_path, 'utils', 'flash', 'wb03', 'flashcfg_list.csv')
with open(table_file, 'r', encoding='utf-8-sig') as csvfile:
table_list = []
cfgfile_list = []
reader = csv.DictReader(csvfile)
cnt = 0
for row in reader:
row_dict = {}
row_dict['jid'] = row.get('flashJedecID', '')
row_dict['cfgfile'] = row.get('configFile', '')
if row_dict['cfgfile'] not in cfgfile_list:
cfgfile_list.append(row_dict['cfgfile'])
else:
table_list.append(row_dict)
cnt += 1
table_list_len = 4 + cnt * 8 + 4
for cfgfile in cfgfile_list:
cfgfile = os.path.join(app_path, 'utils', 'flash', 'wb03', cfgfile)
data = create_flashcfg_data_from_cfg(single_flashcfg_len - 8, cfgfile)
flash_table_data += data
for dict in table_list:
flash_table_list += bflb_utils.int_to_4bytearray_b(int(dict['jid'] + '00', 16))
i = 0
offset = 0
for cfgfile in cfgfile_list:
if cfgfile == dict['cfgfile']:
offset = start_addr + table_list_len + single_flashcfg_len * i
break
else:
i += 1
flash_table_list += bflb_utils.int_to_4bytearray_l(offset)
crcarray = bflb_utils.get_crc32_bytearray(flash_table_list)
flash_table_list = bflb_utils.int_to_4bytearray_l(1196704582) + flash_table_list + crcarray
return (
flash_table_list, flash_table_data, len(flash_table_list))
# okay decompiling ./libs/base/wb03/flash_select_do.pyc

View File

@ -0,0 +1,766 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/wb03/img_create_do.py
import os, sys, hashlib, binascii, codecs, ecdsa
from CryptoPlus.Cipher import AES as AES_XTS
from libs import bflb_utils
from libs.bflb_utils import img_create_sha256_data, img_create_encrypt_data
from libs.bflb_configobj import BFConfigParser
from libs.base.wb03.flash_select_do import create_flashcfg_table
from libs.base.wb03.bootheader_cfg_keys import custom_config_len as custom_cfg_len
from libs.base.wb03.bootheader_cfg_keys import flashcfg_table_start_pos as flashcfg_table_start
from libs.base.wb03.bootheader_cfg_keys import bootcpucfg_start_pos as bootcpucfg_start
from libs.base.wb03.bootheader_cfg_keys import bootcpucfg_len as bootcpucfg_length
from libs.base.wb03.bootheader_cfg_keys import bootcpucfg_m0_index as bootcpucfg_m0_index_number
from libs.base.wb03.bootheader_cfg_keys import bootcfg_start_pos as bootcfg_start
from libs.base.wb03.bootheader_cfg_keys import bootheader_len as header_len
keyslot0 = 28
keyslot1 = keyslot0 + 16
keyslot2 = keyslot1 + 16
keyslot3 = keyslot2 + 16
keyslot3_end = keyslot3 + 16
keyslot4 = 128
keyslot5 = keyslot4 + 16
keyslot6 = keyslot5 + 16
keyslot7 = keyslot6 + 16
keyslot8 = keyslot7 + 16
keyslot9 = keyslot8 + 16
keyslot10 = keyslot9 + 16
keyslot10_end = keyslot10 + 16
keyslot11 = keyslot3_end + 16
keyslot11_end = keyslot11 + 16
wr_lock_boot_mode = 14
wr_lock_dbg_pwd = 15
wr_lock_wifi_mac = 16
wr_lock_key_slot_0 = 17
wr_lock_key_slot_1 = 18
wr_lock_key_slot_2 = 19
wr_lock_key_slot_3 = 20
wr_lock_sw_usage_0 = 21
wr_lock_sw_usage_1 = 22
wr_lock_sw_usage_2 = 23
wr_lock_sw_usage_3 = 24
wr_lock_key_slot_11 = 25
rd_lock_dbg_pwd = 26
rd_lock_key_slot_0 = 27
rd_lock_key_slot_1 = 28
rd_lock_key_slot_2 = 29
rd_lock_key_slot_3 = 30
rd_lock_key_slot_11 = 31
wr_lock_key_slot_4 = 15
wr_lock_key_slot_5 = 16
wr_lock_key_slot_6 = 17
wr_lock_key_slot_7 = 18
wr_lock_key_slot_8 = 19
wr_lock_key_slot_9 = 20
wr_lock_key_slot_10 = 21
rd_lock_key_slot_4 = 25
rd_lock_key_slot_5 = 26
rd_lock_key_slot_6 = 27
rd_lock_key_slot_7 = 28
rd_lock_key_slot_8 = 29
rd_lock_key_slot_9 = 30
rd_lock_key_slot_10 = 31
def bytearray_data_merge(data1, data2, len):
for i in range(len):
data1[i] |= data2[i]
return data1
def img_update_efuse_group0(cfg, sign, pk_hash, flash_encryp_type, flash_key, sec_eng_key_sel, sec_eng_key, security=False):
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_file'), 'rb')
efuse_data = bytearray(fp.read()) + bytearray(0)
fp.close()
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_mask_file'), 'rb')
efuse_mask_data = bytearray(fp.read()) + bytearray(0)
fp.close()
mask_4bytes = bytearray.fromhex('FFFFFFFF')
if flash_encryp_type >= 3:
efuse_data[0] |= 3
else:
efuse_data[0] |= flash_encryp_type
if sign > 0:
efuse_data[92] |= sign << 7
efuse_mask_data[92] |= 255
if flash_encryp_type > 0:
efuse_data[0] |= 48
efuse_mask_data[0] |= 255
rw_lock0 = 0
rw_lock1 = 0
if pk_hash is not None:
efuse_data[keyslot0:keyslot2] = pk_hash
efuse_mask_data[keyslot0:keyslot2] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_0
rw_lock0 |= 1 << wr_lock_key_slot_1
if flash_key is not None:
if flash_encryp_type == 1:
efuse_data[keyslot2:keyslot3] = flash_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
else:
if flash_encryp_type == 2:
efuse_data[keyslot2:keyslot3_end] = flash_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
else:
if flash_encryp_type == 3:
efuse_data[keyslot2:keyslot3_end] = flash_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
else:
if flash_encryp_type == 4 or flash_encryp_type == 5 or flash_encryp_type == 6:
efuse_data[keyslot2:keyslot3_end] = flash_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
if sec_eng_key is not None:
if flash_encryp_type == 0:
if sec_eng_key_sel == 0:
efuse_data[keyslot2:keyslot3] = sec_eng_key[16:32]
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 1:
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[16:32]
efuse_data[keyslot4:keyslot5] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot3_end] = mask_4bytes * 4
efuse_mask_data[keyslot4:keyslot5] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock0 |= 1 << rd_lock_key_slot_3
rw_lock1 |= 1 << rd_lock_key_slot_4
if sec_eng_key_sel == 2:
efuse_data[keyslot4:keyslot5] = sec_eng_key[16:32]
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot5] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock0 |= 1 << rd_lock_key_slot_2
if sec_eng_key_sel == 3:
efuse_data[keyslot4:keyslot5] = sec_eng_key[16:32]
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot5] = mask_4bytes * 8
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock1 |= 1 << rd_lock_key_slot_4
rw_lock0 |= 1 << rd_lock_key_slot_2
if flash_encryp_type == 1:
if sec_eng_key_sel == 0:
efuse_data[keyslot5:keyslot6] = sec_eng_key[0:16]
efuse_mask_data[keyslot5:keyslot6] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_5
rw_lock1 |= 1 << rd_lock_key_slot_5
if sec_eng_key_sel == 1:
efuse_data[keyslot4:keyslot5] = sec_eng_key[0:16]
efuse_mask_data[keyslot4:keyslot5] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_4
rw_lock1 |= 1 << rd_lock_key_slot_4
if sec_eng_key_sel == 2:
if flash_key is not None:
pass
else:
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot3:keyslot3_end] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 3:
if flash_key is not None:
pass
else:
efuse_data[keyslot2:keyslot3] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3] = mask_4bytes * 4
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
if flash_encryp_type == 2 or flash_encryp_type == 3 or flash_encryp_type == 4 or flash_encryp_type == 5 or flash_encryp_type == 6:
if sec_eng_key_sel == 0:
efuse_data[keyslot6:keyslot7] = sec_eng_key[16:32]
efuse_data[keyslot10:keyslot10_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot6:keyslot7] = mask_4bytes * 4
efuse_mask_data[keyslot10:keyslot10_end] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_6
rw_lock1 |= 1 << wr_lock_key_slot_10
rw_lock1 |= 1 << rd_lock_key_slot_6
rw_lock1 |= 1 << rd_lock_key_slot_10
if sec_eng_key_sel == 1:
efuse_data[keyslot10:keyslot10_end] = sec_eng_key[16:32]
efuse_data[keyslot6:keyslot7] = sec_eng_key[0:16]
efuse_mask_data[keyslot6:keyslot7] = mask_4bytes * 4
efuse_mask_data[keyslot10:keyslot10_end] = mask_4bytes * 4
rw_lock1 |= 1 << wr_lock_key_slot_6
rw_lock1 |= 1 << wr_lock_key_slot_10
rw_lock1 |= 1 << rd_lock_key_slot_6
rw_lock1 |= 1 << rd_lock_key_slot_10
if sec_eng_key_sel == 2:
if flash_key is not None:
pass
else:
efuse_data[keyslot2:keyslot3] = sec_eng_key[16:32]
efuse_data[keyslot3:keyslot3_end] = sec_eng_key[0:16]
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
if sec_eng_key_sel == 3:
if flash_key is not None:
pass
else:
efuse_data[keyslot2:keyslot3_end] = sec_eng_key
efuse_mask_data[keyslot2:keyslot3_end] = mask_4bytes * 8
rw_lock0 |= 1 << wr_lock_key_slot_2
rw_lock0 |= 1 << rd_lock_key_slot_2
rw_lock0 |= 1 << wr_lock_key_slot_3
rw_lock0 |= 1 << rd_lock_key_slot_3
efuse_data[124:128] = bytearray_data_merge(efuse_data[124:128], bflb_utils.int_to_4bytearray_l(rw_lock0), 4)
efuse_mask_data[124:128] = bytearray_data_merge(efuse_mask_data[124:128], bflb_utils.int_to_4bytearray_l(rw_lock0), 4)
efuse_data[252:256] = bytearray_data_merge(efuse_data[252:256], bflb_utils.int_to_4bytearray_l(rw_lock1), 4)
efuse_mask_data[252:256] = bytearray_data_merge(efuse_mask_data[252:256], bflb_utils.int_to_4bytearray_l(rw_lock1), 4)
if security is True:
bflb_utils.printf('Encrypt efuse data')
security_key, security_iv = bflb_utils.get_security_key()
efuse_data = img_create_encrypt_data(efuse_data, security_key, security_iv, 0)
efuse_data = bytearray(4096) + efuse_data
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_file'), 'wb+')
fp.write(efuse_data)
fp.close()
fp = open(cfg.get('Img_Group0_Cfg', 'efuse_mask_file'), 'wb+')
fp.write(efuse_mask_data)
fp.close()
def img_create_get_sign_encrypt_info(bootheader_data):
sign = bootheader_data[bootcfg_start] & 3
encrypt = bootheader_data[bootcfg_start] >> 2 & 3
key_sel = bootheader_data[bootcfg_start] >> 4 & 3
xts_mode = bootheader_data[bootcfg_start] >> 6 & 1
return (
sign, encrypt, key_sel, xts_mode)
def img_create_get_img_start_addr(bootheader_data):
bootentry = []
bootentry.append(bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(bootheader_data[bootcpucfg_start + bootcpucfg_length * bootcpucfg_m0_index_number + 16:bootcpucfg_start + bootcpucfg_length * bootcpucfg_m0_index_number + 16 + 4])))
return bootentry
def img_create_flash_default_data(length):
datas = bytearray(length)
for i in range(length):
datas[i] = 255
return datas
def img_get_file_data(files):
datas = []
for file in files:
if file == 'UNUSED':
datas.append(bytearray(0))
continue
else:
with open(file, 'rb') as fp:
data = fp.read()
datas.append(data)
return datas
def img_get_largest_addr(addrs, files):
min = 67108863
maxlen = 0
datalen = 0
for i in range(len(addrs)):
if files[i] == 'UNUSED':
continue
else:
addr = addrs[i] & 67108863
if addr >= maxlen:
maxlen = addr
datalen = os.path.getsize(files[i])
if addr <= min:
min = addr
if maxlen == 0:
if datalen == 0:
return (0, 0)
return (
maxlen + datalen - min, min)
def img_get_one_group_img(d_addrs, d_files):
whole_img_len, min = img_get_largest_addr(d_addrs, d_files)
whole_img_len &= 67108863
whole_img_data = img_create_flash_default_data(whole_img_len)
filedatas = img_get_file_data(d_files)
for i in range(len(d_addrs)):
if d_files[i] == 'UNUSED':
continue
else:
start_addr = d_addrs[i]
start_addr &= 67108863
start_addr -= min
whole_img_data[start_addr:start_addr + len(filedatas[i])] = filedatas[i]
return whole_img_data
def img_create_get_hash_ignore(bootheader_data):
return bootheader_data[bootcfg_start + 2] >> 1 & 1
def img_create_get_crc_ignore(bootheader_data):
return bootheader_data[bootcfg_start + 2] & 1
def img_create_update_bootheader_if(bootheader_data, hash, seg_cnt):
bootheader_data[bootcfg_start + 12:bootcfg_start + 12 + 4] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign = bootheader_data[bootcfg_start] & 3
encrypt = bootheader_data[bootcfg_start] >> 2 & 3
key_sel = bootheader_data[bootcfg_start] >> 4 & 3
xts_mode = bootheader_data[bootcfg_start] >> 6 & 1
if bootheader_data[bootcfg_start + 2] >> 1 & 1 == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[bootcfg_start + 16:bootcfg_start + 16 + 32] = hash
if bootheader_data[bootcfg_start + 2] & 1 == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[custom_cfg_len:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data
def img_create_update_custom_bootheader(bootheader_data, seg_cnt, hash, signature, pk_data, aesiv_data):
bootheader_data[20:24] = bflb_utils.int_to_4bytearray_l(seg_cnt)
if hash != bytearray(0):
bootheader_data[28:60] = hash
if signature != bytearray(0):
bootheader_data[60:124] = signature[4:68]
if pk_data != bytearray(0):
bootheader_data[124:188] = pk_data[0:64]
if aesiv_data != bytearray(0):
bootheader_data[188:204] = aesiv_data[0:16]
bootheader_data[4:8] = bflb_utils.get_crc32_bytearray(bootheader_data[8:custom_cfg_len - 4])
return bootheader_data[0:header_len]
def img_create_update_bootheader(bootheader_data, hash, seg_cnt, flashcfg_table_addr, flashcfg_table_len):
bootheader_data[flashcfg_table_start:flashcfg_table_start + 4] = bflb_utils.int_to_4bytearray_l(flashcfg_table_addr)
bootheader_data[flashcfg_table_start + 4:flashcfg_table_start + 8] = bflb_utils.int_to_4bytearray_l(flashcfg_table_len)
bootheader_data[bootcfg_start + 12:bootcfg_start + 12 + 4] = bflb_utils.int_to_4bytearray_l(seg_cnt)
sign, encrypt, key_sel, xts_mode = img_create_get_sign_encrypt_info(bootheader_data)
if img_create_get_hash_ignore(bootheader_data) == 1 and sign == 0:
bflb_utils.printf('Hash ignored')
else:
bootheader_data[bootcfg_start + 16:bootcfg_start + 16 + 32] = hash
if img_create_get_crc_ignore(bootheader_data) == 1:
bflb_utils.printf('Header crc ignored')
else:
hd_crcarray = bflb_utils.get_crc32_bytearray(bootheader_data[custom_cfg_len:header_len - 4])
bootheader_data[header_len - 4:header_len] = hd_crcarray
bflb_utils.printf('Header crc: ', binascii.hexlify(hd_crcarray))
return bootheader_data[0:header_len]
def img_create_update_segheader(segheader, segdatalen, segdatacrc):
segheader[4:8] = segdatalen
segheader[8:12] = segdatacrc
return segheader
def reverse_str_data_unit_number(str_data_unit_number):
"""
high position low data
data unit number:00000280
storage format: 80020000
"""
reverse_str = ''
if len(str_data_unit_number) == 8:
str_part1 = str_data_unit_number[0:2]
str_part2 = str_data_unit_number[2:4]
str_part3 = str_data_unit_number[4:6]
str_part4 = str_data_unit_number[6:8]
reverse_str = str_part4 + str_part3 + str_part2 + str_part1
return reverse_str
def reverse_iv(need_reverse_iv_bytearray):
temp_reverse_iv_bytearray = binascii.hexlify(need_reverse_iv_bytearray).decode()
if temp_reverse_iv_bytearray[24:32] != '00000000':
bflb_utils.printf('The lower 4 bytes of IV should be set 0, if set IV is less than 16 bytes, make up 0 for the low 4 bytes of IV ')
sys.exit()
reverse_iv_bytearray = '00000000' + temp_reverse_iv_bytearray[0:24]
return reverse_iv_bytearray
def img_create_encrypt_data_xts(data_bytearray, key_bytearray, iv_bytearray, encrypt):
counter = binascii.hexlify(iv_bytearray[4:16]).decode()
data_unit_number = 0
key = (
key_bytearray[0:16], key_bytearray[16:32])
if encrypt == 2 or encrypt == 3:
key = (
key_bytearray, key_bytearray)
cipher = AES_XTS.new(key, AES_XTS.MODE_XTS)
total_len = len(data_bytearray)
ciphertext = bytearray(0)
deal_len = 0
while deal_len < total_len:
data_unit_number = str(hex(data_unit_number)).replace('0x', '')
data_unit_number_to_str = str(data_unit_number)
right_justify_str = data_unit_number_to_str.rjust(8, '0')
reverse_data_unit_number_str = reverse_str_data_unit_number(right_justify_str)
tweak = reverse_data_unit_number_str + counter
tweak = bflb_utils.hexstr_to_bytearray('0' * (32 - len(tweak)) + tweak)
if 32 + deal_len <= total_len:
cur_block = data_bytearray[0 + deal_len:32 + deal_len]
ciphertext += cipher.encrypt(cur_block, tweak)
else:
cur_block = data_bytearray[0 + deal_len:16 + deal_len] + bytearray(16)
ciphertext += cipher.encrypt(cur_block, tweak)[0:16]
deal_len += 32
data_unit_number = int(data_unit_number, 16)
data_unit_number += 1
return ciphertext
def img_create_sign_data(data_bytearray, privatekey_file_uecc, publickey_file):
sk = ecdsa.SigningKey.from_pem(open(privatekey_file_uecc).read())
vk = ecdsa.VerifyingKey.from_pem(open(publickey_file).read())
pk_data = vk.to_string()
bflb_utils.printf('Private key: ', binascii.hexlify(sk.to_string()))
bflb_utils.printf('Public key: ', binascii.hexlify(pk_data))
pk_hash = img_create_sha256_data(pk_data)
bflb_utils.printf('Public key hash=', binascii.hexlify(pk_hash))
signature = sk.sign(data_bytearray, hashfunc=(hashlib.sha256), sigencode=(ecdsa.util.sigencode_string))
bflb_utils.printf('Signature=', binascii.hexlify(signature))
len_array = bflb_utils.int_to_4bytearray_l(len(signature))
sig_field = len_array + signature
crcarray = bflb_utils.get_crc32_bytearray(sig_field)
return (
pk_data, pk_hash, sig_field + crcarray)
def img_create_read_file_append_crc(file, crc):
fp = open(file, 'rb')
read_data = bytearray(fp.read())
crcarray = bytearray(0)
if crc:
crcarray = bflb_utils.get_crc32_bytearray(read_data)
fp.close()
return read_data + crcarray
def encrypt_loader_bin_do(file, sign, encrypt, temp_encrypt_key, temp_encrypt_iv, publickey_file, privatekey_file):
if encrypt != 0 or sign != 0:
encrypt_key = bytearray(0)
encrypt_iv = bytearray(0)
load_helper_bin_header = bytearray(0)
load_helper_bin_body = bytearray(0)
offset = bootcfg_start
sign_pos = 0
encrypt_type_pos = 2
pk_data = bytearray(0)
signature = bytearray(0)
aesiv_data = bytearray(0)
data_tohash = bytearray(0)
with open(file, 'rb') as fp:
load_helper_bin = fp.read()
load_helper_bin_header = load_helper_bin[0:header_len]
load_helper_bin_body = load_helper_bin[header_len:]
if load_helper_bin_header != bytearray(0):
if load_helper_bin_body != bytearray(0):
load_helper_bin_body = bflb_utils.add_to_16(load_helper_bin_body)
if encrypt != 0:
encrypt_key = bflb_utils.hexstr_to_bytearray(temp_encrypt_key)
encrypt_iv = bflb_utils.hexstr_to_bytearray(temp_encrypt_iv)
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
data_tohash = data_tohash + aesiv_data
load_helper_bin_body_encrypt = bflb_utils.img_create_encrypt_data(load_helper_bin_body, encrypt_key, encrypt_iv, 0)
else:
load_helper_bin_body_encrypt = load_helper_bin_body
data = bytearray(load_helper_bin_header)
oldval = bflb_utils.bytearray_to_int(bflb_utils.bytearray_reverse(data[offset:offset + 4]))
newval = oldval
if encrypt != 0:
newval = newval | 1 << encrypt_type_pos
if sign != 0:
newval = newval | 1 << sign_pos
data_tohash += load_helper_bin_body_encrypt
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
data[offset:offset + 4] = bflb_utils.int_to_4bytearray_l(newval)
load_helper_bin_header = data
load_helper_bin_encrypt = load_helper_bin_header + pk_data + signature + aesiv_data + load_helper_bin_body_encrypt
hashfun = hashlib.sha256()
hashfun.update(load_helper_bin_body_encrypt)
hash = bflb_utils.hexstr_to_bytearray(hashfun.hexdigest())
load_helper_bin_data = bytearray(load_helper_bin_encrypt)
load_helper_bin_encrypt = img_create_update_bootheader_if(load_helper_bin_data, hash, 1)
return (
True, load_helper_bin_encrypt)
return (False, None)
def img_creat_process(group_type, flash_img, cfg, security=False):
encrypt_blk_size = 16
padding = bytearray(encrypt_blk_size)
data_tohash = bytearray(0)
cfg_section = ''
img_update_efuse_fun = img_update_efuse_group0
cfg_section = 'Img_Group0_Cfg'
segheader_file = []
if flash_img == 0:
for files in cfg.get(cfg_section, 'segheader_file').split(' '):
segheader_file.append(str(files))
segdata_file = []
for files in cfg.get(cfg_section, 'segdata_file').split('|'):
if files:
segdata_file.append(str(files))
boot_header_file = cfg.get(cfg_section, 'boot_header_file')
bootheader_data = img_create_read_file_append_crc(boot_header_file, 0)
encrypt = 0
sign, encrypt, key_sel, xts_mode = img_create_get_sign_encrypt_info(bootheader_data)
boot_entry = img_create_get_img_start_addr(bootheader_data)
aesiv_data = bytearray(0)
pk_data = bytearray(0)
publickey_file = ''
privatekey_file_uecc = ''
if sign != 0:
bflb_utils.printf('Image need sign')
publickey_file = cfg.get(cfg_section, 'publickey_file')
privatekey_file_uecc = cfg.get(cfg_section, 'privatekey_file_uecc')
if encrypt != 0:
bflb_utils.printf('Image need encrypt ', encrypt)
if xts_mode == 1:
bflb_utils.printf('Enable xts mode')
encrypt_key_org = bflb_utils.hexstr_to_bytearray(cfg.get(cfg_section, 'aes_key_org'))
if encrypt == 1:
if xts_mode == 1:
encrypt_key = encrypt_key_org[0:32]
else:
encrypt_key = encrypt_key_org[0:16]
else:
if encrypt == 2:
if xts_mode == 1:
encrypt_key = encrypt_key_org[0:32]
else:
encrypt_key = encrypt_key_org[0:32]
else:
if encrypt == 3:
if xts_mode == 1:
encrypt_key = encrypt_key_org[0:24]
else:
encrypt_key = encrypt_key_org[0:24]
bflb_utils.printf('Key= ', binascii.hexlify(encrypt_key))
iv_value = cfg.get(cfg_section, 'aes_iv')
if xts_mode == 1:
iv_value = iv_value[24:32] + iv_value[:24]
encrypt_iv = bflb_utils.hexstr_to_bytearray(iv_value)
iv_crcarray = bflb_utils.get_crc32_bytearray(encrypt_iv)
aesiv_data = encrypt_iv + iv_crcarray
seg_cnt = len(segheader_file)
segdata_cnt = len(segdata_file)
if flash_img == 0:
if seg_cnt != segdata_cnt:
bflb_utils.printf('Segheader count and segdata count not match')
return (
'FAIL', data_tohash)
data_toencrypt = bytearray(0)
if flash_img == 0:
i = 0
seg_header_list = []
seg_data_list = []
while i < seg_cnt:
seg_data = bytearray(0)
if segdata_file[i] != 'UNUSED':
seg_data = img_create_read_file_append_crc(segdata_file[i], 0)
else:
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
segdata_crcarray = bflb_utils.get_crc32_bytearray(seg_data)
seg_data_list.append(seg_data)
seg_header = img_create_read_file_append_crc(segheader_file[i], 0)
seg_header = img_create_update_segheader(seg_header, bflb_utils.int_to_4bytearray_l(len(seg_data)), segdata_crcarray)
segheader_crcarray = bflb_utils.get_crc32_bytearray(seg_header)
seg_header = seg_header + segheader_crcarray
seg_header_list.append(seg_header)
i = i + 1
i = 0
cnt = 0
while i < seg_cnt:
if seg_header_list[i][4:8] != bytearray(4):
data_toencrypt += seg_header_list[i]
data_toencrypt += seg_data_list[i]
cnt += 1
else:
i += 1
seg_cnt = cnt
else:
seg_data = img_get_one_group_img(boot_entry, segdata_file)
padding_size = 0
if len(seg_data) % encrypt_blk_size != 0:
padding_size = encrypt_blk_size - len(seg_data) % encrypt_blk_size
seg_data += padding[0:padding_size]
data_toencrypt += seg_data
seg_cnt = len(data_toencrypt)
if encrypt != 0:
unencrypt_mfg_data = bytearray(0)
if seg_cnt >= 8192:
if data_toencrypt[4096:4100] == bytearray('0mfg'.encode('utf-8')):
unencrypt_mfg_data = data_toencrypt[4096:8192]
if xts_mode != 0:
data_toencrypt = img_create_encrypt_data_xts(data_toencrypt, encrypt_key, encrypt_iv, encrypt)
else:
data_toencrypt = img_create_encrypt_data(data_toencrypt, encrypt_key, encrypt_iv, flash_img)
if unencrypt_mfg_data != bytearray(0):
data_toencrypt = data_toencrypt[0:4096] + unencrypt_mfg_data + data_toencrypt[8192:]
fw_data = bytearray(0)
data_tohash += data_toencrypt
fw_data = data_toencrypt
hash = img_create_sha256_data(data_tohash)
bflb_utils.printf('Image hash is ', binascii.hexlify(hash))
signature = bytearray(0)
pk_hash = None
if sign == 1:
pk_data, pk_hash, signature = img_create_sign_data(data_tohash, privatekey_file_uecc, publickey_file)
pk_data = pk_data + bflb_utils.get_crc32_bytearray(pk_data)
flashCfgAddr = len(bootheader_data + pk_data + signature + aesiv_data)
flashCfgListLen = 0
flashCfgList = bytearray(0)
flashCfgTable = bytearray(0)
if flash_img == 1:
if bootheader_data[233:234] == b'\xff':
flashCfgList, flashCfgTable, flashCfgListLen = create_flashcfg_table(flashCfgAddr)
bootheader_data = img_create_update_custom_bootheader(bootheader_data, seg_cnt, hash, signature, pk_data, aesiv_data)
bootheader_data = img_create_update_bootheader(bootheader_data, hash, seg_cnt, flashCfgAddr, flashCfgListLen)
if flash_img == 1:
bflb_utils.printf('Write flash img')
bootinfo_file_name = cfg.get(cfg_section, 'bootinfo_file')
fp = open(bootinfo_file_name, 'wb+')
bootinfo = bootheader_data + pk_data + signature + aesiv_data + flashCfgList + flashCfgTable
fp.write(bootinfo)
fp.close()
fw_file_name = cfg.get(cfg_section, 'img_file')
fp = open(fw_file_name, 'wb+')
fp.write(fw_data)
fp.close()
fw_data_hash = img_create_sha256_data(fw_data)
fp = open(fw_file_name.replace('.bin', '_withhash.bin'), 'wb+')
fp.write(fw_data + fw_data_hash)
fp.close()
if encrypt != 0:
flash_encrypt_type = 0
if encrypt == 1:
flash_encrypt_type = 1
if encrypt == 2:
flash_encrypt_type = 3
if encrypt == 3:
flash_encrypt_type = 2
if xts_mode == 1:
flash_encrypt_type += 3
img_update_efuse_fun(cfg, sign, pk_hash, flash_encrypt_type, encrypt_key + bytearray(32 - len(encrypt_key)), key_sel, None, security)
else:
img_update_efuse_fun(cfg, sign, pk_hash, encrypt, None, key_sel, None, security)
else:
bflb_utils.printf('Write if img')
whole_img_file_name = cfg.get(cfg_section, 'whole_img_file')
fp = open(whole_img_file_name, 'wb+')
img_data = bootheader_data + pk_data + signature + aesiv_data + fw_data
fp.write(img_data)
fp.close()
if encrypt != 0:
if_encrypt_type = 0
if encrypt == 1:
if_encrypt_type = 1
if encrypt == 2:
if_encrypt_type = 3
if encrypt == 3:
if_encrypt_type = 2
if xts_mode == 1:
if_encrypt_type += 3
img_update_efuse_fun(cfg, sign, pk_hash, if_encrypt_type, None, key_sel, encrypt_key + bytearray(32 - len(encrypt_key)), security)
else:
img_update_efuse_fun(cfg, sign, pk_hash, 0, None, key_sel, bytearray(32), security)
return (
'OK', data_tohash)
def img_create_do(args, img_dir_path=None, config_file=None):
bflb_utils.printf('Image create path: ', img_dir_path)
if config_file is None:
config_file = img_dir_path + '/img_create_cfg.ini'
bflb_utils.printf('Config file: ', config_file)
cfg = BFConfigParser()
cfg.read(config_file)
group_type = 'all'
img_type = 'media'
signer = 'none'
security = False
data_tohash = bytearray(0)
try:
if args.image:
img_type = args.image
if args.group:
group_type = args.group
if args.signer:
signer = args.signer
if args.security:
security = args.security == 'efuse'
except Exception as e:
try:
bflb_utils.printf(e)
finally:
e = None
del e
if img_type == 'media':
flash_img = 1
else:
flash_img = 0
ret0 = ret1 = 'OK'
if group_type == 'group0' or group_type == 'all':
ret0, data_tohash0 = img_creat_process('group0', flash_img, cfg, security)
else:
img_creat_process('', flash_img, cfg, security)
if ret0 != 'OK':
bflb_utils.printf('Fail to create group0 images!')
return
if ret1 != 'OK':
bflb_utils.printf('Fail to create group1 images!')
def create_sp_media_image(config, cpu_type=None, security=False):
bflb_utils.printf('========= sp image create =========')
cfg = BFConfigParser()
cfg.read(config)
img_creat_process('group0', 1, cfg, security)
if __name__ == '__main__':
data_bytearray = codecs.decode('42464E500100000046434647040101036699FF039F00B7E904EF0001C72052D8060232000B010B013B01BB006B01EB02EB02025000010001010002010101AB01053500000131000038FF20FF77030240770302F02C01B004B0040500FFFF030036C3DD9E5043464704040001010105000101050000010101A612AC86000144650020000000000000503100007A6345494BCABEC7307FD8F8396729EB67DDC8C63B7AD69B797B08564E982A8701000000000000000000000000000000000000D80000000000010000000000000000000000200100000001D80000000000010000000000000000000000200200000002580000000000010000000000000000000000200300000003580000000000010000D0C57503C09E750300200400000004580000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000935F92BB', 'hex')
key_bytearray = codecs.decode('fffefdfcfbfaf9f8f7f6f5f4f3f2f1f0000102030405060708090a0b0c0d0e0f', 'hex')
need_reverse_iv_bytearray = codecs.decode('01000000000000000000000000000000', 'hex')
iv_bytearray = codecs.decode(reverse_iv(need_reverse_iv_bytearray), 'hex')
img_create_encrypt_data_xts(data_bytearray, key_bytearray, iv_bytearray, 0)
# okay decompiling ./libs/base/wb03/img_create_do.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/wb03/jlink_load_cfg.py
jlink_shake_hand_addr = '4201BFF0'
jlink_data_addr = '4201C000'
jlink_load_addr = '22010000'
jlink_core_type = 'RISC-V'
jlink_set_tif = 0
jlink_run_addr = '22010000'
# okay decompiling ./libs/base/wb03/jlink_load_cfg.pyc

View File

@ -0,0 +1,12 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: libs/base/wb03/openocd_load_cfg.py
openocd_shake_hand_addr = '4201BFF0'
openocd_data_addr = '4201C000'
openocd_load_addr = '22010000'
openocd_core_type = 'RISC-V'
openocd_set_tif = 0
openocd_run_addr = '22010000'
# okay decompiling ./libs/base/wb03/openocd_load_cfg.pyc

View File

@ -1,21 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/__init__.py
__version__ = '0.5.0'
__title__ = 'pylink'
__author__ = 'Square Embedded Software Team'
__author_email__ = 'esw-team@squareup.com'
__copyright__ = 'Copyright 2017 Square, Inc.'
__license__ = 'Apache 2.0'
__url__ = 'http://www.github.com/Square/pylink'
__description__ = 'Python interface for SEGGER J-Link.'
__long_description__ = "This module provides a Python implementation of the\nJ-Link SDK by leveraging the SDK's DLL.\n"
from .enums import *
from .errors import *
from .jlink import *
from .library import *
from .structs import *
from .unlockers import *
# okay decompiling ./pylink/__init__.pyc

View File

@ -1,57 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/binpacker.py
import ctypes, math
BITS_PER_BYTE = 8
def pack_size(value):
"""Returns the number of bytes required to represent a given value.
Args:
value (int): the natural number whose size to get
Returns:
The minimal number of bytes required to represent the given integer.
Raises:
ValueError: if ``value < 0``.
TypeError: if ``value`` is not a number.
"""
if value == 0:
return 1
if value < 0:
raise ValueError('Expected non-negative integer.')
return int(math.log(value, 256)) + 1
def pack(value, nbits=None):
"""Packs a given value into an array of 8-bit unsigned integers.
If ``nbits`` is not present, calculates the minimal number of bits required
to represent the given ``value``. The result is little endian.
Args:
value (int): the integer value to pack
nbits (int): optional number of bits to use to represent the value
Returns:
An array of ``ctypes.c_uint8`` representing the packed ``value``.
Raises:
ValueError: if ``value < 0`` and ``nbits`` is ``None`` or ``nbits <= 0``.
TypeError: if ``nbits`` or ``value`` are not numbers.
"""
if nbits is None:
nbits = pack_size(value) * BITS_PER_BYTE
else:
if nbits <= 0:
raise ValueError('Given number of bits must be greater than 0.')
buf_size = int(math.ceil(nbits / float(BITS_PER_BYTE)))
buf = (ctypes.c_uint8 * buf_size)()
for idx, _ in enumerate(buf):
buf[idx] = value >> idx * BITS_PER_BYTE & 255
return buf
# okay decompiling ./pylink/binpacker.pyc

View File

@ -1,52 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/decorators.py
from . import threads
import functools
def async_decorator(func):
"""Asynchronous function decorator. Interprets the function as being
asynchronous, so returns a function that will handle calling the
Function asynchronously.
Args:
func (function): function to be called asynchronously
Returns:
The wrapped function.
Raises:
AttributeError: if ``func`` is not callable
"""
@functools.wraps(func)
def async_wrapper(*args, **kwargs):
if not ('callback' not in kwargs or kwargs['callback']):
return func(*args, **kwargs)
callback = kwargs.pop('callback')
if not callable(callback):
raise TypeError("Expected 'callback' is not callable.")
def thread_func(*args, **kwargs):
exception, res = (None, None)
try:
res = func(*args, **kwargs)
except Exception as e:
try:
exception = e
finally:
e = None
del e
return callback(exception, res)
thread = threads.ThreadReturn(target=thread_func, args=args,
kwargs=kwargs)
thread.daemon = True
thread.start()
return thread
return async_wrapper
# okay decompiling ./pylink/decorators.pyc

View File

@ -1,528 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/enums.py
import ctypes
class JLinkGlobalErrors(object):
__doc__ = 'Enumeration for the error codes which any J-Link SDK DLL API-function\n can have as a return value.'
UNSPECIFIED_ERROR = -1
EMU_NO_CONNECTION = -256
EMU_COMM_ERROR = -257
DLL_NOT_OPEN = -258
VCC_FAILURE = -259
INVALID_HANDLE = -260
NO_CPU_FOUND = -261
EMU_FEATURE_UNSUPPORTED = -262
EMU_NO_MEMORY = -263
TIF_STATUS_ERROR = -264
FLASH_PROG_COMPARE_FAILED = -265
FLASH_PROG_PROGRAM_FAILED = -266
FLASH_PROG_VERIFY_FAILED = -267
OPEN_FILE_FAILED = -268
UNKNOWN_FILE_FORMAT = -269
WRITE_TARGET_MEMORY_FAILED = -270
DEVICE_FEATURE_NOT_SUPPORTED = -271
WRONG_USER_CONFIG = -272
NO_TARGET_DEVICE_SELECTED = -273
CPU_IN_LOW_POWER_MODE = -274
@classmethod
def to_string(cls, error_code):
"""Returns the string message for the given ``error_code``.
Args:
cls (JlinkGlobalErrors): the ``JLinkGlobalErrors`` class
error_code (int): error code to convert
Returns:
An error string corresponding to the error code.
Raises:
ValueError: if the error code is invalid.
"""
if error_code == cls.EMU_NO_CONNECTION:
return 'No connection to emulator.'
if error_code == cls.EMU_COMM_ERROR:
return 'Emulator connection error.'
if error_code == cls.DLL_NOT_OPEN:
return "DLL has not been opened. Did you call '.connect()'?"
if error_code == cls.VCC_FAILURE:
return 'Target system has no power.'
if error_code == cls.INVALID_HANDLE:
return 'Given file / memory handle is invalid.'
if error_code == cls.NO_CPU_FOUND:
return 'Could not find supported CPU.'
if error_code == cls.EMU_FEATURE_UNSUPPORTED:
return 'Emulator does not support the selected feature.'
if error_code == cls.EMU_NO_MEMORY:
return 'Emulator out of memory.'
if error_code == cls.TIF_STATUS_ERROR:
return 'Target interface error.'
if error_code == cls.FLASH_PROG_COMPARE_FAILED:
return 'Programmed data differs from source data.'
if error_code == cls.FLASH_PROG_PROGRAM_FAILED:
return 'Programming error occured.'
if error_code == cls.FLASH_PROG_VERIFY_FAILED:
return 'Error while verifying programmed data.'
if error_code == cls.OPEN_FILE_FAILED:
return 'Specified file could not be opened.'
if error_code == cls.UNKNOWN_FILE_FORMAT:
return 'File format of selected file is not supported.'
if error_code == cls.WRITE_TARGET_MEMORY_FAILED:
return 'Could not write target memory.'
if error_code == cls.DEVICE_FEATURE_NOT_SUPPORTED:
return 'Feature not supported by connected device.'
if error_code == cls.WRONG_USER_CONFIG:
return 'User configured DLL parameters incorrectly.'
if error_code == cls.NO_TARGET_DEVICE_SELECTED:
return 'User did not specify core to connect to.'
if error_code == cls.CPU_IN_LOW_POWER_MODE:
return 'Target CPU is in low power mode.'
if error_code == cls.UNSPECIFIED_ERROR:
return 'Unspecified error.'
raise ValueError('Invalid error code: %d' % error_code)
class JLinkEraseErrors(JLinkGlobalErrors):
__doc__ = 'Enumeration for the error codes generated during an erase operation.'
ILLEGAL_COMMAND = -5
@classmethod
def to_string(cls, error_code):
if error_code == cls.ILLEGAL_COMMAND:
return 'Failed to erase sector.'
return super(JLinkEraseErrors, cls).to_string(error_code)
class JLinkFlashErrors(JLinkGlobalErrors):
__doc__ = 'Enumeration for the error codes generated during a flash operation.'
COMPARE_ERROR = -2
PROGRAM_ERASE_ERROR = -3
VERIFICATION_ERROR = -4
@classmethod
def to_string(cls, error_code):
if error_code == cls.COMPARE_ERROR:
return 'Error comparing flash content to programming data.'
if error_code == cls.PROGRAM_ERASE_ERROR:
return 'Error during program/erase phase.'
if error_code == cls.VERIFICATION_ERROR:
return 'Error verifying programmed data.'
return super(JLinkFlashErrors, cls).to_string(error_code)
class JLinkWriteErrors(JLinkGlobalErrors):
__doc__ = 'Enumeration for the error codes generated during a write.'
ZONE_NOT_FOUND_ERROR = -5
@classmethod
def to_string(cls, error_code):
if error_code == cls.ZONE_NOT_FOUND_ERROR:
return 'Zone not found'
return super(JLinkWriteErrors, cls).to_string(error_code)
class JLinkReadErrors(JLinkGlobalErrors):
__doc__ = 'Enumeration for the error codes generated during a read.'
ZONE_NOT_FOUND_ERROR = -5
@classmethod
def to_string(cls, error_code):
if error_code == cls.ZONE_NOT_FOUND_ERROR:
return 'Zone not found'
return super(JLinkReadErrors, cls).to_string(error_code)
class JLinkDataErrors(JLinkGlobalErrors):
__doc__ = 'Enumeration for the error codes generated when setting a data event.'
ERROR_UNKNOWN = 2147483648
ERROR_NO_MORE_EVENTS = 2147483649
ERROR_NO_MORE_ADDR_COMP = 2147483650
ERROR_NO_MORE_DATA_COMP = 2147483652
ERROR_INVALID_ADDR_MASK = 2147483680
ERROR_INVALID_DATA_MASK = 2147483712
ERROR_INVALID_ACCESS_MASK = 2147483776
@classmethod
def to_string(cls, error_code):
if error_code == cls.ERROR_UNKNOWN:
return 'Unknown error.'
if error_code == cls.ERROR_NO_MORE_EVENTS:
return 'There are no more available watchpoint units.'
if error_code == cls.ERROR_NO_MORE_ADDR_COMP:
return 'No more address comparisons can be set.'
if error_code == cls.ERROR_NO_MORE_DATA_COMP:
return 'No more data comparisons can be set.'
if error_code == cls.ERROR_INVALID_ADDR_MASK:
return 'Invalid flags passed for the address mask.'
if error_code == cls.ERROR_INVALID_DATA_MASK:
return 'Invalid flags passed for the data mask.'
if error_code == cls.ERROR_INVALID_ACCESS_MASK:
return 'Invalid flags passed for the access mask.'
return super(JLinkDataErrors, cls).to_string(error_code)
class JLinkRTTErrors(JLinkGlobalErrors):
__doc__ = 'Enumeration for error codes from RTT.'
RTT_ERROR_CONTROL_BLOCK_NOT_FOUND = -2
@classmethod
def to_string(cls, error_code):
if error_code == cls.RTT_ERROR_CONTROL_BLOCK_NOT_FOUND:
return 'The RTT Control Block has not yet been found (wait?)'
return super(JLinkRTTErrors, cls).to_string(error_code)
class JLinkHost(object):
__doc__ = 'Enumeration for the different JLink hosts: currently only IP and USB.'
USB = 1
IP = 2
USB_OR_IP = USB | IP
class JLinkInterfaces(object):
__doc__ = 'Target interfaces for the J-Link.'
JTAG = 0
SWD = 1
FINE = 3
ICSP = 4
SPI = 5
C2 = 6
class JLinkResetStrategyCortexM3(object):
__doc__ = 'Target reset strategies for the J-Link.\n\n Attributes:\n NORMAL: default reset strategy, does whatever is best to reset.\n CORE: only the core is reset via the ``VECTRESET`` bit.\n RESETPIN: pulls the reset pin low to reset the core and peripherals.\n CONNECT_UNDER_RESET: J-Link connects to target while keeping reset\n active. This is recommented for STM32 devices.\n HALT_AFTER_BTL: halt the core after the bootloader is executed.\n HALT_BEFORE_BTL: halt the core before the bootloader is executed.\n KINETIS: performs a normal reset, but also disables the watchdog.\n ADI_HALT_AFTER_KERNEL: sets the ``SYSRESETREQ`` bit in the ``AIRCR`` in\n order to reset the device.\n CORE_AND_PERIPHERALS: sets the ``SYSRESETREQ`` bit in the ``AIRCR``, and\n the ``VC_CORERESET`` bit in the ``DEMCR`` to make sure that the CPU is\n halted immediately after reset.\n LPC1200: reset for LPC1200 devices.\n S3FN60D: reset for Samsung S3FN60D devices.\n\n Note:\n Please see the J-Link SEGGER Documentation, UM8001, for full information\n about the different reset strategies.\n '
NORMAL = 0
CORE = 1
RESETPIN = 2
CONNECT_UNDER_RESET = 3
HALT_AFTER_BTL = 4
HALT_BEFORE_BTL = 5
KINETIS = 6
ADI_HALT_AFTER_KERNEL = 7
CORE_AND_PERIPHERALS = 8
LPC1200 = 9
S3FN60D = 10
class JLinkFunctions(object):
__doc__ = 'Collection of function prototype and type builders for the J-Link SDK\n API calls.'
LOG_PROTOTYPE = ctypes.CFUNCTYPE(None, ctypes.c_char_p)
UNSECURE_HOOK_PROTOTYPE = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint32)
FLASH_PROGRESS_PROTOTYPE = ctypes.CFUNCTYPE(None, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int)
class JLinkCore(object):
__doc__ = 'Enumeration for the different CPU core identifiers.\n\n These are the possible cores for targets the J-Link is connected to.\n Note that these are bitfields.'
NONE = 0
ANY = 4294967295
CORTEX_M1 = 16777471
COLDFIRE = 50331647
CORTEX_M3 = 50331903
CORTEX_M3_R1P0 = 50331664
CORTEX_M3_R1P1 = 50331665
CORTEX_M3_R2P0 = 50331680
SIM = 83886079
XSCALE = 100663295
CORTEX_M0 = 100663551
CORTEX_M_V8BASEL = 100729087
ARM7 = 134217727
ARM7TDMI = 117440767
ARM7TDMI_R3 = 117440575
ARM7TDMI_R4 = 117440591
ARM7TDMI_S = 117441023
ARM7TDMI_S_R3 = 117440831
ARM7TDMI_S_R4 = 117440847
CORTEX_A8 = 134217983
CORTEX_A7 = 134742271
CORTEX_A9 = 134807807
CORTEX_A12 = 134873343
CORTEX_A15 = 134938879
CORTEX_A17 = 135004415
ARM9 = 167772159
ARM9TDMI_S = 150995455
ARM920T = 153092351
ARM922T = 153223423
ARM926EJ_S = 153485823
ARM946E_S = 155582975
ARM966E_S = 157680127
ARM968E_S = 157811199
ARM11 = 201326591
ARM1136 = 188153855
ARM1136J = 188089087
ARM1136J_S = 188089343
ARM1136JF = 188090111
ARM1136JF_S = 188090367
ARM1156 = 190251007
ARM1176 = 192348159
ARM1176J = 192283391
ARM1176J_S = 192283647
ARM1176JF = 192284415
ARM1176JF_S = 192284671
CORTEX_R4 = 201326847
CORTEX_R5 = 201392383
RX = 234881023
RX610 = 218169343
RX62N = 218234879
RX62T = 218300415
RX63N = 218365951
RX630 = 218431487
RX63T = 218497023
RX621 = 218562559
RX62G = 218628095
RX631 = 218693631
RX210 = 219217919
RX21A = 219283455
RX220 = 219348991
RX230 = 219414527
RX231 = 219480063
RX23T = 219545599
RX111 = 220266495
RX110 = 220332031
RX113 = 220397567
RX64M = 221315071
RX71M = 221380607
CORTEX_M4 = 234881279
CORTEX_M7 = 234946815
CORTEX_M_V8MAINL = 235012351
CORTEX_A5 = 251658495
POWER_PC = 285212671
POWER_PC_N1 = 285147391
POWER_PC_N2 = 285147647
MIPS = 301989887
MIPS_M4K = 285278207
MIPS_MICROAPTIV = 285343743
EFM8_UNSPEC = 318767103
CIP51 = 302055423
class JLinkDeviceFamily(object):
__doc__ = 'Enumeration for the difference device families.\n\n These are the possible device families for targets that the J-Link is\n connected to.'
AUTO = 0
CORTEX_M1 = 1
COLDFIRE = 2
CORTEX_M3 = 3
SIMULATOR = 4
XSCALE = 5
CORTEX_M0 = 6
ARM7 = 7
CORTEX_A8 = 8
CORTEX_A9 = 8
ARM9 = 9
ARM10 = 10
ARM11 = 11
CORTEX_R4 = 12
RX = 13
CORTEX_M4 = 14
CORTEX_A5 = 15
POWERPC = 16
MIPS = 17
EFM8 = 18
ANY = 255
class JLinkFlags(object):
__doc__ = 'Enumeration for the different flags that are passed to the J-Link C SDK\n API methods.'
GO_OVERSTEP_BP = 1
DLG_BUTTON_YES = 1
DLG_BUTTON_NO = 2
DLG_BUTTON_OK = 4
DLG_BUTTON_CANCEL = 8
HW_PIN_STATUS_LOW = 0
HW_PIN_STATUS_HIGH = 1
HW_PIN_STATUS_UNKNOWN = 255
class JLinkSWOInterfaces(object):
__doc__ = 'Serial Wire Output (SWO) interfaces.'
UART = 0
MANCHESTER = 1
class JLinkSWOCommands(object):
__doc__ = 'Serial Wire Output (SWO) commands.'
START = 0
STOP = 1
FLUSH = 2
GET_SPEED_INFO = 3
GET_NUM_BYTES = 10
SET_BUFFERSIZE_HOST = 20
SET_BUFFERSIZE_EMU = 21
class JLinkCPUCapabilities(object):
__doc__ = 'Target CPU Cabilities.'
READ_MEMORY = 2
WRITE_MEMORY = 4
READ_REGISTERS = 8
WRITE_REGISTERS = 16
GO = 32
STEP = 64
HALT = 128
IS_HALTED = 256
RESET = 512
RUN_STOP = 1024
TERMINAL = 2048
DCC = 16384
HSS = 32768
class JLinkHaltReasons(object):
__doc__ = 'Halt reasons for the CPU.\n\n Attributes:\n DBGRQ: CPU has been halted because DBGRQ signal asserted.\n CODE_BREAKPOINT: CPU has been halted because of code breakpoint match.\n DATA_BREAKPOINT: CPU has been halted because of data breakpoint match.\n VECTOR_CATCH: CPU has been halted because of vector catch.\n '
DBGRQ = 0
CODE_BREAKPOINT = 1
DATA_BREAKPOINT = 2
VECTOR_CATCH = 3
class JLinkVectorCatchCortexM3(object):
__doc__ = 'Vector catch types for the ARM Cortex M3.\n\n Attributes:\n CORE_RESET: The CPU core reset.\n MEM_ERROR: A memory management error occurred.\n COPROCESSOR_ERROR: Usage fault error accessing the Coprocessor.\n CHECK_ERROR: Usage fault error on enabled check.\n STATE_ERROR: Usage fault state error.\n BUS_ERROR: Normal bus error.\n INT_ERROR: Interrupt or exception service error.\n HARD_ERROR: Hard fault error.\n '
CORE_RESET = 1
MEM_ERROR = 16
COPROCESSOR_ERROR = 32
CHECK_ERROR = 64
STATE_ERROR = 128
BUS_ERROR = 256
INT_ERROR = 512
HARD_ERROR = 1024
class JLinkBreakpoint(object):
__doc__ = 'J-Link breakpoint types.\n\n Attributes:\n SW_RAM: Software breakpont located in RAM.\n SW_FLASH: Software breakpoint located in flash.\n SW: Software breakpoint located in RAM or flash.\n HW: Hardware breakpoint.\n ANY: Allows specifying any time of breakpoint.\n ARM: Breakpoint in ARM mode (only available on ARM 7/9 cores).\n THUMB: Breakpoint in THUMB mode (only available on ARM 7/9 cores).\n '
SW_RAM = 16
SW_FLASH = 32
SW = 240
HW = 4294967040
ANY = 4294967280
ARM = 1
THUMB = 2
class JLinkBreakpointImplementation(object):
__doc__ = 'J-Link breakpoint implementation types.\n\n Attributes:\n HARD: Hardware breakpoint using a breakpoint unit.\n SOFT: Software breakpoint using a breakpoint instruction.\n PENDING: Breakpoint has not been set yet.\n FLASH: Breakpoint set in flash.\n '
HARD = 1
SOFT = 2
PENDING = 4
FLASH = 16
class JLinkEventTypes(object):
__doc__ = 'J-Link data event types.\n\n Attributes:\n BREAKPOINT: breakpoint data event.\n '
BREAKPOINT = 1
class JLinkAccessFlags(object):
__doc__ = 'J-Link access types for data events.\n\n These access types allow specifying the different types of access events\n that should be monitored.\n\n Attributes:\n READ: specifies to monitor read accesses.\n WRITE: specifies to monitor write accesses.\n PRIVILEGED: specifies to monitor privileged accesses.\n SIZE_8BIT: specifies to monitor an 8-bit access width.\n SIZE_16BIT: specifies to monitor an 16-bit access width.\n SIZE_32BIT: specifies to monitor an 32-bit access width.\n '
READ = 0
WRITE = 1
PRIV = 16
SIZE_8BIT = 0
SIZE_16BIT = 2
SIZE_32BIT = 4
class JLinkAccessMaskFlags(object):
__doc__ = 'J-Link access mask flags.\n\n Attributes:\n SIZE: specifies to not care about the access size of the event.\n DIR: specifies to not care about the access direction of the event.\n PRIV: specifies to not care about the access privilege of the event.\n '
SIZE = 6
DIR = 1
PRIV = 16
class JLinkStraceCommand(object):
__doc__ = 'STRACE commmands.'
TRACE_EVENT_SET = 0
TRACE_EVENT_CLR = 1
TRACE_EVENT_CLR_ALL = 2
SET_BUFFER_SIZE = 3
class JLinkStraceEvent(object):
__doc__ = 'STRACE events.'
CODE_FETCH = 0
DATA_ACCESS = 1
DATA_LOAD = 2
DATA_STORE = 3
class JLinkStraceOperation(object):
__doc__ = 'STRACE operation specifiers.'
TRACE_START = 0
TRACE_STOP = 1
TRACE_INCLUDE_RANGE = 2
TRACE_EXCLUDE_RANGE = 3
class JLinkTraceSource(object):
__doc__ = 'Sources for tracing.'
ETB = 0
ETM = 1
MTB = 2
class JLinkTraceCommand(object):
__doc__ = 'J-Link trace commands.'
START = 0
STOP = 1
FLUSH = 2
GET_NUM_SAMPLES = 16
GET_CONF_CAPACITY = 17
SET_CAPACITY = 18
GET_MIN_CAPACITY = 19
GET_MAX_CAPACITY = 20
SET_FORMAT = 32
GET_FORMAT = 33
GET_NUM_REGIONS = 48
GET_REGION_PROPS = 49
GET_REGION_PROPS_EX = 50
class JLinkTraceFormat(object):
__doc__ = 'J-Link trace formats.\n\n Attributes:\n FORMAT_4BIT: 4-bit data.\n FORMAT_8BIT: 8-bit data.\n FORMAT_16BIT: 16-bit data.\n FORMAT_MULTIPLEXED: multiplexing on ETM / buffer link.\n FORMAT_DEMULTIPLEXED: de-multiplexing on ETM / buffer link.\n FORMAT_DOUBLE_EDGE: clock data on both ETM / buffer link edges.\n FORMAT_ETM7_9: ETM7/ETM9 protocol.\n FORMAT_ETM10: ETM10 protocol.\n FORMAT_1BIT: 1-bit data.\n FORMAT_2BIT: 2-bit data.\n '
FORMAT_4BIT = 1
FORMAT_8BIT = 2
FORMAT_16BIT = 4
FORMAT_MULTIPLEXED = 8
FORMAT_DEMULTIPLEXED = 16
FORMAT_DOUBLE_EDGE = 32
FORMAT_ETM7_9 = 64
FORMAT_ETM10 = 128
FORMAT_1BIT = 256
FORMAT_2BIT = 512
class JLinkROMTable(object):
__doc__ = 'The J-Link ROM tables.'
NONE = 256
ETM = 257
MTB = 258
TPIU = 259
ITM = 260
DWT = 261
FPB = 262
NVIC = 263
TMC = 264
TF = 265
PTM = 266
ETB = 267
DBG = 268
APBAP = 269
AHBAP = 270
SECURE = 271
class JLinkRTTCommand(object):
__doc__ = 'RTT commands.'
START = 0
STOP = 1
GETDESC = 2
GETNUMBUF = 3
GETSTAT = 4
class JLinkRTTDirection(object):
__doc__ = 'RTT Direction.'
UP = 0
DOWN = 1
# okay decompiling ./pylink/enums.pyc

View File

@ -1,44 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/errors.py
from . import enums
from . import util
class JLinkException(enums.JLinkGlobalErrors, Exception):
__doc__ = 'Generic J-Link exception.'
def __init__(self, code):
message = code
self.code = None
if util.is_integer(code):
message = self.to_string(code)
self.code = code
super(JLinkException, self).__init__(message)
self.message = message
class JLinkEraseException(enums.JLinkEraseErrors, JLinkException):
__doc__ = 'J-Link erase exception.'
class JLinkFlashException(enums.JLinkFlashErrors, JLinkException):
__doc__ = 'J-Link flash exception.'
class JLinkWriteException(enums.JLinkWriteErrors, JLinkException):
__doc__ = 'J-Link write exception.'
class JLinkReadException(enums.JLinkReadErrors, JLinkException):
__doc__ = 'J-Link read exception.'
class JLinkDataException(enums.JLinkDataErrors, JLinkException):
__doc__ = 'J-Link data event exception.'
class JLinkRTTException(enums.JLinkRTTErrors, JLinkException):
__doc__ = 'J-Link RTT exception.'
# okay decompiling ./pylink/errors.pyc

File diff suppressed because it is too large Load Diff

View File

@ -1,114 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/jlock.py
import psutil, errno, tempfile, os
class JLock(object):
__doc__ = 'Lockfile for accessing a particular J-Link.\n\n The J-Link SDK does not prevent accessing the same J-Link multiple times\n from the same process or multiple processes. As a result, a user can\n have the same J-Link being accessed by multiple processes. This class\n provides an interface to a lock-file like structure for the physical\n J-Links to ensure that any instance of a ``JLink`` with an open emulator\n connection will be the only one accessing that emulator.\n\n This class uses a PID-style lockfile to allow acquiring of the lockfile in\n the instances where the lockfile exists, but the process which created it\n is no longer running.\n\n To share the same emulator connection between multiple threads, processes,\n or functions, a single instance of a ``JLink`` should be created and passed\n between the threads and processes.\n\n Attributes:\n name: the name of the lockfile.\n path: full path to the lockfile.\n fd: file description of the lockfile.\n acquired: boolean indicating if the lockfile lock has been acquired.\n '
SERIAL_NAME_FMT = '.pylink-usb-{}.lck'
IPADDR_NAME_FMT = '.pylink-ip-{}.lck'
def __init__(self, serial_no):
"""Creates an instance of a ``JLock`` and populates the name.
Note:
This method may fail if there is no temporary directory in which to
have the lockfile placed.
Args:
self (JLock): the ``JLock`` instance
serial_no (int): the serial number of the J-Link
Returns:
``None``
"""
self.name = self.SERIAL_NAME_FMT.format(serial_no)
self.acquired = False
self.fd = None
self.path = None
self.path = os.path.join(tempfile.tempdir, self.name)
def __del__(self):
"""Cleans up the lockfile instance if it was acquired.
Args:
self (JLock): the ``JLock`` instance
Returns:
``None``
"""
self.release()
def acquire(self):
"""Attempts to acquire a lock for the J-Link lockfile.
If the lockfile exists but does not correspond to an active process,
the lockfile is first removed, before an attempt is made to acquire it.
Args:
self (Jlock): the ``JLock`` instance
Returns:
``True`` if the lock was acquired, otherwise ``False``.
Raises:
OSError: on file errors.
"""
if os.path.exists(self.path):
try:
pid = None
with open(self.path, 'r') as f:
line = f.readline().strip()
pid = int(line)
if not psutil.pid_exists(pid):
os.remove(self.path)
except ValueError as e:
try:
os.remove(self.path)
finally:
e = None
del e
except IOError as e:
try:
pass
finally:
e = None
del e
try:
self.fd = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_RDWR)
to_write = '%s%s' % (os.getpid(), os.linesep)
os.write(self.fd, to_write.encode())
except OSError as e:
try:
if not os.path.exists(self.path):
raise
return False
finally:
e = None
del e
self.acquired = True
return True
def release(self):
"""Cleans up the lockfile if it was acquired.
Args:
self (JLock): the ``JLock`` instance
Returns:
``False`` if the lock was not released or the lock is not acquired,
otherwise ``True``.
"""
if not self.acquired:
return False
os.close(self.fd)
if os.path.exists(self.path):
os.remove(self.path)
self.acquired = False
return True
# okay decompiling ./pylink/jlock.pyc

View File

@ -1,346 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/library.py
from . import util
import ctypes
import ctypes.util as ctypes_util
import os, sys, tempfile
class Library(object):
__doc__ = 'Wrapper to provide easy access to loading the J-Link SDK DLL.\n\n This class provides a convenience for finding and loading the J-Link DLL\n across multiple platforms, and accounting for the inconsistencies between\n Windows and nix-based platforms.\n\n Attributes:\n _standard_calls_: list of names of the methods for the API calls that\n must be converted to standard calling convention on the Windows\n platform.\n JLINK_SDK_NAME: name of the J-Link DLL on nix-based platforms.\n WINDOWS_JLINK_SDK_NAME: name of the J-Link DLL on Windows platforms.\n '
_standard_calls_ = [
'JLINK_Configure',
'JLINK_DownloadFile',
'JLINK_GetAvailableLicense',
'JLINK_GetPCode',
'JLINK_PrintConfig',
'JLINK_EraseChip',
'JLINK_SPI_Transfer',
'JLINK_GetpFunc',
'JLINK_GetMemZones',
'JLINK_ReadMemZonedEx',
'JLINK_SetHookUnsecureDialog',
'JLINK_WriteMemZonedEx',
'JLINK_DIALOG_Configure',
'JLINK_DIALOG_ConfigureEx',
'JLINK_EMU_GPIO_GetProps',
'JLINK_EMU_GPIO_GetState',
'JLINK_EMU_GPIO_SetState',
'JLINK_EMU_AddLicense',
'JLINK_EMU_EraseLicenses',
'JLINK_EMU_GetLicenses',
'JLINK_HSS_GetCaps',
'JLINK_HSS_Start',
'JLINK_HSS_Stop',
'JLINK_HSS_Read',
'JLINK_POWERTRACE_Control',
'JLINK_POWERTRACE_Read',
'JLINK_RTTERMINAL_Control',
'JLINK_RTTERMINAL_Read',
'JLINK_RTTERMINAL_Write',
'JLINK_STRACE_Config',
'JLINK_STRACE_Control',
'JLINK_STRACE_Read',
'JLINK_STRACE_Start',
'JLINK_STRACE_Stop',
'JLINK_SWD_GetData',
'JLINK_SWD_GetU8',
'JLINK_SWD_GetU16',
'JLINK_SWD_GetU32',
'JLINK_SWD_StoreGetRaw',
'JLINK_SWD_StoreRaw',
'JLINK_SWD_SyncBits',
'JLINK_SWD_SyncBytes',
'JLINK_SetFlashProgProgressCallback']
JLINK_SDK_NAME = 'libjlinkarm'
WINDOWS_32_JLINK_SDK_NAME = 'JLinkARM'
WINDOWS_64_JLINK_SDK_NAME = 'JLink_x64'
@classmethod
def get_appropriate_windows_sdk_name(cls):
"""Returns the appropriate JLink SDK library name on Windows depending
on 32bit or 64bit Python variant.
SEGGER delivers two variants of their dynamic library on Windows:
- ``JLinkARM.dll`` for 32-bit platform
- ``JLink_x64.dll`` for 64-bit platform
Args:
cls (Library): the ``Library`` class
Returns:
The name of the library depending on the platform this module is run on.
"""
if sys.maxsize == 9223372036854775807:
return Library.WINDOWS_64_JLINK_SDK_NAME
return Library.WINDOWS_32_JLINK_SDK_NAME
@classmethod
def find_library_windows(cls):
r"""Loads the SEGGER DLL from the windows installation directory.
On Windows, these are found either under:
- ``C:\Program Files\SEGGER\JLink``
- ``C:\Program Files (x86)\SEGGER\JLink``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found.
"""
dll = cls.get_appropriate_windows_sdk_name() + '.dll'
root = 'C:\\'
for d in os.listdir(root):
dir_path = os.path.join(root, d)
if d.startswith('Program Files'):
if os.path.isdir(dir_path):
dir_path = os.path.join(dir_path, 'SEGGER')
if not os.path.isdir(dir_path):
continue
else:
ds = filter(lambda x: x.startswith('JLink')
, os.listdir(dir_path))
for jlink_dir in ds:
lib_path = os.path.join(dir_path, jlink_dir, dll)
if os.path.isfile(lib_path):
yield lib_path
@classmethod
def find_library_linux(cls):
"""Loads the SEGGER DLL from the root directory.
On Linux, the SEGGER tools are installed under the ``/opt/SEGGER``
directory with versioned directories having the suffix ``_VERSION``.
Args:
cls (Library): the ``Library`` class
Returns:
The paths to the J-Link library files in the order that they are
found.
"""
dll = Library.JLINK_SDK_NAME
root = os.path.join('/', 'opt', 'SEGGER')
for directory_name, subdirs, files in os.walk(root):
fnames = []
x86_found = False
for f in files:
path = os.path.join(directory_name, f)
if os.path.isfile(path):
if f.startswith(dll):
fnames.append(f)
if '_x86' in path:
x86_found = True
for fname in fnames:
fpath = os.path.join(directory_name, fname)
if util.is_os_64bit():
if '_x86' not in fname:
yield fpath
else:
if x86_found:
if '_x86' in fname:
yield fpath
else:
yield fpath
@classmethod
def find_library_darwin(cls):
r"""Loads the SEGGER DLL from the installed applications.
This method accounts for the all the different ways in which the DLL
may be installed depending on the version of the DLL. Always uses
the first directory found.
SEGGER's DLL is installed in one of three ways dependent on which
which version of the SEGGER tools are installed:
======== ============================================================
Versions Directory
======== ============================================================
< 5.0.0 ``/Applications/SEGGER/JLink\ NUMBER``
< 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm.major.minor.dylib``
>= 6.0.0 ``/Applications/SEGGER/JLink/libjlinkarm``
======== ============================================================
Args:
cls (Library): the ``Library`` class
Returns:
The path to the J-Link library files in the order they are found.
"""
dll = Library.JLINK_SDK_NAME
root = os.path.join('/', 'Applications', 'SEGGER')
if not os.path.isdir(root):
return
for d in os.listdir(root):
dir_path = os.path.join(root, d)
if os.path.isdir(dir_path):
if d.startswith('JLink'):
files = list((f for f in os.listdir(dir_path) if os.path.isfile(os.path.join(dir_path, f))))
if dll + '.dylib' in files:
yield os.path.join(dir_path, dll + '.dylib')
else:
for f in files:
if f.startswith(dll):
yield os.path.join(dir_path, f)
def __init__(self, dllpath=None):
"""Initializes an instance of a ``Library``.
Loads the default J-Link DLL if ``dllpath`` is ``None``, otherwise
loads the DLL specified by the given ``dllpath``.
Args:
self (Library): the ``Library`` instance
dllpath (str): the DLL to load into the library
Returns:
``None``
"""
self._lib = None
self._winlib = None
self._path = None
self._windows = sys.platform.startswith('win')
self._cygwin = sys.platform.startswith('cygwin')
self._temp = None
if self._windows or self._cygwin:
self._sdk = self.get_appropriate_windows_sdk_name()
else:
self._sdk = self.JLINK_SDK_NAME
if dllpath is not None:
self.load(dllpath)
else:
self.load_default()
def __del__(self):
"""Cleans up the temporary DLL file created when the lib was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``None``
"""
self.unload()
def load_default(self):
"""Loads the default J-Link SDK DLL.
The default J-Link SDK is determined by first checking if ``ctypes``
can find the DLL, then by searching the platform-specific paths.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was loaded, otherwise ``False``.
"""
path = ctypes_util.find_library(self._sdk)
if not path is None or self._windows or self._cygwin:
path = next(self.find_library_windows(), None)
else:
if sys.platform.startswith('linux'):
path = next(self.find_library_linux(), None)
else:
if sys.platform.startswith('darwin'):
path = next(self.find_library_darwin(), None)
if path is not None:
return self.load(path)
return False
def load(self, path=None):
"""Loads the specified DLL, if any, otherwise re-loads the current DLL.
If ``path`` is specified, loads the DLL at the given ``path``,
otherwise re-loads the DLL currently specified by this library.
Note:
This creates a temporary DLL file to use for the instance. This is
necessary to work around a limitation of the J-Link DLL in which
multiple J-Links cannot be accessed from the same process.
Args:
self (Library): the ``Library`` instance
path (path): path to the DLL to load
Returns:
``True`` if library was loaded successfully.
Raises:
OSError: if there is no J-LINK SDK DLL present at the path.
See Also:
`J-Link Multi-session <http://forum.segger.com/index.php?page=Thread&threadID=669>`_.
"""
self.unload()
self._path = path or self._path
if self._windows or self._cygwin:
suffix = '.dll'
else:
if sys.platform.startswith('darwin'):
suffix = '.dylib'
else:
suffix = '.so'
tf = tempfile.NamedTemporaryFile(delete=False, suffix=suffix)
with open(tf.name, 'wb') as outputfile:
with open(self._path, 'rb') as inputfile:
outputfile.write(inputfile.read())
tf.close()
self._temp = tf
self._lib = ctypes.cdll.LoadLibrary(tf.name)
if self._windows:
self._winlib = ctypes.windll.LoadLibrary(tf.name)
for stdcall in self._standard_calls_:
if hasattr(self._winlib, stdcall):
setattr(self._lib, stdcall, getattr(self._winlib, stdcall))
return True
def unload(self):
"""Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was unloaded, otherwise ``False``.
"""
unloaded = False
if self._lib is not None:
if self._winlib is not None:
ctypes.windll.kernel32.FreeLibrary.argtypes = (
ctypes.c_void_p,)
ctypes.windll.kernel32.FreeLibrary(self._lib._handle)
ctypes.windll.kernel32.FreeLibrary(self._winlib._handle)
self._lib = None
self._winlib = None
unloaded = True
else:
del self._lib
self._lib = None
unloaded = True
if self._temp is not None:
os.remove(self._temp.name)
self._temp = None
return unloaded
def dll(self):
"""Returns the DLL for the underlying shared library.
Args:
self (Library): the ``Library`` instance
Returns:
A ``ctypes`` DLL instance if one was loaded, otherwise ``None``.
"""
return self._lib
# okay decompiling ./pylink/library.pyc

View File

@ -1,206 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/registers.py
import ctypes
class IDCodeRegisterBits(ctypes.LittleEndianStructure):
__doc__ = 'This class holds the different bit masks for the IDCode register.\n\n Attributes:\n valid: validity bit, should always be ``0``.\n manufactuer: the JEDEC Manufacturer ID.\n part_no: the part number defined by the manufacturer.\n version_code: the version code.\n '
_fields_ = [
(
'valid', ctypes.c_uint32, 1),
(
'manufacturer', ctypes.c_uint32, 11),
(
'part_no', ctypes.c_uint32, 16),
(
'version_code', ctypes.c_uint32, 4)]
class IDCodeRegisterFlags(ctypes.Union):
__doc__ = 'Mask for the IDCode register bits.\n\n Attributes:\n value: the value stored in the mask.\n '
_anonymous_ = ('bit', )
_fields_ = [
(
'bit', IDCodeRegisterBits),
(
'value', ctypes.c_uint32)]
class AbortRegisterBits(ctypes.LittleEndianStructure):
__doc__ = 'This class holds the different bit mask for the Abort Register.\n\n Attributes:\n DAPABORT: write ``1`` to trigger a DAP abort.\n STKCMPCLR: write ``1`` to clear the ``STICKYCMP`` sticky compare flag\n (only supported on SW-DP).\n STKERRCLR: write ``1`` to clear the ``STICKYERR`` sticky error flag\n (only supported on SW-DP).\n WDERRCLR: write ``1`` to clear the ``WDATAERR`` write data error flag\n (only supported on SW-DP).\n ORUNERRCLR: write ``1`` to clear the ``STICKYORUN`` overrun error flag\n (only supported on SW-DP).\n '
_fields_ = [
(
'DAPABORT', ctypes.c_uint32, 1),
(
'STKCMPCLR', ctypes.c_uint32, 1),
(
'STKERRCLR', ctypes.c_uint32, 1),
(
'WDERRCLR', ctypes.c_uint32, 1),
(
'ORUNERRCLR', ctypes.c_uint32, 1),
(
'RESERVED', ctypes.c_uint32, 27)]
class AbortRegisterFlags(ctypes.Union):
__doc__ = 'Mask for the abort register bits.\n\n Attributes:\n value: the value stored in the mask.\n '
_anonymous_ = ('bit', )
_fields_ = [
(
'bit', AbortRegisterBits),
(
'value', ctypes.c_uint32)]
class ControlStatusRegisterBits(ctypes.LittleEndianStructure):
__doc__ = 'This class holds the different bit masks for the DP Control / Status\n Register bit assignments.\n\n Attributes:\n ORUNDETECT: if set, enables overrun detection.\n STICKYORUN: if overrun is enabled, is set when overrun occurs.\n TRNMODE: transfer mode for acess port operations.\n STICKYCMP: is set when a match occurs on a pushed compare or verify\n operation.\n STICKYERR: is set when an error is returned by an access port\n transaction.\n READOK: is set when the response to a previous access port or ``RDBUFF``\n was ``OK``.\n WDATAERR: set to ``1`` if a Write Data Error occurs.\n MASKLANE: bytes to be masked in pushed compare and verify operations.\n TRNCNT: transaction counter.\n RESERVED: reserved.\n CDBGRSTREQ: debug reset request.\n CDBGRSTACK: debug reset acknowledge.\n CDBGPWRUPREQ: debug power-up request.\n CDBGPWRUPACK: debug power-up acknowledge.\n CSYSPWRUPREQ: system power-up request\n CSYSPWRUPACK: system power-up acknowledge.\n\n See also:\n See the ARM documentation on the significance of these masks\n `here <http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ihi0031c/index.html>`_.\n '
_fields_ = [
(
'ORUNDETECT', ctypes.c_uint32, 1),
(
'STICKYORUN', ctypes.c_uint32, 1),
(
'TRNMODE', ctypes.c_uint32, 2),
(
'STICKYCMP', ctypes.c_uint32, 1),
(
'STICKYERR', ctypes.c_uint32, 1),
(
'READOK', ctypes.c_uint32, 1),
(
'WDATAERR', ctypes.c_uint32, 1),
(
'MASKLANE', ctypes.c_uint32, 4),
(
'TRNCNT', ctypes.c_uint32, 12),
(
'RESERVED', ctypes.c_uint32, 2),
(
'CDBGRSTREQ', ctypes.c_uint32, 1),
(
'CDBGRSTACK', ctypes.c_uint32, 1),
(
'CDBGPWRUPREQ', ctypes.c_uint32, 1),
(
'CDBGPWRUPACK', ctypes.c_uint32, 1),
(
'CSYSPWRUPREQ', ctypes.c_uint32, 1),
(
'CSYSPWRUPACK', ctypes.c_uint32, 1)]
class ControlStatusRegisterFlags(ctypes.Union):
__doc__ = 'Mask for the control/status register bits.\n\n Attributes:\n value: the value stored in the mask.\n '
_anonymous_ = ('bit', )
_fields_ = [
(
'bit', ControlStatusRegisterBits),
(
'value', ctypes.c_uint32)]
class SelectRegisterBits(ctypes.LittleEndianStructure):
__doc__ = 'This class holds the different bit masks for the AP Select Register.\n\n Attributes:\n CTRLSEL: SW-DP debug port address bank select.\n RESERVED_A: reserved.\n APBANKSEL: selects the active four-word register window on the current\n access port.\n RESERVED_B: reserved.\n APSEL: selects the current access port.\n '
_fields_ = [
(
'CTRLSEL', ctypes.c_uint32, 1),
(
'RESERVED_A', ctypes.c_uint32, 3),
(
'APBANKSEL', ctypes.c_uint32, 4),
(
'RESERVED_B', ctypes.c_uint32, 16),
(
'APSEL', ctypes.c_uint32, 8)]
class SelectRegisterFlags(ctypes.Union):
__doc__ = 'Mask for the select register bits.\n\n Attributes:\n value: the value stored in the mask.\n '
_anonymous_ = ('bit', )
_fields_ = [
(
'bit', SelectRegisterBits),
(
'value', ctypes.c_uint32)]
class MDMAPControlRegisterBits(ctypes.LittleEndianStructure):
__doc__ = 'This class holds the different bit masks for the MDM-AP Control\n Register.\n\n Attributes:\n flash_mass_erase: set to cause a mass erase, this is cleared\n automatically when a mass erase finishes.\n debug_disable: set to disable debug, clear to allow debug.\n debug_request: set to force the core to halt.\n sys_reset_request: set to force a system reset.\n core_hold_reset: set to suspend the core in reset at the end of reset\n sequencing.\n VLLDBGREQ: set to hold the system in reset after the next recovery from\n VLLSx (Very Low Leakage Stop).\n VLLDBGACK: set to release a system held in reset following a VLLSx\n (Very Low Leakage Stop) recovery.\n VLLSTATACK: set to acknowledge that the DAP LLS (Low Leakage Stop) and\n VLLS (Very Low Leakage Stop) status bits have read.\n '
_fields_ = [
(
'flash_mass_erase', ctypes.c_uint8, 1),
(
'debug_disable', ctypes.c_uint8, 1),
(
'debug_request', ctypes.c_uint8, 1),
(
'sys_reset_request', ctypes.c_uint8, 1),
(
'core_hold_reset', ctypes.c_uint8, 1),
(
'VLLDBGREQ', ctypes.c_uint8, 1),
(
'VLLDBGACK', ctypes.c_uint8, 1),
(
'VLLSTATACK', ctypes.c_uint8, 1)]
class MDMAPControlRegisterFlags(ctypes.Union):
__doc__ = 'Mask for the MDM-AP control register bits.\n\n Attributes:\n value: the value stored in the mask.\n '
_anonymous_ = ('bit', )
_fields_ = [
(
'bit', MDMAPControlRegisterBits),
(
'value', ctypes.c_uint8)]
class MDMAPStatusRegisterBits(ctypes.LittleEndianStructure):
__doc__ = 'Holds the bit masks for the MDM-AP Status Register.\n\n Attributes:\n flash_mass_erase_ack: cleared after a system reset, indicates that a\n flash mass erase was acknowledged.\n flash_ready: indicates that flash has been initialized and can be\n configured.\n system_security: if set, system is secure and debugger cannot access the\n memory or system bus.\n system_reset: ``1`` if system is in reset, otherwise ``0``.\n mass_erase_enabled: ``1`` if MCU can be mass erased, otherwise ``0``.\n low_power_enabled: ``1`` if low power stop mode is enabled, otherwise ``0``.\n very_low_power_mode: ``1`` if device is in very low power mode.\n LLSMODEEXIT: indicates an exit from LLS mode has occurred.\n VLLSxMODEEXIT: indicates an exit from VLLSx mode has occured.\n core_halted; indicates core has entered debug halt mode.\n core_deep_sleep: indicates core has entered a low power mode.\n core_sleeping: indicates the core has entered a low power mode.\n\n Note:\n if ``core_sleeping & !core_deep_sleep``, then the core is in VLPW (very\n low power wait) mode, otherwise if ``core_sleeping & core_deep_sleep``,\n then it is in VLPS (very low power stop) mode.\n '
_fields_ = [
(
'flash_mass_erase_ack', ctypes.c_uint32, 1),
(
'flash_ready', ctypes.c_uint32, 1),
(
'system_security', ctypes.c_uint32, 1),
(
'system_reset', ctypes.c_uint32, 1),
(
'RESERVED_A', ctypes.c_uint32, 1),
(
'mass_erase_enabled', ctypes.c_uint32, 1),
(
'backdoor_access_enabled', ctypes.c_uint32, 1),
(
'low_power_enabled', ctypes.c_uint32, 1),
(
'very_low_power_mode', ctypes.c_uint32, 1),
(
'LLSMODEEXIT', ctypes.c_uint32, 1),
(
'VLLSxMODEEXIT', ctypes.c_uint32, 1),
(
'RESERVED_B', ctypes.c_uint32, 5),
(
'core_halted', ctypes.c_uint32, 1),
(
'core_deep_sleep', ctypes.c_uint32, 1),
(
'core_sleeping', ctypes.c_uint32, 1),
(
'RESERVED_C', ctypes.c_uint32, 13)]
class MDMAPStatusRegisterFlags(ctypes.Union):
__doc__ = 'Mask for the MDM-AP status register bits.\n\n Attributes:\n value: the value stored in the mask.\n '
_anonymous_ = ('bit', )
_fields_ = [
(
'bit', MDMAPStatusRegisterBits),
(
'value', ctypes.c_uint32)]
# okay decompiling ./pylink/registers.pyc

View File

@ -1,907 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/structs.py
from . import enums
import ctypes
class JLinkConnectInfo(ctypes.Structure):
__doc__ = 'J-Link connection info structure.\n\n Attributes:\n SerialNumber: J-Link serial number.\n Connection: type of connection (e.g. ``enums.JLinkHost.USB``)\n USBAddr: USB address if connected via USB.\n aIPAddr: IP address if connected via IP.\n Time: Time period (ms) after which UDP discover answer was received.\n Time_us: Time period (uS) after which UDP discover answer was received.\n HWVersion: Hardware version of J-Link, if connected via IP.\n abMACAddr: MAC Address, if connected via IP.\n acProduct: Product name, if connected via IP.\n acNickname: Nickname, if connected via IP.\n acFWString: Firmware string, if connected via IP.\n IsDHCPAssignedIP: Is IP address reception via DHCP.\n IsDHCPAssignedIPIsValid: True if connected via IP.\n NumIPConnections: Number of IP connections currently established.\n NumIPConnectionsIsValid: True if connected via IP.\n aPadding: Bytes reserved for future use.\n '
_fields_ = [
(
'SerialNumber', ctypes.c_uint32),
(
'Connection', ctypes.c_ubyte),
(
'USBAddr', ctypes.c_uint32),
(
'aIPAddr', ctypes.c_uint8 * 16),
(
'Time', ctypes.c_int),
(
'Time_us', ctypes.c_uint64),
(
'HWVersion', ctypes.c_uint32),
(
'abMACAddr', ctypes.c_uint8 * 6),
(
'acProduct', ctypes.c_char * 32),
(
'acNickname', ctypes.c_char * 32),
(
'acFWString', ctypes.c_char * 112),
(
'IsDHCPAssignedIP', ctypes.c_char),
(
'IsDHCPAssignedIPIsValid', ctypes.c_char),
(
'NumIPConnections', ctypes.c_char),
(
'NumIPConnectionsIsValid', ctypes.c_char),
(
'aPadding', ctypes.c_uint8 * 34)]
def __repr__(self):
"""Returns a representation of this class.
Args:
self (JLinkConnectInfo): the ``JlinkConnectInfo`` instance
Returns:
String representation of the class.
"""
return 'JLinkConnectInfo(%s)' % self.__str__()
def __str__(self):
"""Returns a string representation of the connection info.
Args:
self (JLinkConnectInfo): the ``JLinkConnectInfo`` instance
Returns:
String specifying the product, its serial number, and the type of
connection that it has (one of USB or IP).
"""
conn = 'USB' if self.Connection == 1 else 'IP'
return '%s <Serial No. %s, Conn. %s>' % (self.acProduct.decode(), self.SerialNumber, conn)
class JLinkFlashArea(ctypes.Structure):
__doc__ = 'Definition for a region of Flash.\n\n Attributes:\n Addr: address where the flash area starts.\n Size: size of the flash area.\n '
_fields_ = [
(
'Addr', ctypes.c_uint32),
(
'Size', ctypes.c_uint32)]
def __repr__(self):
"""Returns a representation of the instance.
Args:
self (FlashArea): the ``FlashArea`` instance
Returns:
String representation of the Flash Area.
"""
return '%s(%s)' % (self.__class__.__name__, self.__str__())
def __str__(self):
"""Returns a string representation of the instance.
Args:
self (FlashArea): the ``FlashArea`` instance
Returns:
String specifying address of flash region, and its size.
"""
return 'Address = 0x%x, Size = %s' % (self.Addr, self.Size)
class JLinkRAMArea(JLinkFlashArea):
__doc__ = 'Definition for a region of RAM.\n\n Attributes:\n Addr: address where the flash area starts.\n Size: size of the flash area.\n '
class JLinkDeviceInfo(ctypes.Structure):
__doc__ = 'J-Link device information.\n\n This structure is used to represent a device that is supported by the\n J-Link.\n\n Attributes:\n SizeOfStruct: Size of the struct (DO NOT CHANGE).\n sName: name of the device.\n CoreId: core identifier of the device.\n FlashAddr: base address of the internal flash of the device.\n RAMAddr: base address of the internal RAM of the device.\n EndianMode: the endian mode of the device (0 -> only little endian,\n 1 -> only big endian, 2 -> both).\n FlashSize: total flash size in bytes.\n RAMSize: total RAM size in bytes.\n sManu: device manufacturer.\n aFlashArea: a list of ``JLinkFlashArea`` instances.\n aRamArea: a list of ``JLinkRAMArea`` instances.\n Core: CPU core.\n '
_fields_ = [
(
'SizeofStruct', ctypes.c_uint32),
(
'sName', ctypes.POINTER(ctypes.c_char)),
(
'CoreId', ctypes.c_uint32),
(
'FlashAddr', ctypes.c_uint32),
(
'RAMAddr', ctypes.c_uint32),
(
'EndianMode', ctypes.c_char),
(
'FlashSize', ctypes.c_uint32),
(
'RAMSize', ctypes.c_uint32),
(
'sManu', ctypes.POINTER(ctypes.c_char)),
(
'aFlashArea', JLinkFlashArea * 32),
(
'aRAMArea', JLinkRAMArea * 32),
(
'Core', ctypes.c_uint32)]
def __init__(self, *args, **kwargs):
(super(JLinkDeviceInfo, self).__init__)(*args, **kwargs)
self.SizeofStruct = ctypes.sizeof(self)
def __repr__(self):
"""Returns a representation of this instance.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Returns a string representation of the instance.
"""
return 'JLinkDeviceInfo(%s)' % self.__str__()
def __str__(self):
"""Returns a string representation of this instance.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Returns a string specifying the device name, core, and manufacturer.
"""
manu = self.manufacturer
return '%s <Core Id. %s, Manu. %s>' % (self.name, self.Core, manu)
@property
def name(self):
"""Returns the name of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Device name.
"""
return ctypes.cast(self.sName, ctypes.c_char_p).value.decode()
@property
def manufacturer(self):
"""Returns the name of the manufacturer of the device.
Args:
self (JLinkDeviceInfo): the ``JLinkDeviceInfo`` instance
Returns:
Manufacturer name.
"""
buf = ctypes.cast(self.sManu, ctypes.c_char_p).value
if buf:
return buf.decode()
class JLinkHardwareStatus(ctypes.Structure):
__doc__ = 'Definition for the hardware status information for a J-Link.\n\n Attributes:\n VTarget: target supply voltage.\n tck: measured state of TCK pin.\n tdi: measured state of TDI pin.\n tdo: measured state of TDO pin.\n tms: measured state of TMS pin.\n tres: measured state of TRES pin.\n trst: measured state of TRST pin.\n '
_fields_ = [
(
'VTarget', ctypes.c_uint16),
(
'tck', ctypes.c_uint8),
(
'tdi', ctypes.c_uint8),
(
'tdo', ctypes.c_uint8),
(
'tms', ctypes.c_uint8),
(
'tres', ctypes.c_uint8),
(
'trst', ctypes.c_uint8)]
def __repr__(self):
"""Returns a string representation of the instance.
Args:
self (JLinkHardwareStatus): the ``JlinkHardwareStatus`` instance
Returns:
String representation of the instance.
"""
return '%s(VTarget=%dmV)' % (self.__class__.__name__, self.voltage)
@property
def voltage(self):
"""Returns the target supply voltage.
This is an alias for ``.VTarget``.
Args:
self (JLInkHardwareStatus): the ``JLinkHardwareStatus`` instance
Returns:
Target supply voltage as an integer.
"""
return self.VTarget
class JLinkGPIODescriptor(ctypes.Structure):
__doc__ = 'Definition for the structure that details the name and capabilities of a\n user-controllable GPIO.\n\n Attributes:\n acName: name of the GPIO.\n Caps: bitfield of capabilities.\n '
_fields_ = [
(
'acName', ctypes.c_char * 32),
(
'Caps', ctypes.c_uint32)]
def __repr__(self):
"""Returns a string representation of the instance.
Args:
self (JLinkGPIODescriptor): the ``JLinkGPIODescriptor`` instance
Returns:
String representation of the instance.
"""
return '%s(%s)' % (self.__class__.__name__, self.__str__())
def __str__(self):
"""Returns the GPIO name.
Args:
self (JLinkGPIODescriptor): the ``JLInkGPIODescriptor`` instance
Returns:
GPIO name.
"""
return self.acName.decode()
class JLinkMemoryZone(ctypes.Structure):
__doc__ = 'Represents a CPU memory zone.\n\n Attributes:\n sName: initials of the memory zone.\n sDesc: name of the memory zone.\n VirtAddr: start address of the virtual address space of the memory zone.\n abDummy: reserved for future use.\n '
_fields_ = [
(
'sName', ctypes.c_char_p),
(
'sDesc', ctypes.c_char_p),
(
'VirtAddr', ctypes.c_uint64),
(
'abDummy', ctypes.c_uint8 * 16)]
def __repr__(self):
"""Returns a string representation of the instance
Args:
self: the ``JLinkMemoryZone`` instance
Returns:
String representation of the instance.
"""
return '%s(%s)' % (self.__class__.__name__, self.__str__())
def __str__(self):
"""Returns a formatted string describing the memory zone.
Args:
self: the ``JLinkMemoryZone`` instance
Returns:
String representation of the memory zone.
"""
return '%s <Desc. %s, VirtAddr. 0x%x>' % (self.sName, self.sDesc, self.VirtAddr)
@property
def name(self):
"""Alias for the memory zone name.
Args:
self (JLinkMemoryZone): the ``JLinkMemoryZone`` instance
Returns:
The memory zone name.
"""
return self.sName
class JLinkSpeedInfo(ctypes.Structure):
__doc__ = "Represents information about an emulator's supported speeds.\n\n The emulator can support all target interface speeds calculated by dividing\n the base frequency by atleast ``MinDiv``.\n\n Attributes:\n SizeOfStruct: the size of this structure.\n BaseFreq: Base frequency (in HZ) used to calculate supported speeds.\n MinDiv: minimum divider allowed to divide the base frequency.\n SupportAdaptive: ``1`` if emulator supports adaptive clocking, otherwise\n ``0``.\n "
_fields_ = [
(
'SizeOfStruct', ctypes.c_uint32),
(
'BaseFreq', ctypes.c_uint32),
(
'MinDiv', ctypes.c_uint16),
(
'SupportAdaptive', ctypes.c_uint16)]
def __init__(self):
super(JLinkSpeedInfo, self).__init__()
self.SizeOfStruct = ctypes.sizeof(self)
def __repr__(self):
"""Returns a string representation of the instance.
Args:
self (JLinkSpeedInfo): the ``JLinkSpeedInfo`` instance
Returns:
String representation of the instance.
"""
return self.__str__()
def __str__(self):
"""Returns this instance formatted as a string.
Args:
self (JLinkSpeedInfo): the ``JLinkSpeedInfo`` instance
Returns:
String formatted instance.
"""
return '%s(Freq=%sHz)' % (self.__class__.__name__, self.BaseFreq)
class JLinkSWOStartInfo(ctypes.Structure):
__doc__ = 'Represents configuration information for collecting Serial Wire Output\n (SWO) information.\n\n Attributes:\n SizeofStruct: size of the structure.\n Interface: the interface type used for SWO.\n Speed: the frequency used for SWO communication in Hz.\n\n Note:\n You should *never* change ``.SizeofStruct`` or ``.Interface``.\n '
_fields_ = [
(
'SizeofStruct', ctypes.c_uint32),
(
'Interface', ctypes.c_uint32),
(
'Speed', ctypes.c_uint32)]
def __init__(self):
super(JLinkSWOStartInfo, self).__init__()
self.SizeofStruct = ctypes.sizeof(self)
self.Interface = enums.JLinkSWOInterfaces.UART
def __repr__(self):
"""Returns a representation of this instance.
Args:
self (JLinkSWOStartInfo): the ``JLinkSWOStartInfo`` instance
Returns:
The string representation of this instance.
"""
return self.__str__()
def __str__(self):
"""Returns a string representation of this instance.
Args:
self (JLinkSWOStartInfo): the ``JLinkSWOStartInfo`` instance
Returns:
The string representation of this instance.
"""
return '%s(Speed=%sHz)' % (self.__class__.__name__, self.Speed)
class JLinkSWOSpeedInfo(ctypes.Structure):
__doc__ = "Structure representing information about target's supported SWO speeds.\n\n To calculate the supported SWO speeds, the base frequency is taken and\n divide by a number in the range of ``[ MinDiv, MaxDiv ]``.\n\n Attributes:\n SizeofStruct: size of the structure.\n Interface: interface type for the speed information.\n BaseFreq: base frequency (Hz) used to calculate supported SWO speeds.\n MinDiv: minimum divider allowed to divide the base frequency.\n MaxDiv: maximum divider allowed to divide the base frequency.\n MinPrescale: minimum prescaler allowed to adjust the base frequency.\n MaxPrescale: maximum prescaler allowed to adjust the base frequency.\n\n Note:\n You should *never* change ``.SizeofStruct`` or ``.Interface``.\n "
_fields_ = [
(
'SizeofStruct', ctypes.c_uint32),
(
'Interface', ctypes.c_uint32),
(
'BaseFreq', ctypes.c_uint32),
(
'MinDiv', ctypes.c_uint32),
(
'MaxDiv', ctypes.c_uint32),
(
'MinPrescale', ctypes.c_uint32),
(
'MaxPrescale', ctypes.c_uint32)]
def __init__(self):
super(JLinkSWOSpeedInfo, self).__init__()
self.SizeofStruct = ctypes.sizeof(self)
self.Interface = enums.JLinkSWOInterfaces.UART
def __repr__(self):
"""Returns a representation of the instance.
Args:
self (JLinkSWOSpeedInfo): the ``JLinkSWOSpeedInfo`` instance
Returns:
``None``
"""
return self.__str__()
def __str__(self):
"""Returns a string representaton of the instance.
Args:
self (JLinkSWOSpeedInfo): the ``JLinkSWOSpeedInfo`` instance
Returns:
``None``
"""
return '%s(Interface=UART, Freq=%sHz)' % (self.__class__.__name__, self.BaseFreq)
class JLinkMOEInfo(ctypes.Structure):
__doc__ = 'Structure representing the Method of Debug Entry (MOE).\n\n The method of debug entry is a reason for which a CPU has stopped. At any\n given time, there may be multiple methods of debug entry.\n\n Attributes:\n HaltReason: reason why the CPU stopped.\n Index: if cause of CPU stop was a code/data breakpoint, this identifies\n the index of the code/data breakpoint unit which causes the CPU to\n stop, otherwise it is ``-1``.\n '
_fields_ = [
(
'HaltReason', ctypes.c_uint32),
(
'Index', ctypes.c_int)]
def __repr__(self):
"""Returns a string representation of the instance.
Args:
self (JLinkMOEInfo): the ``JLinkMOEInfo`` instance
Returns:
A string representation of the instance.
"""
return '%s(%s)' % (self.__class__.__name__, self.__str__())
def __str__(self):
"""Returns a string representation of the instance.
Args:
self (JLinkMOEInfo): the ``JLinkMOEInfo`` instance
Returns:
A string representation of the instance.
"""
d = enums.JLinkHaltReasons.__dict__
s = next((k for k, v in d.items() if v == self.HaltReason))
if self.dbgrq():
return s
return s.replace('_', ' ').title()
def dbgrq(self):
"""Returns whether this a DBGRQ.
Args:
self (JLinkMOEInfo): the ``JLinkMOEInfo`` instance
Returns:
``True`` if this is a DBGRQ, otherwise ``False``.
"""
return self.HaltReason == enums.JLinkHaltReasons.DBGRQ
def code_breakpoint(self):
"""Returns whether this a code breakpoint.
Args:
self (JLinkMOEInfo): the ``JLinkMOEInfo`` instance
Returns:
``True`` if this is a code breakpoint, otherwise ``False``.
"""
return self.HaltReason == enums.JLinkHaltReasons.CODE_BREAKPOINT
def data_breakpoint(self):
"""Returns whether this a data breakpoint.
Args:
self (JLinkMOEInfo): the ``JLinkMOEInfo`` instance
Returns:
``True`` if this is a data breakpoint, otherwise ``False``.
"""
return self.HaltReason == enums.JLinkHaltReasons.DATA_BREAKPOINT
def vector_catch(self):
"""Returns whether this a vector catch.
Args:
self (JLinkMOEInfo): the ``JLinkMOEInfo`` instance
Returns:
``True`` if this is a vector catch, otherwise ``False``.
"""
return self.HaltReason == enums.JLinkHaltReasons.VECTOR_CATCH
class JLinkBreakpointInfo(ctypes.Structure):
__doc__ = 'Class representing information about a breakpoint.\n\n Attributes:\n SizeOfStruct: the size of the structure (this should not be modified).\n Handle: breakpoint handle.\n Addr: address of where the breakpoint has been set.\n Type: type flags which were specified when the breakpoint was created.\n ImpFlags: describes the current state of the breakpoint.\n UseCnt: describes how often the breakpoint is set at the same address.\n '
_fields_ = [
(
'SizeOfStruct', ctypes.c_uint32),
(
'Handle', ctypes.c_uint32),
(
'Addr', ctypes.c_uint32),
(
'Type', ctypes.c_uint32),
(
'ImpFlags', ctypes.c_uint32),
(
'UseCnt', ctypes.c_uint32)]
def __init__(self):
super(JLinkBreakpointInfo, self).__init__()
self.SizeOfStruct = ctypes.sizeof(self)
def __repr__(self):
"""Returns a formatted string describing the breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
Stirng representation of the breakpoint.
"""
return self.__str__()
def __str__(self):
"""Returns a formatted string describing the breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
Stirng representation of the breakpoint.
"""
name = self.__class__.__name__
return '%s(Handle %d, Address %d)' % (name, self.Handle, self.Addr)
def software_breakpoint(self):
"""Returns whether this is a software breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
``True`` if the breakpoint is a software breakpoint, otherwise
``False``.
"""
software_types = [
enums.JLinkBreakpoint.SW_RAM,
enums.JLinkBreakpoint.SW_FLASH,
enums.JLinkBreakpoint.SW]
return any((self.Type & stype for stype in software_types))
def hardware_breakpoint(self):
"""Returns whether this is a hardware breakpoint.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
``True`` if the breakpoint is a hardware breakpoint, otherwise
``False``.
"""
return self.Type & enums.JLinkBreakpoint.HW
def pending(self):
"""Returns if this breakpoint is pending.
Args:
self (JLinkBreakpointInfo): the ``JLinkBreakpointInfo`` instance
Returns:
``True`` if the breakpoint is still pending, otherwise ``False``.
"""
return self.ImpFlags & enums.JLinkBreakpointImplementation.PENDING
class JLinkDataEvent(ctypes.Structure):
__doc__ = 'Class representing a data event.\n\n A data may halt the CPU, trigger SWO output, or trigger trace output.\n\n Attributes:\n SizeOfStruct: the size of the structure (this should not be modified).\n Type: the type of the data event (this should not be modified).\n Addr: the address on which the watchpoint was set\n AddrMask: the address mask used for comparision.\n Data: the data on which the watchpoint has been set.\n DataMask: the data mask used for comparision.\n Access: the control data on which the event has been set.\n AccessMask: the control mask used for comparison.\n '
_fields_ = [
(
'SizeOfStruct', ctypes.c_int),
(
'Type', ctypes.c_int),
(
'Addr', ctypes.c_uint32),
(
'AddrMask', ctypes.c_uint32),
(
'Data', ctypes.c_uint32),
(
'DataMask', ctypes.c_uint32),
(
'Access', ctypes.c_uint8),
(
'AccessMask', ctypes.c_uint8)]
def __init__(self):
super(JLinkDataEvent, self).__init__()
self.SizeOfStruct = ctypes.sizeof(self)
self.Type = enums.JLinkEventTypes.BREAKPOINT
def __repr__(self):
"""Returns a string representation of the data event.
Args:
self (JLinkDataEvent): the ``JLinkDataEvent`` instance
Returns:
A string representation of the data event.
"""
return self.__str__()
def __str__(self):
"""Returns a string representation of the data event.
Args:
self (JLinkDataEvent): the ``JLinkDataEvent`` instance
Returns:
A string representation of the data event.
"""
name = self.__class__.__name__
return '%s(Type %d, Address %d)' % (name, self.Type, self.Addr)
class JLinkWatchpointInfo(ctypes.Structure):
__doc__ = 'Class representing information about a watchpoint.\n\n Attributes:\n SizeOfStruct: the size of the structure (this should not be modified).\n Handle: the watchpoint handle.\n Addr: the address the watchpoint was set at.\n AddrMask: the address mask used for comparison.\n Data: the data on which the watchpoint was set.\n DataMask: the data mask used for comparision.\n Ctrl: the control data on which the breakpoint was set.\n CtrlMask: the control mask used for comparison.\n WPUnit: the index of the watchpoint unit.\n '
_fields_ = [
(
'SizeOfStruct', ctypes.c_uint32),
(
'Handle', ctypes.c_uint32),
(
'Addr', ctypes.c_uint32),
(
'AddrMask', ctypes.c_uint32),
(
'Data', ctypes.c_uint32),
(
'DataMask', ctypes.c_uint32),
(
'Ctrl', ctypes.c_uint32),
(
'CtrlMask', ctypes.c_uint32),
(
'WPUnit', ctypes.c_uint8)]
def __init__(self):
super(JLinkWatchpointInfo, self).__init__()
self.SizeOfStruct = ctypes.sizeof(self)
def __repr__(self):
"""Returns a formatted string describing the watchpoint.
Args:
self (JLinkWatchpointInfo): the ``JLinkWatchpointInfo`` instance
Returns:
String representation of the watchpoint.
"""
return self.__str__()
def __str__(self):
"""Returns a formatted string describing the watchpoint.
Args:
self (JLinkWatchpointInfo): the ``JLinkWatchpointInfo`` instance
Returns:
String representation of the watchpoint.
"""
name = self.__class__.__name__
return '%s(Handle %d, Address %d)' % (name, self.Handle, self.Addr)
class JLinkStraceEventInfo(ctypes.Structure):
__doc__ = 'Class representing the STRACE event information.\n\n Attributes:\n SizeOfStruct: size of the structure.\n Type: type of event.\n Op: the STRACE operation to perform.\n AccessSize: access width for trace events.\n Reserved0: reserved.\n Addr: specifies the load/store address for data.\n Data: the data to be compared for the operation for data access events.\n DataMask: bitmask for bits of data to omit in comparision for data access\n events.\n AddrRangeSize: address range for range events.\n '
_fields_ = [
(
'SizeOfStruct', ctypes.c_uint32),
(
'Type', ctypes.c_uint8),
(
'Op', ctypes.c_uint8),
(
'AccessSize', ctypes.c_uint8),
(
'Reserved0', ctypes.c_uint8),
(
'Addr', ctypes.c_uint64),
(
'Data', ctypes.c_uint64),
(
'DataMask', ctypes.c_uint64),
(
'AddrRangeSize', ctypes.c_uint32)]
def __init__(self):
super(JLinkStraceEventInfo, self).__init__()
self.SizeOfStruct = ctypes.sizeof(self)
def __repr__(self):
"""Returns a formatted string describing the event info.
Args:
self (JLinkStraceEventInfo): the ``JLinkStraceEventInfo`` instance
Returns:
String representation of the event info.
"""
return self.__str__()
def __str__(self):
"""Returns a formatted string describing the event info.
Args:
self (JLinkStraceEventInfo): the ``JLinkStraceEventInfo`` instance
Returns:
String representation of the event information.
"""
name = self.__class__.__name__
return '%s(Type=%d, Op=%d)' % (name, self.Type, self.Op)
class JLinkTraceData(ctypes.Structure):
__doc__ = 'Structure representing trace data returned by the trace buffer.\n\n Attributes:\n PipeStat: type of trace data.\n Sync: sync point in buffer.\n Packet: trace data packet.\n '
_fields_ = [
(
'PipeStat', ctypes.c_uint8),
(
'Sync', ctypes.c_uint8),
(
'Packet', ctypes.c_uint16)]
def __repr__(self):
"""Returns a string representation of the trace data instance.
Args:
self (JLinkTraceData): the ``JLinkTraceData`` instance.
Returns:
A string representation of the instance.
"""
return self.__str__()
def __str__(self):
"""Returns a string representation of the trace data instance.
Args:
self (JLinkTraceData): the ``JLinkTraceData`` instance.
Returns:
A string representation of the instance.
"""
return '%s(%d)' % (self.__class__.__name__, self.Packet)
def instruction(self):
"""Returns whether the data corresponds to an executed instruction.
Args:
self (JLinkTraceData): the ``JLinkTraceData`` instance.
Returns:
``True`` if this is trace data for an executed instruction.
"""
return self.PipeStat == 0
def data_instruction(self):
"""Returns whether the data corresponds to an data instruction.
Args:
self (JLinkTraceData): the ``JLinkTraceData`` instance.
Returns:
``True`` if this is trace data for an data instruction.
"""
return self.PipeStat == 1
def non_instruction(self):
"""Returns whether the data corresponds to an un-executed instruction.
Args:
self (JLinkTraceData): the ``JLinkTraceData`` instance.
Returns:
``True`` if this is trace data for an un-executed instruction.
"""
return self.PipeStat == 2
def wait(self):
"""Returns whether the data corresponds to a wait.
Args:
self (JLinkTraceData): the ``JLinkTraceData`` instance.
Returns:
``True`` if this is trace data for a wait.
"""
return self.PipeStat == 3
def branch(self):
"""Returns whether the data corresponds to a branch execution.
Args:
self (JLinkTraceData): the ``JLinkTraceData`` instance.
Returns:
``True`` if this is trace data for a branch execution.
"""
return self.PipeStat == 4
def data_branch(self):
"""Returns whether the data corresponds to a branch with data.
Args:
self (JLinkTraceData): the ``JLinkTraceData`` instance.
Returns:
``True`` if this is trace data for a branch with data.
"""
return self.PipeStat == 5
def trigger(self):
"""Returns whether the data corresponds to a trigger event.
Args:
self (JLinkTraceData): the ``JLinkTraceData`` instance.
Returns:
``True`` if this is trace data for a trigger event.
"""
return self.PipeStat == 6
def trace_disabled(self):
"""Returns whether the data corresponds to trace being disabled.
Args:
self (JLinkTraceData): the ``JLinkTraceData`` instance.
Returns:
``True`` if this is trace data for the trace disabled event.
"""
return self.PipeStat == 7
class JLinkTraceRegion(ctypes.Structure):
__doc__ = 'Structure describing a trace region.\n\n Attributes:\n SizeOfStruct: size of the structure.\n RegionIndex: index of the region.\n NumSamples: number of samples in the region.\n Off: offset in the trace buffer.\n RegionCnt: number of trace regions.\n Dummy: unused.\n Timestamp: timestamp of last event written to buffer.\n '
_fields_ = [
(
'SizeOfStruct', ctypes.c_uint32),
(
'RegionIndex', ctypes.c_uint32),
(
'NumSamples', ctypes.c_uint32),
(
'Off', ctypes.c_uint32),
(
'RegionCnt', ctypes.c_uint32),
(
'Dummy', ctypes.c_uint32),
(
'Timestamp', ctypes.c_uint64)]
def __init__(self):
super(JLinkTraceRegion, self).__init__()
self.SizeOfStruct = ctypes.sizeof(self)
def __repr__(self):
"""Returns a string representation of the instance.
Args:
self (JLinkTraceRegion): the ``JLinkTraceRegion`` instance.
Returns:
String representation of the trace region.
"""
return self.__str__()
def __str__(self):
"""Returns a string representation of the instance.
Args:
self (JLinkTraceRegion): the ``JLinkTraceRegion`` instance.
Returns:
String representation of the trace region.
"""
return '%s(Index=%d)' % (self.__class__.__name__, self.RegionIndex)
# okay decompiling ./pylink/structs.pyc

View File

@ -1,45 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/threads.py
import threading
class ThreadReturn(threading.Thread):
__doc__ = 'Implementation of a thread with a return value.\n\n See also:\n `StackOverflow <http://stackoverflow.com/questions/6893968/>`__.\n '
def __init__(self, daemon=False, *args, **kwargs):
"""Initializes the thread.
Args:
self (ThreadReturn): the ``ThreadReturn`` instance
daemon (bool): if the thread should be spawned as a daemon
args: optional list of arguments
kwargs: optional key-word arguments
Returns:
``None``
"""
(super(ThreadReturn, self).__init__)(*args, **kwargs)
self.daemon = daemon
self._return = None
def run(self):
"""Runs the thread.
Args:
self (ThreadReturn): the ``ThreadReturn`` instance
Returns:
``None``
"""
target = getattr(self, '_Thread__target', getattr(self, '_target', None))
args = getattr(self, '_Thread__args', getattr(self, '_args', None))
kwargs = getattr(self, '_Thread__kwargs', getattr(self, '_kwargs', None))
if target is not None:
self._return = target(*args, **kwargs)
def join(self, *args, **kwargs):
(super(ThreadReturn, self).join)(*args, **kwargs)
return self._return
# okay decompiling ./pylink/threads.pyc

View File

@ -1,157 +0,0 @@
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Mar 30 2023, 01:25:49)
# [GCC 12.2.1 20220924]
# Embedded file name: pylink/util.py
from . import enums
import platform, sys
def is_integer(val):
"""Returns whether the given value is an integer.
Args:
val (object): value to check
Returns:
``True`` if the given value is an integer, otherwise ``False``.
"""
try:
val += 1
except TypeError:
return False
else:
return True
def is_natural(val):
"""Returns whether the given value is a natrual number.
Args:
val (object): value to check
Returns:
``True`` if the given value is a natural number, otherwise ``False``.
"""
return is_integer(val) and val >= 0
def is_os_64bit():
"""Returns whether the current running platform is 64bit.
Returns:
``True`` if the platform is 64bit, otherwise ``False``.
"""
return platform.machine().endswith('64')
def noop(*args, **kwargs):
"""No-op. Does nothing.
Args:
args: list of arguments
kwargs: keyword arguments dictionary
Returns:
``None``
"""
pass
def unsecure_hook_dialog(title, msg, flags):
"""No-op that ignores the dialog.
Args:
title (str): title of the unsecure dialog
msg (str): text of the unsecure dialog
flags (int): flags specifying which values can be returned
Returns:
``enums.JLinkFlags.DLG_BUTTON_NO``
"""
return enums.JLinkFlags.DLG_BUTTON_NO
def progress_bar(iteration, total, prefix=None, suffix=None, decs=1, length=100):
"""Creates a console progress bar.
This should be called in a loop to create a progress bar.
See `StackOverflow <http://stackoverflow.com/questions/3173320/>`__.
Args:
iteration (int): current iteration
total (int): total iterations
prefix (str): prefix string
suffix (str): suffix string
decs (int): positive number of decimals in percent complete
length (int): character length of the bar
Returns:
``None``
Note:
This function assumes that nothing else is printed to the console in the
interim.
"""
if prefix is None:
prefix = ''
if suffix is None:
suffix = ''
format_str = '{0:.' + str(decs) + 'f}'
percents = format_str.format(100 * (iteration / float(total)))
filled_length = int(round(length * iteration / float(total)))
bar = '' * filled_length + '-' * (length - filled_length)
prefix, suffix = prefix.strip(), suffix.strip()
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix))
sys.stdout.flush()
if iteration == total:
sys.stdout.write('\n')
sys.stdout.flush()
def flash_progress_callback(action, progress_string, percentage):
"""Callback that can be used with ``JLink.flash()``.
This callback generates a progress bar in the console to show the progress
of each of the steps of the flash.
Args:
action (str): the current action being invoked
progress_string (str): the current step in the progress
percentage (int): the percent to which the current step has been done
Returns:
``None``
Note:
This function ignores the compare action.
"""
if action.lower() != 'compare':
return progress_bar((min(100, percentage)), 100, prefix=action)
def calculate_parity(n):
"""Calculates and returns the parity of a number.
The parity of a number is ``1`` if the number has an odd number of ones
in its binary representation, otherwise ``0``.
Args:
n (int): the number whose parity to calculate
Returns:
``1`` if the number has an odd number of ones, otherwise ``0``.
Raises:
ValueError: if ``n`` is less than ``0``.
"""
if not is_natural(n):
raise ValueError('Expected n to be a positive integer.')
y = 0
n = abs(n)
while n:
y += n & 1
n = n >> 1
return y & 1
# okay decompiling ./pylink/util.pyc

View File

@ -1 +1,8 @@
psutil==5.9.5 psutil==5.9.5
six==1.16.0
pyserial==3.5
pylink-square==0.5.0
pycryptodome==3.9.8
pycklink==0.1.1
ecdsa==0.18.0
pycryptoplus==0.0.1